code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _get_abstract_layer_name(self): """ Looks for the name of abstracted layer. Usually these layers appears when model is stacked. :return: List of abstracted layers """ abstract_layers = [] for layer in self.model.layers: if 'layers' in layer.get_config(): abstract_layers.app...
Looks for the name of abstracted layer. Usually these layers appears when model is stacked. :return: List of abstracted layers
Below is the the instruction that describes the task: ### Input: Looks for the name of abstracted layer. Usually these layers appears when model is stacked. :return: List of abstracted layers ### Response: def _get_abstract_layer_name(self): """ Looks for the name of abstracted layer. Usually t...
def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._created is not None: return False if self._updated is not None: return False if self._type_ is not None: return Fa...
:rtype: bool
Below is the the instruction that describes the task: ### Input: :rtype: bool ### Response: def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._created is not None: return False if self._updated...
def pc( self ): """ e.g. 1000 x 2 U[:, :npc] * d[:npc], to plot etc. """ n = self.npc return self.U[:, :n] * self.d[:n]
e.g. 1000 x 2 U[:, :npc] * d[:npc], to plot etc.
Below is the the instruction that describes the task: ### Input: e.g. 1000 x 2 U[:, :npc] * d[:npc], to plot etc. ### Response: def pc( self ): """ e.g. 1000 x 2 U[:, :npc] * d[:npc], to plot etc. """ n = self.npc return self.U[:, :n] * self.d[:n]
def tell(self, message, sender=no_sender): """ Send a message to this actor. Asynchronous fire-and-forget. :param message: The message to send. :type message: Any :param sender: The sender of the message. If provided it will be made available to the receiving actor via the ...
Send a message to this actor. Asynchronous fire-and-forget. :param message: The message to send. :type message: Any :param sender: The sender of the message. If provided it will be made available to the receiving actor via the :attr:`Actor.sender` attribute. :type sender: :...
Below is the the instruction that describes the task: ### Input: Send a message to this actor. Asynchronous fire-and-forget. :param message: The message to send. :type message: Any :param sender: The sender of the message. If provided it will be made available to the receiving ...
def _convert_asset_timestamp_fields(dict_): """ Takes in a dict of Asset init args and converts dates to pd.Timestamps """ for key in _asset_timestamp_fields & viewkeys(dict_): value = pd.Timestamp(dict_[key], tz='UTC') dict_[key] = None if isnull(value) else value return dict_
Takes in a dict of Asset init args and converts dates to pd.Timestamps
Below is the the instruction that describes the task: ### Input: Takes in a dict of Asset init args and converts dates to pd.Timestamps ### Response: def _convert_asset_timestamp_fields(dict_): """ Takes in a dict of Asset init args and converts dates to pd.Timestamps """ for key in _asset_timestam...
def copy_extra_files(tile): """Copy all files listed in a copy_files and copy_products section. Files listed in copy_files will be copied from the specified location in the current component to the specified path under the output folder. Files listed in copy_products will be looked up with a Produ...
Copy all files listed in a copy_files and copy_products section. Files listed in copy_files will be copied from the specified location in the current component to the specified path under the output folder. Files listed in copy_products will be looked up with a ProductResolver and copied copied to...
Below is the the instruction that describes the task: ### Input: Copy all files listed in a copy_files and copy_products section. Files listed in copy_files will be copied from the specified location in the current component to the specified path under the output folder. Files listed in copy_produ...
def point_to_t(self, point): """If the point lies on the Arc, returns its `t` parameter. If the point does not lie on the Arc, returns None. This function only works on Arcs with rotation == 0.0""" def in_range(min, max, val): return (min <= val) and (max >= val) # ...
If the point lies on the Arc, returns its `t` parameter. If the point does not lie on the Arc, returns None. This function only works on Arcs with rotation == 0.0
Below is the the instruction that describes the task: ### Input: If the point lies on the Arc, returns its `t` parameter. If the point does not lie on the Arc, returns None. This function only works on Arcs with rotation == 0.0 ### Response: def point_to_t(self, point): """If the point lies...
def _reset(self): ''' _reset - reset this object. Assigned to .reset after __init__ call. ''' HTMLParser.reset(self) self.root = None self.doctype = None self._inTag = []
_reset - reset this object. Assigned to .reset after __init__ call.
Below is the the instruction that describes the task: ### Input: _reset - reset this object. Assigned to .reset after __init__ call. ### Response: def _reset(self): ''' _reset - reset this object. Assigned to .reset after __init__ call. ''' HTMLParser.reset(self) self.r...
def raise_db_exception(self): """ Raises exception from last server message This function will skip messages: The statement has been terminated """ if not self.messages: raise tds_base.Error("Request failed, server didn't send error message") msg = None while...
Raises exception from last server message This function will skip messages: The statement has been terminated
Below is the the instruction that describes the task: ### Input: Raises exception from last server message This function will skip messages: The statement has been terminated ### Response: def raise_db_exception(self): """ Raises exception from last server message This function will skip ...
def _add_new(self, host_object): """Add a new host to the collection. Before a new hostname can be added, all its subdomains already present in the collection must be removed. Since the collection is sorted, we can limit our search for them to a slice of the collection starting ...
Add a new host to the collection. Before a new hostname can be added, all its subdomains already present in the collection must be removed. Since the collection is sorted, we can limit our search for them to a slice of the collection starting from insertion point and ending with ...
Below is the the instruction that describes the task: ### Input: Add a new host to the collection. Before a new hostname can be added, all its subdomains already present in the collection must be removed. Since the collection is sorted, we can limit our search for them to a slice of ...
def _get_file_magic_name(self, buffer): """ Return the filetype guessed for a buffer :param buffer: bytes :returns: str of filetype """ default = "Unknown" # Faster way, test once, return default. if self.__no_magic: return default tr...
Return the filetype guessed for a buffer :param buffer: bytes :returns: str of filetype
Below is the the instruction that describes the task: ### Input: Return the filetype guessed for a buffer :param buffer: bytes :returns: str of filetype ### Response: def _get_file_magic_name(self, buffer): """ Return the filetype guessed for a buffer :param buffer: bytes ...
def stop_message_live_location(self, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None): """ Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires :param chat_id: :param message_...
Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires :param chat_id: :param message_id: :param inline_message_id: :param reply_markup: :return:
Below is the the instruction that describes the task: ### Input: Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires :param chat_id: :param message_id: :param inline_message_id: :param reply_mark...
def _fill_matrix(rot_crop_matrix, eigvectors): """ Helper function for opt_soft """ (x, y) = rot_crop_matrix.shape row_sums = np.sum(rot_crop_matrix, axis=1) row_sums = np.reshape(row_sums, (x, 1)) # add -row_sums as leftmost column to rot_crop_matrix rot_crop_matrix = np.concatenate...
Helper function for opt_soft
Below is the the instruction that describes the task: ### Input: Helper function for opt_soft ### Response: def _fill_matrix(rot_crop_matrix, eigvectors): """ Helper function for opt_soft """ (x, y) = rot_crop_matrix.shape row_sums = np.sum(rot_crop_matrix, axis=1) row_sums = np.reshape(...
def unmount_path(path, force=False): """ Unmounts the directory specified by path. """ r = util.subp(['umount', path]) if not force: if r.return_code != 0: raise ValueError(r.stderr)
Unmounts the directory specified by path.
Below is the the instruction that describes the task: ### Input: Unmounts the directory specified by path. ### Response: def unmount_path(path, force=False): """ Unmounts the directory specified by path. """ r = util.subp(['umount', path]) if not force: if r.retu...
def is_header(line): """true if we are in a header""" if re.match('^@',line): f = line.rstrip().split("\t") if(len(f) > 9): return False return True return False
true if we are in a header
Below is the the instruction that describes the task: ### Input: true if we are in a header ### Response: def is_header(line): """true if we are in a header""" if re.match('^@',line): f = line.rstrip().split("\t") if(len(f) > 9): return False return True return False
def average_balance_recharges(user, **kwargs): """ Return the average daily balance estimated from all recharges. We assume a linear usage between two recharges, and an empty balance before a recharge. The average balance can be seen as the area under the curve delimited by all recharges. """ ...
Return the average daily balance estimated from all recharges. We assume a linear usage between two recharges, and an empty balance before a recharge. The average balance can be seen as the area under the curve delimited by all recharges.
Below is the the instruction that describes the task: ### Input: Return the average daily balance estimated from all recharges. We assume a linear usage between two recharges, and an empty balance before a recharge. The average balance can be seen as the area under the curve delimited by all recharges....
def parse_geo_tiff( key_dir_vlr: GeoKeyDirectoryVlr, double_vlr: GeoDoubleParamsVlr, ascii_vlr: GeoAsciiParamsVlr, ) -> List[GeoTiffKey]: """ Parses the GeoTiff VLRs information into nicer structs """ geotiff_keys = [] for k in key_dir_vlr.geo_keys: if k.tiff_tag_location == 0: ...
Parses the GeoTiff VLRs information into nicer structs
Below is the the instruction that describes the task: ### Input: Parses the GeoTiff VLRs information into nicer structs ### Response: def parse_geo_tiff( key_dir_vlr: GeoKeyDirectoryVlr, double_vlr: GeoDoubleParamsVlr, ascii_vlr: GeoAsciiParamsVlr, ) -> List[GeoTiffKey]: """ Parses the GeoTiff VLRs...
def setText(self, value): """ Set the element's L{Text} content. @param value: The element's text value. @type value: basestring @return: self @rtype: I{Element} """ if isinstance(value, Text): self.text = value else: self.t...
Set the element's L{Text} content. @param value: The element's text value. @type value: basestring @return: self @rtype: I{Element}
Below is the the instruction that describes the task: ### Input: Set the element's L{Text} content. @param value: The element's text value. @type value: basestring @return: self @rtype: I{Element} ### Response: def setText(self, value): """ Set the element's L{Text} ...
def _get_all_scanner_ids(zap_helper): """Get all scanner IDs.""" scanners = zap_helper.zap.ascan.scanners() return [s['id'] for s in scanners]
Get all scanner IDs.
Below is the the instruction that describes the task: ### Input: Get all scanner IDs. ### Response: def _get_all_scanner_ids(zap_helper): """Get all scanner IDs.""" scanners = zap_helper.zap.ascan.scanners() return [s['id'] for s in scanners]
def intersection(self, keys): """ Return the intersection of the segmentlists associated with the keys in keys. """ keys = set(keys) if not keys: return segmentlist() seglist = _shallowcopy(self[keys.pop()]) for key in keys: seglist &= self[key] return seglist
Return the intersection of the segmentlists associated with the keys in keys.
Below is the the instruction that describes the task: ### Input: Return the intersection of the segmentlists associated with the keys in keys. ### Response: def intersection(self, keys): """ Return the intersection of the segmentlists associated with the keys in keys. """ keys = set(keys) if not keys...
def generate_error(request, cls, e, tb, include_traceback=False): """ Builds an L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} based on the last traceback and the request that was sent. """ import traceback if hasattr(cls, '_amf_code'): code = cls._amf_code else: code = ...
Builds an L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} based on the last traceback and the request that was sent.
Below is the the instruction that describes the task: ### Input: Builds an L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} based on the last traceback and the request that was sent. ### Response: def generate_error(request, cls, e, tb, include_traceback=False): """ Builds an L{ErrorMessage<pyamf.fle...
def FDMT_initialization(datain, f_min, f_max, maxDT, dataType): """ Input: datain - visibilities of (nint, nbl, nchan, npol) f_min,f_max - are the base-band begin and end frequencies. The frequencies can be entered in both MHz and GHz, units are factored out in all uses. maxDT - the ...
Input: datain - visibilities of (nint, nbl, nchan, npol) f_min,f_max - are the base-band begin and end frequencies. The frequencies can be entered in both MHz and GHz, units are factored out in all uses. maxDT - the maximal delay (in time bins) of the maximal dispersion. Appears ...
Below is the the instruction that describes the task: ### Input: Input: datain - visibilities of (nint, nbl, nchan, npol) f_min,f_max - are the base-band begin and end frequencies. The frequencies can be entered in both MHz and GHz, units are factored out in all uses. maxDT - the maximal...
def NewFromRgb(r, g, b, alpha=1.0, wref=_DEFAULT_WREF): '''Create a new instance based on the specifed RGB values. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alpha: The color...
Create a new instance based on the specifed RGB values. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: T...
Below is the the instruction that describes the task: ### Input: Create a new instance based on the specifed RGB values. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alpha: The...
def shutdown(cls): """Close all connections on in all pools""" for pid in list(cls._pools.keys()): cls._pools[pid].shutdown() LOGGER.info('Shutdown complete, all pooled connections closed')
Close all connections on in all pools
Below is the the instruction that describes the task: ### Input: Close all connections on in all pools ### Response: def shutdown(cls): """Close all connections on in all pools""" for pid in list(cls._pools.keys()): cls._pools[pid].shutdown() LOGGER.info('Shutdown complete, all ...
def sanitize(url, config): """ Obtains dump of an Postgres database by executing `pg_dump` command and sanitizes it's output. :param url: URL to the database which is going to be sanitized, parsed by Python's URL parser. :type url: six.moves.urllib.parse.ParseResult :param conf...
Obtains dump of an Postgres database by executing `pg_dump` command and sanitizes it's output. :param url: URL to the database which is going to be sanitized, parsed by Python's URL parser. :type url: six.moves.urllib.parse.ParseResult :param config: Optional sanitizer configuration to...
Below is the the instruction that describes the task: ### Input: Obtains dump of an Postgres database by executing `pg_dump` command and sanitizes it's output. :param url: URL to the database which is going to be sanitized, parsed by Python's URL parser. :type url: six.moves.urllib.pars...
def get_person_by_prox_rfid(self, prox_rfid): """ Returns a restclients.Person object for the given rfid. If the rfid isn't found, or if there is an error communicating with the IdCard WS, a DataFailureException will be thrown. """ if not self.valid_prox_rfid(prox_rfid):...
Returns a restclients.Person object for the given rfid. If the rfid isn't found, or if there is an error communicating with the IdCard WS, a DataFailureException will be thrown.
Below is the the instruction that describes the task: ### Input: Returns a restclients.Person object for the given rfid. If the rfid isn't found, or if there is an error communicating with the IdCard WS, a DataFailureException will be thrown. ### Response: def get_person_by_prox_rfid(self, prox_rf...
def tracebacks_from_file(fileobj, reverse=False): """Generator that yields tracebacks found in a file object With reverse=True, searches backwards from the end of the file. """ if reverse: lines = deque() for line in BackwardsReader(fileobj): lines.appendleft(line) ...
Generator that yields tracebacks found in a file object With reverse=True, searches backwards from the end of the file.
Below is the the instruction that describes the task: ### Input: Generator that yields tracebacks found in a file object With reverse=True, searches backwards from the end of the file. ### Response: def tracebacks_from_file(fileobj, reverse=False): """Generator that yields tracebacks found in a file objec...
def update_node(cls, cluster_id_label, command, private_dns, parameters=None): """ Add a node to an existing cluster """ conn = Qubole.agent(version=Cluster.api_version) parameters = {} if not parameters else parameters data = {"command" : command, "private_dns" : private...
Add a node to an existing cluster
Below is the the instruction that describes the task: ### Input: Add a node to an existing cluster ### Response: def update_node(cls, cluster_id_label, command, private_dns, parameters=None): """ Add a node to an existing cluster """ conn = Qubole.agent(version=Cluster.api_version) ...
def get_bucket_notification_config(self, bucket): """ Get the notification configuration of a bucket. @param bucket: The name of the bucket. @return: A C{Deferred} that will request the bucket's notification configuration. """ details = self._details( ...
Get the notification configuration of a bucket. @param bucket: The name of the bucket. @return: A C{Deferred} that will request the bucket's notification configuration.
Below is the the instruction that describes the task: ### Input: Get the notification configuration of a bucket. @param bucket: The name of the bucket. @return: A C{Deferred} that will request the bucket's notification configuration. ### Response: def get_bucket_notification_config(self, b...
def find(self, y): """Returns starting position of the substring y in the string used for building the Suffix tree. :param y: String :return: Index of the starting position of string y in the string used for building the Suffix tree -1 if y is not a substring. "...
Returns starting position of the substring y in the string used for building the Suffix tree. :param y: String :return: Index of the starting position of string y in the string used for building the Suffix tree -1 if y is not a substring.
Below is the the instruction that describes the task: ### Input: Returns starting position of the substring y in the string used for building the Suffix tree. :param y: String :return: Index of the starting position of string y in the string used for building the Suffix tree ...
def launchapp(self, cmd, args=[], delay=0, env=1, lang="C"): """ Launch application. @param cmd: Command line string to execute. @type cmd: string @param args: Arguments to the application @type args: list @param delay: Delay after the application is launched ...
Launch application. @param cmd: Command line string to execute. @type cmd: string @param args: Arguments to the application @type args: list @param delay: Delay after the application is launched @type delay: int @param env: GNOME accessibility environment to be s...
Below is the the instruction that describes the task: ### Input: Launch application. @param cmd: Command line string to execute. @type cmd: string @param args: Arguments to the application @type args: list @param delay: Delay after the application is launched @type d...
def parse(expression): """ Return array of parsed tokens in the expression expression String: Math expression to parse in infix notation """ result = [] current = "" for i in expression: if i.isdigit() or i == '.': current += i else: if le...
Return array of parsed tokens in the expression expression String: Math expression to parse in infix notation
Below is the the instruction that describes the task: ### Input: Return array of parsed tokens in the expression expression String: Math expression to parse in infix notation ### Response: def parse(expression): """ Return array of parsed tokens in the expression expression String: Math exp...
def ReadPathInfo(self, client_id, path_type, components, timestamp=None, cursor=None): """Retrieves a path info record for a given path.""" if timestamp is None: path_infos = self.ReadPathInfos(client_id, path_t...
Retrieves a path info record for a given path.
Below is the the instruction that describes the task: ### Input: Retrieves a path info record for a given path. ### Response: def ReadPathInfo(self, client_id, path_type, components, timestamp=None, cursor=None): """...
def future_then_immediate(future, func): """Returns a future that maps the result of `future` by `func`. If `future` succeeds, sets the result of the returned future to `func(future.result())`. If `future` fails or `func` raises an exception, the exception is stored in the returned future. If `future...
Returns a future that maps the result of `future` by `func`. If `future` succeeds, sets the result of the returned future to `func(future.result())`. If `future` fails or `func` raises an exception, the exception is stored in the returned future. If `future` has not yet finished, `func` is invoked by the...
Below is the the instruction that describes the task: ### Input: Returns a future that maps the result of `future` by `func`. If `future` succeeds, sets the result of the returned future to `func(future.result())`. If `future` fails or `func` raises an exception, the exception is stored in the returned fu...
def GetCredentials(package_name, scopes, client_id, client_secret, user_agent, credentials_filename=None, api_key=None, # pylint: disable=unused-argument client=None, # pylint: disable=unused-argument oauth2client_args=None, ...
Attempt to get credentials, using an oauth dance as the last resort.
Below is the the instruction that describes the task: ### Input: Attempt to get credentials, using an oauth dance as the last resort. ### Response: def GetCredentials(package_name, scopes, client_id, client_secret, user_agent, credentials_filename=None, api_key=None, # pylint...
def legal_onsets(self, syllables): """ Filters syllable respecting the legality principle :param syllables: str list Example: The method scans for invalid syllable onsets: >>> s = Syllabifier(["i", "u", "y"], ["o", "ø", "e"], ["a"], ["r"], ["l"], ["m", "n"], ["f...
Filters syllable respecting the legality principle :param syllables: str list Example: The method scans for invalid syllable onsets: >>> s = Syllabifier(["i", "u", "y"], ["o", "ø", "e"], ["a"], ["r"], ["l"], ["m", "n"], ["f", "v", "s", "h"], ["k", "g", "b", "p", "t", "d"]) ...
Below is the the instruction that describes the task: ### Input: Filters syllable respecting the legality principle :param syllables: str list Example: The method scans for invalid syllable onsets: >>> s = Syllabifier(["i", "u", "y"], ["o", "ø", "e"], ["a"], ["r"], ["l"], [...
def cat_acc(y, z): """Classification accuracy for multi-categorical case """ weights = _cat_sample_weights(y) _acc = K.cast(K.equal(K.argmax(y, axis=-1), K.argmax(z, axis=-1)), K.floatx()) _acc = K.sum(_acc * weights) / K.sum(weights) return _acc
Classification accuracy for multi-categorical case
Below is the the instruction that describes the task: ### Input: Classification accuracy for multi-categorical case ### Response: def cat_acc(y, z): """Classification accuracy for multi-categorical case """ weights = _cat_sample_weights(y) _acc = K.cast(K.equal(K.argmax(y, axis=-1), ...
def update_DOM(self): """ Makes a request and updates `self._DOM`. Worth using only if you manually change `self.base_url` or `self.path`. :return: self :rtype: Url """ response = self.fetch() self._DOM = html.fromstring(response.text) return self
Makes a request and updates `self._DOM`. Worth using only if you manually change `self.base_url` or `self.path`. :return: self :rtype: Url
Below is the the instruction that describes the task: ### Input: Makes a request and updates `self._DOM`. Worth using only if you manually change `self.base_url` or `self.path`. :return: self :rtype: Url ### Response: def update_DOM(self): """ Makes a request and updates `s...
def _sort_locations(locations): """ Sort locations into "files" (archives) and "urls", and return a pair of lists (files,urls) """ files = [] urls = [] # puts the url for the given file path into the appropriate # list def sort_path(path): ...
Sort locations into "files" (archives) and "urls", and return a pair of lists (files,urls)
Below is the the instruction that describes the task: ### Input: Sort locations into "files" (archives) and "urls", and return a pair of lists (files,urls) ### Response: def _sort_locations(locations): """ Sort locations into "files" (archives) and "urls", and return a pair of lists...
def run(self): """ Start queueing the tasks to the worker cluster :return: the task id """ self.kwargs['cached'] = self.cached self.kwargs['sync'] = self.sync self.kwargs['broker'] = self.broker self.id = async_iter(self.func, self.args, **self.kwargs) ...
Start queueing the tasks to the worker cluster :return: the task id
Below is the the instruction that describes the task: ### Input: Start queueing the tasks to the worker cluster :return: the task id ### Response: def run(self): """ Start queueing the tasks to the worker cluster :return: the task id """ self.kwargs['cached'] = self....
def updateMetadata(self, new): """ Update the metadata stored for this broker. Future connections made to the broker will use the host and port defined in the new metadata. Any existing connection is not dropped, however. :param new: :clas:`afkak.common.Brok...
Update the metadata stored for this broker. Future connections made to the broker will use the host and port defined in the new metadata. Any existing connection is not dropped, however. :param new: :clas:`afkak.common.BrokerMetadata` with the same node ID as the ...
Below is the the instruction that describes the task: ### Input: Update the metadata stored for this broker. Future connections made to the broker will use the host and port defined in the new metadata. Any existing connection is not dropped, however. :param new: :clas:...
def convert_association(self, association: Association) -> Entity: """ 'id' is already `join`ed in both the Association and the Entity, so we don't have to worry about what that looks like. We assume it's correct. """ if "header" not in association or association["header"...
'id' is already `join`ed in both the Association and the Entity, so we don't have to worry about what that looks like. We assume it's correct.
Below is the the instruction that describes the task: ### Input: 'id' is already `join`ed in both the Association and the Entity, so we don't have to worry about what that looks like. We assume it's correct. ### Response: def convert_association(self, association: Association) -> Entity: ""...
def get_diff(self, ignore=[]): """Get the diff to the last time the state of objects was measured. keyword arguments ignore -- list of objects to ignore """ # ignore this and the caller frame ignore.append(inspect.currentframe()) #PYCHOK change ignore self.o1 = ...
Get the diff to the last time the state of objects was measured. keyword arguments ignore -- list of objects to ignore
Below is the the instruction that describes the task: ### Input: Get the diff to the last time the state of objects was measured. keyword arguments ignore -- list of objects to ignore ### Response: def get_diff(self, ignore=[]): """Get the diff to the last time the state of objects was m...
def rest_delete(url, timeout, show_error=False): '''Call rest delete method''' try: response = requests.delete(url, timeout=timeout) return response except Exception as exception: if show_error: print_error(exception) return None
Call rest delete method
Below is the the instruction that describes the task: ### Input: Call rest delete method ### Response: def rest_delete(url, timeout, show_error=False): '''Call rest delete method''' try: response = requests.delete(url, timeout=timeout) return response except Exception as exception: ...
def transaction_type(self, value): """Set the TransactionType (with Input Validation)""" if value is not None: if value not in self.ALLOWED_TRANSACTION_TYPES: raise AttributeError('%s transaction_type element must be one of %s not %s' % ( self.__class__.__...
Set the TransactionType (with Input Validation)
Below is the the instruction that describes the task: ### Input: Set the TransactionType (with Input Validation) ### Response: def transaction_type(self, value): """Set the TransactionType (with Input Validation)""" if value is not None: if value not in self.ALLOWED_TRANSACTION_TYPES: ...
def visit_assert(self, node): """return an astroid.Assert node as string""" if node.fail: return "assert %s, %s" % (node.test.accept(self), node.fail.accept(self)) return "assert %s" % node.test.accept(self)
return an astroid.Assert node as string
Below is the the instruction that describes the task: ### Input: return an astroid.Assert node as string ### Response: def visit_assert(self, node): """return an astroid.Assert node as string""" if node.fail: return "assert %s, %s" % (node.test.accept(self), node.fail.accept(self)) ...
def post_load(fn=None, pass_many=False, pass_original=False): """Register a method to invoke after deserializing an object. The method receives the deserialized data and returns the processed data. By default, receives a single datum at a time, transparently handling the ``many`` argument passed to the...
Register a method to invoke after deserializing an object. The method receives the deserialized data and returns the processed data. By default, receives a single datum at a time, transparently handling the ``many`` argument passed to the Schema. If ``pass_many=True``, the raw data (which may be a coll...
Below is the the instruction that describes the task: ### Input: Register a method to invoke after deserializing an object. The method receives the deserialized data and returns the processed data. By default, receives a single datum at a time, transparently handling the ``many`` argument passed to the...
def basis_function(degree, knot_vector, span, knot): """ Computes the non-vanishing basis functions for a single parameter. Implementation of Algorithm A2.2 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :typ...
Computes the non-vanishing basis functions for a single parameter. Implementation of Algorithm A2.2 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param span: knot span, :math:...
Below is the the instruction that describes the task: ### Input: Computes the non-vanishing basis functions for a single parameter. Implementation of Algorithm A2.2 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` ...
def _complete_word(self, symbol, attribute): """Suggests context completions based exclusively on the word preceding the cursor.""" #The cursor is after a %(,\s and the user is looking for a list #of possibilities that is a bit smarter that regular AC. if self.context.el_call in ...
Suggests context completions based exclusively on the word preceding the cursor.
Below is the the instruction that describes the task: ### Input: Suggests context completions based exclusively on the word preceding the cursor. ### Response: def _complete_word(self, symbol, attribute): """Suggests context completions based exclusively on the word preceding the cursor."""...
def preprocess_dataset(dataset, transform, num_workers=8): """Use multiprocessing to perform transform for dataset. Parameters ---------- dataset: dataset-like object Source dataset. transform: callable Transformer function. num_workers: int, default 8 The number of mult...
Use multiprocessing to perform transform for dataset. Parameters ---------- dataset: dataset-like object Source dataset. transform: callable Transformer function. num_workers: int, default 8 The number of multiprocessing workers to use for data preprocessing.
Below is the the instruction that describes the task: ### Input: Use multiprocessing to perform transform for dataset. Parameters ---------- dataset: dataset-like object Source dataset. transform: callable Transformer function. num_workers: int, default 8 The number of m...
def generate_daily(day_end_hour, use_dst, calib_data, hourly_data, daily_data, process_from): """Generate daily summaries from calibrated and hourly data.""" start = daily_data.before(datetime.max) if start is None: start = datetime.min start = calib_data.after(start + SECOND)...
Generate daily summaries from calibrated and hourly data.
Below is the the instruction that describes the task: ### Input: Generate daily summaries from calibrated and hourly data. ### Response: def generate_daily(day_end_hour, use_dst, calib_data, hourly_data, daily_data, process_from): """Generate daily summaries from calibrated and hourly data."...
def _iter_module_subclasses(package, module_name, base_cls): """inspect all modules in this directory for subclasses of inherit from ``base_cls``. inpiration from http://stackoverflow.com/q/1796180/564709 """ module = importlib.import_module('.' + module_name, package) for name, obj in inspect.getme...
inspect all modules in this directory for subclasses of inherit from ``base_cls``. inpiration from http://stackoverflow.com/q/1796180/564709
Below is the the instruction that describes the task: ### Input: inspect all modules in this directory for subclasses of inherit from ``base_cls``. inpiration from http://stackoverflow.com/q/1796180/564709 ### Response: def _iter_module_subclasses(package, module_name, base_cls): """inspect all modules in ...
def _modeldesc_to_dict(self, md): """Return a string representation of a patsy ModelDesc object""" d = {'lhs_termlist': [md.lhs_termlist[0].factors[0].name()]} rhs_termlist = [] # add other terms, if any for term in md.rhs_termlist[:]: if len(term.factors) == 0: ...
Return a string representation of a patsy ModelDesc object
Below is the the instruction that describes the task: ### Input: Return a string representation of a patsy ModelDesc object ### Response: def _modeldesc_to_dict(self, md): """Return a string representation of a patsy ModelDesc object""" d = {'lhs_termlist': [md.lhs_termlist[0].factors[0].name()]} ...
def object_to_primitive(obj): ''' convert object to primitive type so we can serialize it to data format like python. all primitive types: dict, list, int, float, bool, str, None ''' if obj is None: return obj if isinstance(obj, (int, float, bool, str)): return obj if isin...
convert object to primitive type so we can serialize it to data format like python. all primitive types: dict, list, int, float, bool, str, None
Below is the the instruction that describes the task: ### Input: convert object to primitive type so we can serialize it to data format like python. all primitive types: dict, list, int, float, bool, str, None ### Response: def object_to_primitive(obj): ''' convert object to primitive type so we can s...
def ic(ctext): ''' takes ciphertext, calculates index of coincidence.''' counts = ngram_count(ctext,N=1) icval = 0 for k in counts.keys(): icval += counts[k]*(counts[k]-1) icval /= (len(ctext)*(len(ctext)-1)) return icval
takes ciphertext, calculates index of coincidence.
Below is the the instruction that describes the task: ### Input: takes ciphertext, calculates index of coincidence. ### Response: def ic(ctext): ''' takes ciphertext, calculates index of coincidence.''' counts = ngram_count(ctext,N=1) icval = 0 for k in counts.keys(): icval += counts[k]*(co...
def predict(self, Xnew): """Prediction on the new data Parameters ---------- Xnew : array_like, shape = (n_samples, n_features) The test data. Returns ------- mean : array_like, shape = (n_samples, output.dim) Posterior mean at the locati...
Prediction on the new data Parameters ---------- Xnew : array_like, shape = (n_samples, n_features) The test data. Returns ------- mean : array_like, shape = (n_samples, output.dim) Posterior mean at the location of Xnew var : array_like...
Below is the the instruction that describes the task: ### Input: Prediction on the new data Parameters ---------- Xnew : array_like, shape = (n_samples, n_features) The test data. Returns ------- mean : array_like, shape = (n_samples, output.dim) ...
def get_natural_random_walk_matrix(adjacency_matrix, make_shared=False): """ Returns the natural random walk transition probability matrix given the adjacency matrix. Input: - A: A sparse matrix that contains the adjacency matrix of the graph. Output: - W: A sparse matrix that contains the natural ra...
Returns the natural random walk transition probability matrix given the adjacency matrix. Input: - A: A sparse matrix that contains the adjacency matrix of the graph. Output: - W: A sparse matrix that contains the natural random walk transition probability matrix.
Below is the the instruction that describes the task: ### Input: Returns the natural random walk transition probability matrix given the adjacency matrix. Input: - A: A sparse matrix that contains the adjacency matrix of the graph. Output: - W: A sparse matrix that contains the natural random walk transi...
def _guess_x(self, y_desired, **kwargs): """Choose the relevant neighborhood to feed the inverse model, based on the minimum spread of the corresponding neighborhood in S. for each (x, y) with y neighbor of y_desired, 1. find the neighborhood of x, (xi, yi)_k. 2. compute ...
Choose the relevant neighborhood to feed the inverse model, based on the minimum spread of the corresponding neighborhood in S. for each (x, y) with y neighbor of y_desired, 1. find the neighborhood of x, (xi, yi)_k. 2. compute the standart deviation of the error between yi and y...
Below is the the instruction that describes the task: ### Input: Choose the relevant neighborhood to feed the inverse model, based on the minimum spread of the corresponding neighborhood in S. for each (x, y) with y neighbor of y_desired, 1. find the neighborhood of x, (xi, yi)_k. ...
def add_py_file(self, src, dest=None): """This is a special case of :py:meth:`add_file` that helps for adding a ``py`` when a ``pyc`` may be present as well. So for example, if ``__file__`` is ``foo.pyc`` and you do: .. code-block:: python archive.add_py_file(__file__) ...
This is a special case of :py:meth:`add_file` that helps for adding a ``py`` when a ``pyc`` may be present as well. So for example, if ``__file__`` is ``foo.pyc`` and you do: .. code-block:: python archive.add_py_file(__file__) then this method will add ``foo.py`` instead if...
Below is the the instruction that describes the task: ### Input: This is a special case of :py:meth:`add_file` that helps for adding a ``py`` when a ``pyc`` may be present as well. So for example, if ``__file__`` is ``foo.pyc`` and you do: .. code-block:: python archive.add_py_fi...
def add_footer_part(self): """Return (footer_part, rId) pair for newly-created footer part.""" footer_part = FooterPart.new(self.package) rId = self.relate_to(footer_part, RT.FOOTER) return footer_part, rId
Return (footer_part, rId) pair for newly-created footer part.
Below is the the instruction that describes the task: ### Input: Return (footer_part, rId) pair for newly-created footer part. ### Response: def add_footer_part(self): """Return (footer_part, rId) pair for newly-created footer part.""" footer_part = FooterPart.new(self.package) rId = self.r...
def ec2_route_table_main_route_table_id(self, lookup, default=None): """ Args: lookup: the friendly name of the VPC whose main route table we are looking up default: the optional value to return if lookup failed; returns None if not set Returns: the ID of the main route table of the named ...
Args: lookup: the friendly name of the VPC whose main route table we are looking up default: the optional value to return if lookup failed; returns None if not set Returns: the ID of the main route table of the named VPC, or default if no match/multiple matches found
Below is the the instruction that describes the task: ### Input: Args: lookup: the friendly name of the VPC whose main route table we are looking up default: the optional value to return if lookup failed; returns None if not set Returns: the ID of the main route table of the named VPC, or defa...
def registerEventHandlers(self): """ Registers needed keybinds and schedules the :py:meth:`update` Method. You can control what keybinds are used via the :confval:`controls.controls.forward` etc. Configuration Values. """ # Forward self.peng.keybinds.add(self.pen...
Registers needed keybinds and schedules the :py:meth:`update` Method. You can control what keybinds are used via the :confval:`controls.controls.forward` etc. Configuration Values.
Below is the the instruction that describes the task: ### Input: Registers needed keybinds and schedules the :py:meth:`update` Method. You can control what keybinds are used via the :confval:`controls.controls.forward` etc. Configuration Values. ### Response: def registerEventHandlers(self): ...
def heightmap_set_value(hm: np.ndarray, x: int, y: int, value: float) -> None: """Set the value of a point on a heightmap. .. deprecated:: 2.0 `hm` is a NumPy array, so values should be assigned to it directly. """ if hm.flags["C_CONTIGUOUS"]: warnings.warn( "Assign to this ...
Set the value of a point on a heightmap. .. deprecated:: 2.0 `hm` is a NumPy array, so values should be assigned to it directly.
Below is the the instruction that describes the task: ### Input: Set the value of a point on a heightmap. .. deprecated:: 2.0 `hm` is a NumPy array, so values should be assigned to it directly. ### Response: def heightmap_set_value(hm: np.ndarray, x: int, y: int, value: float) -> None: """Set the ...
def _darwin_current_arch(self): """Add Mac OS X support.""" if sys.platform == "darwin": if sys.maxsize > 2 ** 32: # 64bits. return platform.mac_ver()[2] # Both Darwin and Python are 64bits. else: # Python 32 bits return platform.processor()
Add Mac OS X support.
Below is the the instruction that describes the task: ### Input: Add Mac OS X support. ### Response: def _darwin_current_arch(self): """Add Mac OS X support.""" if sys.platform == "darwin": if sys.maxsize > 2 ** 32: # 64bits. return platform.mac_ver()[2] # Both Darwin an...
async def _attempt_reconnect(self): """ Attempts to reconnect to the Lavalink server. Returns ------- bool ``True`` if the reconnection attempt was successful. """ log.info('Connection closed; attempting to reconnect in 30 seconds') fo...
Attempts to reconnect to the Lavalink server. Returns ------- bool ``True`` if the reconnection attempt was successful.
Below is the the instruction that describes the task: ### Input: Attempts to reconnect to the Lavalink server. Returns ------- bool ``True`` if the reconnection attempt was successful. ### Response: async def _attempt_reconnect(self): """ Attempts to reconn...
def getuvalue(self): """ .. _getuvalue: Get the unsigned value of the Integer, truncate it and handle Overflows. """ bitset = [0] * self.width zero = [1] * self.width for shift in range(self.width): bitset[shift] = (self._value & (1 << shift)) >> shift if(self._sign): bitset = bitsetxor(zero, bit...
.. _getuvalue: Get the unsigned value of the Integer, truncate it and handle Overflows.
Below is the the instruction that describes the task: ### Input: .. _getuvalue: Get the unsigned value of the Integer, truncate it and handle Overflows. ### Response: def getuvalue(self): """ .. _getuvalue: Get the unsigned value of the Integer, truncate it and handle Overflows. """ bitset = [0] * se...
def foreign_field_func(field_name, short_description=None, admin_order_field=None): """ Allow to use ForeignKey field attributes at list_display in a simple way. Example: from misc.admin import foreign_field_func as ff class SongAdmin(admin.ModelAdmin): ...
Allow to use ForeignKey field attributes at list_display in a simple way. Example: from misc.admin import foreign_field_func as ff class SongAdmin(admin.ModelAdmin): ...
Below is the the instruction that describes the task: ### Input: Allow to use ForeignKey field attributes at list_display in a simple way. Example: from misc.admin import foreign_field_func as ff class SongAdmin(admin.ModelAdmin): ...
def best_model(self): """Rebuilds the top scoring model from an optimisation. Returns ------- model: AMPAL Returns an AMPAL model of the top scoring parameters. Raises ------ AttributeError Raises a name error if the optimiser has not bee...
Rebuilds the top scoring model from an optimisation. Returns ------- model: AMPAL Returns an AMPAL model of the top scoring parameters. Raises ------ AttributeError Raises a name error if the optimiser has not been run.
Below is the the instruction that describes the task: ### Input: Rebuilds the top scoring model from an optimisation. Returns ------- model: AMPAL Returns an AMPAL model of the top scoring parameters. Raises ------ AttributeError Raises a nam...
def poly_to_pwl(self, n_points=4): """ Sets the piece-wise linear cost attribute, converting the polynomial cost variable by evaluating at zero and then at n_points evenly spaced points between p_min and p_max. """ assert self.pcost_model == POLYNOMIAL p_min = self.p_min ...
Sets the piece-wise linear cost attribute, converting the polynomial cost variable by evaluating at zero and then at n_points evenly spaced points between p_min and p_max.
Below is the the instruction that describes the task: ### Input: Sets the piece-wise linear cost attribute, converting the polynomial cost variable by evaluating at zero and then at n_points evenly spaced points between p_min and p_max. ### Response: def poly_to_pwl(self, n_points=4): """ S...
def xpathNextPrecedingSibling(self, cur): """Traversal function for the "preceding-sibling" direction The preceding-sibling axis contains the preceding siblings of the context node in reverse document order; the first preceding sibling is first on the axis; the sibling p...
Traversal function for the "preceding-sibling" direction The preceding-sibling axis contains the preceding siblings of the context node in reverse document order; the first preceding sibling is first on the axis; the sibling preceding that node is the second on the axis and so o...
Below is the the instruction that describes the task: ### Input: Traversal function for the "preceding-sibling" direction The preceding-sibling axis contains the preceding siblings of the context node in reverse document order; the first preceding sibling is first on the axis; the sibl...
def detected_releasers(cls, config): """ Returns all of the releasers that are compatible with the project. """ def get_config(releaser): if config: return config.get(releaser.config_name(), {}) return {} releasers = [] for rele...
Returns all of the releasers that are compatible with the project.
Below is the the instruction that describes the task: ### Input: Returns all of the releasers that are compatible with the project. ### Response: def detected_releasers(cls, config): """ Returns all of the releasers that are compatible with the project. """ def get_config(releaser)...
def timestamp(self, name, value): """ Records the given timestamp. :param name: a counter name of Timestamp type. :param value: a timestamp to record. """ for counter in self._counters: counter.timestamp(name, value)
Records the given timestamp. :param name: a counter name of Timestamp type. :param value: a timestamp to record.
Below is the the instruction that describes the task: ### Input: Records the given timestamp. :param name: a counter name of Timestamp type. :param value: a timestamp to record. ### Response: def timestamp(self, name, value): """ Records the given timestamp. :param name: ...
def cmd_oreoled(self, args): '''send LED pattern as override, using OreoLED conventions''' if len(args) < 4: print("Usage: oreoled LEDNUM RED GREEN BLUE <RATE>") return lednum = int(args[0]) pattern = [0] * 24 pattern[0] = ord('R') pattern[1] = ord...
send LED pattern as override, using OreoLED conventions
Below is the the instruction that describes the task: ### Input: send LED pattern as override, using OreoLED conventions ### Response: def cmd_oreoled(self, args): '''send LED pattern as override, using OreoLED conventions''' if len(args) < 4: print("Usage: oreoled LEDNUM RED GREEN BLUE...
def check_github(self): """ If the requirement is frozen to a github url, check for new commits. API Tokens ---------- For more than 50 github api calls per hour, pipchecker requires authentication with the github api by settings the environemnt variable ``GITHUB...
If the requirement is frozen to a github url, check for new commits. API Tokens ---------- For more than 50 github api calls per hour, pipchecker requires authentication with the github api by settings the environemnt variable ``GITHUB_API_TOKEN`` or setting the command flag ...
Below is the the instruction that describes the task: ### Input: If the requirement is frozen to a github url, check for new commits. API Tokens ---------- For more than 50 github api calls per hour, pipchecker requires authentication with the github api by settings the environemnt ...
def handle_stream_features(self, stream, features): """Process incoming <stream:features/> element. [initiating entity only] """ element = features.find(MECHANISMS_TAG) self.peer_sasl_mechanisms = [] if element is None: return None for sub in element:...
Process incoming <stream:features/> element. [initiating entity only]
Below is the the instruction that describes the task: ### Input: Process incoming <stream:features/> element. [initiating entity only] ### Response: def handle_stream_features(self, stream, features): """Process incoming <stream:features/> element. [initiating entity only] """ ...
def _register_messages(self): """Register messages to listen for.""" template_on_group = StandardReceive.template( commandtuple=COMMAND_LIGHT_ON_0X11_NONE, address=self._address, target=bytearray([0x00, 0x00, self._group]), flags=MessageFlags.template(MESS...
Register messages to listen for.
Below is the the instruction that describes the task: ### Input: Register messages to listen for. ### Response: def _register_messages(self): """Register messages to listen for.""" template_on_group = StandardReceive.template( commandtuple=COMMAND_LIGHT_ON_0X11_NONE, address...
def command_line_config(self): """ settings.py is the basis if wants to change them by command line arguments, the existing option will be transformed to the value type in settings.py the unexisting option will be treated as string by default, and transform to certain ty...
settings.py is the basis if wants to change them by command line arguments, the existing option will be transformed to the value type in settings.py the unexisting option will be treated as string by default, and transform to certain type if `!<type>` was added after the value. ...
Below is the the instruction that describes the task: ### Input: settings.py is the basis if wants to change them by command line arguments, the existing option will be transformed to the value type in settings.py the unexisting option will be treated as string by default, and trans...
def Ntubes_Phadkeb(DBundle, Do, pitch, Ntp, angle=30): r'''Using tabulated values and correction factors for number of passes, the highly accurate method of [1]_ is used to obtain the tube count of a given tube bundle outer diameter for a given tube size and pitch. Parameters ---------- DBundle...
r'''Using tabulated values and correction factors for number of passes, the highly accurate method of [1]_ is used to obtain the tube count of a given tube bundle outer diameter for a given tube size and pitch. Parameters ---------- DBundle : float Outer diameter of tube bundle, [m] Do ...
Below is the the instruction that describes the task: ### Input: r'''Using tabulated values and correction factors for number of passes, the highly accurate method of [1]_ is used to obtain the tube count of a given tube bundle outer diameter for a given tube size and pitch. Parameters ---------- ...
def Dropout(x, params, rate=0.0, mode='train', rng=None, **kwargs): """Layer construction function for a dropout layer with given rate.""" del params, kwargs if rng is None: msg = ('Dropout layer requires apply_fun to be called with a rng keyword ' 'argument. That is, instead of `Dropout(params, in...
Layer construction function for a dropout layer with given rate.
Below is the the instruction that describes the task: ### Input: Layer construction function for a dropout layer with given rate. ### Response: def Dropout(x, params, rate=0.0, mode='train', rng=None, **kwargs): """Layer construction function for a dropout layer with given rate.""" del params, kwargs if rng ...
def intersect(self, other): """ Makes a striplog of all intersections. Args: Striplog. The striplog instance to intersect with. Returns: Striplog. The result of the intersection. """ if not isinstance(other, self.__class__): m = "You ...
Makes a striplog of all intersections. Args: Striplog. The striplog instance to intersect with. Returns: Striplog. The result of the intersection.
Below is the the instruction that describes the task: ### Input: Makes a striplog of all intersections. Args: Striplog. The striplog instance to intersect with. Returns: Striplog. The result of the intersection. ### Response: def intersect(self, other): """ ...
def rm_regions(a, b, a_start_ind, a_stop_ind): '''Remove contiguous regions in `a` before region `b` Boolean arrays `a` and `b` should have alternating occuances of regions of `True` values. This routine removes additional contiguous regions in `a` that occur before a complimentary region in `b` has oc...
Remove contiguous regions in `a` before region `b` Boolean arrays `a` and `b` should have alternating occuances of regions of `True` values. This routine removes additional contiguous regions in `a` that occur before a complimentary region in `b` has occured Args ---- a: ndarray Boolea...
Below is the the instruction that describes the task: ### Input: Remove contiguous regions in `a` before region `b` Boolean arrays `a` and `b` should have alternating occuances of regions of `True` values. This routine removes additional contiguous regions in `a` that occur before a complimentary regio...
def join(tokens, start, result): """Join tokens into a single string with spaces between.""" texts = [] if len(result) > 0: for e in result: for child in e.iter(): if child.text is not None: texts.append(child.text) return [E(result[0].tag, ' '...
Join tokens into a single string with spaces between.
Below is the the instruction that describes the task: ### Input: Join tokens into a single string with spaces between. ### Response: def join(tokens, start, result): """Join tokens into a single string with spaces between.""" texts = [] if len(result) > 0: for e in result: for child...
def get_electoral_votes(self): """ Get all electoral votes for all candidates in this election. """ candidate_elections = CandidateElection.objects.filter(election=self) electoral_votes = None for ce in candidate_elections: electoral_votes = electoral_votes |...
Get all electoral votes for all candidates in this election.
Below is the the instruction that describes the task: ### Input: Get all electoral votes for all candidates in this election. ### Response: def get_electoral_votes(self): """ Get all electoral votes for all candidates in this election. """ candidate_elections = CandidateElection.obj...
def _update_service_context(self, resp, **kwargs): """ Deal with Provider Config Response. Based on the provider info response a set of parameters in different places needs to be set. :param resp: The provider info response :param service_context: Information collected/used by s...
Deal with Provider Config Response. Based on the provider info response a set of parameters in different places needs to be set. :param resp: The provider info response :param service_context: Information collected/used by services
Below is the the instruction that describes the task: ### Input: Deal with Provider Config Response. Based on the provider info response a set of parameters in different places needs to be set. :param resp: The provider info response :param service_context: Information collected/used by ser...
def bitsCmp(self, other, op, evalFn=None): """ :attention: If other is Bool signal convert this to bool (not ideal, due VHDL event operator) """ other = toHVal(other) t = self._dtype ot = other._dtype iamVal = isinstance(self, Value) otherIsVal = isinstance(other, Value) if...
:attention: If other is Bool signal convert this to bool (not ideal, due VHDL event operator)
Below is the the instruction that describes the task: ### Input: :attention: If other is Bool signal convert this to bool (not ideal, due VHDL event operator) ### Response: def bitsCmp(self, other, op, evalFn=None): """ :attention: If other is Bool signal convert this to bool (not ideal, du...
def from_file(cls, filepath): """Alternative constructor to get Torrent object from file. :param str filepath: :rtype: Torrent """ torrent = cls(Bencode.read_file(filepath)) torrent._filepath = filepath return torrent
Alternative constructor to get Torrent object from file. :param str filepath: :rtype: Torrent
Below is the the instruction that describes the task: ### Input: Alternative constructor to get Torrent object from file. :param str filepath: :rtype: Torrent ### Response: def from_file(cls, filepath): """Alternative constructor to get Torrent object from file. :param str filepat...
async def _throttled_request(self, request): '''Process a single request, respecting the concurrency limit.''' disconnect = False try: timeout = self.processing_timeout async with timeout_after(timeout): async with self._incoming_concurrency: ...
Process a single request, respecting the concurrency limit.
Below is the the instruction that describes the task: ### Input: Process a single request, respecting the concurrency limit. ### Response: async def _throttled_request(self, request): '''Process a single request, respecting the concurrency limit.''' disconnect = False try: timeo...
def run_webhook(self, webhook_url, **options): """ Convenience method for running bots in webhook mode :Example: >>> if __name__ == '__main__': >>> bot.run_webhook(webhook_url="https://yourserver.com/webhooktoken") Additional documentation on https://core.telegram....
Convenience method for running bots in webhook mode :Example: >>> if __name__ == '__main__': >>> bot.run_webhook(webhook_url="https://yourserver.com/webhooktoken") Additional documentation on https://core.telegram.org/bots/api#setwebhook
Below is the the instruction that describes the task: ### Input: Convenience method for running bots in webhook mode :Example: >>> if __name__ == '__main__': >>> bot.run_webhook(webhook_url="https://yourserver.com/webhooktoken") Additional documentation on https://core.telegra...
def add_rrset(self, section, rrset, **kw): """Add the rrset to the specified section. Any keyword arguments are passed on to the rdataset's to_wire() routine. @param section: the section @type section: int @param rrset: the rrset @type rrset: dns.rrset.RRset obj...
Add the rrset to the specified section. Any keyword arguments are passed on to the rdataset's to_wire() routine. @param section: the section @type section: int @param rrset: the rrset @type rrset: dns.rrset.RRset object
Below is the the instruction that describes the task: ### Input: Add the rrset to the specified section. Any keyword arguments are passed on to the rdataset's to_wire() routine. @param section: the section @type section: int @param rrset: the rrset @type rrset: dns....
def EnumMissingModules(): """Enumerate all modules which match the patterns MODULE_PATTERNS. PyInstaller often fails to locate all dlls which are required at runtime. We import all the client modules here, we simply introspect all the modules we have loaded in our current running process, and all the ones ma...
Enumerate all modules which match the patterns MODULE_PATTERNS. PyInstaller often fails to locate all dlls which are required at runtime. We import all the client modules here, we simply introspect all the modules we have loaded in our current running process, and all the ones matching the patterns are copied ...
Below is the the instruction that describes the task: ### Input: Enumerate all modules which match the patterns MODULE_PATTERNS. PyInstaller often fails to locate all dlls which are required at runtime. We import all the client modules here, we simply introspect all the modules we have loaded in our current ...
def __is_block_data_move(self): """ Private method to tell if the instruction pointed to by the program counter is a block data move instruction. Currently only works for x86 and amd64 architectures. """ block_data_move_instructions = ('movs', 'stos', 'lods') isB...
Private method to tell if the instruction pointed to by the program counter is a block data move instruction. Currently only works for x86 and amd64 architectures.
Below is the the instruction that describes the task: ### Input: Private method to tell if the instruction pointed to by the program counter is a block data move instruction. Currently only works for x86 and amd64 architectures. ### Response: def __is_block_data_move(self): """ Pri...
def absent(name, acl_type, acl_name='', perms='', recurse=False): ''' Ensure a Linux ACL does not exist name The acl path acl_type The type of the acl is used for, it can be 'user' or 'group' acl_names The user or group perms Remove the permissions eg.: rwx ...
Ensure a Linux ACL does not exist name The acl path acl_type The type of the acl is used for, it can be 'user' or 'group' acl_names The user or group perms Remove the permissions eg.: rwx recurse Set the permissions recursive in the path
Below is the the instruction that describes the task: ### Input: Ensure a Linux ACL does not exist name The acl path acl_type The type of the acl is used for, it can be 'user' or 'group' acl_names The user or group perms Remove the permissions eg.: rwx recurs...
def get_cached_element_by_path(data_tree, path): # type: (ArTree, str) -> typing.Optional[_Element] """Get element from ArTree by path.""" if not isinstance(data_tree, ArTree): logger.warning("%s not called with ArTree, return None", get_cached_element_by_path.__name__) return None ptr =...
Get element from ArTree by path.
Below is the the instruction that describes the task: ### Input: Get element from ArTree by path. ### Response: def get_cached_element_by_path(data_tree, path): # type: (ArTree, str) -> typing.Optional[_Element] """Get element from ArTree by path.""" if not isinstance(data_tree, ArTree): logger...
def get_magnitude_time_distribution(self, magnitude_bins, time_bins, normalisation=False, bootstrap=None): ''' Returns a 2-D histogram indicating the number of earthquakes in a set of time-magnitude bins. Time is in decimal years! :param numpy.nda...
Returns a 2-D histogram indicating the number of earthquakes in a set of time-magnitude bins. Time is in decimal years! :param numpy.ndarray magnitude_bins: Bin edges for the magnitudes :param numpy.ndarray time_bins: Bin edges for the times :param bool normal...
Below is the the instruction that describes the task: ### Input: Returns a 2-D histogram indicating the number of earthquakes in a set of time-magnitude bins. Time is in decimal years! :param numpy.ndarray magnitude_bins: Bin edges for the magnitudes :param numpy.ndarray time_...
def parse( files, config=None, compilation_mode=COMPILATION_MODE.FILE_BY_FILE, cache=None): """ Parse header files. :param files: The header files that should be parsed :type files: list of str :param config: Configuration object or None :type config: :class:`par...
Parse header files. :param files: The header files that should be parsed :type files: list of str :param config: Configuration object or None :type config: :class:`parser.xml_generator_configuration_t` :param compilation_mode: Determines whether the files are parsed ind...
Below is the the instruction that describes the task: ### Input: Parse header files. :param files: The header files that should be parsed :type files: list of str :param config: Configuration object or None :type config: :class:`parser.xml_generator_configuration_t` :param compilation_mode: Det...
def charge_credit_card(credit_card_psp_object: Model, amount: Money, client_ref: str) -> Tuple[bool, Model]: """ :param credit_card_psp_object: an instance representing the credit card in the psp :param amount: the amount to charge :param client_ref: a reference that will appear on the customer's credit...
:param credit_card_psp_object: an instance representing the credit card in the psp :param amount: the amount to charge :param client_ref: a reference that will appear on the customer's credit card report :return: a tuple (success, payment_psp_object)
Below is the the instruction that describes the task: ### Input: :param credit_card_psp_object: an instance representing the credit card in the psp :param amount: the amount to charge :param client_ref: a reference that will appear on the customer's credit card report :return: a tuple (success, payment_...
def _get_context_key(self, **kwargs): """ Get value of `self._resource.parent.id_name` from :kwargs: """ return str(kwargs.get(self._resource.parent.id_name))
Get value of `self._resource.parent.id_name` from :kwargs:
Below is the the instruction that describes the task: ### Input: Get value of `self._resource.parent.id_name` from :kwargs: ### Response: def _get_context_key(self, **kwargs): """ Get value of `self._resource.parent.id_name` from :kwargs: """ return str(kwargs.get(self._resource.parent.id_name))
def phi5_plaintext_cleanup(text, rm_punctuation=False, rm_periods=False): """Remove and substitute post-processing for Greek PHI5 text. TODO: Surely more junk to pull out. Please submit bugs! TODO: This is a rather slow now, help in speeding up welcome. """ # This works OK, doesn't get some # No...
Remove and substitute post-processing for Greek PHI5 text. TODO: Surely more junk to pull out. Please submit bugs! TODO: This is a rather slow now, help in speeding up welcome.
Below is the the instruction that describes the task: ### Input: Remove and substitute post-processing for Greek PHI5 text. TODO: Surely more junk to pull out. Please submit bugs! TODO: This is a rather slow now, help in speeding up welcome. ### Response: def phi5_plaintext_cleanup(text, rm_punctuation=Fal...
def get_dip(self): """ Return the fault dip as the average dip over the mesh. The average dip is defined as the weighted mean inclination of all the mesh cells. See :meth:`openquake.hazardlib.geo.mesh.RectangularMesh.get_mean_inclination_and_azimuth` :returns: ...
Return the fault dip as the average dip over the mesh. The average dip is defined as the weighted mean inclination of all the mesh cells. See :meth:`openquake.hazardlib.geo.mesh.RectangularMesh.get_mean_inclination_and_azimuth` :returns: The average dip, in decimal degrees.
Below is the the instruction that describes the task: ### Input: Return the fault dip as the average dip over the mesh. The average dip is defined as the weighted mean inclination of all the mesh cells. See :meth:`openquake.hazardlib.geo.mesh.RectangularMesh.get_mean_inclination_and_azimuth...
def main(port=8888): """Run as sample test server.""" import tornado.ioloop routes = [] + TornadoProfiler().get_routes() app = tornado.web.Application(routes) app.listen(port) tornado.ioloop.IOLoop.current().start()
Run as sample test server.
Below is the the instruction that describes the task: ### Input: Run as sample test server. ### Response: def main(port=8888): """Run as sample test server.""" import tornado.ioloop routes = [] + TornadoProfiler().get_routes() app = tornado.web.Application(routes) app.listen(port) tornado....