query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Check if the specified cell is inside a merge box
def insideMergeBox(self, i, j): self.merged_cells = self.r_sheet.merged_cells for crange in self.merged_cells: rlo, rhi, clo, chi = crange if i <= rhi - 1 and i >= rlo and j <= chi - 1 and j >= clo: return True return False
[ "def _cell_in_boundary(self, i_row, i_col):\n return ((i_row, i_col) == self._tl_cell or\n (i_row, i_col) == self._tr_cell or\n (i_row, i_col) == self._bl_cell or\n (i_row, i_col) == self._br_cell or\n (i_row, i_col) in self._ls_cells or\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get type for a given excel style. Style name must be prefixed by 'TL '
def getType(self, style): typematch = re.search('TL\s(.*)',style) if typematch : cellType = typematch.group(1) else : cellType = 'Unknown' return cellType
[ "def get_style_name(style):\n return style_names[style]", "def _getTypeStyle(self, node_type):\n type_name = node_type.nameComponents()[2]\n\n # Get the category name from the node and also check the 'all'\n # category.\n categories = (node_type.category().name(), \"all\")\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether the row 'i' is empty by iterating over all its cells
def isEmptyRow(self, i, colns): for j in range(0,colns) : if not self.isEmpty(i,j): return False return True
[ "def IsEmptyCell(self, row, col): \n\t\treturn False", "def is_empty(self, row, col):\n return self._cells[row][col] != FULL", "def isEmptyColumn(self, j, rowns ):\n for i in range(0,rowns) :\n if not self.isEmpty(i,j):\n return False\n return True", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether the column 'j' is empty by iterating over all its cells
def isEmptyColumn(self, j, rowns ): for i in range(0,rowns) : if not self.isEmpty(i,j): return False return True
[ "def isEmptyRow(self, i, colns):\n for j in range(0,colns) :\n if not self.isEmpty(i,j):\n return False\n return True", "def IsEmptyCell(self, row, col): \n\t\treturn False", "def is_empty(self, row, col):\n return self._cells[row][col] != FULL", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a valid QName from a string or dictionary of names
def getQName(self, names): if type(names) == dict : qname = self.sheet_qname for k in names : qname = qname + '_' + self.processString(names[k]) else : qname = self.sheet_qname + '_' + self.processString(names) self.log.debug(...
[ "def prefixed_to_qname(name, namespaces):\n if not name or name[0] == '{':\n return name\n\n try:\n prefix, name = name.split(':')\n except ValueError:\n if ':' in name:\n raise XMLSchemaValueError(\"wrong format for reference name %r\" % name)\n try:\n uri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a "value" + optional label to the graph for a cell in the source Excel sheet. The value is typically the value stored in the source cell itself, but may also be a copy of another cell (e.g. in the case of 'idem.').
def addValue(self, source_cell_value, altLabel=None): source_cell_value_qname = self.getQName(source_cell_value) #self.graph.add((self.namespaces['scope'][source_cell_value_qname],self.namespaces['qb']['dataSet'],self.namespaces['scope'][self.sheet_qname])) #self.graph.add((self.namespa...
[ "def addData(self, label, value):\n self.__dataPoints__[str(label)] = value", "def addDataCellProperty(self):\n\n if len(self.config.get('dataCell', 'propertyName')) > 0 :\n self.dataCellPropertyName = self.config.get('dataCell', 'propertyName')\n else :\n self.dataCellP...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the currently selected sheet in the workbook, takes no arguments. Iterates over all cells in the Excel sheet and produces relevant RDF Triples.
def parseSheet(self): self.log.info("Parsing {0} rows and {1} columns.".format(self.rowns,self.colns)) self.column_dimensions = {} self.property_dimensions = {} self.row_dimensions = {} self.rowhierarchy = {} # Get dictionary of annotations self.annotati...
[ "def parseWorkbook(workspace,wb):\n # PARSE ALL THE SHEETS IN THE WORKBOOK\n print(\"LOADING WORKBOOK...\")\n for type in repository.getResourceTypes().keys():\n regex = repository.getResourceTypeSheetRegex(type)\n for name in wb.sheetnames:\n if re.match(regex, name, re.IGNORECASE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create relevant triples for the cell marked as HierarchicalRowHeader (i, j are row and column)
def parseHierarchicalRowHeader(self, i, j) : # Use the rowhierarchy to create a unique qname for the cell's contents, # give the source_cell's original value as extra argument self.log.debug("Parsing HierarchicalRowHeader") # Add all the values for (index, ...
[ "def parseRowHeader(self, i, j) :\n rowHeaderValue = \"\"\n\n # Don't attach the cell value to the namespace if it's already a URI\n isURI = urlparse(str(self.source_cell.value))\n if isURI.scheme and isURI.netloc:\n rowHeaderValue = URIRef(self.source_cell.value)\n els...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create relevant triples for the cell marked as RowHeader (i, j are row and column)
def parseRowHeader(self, i, j) : rowHeaderValue = "" # Don't attach the cell value to the namespace if it's already a URI isURI = urlparse(str(self.source_cell.value)) if isURI.scheme and isURI.netloc: rowHeaderValue = URIRef(self.source_cell.value) else: ...
[ "def parseHierarchicalRowHeader(self, i, j) :\n \n # Use the rowhierarchy to create a unique qname for the cell's contents, \n # give the source_cell's original value as extra argument\n self.log.debug(\"Parsing HierarchicalRowHeader\")\n \n # Add all the values\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create relevant triples for the cell marked as Header (i, j are row and column)
def parseColHeader(self, i, j) : cell_content = self.processString(self.source_cell.value) if self.isEmpty(i,j): if self.insideMergeBox(i,j): k, l = self.getMergeBoxCoord(i,j) # If we are in a vertical merge box, skip adding the dimension ...
[ "def CreateHeaderCell(ws1, numConcepts, y, value, count):\n ws1.merge_cells(start_row=y, start_column=2, end_row=y, end_column=2 + numConcepts - 1)\n\n c = ws1.cell(row=y, column=2)\n c.value = value\n thin = Side(border_style=\"thin\", color=\"000000\")\n b = Border(top=thin, left=thin, right=thin, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create relevant triples for the cell marked as Property (i, j are row and column)
def parseRowProperty(self, i, j) : if self.isEmpty(i,j): if self.insideMergeBox(i,j): k, l = self.getMergeBoxCoord(i,j) self.source_cell_value_qname = self.addValue(self.r_sheet.cell(k,l).value) else: return else: self.s...
[ "def copy_cell_properties_from_wt_to_voronoi( wt, voronoi, properties ):\n for i in properties:\n try:\n for j in voronoi:\n if j.cell_id != -1:\n #print wt._cell2properties[j.cell_id]\n j.__setattr__( i, wt.cell_property(j.cell_id, i) )\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create relevant triples for the cell marked as Title (i, j are row and column)
def parseTitle(self, i, j) : self.graph.add((self.namespaces['scope'][self.sheet_qname], self.namespaces['tablink']['title'], Literal(self.source_cell.value))) return
[ "def createTitle(ws1, numConcepts, row):\n ws1.merge_cells(start_row=row, start_column=2, end_row=row, end_column=2 + numConcepts - 1)", "def create_cells(self):\n count = 1\n for i in range(10):\n temp = []\n for j in range(10):\n temp.append(Cell(self.win, (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create relevant triples for the cell marked as Data (i, j are row and column)
def parseData(self, i,j) : if self.isEmpty(i,j) and self.config.get('dataCell', 'implicitZeros') == '0': return # Use the fully qualified name of the cell for the resource name observation = self.namespaces['scope'][self.source_cell_qname] # It's an observa...
[ "def generate_cell_data(self):\n self.cell_data_store = {}\n self.cell_data = {\n \"1\":\n {\n 'p': 11,\n 'v': 6,\n 'a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create relevant triples for the annotation attached to cell (i, j)
def parseAnnotation(self, i, j) : if self.config.get('annotations', 'model') == 'oa': # Create triples according to Open Annotation model body = BNode() self.annotationGraph.add((self.annotationNamespaces['scope'][self.source_cell_qname], ...
[ "def _annotation_cell2(self, table, row, column):\n element = dict()\n c = table.cellAt(row, column)\n start = int(c.firstCursorPosition().position())\n end = int(c.lastCursorPosition().position())\n #try:\n element['id'] = c.format().anchorNames()[0]\n #except:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return True/False Accepts a list of number. Check each of them for pairwise primality against the last number in the list. Presumably the numbers other than the last have been checked together already as they were added to the group
def pair_check_last(pgroup): if len(pgroup) < 2: return True #only one number, we're all good p2 = pgroup[-1] for p1 in pgroup[:-1]: # concatenate the two numbers x = concatenate_number(p1,p2) y = concatenate_number(p2,p1) if not is_prime(x) or not is_prime(y): ...
[ "def pairwise_coprime(listing:list):\n\n assert isinstance(listing, list)\n \n size=len(listing)\n \n for i in range(0, size-1):\n for j in range(i+1, size):\n if not coprime(listing[i], listing[j]) : return False\n \n return True", "def pairwise_coprime(listing: list):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Factory function to create a Scanner Object. Creates the appropriate Scanner based on the type of "function".
def Scanner(function, *args, **kwargs): if SCons.Util.is_Dict(function): return Selector(function, *args, **kwargs) return ScannerBase(function, *args, **kwargs)
[ "def __init__(self, scanner):\n self.scanner = scanner", "def create_scanner(self,fp):\n\n\t\t# define some pattern constructs\n\t\tletter = plex.Range(\"AZaz\")\n\t\tdigit = plex.Range(\"09\")\n\n\t\tvariable = letter + plex.Rep(letter | digit)\n\t\ttrue = plex.NoCase(plex.Str(\"true\",\"t\",\"1\")) \n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct a new scanner object given a scanner function.
def __init__( self, function, name="NONE", argument=_null, skeys=_null, path_function=None, # Node.FS.Base so that, by default, it's okay for a # scanner to return a Dir, File or Entry. node_class=SCons.Node.FS.Base, node_factory=None, ...
[ "def Scanner(function, *args, **kwargs):\n if SCons.Util.is_Dict(function):\n return Selector(function, *args, **kwargs)\n\n return ScannerBase(function, *args, **kwargs)", "def __init__(self, scanner):\n self.scanner = scanner", "def create_scanner(self,fp):\n\n\t\t# define some pattern con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a skey to the list of skeys
def add_skey(self, skey): self.skeys.append(skey)
[ "def add_key(self, key: str) -> None:\n self._keys.add(key)", "def _newKey(self, key):\n self._testKeySubNsAdd()\n self._getKeyList().append(key)", "def add_key(self, key_list: list) -> None:\n\n for key, funct, desc in key_list:\n # Force keys to be lowercase\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A zombie contaminate an entity (a human)
def contaminate_human(self, zombie, entity, contagion): zombie.remove_contagion() self._entities['humans'].remove(entity) # First, remove from humans list entity.create_zombie(zombie._team, contagion) # Create the zombie self.add_zombie(entity) # Add the zombie to correct lists
[ "def make_zombie(pavement='bottom'):\n global zombies\n direction = random.choice(['l', 'r'])\n if len(zombies) < max_zombies:\n new_zombie = Actor('zombie1')\n new_zombie.direction = direction\n new_zombie.frame = 1\n if pavement == 'bottom':\n new_zombie.top = rows[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if _berzerk == 0, return True, otherwise False and decrement _berzerk
def explode_berzerk(self): if self._berzerk == 0: return True else: self._berzerk -= 1 return False
[ "def __bool__(self):\n return self.balance > 0", "def bust(person):\n if person.total > GOAL_TOTAL() and person.aceCount == 0:\n return True\n elif person.total > GOAL_TOTAL() and person.aceCount > 0:\n adjust_ace(person)\n return person.total > GOAL_TOTAL()\n else: # person...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save the chosen inline result.
def handle_chosen_inline_result(bot, update, session, user): print('yey') result = update.chosen_inline_result [search_id, file_id] = result.result_id.split(':') inline_search = session.query(InlineSearch).get(search_id) inline_search.sticker_file_id = file_id
[ "def save_results(self):\n raise NotImplementedError", "def save_result(self):\n self.print_to_console()", "def SaveResult(self):\n return self._SaveResult", "def save(self, output, data):\n return", "def save_output(self):\n pass", "def save(self, output, data):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate Docker packager context for templates
def _generate_template_context(arguments: PackagingResourceArguments, manifest: OdahuProjectManifest, output_folder: str) -> DockerTemplateContext: logging.info('Building context for template') return DockerTemplateContext( model_name=manife...
[ "def containerTemplate(*args, **kwargs):\n\n pass", "def generate_dockerfile():\n # pylint: disable=global-statement\n global DOCKERFILE_TEMPLATE_FILE_NAMES\n\n missing = []\n if not configuration.EXTRACTOR_NAME:\n missing.append(\"Extractor name\")\n if not configuration.AUTHOR_NAME:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
contact BigCommerce to get a list of all statuses
def statuses(self): big = BigCommerceAPI() response = big.get('orderstatuses') return response.text
[ "def get_statuses(cls, joblist):\n ...", "def get_book_statuses() -> list:\n return data.get_book_statuses()", "def statuses(self):\n return self._get_paged(\"statuses\")", "def test_get_account_status_all_using_get(self):\n pass", "def get_statuses(cls) -> Type[TextChoices]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
IoU Loss for individual examples inputs N x Classes x H x W target_oneHot N x Classes x H x W
def forward(self, inputs, target_oneHot): N = inputs.size()[0] # predicted probabilities for each pixel along channel inputs = F.softmax(inputs, dim=1) # Numerator Product inter = inputs * target_oneHot # Sum over all pixels N x C x H x W => N x C inter = inter...
[ "def instance_embedding_iou_loss(embedding,\n instance_labels,\n num_samples,\n similarity_strategy='dotproduct'):\n embedding_shape = tf.shape(embedding)\n height = embedding_shape[0]\n width = embedding_shape[1]\n dim...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an increasing list of failure times, quantify the stability of the activity. A single failure, 10 seconds in the past, has a stability factor of 0.5; if there were additional failures before that, the stability factor will be lower. Returns a culled list of stop times and a stability factor (0 1).
def stability_factor(times, window=120): now = time.time() if len(times) == 0: return times, 1. # Only keep the last few failures, within our time window. times = [t for t in times[-200:-1] if t >= now - window] + times[-1:] dt = [5. / (now - t) for t in times] return times,...
[ "def staleness_scaled(T, clock) -> float:\n return (clock - T) / clock", "def time_to_failure():\n if not useWeibull:\n nextFailure = int(random.expovariate(BREAK_MEAN))\n else:\n # The Weibull distr. generates many errors.\n nextFailure = int(np.random.weibull(WEIBULL_K)*10.0) + MTB...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update self.status based on service info (in format returned by parse_docker_state).
def update(self, service): self.service.update(service) if service['running']: self.status = None, time.time() else: self.status = service['exit_code'], time.time()
[ "def service_status(self, service_status):\n\n self._service_status = service_status", "def service_status(self, **kwargs):\n return self.call_api(\n \"GET\", self.status_endpoint, params={\"format\": \"json\"}, **kwargs\n )", "def run_status() -> None:\n\n # retrieve stat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Analyze a dockercompose.yaml file to get a list of services. Using dockercompose ps and docker inspect, determine whether each service is running or not. Use docker_compose_bin to pass in the full path to the dockercompose executable.
def parse_docker_state(docker_compose_file, docker_compose_bin=None): summary = {} compose = yaml.safe_load(open(docker_compose_file, 'r')) for key, cfg in compose.get('services', []).items(): summary[key] = { 'service': key, 'running': False, 'exit_code': 127, ...
[ "def find_docker_compose_services():\n dir_list = os.listdir(BASE_DIR)\n directories = [d for d in dir_list if os.path.isdir(os.path.join(BASE_DIR, d))]\n\n return [d for d in directories if 'docker-compose.yml' in os.listdir(os.path.join(BASE_DIR, d))]", "def start_docker_compose_services():\n try:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize order from json request.
def __init__(self, order_json): self.shop = order_json['shop'] self.size = order_json['size'] self.customer_name = order_json['name'] self.drink_name = order_json['drink'] self.customer_number = order_json['customer_number'] self.location = order_json['location'] ...
[ "def from_json(cls, data: Dict[str, Any]) -> \"InFlightOrder\":\n order = InFlightOrder(\n client_order_id=data[\"client_order_id\"],\n trading_pair=data[\"trading_pair\"],\n order_type=getattr(OrderType, data[\"order_type\"]),\n trade_type=getattr(TradeType, data[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Output accounts (Working accounts and bad accounts) to a HTML file with information of the account.
def Save_html(self, accounts): try: self.extension = ".html" colors.info("Saving as HTML in {}{}".format(self.file, self.extension)) SpotifyFree = [] SpotifyPremium = [] PremiumFamily = [] AdminPremiumFamily = [] BadAccounts ...
[ "def write_out_account_numbers_and_balances(list_of_all_accounts_known):\n with open('./practise_accounts.txt', mode='wt') as accounts_and_balances_to_write_out:\n for accounts in list_of_all_accounts_known:\n accounts_and_balances_to_write_out.writelines('{0} {1}\\n'.format(account...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Output accounts (Working accounts and bad accounts) to a XML file with information of the account.
def Save_xml(self, accounts): try: self.extension = ".xml" colors.info("Saving as XML in {}{}".format(self.file, self.extension)) Main = ET.Element("SpotCheck") SpotifyFree = ET.SubElement(Main, 'SpotifyFree') SpotifyPremium = ET.SubElement(Main, '...
[ "def createXML(whatToCreate):\n\n XMLSerializer = serializers.get_serializer(\"xml\")\n xml_serializer = XMLSerializer()\n if whatToCreate == \"allAccount\":\n path_fullToOutputFile = os.path.join(settings.PDF_OUTPUT_ROOT, \"accounts.xml\")\n objectsToSerialize = Account.o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ouput accounts (Working accounts and bad accounts) to a JSON file with information of the account.
def Save_json(self, accounts): try: self.extension = ".json" colors.info("Saving as JSON in {}{}".format(self.file, self.extension)) json = {} json["Spotify Free"] = [] json["Spotify Premium"] = [] json["Premium Family"] = [] ...
[ "def export_accounts(self):\n print('=== Exporting all account data...')\n\n for account in self.client.tenant.accounts:\n print('- Exporting account:', account.email)\n\n json = {\n 'id': self.get_id(account),\n 'href': account.href,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Output only the working accounts to a TXT file with information of the account.
def Save_txt(self, accounts): self.extension = ".txt" self.sep = "<--------Account-------->\n" colors.info("Saving as TXT in {}{}".format(self.file, self.extension)) try: with open(self.file + self.extension, "a") as output_: for account in accounts: ...
[ "def write_out_account_numbers_and_balances(list_of_all_accounts_known):\n with open('./practise_accounts.txt', mode='wt') as accounts_and_balances_to_write_out:\n for accounts in list_of_all_accounts_known:\n accounts_and_balances_to_write_out.writelines('{0} {1}\\n'.format(account...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select the best candidate pagenumber for the given page, with reference to neighboring pages. 'pages' must be a windowed_iterator; 'window', if provided, will look to a smaller set of neighboring pages to determine a likely page number. (Smaller than that provided by the given windowed_iterator.)
def guess_best_pageno(pageinfo, pages, window=None): if window is None: window = pages.window def tally(pageinfo, current_index, sofar, weight): for c in pageinfo.info['pageno_candidates']: if c.offset >= current_index: continue if c.offset not in sofar[c....
[ "def define_page_range(current_page, total_pages, window=6):\n # maximum length of page range is window + 1\n maxlen = window + 1\n page_range = deque(maxlen=maxlen)\n\n # minimum possible index is either: (current_page - window) or 1\n window_start = (current_page - window) if (current_page - window...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
先遍历一遍链表,克隆 label 和 next 的信息,random 信息放到第二次遍历设置
def Clone(self, pHead): newHead = None p, q = pHead, None map = {} while p: t = RandomListNode(p.label) if not newHead: newHead = t else: q.next = t # 保存映射关系 map[p] = t p = p.next ...
[ "def copyRandomList(self, head: 'Node') -> 'Node': \n map_new = collections.defaultdict(lambda: Node(None, None, None))\n map_new[None] = None # if a node's next or random is None, their value will be None but not a new Node, doing so removes the if-else check in the while loop\n \n nd_o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate server & server_ip_address MDC fields
def default_server_info(): # If not set or purposely set = None, then set default if MDC.get('server') is None: try: server = socket.getfqdn() except Exception: try: server = socket.gethostname() except Exception: server = '' ...
[ "def _create_server(self):\n server = super()._create_server(networks='none')\n source_host = server['OS-EXT-SRV-ATTR:host']\n target_host = 'host2' if source_host == 'host1' else 'host1'\n return server, source_host, target_host", "def populate_default_mdc(request):\n if MDC.get(\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate MDC fields given a request in json format
def mdc_from_json(request_json): if MDC.get("instanceUUID") is None: default_mdc() MDC.put('requestID', get_request_id(request_json)) MDC.put('partnerName', get_partner_name(request_json))
[ "def populate_mdc(request):\n populate_default_mdc(request)\n req_id = request.headers.get('X-ONAP-RequestID', g.empty_value)\n request_json = request.get_json()\n if req_id == g.empty_value:\n req_id = get_request_id(request_json)\n g.request_id = req_id\n MDC.put('requestID', req_id)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate default MDC fields given the request
def populate_default_mdc(request): if MDC.get("instanceUUID") is None: default_mdc() g.request_start = time.process_time() g.empty_value = "EMPTY" g.request_id = MDC.get("requestID") MDC.put('serviceName', request.path) MDC.put('IPAddress', request.headers.get('X-Forwarded-Fo...
[ "def populate_mdc(request):\n populate_default_mdc(request)\n req_id = request.headers.get('X-ONAP-RequestID', g.empty_value)\n request_json = request.get_json()\n if req_id == g.empty_value:\n req_id = get_request_id(request_json)\n g.request_id = req_id\n MDC.put('requestID', req_id)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate MDC fields from the request headers
def populate_mdc(request): populate_default_mdc(request) req_id = request.headers.get('X-ONAP-RequestID', g.empty_value) request_json = request.get_json() if req_id == g.empty_value: req_id = get_request_id(request_json) g.request_id = req_id MDC.put('requestID', req_id) MDC.put('par...
[ "def _make_request_headers(self, access_token):\n return {'Authorization': 'Bearer %s' % access_token}", "def add_headers():\n # the actual access token -\n g.x_tapis_token = request.headers.get('X-Tapis-Token')\n\n # the tenant associated with the subject of the request; used, for instance, when ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the request_id from the request
def get_request_id(request_json): request_id = request_json['requestInfo'].get('requestId') if not request_id: request_id = request_json['requestInfo'].get('requestID') return request_id
[ "def request_id(self):\n return self._request_id", "def get_request_id():\n try:\n return id(request._get_current_object())\n except:\n return 0", "def request_id(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"request_id\")", "def get_request_id(self, reque...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set errorCode and description
def set_error_details(code, desc): MDC.put('errorCode', code) MDC.put('errorDescription', desc)
[ "def error_1(self, id, errorCode, errorMsg):", "def error_desc(self, error_desc):\n\n self._error_desc = error_desc", "def err_code(self, err_code):\n\n self._err_code = err_code", "def __init__(self, error_code, error_message):\n self.error_code = error_code\n self.error_message =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
プロジェクト索クエリを修正する。 ``user_id`` から ``account_id`` に変換する。 ``except_user_id`` から ``except_account_id`` に変換する。 ``page`` , ``limit``を削除」する
def _modify_project_query(self, organization_name: str, project_query: Dict[str, Any]) -> Dict[str, Any]: def remove_key(arg_key: str): if arg_key in project_query: logger.info(f"project_query から、`{arg_key}` キーを削除しました。") project_query.pop(arg_key) remove_key...
[ "def fix_account(self, account):\n pass", "def test_account_invalid_user_unfollow(self):\n url = reverse('user-account-follow', args=('invalid_user',))\n self.token_login()\n request = self.c.delete(path=url, content_type='application/json',\n **self.clie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Break PPDDL into tokens (brackets, nonbracket chunks)
def _ppddl_tokenize(ppddl_txt): # strip comments lines = ppddl_txt.splitlines() mod_lines = [] for line in lines: try: semi_idx = line.index(';') except ValueError: pass else: line = line[:semi_idx] mod_lines.append(line) ppddl_txt ...
[ "def _tokenize_pddl(contents: str) -> Iterator[str]:\n last_token = \"\"\n for c in contents:\n if c in [\" \", \"\\n\", \"\\t\"]:\n if last_token:\n yield last_token\n last_token = \"\"\n elif c in [\"(\", \")\"]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a HList back into tokens (either single open/close parens or nonparen chunks)
def _hlist_to_tokens(hlist): tokens = ['('] for item in hlist: if isinstance(item, HList): tokens.extend(_hlist_to_tokens(item)) else: assert isinstance(item, str), "Can't handle item '%r'" % (item, ) tokens.append(item) tokens.append(')') return token...
[ "def parse(tokens: list):\n tmp: list = [Expression(True)]\n tmp[0].term = Term.parse(tokens)\n if len(tokens) == 0:\n return tmp[0]\n t: str = tokens[0]\n while len(tokens) > 0 and (t == \"+\" or t == \"-\"):\n del tokens[0]\n tmp.append(Expressio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract HLists representing PDDL for domain & problem from a collection of PDDL files & a problem name.
def extract_domain_problem(pddl_files, problem_name=None): domains, problems = extract_all_domains_problems(pddl_files) # retrieve hlist for problem & figure out corresponding domain if problem_name is None: problem_names = list(problems.keys()) if len(problem_names) != 1: raise...
[ "def get_pddl(expdir, parentdir = \"domains\"):\n \n domains = glob.glob(parentdir + f\"/**/{args.domain}\", recursive = True)\n problems = glob.glob(parentdir + f\"/**/{args.problem}\", recursive = True)\n myprint(f'\\nStep 1: Prepare input pddl files in experiment directory {parentdir}\\n Found domai...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract a domain name from a single PDDL domain file.
def extract_domain_name(pddl_path): assert isinstance(pddl_path, str), \ "this only takes a single (string) filename" domains, _ = extract_all_domains_problems([pddl_path]) assert len(domains) == 1, \ "PDDL file at '%s' contains %d domains (not 1); they are %s" \ % (pddl_path, len(do...
[ "def _parse_domainname():\n return _parse_resolve().get(\"domain\", \"\")", "def extract_domain_problem(pddl_files, problem_name=None):\n domains, problems = extract_all_domains_problems(pddl_files)\n\n # retrieve hlist for problem & figure out corresponding domain\n if problem_name is None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create modified hlist for problem that has old init atoms replaced with new set of init atoms.
def replace_init_state(problem_hlist, new_init_atoms): # check format for new atoms assert isinstance(new_init_atoms, (tuple, list)) for atom in new_init_atoms: # make sure atoms have the right format (they should all be paren-free, # which is the same format used when interfacing with SSiPP...
[ "def _rehash(self):\n\n # Create a new larger table.\n origTable = self._table\n newSize = len(self._table) * 2 + 1\n self._table = Array(newSize)\n # Modify the size attributes.\n self._count = 0\n self._maxCount = newSize - newSize // 3\n\n # Add the keys fr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Factory method for creating a list of datasets based on the provided config.
def create_datasets(cls, dataset_config, phase): raise NotImplementedError
[ "def create_dataset(self, config, rng):\n raise NotImplementedError()", "def get_dataset(config):\n\n if config['dataset'] == 'cifar':\n data_dir = '../data/cifar/'\n apply_transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterates over a given ndim dataset patchbypatch with a given stride and builds an array of slice positions.
def _build_slices(dataset, patch_shape, stride_shape): slices = [] if dataset.ndim == 4: in_channels, i_z, i_y, i_x = dataset.shape else: i_z, i_y, i_x = dataset.shape k_z, k_y, k_x = patch_shape s_z, s_y, s_x = stride_shape z_steps = SliceBuilder...
[ "def _build_slices(dataset, patch_shape, stride_shape):\n slices = []\n i_z, i_y, i_x = dataset.shape\n k_z, k_y, k_x = patch_shape\n s_z, s_y, s_x = stride_shape\n z_steps = SliceBuilder._gen_indices(i_z, k_z, s_z)\n for z in z_steps:\n y_steps = SliceBuilder._g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns dictionary containing the training and validation loaders (torch.utils.data.DataLoader).
def get_train_loaders(config): assert 'loaders' in config, 'Could not find data loaders configuration' loaders_config = config['loaders'] logger.info('Creating training and validation set loaders...') # get dataset class dataset_cls_str = loaders_config.get('dataset', None) if dataset_cls_str ...
[ "def get_train_val_loaders():\n dataloaders = {\n x: DataLoader(\n get_train_val_datasets()[x], batch_size=TRAIN_BATCH_SIZE, shuffle=True, num_workers=TRAIN_NUM_WORKERS\n )\n for x in [\"train\", \"val\"]\n }\n return dataloaders", "def getDataLoaders(self):\r\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Forces the kernel to forget any internal state
def reset(self): # we can have stateful kernels now raise NotImplementedError()
[ "def soft_reset() -> NoReturn:", "def soft_reset() -> None:\n ...", "def _recover_state(self):", "def context_reset(self):\n self._context_state = None\n logging.info('Resetting the context')", "def resetDeviceStates(self):", "def unwatch(self):\n pass", "def soft_reset(self, **kwargs):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Junction table between track and tag
def create_table_track_tag(): db, cursor = connect_db() sql = """CREATE TABLE track_tag( id INT PRIMARY KEY AUTO_INCREMENT, track CHAR(50), listeners INT, tag CHAR(80))""" if not table_exists('track_tag'): cursor.execute(sql) db.close()
[ "def relabel_trackID(label_table):\n\n dic = {}\n ori = list(np.unique(label_table['trackId']))\n for i in range(1, len(ori) + 1):\n dic[ori[i - 1]] = i\n dic[0] = 0\n for i in range(label_table.shape[0]):\n label_table.loc[i, 'trackId'] = dic[label_table['trackId'][i]]\n label_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Comment table, each track can have many comments
def create_table_comment(): db, cursor = connect_db() sql = """CREATE TABLE comment( id INT PRIMARY KEY AUTO_INCREMENT, content TEXT NOT NULL, track CHAR(50), FOREIGN KEY (track) REFERENCES track(mbid_track) ON DELETE CASCADE ON UPDATE CASCADE) ...
[ "def comments(table='None',record_id=None):\n return LOAD('plugin_wiki','comment',\n args=(table,record_id or 0),ajax=True)", "def process_comments(session, comments):\n for c in tqdm(comments, desc=\"Injecting comments into DB\"):\n db_comment = session.query(Comment).get(c['i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Executes on 'inst = extension(__file__)', once the FuncExtension class is instantiate, overwrite the __init__() method and add the instance into lifecycle hooks.
def __call__(cls, *args, **kwargs): scope = ExtensionMeta._get_extension_scope(cls) # Only register function extension here if scope is ExtensionScope.FUNCTION: instance = super(ExtensionMeta, cls).__call__(*args, **kwargs) ExtensionMeta._register_function_extension(inst...
[ "def init_extension(self, ext, *args, **kwargs):\n return ext.init_app(self, *args, **kwargs)", "def test_extension_registration(self):\n class NewExtensionBeforeInvocation(FuncExtensionBase):\n def __init__(self, file_path: str):\n super().__init__(file_path)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the scope of an extension
def _get_extension_scope(cls, extension) -> ExtensionScope: return getattr(extension, '_scope', ExtensionScope.UNKNOWN)
[ "def get_scope(self) -> str:\n return self.get_value(\"scope\") or \"\"", "def get_scope(self, ):\n return self.attrs.get(self.AttributeNames.SCOPE, None)", "def scope(self):\n return self._scope", "def scope(self) -> Sequence[str]:\n return pulumi.get(self, \"scope\")", "def sco...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract feature of the article.
def extract_feature(self, article) : pass
[ "def extractFeatures(self, datum):\n abstract", "def get_article_features(self, article_id):\n return self.article_features[article_id]", "def feature_extractor():\n pass", "def extract_features(self):\n self.extract_features_static()\n self.extract_features_dynamic()", "def e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serve qwerty.sh file as requested. URL path indicates git ref to serve, defaulting to current HEAD.
def serve_qwerty(environ): if not valid_request(environ): return ( # HTTP Status '400 BAD REQUEST', # HTTP Response Headers (('Content-Type', 'text/plain'),), # WSGI Body string_response(SHELL_BAD_REQUEST)) req_ref = parse_ref(en...
[ "def serve_content(self, path, method=\"GET\"):\n if path.path in (\"\", \"/\"):\n temp = \"/\" + self.main_page()\n self.do_redirect(temp)\n\n else:\n params = parse_qs(path.query)\n params[\"__path__\"] = path\n # here you might want to look int...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse URL which has a git ref.
def parse_ref(url_path): ref = url_path.lstrip('/') if not ref: ref = os.environ.get('DEFAULT_GIT_REF', 'HEAD').strip() return ref
[ "def parse_url(ref):\n url = urlparse(ref)\n return Url(\n scheme=url.scheme,\n auth=Auth(url.username, url.password),\n host=Host(url.hostname, url.port),\n path=Path(url.path, url.query),\n hash=url.fragment\n )", "def code_giturl_parse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List of remote names as returned by `git remote`.
def git_remote(**kw): return sh('git', 'remote', **kw).strip().split('\n')
[ "def remote_names(self):\n return [x.name for x in self.repo.remotes]", "def remotes():\n result = []\n for l in run([\"-v\"]).splitlines():\n name, url, role = l.split()\n if \"fetch\" in role:\n result.append([name, url])\n return result", "def getRemotes(directory):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run `git revparse short` on given ref, return stdout.
def git_rev_parse(ref, **kw): return sh('git', 'rev-parse', '--short', ref, **kw).strip()
[ "def rev_parse(commit_ish, short=False):\n args = [\"--short\"] if short else []\n return (\n subprocess.check_output([\"git\", \"rev-parse\"] + args + [commit_ish])\n .decode()\n .strip()\n )", "def cmd_get_sha(ref):\n return ['git', 'rev-parse', ref]", "def sha1(f=None, short=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Provide file content at given ref (via `git show`). Accept a projectspecific ref 'DIRTY' which requests file content within the working tree, whether the file matches HEAD or is modified/dirty. When GIT_DIR is in use, the working tree may not be known. Therefore, an environment variable QWERTY_SH specifies where to fin...
def git_show(ref, filepath, **kw): if ref == DIRTY and filepath == 'qwerty.sh': return sh('cat', os.environ.get('QWERTY_SH', filepath), **kw) return sh('git', 'show', '{ref}:{filepath}'.format(**locals()), **kw)
[ "def show(reference, path, directory=None):\n # Check to see if this is a directory\n dirs = ls_tree(reference, path, directory)\n if dirs is not None:\n return dirs\n # Otherwise a file or does not exist, check for the file\n cmd = 'git show {0}:{1}'.format(reference, path)\n # Check to se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Counts the number of times a given character occurs in the sequence.
def count(self, char): return self._sequence.count(char)
[ "def count_chars(entry, char):\r\n\r\n pos = 0\r\n count = 0\r\n while pos < len(entry):\r\n if entry[pos] == char:\r\n count = count + 1\r\n pos = pos + 1\r\n return count", "def count_chars(text: str, char_to_count: str) -> int:\n count = 0\n for char in text:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Counts the number of times a given codon occurs in the sequence.
def count_codon(self, codon): return sum([1 for c in self if c == codon])
[ "def CountCodonOccurrences(seqs, icodon, codons):\n counts = dict([(codon, 0) for codon in codons])\n n = len(seqs[0][1])\n assert n % 3 == 0\n assert 1 <= icodon <= n / 3\n for (head, seq) in seqs:\n assert len(seq) == n\n seqcodon = seq[3 * (icodon - 1) : 3 * icodon]\n for codo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Follow the given line along our raster data (which contains the height), and return an elevation profile based on this data. This "line following" can be done using the following SQL Common Table
def generate_elevation_profile(line): elem = from_shape(line, 4326) line_cte = db.session.query( func.ST_Transform(elem, 28992).label("geom")).cte(name="line") cells_cte = db.session.query( # Get the centroid of the cell which intersects our line func.ST_Centroid( #...
[ "def extract_profile(tif, line_file, ds):\r\n\r\n import numpy as np\r\n import gdal\r\n import fiona\r\n from scipy.interpolate import interp1d\r\n# from scipy.interpolate import interp2d\r\n from scipy.ndimage import map_coordinates\r\n \r\n #%% Create evenly spaced points\r\n # Read co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to get last customer_id from dimemsion table `dimCustomer`
def get_dimCustomer_last_id(db_engine): query = "SELECT max(customer_id) AS last_id FROM dimCustomer" tdf = pd.read_sql(query, db_engine) return tdf.iloc[0]['last_id']
[ "def select_cust_id(**kwargs):\n db = kwargs.get('db')\n try:\n query = \"\"\"\n SELECT\n MAX(CUST_ID)\n FROM\n CUST_INFO\n \"\"\"\n db.check_alive()\n db.cursor.execute(query)\n results = db.cursor.fetchall()\n if r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to extract table `customer`
def extract_table_customer(last_id, db_engine): if last_id == None: last_id = -1 query = "SELECT * FROM customer WHERE customer_id > {} LIMIT 100000".format( last_id) return pd.read_sql(query, db_engine)
[ "def table_info(self):\n for customer in self.customers:\n print(customer.get_name())", "def return_all_customer_info():\n all_customer_records = Customer.select()\n\n\n\n for persion in all_customer_records:\n print(f\"Customer id: {person.customer_id}\\nFirst Name: {person.first_n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to lookup table `city`
def lookup_table_city(address_df, db_engine): unique_ids = list(address_df.city_id.unique()) unique_ids = list(filter(None, unique_ids)) query = "SELECT * FROM city WHERE city_id IN ({})".format( ','.join(map(str, unique_ids))) return pd.read_sql(query, db_engine)
[ "def gettraincity(cityname):\n if cityname.upper() in citytotrainmap.keys():\n return citytotrainmap[cityname.upper()]\n return cityname", "def load_cities_table():\n cities = {}\n with open(str(BASE_DIR.joinpath('cidades.csv'))) as cities_file:\n for code, city, _ in (c.split(';') for c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to lookup table `country`
def lookup_table_country(address_df, db_engine): unique_ids = list(address_df.country_id.unique()) unique_ids = list(filter(None, unique_ids)) query = "SELECT * FROM country WHERE country_id IN ({})".format( ','.join(map(str, unique_ids))) return pd.read_sql(query, db_engine)
[ "def get_countries(datasource=world_trade_data.defaults.DEFAULT_DATASOURCE):\n table = get_referential('country', datasource=datasource)\n table = table.set_index('iso3Code')[\n ['name', 'notes', 'countrycode', 'isreporter', 'ispartner', 'isgroup', 'grouptype']]\n\n return table", "def __country(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively tries all valid moves until a dead end or vault is reached. If the vault is reached, the successful path is appended to the list of successful paths to be later tested for the shortest item.
def next_step(x, y, path): # Terminate if we're at the vault if x == 3 and y == 3: paths.append(path) return # Not at the vault, so figure out where we can go valids = get_valid_moves(x, y, path) # Try all the valid moves. if 'U' in valids: next_step(x, y - 1, path + 'U') if 'D' in...
[ "def path_check(focal_unit, modifier = 0):\n # need to boil for loops down to a recursive function\n\n global valid_moves\n global first_loop\n global first_turn\n global loop_counter\n\n if first_loop == 0:\n first_loop += 1\n del valid_moves[:]\n if first_turn == True:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change ligand format from pdb to mae. Command e.g. $SCHRODINGER/utilities/structconvert imae gold_5HT2B_1106_0001_receptor_prep.mae omol2 gold_5HT2B_1106_0001_lreceptor_prep.mol2
def ChangeFormattoMol2(self): print "coverting" mainExecutablePath = os.path.join(self.Program_path,"utilities/structconvert") outputLigName = FileManager().changeExtention(os.path.basename(DockParams.glideRecAdd),".mol2") outputFile = os.path.join(self.ouPutDir,outputLigName) #if the file is already ther...
[ "def edit_pdb(in_origin, out_origin):\n # set the origins of the pdb as specified in input\n # this is necessary due to the ALIGN and RMSD columns having different\n # default values when produced by VMD and Gromacs\n origins = {\"IN\":in_origin, \"OUT\":out_origin}\n for state in [\"IN\", \"OUT\"]:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inventor Document Object Open the specified Inventor document. Check document type and bind the document COM object to the associate class in the wrapper.
def _load_document(path, app): start_inventor() document_type_enum = { 12289: 'UnnownDocument', 12290: 'PartDocument', 12291: 'AssemblyDocument', 12292: 'DrawingDocument', 12293: 'PresentationDocument', 12294: 'DesignElementDocument...
[ "def load_document_type(doctype, *args, **kwargs):\n cls_name = \"%sDocument\" % doctype.upper()\n cls = getattr(importlib.import_module(\"cosrlib.document.%s\" % doctype), cls_name)\n return cls(*args, **kwargs)", "def open_doc(data_file: adsk.core.DataFile):\n app = adsk.core.Application.get()\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Export file Publish file into the export directory using the Inventor translator addin. Can export files such as; dwf, dxf, dwg, pdf, iges & step.
def export_to(self, subdir, filetype='pdf'): file = self.partcode + '.' + filetype path = self.export_dir.joinpath(subdir).joinpath(file) print(str(path)) self.doc.SaveAs(str(path), True)
[ "def export(request, project_slug):\n project = Project.objects.live().get(user=request.user, slug=project_slug)\n os.chdir(project.doc_path)\n dir_path = os.path.join(settings.MEDIA_ROOT, 'export', project.user.username)\n zip_filename = '%s.zip' % project.slug\n file_path = os.path.join(dir_path, z...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Close Document Close current Inventor document without saving.
def close(self): self.doc.Close(SkipSave=True)
[ "def close( self ):\r\n self.oodocument.close( 1 )", "def close( self ):\n self.oodocument.dispose()\n self.oodocument.close( 1 )", "def close(self):\n self.event_writer.close()", "def close(self):\n if not self.is_close:\n if self._action_on_close:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sheet Size Get the size of the sheet.
def get_drawing_sheet_size(self): drawing_sheet_size_enum = { 9993: 'A0', 9994: 'A1', 9995: 'A2', 9996: 'A3', 9997: 'A4' } return drawing_sheet_size_enum[self.doc.Sheets(1).Size]
[ "def get_sheet_size(self, title):\n resp = self.service.spreadsheets().get(\n spreadsheetId=self.docid,\n ranges=title).execute()\n grid_props = resp['sheets'][0]['properties']['gridProperties']\n return (grid_props['rowCount'], grid_props['columnCount'])", "def cell_siz...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Drawing Infomation Return a dictionary of the drawing's properties.
def get_drawing_info(self): iprop = self.doc.PropertySets.Item("Inventor User Defined Properties") drawing_info = { 'partcode': str(iprop.Item('Dwg_No')), 'rev': int(iprop.Item('Revision')), 'desc': str(iprop.Item('Component')), 'material': str(iprop.Item(...
[ "def to_shape_attributes(self):\n return {\"name\": \"rect\",\n \"x\": int(self.x), \"y\": int(self.y),\n \"width\": int(self.width), \"height\": int(self.height)}", "def _build_layered_drawing_object_dict(self, debug=False):\n\n self.layered_drawing_object_dict = {}\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Part List Export the drawings part list to an excel spreadsheet.
def export_part_list(self, filetype='xlsx'): if filetype == 'csv': enum = 48649 else: enum = 48642 path = self.export_dir.joinpath(self.partcode).joinpath('part_list.xlsx') self.doc.Sheets(1).PartsLists(1).Export(str(path), enum)
[ "def part_list(ctx):\n click.echo(\n json.dumps(\n PartList(ctx.obj['CLIENT'],\n design_id=ctx.obj['DESIGN_ID']).invoke()))", "def export_spendings_to_excel(board):\n\n style_normal = xlwt.easyxf('font: name Times New Roman')\n style_income = xlwt.easyxf('font: name ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assembly BOM Export the assembly's bom to an excel spreadsheet.
def export_bom(self): path = self.export_dir.joinpath(self.partcode).joinpath('bom.xlsx') bom = self.doc.ComponentDefinition.BOM bom.StructuredViewFirstLevelOnly = False bom.StructuredViewEnabled = True bom.BOMViews.Item("Structured").Export(path, 74498)
[ "def test_export_to_excel():\n ic = InventoryCar(cm, method=\"recipe\", indicator=\"endpoint\")\n\n for b in (\"3.5\", \"3.6\", \"3.7\", \"3.7.1\", \"3.8\"):\n for s in (\"brightway2\", \"simapro\"):\n for d in (\"file\", \"bw2io\"):\n #\n ic.export_lci(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inventor Application COM Object Start COM client session with Inventor, and create object 'mod' that will point to the Python COM wrapper for Inventor's type library. Recast 'app' as an instance of the Application class in the wrapper.
def application(silent=True, visible=True): mod = win32com.client.gencache.EnsureModule( '{D98A091D-3A0F-4C3E-B36E-61F62068D488}', 0, 1, 0) app = win32com.client.Dispatch('Inventor.Application') app = mod.Application.Application(app) app.SilentOperation = silent app.Visible = visible ret...
[ "def xl_app():\n # get the Excel application object from PyXLL and wrap it\n xl_window = get_active_object()\n xl_app = win32com.client.Dispatch(xl_window).Application\n # it's helpful to make sure the gen_py wrapper has been created\n # as otherwise things like constants and event handlers won't wor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the laitude and longitude of the satellite.
def getlatlon(self): lat = np.pi/2.0 - self._th time = self.gettime() lon = self._phi - 2*np.pi*time/86164.09164 return lat, lon
[ "def longitude(self):\n return self.lat_lon_r[:,1]", "def longitude(self):\n return self.coordinates[1]", "def get_longitude(self):\n return self.L + self.dL", "def lat_lons(self):", "def longitude(self):\n longitude = self.get_coord()[0]\n return longitude", "def lon(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the differential at the given state of the satellite.
def diff_func(sat): state = sat.getstate() dstate = np.zeros(7) dstate[-1] = 1.0 dstate[0] = state[1] dstate[2] = state[3]/(state[0]) dstate[4] = state[5]/(state[0]*np.sin(state[2])) acc = tot_acc(sat) dstate[1], dstate[3], dstate[5] = sat.getvdot(acc[0], acc[1], acc[2]) return dstat...
[ "def derivative(self, time, state):\n\n # Update the firing rates:\n x = self.n_act(state)\n\n # Compute the dentritic sums for all neurons\n dend_sum = np.dot(self.w, x) + self.ext_in\n\n # Compute the membrane potential derivative:\n yd = (dend_sum - state) / self.tau\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the total acceleration on the satellite.
def tot_acc(sat): pos = sat.getpos_sph() lat = sat.getlatlon()[0] # g_acc = np.array([-G*M_EARTH/pos[0]**2, 0, 0]) g_acc = forces.gravity_wgs84(pos[0], lat) tether = sat.get_tether() t_acc = tether.accln(sat) return g_acc + t_acc
[ "def get_acceleration(self):\n return self.acceleration", "def getAcceleration(self):\r\n return self.__acceleration", "def calculate_acceleration(self) -> np.array:\n F = self.calculate_net_force()\n m = self.mass\n a = F / m\n\n return a", "def average_speed(self):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the orbit. sat Satellite object. tfinal Duration for which the simulation is to be continued. tstep Time steps for rk4 method. trec Time durations after which the data are to be recorded.
def getorbit(sat, tfinal, tstep, trec): ntimes = (int)(tfinal/tstep) n_tvals = (int)(tfinal/trec) state_arr = np.zeros((6, n_tvals)) orbelem_arr = np.zeros((6, n_tvals)) s_major_arr = np.zeros(n_tvals) count = 0 for i in range(ntimes): sat.rk4_step_sat(tstep) if i % (trec/tst...
[ "def integrate(self, Tfinal, Nt, initial_sol, method = \"ExplicitEuler\"):\r\n if method==\"JitCDDE\":\r\n f = [jit.y(k) for k in range(1, self.n)]\r\n f.append(-self.a.dot([jit.y(k) for k in range(self.n)]) \\\r\n - self.alpha.dot([jit.y(k, jit.t - self.tau) for k in range(self.n)]))\r\n e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add multiple edges from a list. Creates necessary nodes if missing.
def addEdgeList(self, edges): for e in edges: self.addEdge(e[0], e[1], e[2] if len(e) > 2 else None)
[ "def populate_edges(self, edges_list):\n edges = []\n for edge in edges_list:\n source, target, weight = edge[4], edge[5], edge[6]\n freq, line, geom = edge[7], edge[1], edge[2]\n edges.append(Edge(source, target, weight,\n freq, line, geom...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the shortest path from a single node to all other nodes using then BellmanFord algorithm.
def spBellmanFord(self, node, returnPaths = False): # Initialize working dictionaries and next edges to check curr = dict(map(lambda k: (k, (0, k) if k == node else (self.Inf, None)),\ self.__nodes.keys())) prev = {} edges = self.__nodes[node]["tails"] # Iter...
[ "def shortest(self, from_node, to_node):\n print \"Shortest path from {} to {}\".format(from_node.name, to_node.name)\n current = from_node\n solution = {current.name: 0}\n visited = []\n if from_node.name == to_node.name:\n return \"No route necessary\"\n\n whil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sifts node up heap from starting position up to stopping position. Helper for Dijkstra shortest path algorithm.
def __siftup(heap, nodes, pos, stopPos = 0): # Loop until past stopping position while pos > stopPos: # Set parent position parentPos = (pos - 1) >> 1 # Swap if child less than parent if heap[pos][0] < heap[parentPos][0]: Graph.__swapHeapN...
[ "def sift_up(heap, start, end):\n # Swap last node with parents until no longer greater.\n i = end - 1\n heaped = False\n while i > start and not heaped:\n parent = (i - 1) // 2\n if compare(heap[i], heap[parent]) > 0:\n heap[i], heap[parent] = heap[parent], heap[i]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Choos the closest option to the value in the provided scale This function quantifies a continuous domain value by transforming it on the closest value in a provided discrete scale. If the initial value is out of scale range, any transformation is applied.
def quantify ( value, scale ): if value < scale[0] or value > scale[-1]: return value for i in range (1, len(scale)): if value <= scale[i]: if scale[i] - value > value - scale[i-1]: return scale[i-1] else: return scale[i]
[ "def normalize_scale(scale):\r\n return scale >= 1.0 and (1.0 / scale) or scale", "def default_scale(scale):\n return sequence_scale(scale, (1, 1.25, 1.5, 1.75, 2,\n 2.5, 3, 4, 5, 6, 7.5, 8, 9, 10))", "def scale_equation(scale):\n\n return upper_diff(scale, find_b(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Provide a generator for looping on a signal through consecutive windows This function returns a python generator for looping on a signal. For each loop a single window is yielded. This way, any processing could be applied to the signal for each window through a simple forloop. If the withWindowIndex param is setted to ...
def getSignalReader( signal, sampleRate=16000, windowWidth=0.032, step=0.01, withWindowIndex=False): windowWidth = int( windowWidth * sampleRate) step = int( step * sampleRate) nbWindows = int((signal.size - windowWidth) // step ) +1 if withWindowIndex: for i in range(nbWindows): startIndex = ste...
[ "def windows(self,windowSize):\n for i in range(0,len(self)-windowSize):\n yield (i,i+windowSize)", "def sliding_window(self):\n for y in range(0, self.image.shape[0], self.step_size):\n for x in range(0, self.image.shape[1], self.step_size):\n yield (self.image[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append the shorter provided signal so that its size equals the second signal size
def equalizeShapes( signal1, signal2): if signal1.size < signal2.size: signal1 = np.append( signal1, [0] * (signal2.size-signal1.size)) elif signal1.size > signal2.size: signal2 = np.append( signal2, [0] *(signal1.size - signal2.size)) return signal1, signal2
[ "def extend_signals(signals, length=None, samplerate=None):\n if length is None:\n return signals\n if samplerate is not None:\n length = round(samplerate * length)\n\n def extend(signal):\n padding = length - signal.shape[-1]\n if padding < 1:\n return signal.copy()\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Note This is lazyly evaluated, no operation is actually run. Returns CacheID A global cache volume identifier. Raises ExecuteTimeoutError If the time to execute the query exceeds the configured timeout. QueryError If the API returns an error.
def id(self) -> CacheID: _args: list[Arg] = [] _ctx = self._select("id", _args) return _ctx.execute_sync(CacheID)
[ "def query_id(self) -> str:\n return pulumi.get(self, \"query_id\")", "def getIdOrThrow(con, key, value, table):\n\n # create cache directory if not present\n Path(ID_CACHE_FILE.parent).mkdir(parents=True, exist_ok=True)\n \n path_exists = Path(ID_CACHE_FILE).exists()\n\n cache = None\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves default arguments for future commands. Returns Optional[list[str]] The `String` scalar type represents textual data, represented as UTF8 character sequences. The String type is most often used by GraphQL to represent freeform humanreadable text. Raises ExecuteTimeoutError If the time to execute the query exce...
def default_args(self) -> Optional[list[str]]: _args: list[Arg] = [] _ctx = self._select("defaultArgs", _args) return _ctx.execute_sync(Optional[list[str]])
[ "def get_default_string_values(self):\n # Implemented from template for osid.Metadata.get_minimum_cardinal\n from .osid_errors import IllegalState\n if self._kwargs['syntax'] not in ['STRING']:\n raise IllegalState()\n else:\n return self._kwargs['default_string_val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves an endpoint that clients can use to reach this container. If no port is specified, the first exposed port is used. If none exist an error is returned.
def endpoint( self, port: Optional[int] = None, scheme: Optional[str] = None, ) -> str: _args = [ Arg("port", port, None), Arg("scheme", scheme, None), ] _ctx = self._select("endpoint", _args) return _ctx.execute_sync(str)
[ "def discovery_endpoint(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"discovery_endpoint\")", "def get(self, endpoint_name: str) -> OnlineEndpoint:\n endpoint = self._endpoint_stub.get(endpoint_name=endpoint_name)\n container = self._docker_client.get_endpoint_container(endpoint_na...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves entrypoint to be prepended to the arguments of all commands. Returns Optional[list[str]] The `String` scalar type represents textual data, represented as UTF8 character sequences. The String type is most often used by GraphQL to represent freeform humanreadable text. Raises ExecuteTimeoutError If the time to ...
def entrypoint(self) -> Optional[list[str]]: _args: list[Arg] = [] _ctx = self._select("entrypoint", _args) return _ctx.execute_sync(Optional[list[str]])
[ "def get_entry_point_command(\n entry_point: Optional[\"EntryPoint\"], parameters: Dict[str, Any]\n) -> List[str]:\n if entry_point is None:\n return []\n return entry_point.compute_command(parameters)", "def get_command_args(self, skip_serialized_namedtuple: bool = False) -> Sequence[str]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the list of environment variables passed to commands.
def env_variables(self) -> list["EnvVariable"]: _args: list[Arg] = [] _ctx = self._select("envVariables", _args) _ctx = EnvVariable(_ctx)._select_multiple( _name="name", _value="value", ) return _ctx.execute_sync(list[EnvVariable])
[ "def get_variables():\n list_variables = []\n for key in environ:\n list_variables.append(key)\n return list_variables", "def getEnvironmentVariables(self):\n return {v.name: v.value for v in self.environment_variables}", "def list(self):\n env_list = []\n for (key, val) in self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exit code of the last executed command. Zero means success. Will execute default command if none is set, or error if there's no default. Returns int The `Int` scalar type represents nonfractional signed whole numeric values. Int can represent values between (2^31) and 2^31 1. Raises ExecuteTimeoutError If the time to e...
def exit_code(self) -> int: _args: list[Arg] = [] _ctx = self._select("exitCode", _args) return _ctx.execute_sync(int)
[ "def getReturnCode(self):\n retcode = self.sendCmd(\"echo $?\")\n try:\n return int(retcode)\n except:\n return retcode", "def last_exit_code(self) -> Optional[pulumi.Input[int]]:\n return pulumi.get(self, \"last_exit_code\")", "def getReturnCode(self):\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes the container as an OCI tarball to the destination file path on the host for the specified platform variants. Return true on success. It can also publishes platform variants.
def export( self, path: str, platform_variants: Optional[Sequence["Container"]] = None, forced_compression: Optional[ImageLayerCompression] = None, ) -> bool: _args = [ Arg("path", path), Arg("platformVariants", platform_variants, None), Ar...
[ "def publish(\n self,\n address: str,\n platform_variants: Optional[Sequence[\"Container\"]] = None,\n forced_compression: Optional[ImageLayerCompression] = None,\n ) -> str:\n _args = [\n Arg(\"address\", address),\n Arg(\"platformVariants\", platform_var...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the list of exposed ports. This includes ports already exposed by the image, even if not explicitly added with dagger. Currently experimental; set _EXPERIMENTAL_DAGGER_SERVICES_DNS=0 to disable.
def exposed_ports(self) -> list["Port"]: _args: list[Arg] = [] _ctx = self._select("exposedPorts", _args) _ctx = Port(_ctx)._select_multiple( _description="description", _port="port", _protocol="protocol", ) return _ctx.execute_sync(list[Port])
[ "def exposed_ports(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['GroupExposedPortArgs']]]]:\n return pulumi.get(self, \"exposed_ports\")", "def list_ports(self):\n return self.ironic_client.port.list()", "def _generate_expose_services(self):\n ports = []\n for p in self.image...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves a hostname which can be used by clients to reach this container. Currently experimental; set _EXPERIMENTAL_DAGGER_SERVICES_DNS=0 to disable. Returns str The `String` scalar type represents textual data, represented as UTF8 character sequences. The String type is most often used by GraphQL to represent freefor...
def hostname(self) -> str: _args: list[Arg] = [] _ctx = self._select("hostname", _args) return _ctx.execute_sync(str)
[ "def get_hostname(self):\n module = 'hostname'\n method = 'GET'\n response = self.axapi_call(module, method)\n hostname = response.json()['hostname']['value']\n print(self.device + ' Device hostname is: ' + hostname)", "def server_hostname(self):\n return dns.future_hostn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The unique image reference which can only be retrieved immediately after the 'Container.From' call. Returns Optional[str] The `String` scalar type represents textual data, represented as UTF8 character sequences. The String type is most often used by GraphQL to represent freeform humanreadable text. Raises ExecuteTimeo...
def image_ref(self) -> Optional[str]: _args: list[Arg] = [] _ctx = self._select("imageRef", _args) return _ctx.execute_sync(Optional[str])
[ "def image_name(self) -> pulumi.Output[Optional[str]]:\n return pulumi.get(self, \"image_name\")", "def _get_container_image_name(image_reference):\n if '@' in image_reference:\n return image_reference.split('@', 1)[0]\n else:\n return image_reference.rsplit(':', 1)[0]", "def blob_con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The platform this container executes and publishes as. Returns Platform The platform config OS and architecture in a Container. The format is [os]/[platform]/[version] (e.g., "darwin/arm64/v7", "windows/amd64", "linux/arm64"). Raises ExecuteTimeoutError If the time to execute the query exceeds the configured timeout. Q...
def platform(self) -> Platform: _args: list[Arg] = [] _ctx = self._select("platform", _args) return _ctx.execute_sync(Platform)
[ "def platform(self) -> Optional[pulumi.Input['DockerImagePlatformArgs']]:\n return pulumi.get(self, \"platform\")", "def _get_platform(self):\n # This needs to be extended to support remote execution, e.g. job queues on clusters.\n # Use Sumatra?\n network_name = platform.node()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Publishes this container as a new image to the specified address. Publish returns a fully qualified ref. It can also publish platform variants.
def publish( self, address: str, platform_variants: Optional[Sequence["Container"]] = None, forced_compression: Optional[ImageLayerCompression] = None, ) -> str: _args = [ Arg("address", address), Arg("platformVariants", platform_variants, None), ...
[ "def containerPublish(*args, **kwargs):\n\n pass", "def containerPublish(*args, bindNode: Union[List[AnyStr, AnyStr], bool]=None,\n bindTemplateStandins: bool=True, inConnections: bool=True, mergeShared:\n bool=True, outConnections: bool=True, publishNode: Union[List[Any...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The error stream of the last executed command. Will execute default command if none is set, or error if there's no default. Returns str The `String` scalar type represents textual data, represented as UTF8 character sequences. The String type is most often used by GraphQL to represent freeform humanreadable text. Raise...
def stderr(self) -> str: _args: list[Arg] = [] _ctx = self._select("stderr", _args) return _ctx.execute_sync(str)
[ "def error_sql(self):\n if self.type == 'ANL':\n return self.parser.parse_analyze_error_sql()", "def read_error(self):\n \n error = self.inst.query(\"SYSTem:ERRor?\")\n return error", "def Query(args: rdf_osquery.OsqueryArgs) -> str:\n timeout = args.timeout_millis / 1000...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }