IronPython.Runtime.PythonDictionary getTeleportDictionaryFromData(out string heightDimensions, double[,] imageData, double[,] imageData2, double mixture, double normalization = 0, bool useLog = false) { dynamic teleportationHelper = pythonFile.TeleportationHelper("TeleportationHelper"); bool normalizeManually = normalization > 0; teleportationHelper.SetHeights(imageData, imageData2, imageData.GetLength(0), imageData.GetLength(1)); teleportationHelper.ApplySwap(mixture, useLog, normalizeManually); dynamic circuit = teleportationHelper.GetCircuit(); int numberofQubits = circuit.num_qubits; heightDimensions = circuit.name; QuantumCircuit quantumCircuit = QuantumImageHelper.ParseCircuit(circuit.data, numberofQubits); MicroQiskitSimulator simulator = new MicroQiskitSimulator(); quantumCircuit.Normalize(); double[] doubleArray = new double[0]; string[] stringArray = new string[0]; double[] probs = simulator.GetProbabilities(quantumCircuit); QuantumImageHelper.GetProbabilityArrays(probs, numberofQubits, ref doubleArray, ref stringArray); IronPython.Runtime.PythonDictionary dictionary = pythonFile.CombinedHeightFromProbabilities(stringArray, doubleArray, doubleArray.Length, numberofQubits, heightDimensions, useLog, normalization); return(dictionary); }
//interface //constructor public Console(IConsoleTarget target) { if (target == null) { throw new ArgumentException("target cannot be null"); } title = target.ConsoleTitle; this.target = target; var targetScope = target.GetScope(); var locals = new IronPython.Runtime.PythonDictionary(); foreach (var name in targetScope.GetVariableNames()) { locals[name] = targetScope.GetVariable(name); } scope = Py.CreateScope(); scope.SetVariable("_locals", locals); var ops = scope.Engine.Operations; string init_script = System.IO.File.ReadAllText(Util.ResourcePath("PythonScripts/initialize_new_console.py")); Py.Engine.Execute(init_script, scope); python_output_buffer = scope.GetVariable <IronPython.Modules.PythonIOModule.StringIO>("output_buffer"); python_compile_command = scope.GetVariable <IronPython.Runtime.PythonFunction>("compile_command"); python_console_run_code = scope.GetVariable <IronPython.Runtime.PythonFunction>("console_run_code"); output = new LineBuffer(new string[] { ">>> " }); input = new LineBuffer(new string[] { "" }); editor = new StringBuilder(500); multilineEditor = new StringBuilder(500); _currentInputIndex = 0; _editorCursor = 0; }
public static Texture2D CalculateGreyTexture(IronPython.Runtime.PythonDictionary probabilityDict, string dimensions) { Vector2Int dim = ParseVector(dimensions); int width = dim.x; int height = dim.y; return(CalculateGreyTexture(probabilityDict, width, height)); }
private static void Monster_Data(DesignerItem monster, int aiID) { var ipy = Python.CreateRuntime(); dynamic test = ipy.UseFile("Code\\monster_data.py"); IronPython.Runtime.PythonDictionary data = test.data; IronPython.Runtime.PythonDictionary unit = null; IronPython.Runtime.PythonTuple tuple = null; List <int> aiIDList = new List <int>(); aiIDList.Add(aiID); int monsterID = -1; for (int i = 0; i < monster.outputValue.Count; ++i) { MyTextBox tempTextBox = monster.outputValue[i]; if (tempTextBox.Property.Equals("ID")) { try { monsterID = Convert.ToInt32(tempTextBox.propertyValue); } catch (Exception e) { var ex = new Exception("缺少怪物ID"); throw ex; } } } if (data.ContainsKey(monsterID)) { unit = data[monsterID] as IronPython.Runtime.PythonDictionary; if (unit["monsterAI"] != null) { tuple = unit["monsterAI"] as IronPython.Runtime.PythonTuple; for (int i = 0; i < tuple.Count; ++i) { int exitAIID = Convert.ToInt32(tuple[i]); if (!aiIDList.Contains(exitAIID)) { aiIDList.Add(exitAIID); } } } } else { unit = new IronPython.Runtime.PythonDictionary(); } unit["monsterAI"] = new IronPython.Runtime.PythonTuple(aiIDList); for (int i = 0; i < monster.outputValue.Count; ++i) { MyTextBox tempTextBox = monster.outputValue[i]; if (!tempTextBox.Property.Equals(tempTextBox.propertyValue) && tempTextBox.propertyValue != null && !tempTextBox.Property.Equals("ID")) { unit[tempTextBox.Property] = tempTextBox.propertyValue; } } data[monsterID] = unit; exportCode(data, "monster_data.py"); }
public static IronPython.Runtime.PythonDictionary AsPyDictionary(this object source) //, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance) { var pyDic = new IronPython.Runtime.PythonDictionary(); Type someObjectType = source.GetType(); foreach (var item in source.GetType().GetProperties()) { object newValue = null; try { if ((item.PropertyType.GetInterfaces().Contains(typeof(System.Collections.IList)))) { MethodInfo method = typeof(ObjectExtensions).GetMethod("AsPyList"); var value = item.GetValue(source, null); if (value != null) { newValue = method.Invoke(null, new object[] { item.GetValue(source, null) }); } } else if (item.PropertyType.Namespace == typeof(ObjectExtensions).Namespace) { MethodInfo method = typeof(ObjectExtensions).GetMethod("AsPyDictionary"); var value = item.GetValue(source, null); if (value != null) { newValue = method.Invoke(null, new object[] { item.GetValue(source, null) }); } } else { newValue = item.GetValue(source, null); } //pyDic.Add(item.Name, item.GetValue(source, null)); if (newValue != null) { //we encode strings as unicode if (newValue.GetType() == typeof(string)) { pyDic.Add(item.Name, Encoding.Unicode.GetString(Encoding.Unicode.GetBytes((string)newValue))); } else { pyDic.Add(item.Name, newValue); } } } catch (Exception ex) { Console.WriteLine("Unable to add:" + newValue.ToString()); Console.WriteLine(ex.Message); } } return(pyDic); }
public static void PerformModuleReload( IronPython.Runtime.PythonContext context, IronPython.Runtime.PythonDictionary dict) { context.DomainManager.LoadAssembly(typeof(System.Xml.Linq.XDocument).Assembly); dict["FOO"] = "bar"; System.Console.WriteLine("Module Load"); }
public static IronPython.Runtime.PythonDictionary ToPythonDictionary(this System.Collections.Generic.IDictionary <string, object> dictionary) { var pyDictionary = new IronPython.Runtime.PythonDictionary(); foreach (var pair in dictionary) { pyDictionary.Add(System.Collections.Generic.KeyValuePair.Create <object, object>(pair.Key.ToString(), pair.Value.ToString())); } return(pyDictionary); }
/// <summary> /// Constructing a greyscale image from a single quantumCircuit (which should represent a greyscale image). /// Used after image effect are applied to the image (the circuit) to get the modified picture. /// </summary> /// <param name="quantumCircuit">The circuit representing the (modified) image.</param> /// <param name="useLog">If logarithmic decoding should be used to decode the image.</param> /// <returns></returns> public Texture2D GetGreyTexture(QuantumCircuit quantumCircuit, bool useLog = false) { MicroQiskitSimulator simulator = new MicroQiskitSimulator(); double[] doubleArray = new double[0]; string[] stringArray = new string[0]; QuantumImageHelper.GetProbabilityArrays(simulator.GetProbabilities(quantumCircuit), quantumCircuit.NumberOfQubits, ref doubleArray, ref stringArray); IronPython.Runtime.PythonDictionary dictionary = pythonFile.HeightFromProbabilities(stringArray, doubleArray, doubleArray.Length, quantumCircuit.DimensionString, useLog); return(QuantumImageHelper.CalculateGreyTexture(dictionary, quantumCircuit.DimensionString)); }
public void CalibrateTrafficDataStats() { Task.Factory.StartNew(new Action(() => { int count = 0; try { string pythonLibPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PythonLib"); string pythohFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "stats_calibration.py"); ScriptEngine engine = IronPython.Hosting.Python.CreateEngine(); engine.SetSearchPaths(new List <string> { pythonLibPath }); dynamic pythonFile = engine.Runtime.UseFile(pythohFilePath); while (count++ < 5) { try { IronPython.Runtime.PythonDictionary dictionary = (IronPython.Runtime.PythonDictionary)pythonFile.get_stats_by_http(); string monthTotalMib = (dictionary["MonthTotal"] as IronPython.Runtime.List)[0] as string; string monthUsedMib = (dictionary["MonthUsed"] as IronPython.Runtime.List)[0] as string; string monthUploadMib = (dictionary["MonthUpload"] as IronPython.Runtime.List)[0] as string; string monthDownloadMib = (dictionary["MonthDownload"] as IronPython.Runtime.List)[0] as string; this.MonthTotal = (long)Utils.ConvertToBytes(double.Parse(monthTotalMib)).Value; this.MonthUsed = (long)Utils.ConvertToBytes(double.Parse(monthUsedMib)).Value; this.MonthUpload = (long)Utils.ConvertToBytes(double.Parse(monthUploadMib)).Value; this.MonthDownload = (long)Utils.ConvertToBytes(double.Parse(monthDownloadMib)).Value; this.Save(); Console.WriteLine("CalibrateTrafficDataStats success."); break; } catch (Exception ex) { Console.WriteLine("CalibrateTrafficDataStats error: " + ex.Message); continue; } } if (count >= 5) { Console.WriteLine("CalibrateTrafficDataStats error: Over max attempt times."); } } catch (Exception ex) { //数据校正失败 Console.WriteLine("CalibrateTrafficDataStats error: " + ex.Message); } }), new CancellationTokenSource().Token, TaskCreationOptions.LongRunning, TaskScheduler.Current); }
public static void FillTextureGrey(IronPython.Runtime.PythonDictionary probabilityDict, Texture2D textureToFill, int startWidth = 0, int startHeight = 0) { Vector2Int position; float colorValue; foreach (var item in probabilityDict) { position = ParseVector(item.Key.ToString()); colorValue = (float)(double)item.Value; textureToFill.SetPixel(position.x + startWidth, position.y + startHeight, new Color(colorValue, colorValue, colorValue)); } }
/// <summary> /// Using the quantum teleportation algorithm to mix 2 images. /// Kind of using teleportation to swap placed between the 2 images. /// Teleportation progress of 0 means no teleportation, Teleportation progress of 1 means the teleportation finished. /// And Teleportation progress of 0.5 means it is right in the middle. /// </summary> /// <param name="inputTexture">The first image which should be mixed.</param> /// <param name="inputTexture2">The second image which should be mixed.</param> /// <param name="teleportationProgress">How far the teleportation has progressed. 0 Not at all, 0.5 in the middle, 1 finished. Can take on any value between 0 and 1</param> /// <returns></returns> public Texture2D TeleportTexturesGrey(Texture2D inputTexture, Texture2D inputTexture2, double teleportationProgress) { string heightDimensions; Texture2D OutputTexture = new Texture2D(2, 2); double[,] imageData = QuantumImageHelper.GetGreyHeighArray(inputTexture); double[,] imageData2 = QuantumImageHelper.GetGreyHeighArray(inputTexture2); IronPython.Runtime.PythonDictionary greyDictionary = getTeleportDictionaryFromData(out heightDimensions, imageData, imageData2, teleportationProgress); OutputTexture = QuantumImageHelper.CalculateGreyTexture(greyDictionary, heightDimensions); return(OutputTexture); }
static void Main(string[] args) { int count = 0; try { string pythonLibPath = AppDomain.CurrentDomain.BaseDirectory + "PythonLib"; string pythohFilePath = AppDomain.CurrentDomain.BaseDirectory + "stats_calibration.py"; ScriptEngine engine = IronPython.Hosting.Python.CreateEngine(); engine.SetSearchPaths(new List <string> { pythonLibPath }); //ScriptSource script = engine.CreateScriptSourceFromFile(@"stats_calibration.py", Encoding.UTF8); //ScriptScope scope = engine.CreateScope(); //script.Execute(scope); //var result = scope.GetVariable<Func<object>>("get_stats_by_http"); dynamic pythonFile = engine.Runtime.UseFile(pythohFilePath); while (count++ < 5) { try { IronPython.Runtime.PythonDictionary dictionary = (IronPython.Runtime.PythonDictionary)pythonFile.get_stats_by_http(); var monthTotalMib = (dictionary["MonthTotal"] as IronPython.Runtime.List)[0]; var monthUsedMib = (dictionary["MonthUsed"] as IronPython.Runtime.List)[0]; var monthUploadMib = (dictionary["MonthUpload"] as IronPython.Runtime.List)[0]; var monthDownloadMib = (dictionary["MonthDownload"] as IronPython.Runtime.List)[0]; Console.WriteLine(monthTotalMib); Console.WriteLine(monthUsedMib); Console.WriteLine(monthUploadMib); Console.WriteLine(monthDownloadMib); break; } catch (Exception ex) { Console.WriteLine("CalibrateTrafficDataStats error: " + ex.Message); continue; } } } catch (Exception ex) { //数据校正失败 Console.WriteLine("数据校正失败:" + ex.Message); } //string result = script.Execute(); Console.ReadLine(); }
public static void FillTextureColored(IronPython.Runtime.PythonDictionary redDict, IronPython.Runtime.PythonDictionary greenDict, IronPython.Runtime.PythonDictionary blueDict, Texture2D textureToFill, int startWidth = 0, int startHeight = 0) { Vector2Int position; float redValue, greenValue, blueValue; foreach (var item in redDict) { position = ParseVector(item.Key.ToString()); redValue = (float)(double)item.Value; greenValue = (float)(double)greenDict[item.Key]; blueValue = (float)(double)blueDict[item.Key]; textureToFill.SetPixel(position.x + startWidth, position.y + startHeight, new Color(redValue, greenValue, blueValue)); } }
public static T ToObject <T>(this IronPython.Runtime.PythonDictionary source) where T : class, new() { T someObject = new T(); Type someObjectType = someObject.GetType(); foreach (var item in source) { try { var newValue = item.Value; PropertyInfo prop = null; //try to get the property from the sub class prop = someObjectType.GetProperty((String)item.Key, BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); if (prop == null) { //serch in the base classes prop = someObjectType.GetProperty((String)item.Key); } if (newValue.GetType() == typeof(IronPython.Runtime.List)) { MethodInfo method = typeof(ObjectExtensions).GetMethod("ToList"); MethodInfo generic = method.MakeGenericMethod(prop.PropertyType.GenericTypeArguments[0]); newValue = generic.Invoke(null, new object[] { (IronPython.Runtime.List)newValue }); } else if (newValue.GetType() == typeof(IronPython.Runtime.PythonDictionary)) { MethodInfo method = typeof(ObjectExtensions).GetMethod("ToObject"); MethodInfo generic = method.MakeGenericMethod(prop.PropertyType); newValue = generic.Invoke(null, new object[] { (IronPython.Runtime.PythonDictionary)newValue }); } prop.SetValue(someObject, newValue, null); } catch (Exception ex) { Console.WriteLine("Unable to set:" + item.Key); Console.WriteLine(ex.Message); } } return(someObject); }
public static Texture2D CalculateGreyTexture(IronPython.Runtime.PythonDictionary probabilityDict, int width, int height) { Texture2D texture = new Texture2D(width, height); Vector2Int position; float greyValue; foreach (var item in probabilityDict) { position = ParseVector(item.Key.ToString()); greyValue = (float)(double)item.Value; texture.SetPixel(position.x, position.y, new Color(greyValue, greyValue, greyValue)); } texture.Apply(); return(texture); }
/// <summary> /// Constructing a colored image from 3 quantumCircuits, 1 per channel, (which should represent a colored image). /// Used after image effect are applied to the image (the circuit) to get the modified picture /// </summary> /// <param name="redCircuit">The circuit representing the red color channel of the (modified) image.</param> /// <param name="greenCircuit">The circuit representing the green color channel of the (modified) image</param> /// <param name="blueCircuit">The circuit representing the blue color channel of the (modified) image</param> /// <param name="useLog">If logarithmic decoding should be used to decode the image.</param> /// <returns></returns> public Texture2D GetColoreTexture(QuantumCircuit redCircuit, QuantumCircuit greenCircuit, QuantumCircuit blueCircuit, bool useLog = false) { MicroQiskitSimulator simulator = new MicroQiskitSimulator(); //TODO OPTIMIZATIOn initialize arrays only once double[] doubleArray = new double[0]; string[] stringArray = new string[0]; QuantumImageHelper.GetProbabilityArrays(simulator.GetProbabilities(redCircuit), redCircuit.NumberOfQubits, ref doubleArray, ref stringArray); IronPython.Runtime.PythonDictionary redDictionary = pythonFile.HeightFromProbabilities(stringArray, doubleArray, doubleArray.Length, redCircuit.DimensionString, useLog); QuantumImageHelper.GetProbabilityArrays(simulator.GetProbabilities(greenCircuit), greenCircuit.NumberOfQubits, ref doubleArray, ref stringArray); IronPython.Runtime.PythonDictionary greenDictionary = pythonFile.HeightFromProbabilities(stringArray, doubleArray, doubleArray.Length, greenCircuit.DimensionString, useLog); QuantumImageHelper.GetProbabilityArrays(simulator.GetProbabilities(blueCircuit), blueCircuit.NumberOfQubits, ref doubleArray, ref stringArray); IronPython.Runtime.PythonDictionary blueDictionary = pythonFile.HeightFromProbabilities(stringArray, doubleArray, doubleArray.Length, blueCircuit.DimensionString, useLog); return(QuantumImageHelper.CalculateColorTexture(redDictionary, greenDictionary, blueDictionary, redCircuit.DimensionString)); }
public void ReDrawDiagram(string index) { int id = int.Parse(index); AIInitParams["id"] = index; var ipy = Python.CreateRuntime(); dynamic test = ipy.UseFile("Code\\monster_ai_data.py"); IronPython.Runtime.PythonDictionary data = test.data; aiAction = data[id] as IronPython.Runtime.PythonDictionary; init(); IronPython.Runtime.List Trigger = aiAction["trigger"] as IronPython.Runtime.List; triggerName = Convert.ToString(Trigger[0]); for (int i = 1; i < Trigger.Count; ++i) { triggerParamList.Add(Convert.ToString(Trigger[i])); } foreach (var key in aiAction.Keys) { SelectDictionary(Convert.ToString(key)); } }
IronPython.Runtime.PythonDictionary getBlurDictionaryFromData(out string heightDimensions, double[,] imageData, float rotation, bool useLog = false) { //dynamic pythonHelper = PythonFile.QuantumBlurHelper("Helper"); blurHelper.SetHeights(imageData, imageData.GetLength(0), imageData.GetLength(1), useLog); blurHelper.ApplyPartialX(rotation); dynamic circuit = blurHelper.GetCircuit(); int numberofQubits = circuit.num_qubits; heightDimensions = circuit.name; QuantumCircuit quantumCircuit = QuantumImageHelper.ParseCircuit(circuit.data, numberofQubits); MicroQiskitSimulator simulator = new MicroQiskitSimulator(); double[] doubleArray = new double[0]; string[] stringArray = new string[0]; QuantumImageHelper.GetProbabilityArrays(simulator.GetProbabilities(quantumCircuit), numberofQubits, ref doubleArray, ref stringArray); IronPython.Runtime.PythonDictionary dictionary = pythonFile.HeightFromProbabilities(stringArray, doubleArray, doubleArray.Length, heightDimensions, useLog); return(dictionary); }
/// <summary> /// A slightly faster version to construct a colored image from 3 quantumCircuits, 1 per channel, (which should represent a colored image). /// Used after image effect are applied to the image (the circuit) to get the modified picture /// This version should produce less garbage, however, it only makes a small difference, since the python part is the same (and the slow part) /// </summary> /// <param name="redCircuit">The circuit representing the red color channel of the (modified) image.</param> /// <param name="greenCircuit">The circuit representing the green color channel of the (modified) image</param> /// <param name="blueCircuit">The circuit representing the blue color channel of the (modified) image</param> /// <param name="useLog">If logarithmic decoding should be used to decode the image.</param> /// <returns></returns> public Texture2D GetColoreTextureFast(QuantumCircuit redCircuit, QuantumCircuit greenCircuit, QuantumCircuit blueCircuit, bool useLog = false) { MicroQiskitSimulator simulator = new MicroQiskitSimulator(); //Trying optimazations (less garbage). Negative side is we need the full arrays // TODO make circuit initialization better double[] probabilities = new double[MathHelper.IntegerPower(2, redCircuit.NumberOfQubits)]; ComplexNumber[] amplitudes = null; string[] stringArray = QuantumImageHelper.CalculateNameStrings(probabilities.Length, redCircuit.NumberOfQubits); simulator.CalculateProbabilities(redCircuit, ref probabilities, ref amplitudes); IronPython.Runtime.PythonDictionary redDictionary = pythonFile.HeightFromProbabilities(stringArray, probabilities, probabilities.Length, redCircuit.DimensionString, useLog); simulator.CalculateProbabilities(greenCircuit, ref probabilities, ref amplitudes); IronPython.Runtime.PythonDictionary greenDictionary = pythonFile.HeightFromProbabilities(stringArray, probabilities, probabilities.Length, greenCircuit.DimensionString, useLog); simulator.CalculateProbabilities(blueCircuit, ref probabilities, ref amplitudes); IronPython.Runtime.PythonDictionary blueDictionary = pythonFile.HeightFromProbabilities(stringArray, probabilities, probabilities.Length, blueCircuit.DimensionString, useLog); return(QuantumImageHelper.CalculateColorTexture(redDictionary, greenDictionary, blueDictionary, redCircuit.DimensionString)); }
public static Texture2D CalculateColorTexture(IronPython.Runtime.PythonDictionary redValues, IronPython.Runtime.PythonDictionary greenValues, IronPython.Runtime.PythonDictionary blueValues, string dimensions) { Vector2Int dim = ParseVector(dimensions); int width = dim.x; int height = dim.y; Texture2D texture = new Texture2D(width, height); Vector2Int position; float redValue, greenValue, blueValue; foreach (var item in redValues) { position = ParseVector(item.Key.ToString()); redValue = (float)(double)item.Value; greenValue = (float)(double)greenValues[item.Key]; blueValue = (float)(double)blueValues[item.Key]; texture.SetPixel(position.x, position.y, new Color(redValue, greenValue, blueValue)); } texture.Apply(); return(texture); }
private void CreatePythonObjects() { if (string.IsNullOrEmpty(text) == false) { source = python.CreateScriptSourceFromString(text, Microsoft.Scripting.SourceCodeKind.Statements); scope = python.CreateScope(); scope.SetVariable("Application", Env.Current.ScriptManager.ScriptApplication); //Try to execute script to get all its functions into 'scope' try { source.Execute(scope); } catch (System.Exception e) { Env.Current.Logger.LogWarning(string.Format("Fail to execute script '{0}': {1}", this.Name, e.Message)); return; } ScriptScope sysModule = python.GetSysModule(); IronPython.Runtime.PythonDictionary modules = sysModule.GetVariable <IronPython.Runtime.PythonDictionary>("modules"); modules[name] = scope; } }
public Track get_track_info(string store_track_id) { IronPython.Runtime.PythonDictionary tmp = pyMobileclient.get_track_info(store_track_id); return(tmp.ToObject <Track>()); }
public AlbumInfo get_album_info(string album_id, bool include_tracks = true) { IronPython.Runtime.PythonDictionary tmp = pyMobileclient.get_album_info(album_id, include_tracks); return(tmp.ToObject <AlbumInfo>()); }
public ArtistInfo get_artist_info(string artist_id, bool include_albums = true, int max_top_tracks = 5, int max_rel_artist = 5) { IronPython.Runtime.PythonDictionary tmp = pyMobileclient.get_artist_info(artist_id, include_albums, max_top_tracks, max_rel_artist); return(tmp.ToObject <ArtistInfo>()); }
public SearchResult search_all_access(string query, int max_results = 50) { IronPython.Runtime.PythonDictionary tmp = pyMobileclient.search_all_access(query, max_results); return(tmp.ToObject <SearchResult>()); }
private void btnTest_Click(object sender, EventArgs e) { Reaper RR = new Reaper(); Reaper RR2 = new Reaper(); richTextBox.Clear(); WoTReplay Replay = RR.Parse(@"D:\MyClouds\YandexDisk\wot\REP_Cache\086\086_20130531_2238_uk-GB51_Excelsior_07_lakeville (1).wotreplay"); WoTReplay Replay2 = RR2.Parse(@"D:\MyClouds\YandexDisk\wot\REP_Cache\67690030279124597.wotreplay"); /* * ReplayInfo RI = new ReplayInfo(); * RI.ReadDataFromFile(@"D:\MyClouds\YandexDisk\wot\REP_Cache\086\086_20130531_2238_uk-GB51_Excelsior_07_lakeville (1).wotreplay"); * * ReplayInfo RI2 = new ReplayInfo(); * RI2.ReadDataFromFile(@"D:\MyClouds\YandexDisk\wot\REP_Cache\67690030279124597.wotreplay"); */ // BattleResult_v2 BR = new BattleResult_v2(@"D:\MyClouds\YandexDisk\wot\REP_Cache\!!!\___KV1_321235285635519637.dat"); //BattleResult_v2 BRv2 = new BattleResult_v2(@"D:\MyClouds\YandexDisk\wot\REP_Cache\!!!\82243763184823766.dat"); //KeyValuePair<string, dynamic> /* * foreach (int key in BRv2.Vehicles.Keys) * { * richTextBox.AppendText(BRv2.Players[BRv2.Vehicles[key]["accountDBID"]]["name"]); * if (BRv2.Players[BRv2.Vehicles[key]["accountDBID"]]["clanAbbver"] != "") * { * richTextBox.AppendText("[" + BRv2.Players[BRv2.Vehicles[key]["accountDBID"]]["clanAbbver"] + "]"); * } * richTextBox.AppendText("\n"); * richTextBox.AppendText("---Damage: "+BRv2.Vehicles[key]["damageDealt"]+"\n"); * richTextBox.AppendText("---Team : " + BRv2.Vehicles[key]["team"] + "\n"); * } */ JsonTextReader reader = new JsonTextReader(new StringReader(RR.RawData2)); ////////////////////////////////////////////////////////////////// /// UnPicle ////////////////////////////////////////////////////////////////// ScriptEngine m_engine = Python.CreateEngine(); ScriptScope m_scope = null; m_scope = m_engine.CreateScope(); var paths = new List <string>(); paths.Add(@"C:\Program Files (x86)\IronPython 2.7\Lib"); m_engine.SetSearchPaths(paths); string code = @" import pickle class Serialize(object): def unpickle(self,value): return pickle.loads(value) def unpickledat(self,value): f = open(value,'rb') f.seek(261) bb = f.read() return pickle.loads(bb) "; ObjectOperations ops = m_engine.Operations; ScriptSource source; source = m_engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements); source.Execute(m_scope); object klass = m_scope.GetVariable("Serialize"); object instance = ops.Invoke(klass); object method = ops.GetMember(instance, "unpickle"); object result1 = ops.Invoke(method, (object)RR.RawData3); object result2 = ops.Invoke(method, (object)RR2.RawData3); IronPython.Runtime.PythonDictionary OBJ = (IronPython.Runtime.PythonDictionary)result1; //Dictionary<string, dynamic> D = OBJ.ToDictionary<string, dynamic>(; //double O2 = (double)(((IronPython.Runtime.PythonDictionary)OBJ["common"])["duration"]); //269093955030980.dat //BattleResult BR2 = new BattleResult("D:\\322055057453144847.dat"); string[] LAYOUT = new string[] { "_version", "lastBattleTime", "battleLifeTime", "maxFrags", "xp", "maxXP", "battlesCount", "wins", "losses", "survivedBattles", "winAndSurvived", "frags", "frags8p", "fragsBeast", "shots", "hits", "spotted", "damageDealt", "damageReceived", "treesCut", "capturePoints", "droppedCapturePoints", "sniperSeries", "maxSniperSeries", "invincibleSeries", "maxInvincibleSeries", "diehardSeries", "maxDiehardSeries", "killingSeries", "maxKillingSeries", "piercingSeries", "maxPiercingSeries", "battleHeroes", "fragsSinai", "warrior", "invader", "sniper", "defender", "steelwall", "supporter", "scout", "evileye", "medalKay", "medalCarius", "medalKnispel", "medalPoppel", "medalAbrams", "medalLeClerc", "medalLavrinenko", "medalEkins", "medalWittmann", "medalOrlik", "medalOskin", "medalHalonen", "medalBurda", "medalBillotte", "medalKolobanov", "medalFadin", "medalRadleyWalters", "medalBrunoPietro", "medalTarczay", "medalPascucci", "medalDumitru", "medalLehvaslaiho", "medalNikolas", "medalLafayettePool", "sinai", "heroesOfRassenay", "beasthunter", "mousebane", "tankExpertStrg", "titleSniper", "invincible", "diehard", "raider", "handOfDeath", "armorPiercer", "kamikaze", "lumberjack", "markOfMastery", "company/xp", "company/battlesCount", "company/wins", "company/losses", "company/survivedBattles", "company/frags", "company/shots", "company/hits", "company/spotted", "company/damageDealt", "company/damageReceived", "company/capturePoints", "company/droppedCapturePoints", "clan/xp", "clan/battlesCount", "clan/wins", "clan/losses", "clan/survivedBattles", "clan/frags", "clan/shots", "clan/hits", "clan/spotted", "clan/damageDealt", "clan/damageReceived", "clan/capturePoints", "clan/droppedCapturePoints", "tankExpert", "tankExpert0", "tankExpert1", "tankExpert2", "tankExpert3", "tankExpert4", "tankExpert5", "tankExpert6", "tankExpert7", "tankExpert8", "tankExpert9", "tankExpert10", "tankExpert11", "tankExpert12", "tankExpert13", "tankExpert14", "medalBrothersInArms", "medalCrucialContribution", "medalDeLanglade", "medalTamadaYoshio", "bombardier", "huntsman", "alaric", "sturdy", "ironMan", "luckyDevil", "pattonValley", "fragsPatton", "_dynRecPos_vehicle" }; }
public static void exportCode(IronPython.Runtime.PythonDictionary data, string path) { string Path = codePath + "\\" + path; FileStream fs = new FileStream(Path, FileMode.Create, FileAccess.Write); StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8); string startString = "data = {"; sw.WriteLine(startString); foreach (var key in data.Keys) { string phraseOne = "\t" + Convert.ToString(key) + " : " + "{"; string phraseValue = null; IronPython.Runtime.PythonDictionary nodeValue = data[key] as IronPython.Runtime.PythonDictionary; foreach (var kvp in nodeValue.Keys) { if (nodeValue[kvp] == null || nodeValue[kvp].Equals("")) { continue; } string phraseTwo = "'" + Convert.ToString(kvp) + "' : "; string phraseThree = null; if (nodeValue[kvp] is IronPython.Runtime.List) { IronPython.Runtime.List paramList = nodeValue[kvp] as IronPython.Runtime.List; phraseThree = "["; for (int j = 0; j < paramList.Count; ++j) { string convertString = Convert.ToString(paramList[j]); if (Regex.IsMatch(convertString, @"^(\-|\+)?\d+(\.\d+)?$") || Regex.IsMatch(convertString, @"\(\.*\)")) { phraseThree += convertString; } else { phraseThree += "'" + convertString + "'"; } if (j != paramList.Count - 1) { phraseThree += ","; } else { phraseThree += "], "; } } } else { string convertString = Convert.ToString(nodeValue[kvp]); if (Regex.IsMatch(convertString, @"^(\-|\+)?\d+(\.\d+)?$") || nodeValue[kvp] is IronPython.Runtime.PythonTuple) { phraseThree = convertString + ", "; } else { phraseThree = "'" + convertString + "'" + ", "; } } phraseValue += (phraseTwo + phraseThree); } phraseValue = phraseOne + phraseValue + "},"; sw.WriteLine(phraseValue); } sw.WriteLine("}"); sw.Close(); fs.Close(); }
static void Main(string[] args) { // 加载外部 python 脚本文件. ScriptRuntime pyRumTime = Python.CreateRuntime(); dynamic obj = pyRumTime.UseFile("hello.py"); // ================================================== // 简单调用脚本文件中的方法. Console.WriteLine(obj.welcome("Test C# Call Python.")); Console.WriteLine(obj.welcome("测试中文看看是否正常!")); // ================================================== // 测试自定义对象. TestDataObject testObj = new TestDataObject() { UserName = "******", Age = 20, Desc = "", }; Console.WriteLine("调用脚本前对象数据:{0}", testObj); obj.testAddAge(testObj); Console.WriteLine("调用 testAddAge 脚本后,对象数据={0}", testObj); obj.testAddAge2(testObj); Console.WriteLine("调用 testAddAge2 脚本后,对象数据={0}", testObj); // ================================================== // 测试 List. IronPython.Runtime.List testList = new IronPython.Runtime.List(); testList.Add("List数据1"); testList.Add("List数据2"); testList.Add("List数据3"); // 测试参数为 List. string result = obj.testList(testList); Console.WriteLine("调用 testList , 返回结果:{0}", result); // ================================================== // 测试 Set. IronPython.Runtime.SetCollection testSet = new IronPython.Runtime.SetCollection(); testSet.add("Set数据1"); testSet.add("Set数据2"); testSet.add("Set数据3"); // 测试参数为 Set. result = obj.testSet(testSet); Console.WriteLine("调用 testSet , 返回结果:{0}", result); // ================================================== // 测试 Dictionary. IronPython.Runtime.PythonDictionary testDictionary = new IronPython.Runtime.PythonDictionary(); testDictionary["Key1"] = "Value1"; testDictionary["Key2"] = "Value2"; testDictionary["Key3"] = "Value3"; // 测试参数为 Dictionary. result = obj.testDictionary(testDictionary); Console.WriteLine("调用 testDictionary , 返回结果:{0}", result); // 测试调用 MD5 MD5Test.Test(); MD5Test.Test2(); // 测试调用 GetSysPath GetSysPathTest.Test(); GetSysPathTest.Test2(); UmengTest.Test(); Console.ReadLine(); }
public void initRow(DataGridViewRow row, IronPython.Runtime.PythonDictionary shotgunTask = null, Microsoft.Office.Interop.MSProject.Task projectTask = null) { row.Tag = new TaskRow(shotgunTaskIn: shotgunTask, projectTaskIn: projectTask); }
public static void PythonStructure() { IronPython.Runtime.PythonDictionary data = new IronPython.Runtime.PythonDictionary(); }