def test_correct_overload_selection(): """Test correct overloading selection for common types.""" from System import (String, Double, Single, Int16, Int32, Int64) from System import Math substr = String("substring") assert substr.Substring(2) == substr.Substring.__overloads__[Int32]( Int32(2)) assert substr.Substring(2, 3) == substr.Substring.__overloads__[Int32, Int32]( Int32(2), Int32(3)) for atype, value1, value2 in zip([Double, Single, Int16, Int32, Int64], [1.0, 1.0, 1, 1, 1], [2.0, 0.5, 2, 0, -1]): assert Math.Abs(atype(value1)) == Math.Abs.__overloads__[atype](atype(value1)) assert Math.Abs(value1) == Math.Abs.__overloads__[atype](atype(value1)) assert Math.Max(atype(value1), atype(value2)) == Math.Max.__overloads__[atype, atype]( atype(value1), atype(value2)) assert Math.Max(atype(value1), value2) == Math.Max.__overloads__[atype, atype]( atype(value1), atype(value2)) clr.AddReference("System.Runtime.InteropServices") from System.Runtime.InteropServices import GCHandle, GCHandleType from System import Array, Byte cs_array = Array.CreateInstance(Byte, 1000) handler = GCHandle.Alloc(cs_array, GCHandleType.Pinned)
def animation_data_run(abdataPath): import ExcelData from collections import OrderedDict from System import Int32 import AssetBundleManager from AnimationDataManager import _AnimationDataManager__ExcelCovert as ExcelCovert from AnimationDataManager import AnimationData list = [] result = OrderedDict() operation = AssetBundleManager.LoadAllAsset(abdataPath, ExcelData, None) if not operation: return result for data in operation.GetAllAssets[ExcelData](): if not data: continue if (data.name.IndexOf('Sheet1') != -1): list = [] for param in data.list: if (param.list.Count > 0): ok, num2 = Int32.TryParse(param.list.Item[0]) if ok: list.append(ExcelCovert(param)) elif (data.name.IndexOf('Sheet2') != -1): for covert in list: list2 = data.Get(covert.start, covert.end) for j in range(list2.Count): param2 = list2.Item[j] if (param2.list.Count > 0): ok, _ = Int32.TryParse(param2.list.Item[0]) if ok: data2 = AnimationData(param2, False) name = translate(data2.name) result[name] = data2 return result
def load_excel_data(abdataPath, loader, bundle='abdata'): import ExcelData from collections import OrderedDict from System import Int32 import AssetBundleManager from AnimationDataManager import _AnimationDataManager__ExcelCovert as ExcelCovert from AnimationDataManager import AnimationData list = [] result = OrderedDict() operation = AssetBundleManager.LoadAllAsset(abdataPath, ExcelData, bundle) if not operation: return result print 'Getttings assets' for data in operation.GetAllAssets[ExcelData](): if not data: continue print 'reading sheets' if (data.name.IndexOf('Sheet1') != -1): list = [] for param in data.list: if (param.list.Count > 0): ok, num2 = Int32.TryParse(param.list.Item[0]) if ok: list.append(ExcelCovert(param)) elif (data.name.IndexOf('Sheet2') != -1): for covert in list: list2 = data.Get(covert.start, covert.end) for j in range(list2.Count): param2 = list2.Item[j] if (param2.list.Count > 0): ok, _ = Int32.TryParse(param2.list.Item[0]) if ok: name, data = loader(param2) result[name] = data return result
def rows(self): """ Returns a list of rows which are of type _Pdata You may access any fields, do assignments and delete rows like any other _Pdata objects """ _row_db_id = self.api.AdkGetRowDataId(self.data, Int32(0))[1] _nrows_field_id = self.api.AdkGetNrowsFieldId(self.data, Int32(0))[1] _rows_field_id = self.api.AdkGetRowsFieldId(self.data, Int32(0))[1] nrows = self.api.AdkGetDouble(self.data, _nrows_field_id, Double(0.0))[1] _existing_rows = [] for index in range(int(nrows)): data = self.api.AdkGetRowData(self.data, index, Int32(0))[1] _existing_rows.append( _Pdata( self.api, _row_db_id, data, parent_pdata=self, is_a_row=True, row_index=index + 1, ) ) return _existing_rows
def createDatasetWithCompoundType(h5file): mtype = createMemType() ftype = createFileType() npoints = 4 shape = Array[Int64]((npoints, )) dspace = H5S.create_simple(shape.Length, shape) dset = H5D.create(h5file, 'DS1', ftype, dspace) ms = MemoryStream() writer = BinaryWriter(ms) writer.Write(Int32(1153)) s = 'Exterior (static)' if IntPtr.Size == 8: writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt64()) else: writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt32()) writer.Write(Double(53.23)) writer.Write(Double(24.57)) writer.Write(Int32(1184)) s = 'Intake' if IntPtr.Size == 8: writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt64()) else: writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt32()) writer.Write(Double(55.12)) writer.Write(Double(22.95)) writer.Write(Int32(1027)) s = 'Intake manifold' if IntPtr.Size == 8: writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt64()) else: writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt32()) writer.Write(Double(103.55)) writer.Write(Double(31.23)) writer.Write(Int32(1313)) s = 'Exhaust manifold' if IntPtr.Size == 8: writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt64()) else: writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt32()) writer.Write(Double(1252.89)) writer.Write(Double(84.11)) byteArray = ms.ToArray() H5D.write(dset, mtype, H5Array[Byte](byteArray)) H5S.close(dspace) H5T.close(ftype) H5T.close(mtype) return dset
def generate_arrow_graph(tasks): nodes = tasks[:, 0] nodes = [string.ascii_uppercase.index(node.upper()) for node in nodes] tasks[:, 0] = nodes dependencies_list = tasks[:, 1] dependencies_index = [[ string.ascii_uppercase.index(dep.upper()) for dep in dependencies if dep != "-" ] for dependencies in dependencies_list] tasks[:, 1] = dependencies_index ActivityDependencies = List[ActivityDependency]() for task in tasks: #print("Task: {}".format(task[0])) Predecessors = List[Int32]() for t in task[1]: #print("Dependecnies: {}".format(t)) Predecessors.Add(Int32(t)) task_id = Int32(task[0]) ActivityDependencies.Add( ActivityDependency(Activity(task_id), Predecessors)) arrow_graph_generator = ArrowGraphGenerator(ActivityDependencies) activity_arrow_graph = arrow_graph_generator.GenerateGraph() edges = [] # returns Dictionary<ActivityEdge, ActivityEdge> ActivityEdges = activity_arrow_graph.Edges for activity_edge in ActivityEdges: #print("edge [{}, {}]".format(activity_edge.Source.Id, activity_edge.Target.Id)) #print(activity_edge.Target.Id) #print(activity_edge.Activity) if activity_edge.Activity: edges.append([ activity_edge.Source.Id + 1, activity_edge.Target.Id + 1, { 'name': activity_edge.Activity.Id } ]) else: edges.append([ activity_edge.Source.Id + 1, activity_edge.Target.Id + 1, { 'name': '' } ]) nodes = [] Vertices = activity_arrow_graph.Vertices for verticle in Vertices: #print(verticle.Id) nodes.append(verticle.Id + 1) return nodes, edges
def read_frame(self, cam): """Reads a image from the camera, if available, and returns it. If available, it returns ``(data, fmt, (w, h), count, queued_count, t)``, otherwise, it returns None. See :class:`ThorCamServer`. """ queued_count = cam.get_NumberOfQueuedFrames() if queued_count <= 0: return frame = cam.GetPendingFrameOrNull() t = clock() if not frame: return count = frame.FrameNumber h = frame.ImageData.Height_pixels w = frame.ImageData.Width_pixels if self._color_processor is not None: from Thorlabs.TSI import ColorInterfaces demosaicked_data = Array.CreateInstance(UInt16, h * w * 3) processed_data = Array.CreateInstance(UInt16, h * w * 3) fmt = ColorInterfaces.ColorFormat.BGRPixel max_pixel_val = int(2**cam.BitDepth - 1) self._demosaic.Demosaic(w, h, Int32(0), Int32(0), cam.ColorFilterArrayPhase, fmt, ColorInterfaces.ColorSensorType.Bayer, Int32(cam.BitDepth), frame.ImageData.ImageData_monoOrBGR, demosaicked_data) self._color_processor.Transform48To48(demosaicked_data, fmt, 0, max_pixel_val, 0, max_pixel_val, 0, max_pixel_val, 0, 0, 0, processed_data, fmt) pixel_fmt = 'bgr48le' data = as_numpy_array(processed_data) else: pixel_fmt = 'gray16le' data = as_numpy_array(frame.ImageData.ImageData_monoOrBGR) # img = Image( # plane_buffers=[data.tobytes()], # pix_fmt=pixel_fmt, size=(w, h)) return data.tobytes(), pixel_fmt, (w, h), count, queued_count, t
def __init__(self, title, url, width, height, resizable, fullscreen, min_size, webview_ready): self.Text = title self.AutoScaleBaseSize = Size(5, 13) self.ClientSize = Size(width, height) self.MinimumSize = Size(min_size[0], min_size[1]) # Application icon try: # Try loading an icon embedded in the exe file. This will crash when frozen with PyInstaller handler = windll.kernel32.GetModuleHandleW(None) icon_handler = windll.user32.LoadIconW(handler, 1) self.Icon = Icon.FromHandle( IntPtr.op_Explicit(Int32(icon_handler))) except: pass self.webview_ready = webview_ready self.web_browser = WinForms.WebBrowser() self.web_browser.Dock = WinForms.DockStyle.Fill if url: self.web_browser.Navigate(url) self.Controls.Add(self.web_browser) self.is_fullscreen = False self.Shown += self.on_shown if fullscreen: self.toggle_fullscreen()
def __init__(self, window): self.uid = window.uid self.pywebview_window = window self.url = None self.Text = window.title self.Size = Size(window.initial_width, window.initial_height) self.MinimumSize = Size(window.min_size[0], window.min_size[1]) self.BackColor = ColorTranslator.FromHtml(window.background_color) if window.initial_x is not None and window.initial_y is not None: self.move(window.initial_x, window.initial_y) else: self.StartPosition = WinForms.FormStartPosition.CenterScreen self.AutoScaleDimensions = SizeF(96.0, 96.0) self.AutoScaleMode = WinForms.AutoScaleMode.Dpi if not window.resizable: self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle self.MaximizeBox = False if window.minimized: self.WindowState = WinForms.FormWindowState.Minimized # Application icon handle = windll.kernel32.GetModuleHandleW(None) icon_path = os.path.join(os.path.dirname(os.path.realpath(importlib.util.find_spec("bcml").origin)), "data", "bcml.ico") icon_handle = windll.shell32.ExtractIconW(handle, icon_path, 0) if icon_handle != 0: self.Icon = Icon.FromHandle( IntPtr.op_Explicit(Int32(icon_handle)) ).Clone() windll.user32.DestroyIcon(icon_handle) self.closed = window.closed self.closing = window.closing self.shown = window.shown self.loaded = window.loaded self.url = window.url self.text_select = window.text_select self.on_top = window.on_top self.is_fullscreen = False if window.fullscreen: self.toggle_fullscreen() if window.frameless: self.frameless = window.frameless self.FormBorderStyle = 0 CEF.create_browser(window, self.Handle.ToInt32(), BrowserView.alert) self.Shown += self.on_shown self.FormClosed += self.on_close self.FormClosing += self.on_closing self.Resize += self.on_resize
def __init__(self, window): self.uid = window.uid self.pywebview_window = window self.real_url = None self.Text = window.title self.ClientSize = Size(window.width, window.height) self.MinimumSize = Size(window.min_size[0], window.min_size[1]) self.BackColor = ColorTranslator.FromHtml(window.background_color) if window.x is not None and window.y is not None: self.move(window.x, window.y) else: self.StartPosition = WinForms.FormStartPosition.CenterScreen self.AutoScaleDimensions = SizeF(96.0, 96.0) self.AutoScaleMode = WinForms.AutoScaleMode.Dpi if not window.resizable: self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle self.MaximizeBox = False # Application icon handle = windll.kernel32.GetModuleHandleW(None) icon_handle = windll.shell32.ExtractIconW(handle, sys.executable, 0) if icon_handle != 0: self.Icon = Icon.FromHandle(IntPtr.op_Explicit(Int32(icon_handle))).Clone() windll.user32.DestroyIcon(icon_handle) self.shown = window.shown self.loaded = window.loaded self.url = window.url self.text_select = window.text_select self.is_fullscreen = False if window.fullscreen: self.toggle_fullscreen() if window.frameless: self.frameless = window.frameless self.FormBorderStyle = 0 if is_cef: CEF.create_browser(window, self.Handle.ToInt32(), BrowserView.alert) elif is_edge: self.browser = BrowserView.EdgeHTML(self, window) else: self.browser = BrowserView.MSHTML(self, window) self.Shown += self.on_shown self.FormClosed += self.on_close if is_cef: self.Resize += self.on_resize if window.confirm_close: self.FormClosing += self.on_closing
def test_to_type_conversions(self): from System import Decimal, Double, Single from System import Int64, UInt64, Int32, UInt32, Int16, UInt16, Byte, SByte from System import Boolean, Char, DateTime, Object, Enum, DateTimeKind val = 1 for i in [big(val), Int32(val)]: self.assertEqual(i.ToDecimal(self.p), val) self.assertIsInstance(i.ToDecimal(self.p), Decimal) self.assertEqual(i.ToDouble(self.p), val) self.assertIsInstance(i.ToDouble(self.p), Double) self.assertEqual(i.ToSingle(self.p), val) self.assertIsInstance(i.ToSingle(self.p), Single) self.assertEqual(i.ToInt64(self.p), val) self.assertIsInstance(i.ToInt64(self.p), Int64) self.assertEqual(i.ToUInt64(self.p), val) self.assertIsInstance(i.ToUInt64(self.p), UInt64) self.assertEqual(i.ToInt32(self.p), val) self.assertIsInstance(i.ToInt32(self.p), Int32) self.assertEqual(i.ToUInt32(self.p), val) self.assertIsInstance(i.ToUInt32(self.p), UInt32) self.assertEqual(i.ToInt16(self.p), val) self.assertIsInstance(i.ToInt16(self.p), Int16) self.assertEqual(i.ToUInt16(self.p), val) self.assertIsInstance(i.ToUInt16(self.p), UInt16) self.assertEqual(i.ToByte(self.p), val) self.assertIsInstance(i.ToByte(self.p), Byte) self.assertEqual(i.ToSByte(self.p), val) self.assertIsInstance(i.ToSByte(self.p), SByte) self.assertEqual(i.ToBoolean(self.p), val) self.assertIsInstance(i.ToBoolean(self.p), Boolean) self.assertEqual(i.ToChar(self.p), Char(val)) self.assertEqual(i.ToString(self.p), str(val)) self.assertRaisesRegex(TypeError, r"Invalid cast from '\w+' to 'DateTime'", i.ToDateTime, self.p) for t in [ Decimal, Double, Single, Int64, UInt64, Int32, UInt32, Int16, UInt16, Byte, SByte, Boolean, Char, str ]: self.assertEqual(i.ToType(t, self.p), t(i)) self.assertEqual(i.ToType(Object, self.p), i) self.assertIsInstance(i.ToType(Object, self.p), Object) self.assertRaisesRegex(TypeError, r"Invalid cast from '\w+' to 'DateTime'", i.ToType, DateTime, self.p) self.assertRaisesRegex( TypeError, r"Invalid cast from '[\w.]+' to 'System.DateTimeKind'\.", i.ToType, DateTimeKind, self.p) if not is_mono: self.assertRaisesRegex( TypeError, r"Unable to cast object of type '[\w.]+' to type 'System.Enum'\.", i.ToType, Enum, self.p)
def __init__(self, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, webview_ready): self.Text = title self.ClientSize = Size(width, height) self.MinimumSize = Size(min_size[0], min_size[1]) self.BackColor = ColorTranslator.FromHtml(background_color) if not resizable: self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle self.MaximizeBox = False # Application icon handle = windll.kernel32.GetModuleHandleW(None) icon_handle = windll.shell32.ExtractIconW(handle, sys.executable, 0) if icon_handle != 0: self.Icon = Icon.FromHandle( IntPtr.op_Explicit(Int32(icon_handle))).Clone() windll.user32.DestroyIcon(icon_handle) self.webview_ready = webview_ready self.web_browser = WinForms.WebBrowser() self.web_browser.Dock = WinForms.DockStyle.Fill self.web_browser.ScriptErrorsSuppressed = True self.web_browser.IsWebBrowserContextMenuEnabled = False self.web_browser.WebBrowserShortcutsEnabled = False # HACK. Hiding the WebBrowser is needed in order to show a non-default background color. Tweaking the Visible property # results in showing a non-responsive control, until it is loaded fully. To avoid this, we need to disable this behaviour # for the default background color. if background_color != '#FFFFFF': self.web_browser.Visible = False self.first_load = True else: self.first_load = False self.cancel_back = False self.web_browser.PreviewKeyDown += self.on_preview_keydown self.web_browser.Navigating += self.on_navigating self.web_browser.DocumentCompleted += self.on_document_completed if url: self.web_browser.Navigate(url) self.Controls.Add(self.web_browser) self.is_fullscreen = False self.Shown += self.on_shown if confirm_quit: self.FormClosing += self.on_closing if fullscreen: self.toggle_fullscreen()
def testFills(self, mapper, addToCleanUp): # TODO: if we set a lower value, numpy will crash inside arr_add_docstring # I consider docstrings to be low-priority-enough that it's OK to fudge this # for now. also, fixing it would be hard ;). flagPtr = Marshal.AllocHGlobal(Marshal.SizeOf(Int32())) addToCleanUp(lambda: Marshal.FreeHGlobal(flagPtr)) mapper.RegisterData("Py_OptimizeFlag", flagPtr) self.assertEquals(CPyMarshal.ReadInt(flagPtr), 2)
def testCorrectOverloadSelection(self): """ Test correct overloading selection for common types. """ from System.Drawing import Font from System import (String, Double, Single, Int16, Int32, Int64) from System import Math substr = String("substring") self.assertTrue( substr.Substring(2) == substr.Substring.__overloads__[Int32](Int32( 2))) self.assertTrue( substr.Substring(2, 3) == substr.Substring.__overloads__[ Int32, Int32](Int32(2), Int32(3))) for atype, value1, value2 in zip([Double, Single, Int16, Int32, Int64], [1.0, 1.0, 1, 1, 1], [2.0, 0.5, 2, 0, -1]): self.assertTrue( Math.Abs(atype(value1)) == Math.Abs.__overloads__[atype](atype( value1))) self.assertTrue( Math.Abs(value1) == Math.Abs.__overloads__[atype](atype( value1))) self.assertTrue( Math.Max(atype(value1), atype(value2)) == Math.Max.__overloads__[atype, atype](atype(value1), atype(value2))) if (atype is Int64) and six.PY2: value2 = long(value2) self.assertTrue( Math.Max(atype(value1), value2) == Math.Max.__overloads__[ atype, atype](atype(value1), atype(value2))) clr.AddReference("System.Runtime.InteropServices") from System.Runtime.InteropServices import GCHandle, GCHandleType from System import Array, Byte CSArray = Array.CreateInstance(Byte, 1000) handler = GCHandle.Alloc(CSArray, GCHandleType.Pinned)
def __init__(self, uid, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, text_select, frameless, webview_ready): self.uid = uid self.Text = title self.ClientSize = Size(width, height) self.MinimumSize = Size(min_size[0], min_size[1]) self.BackColor = ColorTranslator.FromHtml(background_color) self.AutoScaleDimensions = SizeF(96.0, 96.0) self.AutoScaleMode = WinForms.AutoScaleMode.Dpi if not resizable: self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle self.MaximizeBox = False # Application icon handle = windll.kernel32.GetModuleHandleW(None) icon_handle = windll.shell32.ExtractIconW(handle, sys.executable, 0) if icon_handle != 0: self.Icon = Icon.FromHandle(IntPtr.op_Explicit(Int32(icon_handle))).Clone() windll.user32.DestroyIcon(icon_handle) self.webview_ready = webview_ready self.load_event = Event() self.background_color = background_color self.url = url self.is_fullscreen = False if fullscreen: self.toggle_fullscreen() if frameless: self.frameless = frameless self.FormBorderStyle = 0 if is_cef: CEF.create_browser(self.uid, self.Handle.ToInt32(), BrowserView.alert, url, js_api) else: self._create_mshtml_browser(url, js_api, debug) self.text_select = text_select self.Shown += self.on_shown self.FormClosed += self.on_close if is_cef: self.Resize += self.on_resize if confirm_quit: self.FormClosing += self.on_closing
def create_rows(self, quantity=1): """ Returns a list containg rows of _Pdata type. Example: rows = invoice.create_rows(2) rows[0].adk_ooi_... = "hello" rows[1].adk_ooi_... = "world" invoice.save() Args: quantity: number of rows to create """ if quantity < 1: raise ValueError("New row quantity must be 1 or higher.") _row_db_id = self.api.AdkGetRowDataId(self.data, Int32(0))[1] _nrows_field_id = self.api.AdkGetNrowsFieldId(self.data, Int32(0))[1] _rows_field_id = self.api.AdkGetRowsFieldId(self.data, Int32(0))[1] nrows = self.api.AdkGetDouble(self.data, _nrows_field_id, Double(0.0))[1] _rows = self.api.AdkCreateDataRow(_row_db_id, int(nrows) + quantity) self.api.AdkSetDouble(self.data, _nrows_field_id, Double(nrows + quantity)) self.api.AdkSetData(self.data, _rows_field_id, _rows) row_objects = [] for index in range(quantity): actual_nrows_index = nrows + index row_objects.append( _Pdata( self.api, _row_db_id, self.api.AdkGetDataRow(_rows, actual_nrows_index), parent_pdata=self, row_index=actual_nrows_index, ) ) return row_objects
def createDatasetWithCompoundType(h5file): # component name -> (offset, size, type) ht = { 'a_name': (0, 4, H5T_NATIVE_INT), 'b_name': (4, 4, H5T_NATIVE_FLOAT), 'c_name': (8, 8, H5T_NATIVE_DOUBLE) } sizeof = 0 for k in ht.keys(): sizeof += ht[k][1] dtype = H5T.create(H5T.CreateClass.COMPOUND, sizeof) for k in ht.keys(): H5T.insert(dtype, k, ht[k][0], ht[k][2]) npoints = 10 shape = Array[Int64]((npoints,)) dspace = H5S.create_simple(shape.Length, shape) dset = H5D.create(h5file, 'ArrayOfStructures', dtype, dspace) # create an array of Byte # use BitConverter to get Byte representations shape = Array[Int64]((npoints*sizeof,)) byteArray = Array.CreateInstance(Byte, shape) for i in range(npoints): offset = i*sizeof a = Int32(i) Array.Copy(BitConverter.GetBytes(a), 0, byteArray, offset+ht['a_name'][0], ht['a_name'][1]) b = Single(i*i) Array.Copy(BitConverter.GetBytes(b), 0, byteArray, offset+ht['b_name'][0], ht['b_name'][1]) c = Double(1.0/(i+1.0)) Array.Copy(BitConverter.GetBytes(c), 0, byteArray, offset+ht['c_name'][0], ht['c_name'][1]) H5D.write(dset, dtype, H5Array[Byte](byteArray)) H5S.close(dspace) H5T.close(dtype) return dset
def _fetch_getdev(self): clist = self._clean_channel_list() if self._inbuffer == None: return None #This conversion is much faster than doing # v=array(list(buf.GetDataAsVolts())) buf = self._inbuffer fullsize = buf.BufferSizeInSamples validsize = buf.ValidSamples v = np.ndarray(validsize, dtype=float) Marshal.Copy(buf.GetDataAsVolts(), 0, IntPtr.op_Explicit(Int32(v.ctypes.data)), len(v)) num_channel = len(clist) if num_channel != 1 and self.nb_samples.getcache() != 1: v.shape = (-1, num_channel) v = v.T return v
def __init__(self, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, webview_ready): self.Text = title self.ClientSize = Size(width, height) self.MinimumSize = Size(min_size[0], min_size[1]) if not resizable: self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle self.MaximizeBox = False # Application icon handle = windll.kernel32.GetModuleHandleW(None) icon_handle = windll.shell32.ExtractIconW(handle, sys.executable, 0) if icon_handle != 0: self.Icon = Icon.FromHandle( IntPtr.op_Explicit(Int32(icon_handle))).Clone() windll.user32.DestroyIcon(icon_handle) self.webview_ready = webview_ready self.web_browser = WinForms.WebBrowser() self.web_browser.Dock = WinForms.DockStyle.Fill self.web_browser.ScriptErrorsSuppressed = True self.web_browser.IsWebBrowserContextMenuEnabled = False self.cancel_back = False self.web_browser.PreviewKeyDown += self.on_preview_keydown self.web_browser.Navigating += self.on_navigating if url: self.web_browser.Navigate(url) self.Controls.Add(self.web_browser) self.is_fullscreen = False self.Shown += self.on_shown if confirm_quit: self.FormClosing += self.on_closing if fullscreen: self.toggle_fullscreen()
def convert_numpy_array_to_cnet(nparray): ''' Given a `numpy.ndarray` returns a CLR `System.Array`. See _MAP_NP_NET for the mapping of Numpy dtypes to CLR types. Note: `complex64` and `complex128` arrays are converted to `float32` and `float64` arrays respectively with shape [m,n,...] -> [m,n,...,2] Reference: https://github.com/pythonnet/pythonnet/issues/514 ''' dims = nparray.shape dtype = nparray.dtype # For complex arrays, we must make a view of the array as its corresponding # float type. if dtype == np.complex64: dtype = np.dtype('float32') dims.append(2) nparray = nparray.view(np.float32).reshape(dims) elif dtype == np.complex128: dtype = np.dtype('float64') dims.append(2) nparray = nparray.view(np.float64).reshape(dims) cnet_dims = Array.CreateInstance(Int32, nparray.ndim) for I in range(nparray.ndim): cnet_dims[I] = Int32(dims[I]) if not nparray.flags.c_contiguous: nparray = nparray.copy(order='C') assert nparray.flags.c_contiguous try: cnet_array = Array.CreateInstance(_MAP_NP_NET[dtype], cnet_dims) except KeyError: raise NotImplementedError( "asNetArray does not yet support dtype {}".format(dtype)) try: # Memmove dest_handle = GCHandle.Alloc(cnet_array, GCHandleType.Pinned) src_ptr = nparray.__array_interface__['data'][0] dest_ptr = dest_handle.AddrOfPinnedObject().ToInt64() ctypes.memmove(dest_ptr, src_ptr, nparray.nbytes) finally: if dest_handle.IsAllocated: dest_handle.Free() return cnet_array
def __init__(self, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, webview_ready): self.Text = title self.ClientSize = Size(width, height) self.MinimumSize = Size(min_size[0], min_size[1]) self.AutoScaleDimensions = SizeF(96.0, 96.0) self.AutoScaleMode = WinForms.AutoScaleMode.Dpi if not resizable: self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle self.MaximizeBox = False # Application icon try: # Try loading an icon embedded in the exe file. This will crash when frozen with PyInstaller handler = windll.kernel32.GetModuleHandleW(None) icon_handler = windll.user32.LoadIconW(handler, 1) self.Icon = Icon.FromHandle( IntPtr.op_Explicit(Int32(icon_handler))) except: pass self.webview_ready = webview_ready self.web_browser = WinForms.WebBrowser() self.web_browser.Dock = WinForms.DockStyle.Fill self.web_browser.ScriptErrorsSuppressed = True self.web_browser.IsWebBrowserContextMenuEnabled = False if url: self.web_browser.Navigate(url) self.Controls.Add(self.web_browser) self.is_fullscreen = False self.Shown += self.on_shown if confirm_quit: self.FormClosing += self.on_closing if fullscreen: self.toggle_fullscreen()
def test_char_new(self): from System import Char, Int32, UInt16 self.assertEqual(Char(), '\x00') self.assertEqual(Char('a'), 'a') self.assertEqual(Char(ord('A')), 'A') self.assertEqual(Char(chr(65)), 'A') self.assertEqual(Char(UInt16(65)), 'A') self.assertEqual(Char(Int32(65)), 'A') self.assertEqual(Char(big(65)), 'A') self.assertEqual(Char('€'), '€') self.assertIsInstance(Char(), Char) self.assertIsInstance(Char('a'), Char) self.assertIsInstance(Char(65), Char) self.assertRaises(TypeError, Char, 'a', 'b') self.assertRaises( TypeError, Char, 'ab', ) self.assertRaises(TypeError, Char, '🐍') # surrogate pair self.assertRaises(TypeError, Char, '\U0001F40D') # surrogate pair self.assertEqual(Char('🐍'[0]), '\uD83D') # high surrogate self.assertRaises(TypeError, Char.__new__, str) self.assertRaises(TypeError, Char.__new__, str, 'a') self.assertRaises(TypeError, Char.__new__, str, 65) self.assertRaises(TypeError, Char.__new__, int) self.assertRaises(TypeError, Char.__new__, int, 'a') self.assertRaises(TypeError, Char.__new__, int, 65) # ValueError would be OK too self.assertRaises(OverflowError, Char, -1) self.assertRaises(OverflowError, Char, 0x110000) self.assertRaises(OverflowError, Char, 0x10000)
def testClasses(self): from System.Collections import Hashtable from Python.Test import StringDelegate from System import Int32 self.notify("Running class leak check...") for i in xrange(self.count): if i == 10: self.start_test() # Reference type x = Hashtable() del x # Value type x = Int32(99) del x # Delegate type x = StringDelegate(hello) del x self.end_test()
from AntPlus.Profiles.Components import DataPage from AntPlus.Profiles.BikePower import BikePowerDisplay, SetCustomCalibrationParameterPage from AntPlus.Types import BindableByteArray from System import Array, Byte, BitConverter, Int32 from System.Collections.Generic import List import System def stopScript(): simulator.TurnOff() simulator.TurnOn() page = SetCustomCalibrationParameterPage() # byte 0 # 1 = SCALE # 2 = ? byte_0 = Byte(1) # bytes 1-4 : values (little endian 32 bits int) bytes_value = BitConverter.GetBytes(Int32(-2300)) # byte 5 : reserved future use byte_5 = Byte(0) x = List[Byte]([byte_0] + [Byte(b) for b in bytes_value] + [byte_5]) array = BindableByteArray(x) # page.Encode(array) page.ManufacturerSpecificData = array simulator.SendSetCustomCalibrationParameterPage(page)
def __init__(self, uid, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, text_select, webview_ready): self.uid = uid self.Text = title self.ClientSize = Size(width, height) self.MinimumSize = Size(min_size[0], min_size[1]) self.BackColor = ColorTranslator.FromHtml(background_color) self.AutoScaleDimensions = SizeF(96.0, 96.0) self.AutoScaleMode = WinForms.AutoScaleMode.Dpi if not resizable: self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle self.MaximizeBox = False # Application icon handle = windll.kernel32.GetModuleHandleW(None) icon_handle = windll.shell32.ExtractIconW(handle, sys.executable, 0) if icon_handle != 0: self.Icon = Icon.FromHandle( IntPtr.op_Explicit(Int32(icon_handle))).Clone() windll.user32.DestroyIcon(icon_handle) self.webview_ready = webview_ready self.load_event = Event() self.web_browser = WebBrowserEx() self.web_browser.Dock = WinForms.DockStyle.Fill self.web_browser.ScriptErrorsSuppressed = not debug self.web_browser.IsWebBrowserContextMenuEnabled = debug self.web_browser.WebBrowserShortcutsEnabled = False self.web_browser.DpiAware = True self.web_browser.ScriptErrorsSuppressed = not debug self.web_browser.IsWebBrowserContextMenuEnabled = debug self.js_result_semaphore = Semaphore(0) self.js_bridge = BrowserView.JSBridge() self.js_bridge.parent_uid = uid self.web_browser.ObjectForScripting = self.js_bridge self.text_select = text_select if js_api: self.js_bridge.api = js_api # HACK. Hiding the WebBrowser is needed in order to show a non-default background color. Tweaking the Visible property # results in showing a non-responsive control, until it is loaded fully. To avoid this, we need to disable this behaviour # for the default background color. if background_color != '#FFFFFF': self.web_browser.Visible = False self.first_load = True else: self.first_load = False self.cancel_back = False self.web_browser.PreviewKeyDown += self.on_preview_keydown self.web_browser.Navigating += self.on_navigating self.web_browser.NewWindow3 += self.on_new_window self.web_browser.DownloadComplete += self.on_download_complete self.web_browser.DocumentCompleted += self.on_document_completed if url: self.web_browser.Navigate(url) else: self.web_browser.DocumentText = default_html self.url = url self.Controls.Add(self.web_browser) self.is_fullscreen = False self.Shown += self.on_shown self.FormClosed += self.on_close if confirm_quit: self.FormClosing += self.on_closing if fullscreen: self.toggle_fullscreen()
#=============================================================================== import System from System import Array, Int32, Int64 #=============================================================================== print '\nInitializing HDF5 library\n' status = H5.Open() shape = Array[Int64]((5, 6)) data = Array.CreateInstance(Int32, shape) for row in range(0, shape[0]): for col in range(0, shape[1]): data[row,col] = Int32(row+col) h5file = H5F.create('SDS.h5', H5F.CreateMode.ACC_TRUNC) dspace = H5S.create_simple(shape.Length, shape) dtype = H5T.copy(H5T.H5Type.NATIVE_INT) status = H5T.setOrder(dtype, H5T.Order.LE) dset = H5D.create(h5file, 'IntArray', dtype, dspace) dtype = H5T.copy(H5T.H5Type.NATIVE_INT) status = H5D.write(dset, dtype, H5Array[Int32](data)) H5D.close(dset) H5T.close(dtype)
def __init__(self, window): self.uid = window.uid self.pywebview_window = window self.real_url = None self.Text = window.title self.Size = Size(window.initial_width, window.initial_height) self.MinimumSize = Size(window.min_size[0], window.min_size[1]) if window.transparent: # window transparency is not supported, as webviews are not transparent. self.BackColor = Color.LimeGreen self.TransparencyKey = Color.LimeGreen self.SetStyle( WinForms.ControlStyles.SupportsTransparentBackColor, True) else: self.BackColor = ColorTranslator.FromHtml( window.background_color) if window.initial_x is not None and window.initial_y is not None: self.move(window.initial_x, window.initial_y) else: self.StartPosition = WinForms.FormStartPosition.CenterScreen self.AutoScaleDimensions = SizeF(96.0, 96.0) self.AutoScaleMode = WinForms.AutoScaleMode.Dpi if not window.resizable: self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle self.MaximizeBox = False if window.minimized: self.WindowState = WinForms.FormWindowState.Minimized # Application icon handle = kernel32.GetModuleHandleW(None) icon_handle = windll.shell32.ExtractIconW(handle, sys.executable, 0) if icon_handle != 0: self.Icon = Icon.FromHandle( IntPtr.op_Explicit(Int32(icon_handle))).Clone() windll.user32.DestroyIcon(icon_handle) self.closed = window.closed self.closing = window.closing self.shown = window.shown self.loaded = window.loaded self.url = window.real_url self.text_select = window.text_select self.on_top = window.on_top self.is_fullscreen = False if window.fullscreen: self.toggle_fullscreen() if window.frameless: self.frameless = window.frameless self.FormBorderStyle = 0 if is_cef: CEF.create_browser(window, self.Handle.ToInt32(), BrowserView.alert) elif is_chromium: self.browser = Chromium.EdgeChrome(self, window) elif is_edge: self.browser = Edge.EdgeHTML(self, window) else: self.browser = IE.MSHTML(self, window) self.Shown += self.on_shown self.FormClosed += self.on_close self.FormClosing += self.on_closing if is_cef: self.Resize += self.on_resize
def ptr(offset: int): return IntPtr.op_Explicit(Int32(offset))
def onOpened(s, e): global menuItem menuItem.Items.Clear() config = None directory = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Assembly.GetEntryAssembly().GetName().Name) if Directory.Exists(directory): fileName1 = Path.GetFileName(Assembly.GetEntryAssembly().Location) for fileName2 in Directory.EnumerateFiles(directory, "*.config"): if fileName1.Equals(Path.GetFileNameWithoutExtension(fileName2)): exeConfigurationFileMap = ExeConfigurationFileMap() exeConfigurationFileMap.ExeConfigFilename = fileName2 config = ConfigurationManager.OpenMappedExeConfiguration( exeConfigurationFileMap, ConfigurationUserLevel.None) if config is None: config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None) directory = None if config.AppSettings.Settings["ActivateThreshold"] is not None: threshold = Int64.Parse( config.AppSettings.Settings["ActivateThreshold"].Value) childMenuItem = MenuItem() if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): childMenuItem.Header = "トーク間隔" else: childMenuItem.Header = "Talking Interval" menuItem.Items.Add(childMenuItem) intervalMenuItem1 = MenuItem() if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): intervalMenuItem1.Header = "15秒" else: intervalMenuItem1.Header = "15 seconds" if threshold == 150000000: intervalMenuItem1.IsChecked = True def onIntervalClick1(sender, args): config.AppSettings.Settings[ "ActivateThreshold"].Value = "150000000" config.Save(ConfigurationSaveMode.Modified) intervalMenuItem1.Click += onIntervalClick1 childMenuItem.Items.Add(intervalMenuItem1) intervalMenuItem2 = MenuItem() if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): intervalMenuItem2.Header = "30秒" else: intervalMenuItem2.Header = "30 seconds" if threshold == 300000000: intervalMenuItem2.IsChecked = True def onIntervalClick2(sender, args): config.AppSettings.Settings[ "ActivateThreshold"].Value = "300000000" config.Save(ConfigurationSaveMode.Modified) intervalMenuItem2.Click += onIntervalClick2 childMenuItem.Items.Add(intervalMenuItem2) intervalMenuItem3 = MenuItem() if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): intervalMenuItem3.Header = "1分" else: intervalMenuItem3.Header = "1 minute" if threshold == 600000000: intervalMenuItem3.IsChecked = True def onIntervalClick3(sender, args): config.AppSettings.Settings[ "ActivateThreshold"].Value = "600000000" config.Save(ConfigurationSaveMode.Modified) intervalMenuItem3.Click += onIntervalClick3 childMenuItem.Items.Add(intervalMenuItem3) intervalMenuItem4 = MenuItem() if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): intervalMenuItem4.Header = "2分" else: intervalMenuItem4.Header = "2 minutes" if threshold == 1200000000: intervalMenuItem4.IsChecked = True def onIntervalClick4(sender, args): config.AppSettings.Settings[ "ActivateThreshold"].Value = "1200000000" config.Save(ConfigurationSaveMode.Modified) intervalMenuItem4.Click += onIntervalClick4 childMenuItem.Items.Add(intervalMenuItem4) intervalMenuItem5 = MenuItem() if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): intervalMenuItem5.Header = "3分" else: intervalMenuItem5.Header = "3 minutes" if threshold == 1800000000: intervalMenuItem5.IsChecked = True def onIntervalClick5(sender, args): config.AppSettings.Settings[ "ActivateThreshold"].Value = "1800000000" config.Save(ConfigurationSaveMode.Modified) intervalMenuItem5.Click += onIntervalClick5 childMenuItem.Items.Add(intervalMenuItem5) childMenuItem = MenuItem() if CultureInfo.CurrentCulture.Equals(CultureInfo.GetCultureInfo("ja-JP")): childMenuItem.Header = "テーマ" else: childMenuItem.Header = "Theme" menuItem.Items.Add(Separator()) menuItem.Items.Add(childMenuItem) menuItem1 = MenuItem() menuItem2 = MenuItem() menuItem3 = MenuItem() menuItem4 = MenuItem() menuItem5 = MenuItem() menuItem6 = MenuItem() menuItem7 = MenuItem() menuItem8 = MenuItem() menuItem9 = MenuItem() menuItem10 = MenuItem() if CultureInfo.CurrentCulture.Equals(CultureInfo.GetCultureInfo("ja-JP")): menuItem1.Header = "ブループリント" menuItem2.Header = "ドット" menuItem3.Header = "布" menuItem4.Header = "リネン" menuItem5.Header = "ノイズ1" menuItem6.Header = "ノイズ2" menuItem7.Header = "紙" menuItem8.Header = "ペンタゴン" menuItem9.Header = "雪" menuItem10.Header = "ストライプ" else: menuItem1.Header = "Blueprint" menuItem2.Header = "Dots" menuItem3.Header = "Fabric" menuItem4.Header = "Linen" menuItem5.Header = "Noise 1" menuItem6.Header = "Noise 2" menuItem7.Header = "Paper" menuItem8.Header = "Pentagon" menuItem9.Header = "Snow" menuItem10.Header = "Stripes" if config.AppSettings.Settings[ "BackgroundColor"] is not None and config.AppSettings.Settings[ "BackgroundImage"] is not None and config.AppSettings.Settings[ "TextColor"] is not None and config.AppSettings.Settings[ "LinkColor"]: backColor = config.AppSettings.Settings["BackgroundColor"].Value backImage = config.AppSettings.Settings["BackgroundImage"].Value textColor = config.AppSettings.Settings["TextColor"].Value linkColor = config.AppSettings.Settings["LinkColor"].Value if backColor.Equals("#FF2574B0") and backImage.Equals( "Assets\\Background-Blueprint.png") and textColor.Equals( "#FFFFFFFF") and linkColor.Equals("#FFFEEC27"): menuItem1.IsChecked = True def onClick1(sender, args): config.AppSettings.Settings["BackgroundColor"].Value = "#FF2574B0" config.AppSettings.Settings[ "BackgroundImage"].Value = "Assets\\Background-Blueprint.png" config.AppSettings.Settings["TextColor"].Value = "#FFFFFFFF" config.AppSettings.Settings["LinkColor"].Value = "#FFFEEC27" config.Save(ConfigurationSaveMode.Modified) menuItem1.Click += onClick1 if backColor.Equals("#FF252525") and backImage.Equals( "Assets\\Background-Dots.png") and textColor.Equals( "#FFFFFFFF") and linkColor.Equals("#FF00C0FF"): menuItem2.IsChecked = True def onClick2(sender, args): config.AppSettings.Settings["BackgroundColor"].Value = "#FF252525" config.AppSettings.Settings[ "BackgroundImage"].Value = "Assets\\Background-Dots.png" config.AppSettings.Settings["TextColor"].Value = "#FFFFFFFF" config.AppSettings.Settings["LinkColor"].Value = "#FF00C0FF" config.Save(ConfigurationSaveMode.Modified) menuItem2.Click += onClick2 if backColor.Equals("#FFEAEAEA") and backImage.Equals( "Assets\\Background-Fabric.png") and textColor.Equals( "#FF000000") and linkColor.Equals("#FFFF0066"): menuItem3.IsChecked = True def onClick3(sender, args): config.AppSettings.Settings["BackgroundColor"].Value = "#FFEAEAEA" config.AppSettings.Settings[ "BackgroundImage"].Value = "Assets\\Background-Fabric.png" config.AppSettings.Settings["TextColor"].Value = "#FF000000" config.AppSettings.Settings["LinkColor"].Value = "#FFFF0066" config.Save(ConfigurationSaveMode.Modified) menuItem3.Click += onClick3 if backColor.Equals("#FF252525") and backImage.Equals( "Assets\\Background-Linen.png") and textColor.Equals( "#FFFFFFFF") and linkColor.Equals("#FFFF6600"): menuItem4.IsChecked = True def onClick4(sender, args): config.AppSettings.Settings["BackgroundColor"].Value = "#FF252525" config.AppSettings.Settings[ "BackgroundImage"].Value = "Assets\\Background-Linen.png" config.AppSettings.Settings["TextColor"].Value = "#FFFFFFFF" config.AppSettings.Settings["LinkColor"].Value = "#FFFF6600" config.Save(ConfigurationSaveMode.Modified) menuItem4.Click += onClick4 if backColor.Equals("#FFF2F2F2") and backImage.Equals( "Assets\\Background-Noise1.png") and textColor.Equals( "#FF333333") and linkColor.Equals("#FFFF0066"): menuItem5.IsChecked = True def onClick5(sender, args): config.AppSettings.Settings["BackgroundColor"].Value = "#FFF2F2F2" config.AppSettings.Settings[ "BackgroundImage"].Value = "Assets\\Background-Noise1.png" config.AppSettings.Settings["TextColor"].Value = "#FF333333" config.AppSettings.Settings["LinkColor"].Value = "#FFFF0066" config.Save(ConfigurationSaveMode.Modified) menuItem5.Click += onClick5 if backColor.Equals("#FF262727") and backImage.Equals( "Assets\\Background-Noise2.png") and textColor.Equals( "#FFFFFFFF") and linkColor.Equals("#FFFF6600"): menuItem6.IsChecked = True def onClick6(sender, args): config.AppSettings.Settings["BackgroundColor"].Value = "#FF262727" config.AppSettings.Settings[ "BackgroundImage"].Value = "Assets\\Background-Noise2.png" config.AppSettings.Settings["TextColor"].Value = "#FFFFFFFF" config.AppSettings.Settings["LinkColor"].Value = "#FFFF6600" config.Save(ConfigurationSaveMode.Modified) menuItem6.Click += onClick6 if backColor.Equals("#FFFCFCFC") and backImage.Equals( "Assets\\Background-Paper.png") and textColor.Equals( "#FF000000") and linkColor.Equals("#FFFF0099"): menuItem7.IsChecked = True def onClick7(sender, args): config.AppSettings.Settings["BackgroundColor"].Value = "#FFFCFCFC" config.AppSettings.Settings[ "BackgroundImage"].Value = "Assets\\Background-Paper.png" config.AppSettings.Settings["TextColor"].Value = "#FF000000" config.AppSettings.Settings["LinkColor"].Value = "#FFFF0099" config.Save(ConfigurationSaveMode.Modified) menuItem7.Click += onClick7 if backColor.Equals("#FFEEEEEE") and backImage.Equals( "Assets\\Background-Pentagon.png") and textColor.Equals( "#FF333333") and linkColor.Equals("#FF00A0E9"): menuItem8.IsChecked = True def onClick8(sender, args): config.AppSettings.Settings["BackgroundColor"].Value = "#FFEEEEEE" config.AppSettings.Settings[ "BackgroundImage"].Value = "Assets\\Background-Pentagon.png" config.AppSettings.Settings["TextColor"].Value = "#FF333333" config.AppSettings.Settings["LinkColor"].Value = "#FF00A0E9" config.Save(ConfigurationSaveMode.Modified) menuItem8.Click += onClick8 if backColor.Equals("#FFFBFBFB") and backImage.Equals( "Assets\\Background-Snow.png") and textColor.Equals( "#FF000000") and linkColor.Equals("#FF00A0E9"): menuItem9.IsChecked = True def onClick9(sender, args): config.AppSettings.Settings["BackgroundColor"].Value = "#FFFBFBFB" config.AppSettings.Settings[ "BackgroundImage"].Value = "Assets\\Background-Snow.png" config.AppSettings.Settings["TextColor"].Value = "#FF000000" config.AppSettings.Settings["LinkColor"].Value = "#FF00A0E9" config.Save(ConfigurationSaveMode.Modified) menuItem9.Click += onClick9 if backColor.Equals("#FF39343D") and backImage.Equals( "Assets\\Background-Stripes.png") and textColor.Equals( "#FFFFFFFF") and linkColor.Equals("#FFFF6600"): menuItem10.IsChecked = True def onClick10(sender, args): config.AppSettings.Settings["BackgroundColor"].Value = "#FF39343D" config.AppSettings.Settings[ "BackgroundImage"].Value = "Assets\\Background-Stripes.png" config.AppSettings.Settings["TextColor"].Value = "#FFFFFFFF" config.AppSettings.Settings["LinkColor"].Value = "#FFFF6600" config.Save(ConfigurationSaveMode.Modified) menuItem10.Click += onClick10 childMenuItem.Items.Add(menuItem1) childMenuItem.Items.Add(menuItem2) childMenuItem.Items.Add(menuItem3) childMenuItem.Items.Add(menuItem4) childMenuItem.Items.Add(menuItem5) childMenuItem.Items.Add(menuItem6) childMenuItem.Items.Add(menuItem7) childMenuItem.Items.Add(menuItem8) childMenuItem.Items.Add(menuItem9) childMenuItem.Items.Add(menuItem10) if config.AppSettings.Settings["DropShadow"] is not None: dropShadow = Boolean.Parse( config.AppSettings.Settings["DropShadow"].Value) childMenuItem = MenuItem() childMenuItem.IsCheckable = True childMenuItem.IsChecked = dropShadow if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): childMenuItem.Header = "ドロップシャドウを有効にする" else: childMenuItem.Header = "Enable Drop Shadow" def onClick(sender, args): config.AppSettings.Settings[ "DropShadow"].Value = sender.IsChecked.ToString() config.Save(ConfigurationSaveMode.Modified) childMenuItem.Click += onClick menuItem.Items.Add(Separator()) menuItem.Items.Add(childMenuItem) menuItem.Items.Add(Separator()) if config.AppSettings.Settings["FontFamily"] is not None: fontFamilyName = config.AppSettings.Settings["FontFamily"].Value childMenuItem = MenuItem() if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): childMenuItem.Header = "フォント" else: childMenuItem.Header = "Font" menuItem.Items.Add(childMenuItem) for fontFamily in [ "Arial", "Calibri", "Cambria", "Candara", "Constantia", "Corbel", "Courier New", "Geogia", "MS UI Gothic", "Segoe UI", "Tahoma", "Times New Roman", "Verdana", "メイリオ", "MS ゴシック" ]: fontMenuItem = MenuItem() fontMenuItem.Header = fontFamily if fontFamily.Equals(fontFamilyName): fontMenuItem.IsChecked = True def onClick(sender, args): config.AppSettings.Settings["FontFamily"].Value = sender.Header config.Save(ConfigurationSaveMode.Modified) fontMenuItem.Click += onClick childMenuItem.Items.Add(fontMenuItem) if config.AppSettings.Settings["FontSize"] is not None: fontSize = config.AppSettings.Settings["FontSize"].Value fontSizeConverter = FontSizeConverter() childMenuItem = MenuItem() if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): childMenuItem.Header = "フォントサイズ" else: childMenuItem.Header = "Font Size" menuItem.Items.Add(childMenuItem) for size in [ "8pt", "9pt", "10pt", "11pt", "12pt", "14pt", "16pt", "18pt", "20pt", "22pt", "24pt" ]: fontMenuItem = MenuItem() fontMenuItem.Header = size if fontSize.Equals(size): fontMenuItem.IsChecked = True def onClick(sender, args): config.AppSettings.Settings["FontSize"].Value = sender.Header config.Save(ConfigurationSaveMode.Modified) fontMenuItem.Click += onClick childMenuItem.Items.Add(fontMenuItem) if config.AppSettings.Settings["LineHeight"] is not None: lineHeight = Double.Parse( config.AppSettings.Settings["LineHeight"].Value) maxLineHeight = Convert.ToInt32( fontSizeConverter.ConvertFromString(fontSize)) * 2 if maxLineHeight < lineHeight: maxLineHeight = lineHeight childMenuItem2 = MenuItem() if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): childMenuItem2.Header = "行間" else: childMenuItem2.Header = "Line Height" menuItem.Items.Add(childMenuItem2) for i in range( Convert.ToInt32( fontSizeConverter.ConvertFromString(fontSize)), Convert.ToInt32(maxLineHeight) + 1): lineHeightMenuItem = MenuItem() lineHeightMenuItem.Header = i.ToString() if lineHeight == i: lineHeightMenuItem.IsChecked = True def onClick(sender, args): config.AppSettings.Settings[ "LineHeight"].Value = sender.Header config.Save(ConfigurationSaveMode.Modified) lineHeightMenuItem.Click += onClick childMenuItem2.Items.Add(lineHeightMenuItem) if config.AppSettings.Settings["FrameRate"] is not None: frameRate = Double.Parse( config.AppSettings.Settings["FrameRate"].Value) childMenuItem = MenuItem() if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): childMenuItem.Header = "フレームレート" else: childMenuItem.Header = "Frame Rate" menuItem.Items.Add(Separator()) menuItem.Items.Add(childMenuItem) for i in [24, 30, 60]: frameRateMenuItem = MenuItem() frameRateMenuItem.Header = i.ToString() if frameRate == Convert.ToDouble(i): frameRateMenuItem.IsChecked = True def onClick(sender, args): config.AppSettings.Settings["FrameRate"].Value = sender.Header config.Save(ConfigurationSaveMode.Modified) frameRateMenuItem.Click += onClick childMenuItem.Items.Add(frameRateMenuItem) if config.AppSettings.Settings["Subscriptions"] is not None: path = config.AppSettings.Settings["Subscriptions"].Value childMenuItem = MenuItem() if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): childMenuItem.Header = "フィード" else: childMenuItem.Header = "Subscriptions" menuItem.Items.Add(Separator()) menuItem.Items.Add(childMenuItem) editMenuItem = MenuItem() editMenuItem.Tag = path def onEdit(sender, args): global program path = sender.Tag def onStart(state): Process.Start(state) psi = ProcessStartInfo() if String.IsNullOrEmpty(program): psi.FileName = path else: psi.FileName = program psi.Arguments = path Task.Factory.StartNew(onStart, psi) editMenuItem.Click += onEdit if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): editMenuItem.Header = "フィードの編集..." else: editMenuItem.Header = "Edit..." childMenuItem.Items.Add(editMenuItem) childMenuItem.Items.Add(Separator()) if directory is not None: fileName = Path.Combine(directory, path) if File.Exists(fileName): path = fileName def parseOutline(m, n): if not n.HasChildNodes: return None for xmlNode in n.ChildNodes: if xmlNode.Name.Equals("outline"): text = None xmlUrl = None htmlUrl = None for xmlAttribute in xmlNode.Attributes: if xmlAttribute.Name.Equals( "title") or xmlAttribute.Name.Equals("text"): text = xmlAttribute.Value elif xmlAttribute.Name.Equals("xmlUrl"): xmlUrl = xmlAttribute.Value elif xmlAttribute.Name.Equals("htmlUrl"): htmlUrl = xmlAttribute.Value if not String.IsNullOrEmpty(text): if String.IsNullOrEmpty(xmlUrl): mi = MenuItem() mi.Header = text parsedMenuItem = parseOutline(mi, xmlNode) if parsedMenuItem is None: m.Items.Add(mi) else: m.Items.Add(parsedMenuItem) elif not String.IsNullOrEmpty(xmlUrl): mi = MenuItem() def onClick(sender, args): if not String.IsNullOrEmpty(sender.Tag): def onStart(state): Process.Start(state) Task.Factory.StartNew(onStart, sender.Tag) mi.Header = text mi.Click += onClick mi.Tag = htmlUrl m.Items.Add(mi) return m doc = XmlDocument() doc.Load(path) for xmlNode in doc.SelectNodes("/opml/body"): parseOutline(childMenuItem, xmlNode) if config.AppSettings.Settings["Timeout"] is not None: timeout = Int32.Parse(config.AppSettings.Settings["Timeout"].Value) childMenuItem = MenuItem() if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): childMenuItem.Header = "タイムアウト" else: childMenuItem.Header = "Timeout" menuItem.Items.Add(Separator()) menuItem.Items.Add(childMenuItem) for i in [15000, 30000, 60000, 120000, 180000]: timeMenuItem = MenuItem() timeMenuItem.Header = i.ToString() if timeout == i: timeMenuItem.IsChecked = True def onClick(sender, args): config.AppSettings.Settings["Timeout"].Value = sender.Header config.Save(ConfigurationSaveMode.Modified) timeMenuItem.Click += onClick childMenuItem.Items.Add(timeMenuItem) if config.AppSettings.Settings["Cache"] is not None: path = config.AppSettings.Settings["Cache"].Value if directory is not None: path = Path.Combine(directory, path) childMenuItem = MenuItem() childMenuItem.Tag = path if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): childMenuItem.Header = "キャッシュをクリア" else: childMenuItem.Header = "Clear Cache" def onClick(sender, args): if Directory.Exists(childMenuItem.Tag): for fileName in Directory.EnumerateFiles(childMenuItem.Tag): File.Delete(fileName) childMenuItem.Click += onClick menuItem.Items.Add(Separator()) menuItem.Items.Add(childMenuItem) childMenuItem = MenuItem() if CultureInfo.CurrentCulture.Equals(CultureInfo.GetCultureInfo("ja-JP")): childMenuItem.Header = "GCを強制的に実行" else: childMenuItem.Header = "Force Garbage Collection" def onClick(sender, args): GC.Collect() childMenuItem.Click += onClick menuItem.Items.Add(childMenuItem)
import sys if sys.platform != 'cli': raise ImportError( "If you're running CPython, you don't need ironclad. If you're running Jython, ironclad won't work." ) import os _dirname = os.path.dirname(__file__) import clr from System import GC, Int32, IntPtr from System.Reflection import Assembly from System.Runtime.InteropServices import Marshal if Marshal.SizeOf(Int32()) != Marshal.SizeOf(IntPtr()): raise ImportError("Ironclad is currently 32-bit only") clr.AddReference(Assembly.LoadFile(os.path.join(_dirname, "ironclad.dll"))) from Ironclad import CPyMarshal, PythonMapper from Ironclad.Structs import PyObject, PyVarObject, PyTypeObject _mapper = PythonMapper(os.path.join(_dirname, "python27.dll")) def gcwait(): """ Attempt to force a garbage collection, and wait for pending finalizers. If you think you need to call this function, you're probably wrong. """ for _ in range(4):