Q# : QDK Errors - visual-studio-code

I've recently tried to install the QDK via the VSCode extension in my Windows 10 Desktop and VSCode wasn't able to find the Microsoft libraries even after I was able to execute the code by the dotnet run command on the terminal. The code was the sample project code described in the create new project part of the tutorial. I also didn't have .NET SDK so I installed it but it seems to be working fine. In computers I got problems all the code, all related to not finding the namespaces.
namespace QuantumRNG {
open Microsoft.Quantum.Canon;
open Microsoft.Quantum.Intrinsic;
open Microsoft.Quantum.Measurement;
open Microsoft.Quantum.Math;
open Microsoft.Quantum.Convert;
operation GenerateRandomBit() : Result {
using (q = Qubit()) {
H(q);
return MResetZ(q);
}
}
operation SampleRandomNumberInRange(max : Int) : Int {
mutable output = 0;
repeat {
mutable bits = new Result[0];
for (idxBit in 1..BitSizeI(max)) {
set bits += [GenerateRandomBit()];
}
set output = ResultArrayAsInt(bits);
} until (output <= max);
return output;
}
#EntryPoint()
operation SampleRandomNumber() : Int {
let max = 50;
Message($"Sampling a random number between 0 and {max}: ");
return SampleRandomNumberInRange(max);
}
}

Do you see any error messages in the output console?
To see the output console select "View: Toggle Output" (Ctrl + Shift + U) and select "Q# Language Extension" from the drop down list.
If the drop down list doesn't show "Q# Language Extension" then it probably means that the language-server that gets downloaded on first run is still downloading, so give it a minute or so (depending on your internet connection).

I think I also had the same problem. The .Net SDk which you have downloaded automatically creates a path in the environment variable by the name "%USERPROFILE%.dotnet\tools" so delete this and add "C:\Program Files\dotnet\sdk" or copy the path of dotnet SDK from the drive where you have installed dotnet and create a new environment variable under user variable. This might solve your namespace problem.

Related

ng server command opens file open option menu

In VS code editor, ng serve command opening "How do you want to open this file?" dialog box in
The answer by Petr Freiberg helped get me to what I believe is a better solution. Instead of deleting files that may or may not actually be important for the system, we should update our PATH variables so that the "correct" command is found first.
In my situation, I had my npm paths in this order:
C:\Users\Me\AppData\Roaming\npm\node_modules\#angular\cli\bin
C:\Users\Me\AppData\Roaming\npm
I just switched the order so that C:\Users\Me\AppData\Roaming\npm came first.
The issue is that the terminal is finding the first "command match" which may just be a file, so that is why it is asking where you want to open it.
I did run the command Run Get-Command -All ng | ForEach-Object Path as Petr suggested, which called out the order issue I describe here.
I encountered a similar problem when executing a Docker command within Visual Studio Code. I also got a window asking "How do you want to open this file?". I think the problem is not in Visual Studio Code, but in PowerShell, which Visual Studio Code uses.
I solved it like this:
Run Get-Command -All docker | ForEach-Object Path
Among the file paths returned, remove those that do not end in *.exe (use
Remove-Item):
For ng it should be same.
Credits: https://stackoverflow.com/a/63981418/1816014
i have faced the same issue, while trying to run ng -v or ng --version, it pops open a Open option editor, which gives following ng.js text...
#!/usr/bin/env node
'use strict';
// Provide a title to the process in `ps`.
// Due to an obscure Mac bug, do not start this title with any symbol.
try {
process.title = 'ng ' + Array.from(process.argv).slice(2).join(' ');
} catch (_) {
// If an error happened above, use the most basic title.
process.title = 'ng';
}
// This node version check ensures that extremely old versions of node are not used.
// These may not support ES2015 features such as const/let/async/await/etc.
// These would then crash with a hard to diagnose error message.
// tslint:disable-next-line: no-var-keyword
var version = process.versions.node.split('.').map((part) => Number(part));
if (version[0] % 2 === 1 && version[0] > 14) {
// Allow new odd numbered releases with a warning (currently v15+)
console.warn(
'Node.js version ' +
process.version +
' detected.\n' +
'Odd numbered Node.js versions will not enter LTS status and should not be used for production.' +
' For more information, please see https://nodejs.org/en/about/releases/.',
);
require('../lib/init');
} else if (
version[0] < 12 ||
version[0] === 13 ||
(version[0] === 12 && version[1] < 14) ||
(version[0] === 14 && version[1] < 15)
) {
// Error and exit if less than 12.14 or 13.x or less than 14.15
console.error(
'Node.js version ' +
process.version +
' detected.\n' +
'The Angular CLI requires a minimum Node.js version of either v12.14 or v14.15.\n\n' +
'Please update your Node.js version or visit https://nodejs.org/ for additional instructions.\n',
);
process.exitCode = 3;
} else {
require('../lib/init');
}
what is the error here, i tried uninstall clear cache and install but still same error....

