This is code thai word segmentation by use ICU4NET:
using ICU4NET;
using ICU4NETExtension;
static void Main(string[] args)
{
var sb = new StringBuilder();
var col = new List<string>();
using (BreakIterator bi = BreakIterator.CreateWordInstance(Locale.GetUS()))
{
bi.SetText(Content2);
int start = bi.First(), end = bi.Next();
while (end != BreakIterator.DONE)
{
col.Add(Content2.Substring(start, end - start));
start = end; end = bi.Next();
}
}
}
I write by use program Visual studio 2008
but it error because "Could not load file or assembly 'ICU4NET, Version=1.0.3891.39017, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format". I do not know what it is.
How to use ICU4NET
Add references to ICU4NET.dll and ICU4NETExtension.dll.
Make sure that ICU4C's DLLs, including icudt42.dll, icuin42.dll, icuio42.dll, icule42.dll, iculx42.dll, icutu41.dll, and icuuc42.dll, are in the %PATH% or in the working directory of your exe program.
Related
I am working on adding localisation to my class library. Currently I have two resource files: Strings.resx and Strings.es.resx.
Both files are under the 'internal' access modifier, although I have tried setting both to 'public' without any help.
My problem is that the Spanish resource file (Strings.es.resx) is not being loaded; and this problem will repeat with any more resource files I add for other languages. The Strings.resx works fine as it is the default resource file.
This code is used to grab which string resource files have been loaded; currently only the default file is loaded. Spanish does not appear:
private static void LoadLanguages()
{
var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
foreach (var culture in cultures)
{
try
{
var rs = Properties.Lang.Strings.ResourceManager.GetResourceSet(culture, true, false);
if (rs != null) SupportedLanguages.Add(culture.Name.ToLower(), culture.NativeName);
}
catch (Exception)
{
// ignored
}
}
Log.Info("Loaded languages: " + SupportedLanguages.Count); //OUT: 1
}
I have made a discovery though. In my build output, there is a folder "es", and within that folder is a DLL called Project.resources.dll. If I copy that DLL to the root folder of the build output, the resource gets loaded.
The solution to this problem is to get those resource files loaded from the folders. For some reason this is not happening. Is there a known solution to this? Thanks.
It works out the threads current culture. An example can be seen in the docs over at Microsoft https://learn.microsoft.com/en-us/dotnet/framework/resources/creating-satellite-assemblies-for-desktop-apps (check code at step 13 in the end)
Below the example from the documentation. The localized resource is StringLibrary
using System;
using System.Globalization;
using System.Threading;
public class Example
{
public static void Main()
{
string[] cultureNames = { "en-GB", "en-US", "fr-FR", "ru-RU" };
Random rnd = new Random();
string cultureName = cultureNames[rnd.Next(0, cultureNames.Length)];
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(cultureName);
Console.WriteLine("The current UI culture is {0}",
Thread.CurrentThread.CurrentUICulture.Name);
StringLibrary strLib = new StringLibrary();
string greeting = strLib.GetGreeting();
Console.WriteLine(greeting);
}
}
This is my first Q# program and i'm following this getting started link.https://learn.microsoft.com/en-us/quantum/quantum-writeaquantumprogram?view=qsharp-preview
Error is
The name 'BellTest' does not exist in the current context
but its defined in the Bell.cs
I followed the steps and when building its having errors. I'm not sure how to import the operations from .qs file to driver c# file as this error looks like it can't find that operation.
Any help is really appreciated
Here is the code
Driver.cs
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
namespace Quantum.Bell
{
class Driver
{
static void Main(string[] args)
{
using (var sim = new QuantumSimulator())
{
// Try initial values
Result[] initials = new Result[] { Result.Zero, Result.One };
foreach (Result initial in initials)
{
var res = BellTest.Run(sim, 1000, initial).Result;
var (numZeros, numOnes) = res;
System.Console.WriteLine(
$"Init:{initial,-4} 0s={numZeros,-4} 1s={numOnes,-4}");
}
}
System.Console.WriteLine("Press any key to continue...");
System.Console.ReadKey();
}
}
}
Bell.qs
namespace Quantum.Bell
{
open Microsoft.Quantum.Primitive;
open Microsoft.Quantum.Canon;
operation Set (desired:Result,q1:Qubit) : ()
{
body
{
let current = M(q1);
if (desired != current)
{
X(q1);
}
}
}
operation BellTest (count : Int, initial: Result) : (Int,Int)
{
body
{
mutable numOnes = 0;
using (qubits = Qubit[1])
{
for (test in 1..count)
{
Set (initial, qubits[0]);
let res = M (qubits[0]);
// Count the number of ones we saw:
if (res == One)
{
set numOnes = numOnes + 1;
}
}
Set(Zero, qubits[0]);
}
// Return number of times we saw a |0> and number of times we saw a |1>
return (count-numOnes, numOnes);
}
}
}
I also got the same error, but I was able to do it by pressing the F5 key.
Perhaps the Visual Studio editor is not yet fully support to the .qs file.
Namespace sharing does not seem to be working properly between .cs file and .qs file.
I was able to execute using your code in my development environment.
--
IDE: Visual Studio Community 2017 (Version 15.5.2)
Dev Kit: Microsoft Quantum Development Kit (0 and 1)
I engage the same problem in microsoft.quantum.development.kit/0.3.1811.203-preview version.
The BellTest operation cannot recognised by VSC Pic of VSCode
What I do is,
save all but keep VSCode open
go to directory and delete anything in bin/ obj/ by /bin/rm -rf bin obj
dotnet run
you go back to check VSCode, the BellTest recognised by VSC now.
I am trying to use two different windows UWP project in a Windows 10 cordova app. Both projects produce the same error. The code in one of the projects is as follows:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage;
namespace DiskSpaceLibrary
{
public sealed class DiskSpace
{
internal static readonly StorageFolder[] APP_FOLDERS = {
ApplicationData.Current.LocalFolder,
ApplicationData.Current.RoamingFolder,
ApplicationData.Current.TemporaryFolder
};
[DataContract]
internal class Result
{
[DataMember]
internal ulong app = 0;
[DataMember]
internal ulong total = 0;
[DataMember]
internal ulong free = 0;
}
// Manually compute total size of the given StorageFolder
private static ulong sizeFolder(StorageFolder folder)
{
ulong folderSize = 0;
try
{
DirectoryInfo dirInfo = new DirectoryInfo(folder.Path);
// Get back a prefilled (with size) list of files contained in given folder
foreach (var fileInfo in dirInfo.EnumerateFiles("*", SearchOption.AllDirectories))
{
folderSize += (ulong)fileInfo.Length;
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.ToString());
return 0;
}
return folderSize;
}
// Return the system FreeSpace and Capacity properties
private async static Task<IDictionary<string, object>> getExtraProperties()
{
var basicProperties = await Windows.Storage.ApplicationData.Current.LocalFolder.GetBasicPropertiesAsync();
return await basicProperties.RetrievePropertiesAsync(new string[] { "System.FreeSpace", "System.Capacity" });
}
// Class Entry point
public static IAsyncOperation<string> info(string args)
{
// Entry point in WinRT can not return Task<T> - so here is a trick to convert IAsyncOperation (WinRT) into classic C# async
return infoTask().AsAsyncOperation();
}
// The real disk space work is done here within some asynchronous stuff
private async static Task<string> infoTask()
{
Result result = new Result();
// Run folder discovery into another Thread to not block UI Thread
await Task.Run(() => {
foreach (var folder in APP_FOLDERS)
{
result.app += sizeFolder(folder);
}
});
await getExtraProperties().ContinueWith(propertiesTask =>
{
result.free = (ulong)propertiesTask.Result["System.FreeSpace"];
result.total = (ulong)propertiesTask.Result["System.Capacity"];
});
// Return JSON Result
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Result));
MemoryStream outputMs = new MemoryStream();
serializer.WriteObject(outputMs, result);
outputMs.Position = 0;
StreamReader sr = new StreamReader(outputMs);
return sr.ReadToEnd();
}
}
}
This project is from https://github.com/sqli/sqli-cordova-disk-space-plugin
It simply looks for used disk space and reports the used and available space using the System.IO.DirectoryInfo and the async methods to get the free space and capacity.
When I build this is it generates the winmd files no problems, I have correctly registered and loaded these in my cordova (Visual Studio 2017) project, Build for Windows 10 and run - when I run this code in the main cordova project
DiskSpacePlugin.info({}, function (ok) { console.log(ok); }, function (err) { console.log(err); });
I get this result in the console
WinRTError: The system cannot find the file specified.
System.IO.FileNotFoundException: Could not load file or assembly 'System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
at DiskSpaceLibrary.DiskSpace.sizeFolder(StorageFolder folder)
at DiskSpaceLibrary.DiskSpace.<>c__DisplayClass5_0.<infoTask>b__0()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.Ex
console-via-logger.js (173,15)
{
[functions]: ,
__proto__: { },
asyncOpCausalityId: 461,
asyncOpSource: { },
asyncOpType: "Windows.Foundation.IAsyncOperation`1<String>",
description: "The system cannot find the file specified.
System.IO.FileNotFoundException: Could not load file or assembly 'System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
at DiskSpaceLibrary.DiskSpace.sizeFolder(StorageFolder folder)
at DiskSpaceLibrary.DiskSpace.<>c__DisplayClass5_0.<infoTask>b__0()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.Ex",
message: "The system cannot find the file specified.
System.IO.FileNotFoundException: Could not load file or assembly 'System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
at DiskSpaceLibrary.DiskSpace.sizeFolder(StorageFolder folder)
at DiskSpaceLibrary.DiskSpace.<>c__DisplayClass5_0.<infoTask>b__0()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.Ex",
name: "WinRTError",
number: -2147024894
}
I have also tried another module for unzipping files in a cordova windows 10 project (I do not have the source for this one however it comes from https://github.com/Culture22/cordova-windows10-zip) and it comes up with exactly the same error messages when I try to run it within the app.
I have googled and looked for this issue for the last 4 days and I am unable to progress, the methods being used are all support by the framework apparently looking at (msdn.microsoft.com/en-us/library/windows/apps/mt185496.aspx) - does anyone have any insight?
It seems like the library you're referencing references the System.IO.FileSystem.dll, however for whatever reason its not getting deployed with your application. I suggest try adding a nuget reference to System.IO.FileSystem.dll to your application.
I tried to use firewallAPI.dll to add a rule. It works fine for calc.exe (or some other files) as described bellow but fails for msdtc.exe with the following exception:
System.IO.FileNotFoundException: 'The system cannot find the file
specified. (Exception from HRESULT: 0x80070002)'
Example:
static void Main(string[] args)
{
var manager = GetFirewallManager();
if (manager.LocalPolicy.CurrentProfile.FirewallEnabled)
{
var path = #"C:\Windows\System32\calc.exe";
//var path = #"C:\Windows\System32\msdtc.exe"; // System.IO.FileNotFoundException: 'The system cannot find the file specified.
AuthorizeApplication("Test", path, NET_FW_SCOPE_.NET_FW_SCOPE_ALL, NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY);
}
}
private const string CLSID_FIREWALL_MANAGER =
"{304CE942-6E39-40D8-943A-B913C40C9CD4}";
private static NetFwTypeLib.INetFwMgr GetFirewallManager()
{
Type objectType = Type.GetTypeFromCLSID(
new Guid(CLSID_FIREWALL_MANAGER));
return Activator.CreateInstance(objectType)
as NetFwTypeLib.INetFwMgr;
}
private const string PROGID_AUTHORIZED_APPLICATION =
"HNetCfg.FwAuthorizedApplication";
public static bool AuthorizeApplication(string title, string applicationPath,
NET_FW_SCOPE_ scope, NET_FW_IP_VERSION_ ipVersion)
{
// Create the type from prog id
Type type = Type.GetTypeFromProgID(PROGID_AUTHORIZED_APPLICATION);
INetFwAuthorizedApplication auth = Activator.CreateInstance(type)
as INetFwAuthorizedApplication;
auth.Name = title;
auth.ProcessImageFileName = applicationPath;
auth.Scope = scope;
auth.IpVersion = ipVersion;
auth.Enabled = true;
INetFwMgr manager = GetFirewallManager();
manager.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(auth);
return true;
}
Note: I checked the folder and see the file is located properly...
Could anybody help to add firewall rule for Distributed Transaction Coordinator? Maybe I should try to add another file to firewall (not msdtc.exe)?
Project > Properties > Build tab, untick the "Prefer 32-bit" checkbox. You don't prefer it, there is no 32-bit version of msdtc.exe.
Why the file system redirector caused the FileNotFoundException is explained well in this MSDN article.
I am trying to interface C# to R using RDotNet.
The following code is wants R to calculate the sum of two numbers and C# to get the result back and display it in the command window.
using System;
using RDotNet;
namespace rcon
{
class Program
{
static void Main(string[] args)
{
string dllPath = #"C:\Program Files\R\R-3.1.0\bin\i386";
REngine.SetDllDirectory(dllPath);
REngine.CreateInstance("RDotNet");
//REngine engine = REngine.GetInstanceFromID("RDotNet");
using (REngine engine = REngine.GetInstanceFromID("RDotNet"))
{
var x = engine.Evaluate("x <- 1 + 2");
Console.WriteLine(x);
}
}
}
}
but when I try to send the command to R and get back the calue in x I got an error:
"InvalidOperationException was unhandled"
"Operation is not valid due to the current state of the object."
If I explore the object "engine" I see that IsRunning=false.
Can this be the problem? And how can I fix this in order to be able to interface to R?
It looks like you have outdated version of R.NET.
From R.NET project documentation
R.NET 1.5.10 and subsequent versions include significant changes
notably to alleviate two stumbling blocks often dealt with by users:
paths to the R shared library, and preventing multiple engine
initializations.
You can update your R.NET using NuGet manager from Visual Studio. See the same documentation page for detals.
Here is code sample from the same documentatin page - note that initialization of REngine is significantly simpler now (as now Rengine looks at the Registry settings set up by the R installer):
REngine.SetEnvironmentVariables(); // <-- May be omitted; the next line would call it.
REngine engine = REngine.GetInstance();
// A somewhat contrived but customary Hello World:
CharacterVector charVec = engine.CreateCharacterVector(new[] { "Hello, R world!, .NET speaking" });
engine.SetSymbol("greetings", charVec);
engine.Evaluate("str(greetings)"); // print out in the console
string[] a = engine.Evaluate("'Hi there .NET, from the R engine'").AsCharacter().ToArray();
Console.WriteLine("R answered: '{0}'", a[0]);
Console.WriteLine("Press any key to exit the program");
Console.ReadKey();
engine.Dispose();