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) }
async def add_new_characteristic(self, service_uuid: str, char_uuid: str, properties: GattCharacteristicsFlags, value: Optional[bytearray], permissions: int): """ Generate a new characteristic to be associated with the server Parameters ---------- service_uuid : str The string representation of the uuid of the service to associate the new characteristic with char_uuid : str The string representation of the uuid of the new characteristic properties : GattCharacteristicsFlags The flags for the characteristic value : Optional[bytearray] The initial value for the characteristic permissions : int The permissions for the characteristic """ charguid: Guid = Guid.Parse(char_uuid) serverguid: Guid = Guid.Parse(service_uuid) ReadParameters: GattLocalCharacteristicParameters = ( GattLocalCharacteristicParameters() ) ReadParameters.CharacteristicProperties = properties ReadParameters.ReadProtectionLevel = permissions characteristic_result: GattLocalCharacteristicResult = ( await wrap_IAsyncOperation( IAsyncOperation[GattLocalCharacteristicResult]( self.services.get(str(serverguid), None) .obj.CreateCharacteristicAsync( charguid, ReadParameters) ), return_type=GattLocalCharacteristicResult) ) newChar: GattLocalCharacteristic = characteristic_result.Characteristic newChar.ReadRequested += self.read_characteristic newChar.WriteRequested += self.write_characteristic newChar.SubscribedClientsChanged += self.subscribe_characteristic bleak_characteristic: BlessGATTCharacteristicDotNet = ( BlessGATTCharacteristicDotNet(obj=newChar) ) service: BleakGATTServiceDotNet = self.services.get(str(serverguid)) service.add_characteristic(bleak_characteristic)
async def init(self, service: BlessGATTService): """ Initialize the DotNet GattLocalCharacteristic object Parameters ---------- service : BlessGATTServiceDotNet The service to assign the characteristic to """ charguid: Guid = Guid.Parse(self._uuid) char_parameters: GattLocalCharacteristicParameters = ( GattLocalCharacteristicParameters()) char_parameters.CharacteristicProperties = self._properties.value char_parameters.ReadProtectionLevel = ( BlessGATTCharacteristicDotNet.permissions_to_protection_level( self._permissions, True)) char_parameters.WriteProtectionLevel = ( BlessGATTCharacteristicDotNet.permissions_to_protection_level( self._permissions, False)) characteristic_result: GattLocalCharacteristicResult = ( await wrap_IAsyncOperation( IAsyncOperation[GattLocalCharacteristicResult]( service.obj.CreateCharacteristicAsync( charguid, char_parameters)), return_type=GattLocalCharacteristicResult, )) gatt_char: GattLocalCharacteristic = characteristic_result.Characteristic super(BlessGATTCharacteristic, self).__init__(obj=gatt_char)
def set_op_rf(el): if el.LookupParameter('ADSK_Наименование'): naim = el.LookupParameter('ADSK_Наименование').AsString() or '' else: param = el.get_Parameter(Guid('e6e0f5cd-3e26-485b-9342-23882b20eb43')) if param: naim = param.AsString() or '' else: naim = doc.GetElement( el.GetTypeId()).LookupParameter('Описание').AsString() or '' if el.LookupParameter('ADSK_Марка'): mark = el.LookupParameter('ADSK_Марка').AsString() or '' elif el.LookupParameter('ХТ Размер фитинга ОВ'): mark = el.LookupParameter('ХТ Размер фитинга ОВ').AsString() or '' else: mark = '' if el.LookupParameter('ADSK_Код изделия'): code = el.LookupParameter('ADSK_Код изделия').AsString() or '' else: code = '' el.LookupParameter('наим марка код') and el.LookupParameter( 'наим марка код').Set(naim + ' | ' + mark + ' | ' + code) op = doc.GetElement( el.GetTypeId()).LookupParameter('Описание').AsString() or '' if el.LookupParameter('ХТ Размер фитинга ОВ'): rf = el.LookupParameter('ХТ Размер фитинга ОВ').AsString() or '' else: rf = '' if not el.LookupParameter('оп+рф'): if not el.LookupParameter('наим марка код'): print_once('Не найден параметр "оп+рф" ("наим марка код")') # else: # el.LookupParameter('наим марка код').Set(op + ' ' + rf) # Переделать в н-м-к!!!!!!!!!!!!!!!!!!!!!!!!!!!!2020.05.11 else: el.LookupParameter('оп+рф').Set(op + ' ' + rf)
def setEntryBySrcEntry(): ''' 由源单明细表体写入明细表体 ''' srcEntry = this.View.Model.DataObject["RECEIVEBILLSRCENTRY"] entry = this.View.Model.DataObject["RECEIVEBILLENTRY"] rowNum = this.View.Model.GetEntryRowCount("FRECEIVEBILLENTRY") if rowNum > 0: if (str(entry[rowNum - 1]["RECTOTALAMOUNTFOR"]) == "0" and str(entry[rowNum - 1]["RECAMOUNTFOR_E"]) == "0" and str(entry[rowNum - 1]["SETTLERECAMOUNTFOR"]) == "0"): this.View.Model.DeleteEntryRow("FRECEIVEBILLENTRY", rowNum - 1) for idx, row in enumerate(srcEntry): srcBillType = str(row["SRCBILLTYPEID"]) if srcBillType == "ora_CZ_ReceiptSplit": guid = str(Guid.NewGuid()) amount = str(row["REALRECAMOUNT"]) #本次收款金额 this.View.Model.CreateNewEntryRow("FRECEIVEBILLENTRY") i = this.View.Model.GetEntryRowCount("FRECEIVEBILLENTRY") - 1 this.View.Model.SetValue("FRECTOTALAMOUNTFOR", amount, i) #应收金额 this.View.Model.SetValue("FRECAMOUNTFOR_E", amount, i) #收款金额 this.View.Model.SetValue("FSETTLERECAMOUNTFOR", amount, i) #折后金额 this.View.Model.SetValue("F_ora_ReGuid", guid, i) #明细表体 this.View.Model.SetValue("F_ora_RseGuid", guid, idx) #源单明细表体 this.View.UpdateView("FRECEIVEBILLENTRY")
async def add_new_characteristic( self, service_uuid: str, char_uuid: str, properties: GATTCharacteristicProperties, value: Optional[bytearray], permissions: GATTAttributePermissions, ): """ Generate a new characteristic to be associated with the server Parameters ---------- service_uuid : str The string representation of the uuid of the service to associate the new characteristic with char_uuid : str The string representation of the uuid of the new characteristic properties : GATTCharacteristicProperties The flags for the characteristic value : Optional[bytearray] The initial value for the characteristic permissions : GATTAttributePermissions The permissions for the characteristic """ serverguid: Guid = Guid.Parse(service_uuid) service: BlessGATTServiceDotNet = self.services[str(serverguid)] characteristic: BlessGATTCharacteristicDotNet = BlessGATTCharacteristicDotNet( char_uuid, properties, permissions, value) await characteristic.init(service) characteristic.obj.ReadRequested += self.read_characteristic characteristic.obj.WriteRequested += self.write_characteristic characteristic.obj.SubscribedClientsChanged += self.subscribe_characteristic service.add_characteristic(characteristic)
def testStructConstructor(self): """Test struct constructor args""" from System import Guid from Python.Test import StructConstructorTest guid = Guid.NewGuid() ob = StructConstructorTest(guid) self.assertTrue(ob.value == guid)
def test_struct_constructor(): """Test struct constructor args""" from System import Guid from Python.Test import StructConstructorTest guid = Guid.NewGuid() ob = StructConstructorTest(guid) assert ob.value == guid
def test_method_call_struct_conversion(): """Test struct conversion in method call.""" from System import Guid ob = MethodTest() guid = Guid.NewGuid() temp = guid.ToString() r = ob.TestStructConversion(guid) assert r.ToString() == temp
def testMethodCallStructConversion(self): """Test struct conversion in method call.""" from System import Guid object = MethodTest() guid = Guid.NewGuid() temp = guid.ToString() r = object.TestStructConversion(guid) self.assertTrue(r.ToString() == temp)
def __init__(self, addin_id): #updaterのID self.id = DB.UpdaterId(addin_id, Guid("A7931BDA-F0DC-41B5-83C9-C6FE03CC5025")) #追加エレメント self.addedId = [] #トランザクション名称取得 self.transactionName = None #追加対象用カラーセット self.addedColor = SetElementColor(255, 0, 0, 20) #変更対象用カラーセット self.changedColor = SetElementColor(0, 0, 255, 20)
def randtest(doc): #生成1w个测试点 with dbtrans(doc) as tr: btr = tr.opencurrspace() from System import Guid, Random r = Random(Guid.NewGuid().GetHashCode()) for i in range(10000): tr.addentity( btr, acdb.DBPoint(acge.Point3d(r.Next(0, 1000), r.Next(0, 1000), 0)))
def set_description(el): symbol = doc.GetElement(el.GetTypeId()) description = symbol.LookupParameter('Описание').AsString() or '' if not description: description = '--- Ошибка. Не заполнено Описание для {}: {}'.format( el.LookupParameter('Семейство').AsValueString(), el.LookupParameter('Тип').AsValueString(), ) elif el in pipe_curves and 'егмент' in description: segment_description = el.LookupParameter( 'Описание сегмента').AsString() try: el.LookupParameter('ADSK_Наименование').Set(segment_description) except: param = el.get_Parameter( Guid('e6e0f5cd-3e26-485b-9342-23882b20eb43')) param.Set(segment_description) return # el.LookupParameter('ADSK_Наименование').Set(description) param = el.get_Parameter(Guid('e6e0f5cd-3e26-485b-9342-23882b20eb43')) if param and not param.IsReadOnly: param.Set(description)
def __init__(self, name, ptype, group="pypevitmep", guid=None, description="", modifiable=True, visible=True, new=True): # type: (str, ParameterType or str, str, Guid or None, str, bool, bool, bool) -> None self.name = name self.description = description self.group = group true_tuple = (True, "", None, "True", "Yes", "Oui", 1) if modifiable in true_tuple: self.modifiable = True else: self.modifiable = False if visible in true_tuple: self.visible = True else: self.visible = False # Check if a Guid is given. If not a new one is created if not guid: self.guid = Guid.NewGuid() else: self.guid = guid # Check if given parameter type is valid. If not user is prompted to choose one. if isinstance(ptype, ParameterType): self.type = ptype else: try: self.type = getattr(ParameterType, ptype) except AttributeError: selected_type = rpw.ui.forms.SelectFromList( "Select ParameterType", ParameterType.GetNames(ParameterType), "Parameter {} ParameterType: {} is not valid. Please select a parameter type".format(name, ptype), sort=False) self.type = getattr(ParameterType, selected_type) self.initial_values = {} if new is True: self.new = new else: self.new = False self.initial_values_update() self.changed = False
def __init__(self): p = Process.GetCurrentProcess() self.SLEEP = 5000 self.JITTER = 5000 self.FIRST_CHECKIN = True self.GUID = Guid().NewGuid().ToString() self.URL = str( Uri(Uri(URL), self.GUID )) # This needs to be a tuple of callback domains (eventually) self.USERNAME = Environment.UserName self.DOMAIN = Environment.UserDomainName self.HIGH_INTEGRITY = self.is_high_integrity() #self.IP = ManagementObject("Win32_NetworkAdapterConfiguration") #self.OS = ManagementObject("Win32_OperatingSystem") self.PROCESS = p.Id self.PROCESS_NAME = p.ProcessName self.HOSTNAME = Environment.MachineName self.JOBS = []
def createCodes(self): try: guid = Guid.NewGuid().ToString('N') # global unique ID # get configuration from web.config codeSource = WebConfigurationManager.AppSettings['CodeGenQueue'] lengthCaptchaStrng = int(WebConfigurationManager.AppSettings['captchaStrngLngth']) # create captcha code captcha = '' for a in range(lengthCaptchaStrng): apd = random.choice(codeSource) captcha += apd # save to session cache self.usrDt.addNewItem('GUID', guid) self.usrDt.addNewItem('CAPTCHA', captcha) return guid except Exception,e: self.log.w2lgError(traceback.format_exc())
async def add_new_service(self, uuid: str): """ Generate a new service to be associated with the server Parameters ---------- uuid : str The string representation of the UUID of the service to be added """ logger.debug("Creating a new service with uuid: {}".format(uuid)) guid: Guid = Guid.Parse(uuid) spr: GattServiceProviderResult = await wrap_IAsyncOperation( IAsyncOperation[GattServiceProviderResult]( GattServiceProvider.CreateAsync(guid) ), return_type=GattServiceProviderResult) self.service_provider: GattServiceProvider = spr.ServiceProvider new_service: GattLocalService = self.service_provider.Service bleak_service = BleakGATTServiceDotNet(obj=new_service) logger.debug("Adding service to server with uuid {}".format(uuid)) self.services[uuid] = bleak_service
async def init(self, server: "BaseBlessServer"): """ Initialize the GattLocalService Object Parameters ---------- server: BlessServerDotNet The server to assign the service to """ dotnet_server: "BlessServerDotNet" = cast("BlessServerDotNet", server) guid: Guid = Guid.Parse(self._uuid) service_provider_result: GattServiceProviderResult = await wrap_IAsyncOperation( IAsyncOperation[GattServiceProviderResult]( GattServiceProvider.CreateAsync(guid)), return_type=GattServiceProviderResult, ) self.service_provider: GattServiceProvider = ( service_provider_result.ServiceProvider) self.service_provider.AdvertisementStatusChanged += dotnet_server._status_update new_service: GattLocalService = self.service_provider.Service self.obj = new_service
def SaveCloudModelandChangeName(document, filePath, Name): worksharingOptions = WorksharingSaveAsOptions() worksharingOptions.SaveAsCentral = True saveOpt = SaveAsOptions() saveOpt.SetWorksharingOptions(worksharingOptions) saveOpt.OverwriteExistingFile = True saveOpt.Compact = True document.SaveAs(filePath + Name + ".rvt", saveOpt) document.Close() filePath1 = "\\\\stvgroup.stvinc.com\\v3\\DGPA\\Vol3\\Projects\\4020310\\4020310_0001\\90_CAD Models and Sheets\\07_A_Architectural\\" filePath2 = "\\\\stvgroup.stvinc.com\\v3\\DGPA\\Vol3\\Projects\\4020310\\4020310_0001\\90_CAD Models and Sheets\\07_A_Architectural\\VE\\" modelGUID = Guid("e77aa560-8776-4a0e-8192-3044c5e240df") projectGUID = Guid("20ac335a-5ba8-4520-b948-296e529c3306") model2GUID = Guid("172edfec-1f93-4385-85eb-a4db3b96d5d1") versionName = application.VersionName if versionName == "Autodesk Revit 2020": # Model 1 openedDoc = OpenCloudFiles(modelGUID, projectGUID, application, audit=False) SaveCloudModelandChangeName(openedDoc, filePath1, 'T06-ARCH-NBusGarage-r20') # Model 2 print("Model 1 Download Complete") openedDoc2 = OpenCloudFiles(model2GUID,
PINVOKE_METHOD_ATTRIBUTES = (Refl.MethodAttributes.Public | Refl.MethodAttributes.Static | Refl.MethodAttributes.HideBySig | Refl.MethodAttributes.PinvokeImpl) PUBLIC_STATIC_BINDING_FLAGS = Refl.BindingFlags.Static | Refl.BindingFlags.Public WIN_API_CALLING_CONVENTION = Interop.CallingConvention.StdCall assemblyBuilder = (Emit.AssemblyBuilder.DefineDynamicAssembly( Refl.AssemblyName(WIN32_PINVOKE_DYNAMIC_ASSEMBLY_NAME), Emit.AssemblyBuilderAccess.Run)) MODULE_BUILDER = assemblyBuilder.DefineDynamicModule("WIN_API_MODULE_" + Guid.NewGuid().ToString()) def GetWinApiFunctionImpl(functionName, moduleName, charSet, returnType, *parameterTypes): tbuilder = MODULE_BUILDER.DefineType("WIN_API_TYPE" + "_" + moduleName + "_" + functionName) mbuilder = tbuilder.DefinePInvokeMethod( functionName, moduleName, PINVOKE_METHOD_ATTRIBUTES, Refl.CallingConventions.Standard, clr.GetClrType(returnType), [clr.GetClrType(t) for t in parameterTypes].ToArray[System.Type](), WIN_API_CALLING_CONVENTION, charSet) mbuilder.SetImplementationFlags(mbuilder.MethodImplementationFlags | Refl.MethodImplAttributes.PreserveSig) winApiType = tbuilder.CreateType() methodInfo = winApiType.GetMethod(functionName,
def test_negative(): AssertError(ValueError, clr.LoadTypeLibrary, "DlrComLibrary.DlrComServer") AssertError(ValueError, clr.LoadTypeLibrary, 42) AssertError(EnvironmentError, clr.LoadTypeLibrary, Guid.NewGuid())
# [email protected]. By using this source code in any fashion, you are agreeing to be bound # by the terms of the Apache License, Version 2.0. # # You must not remove this notice, or any other, from this software. # # ##################################################################################### # COM Interop tests for IronPython from iptest.assert_util import skiptest skiptest("win32", "silverlight") from iptest.cominterop_util import * from System import Type, Activator, Guid import clr dlrcomlib_guid = Guid("a50d2773-4b1b-428a-b5b4-9300e1b50484") def test_load_typelib(): for x in [ dlrcomlib_guid, Activator.CreateInstance( Type.GetTypeFromProgID("DlrComLibrary.ParamsInRetval")) ]: lib = clr.LoadTypeLibrary(x) #ComTypeLibInfo Members AreEqual(lib.Guid, dlrcomlib_guid) AreEqual(lib.Name, "DlrComLibraryLib") AreEqual(lib.VersionMajor, 1) AreEqual(lib.VersionMinor, 0)
__title__ = "Architype\nLearn" __doc__ = "Architype Learn \nv1.0" from pyrevit import revit, DB, HOST_APP from pyrevit.framework import List from pyrevit.forms import ProgressBar from System import EventHandler, Uri from Autodesk.Revit.UI.Events import ViewActivatedEventArgs, ViewActivatingEventArgs from Autodesk.Revit.UI import DockablePaneId from Autodesk.Revit import UI from System import Guid from pyrevit import HOST_APP app = HOST_APP.uiapp dpid = DockablePaneId(Guid("39FA492A-6F72-465C-83C9-F7662B89F62C")) dp = app.GetDockablePane(dpid) if dp.IsShown(): dp.Hide() else: dp.Show()
def CreateAgentServer(): import clr from System import Guid typelib = clr.LoadTypeLibrary(Guid("A7B93C73-7B81-11D0-AC5F-00C04FD97575")) return typelib.AgentServerObjects.AgentServer()
opt = ExternalDefinitionCreationOptions(pName, pType) spfilepath = path + '\SP.txt' f = open(spfilepath,'w') f.close() app.SharedParametersFilename = spfilepath defFile = app.OpenSharedParameterFile() tempGroup = defFile.Groups.Create(pName) defs = tempGroup.Definitions opt = ExternalDefinitionCreationOptions(pName, pType) opt.GUID = Guid(pGUID) #opt.GUID = pGUID #pExtDfn = Definitions.Create(opt, True) pExtDfn = defs.Create(opt) doc_i = int(item[4]) if docIds[i] == doc_i:
configFile = os.getenv('REVITRON_CLI_CONFIG') file = open(configFile) config = json.load(file) file.close() try: model = config['model'] if model['type'] == 'local': openOptions.DetachFromCentralOption = revitron.DB.DetachFromCentralOption.DetachAndPreserveWorksets modelPath = revitron.DB.ModelPathUtils.ConvertUserVisiblePathToModelPath( model['path']) else: try: modelPath = revitron.DB.ModelPathUtils.ConvertCloudGUIDsToCloudPath( model['region'], Guid(model['projectGUID']), Guid(model['modelGUID'])) except: modelPath = revitron.DB.ModelPathUtils.ConvertCloudGUIDsToCloudPath( Guid(model['projectGUID']), Guid(model['modelGUID'])) except: print('Invalid model configuration') sys.exit(1) revitron.DOC = HOST_APP.uiapp.Application.OpenDocumentFile( modelPath, openOptions) analyzer = revitron.ModelAnalyzer(configFile) analyzer.snapshot() revitron.DOC.Close(False)
def new_uuid(): """Create a new UUID (using dotnet Guid.NewGuid)""" # RE: https://github.com/eirannejad/pyRevit/issues/413 # return uuid.uuid1() return str(Guid.NewGuid())
def __init__(self, addinId): '''type UpdaterId, choose a different GUID for each updater ! ''' self.updaterID = UpdaterId(addinId, Guid("CBCBF6B2-4C06-42d4-97C1-D1B4EB593EFF"))
Refl.MethodAttributes.HideBySig | Refl.MethodAttributes.PinvokeImpl ) PUBLIC_STATIC_BINDING_FLAGS = Refl.BindingFlags.Static | Refl.BindingFlags.Public WIN_API_CALLING_CONVENTION = Interop.CallingConvention.StdCall assemblyBuilder = ( Emit.AssemblyBuilder.DefineDynamicAssembly( Refl.AssemblyName(WIN32_PINVOKE_DYNAMIC_ASSEMBLY_NAME), Emit.AssemblyBuilderAccess.Run ) ) MODULE_BUILDER = assemblyBuilder.DefineDynamicModule("WIN_API_MODULE_" + Guid.NewGuid().ToString()) def GetWinApiFunctionImpl( functionName, moduleName, charSet, returnType, *parameterTypes ): tbuilder = MODULE_BUILDER.DefineType("WIN_API_TYPE" + "_" + moduleName + "_" + functionName) mbuilder = tbuilder.DefinePInvokeMethod( functionName, moduleName, PINVOKE_METHOD_ATTRIBUTES, Refl.CallingConventions.Standard, clr.GetClrType(returnType),
def SafeParseGuidText(self, guidText): parsed, guid = Guid.TryParse(guidText) return guid if parsed else None