def writeGroupAndDatasets(h5file): grp = H5G.create(h5file, 'A') dtype = H5T.copy(H5T_NATIVE_FLOAT) shape = Array[Int64]((2, 6)) dspacev = H5S.create_simple(shape.Length, shape) dsetv = H5D.create(h5file, 'B', dtype, dspacev) H5T.close(dtype) dtype = H5T.copy(H5T_STD_REF_OBJ) shape = Array[Int64]((2, )) dspacer = H5S.create_simple(shape.Length, shape) dsetr = H5D.create(h5file, 'R', dtype, dspacer) oref = Array.CreateInstance(ObjectReference, 2) oref[0] = H5R.createObjectReference(h5file, 'A') oref[1] = H5R.createObjectReference(h5file, 'B') nBytes = ObjectReference.SizeInBytes data = Array.CreateInstance(Byte, oref.Length * nBytes) for i in range(oref.Length): Array.Copy(oref[i].ToByteArray(), 0, data, i * nBytes, nBytes) H5D.write(dsetr, dtype, H5Array[Byte](data)) H5T.close(dtype) H5D.close(dsetv) H5S.close(dspacev) H5D.close(dsetr) H5S.close(dspacer) return None
def rhSingleSpanNurbsCurveToCurve(rhCurve): #get control points ptArray, weights, knots = [], [], [] rhControlPoints = rhCurve.Points for rhPoint in rhControlPoints: dsPoint = rhPointToPoint(rhPoint) ptArray.append(dsPoint) #get weights for each point weights.append(rhPoint.Weight) #convert Python list to IEnumerable[] ptArray = List[Point](ptArray) weights = Array[float](weights) #get degree of the curve degree = rhCurve.Degree #get knots of the curve rhKnots = rhCurve.Knots for i in rhKnots: knots.append(i) knots.insert(0, knots[0]) knots.insert(len(knots), knots[(len(knots) - 1)]) knots = Array[float](knots) #create ds curve from points, weights and knots dsNurbsCurve = NurbsCurve.ByControlPointsWeightsKnots( ptArray, weights, knots, degree) ptArray.Clear() Array.Clear(weights, 0, len(weights)) Array.Clear(knots, 0, len(knots)) return dsNurbsCurve
def rhMultiSpanNurbsCurveToCurve(rhCurve): dsNurbsCurve, rhSubCurve = [], [] spanCount = rhCurve.SpanCount for i in range(0, spanCount, 1): rhCurveSubdomain = rhCurve.SpanDomain(i) rhSubCurve.append(rhCurve.ToNurbsCurve(rhCurveSubdomain)) for curve in rhSubCurve: #get control points ptArray, weights, knots = [], [], [] rhControlPoints = curve.Points for rhPoint in rhControlPoints: dsPoint = rhPointToPoint(rhPoint) ptArray.append(dsPoint) #get weights for each point weights.append(rhPoint.Weight) #convert Python list to IEnumerable[] ptArray = List[Point](ptArray) weights = Array[float](weights) #get degree of the curve degree = curve.Degree #get knots of the curve rhKnots = curve.Knots for i in rhKnots: knots.append(i) knots.insert(0, knots[0]) knots.insert(len(knots), knots[(len(knots)-1)]) knots = Array[float](knots) #create ds curve from points, weights and knots dsNurbsCurve.append(NurbsCurve.ByControlPointsWeightsKnots(ptArray, weights, knots, degree)) ptArray.Clear() Array.Clear(weights, 0, len(weights)) Array.Clear(knots, 0, len(knots)) return dsNurbsCurve del dsNurbsCurve[:]
def encode_job(self, job): random_bytes = Array.CreateInstance(Byte, 2) Random().NextBytes(random_bytes) data = Encoding.UTF8.GetBytes(JavaScriptSerializer().Serialize(job)) with MemoryStream(data.Length) as initialStream: initialStream.Write(data, 0, data.Length) initialStream.Seek(0, SeekOrigin.Begin) with MemoryStream() as resultStream: with GZipStream(resultStream, CompressionMode.Compress) as zipStream: buffer = Array.CreateInstance(Byte, 4096) bytesRead = initialStream.Read(buffer, 0, buffer.Length) zipStream.Write(buffer, 0, bytesRead) while bytesRead != 0: bytesRead = initialStream.Read(buffer, 0, buffer.Length) zipStream.Write(buffer, 0, bytesRead) result = resultStream.ToArray() result[:2] = random_bytes return { Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring( 0, 8): Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "data": Convert.ToBase64String(result) }
def __init__(self, line, restLength, stiffness): self.PPos = Array[rc.Geometry.Point3d]((line.From, line.To)) self.Move = Array.CreateInstance(rc.Geometry.Vector3d, 2) self.Weighting = Array.CreateInstance(Double, 2) self.RestLength = restLength self.Stiffness = stiffness
def send_waveform(self, waveform, channel): ''' Sends a complete waveform. All parameters need to be specified. Input: waveform (float[numpoints]) : waveform channel (int) : 1 to 4, the number of the designated channel Output: None ''' logging.debug(__name__ + ' : Sending waveform to instrument') wfs = Array.CreateInstance(WaveformStruct, 1) data = Array.CreateInstance(Double, len(waveform)) ctr = 0 for d in waveform: data.SetValue(float(d), ctr) ctr = ctr + 1 # Done because Python assumes all variables are references x = wfs.GetValue(0) x.Sample = data markerarr = Array.CreateInstance(Double, 1) markerarr.SetValue(0, 0) x.Marker = markerarr wfs.SetValue(x, 0) if (self._device != None): oChannel = ARBChannel() oChannel = self._device.GetChannel(channel - 1) res = oChannel.LoadWaveforms(wfs) if (res.ErrorSource != 0): return False seq = Array.CreateInstance(GenerationSequenceStruct, 1) # Done because Python assumes all variables are references x = seq.GetValue(0) x.WaveformIndex = 0 x.Repetitions = 1 seq.SetValue(x, 0) res = oChannel.LoadGenerationSequence( seq, TransferMode.NonReEntrant, True) # Hack to force true boolean type passing if (res.ErrorSource != 0): return False return True else: logging.debug(__name__ + ' : Could not get channel %s' % channel) print "Error getting channel!" return False
def setupDfs0(): global shePath global dfs global dfsDataX global dfsDataY global nX global nY global nZ import clr global simStart global simStart now = MShePy.wm.currentTime() clr.AddReference("DHI.Mike.Install, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c513450b5d0bf0bf") # "fully qualified" name required! from DHI.Mike.Install import MikeImport, MikeProducts MikeImport.SetupLatest() clr.AddReference("DHI.Generic.MikeZero.DFS") clr.AddReference("DHI.Generic.MikeZero.EUM") clr.AddReference("System") import System from System import Array from DHI.Generic.MikeZero import eumUnit, eumItem, eumQuantity from DHI.Generic.MikeZero.DFS import DfsFactory, DfsBuilder, DfsSimpleType, DataValueType shePath = MShePy.wm.getSheFilePath() sheDir = os.path.dirname(shePath) filename = os.path.join(sheDir, 'BndFluxes.dfs2') builder = DfsBuilder.Create(filename, "MSHE SZ boundary fluxes output per layer", 0) builder.SetDataType(1) factory = DfsFactory() builder.SetGeographicalProjection(factory.CreateProjectionGeoOrigin("NON-UTM", 0, 0, 0)) simStart = now nowSys = System.DateTime(now.year, now.month, now.day, now.hour, now.minute, now.second) # note: time unit given here has to be used in WriteItemTimeStepNext axis = factory.CreateTemporalNonEqCalendarAxis(eumUnit.eumUsec, nowSys) builder.SetTemporalAxis(axis) builder.DeleteValueFloat = -1e-30 (startTime, endTime, values) = MShePy.wm.getValues(MShePy.paramTypes.SZ_X_FLO) # just for the geometry (nX, nY, nZ) = values.shape() (x0, y0) = MShePy.wm.gridCellToCoord(0, 0) (x1, y1) = MShePy.wm.gridCellToCoord(1, 1) dfsDataX = Array.CreateInstance(System.Single, nX * nY) dfsDataY = Array.CreateInstance(System.Single, nX * nY) for x in range(nX): for y in range(nY): if(not MShePy.wm.gridIsInModel(x, y)): dfsDataX[x + y * nX] = builder.DeleteValueFloat dfsDataY[x + y * nX] = builder.DeleteValueFloat dx = x1 - x0 # cell size, dx == dy axis = factory.CreateAxisEqD2(eumUnit.eumUmeter, nX, x0 - dx / 2, dx, nY, y0 - dx / 2, dx) itemBuilder = builder.CreateDynamicItemBuilder() itemBuilder.SetValueType(DataValueType.MeanStepBackward) itemBuilder.SetAxis(axis) for iz in range(nZ): for xy in ['x', 'y']: itemBuilder.Set('Boundary inflow layer {0}, {1}-direction'.format(iz + 1, xy), eumQuantity.Create(eumItem.eumIDischarge, eumUnit.eumUm3PerSec), DfsSimpleType.Float) builder.AddDynamicItem(itemBuilder.GetDynamicItemInfo()) builder.CreateFile(filename) dfs = builder.GetFile()
def writeDatasets(h5file): dtype = H5T.copy(H5T.H5Type.NATIVE_INT) shape = Array[Int64]((2, 9)) dspacev = H5S.create_simple(shape.Length, shape) dsetv = H5D.create(h5file, 'MATRIX', dtype, dspacev) data = Array.CreateInstance(Int32, shape) data[0, 0] = data[0, 1] = data[1, 0] = 1 data[0, 2] = data[1, 1] = data[1, 2] = 2 data[0, 3] = data[0, 4] = data[1, 3] = 3 data[0, 5] = data[1, 4] = data[1, 5] = 4 data[0, 6] = data[0, 7] = data[1, 6] = 5 data[0, 8] = data[1, 7] = data[1, 8] = 6 H5D.write(dsetv, dtype, H5Array[Int32](data)) H5T.close(dtype) dtype = H5T.copy(H5T.H5Type.STD_REF_DSETREG) shape = Array[Int64]((2, )) dspacer = H5S.create_simple(shape.Length, shape) dsetr = H5D.create(h5file, 'REGION_REFERENCES', dtype, dspacer) start = Array[Int64]((0, 3)) count = Array[Int64]((2, 3)) H5S.selectHyperslab(dspacev, H5S.SelectOperator.SET, start, count) rr = Array.CreateInstance(RegionReference, 2) rr[0] = H5R.createRegionReference(h5file, 'MATRIX', dspacev) coord = Array.CreateInstance(Int64, 6) coord[0] = coord[1] = coord[4] = 0 coord[2] = 1 coord[3] = 6 coord[5] = 8 H5S.selectNone(dspacev) H5S.selectElements(dspacev, H5S.SelectOperator.SET, IntPtr(3), coord) rr[1] = H5R.createRegionReference(h5file, 'MATRIX', dspacev) nBytes = RegionReference.SizeInBytes data = Array.CreateInstance(Byte, rr.Length * nBytes) for i in range(rr.Length): Array.Copy(rr[i].ToByteArray(), 0, data, i * nBytes, nBytes) H5D.write(dsetr, dtype, H5Array[Byte](data)) H5T.close(dtype) H5D.close(dsetv) H5S.close(dspacev) H5D.close(dsetr) H5S.close(dspacer) return None
def load_sequence(self): # Check if sequence consists of repetitions of a subsequence sequence = self.sequence() if "divisors" in self.parent.optimize: try: N = len(sequence) divisors = [ n for n in reversed(np.arange(2, N + 1)) if N % n == 0 ] for divisor in divisors: sequence_arr = np.array(sequence) reshaped_arr = sequence_arr.reshape( divisor, int(N / divisor)) if (reshaped_arr == reshaped_arr[0]).all(): sequence = reshaped_arr[0] break except Exception: pass self.sequence = sequence sequence_obj = Array.CreateInstance(self._api.GenerationSequenceStruct, len(sequence)) for k, subsequence_info in enumerate(sequence): subsequence = self._api.GenerationSequenceStruct() # Must compare with Integral since np.int32 is not an int if isinstance(subsequence_info, numbers.Integral): subsequence.WaveformIndex = subsequence_info # Set repetitions to 1 (default) if subsequence info is an int subsequence.Repetitions = 1 elif isinstance(subsequence_info, tuple): assert ( len(subsequence_info) == 2 ), "A subsequence tuple must be of the form (WaveformIndex, Repetitions)" subsequence.WaveformIndex = subsequence_info[0] subsequence.Repetitions = subsequence_info[1] else: raise TypeError( "A subsequence must be either an int or (int, int) tuple") sequence_obj[k] = subsequence # Set transfermode to USB (seems to be a fixed function) transfer_mode = Array.CreateInstance(self._api.TransferMode, 1) self.parent.call_dll( self.channel_api.LoadGenerationSequence, sequence_obj, transfer_mode[0], True, msg="loading sequence", )
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 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 GetPhase32fImage(self) : self.updateROI() #Define a dotNet (C#) Single Array buffer = Array.CreateInstance(System.Single,self.roiHeight*self.roiWidth) self.host.GetPhase32fImage(buffer) #copy, reshape and return buffer return np.reshape(ru.dn2np(buffer),(self.roiHeight,self.roiWidth))
def read2FromDatasetWithCompoundType(dset): ht = { 'c_name': (0, 8, H5T_NATIVE_DOUBLE), 'a_name': (8, 4, H5T_NATIVE_INT) } 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]) dspace = H5D.getSpace(dset) npoints = H5S.getSimpleExtentNPoints(dspace) shape = Array[Int64]((npoints*sizeof,)) byteArray = Array.CreateInstance(Byte, shape) H5D.read(dset, dtype, H5Array[Byte](byteArray)) print '\nField\tc\ta' for i in range(npoints): offset = i*sizeof c = BitConverter.ToDouble(byteArray, offset+ht['c_name'][0]) a = BitConverter.ToInt32(byteArray, offset + ht['a_name'][0]) print '\t%.4f\t%d' % (c, a) print '' H5S.close(dspace) H5T.close(dtype) return dset
def read1FromDatasetWithCompoundType(dset): ht = { 'b_name': (0, 4, H5T_NATIVE_FLOAT) } 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]) dspace = H5D.getSpace(dset) npoints = H5S.getSimpleExtentNPoints(dspace) shape = Array[Int64]((npoints*sizeof,)) byteArray = Array.CreateInstance(Byte, shape) H5D.read(dset, dtype, H5Array[Byte](byteArray)) print '\nField\tb' for i in range(npoints): offset = i*sizeof b = BitConverter.ToSingle(byteArray, offset+ht['b_name'][0]) print '\t%.4f' % (b) print '' H5S.close(dspace) H5T.close(dtype) return dset
def get_hand_position_index(name): import StudioUICharaState from System import Array try: return Array.IndexOf(StudioUICharaState.handPtnAnimeName, name) except: return None
def readFromDatasetWithCompoundType(dset): mtype = createMemType() sizeof = H5T.getSize(mtype) dspace = H5D.getSpace(dset) npoints = H5S.getSimpleExtentNPoints(dspace) shape = Array[Int64]((npoints * sizeof, )) byteArray = Array.CreateInstance(Byte, shape) H5D.read(dset, mtype, H5Array[Byte](byteArray)) ms = MemoryStream(byteArray) reader = BinaryReader(ms) for i in range(npoints): if IntPtr.Size == 8: print '%d,%s,%.2f,%.2f' % (reader.ReadInt32( ), Marshal.PtrToStringAnsi(IntPtr( reader.ReadInt64())), reader.ReadDouble(), reader.ReadDouble()) else: print '%d,%s,%.2f,%.2f' % (reader.ReadInt32( ), Marshal.PtrToStringAnsi(IntPtr( reader.ReadInt32())), reader.ReadDouble(), reader.ReadDouble()) H5S.close(dspace) H5T.close(mtype) return None
def numpy2net(np_array): # TODO: set reference instead of copy x = Array.CreateInstance(Single, np_array.shape[0], np_array.shape[1]) for i1 in range(np_array.shape[0]): for i2 in range(np_array.shape[1]): x[i1, i2] = np_array[i1, i2] return x
def findScalarFixedStringAttribute(dset): info = H5O.getInfo(dset) for i in range(info.nAttributes): attr = H5A.openByIndex(dset, '.', H5IndexType.CRT_ORDER, H5IterationOrder.INCREASING, Int64(i)) dtype = H5A.getType(attr) tclass = H5T.getClass(dtype) # ignore variable length strings if tclass == H5T.H5TClass.STRING and not H5T.isVariableString(dtype): mtype = H5T.getNativeType(dtype, H5T.Direction.ASCEND) buffer = Array.CreateInstance(Byte, H5T.getSize(mtype)) H5A.read(attr, mtype, H5Array[Byte](buffer)) enc = System.Text.ASCIIEncoding() fmt = 'Found string attribute; its index is %d , value = %s' print fmt % (i, enc.GetString(buffer)) H5T.close(mtype) H5T.close(dtype) H5A.close(attr) return None
def getIntensityImage(contrast, width, height): #Get the intensity 8bit image if contrast == 'lambda1': obj.SelectDisplayWL(8192) elif contrast == 'lambda2': obj.SelectDisplayWL(16384) elif contrast == 'synth': obj.SelectDisplayWL(32768) elif contrast == 'synth_short': obj.SelectDisplayWL(65536) elif contrast == 'mapping': obj.SelectDisplayWL(131072) else: obj.SelectDisplayWL(8192) w = width h = height stride = (w / 4) * 4 if w % 4 != 0: stride += 4 size = stride * h bufP = Array.CreateInstance(System.Byte, size) obj.GetIntensityImage(bufP) floatbufP = np.zeros(size, dtype=int) for x in range(0, size - 1): floatbufP[x] = int(bufP[x]) out = np.reshape(floatbufP, (h, stride)) return out
def readStratumTable(vw, dal): log.lg('norm', 'START reading stratum table') from CruiseDAL.DataObjects import StratumDO from CruiseDAL.DataObjects import CuttingUnitDO for row in vw: stratum = StratumDO(dal) stratum.Code = str.strip(row.Stratum) stratum.Description = row.Description stratum.Method = row.CruzMeth if (row.CruzMeth != "PCMTRE") else "PCM" stratum.BasalAreaFactor = getattrFloat(row, "BAF") stratum.FixedPlotSize = getattrFloat(row, "FPSize") stratum.Month = row.Month stratum.Year = row.Year stratum.Save() log.lg('low', 'Created Record :' + str(stratum.rowID)) unitCodes = row.Units.split(',') for c in unitCodes: prams = Array.CreateInstance(Object, 1) prams[0] = str.strip(c) unit = dal.ReadSingleRow[CuttingUnitDO]('CuttingUnit', 'WHERE Code = ?', prams) if not unit: log.lg( 'high', 'unable to locate Cutting Unit record in Stratum table. Unit Code: ' + c) stratum.CuttingUnits.Add(unit) stratum.CuttingUnits.Save()
def __init__(self, maxsize): self._maxsize = maxsize self._data = Array.CreateInstance(System.Byte, self._maxsize) Random().NextBytes(self._data) self._log = StringBuilder() self._currentoffset = 0 self._currentlength = 0
def ArrayDiv(a, b): out = Array.CreateInstance(float, len(a)) outstr = '' for i in range(0, len(a)): out[i] = a[i] / b[i] outstr = outstr + str(round(out[i], 2)) + '\t' return out, outstr
def run(self, py_file): self.py_file = py_file #use the current executing version of IPY to launch the debug process ipy = Assembly.GetEntryAssembly().Location cmd_line = "\"%s\" -D \"%s\"" % (ipy, py_file) self.process = self.debugger.CreateProcess(ipy, cmd_line) self.process.OnCreateAppDomain += self.OnCreateAppDomain self.process.OnProcessExit += self.OnProcessExit self.process.OnUpdateModuleSymbols += self.OnUpdateModuleSymbols self.process.OnBreakpoint += self.OnBreakpoint self.process.OnStepComplete += self.OnStepComplete self.process.OnClassLoad += self.OnClassLoad self.terminate_event = AutoResetEvent(False) self.break_event = AutoResetEvent(False) self.initial_breakpoint = None self.breakpoints = [] self.source_files = dict() handles = Array.CreateInstance(WaitHandle, 2) handles[0] = self.terminate_event handles[1] = self.break_event while True: if hasattr(self, 'active_thread'): delattr(self, 'active_thread') if hasattr(self, 'active_appdomain'): delattr(self, 'active_appdomain') self.process.Continue(False) i = WaitHandle.WaitAny(handles) if i == 0: break self._input()
def WriteDataItems(self): outputData = self.outputData resultData = self.resultData builder = self.builder # Create file builder.CreateFile(self.outFileName) dfsfile = builder.GetFile() times = list(resultData.TimesList) # Write data to file val = Array.CreateInstance(System.Single, 1) for timeStepIndex in range(resultData.NumberOfTimeSteps): if (timeStepIndex % self.timeStepSkippingNumber != 0): continue time = times[timeStepIndex].Subtract( resultData.StartTime).TotalSeconds for dataEntry in outputData: dataItem = dataEntry.dataItem elementIndex = dataEntry.elementIndex val[0] = dataItem.GetValue(timeStepIndex, elementIndex) dfsfile.WriteItemTimeStepNext(time, val) dfsfile.Close()
def callback(attr, name, info, obj): print 'Name : ' + name dtype = H5A.getType(attr) dspace = H5A.getSpace(attr) rank = H5S.getSimpleExtentNDims(dspace) dims = H5S.getSimpleExtentDims(dspace) if rank > 0: print 'Rank : %d' % rank print 'Dimension sizes : ', for i in range(rank): print '%d' % dims[i], print '\n' if H5T.getClass(dtype) == H5T.H5TClass.FLOAT and H5T.getSize(dtype) == 4: print 'Type : FLOAT' npoints = H5S.getSimpleExtentNPoints(dspace) buffer = Array.CreateInstance(Single, npoints) H5A.read(attr, dtype, H5Array[Single](buffer)) print 'Values : ', for i in range(npoints): print '%f ' % buffer[i], print '\n' return H5IterationResult.SUCCESS
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 exportXls(self): ex = Excel.ApplicationClass() ex.Visible = True ex.DisplayAlerts = False workbook = ex.Workbooks.Add() workbook.SaveAs(self.filepath) ws = workbook.Worksheets[1] nbr_row = len(self.lstData) nbr_colum = len(self.lstData[0]) xlrange = ws.Range[ws.Cells(1, 1), ws.Cells(nbr_row, nbr_colum)] a = Array.CreateInstance(object, nbr_row, nbr_colum) for indexR, row in enumerate(self.lstData): for indexC, value in enumerate(row): a[indexR, indexC] = value #copy Array in range xlrange.Value2 = a used_range = ws.UsedRange for column in used_range.Columns: column.AutoFit() # apply style missing = System.Type.Missing try: currentWs.ListObjects.Add(Excel.XlListObjectSourceType.xlSrcRange, xlrange, missing, Excel.XlYesNoGuess.xlGuess, missing).Name = "WFTableStyle" currentWs.ListObjects[ "WFTableStyle"].TableStyle = "TableStyleMedium6" except: pass
def dotnet_notification_parser(sender: Any, args: Any): # Return only the UUID string representation as sender. # Also do a conversion from System.Bytes[] to bytearray. reader = DataReader.FromBuffer(args.CharacteristicValue) output = Array.CreateInstance(Byte, reader.UnconsumedBufferLength) reader.ReadBytes(output) return func(sender.Uuid.ToString(), bytearray(output))
def capture(sender, event_args): buffer = Array.CreateInstance( Byte, convertedSource.WaveFormat.BytesPerSecond / 2) while True: read = convertedSource.Read(buffer, 0, buffer.Length) waveWriter.Write(buffer, 0, read) if read <= 0: break
def _string_to_bytearr(buf): retval = Array.CreateInstance(System.Byte, len(buf)) # pylint: disable=consider-using-enumerate for i in range(len(buf)): retval[i] = ord(buf[i]) return retval