code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def on_new_line(self): """On new input line""" self.set_cursor_position('eof') self.current_prompt_pos = self.get_position('cursor') self.new_input_line = False
On new input line
Below is the the instruction that describes the task: ### Input: On new input line ### Response: def on_new_line(self): """On new input line""" self.set_cursor_position('eof') self.current_prompt_pos = self.get_position('cursor') self.new_input_line = False
def compute_rewards(self, scores): """ Compute the "velocity" of (average distance between) the k+1 best scores. Return a list with those k velocities padded out with zeros so that the count remains the same. """ # get the k + 1 best scores in descending order bes...
Compute the "velocity" of (average distance between) the k+1 best scores. Return a list with those k velocities padded out with zeros so that the count remains the same.
Below is the the instruction that describes the task: ### Input: Compute the "velocity" of (average distance between) the k+1 best scores. Return a list with those k velocities padded out with zeros so that the count remains the same. ### Response: def compute_rewards(self, scores): """ ...
def return_hdr(self): """Return the header for further use. Returns ------- subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency chan_name : list of str ...
Return the header for further use. Returns ------- subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency chan_name : list of str list of all the channels...
Below is the the instruction that describes the task: ### Input: Return the header for further use. Returns ------- subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency...
def _getParameters(self): """Returns the result of this decorator.""" param = self.query._getParameters() index = self._getFilterIndex() param.update({ 'filter['+str(index)+'][columnAlias]' : self.__column, 'filter['+str(index)+'][data][type]' : self.__type, 'fil...
Returns the result of this decorator.
Below is the the instruction that describes the task: ### Input: Returns the result of this decorator. ### Response: def _getParameters(self): """Returns the result of this decorator.""" param = self.query._getParameters() index = self._getFilterIndex() param.update({ 'filt...
def _notify_receiver(self, receiver, params, doc): """Send notification to the receiver""" verb = VMAP[doc['op']] ns = doc['ns'] notification_id = Id(ns + 'Notification:' + str(ObjectId()) + '@' + params['authority']) object_id = Id(ns + ':' + str(doc['o']['_id']) + '@' + params[...
Send notification to the receiver
Below is the the instruction that describes the task: ### Input: Send notification to the receiver ### Response: def _notify_receiver(self, receiver, params, doc): """Send notification to the receiver""" verb = VMAP[doc['op']] ns = doc['ns'] notification_id = Id(ns + 'Notification:'...
def create_ticket_from_albaran(pk, list_lines): MODEL_SOURCE = SalesAlbaran MODEL_FINAL = SalesTicket url_reverse = 'CDNX_invoicing_ticketsaless_list' # type_doc msg_error_relation = _("Hay lineas asignadas a ticket") msg_error_not_found = _('Sales albaran not found') ...
context = {} if list_lines: new_list_lines = SalesLines.objects.filter( pk__in=[int(x) for x in list_lines] ).exclude( invoice__isnull=True ).values_list('pk') if new_list_lines: new_pk = SalesLines.objects.values_l...
Below is the the instruction that describes the task: ### Input: context = {} if list_lines: new_list_lines = SalesLines.objects.filter( pk__in=[int(x) for x in list_lines] ).exclude( invoice__isnull=True ).values_list('pk') if...
def freeze_bn(self): '''Freeze BatchNorm layers.''' for layer in self.modules(): if isinstance(layer, nn.BatchNorm2d): layer.eval()
Freeze BatchNorm layers.
Below is the the instruction that describes the task: ### Input: Freeze BatchNorm layers. ### Response: def freeze_bn(self): '''Freeze BatchNorm layers.''' for layer in self.modules(): if isinstance(layer, nn.BatchNorm2d): layer.eval()
def _batch_norm_op(self, input_batch, mean, variance, use_batch_stats, stat_dtype): """Creates a batch normalization op. It uses the tf.nn.batch_normalization op by default and the tf.nn.fused_batch_norm op to support fused batch normalization. Args: input_batch: A input Ten...
Creates a batch normalization op. It uses the tf.nn.batch_normalization op by default and the tf.nn.fused_batch_norm op to support fused batch normalization. Args: input_batch: A input Tensor of arbitrary dimension. mean: A mean tensor, of the same dtype as `input_batch`. variance: A var...
Below is the the instruction that describes the task: ### Input: Creates a batch normalization op. It uses the tf.nn.batch_normalization op by default and the tf.nn.fused_batch_norm op to support fused batch normalization. Args: input_batch: A input Tensor of arbitrary dimension. mean: A m...
def load_repo_addons(_globals): '''Load all fabsetup addons which are stored under ~/.fabsetup-addon-repos as git repositories. Args: _globals(dict): the globals() namespace of the fabric script. Return: None ''' repos_dir = os.path.expanduser('~/.fabsetup-addon-repos') if os.path....
Load all fabsetup addons which are stored under ~/.fabsetup-addon-repos as git repositories. Args: _globals(dict): the globals() namespace of the fabric script. Return: None
Below is the the instruction that describes the task: ### Input: Load all fabsetup addons which are stored under ~/.fabsetup-addon-repos as git repositories. Args: _globals(dict): the globals() namespace of the fabric script. Return: None ### Response: def load_repo_addons(_globals): '''L...
def f_cash(x, counts, bkg, model): """ Wrapper for cash statistics, that defines the model function. Parameters ---------- x : float Model amplitude. counts : `~numpy.ndarray` Count map slice, where model is defined. bkg : `~numpy.ndarray` Background map slice, where...
Wrapper for cash statistics, that defines the model function. Parameters ---------- x : float Model amplitude. counts : `~numpy.ndarray` Count map slice, where model is defined. bkg : `~numpy.ndarray` Background map slice, where model is defined. model : `~numpy.ndarray`...
Below is the the instruction that describes the task: ### Input: Wrapper for cash statistics, that defines the model function. Parameters ---------- x : float Model amplitude. counts : `~numpy.ndarray` Count map slice, where model is defined. bkg : `~numpy.ndarray` Backg...
def _from_dict(cls, _dict): """Initialize a TableReturn object from a json dictionary.""" args = {} if 'document' in _dict: args['document'] = DocInfo._from_dict(_dict.get('document')) if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') if 'mo...
Initialize a TableReturn object from a json dictionary.
Below is the the instruction that describes the task: ### Input: Initialize a TableReturn object from a json dictionary. ### Response: def _from_dict(cls, _dict): """Initialize a TableReturn object from a json dictionary.""" args = {} if 'document' in _dict: args['document'] = D...
def parse_feeds(self, message_channel=True): """ Iterates through each of the feed URLs, parses their items, and sends any items to the channel that have not been previously been parsed. """ if parse: for feed_url in self.feeds: feed = parse(fe...
Iterates through each of the feed URLs, parses their items, and sends any items to the channel that have not been previously been parsed.
Below is the the instruction that describes the task: ### Input: Iterates through each of the feed URLs, parses their items, and sends any items to the channel that have not been previously been parsed. ### Response: def parse_feeds(self, message_channel=True): """ Iterates through ...
def get_account_data(self, start=0, stop=None, inclusion_states=False, security_level=None): # type: (int, Optional[int], bool, Optional[int]) -> dict """ More comprehensive version of :py:meth:`get_transfers` that returns addresses and account balance in addition to bundles. Th...
More comprehensive version of :py:meth:`get_transfers` that returns addresses and account balance in addition to bundles. This function is useful in getting all the relevant information of your account. :param start: Starting key index. :param stop: Sto...
Below is the the instruction that describes the task: ### Input: More comprehensive version of :py:meth:`get_transfers` that returns addresses and account balance in addition to bundles. This function is useful in getting all the relevant information of your account. :param start: ...
def get(self, orig_key): """Get cache entry for key, or return None.""" resp = requests.Response() key = self._clean_key(orig_key) path = os.path.join(self.cache_dir, key) try: with open(path, 'rb') as f: # read lines one at a time wh...
Get cache entry for key, or return None.
Below is the the instruction that describes the task: ### Input: Get cache entry for key, or return None. ### Response: def get(self, orig_key): """Get cache entry for key, or return None.""" resp = requests.Response() key = self._clean_key(orig_key) path = os.path.join(self.cache_...
def p_req_section(self, p): '''req_section : REQUIREMENTS ASSIGN_EQUAL LCURLY string_list RCURLY SEMI | REQUIREMENTS LCURLY string_list RCURLY SEMI | empty''' if len(p) == 7: p[0] = p[4] elif len(p) == 6: p[0] = p[3] s...
req_section : REQUIREMENTS ASSIGN_EQUAL LCURLY string_list RCURLY SEMI | REQUIREMENTS LCURLY string_list RCURLY SEMI | empty
Below is the the instruction that describes the task: ### Input: req_section : REQUIREMENTS ASSIGN_EQUAL LCURLY string_list RCURLY SEMI | REQUIREMENTS LCURLY string_list RCURLY SEMI | empty ### Response: def p_req_section(self, p): '''req_section : REQUIREMENTS...
def bot_has_any_role(*items): """Similar to :func:`.has_any_role` except checks if the bot itself has any of the roles listed. This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. ...
Similar to :func:`.has_any_role` except checks if the bot itself has any of the roles listed. This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure...
Below is the the instruction that describes the task: ### Input: Similar to :func:`.has_any_role` except checks if the bot itself has any of the roles listed. This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot is missing all roles, or :exc:`.NoPrivateMessage` if it is...
def degrees_dir(CIJ): ''' Node degree is the number of links connected to the node. The indegree is the number of inward links and the outdegree is the number of outward links. Parameters ---------- CIJ : NxN np.ndarray directed binary/weighted connection matrix Returns ---...
Node degree is the number of links connected to the node. The indegree is the number of inward links and the outdegree is the number of outward links. Parameters ---------- CIJ : NxN np.ndarray directed binary/weighted connection matrix Returns ------- id : Nx1 np.ndarray ...
Below is the the instruction that describes the task: ### Input: Node degree is the number of links connected to the node. The indegree is the number of inward links and the outdegree is the number of outward links. Parameters ---------- CIJ : NxN np.ndarray directed binary/weighted con...
def getprefix(self, u): """ Get the prefix for the specified namespace (uri) @param u: A namespace uri. @type u: str @return: The namspace. @rtype: (prefix, uri). """ for ns in Namespace.all: if u == ns[1]: return ns[0] ...
Get the prefix for the specified namespace (uri) @param u: A namespace uri. @type u: str @return: The namspace. @rtype: (prefix, uri).
Below is the the instruction that describes the task: ### Input: Get the prefix for the specified namespace (uri) @param u: A namespace uri. @type u: str @return: The namspace. @rtype: (prefix, uri). ### Response: def getprefix(self, u): """ Get the prefix for the sp...
def stream(self, recurring=values.unset, trigger_by=values.unset, usage_category=values.unset, limit=None, page_size=None): """ Streams TriggerInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit ...
Streams TriggerInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. :param TriggerInstance.Recurring recurring: The ...
Below is the the instruction that describes the task: ### Input: Streams TriggerInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory...
def example_number_for_non_geo_entity(country_calling_code): """Gets a valid number for the specified country calling code for a non-geographical entity. Arguments: country_calling_code -- The country calling code for a non-geographical entity. Returns a valid number for the non-geographical entity. R...
Gets a valid number for the specified country calling code for a non-geographical entity. Arguments: country_calling_code -- The country calling code for a non-geographical entity. Returns a valid number for the non-geographical entity. Returns None when the metadata does not contain such information,...
Below is the the instruction that describes the task: ### Input: Gets a valid number for the specified country calling code for a non-geographical entity. Arguments: country_calling_code -- The country calling code for a non-geographical entity. Returns a valid number for the non-geographical entity. ...
def delete_role_perm(role_id, perm_id,**kwargs): """ Remove a permission from a role """ #check_perm(kwargs.get('user_id'), 'edit_perm') _get_perm(perm_id) _get_role(role_id) try: roleperm_i = db.DBSession.query(RolePerm).filter(RolePerm.role_id==role_id, RolePerm.perm_id==perm_...
Remove a permission from a role
Below is the the instruction that describes the task: ### Input: Remove a permission from a role ### Response: def delete_role_perm(role_id, perm_id,**kwargs): """ Remove a permission from a role """ #check_perm(kwargs.get('user_id'), 'edit_perm') _get_perm(perm_id) _get_role(role_id) ...
def return_letters_from_string(text): """Get letters from string only.""" out = "" for letter in text: if letter.isalpha(): out += letter return out
Get letters from string only.
Below is the the instruction that describes the task: ### Input: Get letters from string only. ### Response: def return_letters_from_string(text): """Get letters from string only.""" out = "" for letter in text: if letter.isalpha(): out += letter return out
def project(self, project_id): """Fetch project `project_id`.""" type_ = self.guid(project_id) url = self._build_url(type_, project_id) if type_ in Project._types: return Project(self._json(self._get(url), 200), self.session) raise OSFException('{} is unrecognized typ...
Fetch project `project_id`.
Below is the the instruction that describes the task: ### Input: Fetch project `project_id`. ### Response: def project(self, project_id): """Fetch project `project_id`.""" type_ = self.guid(project_id) url = self._build_url(type_, project_id) if type_ in Project._types: ...
def context_chain(self) -> List['Context']: """Return a list of contexts starting from this one, its parent and so on.""" contexts = [] ctx = self # type: Optional[Context] while ctx is not None: contexts.append(ctx) ctx = ctx.parent return contexts
Return a list of contexts starting from this one, its parent and so on.
Below is the the instruction that describes the task: ### Input: Return a list of contexts starting from this one, its parent and so on. ### Response: def context_chain(self) -> List['Context']: """Return a list of contexts starting from this one, its parent and so on.""" contexts = [] ctx ...
def append(x: T, xs: Iterable[T]) -> Iterator[T]: """ Append a value to an iterable. Parameters ---------- x An element of type T. xs An iterable of elements of type T. Returns ------- Iterator An iterator that yields elements of *xs*, then yields *x*. Exa...
Append a value to an iterable. Parameters ---------- x An element of type T. xs An iterable of elements of type T. Returns ------- Iterator An iterator that yields elements of *xs*, then yields *x*. Examples -------- >>> from delphi.utils.fp import app...
Below is the the instruction that describes the task: ### Input: Append a value to an iterable. Parameters ---------- x An element of type T. xs An iterable of elements of type T. Returns ------- Iterator An iterator that yields elements of *xs*, then yields *x*...
def _calc_position_for_pin(self, x, y, relative_position): """Determine position at fraction of x, y path. :param x,y: two equal length lists of values describing a path. :param relative_position: value between 0 and 1 :returns: the x, y position of the fraction (relative_position) ...
Determine position at fraction of x, y path. :param x,y: two equal length lists of values describing a path. :param relative_position: value between 0 and 1 :returns: the x, y position of the fraction (relative_position) of the path length.
Below is the the instruction that describes the task: ### Input: Determine position at fraction of x, y path. :param x,y: two equal length lists of values describing a path. :param relative_position: value between 0 and 1 :returns: the x, y position of the fraction (relative_position) ...
def compress_pdf(filepath, output_path, ghostscript_binary): """Compress a single PDF file. Args: filepath (str): Path to the PDF file. output_path (str): Output path. ghostscript_binary (str): Name/alias of the Ghostscript binary. Raises: ValueError FileNotFoundErr...
Compress a single PDF file. Args: filepath (str): Path to the PDF file. output_path (str): Output path. ghostscript_binary (str): Name/alias of the Ghostscript binary. Raises: ValueError FileNotFoundError
Below is the the instruction that describes the task: ### Input: Compress a single PDF file. Args: filepath (str): Path to the PDF file. output_path (str): Output path. ghostscript_binary (str): Name/alias of the Ghostscript binary. Raises: ValueError FileNotFoundEr...
def get_legal_params(self, method): '''Given a API name, list all legal parameters using boto3 service model.''' if method not in self.client.meta.method_to_api_mapping: # Injected methods. Ignore. return [] api = self.client.meta.method_to_api_mapping[method] shape = self.client.meta.servic...
Given a API name, list all legal parameters using boto3 service model.
Below is the the instruction that describes the task: ### Input: Given a API name, list all legal parameters using boto3 service model. ### Response: def get_legal_params(self, method): '''Given a API name, list all legal parameters using boto3 service model.''' if method not in self.client.meta.method_to_...
def get_all_items(self): """ Returns all items in the combobox dictionary. """ return [self._widget.itemText(k) for k in range(self._widget.count())]
Returns all items in the combobox dictionary.
Below is the the instruction that describes the task: ### Input: Returns all items in the combobox dictionary. ### Response: def get_all_items(self): """ Returns all items in the combobox dictionary. """ return [self._widget.itemText(k) for k in range(self._widget.count())]
def binary_operation_comparison(self, rule, left, right, **kwargs): """ Callback method for rule tree traversing. Will be called at proper time from :py:class:`pynspect.rules.ComparisonBinOpRule.traverse` method. :param pynspect.rules.Rule rule: Reference to rule. :param left: L...
Callback method for rule tree traversing. Will be called at proper time from :py:class:`pynspect.rules.ComparisonBinOpRule.traverse` method. :param pynspect.rules.Rule rule: Reference to rule. :param left: Left operand for operation. :param right: right operand for operation. :p...
Below is the the instruction that describes the task: ### Input: Callback method for rule tree traversing. Will be called at proper time from :py:class:`pynspect.rules.ComparisonBinOpRule.traverse` method. :param pynspect.rules.Rule rule: Reference to rule. :param left: Left operand for ope...
def iselect(self, tag, limit=0): """Iterate the specified tags.""" for el in CSSMatch(self.selectors, tag, self.namespaces, self.flags).select(limit): yield el
Iterate the specified tags.
Below is the the instruction that describes the task: ### Input: Iterate the specified tags. ### Response: def iselect(self, tag, limit=0): """Iterate the specified tags.""" for el in CSSMatch(self.selectors, tag, self.namespaces, self.flags).select(limit): yield el
def draw_rect(setter, x, y, w, h, color=None, aa=False): """Draw rectangle with top-left corner at x,y, width w and height h""" _draw_fast_hline(setter, x, y, w, color, aa) _draw_fast_hline(setter, x, y + h - 1, w, color, aa) _draw_fast_vline(setter, x, y, h, color, aa) _draw_fast_vline(setter, x + ...
Draw rectangle with top-left corner at x,y, width w and height h
Below is the the instruction that describes the task: ### Input: Draw rectangle with top-left corner at x,y, width w and height h ### Response: def draw_rect(setter, x, y, w, h, color=None, aa=False): """Draw rectangle with top-left corner at x,y, width w and height h""" _draw_fast_hline(setter, x, y, w, c...
def _load_scalar_fit(self, fit_key=None, h5file=None, fit_data=None): """ Loads a single fit """ if (fit_key is None) ^ (h5file is None): raise ValueError("Either specify both fit_key and h5file, or" " neither") if not ((fit_key is None) ^ (fit_data is None))...
Loads a single fit
Below is the the instruction that describes the task: ### Input: Loads a single fit ### Response: def _load_scalar_fit(self, fit_key=None, h5file=None, fit_data=None): """ Loads a single fit """ if (fit_key is None) ^ (h5file is None): raise ValueError("Either specify both fit_k...
def detail_view(self, request): """ Renders the message view to a response. """ context = { 'preview': self, } kwargs = {} if self.form_class: if request.GET: form = self.form_class(data=request.GET) else: ...
Renders the message view to a response.
Below is the the instruction that describes the task: ### Input: Renders the message view to a response. ### Response: def detail_view(self, request): """ Renders the message view to a response. """ context = { 'preview': self, } kwargs = {} if s...
def login(self, login, password, url=None): """login page """ auth = self._auth(login, password) cherrypy.session['isadmin'] = auth['isadmin'] cherrypy.session['connected'] = auth['connected'] if auth['connected']: if auth['isadmin']: message ...
login page
Below is the the instruction that describes the task: ### Input: login page ### Response: def login(self, login, password, url=None): """login page """ auth = self._auth(login, password) cherrypy.session['isadmin'] = auth['isadmin'] cherrypy.session['connected'] = auth['conn...
def train_on_batch(self, *args) -> None: """Trains the model on a single batch. Args: *args: the list of network inputs. Last element of `args` is the batch of targets, all previous elements are training data batches """ *data, labels = args s...
Trains the model on a single batch. Args: *args: the list of network inputs. Last element of `args` is the batch of targets, all previous elements are training data batches
Below is the the instruction that describes the task: ### Input: Trains the model on a single batch. Args: *args: the list of network inputs. Last element of `args` is the batch of targets, all previous elements are training data batches ### Response: def train_on_batch...
def reindex(args): """ %prog reindex gffile pep.fasta ref.pep.fasta Reindex the splice isoforms (mRNA) in input GFF file, preferably generated after PASA annotation update In the input GFF file, there can be several types of mRNA within a locus: * CDS matches reference, UTR extended, inherits ...
%prog reindex gffile pep.fasta ref.pep.fasta Reindex the splice isoforms (mRNA) in input GFF file, preferably generated after PASA annotation update In the input GFF file, there can be several types of mRNA within a locus: * CDS matches reference, UTR extended, inherits reference mRNA ID * CDS (sl...
Below is the the instruction that describes the task: ### Input: %prog reindex gffile pep.fasta ref.pep.fasta Reindex the splice isoforms (mRNA) in input GFF file, preferably generated after PASA annotation update In the input GFF file, there can be several types of mRNA within a locus: * CDS matc...
def connect_array(self, address, connection_key, connection_type, **kwargs): """Connect this array with another one. :param address: IP address or DNS name of other array. :type address: str :param connection_key: Connection key of other array. :type connection_key: str ...
Connect this array with another one. :param address: IP address or DNS name of other array. :type address: str :param connection_key: Connection key of other array. :type connection_key: str :param connection_type: Type(s) of connection desired. :type connection_type: li...
Below is the the instruction that describes the task: ### Input: Connect this array with another one. :param address: IP address or DNS name of other array. :type address: str :param connection_key: Connection key of other array. :type connection_key: str :param connection_t...
def on_message(self, _, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the m...
Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicPrope...
Below is the the instruction that describes the task: ### Input: Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the m...
def status(id): """ View status of all jobs in a project. The command also accepts a specific job name. """ if id: try: experiment = ExperimentClient().get(normalize_job_name(id)) except FloydException: experiment = ExperimentClient().get(id) print_e...
View status of all jobs in a project. The command also accepts a specific job name.
Below is the the instruction that describes the task: ### Input: View status of all jobs in a project. The command also accepts a specific job name. ### Response: def status(id): """ View status of all jobs in a project. The command also accepts a specific job name. """ if id: try...
def set_phy_mode(self, mode=IxePhyMode.ignore): """ Set phy mode to copper or fiber. :param mode: requested PHY mode. """ if isinstance(mode, IxePhyMode): if mode.value: self.api.call_rc('port setPhyMode {} {}'.format(mode.value, self.uri)) else: ...
Set phy mode to copper or fiber. :param mode: requested PHY mode.
Below is the the instruction that describes the task: ### Input: Set phy mode to copper or fiber. :param mode: requested PHY mode. ### Response: def set_phy_mode(self, mode=IxePhyMode.ignore): """ Set phy mode to copper or fiber. :param mode: requested PHY mode. """ if isins...
def sun_events(latitude, longitude, date, timezone=0, zenith=None): """Convenience function for calculating sunrise and sunset. Civil twilight starts/ends when the Sun's centre is 6 degrees below the horizon. Nautical twilight starts/ends when the Sun's centre is 12 degrees below the horizon. ...
Convenience function for calculating sunrise and sunset. Civil twilight starts/ends when the Sun's centre is 6 degrees below the horizon. Nautical twilight starts/ends when the Sun's centre is 12 degrees below the horizon. Astronomical twilight starts/ends when the Sun's centre is 18 degrees belo...
Below is the the instruction that describes the task: ### Input: Convenience function for calculating sunrise and sunset. Civil twilight starts/ends when the Sun's centre is 6 degrees below the horizon. Nautical twilight starts/ends when the Sun's centre is 12 degrees below the horizon. Astro...
def backdate(res, date=None, as_datetime=False, fmt='%Y-%m-%d'): """ get past date based on currect date """ if res is None: return None if date is None: date = datetime.datetime.now() else: try: date = parse_date(date) except Exception as e: pass...
get past date based on currect date
Below is the the instruction that describes the task: ### Input: get past date based on currect date ### Response: def backdate(res, date=None, as_datetime=False, fmt='%Y-%m-%d'): """ get past date based on currect date """ if res is None: return None if date is None: date = datetime.d...
def from_dict(cls, label=None, label2=None, icon=None, thumbnail=None, path=None, selected=None, info=None, properties=None, context_menu=None, replace_context_menu=False, is_playable=None, info_type='video', stream_info=None): '''A ListItem constructor for ...
A ListItem constructor for setting a lot of properties not available in the regular __init__ method. Useful to collect all the properties in a dict and then use the **dct to call this method.
Below is the the instruction that describes the task: ### Input: A ListItem constructor for setting a lot of properties not available in the regular __init__ method. Useful to collect all the properties in a dict and then use the **dct to call this method. ### Response: def from_dict(cls, l...
def node_status_changed_handler(**kwargs): """ send notification when the status of a node changes according to users's settings """ obj = kwargs['instance'] obj.old_status = kwargs['old_status'].name obj.new_status = kwargs['new_status'].name queryset = exclude_owner_of_node(obj) create_notific...
send notification when the status of a node changes according to users's settings
Below is the the instruction that describes the task: ### Input: send notification when the status of a node changes according to users's settings ### Response: def node_status_changed_handler(**kwargs): """ send notification when the status of a node changes according to users's settings """ obj = kwargs[...
def extract_code_from_function(function): """Return code handled by function.""" if not function.__name__.startswith('fix_'): return None code = re.sub('^fix_', '', function.__name__) if not code: return None try: int(code[1:]) except ValueError: return None ...
Return code handled by function.
Below is the the instruction that describes the task: ### Input: Return code handled by function. ### Response: def extract_code_from_function(function): """Return code handled by function.""" if not function.__name__.startswith('fix_'): return None code = re.sub('^fix_', '', function.__name__...
def genlet(generator_function=None, prime=True): """ Decorator to convert a generator function to a :py:class:`~chainlink.ChainLink` :param generator_function: the generator function to convert :type generator_function: generator :param prime: advance the generator to the next/first yield :type...
Decorator to convert a generator function to a :py:class:`~chainlink.ChainLink` :param generator_function: the generator function to convert :type generator_function: generator :param prime: advance the generator to the next/first yield :type prime: bool When used as a decorator, this function can...
Below is the the instruction that describes the task: ### Input: Decorator to convert a generator function to a :py:class:`~chainlink.ChainLink` :param generator_function: the generator function to convert :type generator_function: generator :param prime: advance the generator to the next/first yield ...
def parse_bucket_info(domain): """Parse a domain name to gather the bucket name and region for an S3 bucket. Returns a tuple (bucket_name, bucket_region) if a valid domain name, else `None` >>> parse_bucket_info('www.riotgames.com.br.s3-website-us-west-2.amazonaws.com') ('www.riotgames.com.br', 'us-w...
Parse a domain name to gather the bucket name and region for an S3 bucket. Returns a tuple (bucket_name, bucket_region) if a valid domain name, else `None` >>> parse_bucket_info('www.riotgames.com.br.s3-website-us-west-2.amazonaws.com') ('www.riotgames.com.br', 'us-west-2') Args: domain (`st...
Below is the the instruction that describes the task: ### Input: Parse a domain name to gather the bucket name and region for an S3 bucket. Returns a tuple (bucket_name, bucket_region) if a valid domain name, else `None` >>> parse_bucket_info('www.riotgames.com.br.s3-website-us-west-2.amazonaws.com') ...
def primary_mrna(entrystream, parenttype='gene'): """ Select a single mRNA as a representative for each protein-coding gene. The primary mRNA is the one with the longest translation product. In cases where multiple isoforms have the same translated length, the feature ID is used for sorting. T...
Select a single mRNA as a representative for each protein-coding gene. The primary mRNA is the one with the longest translation product. In cases where multiple isoforms have the same translated length, the feature ID is used for sorting. This function **does not** return only mRNA features, it return...
Below is the the instruction that describes the task: ### Input: Select a single mRNA as a representative for each protein-coding gene. The primary mRNA is the one with the longest translation product. In cases where multiple isoforms have the same translated length, the feature ID is used for sorting....
def get(*dataset, **kwargs): ''' Displays properties for the given datasets. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string comma-separated list of properties to list, defaults to all recursive : boolean recursively list children de...
Displays properties for the given datasets. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string comma-separated list of properties to list, defaults to all recursive : boolean recursively list children depth : int recursively list childr...
Below is the the instruction that describes the task: ### Input: Displays properties for the given datasets. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string comma-separated list of properties to list, defaults to all recursive : boolean recu...
def _input_templates(self): """Read the path template file. """ foo = self._config.read([self._pathfile]) if len(foo) == 1: for k, v in self._config.items('paths'): self.templates[k] = v else: raise ValueError("Could not read {0}!".format(s...
Read the path template file.
Below is the the instruction that describes the task: ### Input: Read the path template file. ### Response: def _input_templates(self): """Read the path template file. """ foo = self._config.read([self._pathfile]) if len(foo) == 1: for k, v in self._config.items('paths')...
def add_data(self, data, table, delimiter='|', bands='', clean_up=True, rename_columns={}, column_fill={}, verbose=False): """ Adds data to the specified database table. Column names must match table fields to insert, however order and completeness don't matter. Parameters ...
Adds data to the specified database table. Column names must match table fields to insert, however order and completeness don't matter. Parameters ---------- data: str, array-like, astropy.table.Table The path to an ascii file, array-like object, or table. The first ...
Below is the the instruction that describes the task: ### Input: Adds data to the specified database table. Column names must match table fields to insert, however order and completeness don't matter. Parameters ---------- data: str, array-like, astropy.table.Table ...
def cli(ctx): """ Run setup after a fresh Vagrant installation. """ log = logging.getLogger('ipsv.setup') assert isinstance(ctx, Context) lock_path = os.path.join(ctx.config.get('Paths', 'Data'), 'setup.lck') if os.path.exists(lock_path): raise Exception('Setup is locked, please rem...
Run setup after a fresh Vagrant installation.
Below is the the instruction that describes the task: ### Input: Run setup after a fresh Vagrant installation. ### Response: def cli(ctx): """ Run setup after a fresh Vagrant installation. """ log = logging.getLogger('ipsv.setup') assert isinstance(ctx, Context) lock_path = os.path.join(ct...
def find_steam_location(): """ Finds the location of the current Steam installation on Windows machines. Returns None for any non-Windows machines, or for Windows machines where Steam is not installed. """ if registry is None: return None key = registry.CreateKey(registry.HKEY_CURRENT_USER,"Software\...
Finds the location of the current Steam installation on Windows machines. Returns None for any non-Windows machines, or for Windows machines where Steam is not installed.
Below is the the instruction that describes the task: ### Input: Finds the location of the current Steam installation on Windows machines. Returns None for any non-Windows machines, or for Windows machines where Steam is not installed. ### Response: def find_steam_location(): """ Finds the location of the ...
def get_float_time(): '''returns time as double precision floats - Time64 in pytables - mapping to and from python datetime's ''' t1 = time.time() t2 = datetime.datetime.fromtimestamp(t1) return time.mktime(t2.timetuple()) + 1e-6 * t2.microsecond
returns time as double precision floats - Time64 in pytables - mapping to and from python datetime's
Below is the the instruction that describes the task: ### Input: returns time as double precision floats - Time64 in pytables - mapping to and from python datetime's ### Response: def get_float_time(): '''returns time as double precision floats - Time64 in pytables - mapping to and from python datetime's ...
def rerouteTraveltime(self, vehID, currentTravelTimes=True): """rerouteTraveltime(string, bool) -> None Reroutes a vehicle. If currentTravelTimes is True (default) then the current traveltime of the edges is loaded and used for rerouting. If currentTravelTimes is False custom travel time...
rerouteTraveltime(string, bool) -> None Reroutes a vehicle. If currentTravelTimes is True (default) then the current traveltime of the edges is loaded and used for rerouting. If currentTravelTimes is False custom travel times are used. The various functions and options for customizing tr...
Below is the the instruction that describes the task: ### Input: rerouteTraveltime(string, bool) -> None Reroutes a vehicle. If currentTravelTimes is True (default) then the current traveltime of the edges is loaded and used for rerouting. If currentTravelTimes is False custom travel times a...
def example_path(cls, project, dataset, annotated_dataset, example): """Return a fully-qualified example string.""" return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}/examples/{example}", project=project, ...
Return a fully-qualified example string.
Below is the the instruction that describes the task: ### Input: Return a fully-qualified example string. ### Response: def example_path(cls, project, dataset, annotated_dataset, example): """Return a fully-qualified example string.""" return google.api_core.path_template.expand( "proje...
def printRemoteDatawraps(location = conf.pyGeno_REMOTE_LOCATION) : """ print all available datawraps from a remote location the location must have a datawraps.json in the following format:: { "Ordered": { "Reference genomes": { "Human" : ["GRCh37.75", "GRCh38.78"], "Mouse" : ["GRCm38.78"], }...
print all available datawraps from a remote location the location must have a datawraps.json in the following format:: { "Ordered": { "Reference genomes": { "Human" : ["GRCh37.75", "GRCh38.78"], "Mouse" : ["GRCm38.78"], }, "SNPs":{ } }, "Flat":{ "Reference genomes": { "G...
Below is the the instruction that describes the task: ### Input: print all available datawraps from a remote location the location must have a datawraps.json in the following format:: { "Ordered": { "Reference genomes": { "Human" : ["GRCh37.75", "GRCh38.78"], "Mouse" : ["GRCm38.78"], }, ...
def update_scale(self, overflow): """dynamically update loss scale""" iter_since_rescale = self._num_steps - self._last_rescale_iter if overflow: self._last_overflow_iter = self._num_steps self._overflows_since_rescale += 1 percentage = self._overflows_since_r...
dynamically update loss scale
Below is the the instruction that describes the task: ### Input: dynamically update loss scale ### Response: def update_scale(self, overflow): """dynamically update loss scale""" iter_since_rescale = self._num_steps - self._last_rescale_iter if overflow: self._last_overflow_iter...
def deviance(self, endog, mu, freq_weights=1, scale=1., axis=None): r''' Deviance function for either Bernoulli or Binomial data. Parameters ---------- endog : array-like Endogenous response variable (already transformed to a probability if appropriate). ...
r''' Deviance function for either Bernoulli or Binomial data. Parameters ---------- endog : array-like Endogenous response variable (already transformed to a probability if appropriate). mu : array Fitted mean response variable freq_we...
Below is the the instruction that describes the task: ### Input: r''' Deviance function for either Bernoulli or Binomial data. Parameters ---------- endog : array-like Endogenous response variable (already transformed to a probability if appropriate). ...
def liquid_jet_pump_ancillary(rhop, rhos, Kp, Ks, d_nozzle=None, d_mixing=None, Qp=None, Qs=None, P1=None, P2=None): r'''Calculates the remaining variable in a liquid jet pump when solving for one if the inlet variables only and the rest of them are known. The equation comes f...
r'''Calculates the remaining variable in a liquid jet pump when solving for one if the inlet variables only and the rest of them are known. The equation comes from conservation of energy and momentum in the mixing chamber. The variable to be solved for must be one of `d_nozzle`, `d_mixing`, `Qp...
Below is the the instruction that describes the task: ### Input: r'''Calculates the remaining variable in a liquid jet pump when solving for one if the inlet variables only and the rest of them are known. The equation comes from conservation of energy and momentum in the mixing chamber. The var...
def from_json(cls, obj): """Construct a MarathonConstraint from a parsed response. :param dict attributes: object attributes from parsed response :rtype: :class:`MarathonConstraint` """ if len(obj) == 2: (field, operator) = obj return cls(field, operator...
Construct a MarathonConstraint from a parsed response. :param dict attributes: object attributes from parsed response :rtype: :class:`MarathonConstraint`
Below is the the instruction that describes the task: ### Input: Construct a MarathonConstraint from a parsed response. :param dict attributes: object attributes from parsed response :rtype: :class:`MarathonConstraint` ### Response: def from_json(cls, obj): """Construct a MarathonConstrai...
def scatter_table(self, x, y, c, s, mark='*'): """Add a data series to the plot. :param x: array containing x-values. :param y: array containing y-values. :param c: array containing values for the color of the mark. :param s: array containing values for the size of the mark. ...
Add a data series to the plot. :param x: array containing x-values. :param y: array containing y-values. :param c: array containing values for the color of the mark. :param s: array containing values for the size of the mark. :param mark: the symbol used to mark the data point. ...
Below is the the instruction that describes the task: ### Input: Add a data series to the plot. :param x: array containing x-values. :param y: array containing y-values. :param c: array containing values for the color of the mark. :param s: array containing values for the size of th...
def _import_module(module_path, classnames): """ Tries to import the given Python module path. """ try: imported_module = __import__(module_path, fromlist=classnames) return imported_module except ImportError: # In case of an ImportError, the module being loaded generally does not ex...
Tries to import the given Python module path.
Below is the the instruction that describes the task: ### Input: Tries to import the given Python module path. ### Response: def _import_module(module_path, classnames): """ Tries to import the given Python module path. """ try: imported_module = __import__(module_path, fromlist=classnames) ...
def sendDAT(self): """This method sends the next DAT packet based on the data in the context. It returns a boolean indicating whether the transfer is finished.""" finished = False blocknumber = self.context.next_block # Test hook if DELAY_BLOCK and DELAY_BLOCK == ...
This method sends the next DAT packet based on the data in the context. It returns a boolean indicating whether the transfer is finished.
Below is the the instruction that describes the task: ### Input: This method sends the next DAT packet based on the data in the context. It returns a boolean indicating whether the transfer is finished. ### Response: def sendDAT(self): """This method sends the next DAT packet based on the d...
def add_bpmn_files(self, filenames): """ Add all filenames in the given list to the parser's set. """ for filename in filenames: f = open(filename, 'r') try: self.add_bpmn_xml(ET.parse(f), filename=filename) finally: f.c...
Add all filenames in the given list to the parser's set.
Below is the the instruction that describes the task: ### Input: Add all filenames in the given list to the parser's set. ### Response: def add_bpmn_files(self, filenames): """ Add all filenames in the given list to the parser's set. """ for filename in filenames: f = op...
def get_system_uptime_output_cmd_error(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_system_uptime = ET.Element("get_system_uptime") config = get_system_uptime output = ET.SubElement(get_system_uptime, "output") cmd_error = ET.SubEl...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_system_uptime_output_cmd_error(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_system_uptime = ET.Element("get_system_uptime") config = ge...
def validate(cls, mapper_spec): """Validates mapper specification. Args: mapper_spec: an instance of model.MapperSpec to validate. Raises: BadWriterParamsError: when Output writer class mismatch. """ if mapper_spec.output_writer_class() != cls: raise errors.BadWriterParamsError("O...
Validates mapper specification. Args: mapper_spec: an instance of model.MapperSpec to validate. Raises: BadWriterParamsError: when Output writer class mismatch.
Below is the the instruction that describes the task: ### Input: Validates mapper specification. Args: mapper_spec: an instance of model.MapperSpec to validate. Raises: BadWriterParamsError: when Output writer class mismatch. ### Response: def validate(cls, mapper_spec): """Validates mappe...
def _relay_message(self, message): """ Relay messages from the forum on the server to the client represented by this actor. """ info("relaying message: {message}") if not message.was_sent_by(self._id_factory): self.pipe.send(message) self.pipe.de...
Relay messages from the forum on the server to the client represented by this actor.
Below is the the instruction that describes the task: ### Input: Relay messages from the forum on the server to the client represented by this actor. ### Response: def _relay_message(self, message): """ Relay messages from the forum on the server to the client represented by this ...
def get_ZPE(viblist): """Returns the zero point energy from a list of frequencies. Parameters ---------- viblist : List of numbers or string of list of numbers. Returns ------- ZPE : Zero point energy in eV. """ if type(viblist) is str: l = ast.literal_eval(viblist) els...
Returns the zero point energy from a list of frequencies. Parameters ---------- viblist : List of numbers or string of list of numbers. Returns ------- ZPE : Zero point energy in eV.
Below is the the instruction that describes the task: ### Input: Returns the zero point energy from a list of frequencies. Parameters ---------- viblist : List of numbers or string of list of numbers. Returns ------- ZPE : Zero point energy in eV. ### Response: def get_ZPE(viblist): "...
def get_task(self, name): """ Returns a TaskConfig """ config = getattr(self, "tasks__{}".format(name)) if not config: raise TaskNotFoundError("Task not found: {}".format(name)) return TaskConfig(config)
Returns a TaskConfig
Below is the the instruction that describes the task: ### Input: Returns a TaskConfig ### Response: def get_task(self, name): """ Returns a TaskConfig """ config = getattr(self, "tasks__{}".format(name)) if not config: raise TaskNotFoundError("Task not found: {}".format(name)) ...
def rotate(self): """Rotate the files to disk. This is done by calling `store.close()` on each store, bumping the batchno and reopening the stores using their factories. """ self._logger.info('Rotating data files. New batch number will be: %s', self.ba...
Rotate the files to disk. This is done by calling `store.close()` on each store, bumping the batchno and reopening the stores using their factories.
Below is the the instruction that describes the task: ### Input: Rotate the files to disk. This is done by calling `store.close()` on each store, bumping the batchno and reopening the stores using their factories. ### Response: def rotate(self): """Rotate the files to disk. This i...
def get_postcodedata(self, postcode, nr, addition="", **params): """get_postcodedata - fetch information for 'postcode'. Parameters ---------- postcode : string The full (dutch) postcode nr : int The housenumber addition : string (optional) ...
get_postcodedata - fetch information for 'postcode'. Parameters ---------- postcode : string The full (dutch) postcode nr : int The housenumber addition : string (optional) the extension to a housenumber params : dict (optional) ...
Below is the the instruction that describes the task: ### Input: get_postcodedata - fetch information for 'postcode'. Parameters ---------- postcode : string The full (dutch) postcode nr : int The housenumber addition : string (optional) ...
def _parse_requirements(self, input): """ Parse a list of requirements specifications. Lines that look like "foobar==1.0" are parsed; all other lines are silently ignored. Returns a tuple of tuples, where each inner tuple is: (package, version) """ r...
Parse a list of requirements specifications. Lines that look like "foobar==1.0" are parsed; all other lines are silently ignored. Returns a tuple of tuples, where each inner tuple is: (package, version)
Below is the the instruction that describes the task: ### Input: Parse a list of requirements specifications. Lines that look like "foobar==1.0" are parsed; all other lines are silently ignored. Returns a tuple of tuples, where each inner tuple is: (package, vers...
def keep_only_current_window(self): """ Close all other windows, except the current one. """ self.tab_pages = [TabPage(self.active_tab.active_window)] self.active_tab_index = 0
Close all other windows, except the current one.
Below is the the instruction that describes the task: ### Input: Close all other windows, except the current one. ### Response: def keep_only_current_window(self): """ Close all other windows, except the current one. """ self.tab_pages = [TabPage(self.active_tab.active_window)] ...
def aes_b64_encrypt(value, secret, block_size=AES.block_size): """ AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt ...
AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt("Hello, world", "aLWEFlwgwlreWELF...
Below is the the instruction that describes the task: ### Input: AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt ...
def check_web_config(config_fname): ''' Try to load the Django settings. If this does not work, than settings file does not exist. Returns: Loaded configuration, or None. ''' print("Looking for config file at {0} ...".format(config_fname)) config = RawConfigParser() ...
Try to load the Django settings. If this does not work, than settings file does not exist. Returns: Loaded configuration, or None.
Below is the the instruction that describes the task: ### Input: Try to load the Django settings. If this does not work, than settings file does not exist. Returns: Loaded configuration, or None. ### Response: def check_web_config(config_fname): ''' Try to load the Django s...
def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': se...
Enable beacons
Below is the the instruction that describes the task: ### Input: Enable beacons ### Response: def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.util...
def _diff_internal(d1,d2): ''' d1 = {'a':'x','b':'y','c':'z'} d2 = {'a':'x','b':'u','d':'v'} _diff_internal(d1,d2) _diff_internald2,d1) ''' same =[] kdiff =[] vdiff = [] for key in d1: value = d1[key] if(key in d2): if(value == d2[key])...
d1 = {'a':'x','b':'y','c':'z'} d2 = {'a':'x','b':'u','d':'v'} _diff_internal(d1,d2) _diff_internald2,d1)
Below is the the instruction that describes the task: ### Input: d1 = {'a':'x','b':'y','c':'z'} d2 = {'a':'x','b':'u','d':'v'} _diff_internal(d1,d2) _diff_internald2,d1) ### Response: def _diff_internal(d1,d2): ''' d1 = {'a':'x','b':'y','c':'z'} d2 = {'a':'x','b':'u','d'...
def neg_loglikelihood(y, mean, scale, shape, skewness): """ Negative loglikelihood function Parameters ---------- y : np.ndarray univariate time series mean : np.ndarray array of location parameters for the Exponential distribution scale : float...
Negative loglikelihood function Parameters ---------- y : np.ndarray univariate time series mean : np.ndarray array of location parameters for the Exponential distribution scale : float scale parameter for the Exponential distribution ...
Below is the the instruction that describes the task: ### Input: Negative loglikelihood function Parameters ---------- y : np.ndarray univariate time series mean : np.ndarray array of location parameters for the Exponential distribution scale : floa...
def sniff(self, sample, delimiters=None): """ Returns a dialect (or None) corresponding to the sample """ quotechar, doublequote, delimiter, skipinitialspace = \ self._guess_quote_and_delimiter(sample, delimiters) if not delimiter: delimiter, skipi...
Returns a dialect (or None) corresponding to the sample
Below is the the instruction that describes the task: ### Input: Returns a dialect (or None) corresponding to the sample ### Response: def sniff(self, sample, delimiters=None): """ Returns a dialect (or None) corresponding to the sample """ quotechar, doublequote, delimiter, skipin...
def author_names(self): """ Returns a dictionary like this: { "urn:cts:greekLit:tlg0012$$n1" : "Homer" , "urn:cts:greekLit:tlg0012$$n2" : "Omero" , ... } """ return {"%s$$n%i" % (author.get_urn(), i): name[1] for author...
Returns a dictionary like this: { "urn:cts:greekLit:tlg0012$$n1" : "Homer" , "urn:cts:greekLit:tlg0012$$n2" : "Omero" , ... }
Below is the the instruction that describes the task: ### Input: Returns a dictionary like this: { "urn:cts:greekLit:tlg0012$$n1" : "Homer" , "urn:cts:greekLit:tlg0012$$n2" : "Omero" , ... } ### Response: def author_names(self): """ Returns a dic...
def upload(target): # type: (str) -> None """ Upload the release to a pypi server. TODO: Make sure the git directory is clean before allowing a release. Args: target (str): pypi target as defined in ~/.pypirc """ log.info("Uploading to pypi server <33>{}".format(target)) ...
Upload the release to a pypi server. TODO: Make sure the git directory is clean before allowing a release. Args: target (str): pypi target as defined in ~/.pypirc
Below is the the instruction that describes the task: ### Input: Upload the release to a pypi server. TODO: Make sure the git directory is clean before allowing a release. Args: target (str): pypi target as defined in ~/.pypirc ### Response: def upload(target): # type: (str) -> No...
def parse(response): """Parse a postdata-style response format from the API into usable data""" """Split a a=1b=2c=3 string into a dictionary of pairs""" tokens = {r[0]: r[1] for r in [r.split('=') for r in response.split("&")]} # The odd dummy parameter is of no use to us if '...
Parse a postdata-style response format from the API into usable data
Below is the the instruction that describes the task: ### Input: Parse a postdata-style response format from the API into usable data ### Response: def parse(response): """Parse a postdata-style response format from the API into usable data""" """Split a a=1b=2c=3 string into a dictionary of pairs...
def LAST(COND, N1, N2): """表达持续性 从前N1日到前N2日一直满足COND条件 Arguments: COND {[type]} -- [description] N1 {[type]} -- [description] N2 {[type]} -- [description] """ N2 = 1 if N2 == 0 else N2 assert N2 > 0 assert N1 > N2 return COND.iloc[-N1:-N2].all()
表达持续性 从前N1日到前N2日一直满足COND条件 Arguments: COND {[type]} -- [description] N1 {[type]} -- [description] N2 {[type]} -- [description]
Below is the the instruction that describes the task: ### Input: 表达持续性 从前N1日到前N2日一直满足COND条件 Arguments: COND {[type]} -- [description] N1 {[type]} -- [description] N2 {[type]} -- [description] ### Response: def LAST(COND, N1, N2): """表达持续性 从前N1日到前N2日一直满足COND条件 Arguments...
def as_freq(data_series, freq, atomic_freq="1 Min", series_type="cumulative"): """Resample data to a different frequency. This method can be used to upsample or downsample meter data. The assumption it makes to do so is that meter data is constant and averaged over the given periods. For instance, to c...
Resample data to a different frequency. This method can be used to upsample or downsample meter data. The assumption it makes to do so is that meter data is constant and averaged over the given periods. For instance, to convert billing-period data to daily data, this method first upsamples to the atomi...
Below is the the instruction that describes the task: ### Input: Resample data to a different frequency. This method can be used to upsample or downsample meter data. The assumption it makes to do so is that meter data is constant and averaged over the given periods. For instance, to convert billing-pe...
def BackAssign(cls, other_entity_klass, this_entity_backpopulate_field, other_entity_backpopulate_field, is_many_to_one=False): """ Assign defined one side mapping relationship to other side. For example, each employee ...
Assign defined one side mapping relationship to other side. For example, each employee belongs to one department, then one department includes many employees. If you defined each employee's department, this method will assign employees to ``Department.employees`` field. This is an one t...
Below is the the instruction that describes the task: ### Input: Assign defined one side mapping relationship to other side. For example, each employee belongs to one department, then one department includes many employees. If you defined each employee's department, this method will assign ...
def get_operations(self, indices: Sequence[LogicalIndex], qubits: Sequence[ops.Qid] ) -> ops.OP_TREE: """Gets the logical operations to apply to qubits."""
Gets the logical operations to apply to qubits.
Below is the the instruction that describes the task: ### Input: Gets the logical operations to apply to qubits. ### Response: def get_operations(self, indices: Sequence[LogicalIndex], qubits: Sequence[ops.Qid] ) -> ops.OP_TREE: """Gets t...
def execstr_dict(dict_, local_name=None, exclude_list=None, explicit=False): """ returns execable python code that declares variables using keys and values execstr_dict Args: dict_ (dict): local_name (str): optional: local name of dictionary. Specifying this is much safer ...
returns execable python code that declares variables using keys and values execstr_dict Args: dict_ (dict): local_name (str): optional: local name of dictionary. Specifying this is much safer exclude_list (list): Returns: str: execstr --- the executable string ...
Below is the the instruction that describes the task: ### Input: returns execable python code that declares variables using keys and values execstr_dict Args: dict_ (dict): local_name (str): optional: local name of dictionary. Specifying this is much safer exclude_list ...
def _ratelimited_get(self, *args, **kwargs): """Perform get request, handling rate limiting.""" with self._ratelimiter: resp = self.session.get(*args, **kwargs) # It's possible that Space-Track will return HTTP status 500 with a # query rate limit violation. This can happen ...
Perform get request, handling rate limiting.
Below is the the instruction that describes the task: ### Input: Perform get request, handling rate limiting. ### Response: def _ratelimited_get(self, *args, **kwargs): """Perform get request, handling rate limiting.""" with self._ratelimiter: resp = self.session.get(*args, **kwargs) ...
def _AbandonQueuedTasks(self): """Marks queued tasks abandoned. This method does not lock the manager and should be called by a method holding the manager lock. """ # Abandon all tasks after they're identified so as not to modify the # dict while iterating over it. tasks_to_abandon = [] ...
Marks queued tasks abandoned. This method does not lock the manager and should be called by a method holding the manager lock.
Below is the the instruction that describes the task: ### Input: Marks queued tasks abandoned. This method does not lock the manager and should be called by a method holding the manager lock. ### Response: def _AbandonQueuedTasks(self): """Marks queued tasks abandoned. This method does not lock t...
def stop(label, at=None, remove_from_labels=False, stop_once=True): """Stops the countdown""" t = at if at is not None else time.time() if label not in labels: return None timer = Marker().loads(labels[label]) if timer.is_running() or (timer.is_stopped() and not stop_once): timer....
Stops the countdown
Below is the the instruction that describes the task: ### Input: Stops the countdown ### Response: def stop(label, at=None, remove_from_labels=False, stop_once=True): """Stops the countdown""" t = at if at is not None else time.time() if label not in labels: return None timer = Marker().l...
def download_collection_configs(self, collection, fs_path): ''' Downloads ZK Directory to the FileSystem. :param collection str: Name of the collection (zk config name) :param fs_path str: Destination filesystem path. ''' if not self.kz.exists('/configs/{}'.for...
Downloads ZK Directory to the FileSystem. :param collection str: Name of the collection (zk config name) :param fs_path str: Destination filesystem path.
Below is the the instruction that describes the task: ### Input: Downloads ZK Directory to the FileSystem. :param collection str: Name of the collection (zk config name) :param fs_path str: Destination filesystem path. ### Response: def download_collection_configs(self, collection, fs_path): ...
def lex(self, text, start=0): """Lexically analyze `text`. Yields pairs (`name`, `tokentext`). """ max = len(text) eaten = start s = self.state r = self.regexes toks = self.toks while eaten < max: for match in r[s].finditer(text, eate...
Lexically analyze `text`. Yields pairs (`name`, `tokentext`).
Below is the the instruction that describes the task: ### Input: Lexically analyze `text`. Yields pairs (`name`, `tokentext`). ### Response: def lex(self, text, start=0): """Lexically analyze `text`. Yields pairs (`name`, `tokentext`). """ max = len(text) eaten = ...
def tangent_bbox_intersection(first, second, intersections): r"""Check if two curves with tangent bounding boxes intersect. .. note:: This is a helper for :func:`intersect_one_round`. These functions are used (directly or indirectly) by :func:`_all_intersections` exclusively, and that fun...
r"""Check if two curves with tangent bounding boxes intersect. .. note:: This is a helper for :func:`intersect_one_round`. These functions are used (directly or indirectly) by :func:`_all_intersections` exclusively, and that function has a Fortran equivalent. If the bounding boxes...
Below is the the instruction that describes the task: ### Input: r"""Check if two curves with tangent bounding boxes intersect. .. note:: This is a helper for :func:`intersect_one_round`. These functions are used (directly or indirectly) by :func:`_all_intersections` exclusively, and that...
def date(self, *args, **kwargs): """Compare attributes of pairs with date algorithm. Shortcut of :class:`recordlinkage.compare.Date`:: from recordlinkage.compare import Date indexer = recordlinkage.Compare() indexer.add(Date()) """ compare = Date(*...
Compare attributes of pairs with date algorithm. Shortcut of :class:`recordlinkage.compare.Date`:: from recordlinkage.compare import Date indexer = recordlinkage.Compare() indexer.add(Date())
Below is the the instruction that describes the task: ### Input: Compare attributes of pairs with date algorithm. Shortcut of :class:`recordlinkage.compare.Date`:: from recordlinkage.compare import Date indexer = recordlinkage.Compare() indexer.add(Date()) ### Response...
def attr(**context): """ Decorator that add attributes into func. Added attributes can be access outside via function's `func_dict` property. """ #TODO(Jim Zhan) FIXME def decorator(func): def wrapped_func(*args, **kwargs): for key, value in context.items(): ...
Decorator that add attributes into func. Added attributes can be access outside via function's `func_dict` property.
Below is the the instruction that describes the task: ### Input: Decorator that add attributes into func. Added attributes can be access outside via function's `func_dict` property. ### Response: def attr(**context): """ Decorator that add attributes into func. Added attributes can be access outs...
def Wow64EnableWow64FsRedirection(Wow64FsEnableRedirection): """ This function may not work reliably when there are nested calls. Therefore, this function has been replaced by the L{Wow64DisableWow64FsRedirection} and L{Wow64RevertWow64FsRedirection} functions. @see: U{http://msdn.microsoft.com/en-...
This function may not work reliably when there are nested calls. Therefore, this function has been replaced by the L{Wow64DisableWow64FsRedirection} and L{Wow64RevertWow64FsRedirection} functions. @see: U{http://msdn.microsoft.com/en-us/library/windows/desktop/aa365744(v=vs.85).aspx}
Below is the the instruction that describes the task: ### Input: This function may not work reliably when there are nested calls. Therefore, this function has been replaced by the L{Wow64DisableWow64FsRedirection} and L{Wow64RevertWow64FsRedirection} functions. @see: U{http://msdn.microsoft.com/en-us/l...
def task_transaction(channel): """Ensures a task is fetched and acknowledged atomically.""" with channel.lock: if channel.poll(0): task = channel.recv() channel.send(Acknowledgement(os.getpid(), task.id)) else: raise RuntimeError("Race condition between worker...
Ensures a task is fetched and acknowledged atomically.
Below is the the instruction that describes the task: ### Input: Ensures a task is fetched and acknowledged atomically. ### Response: def task_transaction(channel): """Ensures a task is fetched and acknowledged atomically.""" with channel.lock: if channel.poll(0): task = channel.recv() ...
def remove_environment(self, name=None, path=None, **kwargs): """ Remove an environment entirely. See ``remove``. """ return self.remove(name=name, path=path, all=True, **kwargs)
Remove an environment entirely. See ``remove``.
Below is the the instruction that describes the task: ### Input: Remove an environment entirely. See ``remove``. ### Response: def remove_environment(self, name=None, path=None, **kwargs): """ Remove an environment entirely. See ``remove``. """ return self.remove(n...