How to import other source code files in dm script

Is there a way to use multiple code files in dm-script to structure the code? Something like:
import "path/to/utility_functions.s";
utility_functions.do_something_general();
Note that I do not want to have the code as a menu item if possible. The code contains only functions that I use in the main script.
I tried the following:
File 1: test.s
void test(){
result("test\n");
}
File 2: require-test.s
AddScriptFileToPackage("path/to/test.s", "test", 3, "test-function", "", "", 1);
ExecuteScriptString("test()"); // works immediately but feels wrong
test(); // works after restart
Now I have the following problems:
I have to restart DigitalMicrograph after executing this script, otherwise test() does not work (ExecuteScriptString("test()"); works but it feels wrong to use strings for invoking code, if possible I'd like to avoid that)
When I restart DigitalMicrograph another time AddScriptFileToPackage() sais 'The script cannot be added because the package exists and is read-only. [...]'. Is there a way around it or do I have to use try blocks?
I feel like I am not doing this wrong at some place.
DM script does not support on-demand-loading of packages, but there are two different ways to achieve what you want:
Using library packages
When you "install" a script, you can choose to either install it as menu-command or as a library. This is true for both installing scripts via the menu command (which get stored in the global preferences file) or via the scripting-command (which can be used to
create .gtk files which one can then add/remove from the plugins
folder as needed).
The "menu" option will install a script such that it is invoked once via the menu-item but does not stay in memory otherwise.
The "library" option will execute a script once on startup and keep the script itself in scope. So you can define methods (or classes) in a library file and have it generally available. And you can put some executable code in a library if you need some startup-action.
Using script libraries as .gtk plugins is possibly the recommended way to achieve what you want. They are, however, always loaded.
Piece of advise: If you make libraries ensure you use very unique class and method names to avoid any conflict. I would recommend pre-fixing all class/method names with some library-name, i.e. use MyLib_MyClass instead of MyClass and the like.
Clarification: Scripts added as library packages are permanently added to the software, i.e. those packages get created once and are then placed in the plugins-folder. They will always load on startup of DM and be available. The Library package method is not suitable for temporarily 'loading' external scripts. Such 'on demand import' is not supported by DM-scripting.
The script commands to create packages are utility commands to help one create packages in an easy and manageable way. Typically, one would create a "Create package XY" script with several such commands adding all scripts from a location into a package. The script would be called once to create the package-file (It is already in the plugins folder afterwards.)
Only when the included scripts change and the package therefore requires to be updated, is the create-package script called again. Note, that in this case it is first required to remove the package-file from the plugins folder and start DigitalMicrograph without loading it, so that a new package is created. Otherwise the script would append to the package, which would not be possible if methods of the same name already exist in the package.
The F1 help documentation has an example script:
A typical examples, using GMS 3.4.0:
Script stored at: C:\Tmp\testLib.s
void TestCall()
{
Result("\nTest")
}
Script stored at: C:\Tmp\menuAction.s
Result("\nPerforming an action here.")
One-time run script to install a package:
// General package parameters
// *********************************************
string pkNa = "myPkg" // Filename of plugin
number pkLe = 3 // level 3 (.gtk) only needed for load order
string pkLo = "user_plugin" // plugin location
string scriptRoot = "C:\\Temp\\"
// List of Scripts to be installed as menu items
// *********************************************
// Each entry needs a (unique) command-name, a menu-name and an optional sub-menu name.
// The "isLibary" flag is set to 0
// It is possible to add the same script multiple times. The script will be executed when the menu item
// is chosen. Methods and Classes of the script are not available otherwise
// A separator can be added by installing and empty script with a (unique) command name starting with "-"
AddScriptFileToPackage( scriptRoot + "menuAction.s", pkNa, pkLe, pkLo, "Call 1", "MyMenu", "MySubMenu", 0 )
AddScriptFileToPackage( scriptRoot + "menuAction.s", pkNa, pkLe, pkLo, "Call 2", "MyMenu", "", 0 )
AddScriptToPackage( "", pkNa, pkLe, pkLo, "-sep1", "MyMenu", "", 0 )
AddScriptFileToPackage( scriptRoot + "menuAction.s", pkNa, pkLe, pkLo, "Call 3", "MyMenu", "", 0 )
// List of Scripts to be installed as library
// *********************************************
// Each entry needs a (unique) command-name. Menu-name and sub-menu name are "".
// The "isLibary" flag is set to 1
// The script will be executed once on startup (if there is executable code). It is also executed once
// here during the install.
// Methods and Classes of the script are permanently available and need unique names.
// Adding a script to the package as libary can be used to create on-load-version info output.
AddScriptFileToPackage( scriptRoot + "testLib.s", pkNa, pkLe, pkLo, "library-1", "", "", 1 )
AddScriptToPackage( "Result(\"Script packages myPkg loaded.\\n\")", pkNa, pkLe, pkLo, "myPkg-versionInfo", "", "", 1 )
After running the install-script there will be:
A menu like this:
Output in the results window like this:
A package file in the folder C:\Users\USERNAME\AppData\Local\Gatan\Plugins\myPkg.gtk
The script command TestCall() generally available in all scripts.
The package will load each time when DM starts as long as the .gtk file remains in the plugins folder.
Calling script code from within scripts
The scripting language supports two commands to call a script from within a script:
Number ExecuteScriptString( String text )
Number ExecuteScriptFile( String file_path )
Using the command to execute scripts form disc can do what you want, but maintaining a useful 'library' that way could be tedious. It also does not allow you to install classes.
Example of calling a script from within a script:
// Direct example
void Demo()
{
ClearResults()
Result( "I am a test call.\n")
number n = 5
Result( "I am working on the number: " + n )
}
Demo()
//Having the script as a string
number otherNumber = 11 // To show how you can modify a script call as an example
string scriptStr
scriptStr += "void Demo()\n{" + "\n"
scriptStr += "ClearResults()" + "\n"
scriptStr += "Result( \"I am a test call.\\n\")" + "\n"
scriptStr += "number n = " + otherNumber + "\n"
scriptStr += "Result( \"I am working on the number: \" + n )"+ "\n"
scriptStr += "}\n"
scriptStr += "Demo()\n"
If ( TwoButtonDialog("Script-call","Show it", "Run it") )
{
ClearResults()
Result( scriptStr )
}
else
ExecuteScriptString( scriptStr )
The following explicit example of build script usage may be closer to what you are looking for. It shows that in the course of a single DM session, one can edit the module source files and repeatedly rebuild the package without having to relaunch DM, contrary to the clarification about package creation provided in the answer from BmyGuest. This example also makes use of the very convenient GetCurrentScriptSourceFilePath function which greatly simplifies file path references when one can locate the build script and module source files in the same folder (this is the approach I take with my own development projects).
Here is the arrangement of my files for this example:
The two source modules are very simple function and class libraries.
Here is Module1:
void Module1SayHello()
{
OKDialog("Hello from module 1");
}
And here is Module2:
class Module2TestClass
{
void Module2SayHello(Object self)
{
OKDialog("Hello from module 2");
}
}
Here is the build script:
void main()
{
// Establish the source code directory relative to the current build script location
String buildScriptSourceFilePath;
GetCurrentScriptSourceFilePath(buildScriptSourceFilePath);
String sourceFileDir = buildScriptSourceFilePath.PathExtractDirectory(0);
// Add the modules
AddScriptFileToPackage(sourceFileDir.PathConcatenate("Module1.s"), "MultiModuleTest", 3, "Module1", "", "", 1);
AddScriptFileToPackage(sourceFileDir.PathConcatenate("Module2.s"), "MultiModuleTest", 3, "Module2", "", "", 1);
}
main();
Contrary to the above-mentioned clarification, this build script can be run multiple times during a DM session and the content of the package file gets replaced each time. So now one has a very nice development environment where one can open the source file for a module, edit it as desired, save it, and then rebuild the package file. One can use the following test script to see that the behavior changes as one edits, saves, and rebuilds the implementation of any function or method in the module source files:
void main()
{
Module1SayHello();
Alloc(Module2TestClass).Module2SayHello();
}
main();
Because of the way the DM script interpreter parses, tokenizes, and executes code, all functions and methods invoked anywhere in a script must have been previously defined before a script is executed. This is why the above test script, or any other script that uses the added modules, cannot simply be appended to the end of the build script (except if embedded in a string passed to the ExecuteScriptString function, as pointed out in the posed question). The concept of imported code modules (e.g. as in Python) is therefore not really possible in DM scripting (as pointed out in a comment to the answer by BmyGuest). In this sense, DM scripting shows its roots in 1990’s coding concepts, which commonly involved separate compilation, linking, and execution phases.
Nevertheless, the build script approach described here allows one to take advantage of the features of a true integrated development environment (IDE). For example, one can add the module source files (and build script) to a project in Visual Studio and get all the benefits of a modern multi-file code editor and revision control (e.g. via Git). This is what I do with the Enabler framework.
The one caveat is that once the DM session is closed, the plug-in (package) file does become finalized in some way so that it can no longer be replaced by the build script in a future DM session. In this case, one does have to remove the package file from the plug-ins folder before resuming another development session in DM (as covered in the clarification from BmyGuest).
For everybody else who needs this, I am using AddScriptFileToPackage() now, inspired by both, #BmyGuest and #MikeKundmann.
The following main.s is always open in my GMS. The real code I'm working on is in program.s. To test your code execute the main.s. This file can be executed multiple times in one session!
For opening GMS I use the (Windows) batch file below. This deleteds registered plugins automatically which makes the main.s usable again. For debugging I created a python script that combines all the files listed in the main.s. This way GMS jumps to the errors. This python program can be downloaded from my github page.
/**
* File: main.s
*/
String __file__;
GetCurrentScriptSourceFilePath(__file__);
String __base__ = __file__.PathExtractDirectory(0);
/**
* Load and add the file `filename`, the name will be the `filename` without
* the extension.
*
* This is dynamic only for the current session. If GMS is restarted, using
* this will create errors except if the plugins folder does not contain the
* required files (delete `%LOCALAPPDATA%\Gatan\Plugins\` before starting).
*
* #param filename The filename (or path) relative to the path of this file
* #param name The internal name to register the script with
*/
void require(String filename, String name){
// AddScriptFileToPackage(
// <file_path>,
// <packageName: filename of .gtk file in plugins>,
// <packageLevel: load order [0..3]>,
// <command_name: id/name of the libary/command>,
// <menu_name: name of the menu, ignored if isLibrary=1>
// <sub_menu_name: name of the submenu, ignored if isLibrary=1>,
// <isLibrary: wheter to add as library (1) or as menu item (0)>
// )
AddScriptFileToPackage(__base__.PathConcatenate(filename), "__require_main_" + name, 3, name, "", "", 1);
}
/**
* Require the file `filename` with the basename of the `filename` as the name.
*
* #see require(String filename, String name);
*
* #param filename The filename (or path) relative to the path of this file
*/
void require(String filename){
require(filename, PathExtractBaseName(filename, 0));
}
void main(){
// add libaries
require("string-lib.s");
// add main file
require("program.s");
}
main();
The (Windows) batch file to start GMS. This deletes the plugins folder automatically. Then the main.s does not cause any problems.
#echo off
rem
rem File: start-gatan.bat
rem ---------------------
echo Deleting GMS cached libaries...
SET plugins_path=%LOCALAPPDATA%\Gatan\Plugins\
SET gms_path=%PROGRAMFILES%\Gatan\DigitalMicrograph.exe
if exist %plugins_path% (
echo Deleting all .gtk files in %plugins_path%...
del %plugins_path%__require_main_*.gtk /F /Q
del %plugins_path%__require_main_*.gt1 /F /Q
del %plugins_path%__require_main_*.gt2 /F /Q
del %plugins_path%__require_main_*.gt3 /F /Q
if exist "%gms_path%" (
echo Starting GMS
start "" "%gms_path%"
) else (
echo GMS path %gms_path% does not exist.
pause
)
) else (
echo Plugins path %plugins_path% does not exist.
pause
)

Installing an exe with Powershell DSC Package resource gets return code 1619

I'm trying to use Powershell DSC's Package resource to install an exe... Perforce's P4V to be specific. Here's my code:
Configuration PerforceMachine
{
Node "SERVERNAME"
{
Package P4V
{
Ensure = "Present"
Name = "Perforce Visual Components"
Path = "\\nas\share\p4vinst64.exe"
ProductId = ''
Arguments = "/S /V/qn" # args for silent mode
LogPath = "$env:ProgramData\p4v_install.log"
}
}
}
When running this, this is the error Powershell gives me:
PowerShell provider MSFT_PackageResource failed to execute Set-TargetResource functionality with error message: The return code 1619 was not expected. Configuration is likely not
correct
+ CategoryInfo : InvalidOperation: (:) [], CimException
+ FullyQualifiedErrorId : ProviderOperationExecutionFailure
+ PSComputerName : SERVERNAME
According to documentation, return code 1619 means the MSI package couldn't be opened. However, when I manually log in to the machine and run "\\nas\share\p4vinst64.exe /S /V/qn", the install works flawlessly.
Does anyone know why this is failing? Alternately, can anyone tell me how to troubleshoot this? I pasted all the error information I got from the terminal, my log file (p4v_install.log) is a 0 byte file, and there are no events in the event viewer. I don't know how to troubleshoot it any further!
EDIT: I should note that I also tried using the File resource to copy the file locally, and then install it from there. Sadly, that met with the same result.
Daniel over at the Powershell.org forums was able to figure this out for me.
The P4V InstallShield setup wrapper puts the MSI file into wrong path if you execute as LocalSystem.
I’ve managed to develop a Configuration that works, see below. The key is the /b switch here which puts the MSI file into a defined location. I’ve added ALLUSERS=1 to get the shortcuts visible to all users and REBOOT=ReallySuppress to avoid a sudden restart (which will happen otherwise).
Configuration PerforceMachine
{
Package P4V
{
Ensure = "Present"
Name = "Perforce Visual Components"
Path = "C:\My\p4vinst64.exe"
ProductId = ''
Arguments = '/b"C:\Windows\Temp\PerforceClient" /S /V"/qn ALLUSERS=1 REBOOT=ReallySuppress"' # args for silent mode
}
}
Well, what happens here is that the package gets installed (not tested with p4vinst64.exe yet! So, not sure why it says pack cannot be opened as the error) but since you did not specify a ProductID value, the verification at the end of install fails. That is the error you are seeing. The Package resource is no good for installing .exe packages or even MSIs with no ProductID represented as a GUID.
You can use the WindowsProcess resource instead.

Background update/upgrade of custom Android application [not using com.android.vending]

Context:
Earlier this year Facebook updated their android app without using the google play services : http://liliputing.com/2013/03/facebook-pushes-android-update-to-enable-silent-updates-bypassing-the-play-store.html
I would like to try a similar thing with my android app.
(I'm aware of the implications so please don't post regarding the same.)
Description:
I have gone through the the related Android classes Package Manager - Androidxref and resources like: Install apps silently, with granted INSTALL_PACKAGES permission but could not find any non-rooted method.
Ways like:
public static int installAPP(String absolutePath){
int status = -1;
File file = new File(absolutePath);
if(file.exists()){
try {
String command = "adb install -r " + StringUtil.insertEscape(absolutePath);
Process install = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
status = install.waitFor();
} catch (Exception e) {
Log.e(TAG, "Not Installed!");
} finally { return status;}
}
}
works just fine, but then again it's for rooted devices.
Any information/hints for possible ways of doing and and any relevant information/hacks regarding the same is much appreciated.
Thank You.
PS. I am working on a ROM.

Firebird custom installation

I want to deploy a firebird installation, and thus will launch it from my installer using command-line parameters. I read Inno Setup's documentation but still can't get it to work.
I just want to install a "Super server" with no documentation or whatsoever.
Here's what I have so far
Firebird-2.1.2.18118_0_Win32.exe /sp- /silent /SUPPRESSMSGBOXES /nocancel /noicons /components="Super Server binary"
But it won't install the server. If I remove the /components it does install the server but install other developer stuff, which customers don't need.
read installation_scripted.txt in C:\Program Files\Firebird\Firebird_2_1\doc
/COMPONENTS="comma separated list of
component names"
Choose from -
ServerComponent\SuperServerComponent,
ServerComponent\ClassicServerComponent,
ServerComponent,
DevAdminComponent and
ClientComponent
Overrides the default components
settings. Using this command line
parameter causes Setup to
automatically select a custom type. A
full install requires combining
components. For example:
/COMPONENTS="ServerComponent\SuperServerComponent,ServerComponent,DevAdminComponent,ClientComponent"
would be required for a full
install.
I use the following and it works fine, however I need to install to a custom directory and also change the server option
string installerFilePath = #"C:\BennaOlivier\Randoms\Delter\Firebird\FirebirdMainInstaller\MainInstaller\MainInstaller\Firebird X64\FirebirdInstallX64\Firebird-2.5x64.exe";
Process installerProcess = new Process();
installerProcess = Process.Start(installerFilePath, Arguments);
while (installerProcess.HasExited == false)
{
//indicate progress to user
Application.DoEvents();
System.Threading.Thread.Sleep(250);
}
}
catch (Exception FBX64)
{
MessageBox.Show(FBX64.Message);
throw;
}public const string comps = #"ServerComponent\ClassicServerComponent,ServerComponent,ClientComponent";
public const string Arguments = "/VERYSILENT /SUPPRESSMSGBOXES";