def generate_guid(): """Return a GUID/UUID in the typical {12345678-90ab-cdef-1234-567890abcdef} format (*with* the braces). """ guid = None # On Windows, try pythoncom.CreateGuid(). if sys.platform == "win32": try: import pythoncom except ImportError: pass else: guid = str(pythoncom.CreateGuid()) # Try Ka-Ping Yee's uuid.py module. if guid is None: from ludditelib import uuid guid = str(uuid.uuid4()) # Fallback to PyXPCOM. if guid is None: from xpcom import components uuidGenerator = components.classes["@mozilla.org/uuid-generator;1"] \ .getService(components.interfaces.nsIUUIDGenerator) guid = str(uuidGenerator.generateUUID()) return guid
class PythonObjectLibrary: # This will create a GUID to register it with Windows, it is unique. _reg_clsid_ = pythoncom.CreateGuid() # Register the object as an EXE file, the alternative is an DLL file (INPROC_SERVER) _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER # the program ID, this is the name of the object library that users will use to create the object. _reg_progid_ = "Python.ObjectLibrary" # this is a description of our object library. _reg_desc_ = "This is our Python object library." # a list of strings that indicate the public methods for the object. If they aren't listed they are conisdered private. _public_methods_ = ['pythonSum', 'pythonMultiply','addArray'] # multiply two cell values. def pythonMultiply(self, a, b): return a * b # add two cell values def pythonSum(self, x, y): return x + y # add a range of cell values def addArray(self, myRange): # create an instance of the range object that is passed through rng1 = win32com.client.Dispatch(myRange) # Get the values from the range rng1val = np.array(list(rng1.Value)) return rng1val.sum()
class PythonObjectLibrary: # This will create a GUID to register it with Windows, it is unique. _reg_clsid_ = pythoncom.CreateGuid() # Register the object as an EXE file, the alternative is an DLL file (INPROC_SERVER) _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER # the program ID, this is the name of the object library that users will use to create the object. _reg_progid_ = "Python.ObjectLibrary" # this is a description of our object library. _reg_desc_ = "This is our Python object library." # a list of strings that indicate the public methods for the object. If they aren't listed they are conisdered private. _public_methods_ = ['SAS', 'SASO'] def __init__(self): self.count = 0 # multiply two cell values. def pythonMultiply(self, a, b): return a * b # multiply two cell values. def pythonAdd(self, a, b): return a + b # multiply two cell values. def SAS(self, op, close, high, low, date, index, reqUrl): # logger.info("Entering SAS") data = dict() data.update({ 'CP': close, 'HP': high, 'LP': low, 'Date': date, 'index': index }) URL = "http://localhost:5000/index" # logger.info("Sending req", "url", URL, "data", data) self.update_values_async(URL, data) return close # multiply two cell values. def SASO(self, q): self.count = self.count + 1 self.update_values_async(q, 1) return self.count def update_values_async(self, URL, data): async_task = AsyncUpdateTask(q=URL, task_type=data) async_task.start() return
class RedisRealtime: _public_methods_ = ["get_snapshot"] _reg_progid_ = "Redis.Snapshot" _reg_clsid_ = pythoncom.CreateGuid() def get_snapshot(self, tagid): htag = conn.hmget(tagid, 'value', 'ts') return float(htag[0].decode())
def genUID(): """ Функция генерации уникального идентификатора UID в формате XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX. """ import pythoncom uid = pythoncom.CreateGuid() return str(uid)[1:-1]
def new_guid(): if sys.platform == "win32": import pythoncom guid = str(pythoncom.CreateGuid()) guid = guid[1:-1] # strip of the {}'s else: guid = os.popen("uuidgen").read().strip().upper() return guid
def writeProject(file, to_path): infile = open("unittest_template.xml", "r") outfile = open(to_path + "/" + file.replace("test_", "testprog_") + ".vcproj", "w") text = infile.read() guid = pythoncom.CreateGuid() text = text.replace("__INSERT_NAME_HERE__", file.replace("test_", "testprog_")) text = text.replace("__INSERT_FILENAME_HERE__", file) text = text.replace("__INSERT_GUID_HERE__", str(guid)) outfile.write(text) return str(guid)
class TrinomialLatticeCOMServer: _public_methods_ = ['pricer'] _reg_progid_ = "TrinomialLatticeCOMServer.Pricer" _reg_clsid_ = pythoncom.CreateGuid() def pricer(self, S0, K, r, T, N, sigma, is_call=True, div=0., is_eu=False): model = TrinomialLattice(S0, K, r, T, N, {"sigma": sigma, "div": div, "is_call": is_call, "is_eu": is_eu}) return model.price()
class PythonUtilities: _public_methods_ = ['SplitString'] _reg_progid_ = "PythonDemos.Utilities" # NEVER copy the following ID # Use"print pythoncom.CreateGuid()" to make a new one. _reg_clsid_ = pythoncom.CreateGuid() print(_reg_clsid_) def SplitString(self, val, item=None): import string if item != None: item = str(item) return string.split(str(val), item)
class BlackScholes: _public_methods_ = ["call_pricer", "put_pricer"] _reg_progid_ = "BlackScholes.Pricer" _reg_clsid_ = pythoncom.CreateGuid() def d1(self, S0, K, r, T, sigma, div): return (np.log(S0/K) + ((r-div) + sigma**2 / 2) * T)/ \ (sigma * np.sqrt(T)) def d2(self, S0, K, r, T, sigma, div): return (np.log(S0 / K) + ((r-div) - sigma**2 / 2) * T) / \ (sigma * np.sqrt(T)) def call_pricer(self, S0, K, r, T, sigma, div): d1 = self.d1(S0, K, r, T, sigma, div) d2 = self.d2(S0, K, r, T, sigma, div) return S0 * np.exp(-div * T) * stats.norm.cdf(d1) \ - K * np.exp(-r * T) * stats.norm.cdf(d2) def put_pricer(self, S0, K, r, T, sigma, div): d1 = self.d1(S0, K, r, T, sigma, div) d2 = self.d2(S0, K, r, T, sigma, div) return K * np.exp(-r * T) * stats.norm.cdf(-d2) \ - S0 * np.exp(-div * T) *stats.norm.cdf(-d1)
class PythonUtilities: _public_methods_ = ['VbgetPrice'] # 对外调用函数名称 _reg_progid_ = 'PythonDemos.Utilities' # 对外申请Com接口 _reg_clsid_ = pythoncom.CreateGuid() # 获取本机注册码 def VbgetPrice(self, orderCount, capacitance, package, voltage, accuracy): ''' 从唯详商城获取指定电容最低价格 :param orderCount: 采购数量 :param capacitance: 电容容量 :param package: 电容封装 :param voltage: 电容耐压 :param accuracy: 电容精度 :return:返回值 productPrice = { 'Flag':True, # 电容规格是否正确 '品牌': '', # 查询到最低价格的品牌 'price': '', # 查询到的最低价格 'Msgbox':'' # 提示字符串 } ''' # 声明变量类型 orderCount = int(orderCount) capacitance = str(capacitance) package = str(package) voltage = str(voltage) accuracy = str(accuracy) # 初始化返回值 productPrice = {'Flag': True, '品牌': '', 'price': '', 'Msgbox': ''} # 判断请购数量 if orderCount < 1: productPrice['Flag'] = False productPrice['Msgbox'] = '订单数量有误' return json.dumps(productPrice).encode('utf-8').decode( 'unicode_escape') priceArr = [] # 设置搜索引擎 aggAttrApi = 'https://soic.oneyac.com/agg_attr?' searchApi = 'https://soic.oneyac.com/search?' flag, msg = PriceTierView.specJudgment(aggAttrApi, capacitance, package, voltage, accuracy) productPrice['Msgbox'] = msg # 判断输入电容规格参数是否有误 if flag == False: productPrice['Flag'] = False return json.dumps(productPrice).encode('utf-8').decode( 'unicode_escape') # 电容参数正确,执行查找价格 respText, webToken, webXlstoken = PriceTierView.getToken() if respText == "webToken获取失败": productPrice['Flag'] = False productPrice['Msgbox'] = "webToken获取失败" return json.dumps(productPrice).encode('utf-8').decode( 'unicode_escape') token = getSearchToken(webToken) xlstoken = getSearchToken(webXlstoken) # 规格参数 specAttr = { "aggFields": "brand", "page": 0, "pageSize": 10, "supplierId": "1", "categoryId": "1207", "keyword": "", "brand_id_filters[]": [], "agg_attr_name_filters[]": ["封装/外壳", "容值", "偏差", "电压"], "token": token, "xlsToken": xlstoken, "attr_封装/外壳[]": [package], "attr_电压[]": [voltage], "attr_容值[]": [capacitance], "attr_偏差[]": [accuracy], "orderBy": "minPrice", "sort": "asc" } productDic = PriceTierView.getJosn(searchApi, specAttr) price = productDic['priceModelList'] productPrice['品牌'] = productDic['brandName'] if len(price) == 0: # 无价格 productPrice['price'] = '' productPrice['Flag'] = False productPrice['Msgbox'] = '暂无价格' elif len(price) == 1: productPrice['price'] = price[0]['price'] # 仅此一个价格 return json.dumps(productPrice).encode('utf-8').decode( 'unicode_escape') else: # 获取所有价格 for i in range(0, len(price)): priceArr.append(int(price[i]['stepNum'])) if orderCount in priceArr: indexNum = priceArr.index(orderCount) productPrice['price'] = price[indexNum]['price'] else: # 将订单数据添加至列表,并重新排序 priceArr.append(orderCount) priceArr.sort() # 获取指定元素orderCount,index indexNum = priceArr.index(orderCount) # 最终确认价格 productPrice['price'] = price[indexNum - 1]['price'] return json.dumps(productPrice).encode('utf-8').decode( 'unicode_escape')
def gen_uuid(): return str(pythoncom.CreateGuid())
def Process(self, grd, dialog_ids): '''Outputs an RC file and header file for the dialog 'dialog_id' stored in resource tree 'grd', to self.base_folder, as discussed in this class's documentation. Arguments: grd: grd = grd_reader.Parse(...); grd.RunGatherers() dialog_ids: ['IDD_MYDIALOG', 'IDD_OTHERDIALOG'] ''' grd.SetOutputContext(self.lang, self.defines) project_name = dialog_ids[0] dir_path = os.path.join(self.base_folder, project_name) if not os.path.isdir(dir_path): os.mkdir(dir_path) # If this fails then we're not on Windows (or you don't have the required # win32all Python libraries installed), so what are you doing mucking # about with RC files anyway? :) import pythoncom # Create the .vcproj file project_text = PROJECT_TEMPLATE.replace( '[[PROJECT_GUID]]', str(pythoncom.CreateGuid())).replace('[[DIALOG_NAME]]', project_name) fname = os.path.join(dir_path, '%s.vcproj' % project_name) self.WriteFile(fname, project_text) print "Wrote %s" % fname # Create the .rc file # Output all <include> nodes since the dialogs might depend on them (e.g. # for icons and bitmaps). include_items = [] for node in grd: if isinstance(node, include.IncludeNode): formatter = node.ItemFormatter('rc_all') if formatter: include_items.append(formatter.Format(node, self.lang)) rc_text = RC_TEMPLATE.replace('[[CODEPAGE_NUM]]', str(self.codepage_number)) rc_text = rc_text.replace('[[INCLUDES]]', ''.join(include_items)) # Then output the dialogs we have been asked to output. dialogs = [] for dialog_id in dialog_ids: node = grd.GetNodeById(dialog_id) # TODO(joi) Add exception handling for better error reporting formatter = node.ItemFormatter('rc_all') dialogs.append(formatter.Format(node, self.lang)) rc_text = rc_text.replace('[[DIALOGS]]', ''.join(dialogs)) fname = os.path.join(dir_path, '%s.rc' % project_name) self.WriteFile(fname, rc_text, self.GetEncoding()) print "Wrote %s" % fname # Create the resource.h file header_defines = [] for node in grd: formatter = node.ItemFormatter('rc_header') if formatter and not isinstance(formatter, rc_header.TopLevel): header_defines.append(formatter.Format(node, self.lang)) header_text = HEADER_TEMPLATE.replace('[[DEFINES]]', ''.join(header_defines)) fname = os.path.join(dir_path, 'resource.h') self.WriteFile(fname, header_text) print "Wrote %s" % fname
def create_guid(): """ MS guid. """ return pythoncom.CreateGuid()
specPath = len(sys.argv) > 1 and os.path.split( sys.argv[1])[1] or 'component.xml' spath = os.path.split(sys.argv[1]) gpath = os.path.split(sys.argv[0]) genPath = os.path.splitdrive(sys.argv[1])[0] and spath[0] or \ spath[0] and os.path.join(gpath[0], spath[0]) or gpath[0] else: specPath = 'component.xml' genPath = os.path.split(sys.argv[0])[0] # initialize specification dictionary import pythoncom specDict = { 'tooltip': '', 'iconpath': '', 'clsid': str(pythoncom.CreateGuid()) } # parse specification from xml.dom.minidom import parse, Element specXML = parse(os.path.join(genPath, specPath)) de = specXML.documentElement for attr in ('name', 'version', 'type', 'paradigm'): specDict[attr] = getattr(de.attributes.get(attr), 'value', None) if specDict[attr] is None: print "Attribute '%s' is missing from 'component' tag." if attr == 'type' and specDict[attr] and specDict[attr] not in ( 'Interpreter', 'Addon'): print "Unrecognized component type. Must be either 'Interpreter' or 'Addon'." specDict[attr] = None if None in specDict.values():
import pythoncom print(pythoncom.CreateGuid()) # returns: {5E685108-CC97-446C-B079-2204C3FF46DC}
j = 0 s = "" while (j < self.rows): s += self.elements[j][i - 1] s += str(delim) j += 1 return s def initialisedStats(self): """After the table/matrix has been initialised provide some basic stats. This function just provides the speech synthesizer with some useful statistics about the newly loaded table or matrix i.e. number of rows and number of columns...""" return "Initialised %d by %d matrix" % (self.rows, self.columns) #Variables required to make this a com object _reg_clsid_ = "{723E7D16-7052-403F-976F-DF68B94BD936}" _reg_progid_ = "latex_access_matrix" _public_methods_ = ["tex_init", "get_cell", "get_row", "get_col"] _public_attrs_ = ["rows", "columns"] #Register the object if __name__ == '__main__': import pythoncom, win32com.server.register matrix._reg_clsid = pythoncom.CreateGuid() matrix._reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER win32com.server.register.UseCommandLine(matrix)
class PythonObjectLibrary: # This will create a GUID to register it with Windows, it is unique. _reg_clsid_ = pythoncom.CreateGuid() # Register the object as an EXE file, the alternative is an DLL file (INPROC_SERVER) _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER # the program ID, this is the name of the object library that users will use to create the object. _reg_progid_ = "Python.APILibrary" # this is a description of our object library. _reg_desc_ = "This is our Python object library." # a list of strings that indicate the public methods for the object. If they aren't listed they are conisdered private. _public_methods_ = ['pullUrlLinks', 'ConvertToJson'] def pullUrlLinks(self, url, ExcRng): ''' Will take a url, fetch the HTML content, find all the 'a' html tags and extract the links to a python list. This list will then be dropped into an Excel range that is specified by the user. :PARA url: The url that will be fetched by the request. :TYPE url: String :PARA ExcRng: The range of data where the links will be dropped, the number of cells in this range will determine how many links come back. :TYPE ExcRng: Excel Range Object ''' # Request the URL, and initialize the list that will store the URLs req = Request(url) html_page = urlopen(req) column_list = [] # Get the HTML content soup = BeautifulSoup(html_page, 'html.parser') # Loop through each of HREF links and store them in the list. for link in soup.findAll('a'): row_list = [] row_list.append(link.get('href')) column_list.append(row_list) # Get our Worksheet, dispatch the range, and define our worksheet. ExcelApp = win32com.client.GetActiveObject("Excel.Application") ExcelRng = win32com.client.dynamic.Dispatch(ExcRng) WrkSht = ExcelApp.ActiveSheet # the number of links is determined my the number of cells in our range. Sort of. NumOfLinks = ExcelRng.Cells.Count # slice the list so we only get the correct number of items. if NumOfLinks > len(column_list): column_list = column_list else: column_list = column_list[0:NumOfLinks] ExcelRng.Value = column_list def ConvertToJson(self, KeyRange, DataRange, DestRange): ''' Will take a range of data and convert it into a JSON string object. :PARA KeyRange: The range data that the contains the keys needed for the JSON object. It is expected to be horizontal. :TYPE KeyRange: Excel Range Object :PARA DataRange: The range of data that contains the values for each key. It is expected to be horizontal. :TYPE DataRange: Excel Range Object :PARA DestRange: A single cell that will be where the JSON string is returned to. :TYPE DestRange: Excel Range Object ''' # get the key values KeyRng = win32com.client.dynamic.Dispatch(KeyRange) KeyVal = KeyRng.Value[0] # get the data values DataRng = win32com.client.dynamic.Dispatch(DataRange) DataVal = DataRng.Value # define the destination range. DestRng = win32com.client.dynamic.Dispatch(DestRange) # initalize the list and dictionary dict_list = [] # loop through each row in the data. for row in DataVal: json_dict = {} # loop through each element in the row for index, element in enumerate(row): json_dict[KeyVal[index]] = element dict_list.append(json_dict) DestRng.Value = str(dict_list) # release objects from memory. KeyRng = None DataRng = None DestRng = None
def util_get_uuid(): return str(pythoncom.CreateGuid()).strip('{}')
def __init__(self): self.handle = 0 self.clsID = pythoncom.CreateGuid() self.IID = pythoncom.MakeIID(self.clsID) self.appID = "pyprogAC" self.AHKAppID = "ahkprogAC"
def new_guid(): import pythoncom guid = str(pythoncom.CreateGuid()) guid = guid[1:-1] # strip of the {}'s return guid
class PythonObjectLibrary: # This will create a GUID to register it with Windows, it is unique and not user friendly ID. _reg_clsid_ = pythoncom.CreateGuid() # Register the object as an EXE file, the alternative is an DLL file (INPROC_SERVER) _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER # The program ID, this is the name of the object library that users will use to create the object. It's also the more User friendly ID _reg_progid_ = "Python.WebScraper" # This is a description of our object library. _reg_desc_ = "This COM Object Server, will allow you to access web scraping functionality found in python." # A list of strings that indicate the public methods for the object. If they aren't listed they are conisdered private. Private methods cannot be accessed. _public_methods_ = [ 'Pull_URL_Links', 'GRABLINKSFROMPAGE_ARRAY', 'GRABLINKSFROMPAGE_LIST' ] def Pull_URL_Links(self, URL_Link, Excel_Dump_Range): ''' This will serve as an Excel array formula, that takes two inputs (URL_Link and Number_Of_Links) and return the number of links from that web page specified in the function. NAME: URL_Link PARA: A valide URL that will redirect to a web page. TYPE: String REQU: True NAME: Excel_Dump_Range PARA: An Excel range, that is passed from VBA to Python. TYPE: Python COM Object REQU: True ''' # Request the URL, and store response. response = requests.get(URL_Link) # Grab the HTML content, and pass it through the parser. soup = BeautifulSoup(response.content, 'html.parser') # Define a list, this will store all the links we want to pass back to Excel. returned_links = [] # find all the Anchor tags ('a'), that have an HREF (href = True) for link in soup.find_all('a', href=True): ''' To make things more complicated, Excel will be expecting an Array back. Here is an example of how we need to build this array. My_Array = [ [], [], [] ] Where the "Outer List" serves as a "Column" and the "Inner Lists" serves as "Rows". ''' # First initalize the "Row". row_list = [] # Add the value to the row row_list.append(link['href']) # Store the row in the "Column", in this case the "Returned Links" list. returned_links.append(row_list) # Get our Worksheet, dispatch the range, and define our worksheet. Excel_Range_to_Dump = win32com.client.dynamic.Dispatch( Excel_Dump_Range) # This method will only return the number of links that is equal to the Range Cell Count, assuming there are enough links to return. Number_Of_Links = Excel_Range_to_Dump.Cells.Count # Make sure to return the right number of links if Number_Of_Links > len(returned_links): # If the number of links to return is greater than the number of links scraped, then return all links. returned_links = returned_links else: # Otherwise, the number of links you scraped is greater then the number of cells in the range, so slice the list. returned_links = returned_links[0:Number_Of_Links] Excel_Range_to_Dump.Value = returned_links def GRABLINKSFROMPAGE_ARRAY(self, URL_Link, Number_Of_Links=1): ''' This will serve as an Excel array formula, that takes two inputs (URL_Link and Number_Of_Links) and return the number of links from that web page specified in the function. NAME: URL_Link PARA: A valide URL that will redirect to a web page. TYPE: String REQU: True NAME: Number_Of_Links PARA: The number of links, that would like returned from the web page. Default is 1, max is 10. If value that is passed through is larger than 10, will return only 10. TYPE: Integer REQU: True ''' # This will ensure only 10 are sent back. if Number_Of_Links > 10: Number_Of_Links = 10 # Request the URL, and store response. response = requests.get(URL_Link) # Grab the HTML content, and pass it through the parser. soup = BeautifulSoup(response.content, 'html.parser') # Define a list, this will store all the links we want to pass back to Excel. returned_links = [] # find all the Anchor tags ('a'), that have an HREF (href = True) for link in soup.find_all('a', href=True): ''' To make things more complicated, Excel will be expecting an Array back. Here is an example of how we need to build this array. My_Array = [ [], [], [] ] Where the "Outer List" serves as a "Column" and the "Inner Lists" serves as "Rows". ''' # First initalize the "Row". row_list = [] # Add the value to the row row_list.append(link['href']) # Store the row in the "Column", in this case the "Returned Links" list. returned_links.append(row_list) # When you grabbed all the links, return the final list to Excel. return returned_links[0:Number_Of_Links] def GRABLINKSFROMPAGE_LIST(self, URL_Link, Number_Of_Links=1): ''' This will serve as an Excel array formula, that takes two inputs (URL_Link and Number_Of_Links) and return the number of links from that web page specified in the function. NAME: URL_Link PARA: A valide URL that will redirect to a web page. TYPE: String REQU: True NAME: Number_Of_Links PARA: The number of links, that would like returned from the web page. Default is 1, max is 10. If value that is passed through is larger than 10, will return only 10. TYPE: Integer REQU: True ''' # This will ensure only 10 are sent back. if Number_Of_Links > 10: Number_Of_Links = 10 # Request the URL, and store response. response = requests.get(URL_Link) # Grab the HTML content, and pass it through the parser. soup = BeautifulSoup(response.content, 'html.parser') # Define a list, this will store all the links we want to pass back to Excel. returned_links = [] # find all the Anchor tags ('a'), that have an HREF (href = True) for link in soup.find_all('a', href=True): ''' To make things more complicated, Excel will be expecting an Array back. Here is an example of how we need to build this array. My_Array = [ [], [], [] ] Where the "Outer List" serves as a "Column" and the "Inner Lists" serves as "Rows". ''' # Store the HREF in the "Returned Links" list. returned_links.append(link['href']) # When you grabbed all the links, return the final list to Excel. return returned_links[0:Number_Of_Links]
def getGUID(): "gets a GUID" return str(pythoncom.CreateGuid())
def preprocessor_from_string(self, input): '''Adds preprocessor entries from a LaTeX string containing \newcommand.''' self.newcommands.translate(input) def preprocessor_write(self, filename): self.preprocessor.write(filename) def preprocessor_read(self, filename): self.preprocessor.read(filename) def activateSettings(self): """Activate the latex-access settings stored in file. Consult the actual function definition in settings.py for details and documentation.""" settings.loadSettings(os.path.expanduser(self.filename)) self.nemeth_translator = settings.brailleTableToUse() return settings.activateSettings({ "braille": self.nemeth_translator, "speak": self.speech_translator, "preprocessor": self.preprocessor }) #Register the object if __name__ == '__main__': import pythoncom, win32com.server.register latex_access_com._reg_clsid_ = pythoncom.CreateGuid() latex_access_com._reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER win32com.server.register.UseCommandLine(latex_access_com)