code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _compile_messages(self): ''' Create a list of all OS messages and their compiled regexs ''' self.compiled_messages = [] if not self._config: return for message_dict in self._config.get('messages', {}): error = message_dict['error'] ...
Create a list of all OS messages and their compiled regexs
Below is the the instruction that describes the task: ### Input: Create a list of all OS messages and their compiled regexs ### Response: def _compile_messages(self): ''' Create a list of all OS messages and their compiled regexs ''' self.compiled_messages = [] if not self._...
def _column_pad_filter(self, next_filter): """ Expand blank lines caused from overflow of other columns to blank whitespace. E.g. INPUT: [ ["1a", "2a"], [None, "2b"], ["1b", "2c"], [None, "2d"] ] OUTPUT:...
Expand blank lines caused from overflow of other columns to blank whitespace. E.g. INPUT: [ ["1a", "2a"], [None, "2b"], ["1b", "2c"], [None, "2d"] ] OUTPUT: [ ["1a", "2a"], [<blan...
Below is the the instruction that describes the task: ### Input: Expand blank lines caused from overflow of other columns to blank whitespace. E.g. INPUT: [ ["1a", "2a"], [None, "2b"], ["1b", "2c"], [None, "2d"] ] ...
def cancel_email_change(self): """ Cancel email change for new users and roll back data """ if not self.email_new: return self.email_new = None self.email_confirmed = True self.email_link = None self.email_new = None self.email_link_expires = None
Cancel email change for new users and roll back data
Below is the the instruction that describes the task: ### Input: Cancel email change for new users and roll back data ### Response: def cancel_email_change(self): """ Cancel email change for new users and roll back data """ if not self.email_new: return self.email_new = None ...
def deepupdate(original, update, levels=5): """Update, like dict.update, but deeper. Update 'original' from dict/iterable 'update'. I.e., it recurses on dicts 'levels' times if necessary. A standard dict.update is levels=0 """ if not isinstance(update, dict): update = dict(update) ...
Update, like dict.update, but deeper. Update 'original' from dict/iterable 'update'. I.e., it recurses on dicts 'levels' times if necessary. A standard dict.update is levels=0
Below is the the instruction that describes the task: ### Input: Update, like dict.update, but deeper. Update 'original' from dict/iterable 'update'. I.e., it recurses on dicts 'levels' times if necessary. A standard dict.update is levels=0 ### Response: def deepupdate(original, update, levels=5): ...
def export(self, output_folder): """Export matrices as ``*.npy`` files to an output folder.""" if not os.path.exists(output_folder): os.makedirs(output_folder) self._interact_with_folder(output_folder, 'w')
Export matrices as ``*.npy`` files to an output folder.
Below is the the instruction that describes the task: ### Input: Export matrices as ``*.npy`` files to an output folder. ### Response: def export(self, output_folder): """Export matrices as ``*.npy`` files to an output folder.""" if not os.path.exists(output_folder): os.makedirs(output_...
def refund_order(self, order_id, **params): """https://developers.coinbase.com/api/v2#refund-an-order""" for required in ['currency']: if required not in params: raise ValueError("Missing required parameter: %s" % required) response = self._post('v2', 'orders', order_...
https://developers.coinbase.com/api/v2#refund-an-order
Below is the the instruction that describes the task: ### Input: https://developers.coinbase.com/api/v2#refund-an-order ### Response: def refund_order(self, order_id, **params): """https://developers.coinbase.com/api/v2#refund-an-order""" for required in ['currency']: if required not in...
def fprint(fmt, *args, **kwargs): """Parse and print a colored and perhaps formatted string. The remaining keyword arguments are the same as for Python's built-in print function. Colors are returning to their defaults before the function returns. """ if not fmt: return hascolor = ...
Parse and print a colored and perhaps formatted string. The remaining keyword arguments are the same as for Python's built-in print function. Colors are returning to their defaults before the function returns.
Below is the the instruction that describes the task: ### Input: Parse and print a colored and perhaps formatted string. The remaining keyword arguments are the same as for Python's built-in print function. Colors are returning to their defaults before the function returns. ### Response: def fprint(fm...
def create_primes(threshold): """ Generate prime values using sieve of Eratosthenes method. Args: threshold (int): The upper bound for the size of the prime values. Returns (List[int]): All primes from 2 and up to ``threshold``. """ if threshold == 2: return...
Generate prime values using sieve of Eratosthenes method. Args: threshold (int): The upper bound for the size of the prime values. Returns (List[int]): All primes from 2 and up to ``threshold``.
Below is the the instruction that describes the task: ### Input: Generate prime values using sieve of Eratosthenes method. Args: threshold (int): The upper bound for the size of the prime values. Returns (List[int]): All primes from 2 and up to ``threshold``. ### Response: def...
def addsalt(self, salt): """ adds a salt to the hash function (OPTIONAL) should be called AFTER Init, and BEFORE update salt: a bytestring, length determined by hashbitlen. if not of sufficient length, the bytestring will be assumed to be a big endi...
adds a salt to the hash function (OPTIONAL) should be called AFTER Init, and BEFORE update salt: a bytestring, length determined by hashbitlen. if not of sufficient length, the bytestring will be assumed to be a big endian number and pref...
Below is the the instruction that describes the task: ### Input: adds a salt to the hash function (OPTIONAL) should be called AFTER Init, and BEFORE update salt: a bytestring, length determined by hashbitlen. if not of sufficient length, the bytestring ...
def tile_to_quadkey(tile, level): """Transform tile coordinates to a quadkey""" tile_x = tile[0] tile_y = tile[1] quadkey = "" for i in xrange(level): bit = level - i digit = ord('0') mask = 1 << (bit - 1) # if (bit - 1) > 0 else 1 >> (bit - 1...
Transform tile coordinates to a quadkey
Below is the the instruction that describes the task: ### Input: Transform tile coordinates to a quadkey ### Response: def tile_to_quadkey(tile, level): """Transform tile coordinates to a quadkey""" tile_x = tile[0] tile_y = tile[1] quadkey = "" for i in xrange(level): ...
def InsertFloatArg(self, string="", **_): """Inserts a Float argument.""" try: float_value = float(string) return self.InsertArg(float_value) except (TypeError, ValueError): raise ParseError("%s is not a valid float." % string)
Inserts a Float argument.
Below is the the instruction that describes the task: ### Input: Inserts a Float argument. ### Response: def InsertFloatArg(self, string="", **_): """Inserts a Float argument.""" try: float_value = float(string) return self.InsertArg(float_value) except (TypeError, ValueError): raise ...
def changed(self, thresh=0.05, idx=True): """ Changed features. {threshdoc} """ ind = self.data[self.pval_column] <= thresh if idx: return ind return self[ind]
Changed features. {threshdoc}
Below is the the instruction that describes the task: ### Input: Changed features. {threshdoc} ### Response: def changed(self, thresh=0.05, idx=True): """ Changed features. {threshdoc} """ ind = self.data[self.pval_column] <= thresh if idx: retu...
def _init_orient(self): """Retrieve the quadrature points and weights if needed. """ if self.orient == orientation.orient_averaged_fixed: (self.beta_p, self.beta_w) = quadrature.get_points_and_weights( self.or_pdf, 0, 180, self.n_beta) self._set_orient_signatu...
Retrieve the quadrature points and weights if needed.
Below is the the instruction that describes the task: ### Input: Retrieve the quadrature points and weights if needed. ### Response: def _init_orient(self): """Retrieve the quadrature points and weights if needed. """ if self.orient == orientation.orient_averaged_fixed: (self.be...
def get_parent(self, update=False): """:returns: the parent node of the current node object.""" if self._meta.proxy_for_model: # the current node is a proxy model; the returned parent # should be the same proxy model, so we need to explicitly # fetch it as an instance...
:returns: the parent node of the current node object.
Below is the the instruction that describes the task: ### Input: :returns: the parent node of the current node object. ### Response: def get_parent(self, update=False): """:returns: the parent node of the current node object.""" if self._meta.proxy_for_model: # the current node is a pro...
def request_vpc_peering_connection(name, requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, conn_name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None,...
name Name of the state requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. String type. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. String type. peer_vpc_id ID of the VPC tp crete VPC peering connection wi...
Below is the the instruction that describes the task: ### Input: name Name of the state requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. String type. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. String type. ...
def verify_verify(self, id, token): """Verify the token of a specific verification.""" return Verify().load(self.request('verify/' + str(id), params={'token': token}))
Verify the token of a specific verification.
Below is the the instruction that describes the task: ### Input: Verify the token of a specific verification. ### Response: def verify_verify(self, id, token): """Verify the token of a specific verification.""" return Verify().load(self.request('verify/' + str(id), params={'token': token}))
def encode_vlq(i): """ Encode integer `i` into a VLQ encoded string. """ # shift in the sign to least significant bit raw = (-i << 1) + 1 if i < 0 else i << 1 if raw < VLQ_MULTI_CHAR: # short-circuit simple case as it doesn't need continuation return INT_B64[raw] result = [...
Encode integer `i` into a VLQ encoded string.
Below is the the instruction that describes the task: ### Input: Encode integer `i` into a VLQ encoded string. ### Response: def encode_vlq(i): """ Encode integer `i` into a VLQ encoded string. """ # shift in the sign to least significant bit raw = (-i << 1) + 1 if i < 0 else i << 1 if raw...
def refresh(self): """ Flush the canvas content to the underlying screen. """ self._screen.block_transfer(self._buffer, self._dx, self._dy)
Flush the canvas content to the underlying screen.
Below is the the instruction that describes the task: ### Input: Flush the canvas content to the underlying screen. ### Response: def refresh(self): """ Flush the canvas content to the underlying screen. """ self._screen.block_transfer(self._buffer, self._dx, self._dy)
def on_menu(self, event): '''called on menu event''' state = self.state if self.popup_menu is not None: ret = self.popup_menu.find_selected(event) if ret is not None: ret.popup_pos = self.popup_pos if ret.returnkey == 'fitWindow': ...
called on menu event
Below is the the instruction that describes the task: ### Input: called on menu event ### Response: def on_menu(self, event): '''called on menu event''' state = self.state if self.popup_menu is not None: ret = self.popup_menu.find_selected(event) if ret is not None: ...
def stacked_cnn(units: tf.Tensor, n_hidden_list: List, filter_width=3, use_batch_norm=False, use_dilation=False, training_ph=None, add_l2_losses=False): """ Number of convolutional layers stacked on top of each other ...
Number of convolutional layers stacked on top of each other Args: units: a tensorflow tensor with dimensionality [None, n_tokens, n_features] n_hidden_list: list with number of hidden units at the ouput of each layer filter_width: width of the kernel in tokens use_batch_norm: whethe...
Below is the the instruction that describes the task: ### Input: Number of convolutional layers stacked on top of each other Args: units: a tensorflow tensor with dimensionality [None, n_tokens, n_features] n_hidden_list: list with number of hidden units at the ouput of each layer filte...
def keys_to_typing(value): """Processes the values that will be typed in the element.""" typing = [] for val in value: if isinstance(val, Keys): typing.append(val) elif isinstance(val, int): val = str(val) for i in range(len(val)): typing.a...
Processes the values that will be typed in the element.
Below is the the instruction that describes the task: ### Input: Processes the values that will be typed in the element. ### Response: def keys_to_typing(value): """Processes the values that will be typed in the element.""" typing = [] for val in value: if isinstance(val, Keys): typ...
def _query_server_pos(self, conn, file_length): """ Queries server to find out what bytes it currently has. Returns (server_start, server_end), where the values are inclusive. For example, (0, 2) would mean that the server has bytes 0, 1, *and* 2. Raises ResumableUploadExceptio...
Queries server to find out what bytes it currently has. Returns (server_start, server_end), where the values are inclusive. For example, (0, 2) would mean that the server has bytes 0, 1, *and* 2. Raises ResumableUploadException if problem querying server.
Below is the the instruction that describes the task: ### Input: Queries server to find out what bytes it currently has. Returns (server_start, server_end), where the values are inclusive. For example, (0, 2) would mean that the server has bytes 0, 1, *and* 2. Raises ResumableUploadExcepti...
def compute_acl(cls, filename, start_index=None, end_index=None, min_nsamples=10): """Computes the autocorrleation length for all model params and temperatures in the given file. Parameter values are averaged over all walkers at each iteration and temperature. The A...
Computes the autocorrleation length for all model params and temperatures in the given file. Parameter values are averaged over all walkers at each iteration and temperature. The ACL is then calculated over the averaged chain. Parameters ----------- filename : str ...
Below is the the instruction that describes the task: ### Input: Computes the autocorrleation length for all model params and temperatures in the given file. Parameter values are averaged over all walkers at each iteration and temperature. The ACL is then calculated over the averaged chain...
def linux(cls, path, argv=None, envp=None, entry_symbol=None, symbolic_files=None, concrete_start='', pure_symbolic=False, stdin_size=None, **kwargs): """ Constructor for Linux binary analysis. :param str path: Path to binary to analyze :param argv: Arguments to provide to the binary ...
Constructor for Linux binary analysis. :param str path: Path to binary to analyze :param argv: Arguments to provide to the binary :type argv: list[str] :param envp: Environment to provide to the binary :type envp: dict[str, str] :param entry_symbol: Entry symbol to resol...
Below is the the instruction that describes the task: ### Input: Constructor for Linux binary analysis. :param str path: Path to binary to analyze :param argv: Arguments to provide to the binary :type argv: list[str] :param envp: Environment to provide to the binary :type en...
def _check_pid(self, allow_reset=False): """Check process id to ensure integrity, reset if in new process.""" if not self.pid == current_process().pid: if allow_reset: self.reset() else: raise RuntimeError("Forbidden operation in multiple processes...
Check process id to ensure integrity, reset if in new process.
Below is the the instruction that describes the task: ### Input: Check process id to ensure integrity, reset if in new process. ### Response: def _check_pid(self, allow_reset=False): """Check process id to ensure integrity, reset if in new process.""" if not self.pid == current_process().pid: ...
def for_json(self): """Handle multi-select vs single-select""" if self.multiselect: return super(MultiSelectField, self).for_json() value = self.get_python() if hasattr(value, 'for_json'): return value.for_json() return value
Handle multi-select vs single-select
Below is the the instruction that describes the task: ### Input: Handle multi-select vs single-select ### Response: def for_json(self): """Handle multi-select vs single-select""" if self.multiselect: return super(MultiSelectField, self).for_json() value = self.get_python() ...
def returnData(self, dsptr): """ " get ip data from db file by data start ptr " param: dsptr """ dataPtr = dsptr & 0x00FFFFFFL dataLen = (dsptr >> 24) & 0xFF self.__f.seek(dataPtr) data = self.__f.read(dataLen) result = data[4:].split('|') ...
" get ip data from db file by data start ptr " param: dsptr
Below is the the instruction that describes the task: ### Input: " get ip data from db file by data start ptr " param: dsptr ### Response: def returnData(self, dsptr): """ " get ip data from db file by data start ptr " param: dsptr """ dataPtr = dsptr & 0x00FFFFFFL ...
def batch_process( self, zoom=None, tile=None, multi=cpu_count(), max_chunksize=1 ): """ Process a large batch of tiles. Parameters ---------- process : MapcheteProcess process to be run zoom : list or int either single zoom level or l...
Process a large batch of tiles. Parameters ---------- process : MapcheteProcess process to be run zoom : list or int either single zoom level or list of minimum and maximum zoom level; None processes all (default: None) tile : tuple ...
Below is the the instruction that describes the task: ### Input: Process a large batch of tiles. Parameters ---------- process : MapcheteProcess process to be run zoom : list or int either single zoom level or list of minimum and maximum zoom level; ...
def parse_widget_name(widget): ''' Parse a alias:block_name string into separate parts. ''' try: alias, block_name = widget.split(':', 1) except ValueError: raise template.TemplateSyntaxError('widget name must be "alias:block_name" - %s' % widget) return alias, block_name
Parse a alias:block_name string into separate parts.
Below is the the instruction that describes the task: ### Input: Parse a alias:block_name string into separate parts. ### Response: def parse_widget_name(widget): ''' Parse a alias:block_name string into separate parts. ''' try: alias, block_name = widget.split(':', 1) except ValueError...
async def put(self, key, value, *args): """Edits a data entry.""" self._db[key] = value await self.save()
Edits a data entry.
Below is the the instruction that describes the task: ### Input: Edits a data entry. ### Response: async def put(self, key, value, *args): """Edits a data entry.""" self._db[key] = value await self.save()
def _jq_format(code): """ DEPRECATED - Use re.escape() instead, which performs the intended action. Use before throwing raw code such as 'div[tab="advanced"]' into jQuery. Selectors with quotes inside of quotes would otherwise break jQuery. If you just want to escape quotes, there's escape_quotes_if...
DEPRECATED - Use re.escape() instead, which performs the intended action. Use before throwing raw code such as 'div[tab="advanced"]' into jQuery. Selectors with quotes inside of quotes would otherwise break jQuery. If you just want to escape quotes, there's escape_quotes_if_needed(). This is similar to ...
Below is the the instruction that describes the task: ### Input: DEPRECATED - Use re.escape() instead, which performs the intended action. Use before throwing raw code such as 'div[tab="advanced"]' into jQuery. Selectors with quotes inside of quotes would otherwise break jQuery. If you just want to esca...
def get_bool(self, key, default=None): """ Same as :meth:`dict.get`, but the value is converted to a bool. The boolean value is considered, respectively, :obj:`True` or :obj:`False` if the string is equal, ignoring case, to ``'true'`` or ``'false'``. """ v = self...
Same as :meth:`dict.get`, but the value is converted to a bool. The boolean value is considered, respectively, :obj:`True` or :obj:`False` if the string is equal, ignoring case, to ``'true'`` or ``'false'``.
Below is the the instruction that describes the task: ### Input: Same as :meth:`dict.get`, but the value is converted to a bool. The boolean value is considered, respectively, :obj:`True` or :obj:`False` if the string is equal, ignoring case, to ``'true'`` or ``'false'``. ### Response: def...
def _binary(self, node): """ Translate a binary node into latex qtree node. :param node: a treebrd node :return: a qtree subtree rooted at the node """ return '[.${op}$ {left} {right} ]'\ .format(op=latex_operator[node.operator], left=self....
Translate a binary node into latex qtree node. :param node: a treebrd node :return: a qtree subtree rooted at the node
Below is the the instruction that describes the task: ### Input: Translate a binary node into latex qtree node. :param node: a treebrd node :return: a qtree subtree rooted at the node ### Response: def _binary(self, node): """ Translate a binary node into latex qtree node. :...
def _replay_info(replay_path): """Query a replay for information.""" if not replay_path.lower().endswith("sc2replay"): print("Must be a replay.") return run_config = run_configs.get() with run_config.start(want_rgb=False) as controller: info = controller.replay_info(run_config.replay_data(replay_pa...
Query a replay for information.
Below is the the instruction that describes the task: ### Input: Query a replay for information. ### Response: def _replay_info(replay_path): """Query a replay for information.""" if not replay_path.lower().endswith("sc2replay"): print("Must be a replay.") return run_config = run_configs.get() wit...
def _remote_folder(dirpath, remotes, syn): """Retrieve the remote folder for files, creating if necessary. """ if dirpath in remotes: return remotes[dirpath], remotes else: parent_dir, cur_dir = os.path.split(dirpath) parent_folder, remotes = _remote_folder(parent_dir, remotes, s...
Retrieve the remote folder for files, creating if necessary.
Below is the the instruction that describes the task: ### Input: Retrieve the remote folder for files, creating if necessary. ### Response: def _remote_folder(dirpath, remotes, syn): """Retrieve the remote folder for files, creating if necessary. """ if dirpath in remotes: return remotes[dirpat...
def delete(self, bucket: str, key: str): """ Deletes an object in a bucket. If the operation definitely did not delete anything, return False. Any other return value is treated as something was possibly deleted. """ bucket_obj = self._ensure_bucket_loaded(bucket) try: ...
Deletes an object in a bucket. If the operation definitely did not delete anything, return False. Any other return value is treated as something was possibly deleted.
Below is the the instruction that describes the task: ### Input: Deletes an object in a bucket. If the operation definitely did not delete anything, return False. Any other return value is treated as something was possibly deleted. ### Response: def delete(self, bucket: str, key: str): """ ...
def check_auth(args): """ Checks courseraoauth2client's connectivity to the coursera.org API servers for a specific application """ oauth2_instance = oauth2.build_oauth2(args.app, args) auth = oauth2_instance.build_authorizer() my_profile_url = ( 'https://api.coursera.org/api/externa...
Checks courseraoauth2client's connectivity to the coursera.org API servers for a specific application
Below is the the instruction that describes the task: ### Input: Checks courseraoauth2client's connectivity to the coursera.org API servers for a specific application ### Response: def check_auth(args): """ Checks courseraoauth2client's connectivity to the coursera.org API servers for a specific ap...
def get_ruptures(self, srcfilter=calc.filters.nofilter): """ :returns: a list of EBRuptures filtered by bounding box """ ebrs = [] with datastore.read(self.filename) as dstore: rupgeoms = dstore['rupgeoms'] for rec in self.rup_array: if src...
:returns: a list of EBRuptures filtered by bounding box
Below is the the instruction that describes the task: ### Input: :returns: a list of EBRuptures filtered by bounding box ### Response: def get_ruptures(self, srcfilter=calc.filters.nofilter): """ :returns: a list of EBRuptures filtered by bounding box """ ebrs = [] with data...
def define(self, value, lineno, namespace=None): """ Defines label value. It can be anything. Even an AST """ if self.defined: error(lineno, "label '%s' already defined at line %i" % (self.name, self.lineno)) self.value = value self.lineno = lineno self.names...
Defines label value. It can be anything. Even an AST
Below is the the instruction that describes the task: ### Input: Defines label value. It can be anything. Even an AST ### Response: def define(self, value, lineno, namespace=None): """ Defines label value. It can be anything. Even an AST """ if self.defined: error(lineno, "label...
def _read_file(name, encoding='utf-8') -> str: """ Read the contents of a file. :param name: The name of the file in the current directory. :param encoding: The encoding of the file; defaults to utf-8. :return: The contents of the file. """ with open(name, encoding=encoding) as f: r...
Read the contents of a file. :param name: The name of the file in the current directory. :param encoding: The encoding of the file; defaults to utf-8. :return: The contents of the file.
Below is the the instruction that describes the task: ### Input: Read the contents of a file. :param name: The name of the file in the current directory. :param encoding: The encoding of the file; defaults to utf-8. :return: The contents of the file. ### Response: def _read_file(name, encoding='utf-8'...
def _simple_expand(template, seq): """ seq IS TUPLE OF OBJECTS IN PATH ORDER INTO THE DATA TREE seq[-1] IS THE CURRENT CONTEXT """ def replacer(found): ops = found.group(1).split("|") path = ops[0] var = path.lstrip(".") depth = min(len(seq), max(1, len(path) - len(...
seq IS TUPLE OF OBJECTS IN PATH ORDER INTO THE DATA TREE seq[-1] IS THE CURRENT CONTEXT
Below is the the instruction that describes the task: ### Input: seq IS TUPLE OF OBJECTS IN PATH ORDER INTO THE DATA TREE seq[-1] IS THE CURRENT CONTEXT ### Response: def _simple_expand(template, seq): """ seq IS TUPLE OF OBJECTS IN PATH ORDER INTO THE DATA TREE seq[-1] IS THE CURRENT CONTEXT "...
def create_function_f_y(self): """output function""" return ca.Function( 'y', [self.t, self.x, self.m, self.p, self.c, self.ng, self.nu], [self.y_rhs], ['t', 'x', 'm', 'p', 'c', 'ng', 'nu'], ['y'], self.func_opt)
output function
Below is the the instruction that describes the task: ### Input: output function ### Response: def create_function_f_y(self): """output function""" return ca.Function( 'y', [self.t, self.x, self.m, self.p, self.c, self.ng, self.nu], [self.y_rhs], ['t'...
def _sub8(ins): """ Pops last 2 bytes from the stack and subtract them. Then push the result onto the stack. Top-1 of the stack is subtracted Top _sub8 t1, a, b === t1 <-- a - b Optimizations: * If 2nd op is ZERO, then do NOTHING: A - 0 = A * If 1st operand is 0, then j...
Pops last 2 bytes from the stack and subtract them. Then push the result onto the stack. Top-1 of the stack is subtracted Top _sub8 t1, a, b === t1 <-- a - b Optimizations: * If 2nd op is ZERO, then do NOTHING: A - 0 = A * If 1st operand is 0, then just do a NEG * If...
Below is the the instruction that describes the task: ### Input: Pops last 2 bytes from the stack and subtract them. Then push the result onto the stack. Top-1 of the stack is subtracted Top _sub8 t1, a, b === t1 <-- a - b Optimizations: * If 2nd op is ZERO, then do NOTHING: A - 0 = A...
def example_2_load_data(self): """ 加载数据 """ # 权重向量, w1代表神经网络的第一层,w2代表神经网络的第二层 self.w1 = Variable(random_normal([2, 3], stddev=1, seed=1)) self.w2 = Variable(random_normal([3, 1], stddev=1, seed=1)) # 特征向量, 区别是,这里不会在计算图中生成节点 #self.x = placeholder(float32, s...
加载数据
Below is the the instruction that describes the task: ### Input: 加载数据 ### Response: def example_2_load_data(self): """ 加载数据 """ # 权重向量, w1代表神经网络的第一层,w2代表神经网络的第二层 self.w1 = Variable(random_normal([2, 3], stddev=1, seed=1)) self.w2 = Variable(random_normal([3, 1], stdd...
def getRegisterUserInfo(self, svctype = "Android NDrive App ver", auth = 0): """Retrieve information about useridx :param svctype: Information about the platform you are using right now. :param auth: Authentication type :return: ``True`` when success or ``False`` when failed ""...
Retrieve information about useridx :param svctype: Information about the platform you are using right now. :param auth: Authentication type :return: ``True`` when success or ``False`` when failed
Below is the the instruction that describes the task: ### Input: Retrieve information about useridx :param svctype: Information about the platform you are using right now. :param auth: Authentication type :return: ``True`` when success or ``False`` when failed ### Response: def getRegiste...
def get_option(self, optionname, default=0): """Returns the first value that matches 'optionname' in parameters passed in via the command line or set via set_option or via the global_plugin_options dictionary, in that order. optionaname may be iterable, in which case the first option th...
Returns the first value that matches 'optionname' in parameters passed in via the command line or set via set_option or via the global_plugin_options dictionary, in that order. optionaname may be iterable, in which case the first option that matches any of the option names is returned.
Below is the the instruction that describes the task: ### Input: Returns the first value that matches 'optionname' in parameters passed in via the command line or set via set_option or via the global_plugin_options dictionary, in that order. optionaname may be iterable, in which case the fi...
async def parse_request(req): """ Parses and validates request :param req: :return: """ async def validate_activity(activity: Activity): if not isinstance(activity.type, str): raise TypeError('BotFrameworkAdapter.parse_request(): invalid or mi...
Parses and validates request :param req: :return:
Below is the the instruction that describes the task: ### Input: Parses and validates request :param req: :return: ### Response: async def parse_request(req): """ Parses and validates request :param req: :return: """ async def validate_activity(activ...
def _rand_sparse(m, n, density, format='csr'): """Construct base function for sprand, sprandn.""" nnz = max(min(int(m*n*density), m*n), 0) row = np.random.randint(low=0, high=m-1, size=nnz) col = np.random.randint(low=0, high=n-1, size=nnz) data = np.ones(nnz, dtype=float) # duplicate (i,j) en...
Construct base function for sprand, sprandn.
Below is the the instruction that describes the task: ### Input: Construct base function for sprand, sprandn. ### Response: def _rand_sparse(m, n, density, format='csr'): """Construct base function for sprand, sprandn.""" nnz = max(min(int(m*n*density), m*n), 0) row = np.random.randint(low=0, high=m-1...
def login_user(user, remember=False, duration=None, force=False, fresh=True): ''' Logs a user in. You should pass the actual user object to this. If the user's `is_active` property is ``False``, they will not be logged in unless `force` is ``True``. This will return ``True`` if the log in attempt s...
Logs a user in. You should pass the actual user object to this. If the user's `is_active` property is ``False``, they will not be logged in unless `force` is ``True``. This will return ``True`` if the log in attempt succeeds, and ``False`` if it fails (i.e. because the user is inactive). :param us...
Below is the the instruction that describes the task: ### Input: Logs a user in. You should pass the actual user object to this. If the user's `is_active` property is ``False``, they will not be logged in unless `force` is ``True``. This will return ``True`` if the log in attempt succeeds, and ``False`...
def precision(y_true, y_score, k=None, return_bounds=False): """ If return_bounds is False then returns precision on the labeled examples in the top k. If return_bounds is True the returns a tuple containing: - precision on the labeled examples in the top k - number of labeled exampl...
If return_bounds is False then returns precision on the labeled examples in the top k. If return_bounds is True the returns a tuple containing: - precision on the labeled examples in the top k - number of labeled examples in the top k - lower bound of precision in the top k, assuming...
Below is the the instruction that describes the task: ### Input: If return_bounds is False then returns precision on the labeled examples in the top k. If return_bounds is True the returns a tuple containing: - precision on the labeled examples in the top k - number of labeled examples i...
def resolve_to_objects_or_project(path, all_matching_results=False): ''' :param path: Path to resolve :type path: string :param all_matching_results: Whether to return a list of all matching results :type all_matching_results: boolean A thin wrapper over :meth:`resolve_existing_path` which thro...
:param path: Path to resolve :type path: string :param all_matching_results: Whether to return a list of all matching results :type all_matching_results: boolean A thin wrapper over :meth:`resolve_existing_path` which throws an error if the path does not look like a project and doesn't match a ...
Below is the the instruction that describes the task: ### Input: :param path: Path to resolve :type path: string :param all_matching_results: Whether to return a list of all matching results :type all_matching_results: boolean A thin wrapper over :meth:`resolve_existing_path` which throws an er...
def connect(self, opt): """This sets up the tokens we expect to see in a way that hvac also expects.""" if not self._kwargs['verify']: LOG.warning('Skipping SSL Validation!') self.version = self.server_version() self.token = self.init_token() my_token = self....
This sets up the tokens we expect to see in a way that hvac also expects.
Below is the the instruction that describes the task: ### Input: This sets up the tokens we expect to see in a way that hvac also expects. ### Response: def connect(self, opt): """This sets up the tokens we expect to see in a way that hvac also expects.""" if not self._kwargs['verif...
def isFrameRange(frange): """ Return True if the given string is a frame range. Any padding characters, such as '#' and '@' are ignored. Args: frange (str): a frame range to test Returns: bool: """ # we're willing to trim padding characte...
Return True if the given string is a frame range. Any padding characters, such as '#' and '@' are ignored. Args: frange (str): a frame range to test Returns: bool:
Below is the the instruction that describes the task: ### Input: Return True if the given string is a frame range. Any padding characters, such as '#' and '@' are ignored. Args: frange (str): a frame range to test Returns: bool: ### Response: def isFrameRange(frang...
def repo(name, keyid=None, env=None, use_passphrase=False, gnupghome='/etc/salt/gpgkeys', runas='builder', timeout=15.0): ''' Make a package repository and optionally sign it and packages present The name is directory to turn into a repo. This state is ...
Make a package repository and optionally sign it and packages present The name is directory to turn into a repo. This state is best used with onchanges linked to your package building states. name The directory to find packages that will be in the repository keyid .. versionchanged:: ...
Below is the the instruction that describes the task: ### Input: Make a package repository and optionally sign it and packages present The name is directory to turn into a repo. This state is best used with onchanges linked to your package building states. name The directory to find packages t...
def add_gt_proposals(self, proposals, targets): """ Arguments: proposals: list[BoxList] targets: list[BoxList] """ # Get the device we're operating on device = proposals[0].bbox.device gt_boxes = [target.copy_with_fields([]) for target in targets]...
Arguments: proposals: list[BoxList] targets: list[BoxList]
Below is the the instruction that describes the task: ### Input: Arguments: proposals: list[BoxList] targets: list[BoxList] ### Response: def add_gt_proposals(self, proposals, targets): """ Arguments: proposals: list[BoxList] targets: list[BoxList] ...
def gfoclt(occtyp, front, fshape, fframe, back, bshape, bframe, abcorr, obsrvr, step, cnfine, result=None): """ Determine time intervals when an observer sees one target occulted by, or in transit across, another. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfoclt_c.html :pa...
Determine time intervals when an observer sees one target occulted by, or in transit across, another. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfoclt_c.html :param occtyp: Type of occultation. :type occtyp: str :param front: Name of body occulting the other. :type front: str ...
Below is the the instruction that describes the task: ### Input: Determine time intervals when an observer sees one target occulted by, or in transit across, another. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfoclt_c.html :param occtyp: Type of occultation. :type occtyp: str :pa...
def tag(version, params): """Build and return full command to use with subprocess.Popen for 'git tag' command :param version: :param params: :return: list """ cmd = ['git', 'tag', '-a', '-m', 'v%s' % version, str(version)] if params: cmd.extend(params...
Build and return full command to use with subprocess.Popen for 'git tag' command :param version: :param params: :return: list
Below is the the instruction that describes the task: ### Input: Build and return full command to use with subprocess.Popen for 'git tag' command :param version: :param params: :return: list ### Response: def tag(version, params): """Build and return full command to use with subpro...
def make_relative_to_root(path): """Update options so that defaults are user relative to specified pex_root.""" return os.path.normpath(path.format(pex_root=ENV.PEX_ROOT))
Update options so that defaults are user relative to specified pex_root.
Below is the the instruction that describes the task: ### Input: Update options so that defaults are user relative to specified pex_root. ### Response: def make_relative_to_root(path): """Update options so that defaults are user relative to specified pex_root.""" return os.path.normpath(path.format(pex_root=EN...
def length(self, t0=0, t1=1, error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH): """The length of an elliptical large_arc segment requires numerical integration, and in that case it's simpler to just do a geometric approximation, as for cubic bezier curves.""" assert 0 <= t0 <= 1 and 0 <= t...
The length of an elliptical large_arc segment requires numerical integration, and in that case it's simpler to just do a geometric approximation, as for cubic bezier curves.
Below is the the instruction that describes the task: ### Input: The length of an elliptical large_arc segment requires numerical integration, and in that case it's simpler to just do a geometric approximation, as for cubic bezier curves. ### Response: def length(self, t0=0, t1=1, error=LENGTH_ERRO...
def validate(self, table: pd.DataFrame, failed_only=False) -> pd.DataFrame: """Return a dataframe of validation results for the appropriate series vs the vector of validators. Args: table (pd.DataFrame): A dataframe on which to apply validation logic. failed_only (bool): If ``Tr...
Return a dataframe of validation results for the appropriate series vs the vector of validators. Args: table (pd.DataFrame): A dataframe on which to apply validation logic. failed_only (bool): If ``True``: return only the indexes that failed to validate.
Below is the the instruction that describes the task: ### Input: Return a dataframe of validation results for the appropriate series vs the vector of validators. Args: table (pd.DataFrame): A dataframe on which to apply validation logic. failed_only (bool): If ``True``: return only ...
def read_block_idb(self, block, _): """Interface Description Block""" options = block[16:] tsresol = 1000000 while len(options) >= 4: code, length = struct.unpack(self.endian + "HH", options[:4]) # PCAP Next Generation (pcapng) Capture File Format # 4....
Interface Description Block
Below is the the instruction that describes the task: ### Input: Interface Description Block ### Response: def read_block_idb(self, block, _): """Interface Description Block""" options = block[16:] tsresol = 1000000 while len(options) >= 4: code, length = struct.unpack(s...
def _set_vni_mask(self, v, load=False): """ Setter method for vni_mask, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/vni_mask (string) If this variable is read-only (config: false) in the source YANG file, then _set_vni_mask is considered as a private method. Backends looki...
Setter method for vni_mask, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/vni_mask (string) If this variable is read-only (config: false) in the source YANG file, then _set_vni_mask is considered as a private method. Backends looking to populate this variable should do so via ca...
Below is the the instruction that describes the task: ### Input: Setter method for vni_mask, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/vni_mask (string) If this variable is read-only (config: false) in the source YANG file, then _set_vni_mask is considered as a private metho...
def encode(self, pdu): """Encode a tag on the end of the PDU.""" # check for special encoding if (self.tagClass == Tag.contextTagClass): data = 0x08 elif (self.tagClass == Tag.openingTagClass): data = 0x0E elif (self.tagClass == Tag.closingTagClass): ...
Encode a tag on the end of the PDU.
Below is the the instruction that describes the task: ### Input: Encode a tag on the end of the PDU. ### Response: def encode(self, pdu): """Encode a tag on the end of the PDU.""" # check for special encoding if (self.tagClass == Tag.contextTagClass): data = 0x08 elif (s...
def create_model(samples_x, samples_y_aggregation, n_restarts_optimizer=250, is_white_kernel=False): ''' Trains GP regression model ''' kernel = gp.kernels.ConstantKernel(constant_value=1, constant_value_bounds=(1e-12, 1e12)) * \ ...
Trains GP regression model
Below is the the instruction that describes the task: ### Input: Trains GP regression model ### Response: def create_model(samples_x, samples_y_aggregation, n_restarts_optimizer=250, is_white_kernel=False): ''' Trains GP regression model ''' kernel = gp.kernels.ConstantKernel(const...
def _add_slide_footer(self, slide_no): """Add the slide footer to the output if enabled.""" if self.builder.config.slide_footer: self.body.append( '\n<div class="slide-footer">%s</div>\n' % ( self.builder.config.slide_footer, ), ...
Add the slide footer to the output if enabled.
Below is the the instruction that describes the task: ### Input: Add the slide footer to the output if enabled. ### Response: def _add_slide_footer(self, slide_no): """Add the slide footer to the output if enabled.""" if self.builder.config.slide_footer: self.body.append( ...
def p_variable_declaration_list(self, p): """ variable_declaration_list \ : variable_declaration | variable_declaration_list COMMA variable_declaration """ if len(p) == 2: p[0] = [p[1]] else: p[1].append(p[3]) p[0] = p[1...
variable_declaration_list \ : variable_declaration | variable_declaration_list COMMA variable_declaration
Below is the the instruction that describes the task: ### Input: variable_declaration_list \ : variable_declaration | variable_declaration_list COMMA variable_declaration ### Response: def p_variable_declaration_list(self, p): """ variable_declaration_list \ : va...
def main(): """Command line interface for the ``coloredlogs`` program.""" actions = [] try: # Parse the command line arguments. options, arguments = getopt.getopt(sys.argv[1:], 'cdh', [ 'convert', 'to-html', 'demo', 'help', ]) # Map command line options to actions...
Command line interface for the ``coloredlogs`` program.
Below is the the instruction that describes the task: ### Input: Command line interface for the ``coloredlogs`` program. ### Response: def main(): """Command line interface for the ``coloredlogs`` program.""" actions = [] try: # Parse the command line arguments. options, arguments = get...
def register_view(self): """ Display registration form and create new User.""" safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_LOGIN_ENDPOINT) safe_reg_next_url = self._get_safe_next_url('reg_next', self.USER_AFTER_REGISTER_ENDPOINT) # Initialize form login_form...
Display registration form and create new User.
Below is the the instruction that describes the task: ### Input: Display registration form and create new User. ### Response: def register_view(self): """ Display registration form and create new User.""" safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_LOGIN_ENDPOINT) safe_...
def commit(ctx, commands, blank, check, sync, comment, confirm, at_time): """ Execute a commit against the device. Purpose: This function will send set commands to a device, and commit | the changes. Options exist for confirming, comments, | synchronizing, checking, blank commits, or dela...
Execute a commit against the device. Purpose: This function will send set commands to a device, and commit | the changes. Options exist for confirming, comments, | synchronizing, checking, blank commits, or delaying to a later | time/date. @param ctx: The click context paramte...
Below is the the instruction that describes the task: ### Input: Execute a commit against the device. Purpose: This function will send set commands to a device, and commit | the changes. Options exist for confirming, comments, | synchronizing, checking, blank commits, or delaying to a lat...
def translate_to_english_phonetic_alphabet(self, hide_stress_mark=False): ''' 转换成英音。只要一个元音的时候需要隐藏重音标识 :param hide_stress_mark: :return: ''' translations = self.stress.mark_ipa() if (not hide_stress_mark) and self.have_vowel else "" for phoneme in self._phoneme_l...
转换成英音。只要一个元音的时候需要隐藏重音标识 :param hide_stress_mark: :return:
Below is the the instruction that describes the task: ### Input: 转换成英音。只要一个元音的时候需要隐藏重音标识 :param hide_stress_mark: :return: ### Response: def translate_to_english_phonetic_alphabet(self, hide_stress_mark=False): ''' 转换成英音。只要一个元音的时候需要隐藏重音标识 :param hide_stress_mark: :re...
def get_dict(cls): """ Return dictionary with conspect / subconspect info. """ mdt = cls.get() if not mdt: return {} return conspectus.subs_by_mdt.get(mdt, {})
Return dictionary with conspect / subconspect info.
Below is the the instruction that describes the task: ### Input: Return dictionary with conspect / subconspect info. ### Response: def get_dict(cls): """ Return dictionary with conspect / subconspect info. """ mdt = cls.get() if not mdt: return {} retur...
def findLibrary(name): """ Look for a library in the system. Emulate the algorithm used by dlopen. `name`must include the prefix, e.g. ``libpython2.4.so`` """ assert is_unix, "Current implementation for Unix only (Linux, Solaris, AIX)" lib = None # Look in the LD_LIBRARY_PATH lp =...
Look for a library in the system. Emulate the algorithm used by dlopen. `name`must include the prefix, e.g. ``libpython2.4.so``
Below is the the instruction that describes the task: ### Input: Look for a library in the system. Emulate the algorithm used by dlopen. `name`must include the prefix, e.g. ``libpython2.4.so`` ### Response: def findLibrary(name): """ Look for a library in the system. Emulate the algorithm use...
def search_alert_deleted_for_facet(self, facet, **kwargs): # noqa: E501 """Lists the values of a specific facet over the customer's deleted alerts # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asy...
Lists the values of a specific facet over the customer's deleted alerts # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.search_alert_deleted_for_facet(facet, async_req...
Below is the the instruction that describes the task: ### Input: Lists the values of a specific facet over the customer's deleted alerts # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
def _update_limits_from_api(self): """ Query EC2's DescribeAccountAttributes API action and update the network interface limit, as needed. Updates ``self.limits``. More info on the network interface limit, from the docs: 'This limit is the greater of either the default limit (35...
Query EC2's DescribeAccountAttributes API action and update the network interface limit, as needed. Updates ``self.limits``. More info on the network interface limit, from the docs: 'This limit is the greater of either the default limit (350) or your On-Demand Instance limit multiplied ...
Below is the the instruction that describes the task: ### Input: Query EC2's DescribeAccountAttributes API action and update the network interface limit, as needed. Updates ``self.limits``. More info on the network interface limit, from the docs: 'This limit is the greater of either the def...
def send_messages(self, messages): """ Send messages. :param list messages: List of SmsMessage instances. :returns: number of messages sended successful. :rtype: int """ counter = 0 for message in messages: res, _ = self._send(message) ...
Send messages. :param list messages: List of SmsMessage instances. :returns: number of messages sended successful. :rtype: int
Below is the the instruction that describes the task: ### Input: Send messages. :param list messages: List of SmsMessage instances. :returns: number of messages sended successful. :rtype: int ### Response: def send_messages(self, messages): """ Send messages. :para...
def get_calls_from_dict(self, file_dict, from_name, settings={}): ''' Processes unfolded yaml object to CallEdge array settings is a dict of settings for keeping information like in what section we are right now (e.g. builders, publishers) ''' calls = [] call_se...
Processes unfolded yaml object to CallEdge array settings is a dict of settings for keeping information like in what section we are right now (e.g. builders, publishers)
Below is the the instruction that describes the task: ### Input: Processes unfolded yaml object to CallEdge array settings is a dict of settings for keeping information like in what section we are right now (e.g. builders, publishers) ### Response: def get_calls_from_dict(self, file_dict, from_nam...
def comment(self, comment): """ Add a :class:`Comment <pypump.models.comment.Comment>` to the object. :param comment: A :class:`Comment <pypump.models.comment.Comment>` instance, text content is also accepted. Example: >>> anote.comment(pump.Comment('I agree!'))...
Add a :class:`Comment <pypump.models.comment.Comment>` to the object. :param comment: A :class:`Comment <pypump.models.comment.Comment>` instance, text content is also accepted. Example: >>> anote.comment(pump.Comment('I agree!'))
Below is the the instruction that describes the task: ### Input: Add a :class:`Comment <pypump.models.comment.Comment>` to the object. :param comment: A :class:`Comment <pypump.models.comment.Comment>` instance, text content is also accepted. Example: >>> anote.comm...
def operation_file(uploader, cmd, filename=''): """File operations""" if cmd == 'list': operation_list(uploader) if cmd == 'do': for path in filename: uploader.file_do(path) elif cmd == 'format': uploader.file_format() elif cmd == 'remove': for path in fil...
File operations
Below is the the instruction that describes the task: ### Input: File operations ### Response: def operation_file(uploader, cmd, filename=''): """File operations""" if cmd == 'list': operation_list(uploader) if cmd == 'do': for path in filename: uploader.file_do(path) el...
def loadScopeGroupbyName(self, name, service_group_id, callback=None, errback=None): """ Load an existing Scope Group by name and service group id into a high level Scope Group object :param str name: Name of an existing Scope Group :param int service_group_id: id of the service group t...
Load an existing Scope Group by name and service group id into a high level Scope Group object :param str name: Name of an existing Scope Group :param int service_group_id: id of the service group the Scope group is associated with
Below is the the instruction that describes the task: ### Input: Load an existing Scope Group by name and service group id into a high level Scope Group object :param str name: Name of an existing Scope Group :param int service_group_id: id of the service group the Scope group is associated with ##...
def week(self): """ Returns an ``int`` of the week number in the season, such as 1 for the first week of the regular season. """ if self._week.lower() == 'wild card': return WILD_CARD if self._week.lower() == 'division': return DIVISION if ...
Returns an ``int`` of the week number in the season, such as 1 for the first week of the regular season.
Below is the the instruction that describes the task: ### Input: Returns an ``int`` of the week number in the season, such as 1 for the first week of the regular season. ### Response: def week(self): """ Returns an ``int`` of the week number in the season, such as 1 for the first we...
def _wrap(text, columns=80): """ Own "dumb" reimplementation of textwrap.wrap(). This is because calling .wrap() on bigger strings can take a LOT of processor power. And I mean like 8 seconds of 3GHz CPU just to wrap 20kB of text without spaces. Args: text (str): Text to wrap. ...
Own "dumb" reimplementation of textwrap.wrap(). This is because calling .wrap() on bigger strings can take a LOT of processor power. And I mean like 8 seconds of 3GHz CPU just to wrap 20kB of text without spaces. Args: text (str): Text to wrap. columns (int): Wrap after `columns` chara...
Below is the the instruction that describes the task: ### Input: Own "dumb" reimplementation of textwrap.wrap(). This is because calling .wrap() on bigger strings can take a LOT of processor power. And I mean like 8 seconds of 3GHz CPU just to wrap 20kB of text without spaces. Args: text (...
def SetCACertificatesPath(self, ca_certificates_path): """Sets the path to the CA certificates. Args: ca_certificates_path (str): path to file containing a list of root certificates to trust. Raises: BadConfigOption: if the CA certificates file does not exist. """ if not ca_cer...
Sets the path to the CA certificates. Args: ca_certificates_path (str): path to file containing a list of root certificates to trust. Raises: BadConfigOption: if the CA certificates file does not exist.
Below is the the instruction that describes the task: ### Input: Sets the path to the CA certificates. Args: ca_certificates_path (str): path to file containing a list of root certificates to trust. Raises: BadConfigOption: if the CA certificates file does not exist. ### Response: def...
def check_cache(path): """Return true if the cache file holding list of all datasets does not exist or is older than 30 days """ if not os.path.exists(path): return True else: # check the age mod_date = datetime.fromtimestamp(os.path.getmtime(path)) if mod_date < (dat...
Return true if the cache file holding list of all datasets does not exist or is older than 30 days
Below is the the instruction that describes the task: ### Input: Return true if the cache file holding list of all datasets does not exist or is older than 30 days ### Response: def check_cache(path): """Return true if the cache file holding list of all datasets does not exist or is older than 30 days ...
def handleCardDblClick( self, item ): """ Handles when a card item is double clicked on. :param item | <QTreeWidgetItem> """ widget = self.uiCardTREE.itemWidget(item, 0) if ( isinstance(widget, XAbstractCardWidget) ): self.emitRecordDoubl...
Handles when a card item is double clicked on. :param item | <QTreeWidgetItem>
Below is the the instruction that describes the task: ### Input: Handles when a card item is double clicked on. :param item | <QTreeWidgetItem> ### Response: def handleCardDblClick( self, item ): """ Handles when a card item is double clicked on. :param ...
def init_logging(): """Initialise Python logging.""" fmt = '%(asctime)s.%(msecs)03d | %(name)-60s | %(levelname)-7s ' \ '| %(message)s' logging.basicConfig(format=fmt, datefmt='%H:%M:%S', level=logging.DEBUG)
Initialise Python logging.
Below is the the instruction that describes the task: ### Input: Initialise Python logging. ### Response: def init_logging(): """Initialise Python logging.""" fmt = '%(asctime)s.%(msecs)03d | %(name)-60s | %(levelname)-7s ' \ '| %(message)s' logging.basicConfig(format=fmt, datefmt='%H:%M:%S',...
def gaus_pdf(x, mean, std): '''Gaussian distribution's probability density function. See, e.g. `Wikipedia <https://en.wikipedia.org/wiki/Normal_distribution>`_. :param x: point in x-axis :type x: float or numpy.ndarray :param float mean: mean or expectation :param float str: standard deviation...
Gaussian distribution's probability density function. See, e.g. `Wikipedia <https://en.wikipedia.org/wiki/Normal_distribution>`_. :param x: point in x-axis :type x: float or numpy.ndarray :param float mean: mean or expectation :param float str: standard deviation :returns: pdf(s) in point **x*...
Below is the the instruction that describes the task: ### Input: Gaussian distribution's probability density function. See, e.g. `Wikipedia <https://en.wikipedia.org/wiki/Normal_distribution>`_. :param x: point in x-axis :type x: float or numpy.ndarray :param float mean: mean or expectation :p...
def _handle_id(self, node, scope, ctxt, stream): """Handle an ID node (return a field object for the ID) :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ if node.name == "__root": return self._root if node.name ==...
Handle an ID node (return a field object for the ID) :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
Below is the the instruction that describes the task: ### Input: Handle an ID node (return a field object for the ID) :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO ### Response: def _handle_id(self, node, scope, ctxt, stream): """Handle an ID nod...
def time_from_match(match_object): """Create a time object from a regular expression match. The regular expression match is expected to be from RE_TIME or RE_DATETIME. @param match_object: The regular expression match. @type value: B{re}.I{MatchObject} @return: A date object. @rtype: B{datetim...
Create a time object from a regular expression match. The regular expression match is expected to be from RE_TIME or RE_DATETIME. @param match_object: The regular expression match. @type value: B{re}.I{MatchObject} @return: A date object. @rtype: B{datetime}.I{time}
Below is the the instruction that describes the task: ### Input: Create a time object from a regular expression match. The regular expression match is expected to be from RE_TIME or RE_DATETIME. @param match_object: The regular expression match. @type value: B{re}.I{MatchObject} @return: A date ob...
def write(self, valuedict, version): """Generates the lines for the converted input file from the valuedict. :arg valuedict: a dictionary of values where the keys are ids in the template and the values obey their template rules. :arg version: the target version of the output file. ...
Generates the lines for the converted input file from the valuedict. :arg valuedict: a dictionary of values where the keys are ids in the template and the values obey their template rules. :arg version: the target version of the output file.
Below is the the instruction that describes the task: ### Input: Generates the lines for the converted input file from the valuedict. :arg valuedict: a dictionary of values where the keys are ids in the template and the values obey their template rules. :arg version: the target version of...
def update(self): """ Fetches the updated ring from Redis and updates the current ranges. """ ring = self._fetch() n_replicas = len(ring) replica_set = set([r[1] for r in self.replicas]) self.ranges = [] for n, (start, replica) in enumerate(ring): ...
Fetches the updated ring from Redis and updates the current ranges.
Below is the the instruction that describes the task: ### Input: Fetches the updated ring from Redis and updates the current ranges. ### Response: def update(self): """ Fetches the updated ring from Redis and updates the current ranges. """ ring = self._fetch() n_replicas = ...
def _post_run_hook(self, runtime): ''' generates a report showing slices from each axis of an arbitrary volume of in_file, with the resulting binary brain mask overlaid ''' self._anat_file = self.inputs.in_file self._mask_file = self.aggregate_outputs(runtime=runtime).mask_file ...
generates a report showing slices from each axis of an arbitrary volume of in_file, with the resulting binary brain mask overlaid
Below is the the instruction that describes the task: ### Input: generates a report showing slices from each axis of an arbitrary volume of in_file, with the resulting binary brain mask overlaid ### Response: def _post_run_hook(self, runtime): ''' generates a report showing slices from each axis of...
def fullpath(relpath): '''Relative path to absolute''' if (type(relpath) is object or type(relpath) is file): relpath = relpath.name return os.path.abspath(os.path.expanduser(relpath))
Relative path to absolute
Below is the the instruction that describes the task: ### Input: Relative path to absolute ### Response: def fullpath(relpath): '''Relative path to absolute''' if (type(relpath) is object or type(relpath) is file): relpath = relpath.name return os.path.abspath(os.path.expanduser(relpath))
def long_to_hex(l, size): """Encode a long value as a hex string, 0-padding to size. Note that size is the size of the resulting hex string. So, for a 32Byte long size should be 64 (two hex characters per byte".""" f_str = "{0:0%sx}" % size return ensure_bytes(f_str.format(l).lower())
Encode a long value as a hex string, 0-padding to size. Note that size is the size of the resulting hex string. So, for a 32Byte long size should be 64 (two hex characters per byte".
Below is the the instruction that describes the task: ### Input: Encode a long value as a hex string, 0-padding to size. Note that size is the size of the resulting hex string. So, for a 32Byte long size should be 64 (two hex characters per byte". ### Response: def long_to_hex(l, size): """Encode a lo...
def _push_property_schema(self, prop): """Construct a sub-schema from a property of the current schema.""" schema = Schema(self._schema.properties[prop]) self._push_schema(schema, ".properties." + prop)
Construct a sub-schema from a property of the current schema.
Below is the the instruction that describes the task: ### Input: Construct a sub-schema from a property of the current schema. ### Response: def _push_property_schema(self, prop): """Construct a sub-schema from a property of the current schema.""" schema = Schema(self._schema.properties[prop]) ...
def threshold_monitor_hidden_threshold_monitor_sfp_apply(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor") threshold_monito...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def threshold_monitor_hidden_threshold_monitor_sfp_apply(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") threshold_monitor_hidden = ET.SubElement(config, "thr...
def publishing_prepare_published_copy(self, draft_obj): """ Prepare published copy of draft prior to saving it """ # We call super here, somewhat perversely, to ensure this method will # be called on publishable subclasses if implemented there. mysuper = super(PublishingModel, self) ...
Prepare published copy of draft prior to saving it
Below is the the instruction that describes the task: ### Input: Prepare published copy of draft prior to saving it ### Response: def publishing_prepare_published_copy(self, draft_obj): """ Prepare published copy of draft prior to saving it """ # We call super here, somewhat perversely, to ensure t...
def set_field_value(self, name, value): """ Set the value to the field modified_data """ name = self.get_real_name(name) if not name or not self._can_write_field(name): return if name in self.__deleted_fields__: self.__deleted_fields__.remove(nam...
Set the value to the field modified_data
Below is the the instruction that describes the task: ### Input: Set the value to the field modified_data ### Response: def set_field_value(self, name, value): """ Set the value to the field modified_data """ name = self.get_real_name(name) if not name or not self._can_writ...
def zero_state(qubits: Union[int, Qubits]) -> State: """Return the all-zero state on N qubits""" N, qubits = qubits_count_tuple(qubits) ket = np.zeros(shape=[2] * N) ket[(0,) * N] = 1 return State(ket, qubits)
Return the all-zero state on N qubits
Below is the the instruction that describes the task: ### Input: Return the all-zero state on N qubits ### Response: def zero_state(qubits: Union[int, Qubits]) -> State: """Return the all-zero state on N qubits""" N, qubits = qubits_count_tuple(qubits) ket = np.zeros(shape=[2] * N) ket[(0,) * N] = ...
def construct_codons_dict(alphabet_file = None): """Generate the sub_codons_right dictionary of codon suffixes. syntax of custom alphabet_files: char: list,of,amino,acids,or,codons,separated,by,commas Parameters ---------- alphabet_file : str File name for a custom al...
Generate the sub_codons_right dictionary of codon suffixes. syntax of custom alphabet_files: char: list,of,amino,acids,or,codons,separated,by,commas Parameters ---------- alphabet_file : str File name for a custom alphabet definition. If no file is provided, the ...
Below is the the instruction that describes the task: ### Input: Generate the sub_codons_right dictionary of codon suffixes. syntax of custom alphabet_files: char: list,of,amino,acids,or,codons,separated,by,commas Parameters ---------- alphabet_file : str File name fo...
def oauth_connect(self, provider, action): """ This endpoint doesn't check if user is logged in, because it has two functions 1. If the user is not logged in, it will try to signup the user - if the social info exist, it will login - not, it will create a new account and...
This endpoint doesn't check if user is logged in, because it has two functions 1. If the user is not logged in, it will try to signup the user - if the social info exist, it will login - not, it will create a new account and proceed 2. If user is logged in, it will try to create...
Below is the the instruction that describes the task: ### Input: This endpoint doesn't check if user is logged in, because it has two functions 1. If the user is not logged in, it will try to signup the user - if the social info exist, it will login - not, it will create a new accou...