code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def parse_formula(fml_file): """ Parse and return MaxSAT formula. """ if re.search('\.wcnf(\.(gz|bz2|lzma|xz))?$', fml_file): fml = WCNF(from_file=fml_file) else: # expecting '*.cnf' fml = CNF(from_file=fml_file).weighted() return fml
Parse and return MaxSAT formula.
Below is the the instruction that describes the task: ### Input: Parse and return MaxSAT formula. ### Response: def parse_formula(fml_file): """ Parse and return MaxSAT formula. """ if re.search('\.wcnf(\.(gz|bz2|lzma|xz))?$', fml_file): fml = WCNF(from_file=fml_file) else: # expe...
def get_default_value_by_type(type_, state=None): """ Java specify defaults values for primitive and reference types. This method returns the default value for a given type. :param str type_: Name of type. :return: Default value for this type. """ if...
Java specify defaults values for primitive and reference types. This method returns the default value for a given type. :param str type_: Name of type. :return: Default value for this type.
Below is the the instruction that describes the task: ### Input: Java specify defaults values for primitive and reference types. This method returns the default value for a given type. :param str type_: Name of type. :return: Default value for this type. ### Response: def get_...
def get_hacr_channels(db=None, gps=None, connection=None, **conectkwargs): """Return the names of all channels present in the given HACR database """ # connect if needed if connection is None: if gps is None: gps = from_gps('now') if db is None: ...
Return the names of all channels present in the given HACR database
Below is the the instruction that describes the task: ### Input: Return the names of all channels present in the given HACR database ### Response: def get_hacr_channels(db=None, gps=None, connection=None, **conectkwargs): """Return the names of all channels present in the given HACR datab...
def human(self): """Emit the address in human-readible format (AA.BB.CC).""" strout = '' first = True for i in range(0, 28, 2): if first: first = False else: strout = strout + '.' strout = strout + self.hex[i:i + 2] ...
Emit the address in human-readible format (AA.BB.CC).
Below is the the instruction that describes the task: ### Input: Emit the address in human-readible format (AA.BB.CC). ### Response: def human(self): """Emit the address in human-readible format (AA.BB.CC).""" strout = '' first = True for i in range(0, 28, 2): if first: ...
def set_temperature(self, zone, temperature, until=None): """Sets the temperature of the given zone.""" if until is None: data = {"Value": temperature, "Status": "Hold", "NextTime": None} else: data = {"Value": temperature, "Status": "Temporary", ...
Sets the temperature of the given zone.
Below is the the instruction that describes the task: ### Input: Sets the temperature of the given zone. ### Response: def set_temperature(self, zone, temperature, until=None): """Sets the temperature of the given zone.""" if until is None: data = {"Value": temperature, "Status": "Hold"...
def pop(self): """ Remove and return the last element from the set. Raises KeyError if the set is empty. Example: >>> oset = OrderedSet([1, 2, 3]) >>> oset.pop() 3 """ if not self.items: raise KeyError("Set is empty") ...
Remove and return the last element from the set. Raises KeyError if the set is empty. Example: >>> oset = OrderedSet([1, 2, 3]) >>> oset.pop() 3
Below is the the instruction that describes the task: ### Input: Remove and return the last element from the set. Raises KeyError if the set is empty. Example: >>> oset = OrderedSet([1, 2, 3]) >>> oset.pop() 3 ### Response: def pop(self): """ Re...
def get_logger(name): """Return a logger with a file handler.""" logger = logging.getLogger(name) logger.setLevel(logging.INFO) # File output handler file_handler = logging.FileHandler(log_path) file_handler.setLevel(logging.INFO) formatter = logging.Formatter( '%(asctime)s %(name)1...
Return a logger with a file handler.
Below is the the instruction that describes the task: ### Input: Return a logger with a file handler. ### Response: def get_logger(name): """Return a logger with a file handler.""" logger = logging.getLogger(name) logger.setLevel(logging.INFO) # File output handler file_handler = logging.FileH...
def fitlin(imgarr,refarr): """ Compute the least-squares fit between two arrays. A Python translation of 'FITLIN' from 'drutil.f' (Drizzle V2.9). """ # Initialize variables _mat = np.zeros((3,3),dtype=np.float64) _xorg = imgarr[0][0] _yorg = imgarr[0][1] _xoorg = refarr[0][0] _yo...
Compute the least-squares fit between two arrays. A Python translation of 'FITLIN' from 'drutil.f' (Drizzle V2.9).
Below is the the instruction that describes the task: ### Input: Compute the least-squares fit between two arrays. A Python translation of 'FITLIN' from 'drutil.f' (Drizzle V2.9). ### Response: def fitlin(imgarr,refarr): """ Compute the least-squares fit between two arrays. A Python translation...
def ref_info(self): """Gets a dictionary of ref positions and the ref IDs of the refs for that game. :returns: A dictionary of ref positions and IDs. """ doc = self.get_doc() table = doc('table#officials') return sportsref.utils.parse_info_table(table)
Gets a dictionary of ref positions and the ref IDs of the refs for that game. :returns: A dictionary of ref positions and IDs.
Below is the the instruction that describes the task: ### Input: Gets a dictionary of ref positions and the ref IDs of the refs for that game. :returns: A dictionary of ref positions and IDs. ### Response: def ref_info(self): """Gets a dictionary of ref positions and the ref IDs of the ref...
def taint(taintedSet, taintedAttribute): u"""Adds an attribute to a set of attributes. Related attributes are also included.""" taintedSet.add(taintedAttribute) if taintedAttribute == 'marker': taintedSet |= set(['marker-start', 'marker-mid', 'marker-end']) if taintedAttribute in ['marker-s...
u"""Adds an attribute to a set of attributes. Related attributes are also included.
Below is the the instruction that describes the task: ### Input: u"""Adds an attribute to a set of attributes. Related attributes are also included. ### Response: def taint(taintedSet, taintedAttribute): u"""Adds an attribute to a set of attributes. Related attributes are also included.""" tainte...
def del_export(exports='/etc/exports', path=None): ''' Remove an export CLI Example: .. code-block:: bash salt '*' nfs.del_export /media/storage ''' edict = list_exports(exports) del edict[path] _write_exports(exports, edict) return edict
Remove an export CLI Example: .. code-block:: bash salt '*' nfs.del_export /media/storage
Below is the the instruction that describes the task: ### Input: Remove an export CLI Example: .. code-block:: bash salt '*' nfs.del_export /media/storage ### Response: def del_export(exports='/etc/exports', path=None): ''' Remove an export CLI Example: .. code-block:: bash ...
def _log(code, message, level, domain): """Call this to add an entry in the journal""" entry = LogEntry(level, domain, code, message) Logger.journal.append(entry) if Logger.silent: return if level >= Logger._verbosity: _print_entry(entry)
Call this to add an entry in the journal
Below is the the instruction that describes the task: ### Input: Call this to add an entry in the journal ### Response: def _log(code, message, level, domain): """Call this to add an entry in the journal""" entry = LogEntry(level, domain, code, message) Logger.journal.append(entry) ...
def process_inline_members_definition(members): """ :param members: this can be any of the following: - a string containing a space and/or comma separated list of names: e.g.: "item1 item2 item3" OR "item1,item2,item3" OR "item1, item2, item3" - tuple/list/Set of strings (names) - Mapping of (...
:param members: this can be any of the following: - a string containing a space and/or comma separated list of names: e.g.: "item1 item2 item3" OR "item1,item2,item3" OR "item1, item2, item3" - tuple/list/Set of strings (names) - Mapping of (name, data) pairs - any kind of iterable that yields (na...
Below is the the instruction that describes the task: ### Input: :param members: this can be any of the following: - a string containing a space and/or comma separated list of names: e.g.: "item1 item2 item3" OR "item1,item2,item3" OR "item1, item2, item3" - tuple/list/Set of strings (names) - Map...
def create(self, status_callback=values.unset, unique_name=values.unset): """ Create a new ModelBuildInstance :param unicode status_callback: The URL we should call using a POST method to send status information to your application :param unicode unique_name: An application-defined stri...
Create a new ModelBuildInstance :param unicode status_callback: The URL we should call using a POST method to send status information to your application :param unicode unique_name: An application-defined string that uniquely identifies the new resource :returns: Newly created ModelBuildInstan...
Below is the the instruction that describes the task: ### Input: Create a new ModelBuildInstance :param unicode status_callback: The URL we should call using a POST method to send status information to your application :param unicode unique_name: An application-defined string that uniquely identifi...
def aggregateLine(requestContext, seriesList, func='avg'): """ Takes a metric or wildcard seriesList and draws a horizontal line based on the function applied to each series. Note: By default, the graphite renderer consolidates data points by averaging data points over time. If you are using the 'm...
Takes a metric or wildcard seriesList and draws a horizontal line based on the function applied to each series. Note: By default, the graphite renderer consolidates data points by averaging data points over time. If you are using the 'min' or 'max' function for aggregateLine, this can cause an unusual ...
Below is the the instruction that describes the task: ### Input: Takes a metric or wildcard seriesList and draws a horizontal line based on the function applied to each series. Note: By default, the graphite renderer consolidates data points by averaging data points over time. If you are using the 'min...
def count_tags(self): '''Count tag occurences by type and update the tag collection''' for key, model in TAGGED.items(): collection = '{0}_tags'.format(key) results = (model.objects(tags__exists=True) .map_reduce(map_tags, reduce_tags, collection)) for result in r...
Count tag occurences by type and update the tag collection
Below is the the instruction that describes the task: ### Input: Count tag occurences by type and update the tag collection ### Response: def count_tags(self): '''Count tag occurences by type and update the tag collection''' for key, model in TAGGED.items(): collection = '{0}_tags'.format(key) ...
def download_as_json(name): """ Download IPList as json. This would allow for easily manipulation of the IPList, but generally recommended only for smaller lists :param str name: name of IPList :return: None """ location = list(IPList.objects.filter(name)) if location: ipli...
Download IPList as json. This would allow for easily manipulation of the IPList, but generally recommended only for smaller lists :param str name: name of IPList :return: None
Below is the the instruction that describes the task: ### Input: Download IPList as json. This would allow for easily manipulation of the IPList, but generally recommended only for smaller lists :param str name: name of IPList :return: None ### Response: def download_as_json(name): """ Do...
def _convert_to_color(cls, color_spec): """ Convert ``color_spec`` to an openpyxl v2 Color object Parameters ---------- color_spec : str, dict A 32-bit ARGB hex string, or a dict with zero or more of the following keys. 'rgb' ...
Convert ``color_spec`` to an openpyxl v2 Color object Parameters ---------- color_spec : str, dict A 32-bit ARGB hex string, or a dict with zero or more of the following keys. 'rgb' 'indexed' 'auto' 'theme' ...
Below is the the instruction that describes the task: ### Input: Convert ``color_spec`` to an openpyxl v2 Color object Parameters ---------- color_spec : str, dict A 32-bit ARGB hex string, or a dict with zero or more of the following keys. 'rgb' ...
def subtract(self, es): """ Subtract the BED elements in es from self. :param es: a list of BED elements (or anything with chrom, start, end) :return: a list of BED elements which represent what is left of self after the subtraction. This might be an empty list. """ workingSet = [s...
Subtract the BED elements in es from self. :param es: a list of BED elements (or anything with chrom, start, end) :return: a list of BED elements which represent what is left of self after the subtraction. This might be an empty list.
Below is the the instruction that describes the task: ### Input: Subtract the BED elements in es from self. :param es: a list of BED elements (or anything with chrom, start, end) :return: a list of BED elements which represent what is left of self after the subtraction. This might be an empty ...
def get_project(url=None, username=None, password=None, token=None, scope=None, scope_id=None, env_filename=None, status=ScopeStatus.ACTIVE): """ Retrieve and return the KE-chain project to be used throughout an app. This helper is made to bootstrap a pykechain enabled python script or an j...
Retrieve and return the KE-chain project to be used throughout an app. This helper is made to bootstrap a pykechain enabled python script or an jupyter notebook with the correct project (technically this is a `pykechain.models.Scope` model). When no parameters are passed in this function, it will try to r...
Below is the the instruction that describes the task: ### Input: Retrieve and return the KE-chain project to be used throughout an app. This helper is made to bootstrap a pykechain enabled python script or an jupyter notebook with the correct project (technically this is a `pykechain.models.Scope` model). ...
def _create_executor(self, handler, args, cpus_per_worker=1): """Return a new :class:`.Executor` instance.""" if self._args.parallel > 0: workers = self._args.parallel else: try: workers = mp.cpu_count() // cpus_per_worker except NotImplemented...
Return a new :class:`.Executor` instance.
Below is the the instruction that describes the task: ### Input: Return a new :class:`.Executor` instance. ### Response: def _create_executor(self, handler, args, cpus_per_worker=1): """Return a new :class:`.Executor` instance.""" if self._args.parallel > 0: workers = self._args.paralle...
def clip_extents(self): """Computes a bounding box in user coordinates covering the area inside the current clip. :return: A ``(x1, y1, x2, y2)`` tuple of floats: the left, top, right and bottom of the resulting extents, respectively. """ ext...
Computes a bounding box in user coordinates covering the area inside the current clip. :return: A ``(x1, y1, x2, y2)`` tuple of floats: the left, top, right and bottom of the resulting extents, respectively.
Below is the the instruction that describes the task: ### Input: Computes a bounding box in user coordinates covering the area inside the current clip. :return: A ``(x1, y1, x2, y2)`` tuple of floats: the left, top, right and bottom of the resulting extents, resp...
def fruchterman_rheingold(self,attraction_multiplier=None,conflict_avoidance=None,\ defaultEdgeWeight=None,EdgeAttribute=None,gravity_multiplier=None,\ layout3D=None,max_distance_factor=None,maxWeightCutoff=None,minWeightCutoff=None,\ network=None,nIterations=None,NodeAttribute=None,nodeList=None,randomize=None,\...
Execute the Edge-weighted Force directed (BioLayout) on a network :param attraction_multiplier (string, optional): Divisor to calculate the a ttraction force, in numeric value :param conflict_avoidance (string, optional): Constant force applied to avo id conflicts, in numeric value :param defaultEdgeWeight...
Below is the the instruction that describes the task: ### Input: Execute the Edge-weighted Force directed (BioLayout) on a network :param attraction_multiplier (string, optional): Divisor to calculate the a ttraction force, in numeric value :param conflict_avoidance (string, optional): Constant force applie...
def _set_option_by_index(self, index): """ Sets a single option in the Combo by its index, returning True if it was able too. """ if index < len(self._options): self._selected.set(self._options[index]) return True else: return False
Sets a single option in the Combo by its index, returning True if it was able too.
Below is the the instruction that describes the task: ### Input: Sets a single option in the Combo by its index, returning True if it was able too. ### Response: def _set_option_by_index(self, index): """ Sets a single option in the Combo by its index, returning True if it was able too. """...
def get_value(self): """Return modified Dataframe -- this is *not* a copy""" # It is import to avoid accessing Qt C++ object as it has probably # already been destroyed, due to the Qt.WA_DeleteOnClose attribute df = self.dataModel.get_data() if self.is_series: r...
Return modified Dataframe -- this is *not* a copy
Below is the the instruction that describes the task: ### Input: Return modified Dataframe -- this is *not* a copy ### Response: def get_value(self): """Return modified Dataframe -- this is *not* a copy""" # It is import to avoid accessing Qt C++ object as it has probably # already been ...
def data_to_binary(self): """ :return: bytes """ tmp = 0x00 if 1 in self.channels: tmp += 0x03 if 2 in self.channels: tmp += 0x0c return bytes([COMMAND_CODE, tmp])
:return: bytes
Below is the the instruction that describes the task: ### Input: :return: bytes ### Response: def data_to_binary(self): """ :return: bytes """ tmp = 0x00 if 1 in self.channels: tmp += 0x03 if 2 in self.channels: tmp += 0x0c return byte...
def process_delete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs): """Recreate queryset from the index and rebuild the index.""" build_kwargs = self.delete_cache.take(obj) if build_kwargs: self.index.build(**build_kwargs)
Recreate queryset from the index and rebuild the index.
Below is the the instruction that describes the task: ### Input: Recreate queryset from the index and rebuild the index. ### Response: def process_delete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs): """Recreate queryset from the index and rebuild the index.""" build_kwargs = ...
def raise_if_cant_commit(self): """Verify VCS status and raise an error if commit is disallowed :return: """ cmd = self._command.status() (code, stdout, stderr) = self._exec(cmd) if code: raise errors.VCSError('Can\'t verify VCS status. Process exited with ...
Verify VCS status and raise an error if commit is disallowed :return:
Below is the the instruction that describes the task: ### Input: Verify VCS status and raise an error if commit is disallowed :return: ### Response: def raise_if_cant_commit(self): """Verify VCS status and raise an error if commit is disallowed :return: """ cmd = self._com...
def _link_or_update_vars(self): """ Creates or updates the symlink to group_vars and returns None. :returns: None """ for d, source in self.links.items(): target = os.path.join(self.inventory_directory, d) source = os.path.join(self._config.scenario.direc...
Creates or updates the symlink to group_vars and returns None. :returns: None
Below is the the instruction that describes the task: ### Input: Creates or updates the symlink to group_vars and returns None. :returns: None ### Response: def _link_or_update_vars(self): """ Creates or updates the symlink to group_vars and returns None. :returns: None ""...
def serialise_packet(self): """ Serialise a message, including framing information inferred from the ``Meta`` inner class of the packet. ``self.Meta.endpoint`` must be defined to call this method. :return: A serialised message, ready to be sent to the Pebble. """ if not ...
Serialise a message, including framing information inferred from the ``Meta`` inner class of the packet. ``self.Meta.endpoint`` must be defined to call this method. :return: A serialised message, ready to be sent to the Pebble.
Below is the the instruction that describes the task: ### Input: Serialise a message, including framing information inferred from the ``Meta`` inner class of the packet. ``self.Meta.endpoint`` must be defined to call this method. :return: A serialised message, ready to be sent to the Pebble. ### Re...
def update(self): """ Update the state """ vm = self._cs_api.list_virtualmachines(id=self.id)[0] self.is_running = self._is_running(vm.state)
Update the state
Below is the the instruction that describes the task: ### Input: Update the state ### Response: def update(self): """ Update the state """ vm = self._cs_api.list_virtualmachines(id=self.id)[0] self.is_running = self._is_running(vm.state)
def download(self, remote, writer): """ Downloads a file :param remote: remote file name :param writer: an object the implements the write(bytes) interface (typical a file descriptor) :return: """ fd = self.open(remote) while True: chunk = sel...
Downloads a file :param remote: remote file name :param writer: an object the implements the write(bytes) interface (typical a file descriptor) :return:
Below is the the instruction that describes the task: ### Input: Downloads a file :param remote: remote file name :param writer: an object the implements the write(bytes) interface (typical a file descriptor) :return: ### Response: def download(self, remote, writer): """ Dow...
def get_color_data(self, condition): ''' Disambiguate similarly-named weather conditions, and return the icon and color that match. ''' if condition not in self.color_icons: # Check for similarly-named conditions if no exact match found condition_lc = cond...
Disambiguate similarly-named weather conditions, and return the icon and color that match.
Below is the the instruction that describes the task: ### Input: Disambiguate similarly-named weather conditions, and return the icon and color that match. ### Response: def get_color_data(self, condition): ''' Disambiguate similarly-named weather conditions, and return the icon and...
def check_robotstxt(url, session): """Check if robots.txt allows our user agent for the given URL. @raises: IOError if URL is not allowed """ roboturl = get_roboturl(url) rp = get_robotstxt_parser(roboturl, session=session) if not rp.can_fetch(UserAgent, str(url)): raise IOError("%s is d...
Check if robots.txt allows our user agent for the given URL. @raises: IOError if URL is not allowed
Below is the the instruction that describes the task: ### Input: Check if robots.txt allows our user agent for the given URL. @raises: IOError if URL is not allowed ### Response: def check_robotstxt(url, session): """Check if robots.txt allows our user agent for the given URL. @raises: IOError if URL i...
def disconnect_handler(remote, *args, **kwargs): """Handle unlinking of remote account. This default handler will just delete the remote account link. You may wish to extend this module to perform clean-up in the remote service before removing the link (e.g. removing install webhooks). :param remo...
Handle unlinking of remote account. This default handler will just delete the remote account link. You may wish to extend this module to perform clean-up in the remote service before removing the link (e.g. removing install webhooks). :param remote: The remote application. :returns: Redirect respo...
Below is the the instruction that describes the task: ### Input: Handle unlinking of remote account. This default handler will just delete the remote account link. You may wish to extend this module to perform clean-up in the remote service before removing the link (e.g. removing install webhooks). ...
def create_design_doc(self): """Create a design document from a Python map function""" source = [x for x in inspect.getsourcelines(self.func)[0] if not x.startswith('@')] doc = { '_id': '_design/{}'.format(self.name), 'language': 'python', '...
Create a design document from a Python map function
Below is the the instruction that describes the task: ### Input: Create a design document from a Python map function ### Response: def create_design_doc(self): """Create a design document from a Python map function""" source = [x for x in inspect.getsourcelines(self.func)[0] if no...
def put(local_path, hdfs_path): """Put a file on hdfs :param local_path: Source (str) :param hdfs_path: Destination (str) :raises: IOError: If unsuccessful """ cmd = "hadoop fs -put %s %s" % (local_path, hdfs_path) rcode, stdout, stderr = _checked_hadoop_fs_command(cmd)
Put a file on hdfs :param local_path: Source (str) :param hdfs_path: Destination (str) :raises: IOError: If unsuccessful
Below is the the instruction that describes the task: ### Input: Put a file on hdfs :param local_path: Source (str) :param hdfs_path: Destination (str) :raises: IOError: If unsuccessful ### Response: def put(local_path, hdfs_path): """Put a file on hdfs :param local_path: Source (str) :pa...
def _set_apply_exp_traffic_class_map_name(self, v, load=False): """ Setter method for apply_exp_traffic_class_map_name, mapped from YANG variable /qos_mpls/map_apply/apply_exp_traffic_class_map_name (container) If this variable is read-only (config: false) in the source YANG file, then _set_apply_exp_tr...
Setter method for apply_exp_traffic_class_map_name, mapped from YANG variable /qos_mpls/map_apply/apply_exp_traffic_class_map_name (container) If this variable is read-only (config: false) in the source YANG file, then _set_apply_exp_traffic_class_map_name is considered as a private method. Backends looking...
Below is the the instruction that describes the task: ### Input: Setter method for apply_exp_traffic_class_map_name, mapped from YANG variable /qos_mpls/map_apply/apply_exp_traffic_class_map_name (container) If this variable is read-only (config: false) in the source YANG file, then _set_apply_exp_traffic_c...
def step(self, loss, optimizer, scheduler, update=True): """ Performs one step of the optimizer. :param loss: value of loss function :param optimizer: optimizer :param update: if True executes weight update """ loss.backward() if update: if se...
Performs one step of the optimizer. :param loss: value of loss function :param optimizer: optimizer :param update: if True executes weight update
Below is the the instruction that describes the task: ### Input: Performs one step of the optimizer. :param loss: value of loss function :param optimizer: optimizer :param update: if True executes weight update ### Response: def step(self, loss, optimizer, scheduler, update=True): ...
def check_all(self): """ Run all checks on the input file. """ self.file_errors = 0 self.line_number = 0 self.indent_char = None self.indent_level = 0 self.previous_logical = '' self.blank_lines = 0 self.tokens = [] parens = 0 ...
Run all checks on the input file.
Below is the the instruction that describes the task: ### Input: Run all checks on the input file. ### Response: def check_all(self): """ Run all checks on the input file. """ self.file_errors = 0 self.line_number = 0 self.indent_char = None self.indent_level...
def add(self, dist): """Add `dist` if we ``can_add()`` it and it has not already been added """ if self.can_add(dist) and dist.has_version(): dists = self._distmap.setdefault(dist.key, []) if dist not in dists: dists.append(dist) dists.sort...
Add `dist` if we ``can_add()`` it and it has not already been added
Below is the the instruction that describes the task: ### Input: Add `dist` if we ``can_add()`` it and it has not already been added ### Response: def add(self, dist): """Add `dist` if we ``can_add()`` it and it has not already been added """ if self.can_add(dist) and dist.has_version(): ...
def _pidgin_status(status, message): """ Updates status and message for Pidgin IM application. `status` Status type. `message` Status message. """ try: iface = _dbus_get_interface('im.pidgin.purple.PurpleService', '/im...
Updates status and message for Pidgin IM application. `status` Status type. `message` Status message.
Below is the the instruction that describes the task: ### Input: Updates status and message for Pidgin IM application. `status` Status type. `message` Status message. ### Response: def _pidgin_status(status, message): """ Updates status and message for Pidgin IM applica...
def verify_hmac_sha1(request, client_secret=None, resource_owner_secret=None): """Verify a HMAC-SHA1 signature. Per `section 3.4`_ of the spec. .. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4 To satisfy `RFC2616 section 5.2`_ item 1, the request argument's uri ...
Verify a HMAC-SHA1 signature. Per `section 3.4`_ of the spec. .. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4 To satisfy `RFC2616 section 5.2`_ item 1, the request argument's uri attribute MUST be an absolute URI whose netloc part identifies the origin server or gateway on whic...
Below is the the instruction that describes the task: ### Input: Verify a HMAC-SHA1 signature. Per `section 3.4`_ of the spec. .. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4 To satisfy `RFC2616 section 5.2`_ item 1, the request argument's uri attribute MUST be an absolute URI ...
def _pfp__build(self, stream=None, save_offset=False): """Build the field and write the result into the stream :stream: An IO stream that can be written to :returns: None """ if save_offset and stream is not None: self._pfp__offset = stream.tell() # returns...
Build the field and write the result into the stream :stream: An IO stream that can be written to :returns: None
Below is the the instruction that describes the task: ### Input: Build the field and write the result into the stream :stream: An IO stream that can be written to :returns: None ### Response: def _pfp__build(self, stream=None, save_offset=False): """Build the field and write the result int...
def classify_regions(dataset, masks, method='ERF', threshold=0.08, remove_overlap=True, regularization='scale', output='summary', studies=None, features=None, class_weight='auto', classifier=None, cross_val='4-Fold', param_grid=None, sc...
Perform classification on specified regions Given a set of masks, this function retrieves studies associated with each mask at the specified threshold, optionally removes overlap and filters by studies and features. Then it trains an algorithm to classify studies based on features and t...
Below is the the instruction that describes the task: ### Input: Perform classification on specified regions Given a set of masks, this function retrieves studies associated with each mask at the specified threshold, optionally removes overlap and filters by studies and features. Then it tr...
def in_edit_mode(self, request, placeholder): """ Returns True, if the plugin is in "edit mode". """ toolbar = getattr(request, 'toolbar', None) edit_mode = getattr(toolbar, 'edit_mode', False) and getattr(placeholder, 'is_editable', True) if edit_mode: edit_m...
Returns True, if the plugin is in "edit mode".
Below is the the instruction that describes the task: ### Input: Returns True, if the plugin is in "edit mode". ### Response: def in_edit_mode(self, request, placeholder): """ Returns True, if the plugin is in "edit mode". """ toolbar = getattr(request, 'toolbar', None) edit...
def get_task_param_string(task): """Get all parameters of a task as one string Returns: str: task parameter string """ # get dict str -> str from luigi param_dict = task.to_str_params() # sort keys, serialize items = [] for key in sorted(param_dict.keys()): items.append...
Get all parameters of a task as one string Returns: str: task parameter string
Below is the the instruction that describes the task: ### Input: Get all parameters of a task as one string Returns: str: task parameter string ### Response: def get_task_param_string(task): """Get all parameters of a task as one string Returns: str: task parameter string """ ...
def p_navigation_step_2(self, p): '''navigation_step : ARROW identifier LSQBR identifier DOT phrase RSQBR''' p[0] = NavigationStepNode(key_letter=p[2], rel_id=p[4], phrase=p[6])
navigation_step : ARROW identifier LSQBR identifier DOT phrase RSQBR
Below is the the instruction that describes the task: ### Input: navigation_step : ARROW identifier LSQBR identifier DOT phrase RSQBR ### Response: def p_navigation_step_2(self, p): '''navigation_step : ARROW identifier LSQBR identifier DOT phrase RSQBR''' p[0] = NavigationStepNode(key_letter=p[2],...
def make_prefix(self, prefix, iterable): """ Add prefix to the label :param prefix: :param iterable: :return: """ if not prefix: yield from iterable for key, value in iterable: yield f"{prefix}_{key}", value
Add prefix to the label :param prefix: :param iterable: :return:
Below is the the instruction that describes the task: ### Input: Add prefix to the label :param prefix: :param iterable: :return: ### Response: def make_prefix(self, prefix, iterable): """ Add prefix to the label :param prefix: :param iterable: :ret...
def get_referenced_object(self): """ :rtype: core.BunqModel :raise: BunqException """ if self._TabUsageSingle is not None: return self._TabUsageSingle if self._TabUsageMultiple is not None: return self._TabUsageMultiple raise exception.B...
:rtype: core.BunqModel :raise: BunqException
Below is the the instruction that describes the task: ### Input: :rtype: core.BunqModel :raise: BunqException ### Response: def get_referenced_object(self): """ :rtype: core.BunqModel :raise: BunqException """ if self._TabUsageSingle is not None: return ...
def list_tables(self, limit=None, start_table=None): """ Return a list of the names of all Tables associated with the current account and region. TODO - Layer2 should probably automatically handle pagination. :type limit: int :param limit: The maximum number of tables to...
Return a list of the names of all Tables associated with the current account and region. TODO - Layer2 should probably automatically handle pagination. :type limit: int :param limit: The maximum number of tables to return. :type start_table: str :param limit: The name o...
Below is the the instruction that describes the task: ### Input: Return a list of the names of all Tables associated with the current account and region. TODO - Layer2 should probably automatically handle pagination. :type limit: int :param limit: The maximum number of tables to ret...
def reduce_duplicate_frequencies(self): """In case multiple frequencies were measured, average them and compute std, min, max values for zt. In case timesteps were added (i.e., multiple separate measurements), group over those and average for each timestep. Examples ---...
In case multiple frequencies were measured, average them and compute std, min, max values for zt. In case timesteps were added (i.e., multiple separate measurements), group over those and average for each timestep. Examples -------- :: import tempfile ...
Below is the the instruction that describes the task: ### Input: In case multiple frequencies were measured, average them and compute std, min, max values for zt. In case timesteps were added (i.e., multiple separate measurements), group over those and average for each timestep. Ex...
def _CreateStopPlacemark(self, stop_folder, stop, style_id): """Creates a new stop <Placemark/> element. Args: stop_folder: the KML folder the placemark will be added to. stop: the actual Stop to create a placemark for. style_id: optional argument indicating a style id to add to the placemark...
Creates a new stop <Placemark/> element. Args: stop_folder: the KML folder the placemark will be added to. stop: the actual Stop to create a placemark for. style_id: optional argument indicating a style id to add to the placemark.
Below is the the instruction that describes the task: ### Input: Creates a new stop <Placemark/> element. Args: stop_folder: the KML folder the placemark will be added to. stop: the actual Stop to create a placemark for. style_id: optional argument indicating a style id to add to the placemar...
def create_coupon(self, currency, amount, receiver): """ This method allows you to create Coupons. Please, note: In order to use this method, you need the Coupon key privilege. You can make a request to enable it by submitting a ticket to Support.. You need to create the API key ...
This method allows you to create Coupons. Please, note: In order to use this method, you need the Coupon key privilege. You can make a request to enable it by submitting a ticket to Support.. You need to create the API key that you are going to use for this method in advance. Please provide ...
Below is the the instruction that describes the task: ### Input: This method allows you to create Coupons. Please, note: In order to use this method, you need the Coupon key privilege. You can make a request to enable it by submitting a ticket to Support.. You need to create the API key that...
async def change_presence(self, *, activity=None, status=None, afk=False, shard_id=None): """|coro| Changes the client's presence. The activity parameter is a :class:`Activity` object (not a string) that represents the activity being done currently. This could also be the slimmed down ...
|coro| Changes the client's presence. The activity parameter is a :class:`Activity` object (not a string) that represents the activity being done currently. This could also be the slimmed down versions, :class:`Game` and :class:`Streaming`. Example: :: game = disc...
Below is the the instruction that describes the task: ### Input: |coro| Changes the client's presence. The activity parameter is a :class:`Activity` object (not a string) that represents the activity being done currently. This could also be the slimmed down versions, :class:`Game` ...
def create_key_for_data(prefix, data, key_params): """ From ``data`` params in task create corresponding key with help of ``key_params`` (defined in decorator) """ d = data.get_data() values = [] for k in key_params: if k in d and type(d[k]) is list: values.append("{0}:{1}".f...
From ``data`` params in task create corresponding key with help of ``key_params`` (defined in decorator)
Below is the the instruction that describes the task: ### Input: From ``data`` params in task create corresponding key with help of ``key_params`` (defined in decorator) ### Response: def create_key_for_data(prefix, data, key_params): """ From ``data`` params in task create corresponding key with help of `...
def unroll_auth_headers(self, authheaders, exclude_signature=False, sep=",", quote=True): """Converts an authorization header dict-like object into a string representing the authorization. Keyword arguments: authheaders -- A string-indexable object which contains the headers appropriate for thi...
Converts an authorization header dict-like object into a string representing the authorization. Keyword arguments: authheaders -- A string-indexable object which contains the headers appropriate for this signature version.
Below is the the instruction that describes the task: ### Input: Converts an authorization header dict-like object into a string representing the authorization. Keyword arguments: authheaders -- A string-indexable object which contains the headers appropriate for this signature version. ### Respons...
def reload(self): """ Reload the flow from the pickle file. Used when we are monitoring the flow executed by the scheduler. In this case, indeed, the flow might have been changed by the scheduler and we have to reload the new flow in memory. """ new = self.__class__.pickl...
Reload the flow from the pickle file. Used when we are monitoring the flow executed by the scheduler. In this case, indeed, the flow might have been changed by the scheduler and we have to reload the new flow in memory.
Below is the the instruction that describes the task: ### Input: Reload the flow from the pickle file. Used when we are monitoring the flow executed by the scheduler. In this case, indeed, the flow might have been changed by the scheduler and we have to reload the new flow in memory. ### Response: ...
def works(self, prefix_id): """ This method retrieve a iterable of Works of the given prefix. args: Crossref Prefix (String) return: Works() """ context = '%s/%s' % (self.ENDPOINT, str(prefix_id)) return Works(context=context)
This method retrieve a iterable of Works of the given prefix. args: Crossref Prefix (String) return: Works()
Below is the the instruction that describes the task: ### Input: This method retrieve a iterable of Works of the given prefix. args: Crossref Prefix (String) return: Works() ### Response: def works(self, prefix_id): """ This method retrieve a iterable of Works of the given prefix....
def transform_rest_response(self, response_body): """Translates an apiserving REST response so it's ready to return. Currently, the only thing that needs to be fixed here is indentation, so it's consistent with what the live app will return. Args: response_body: A string containing the backend r...
Translates an apiserving REST response so it's ready to return. Currently, the only thing that needs to be fixed here is indentation, so it's consistent with what the live app will return. Args: response_body: A string containing the backend response. Returns: A reformatted version of the...
Below is the the instruction that describes the task: ### Input: Translates an apiserving REST response so it's ready to return. Currently, the only thing that needs to be fixed here is indentation, so it's consistent with what the live app will return. Args: response_body: A string containing t...
def sec_project_community(self, project=None): """ Generate the data for the Communication section in a Project report :return: """ def create_csv(metric1, csv_labels, file_label): esfilters = None csv_labels = csv_labels.replace("_", "") # LaTeX not sup...
Generate the data for the Communication section in a Project report :return:
Below is the the instruction that describes the task: ### Input: Generate the data for the Communication section in a Project report :return: ### Response: def sec_project_community(self, project=None): """ Generate the data for the Communication section in a Project report :return:...
def _set_bd_vc_peer_counter(self, v, load=False): """ Setter method for bd_vc_peer_counter, mapped from YANG variable /bd_vc_peer_state/bd_vc_peer_counter (container) If this variable is read-only (config: false) in the source YANG file, then _set_bd_vc_peer_counter is considered as a private method...
Setter method for bd_vc_peer_counter, mapped from YANG variable /bd_vc_peer_state/bd_vc_peer_counter (container) If this variable is read-only (config: false) in the source YANG file, then _set_bd_vc_peer_counter is considered as a private method. Backends looking to populate this variable should do so ...
Below is the the instruction that describes the task: ### Input: Setter method for bd_vc_peer_counter, mapped from YANG variable /bd_vc_peer_state/bd_vc_peer_counter (container) If this variable is read-only (config: false) in the source YANG file, then _set_bd_vc_peer_counter is considered as a private ...
def set_position(self, decl_pos): """Set editor position from ENSIME declPos data.""" if decl_pos["typehint"] == "LineSourcePosition": self.editor.set_cursor(decl_pos['line'], 0) else: # OffsetSourcePosition point = decl_pos["offset"] row, col = self.editor.p...
Set editor position from ENSIME declPos data.
Below is the the instruction that describes the task: ### Input: Set editor position from ENSIME declPos data. ### Response: def set_position(self, decl_pos): """Set editor position from ENSIME declPos data.""" if decl_pos["typehint"] == "LineSourcePosition": self.editor.set_cursor(decl...
def solve_boolexpr(): """ sudo pip install git+https://github.com/tpircher/quine-mccluskey.git sudo pip uninstall quine_mccluskey pip uninstall quine_mccluskey pip install git+https://github.com/tpircher/quine-mccluskey.git Args: varnames (?): Returns: ?: CommandLine...
sudo pip install git+https://github.com/tpircher/quine-mccluskey.git sudo pip uninstall quine_mccluskey pip uninstall quine_mccluskey pip install git+https://github.com/tpircher/quine-mccluskey.git Args: varnames (?): Returns: ?: CommandLine: python -m utool.util_alg...
Below is the the instruction that describes the task: ### Input: sudo pip install git+https://github.com/tpircher/quine-mccluskey.git sudo pip uninstall quine_mccluskey pip uninstall quine_mccluskey pip install git+https://github.com/tpircher/quine-mccluskey.git Args: varnames (?): R...
def create(cls, name, vm, size, snapshotprofile, datacenter, source, disk_type='data', background=False): """ Create a disk and attach it to a vm. """ if isinstance(size, tuple): prefix, size = size if source: size = None disk_params = cls.disk_par...
Create a disk and attach it to a vm.
Below is the the instruction that describes the task: ### Input: Create a disk and attach it to a vm. ### Response: def create(cls, name, vm, size, snapshotprofile, datacenter, source, disk_type='data', background=False): """ Create a disk and attach it to a vm. """ if isinstance(siz...
def items(self): """ A generator yielding ``(key, value)`` attribute pairs, sorted by key name. """ for key in sorted(self.attrs): yield key, self.attrs[key]
A generator yielding ``(key, value)`` attribute pairs, sorted by key name.
Below is the the instruction that describes the task: ### Input: A generator yielding ``(key, value)`` attribute pairs, sorted by key name. ### Response: def items(self): """ A generator yielding ``(key, value)`` attribute pairs, sorted by key name. """ for key in sorted(self.attrs)...
def _get_thumbnail_options(self, context, instance): """ Return the size and options of the thumbnail that should be inserted """ width, height = None, None subject_location = False placeholder_width = context.get('width', None) placeholder_height = context.get('h...
Return the size and options of the thumbnail that should be inserted
Below is the the instruction that describes the task: ### Input: Return the size and options of the thumbnail that should be inserted ### Response: def _get_thumbnail_options(self, context, instance): """ Return the size and options of the thumbnail that should be inserted """ width...
def readline_check_physical(self): """ Check and return the next physical line. This method can be used to feed tokenize.generate_tokens. """ line = self.readline() if line: self.check_physical(line) return line
Check and return the next physical line. This method can be used to feed tokenize.generate_tokens.
Below is the the instruction that describes the task: ### Input: Check and return the next physical line. This method can be used to feed tokenize.generate_tokens. ### Response: def readline_check_physical(self): """ Check and return the next physical line. This method can be used t...
def _run_yum_command(cmd, fatal=False): """Run an YUM command. Checks the output and retry if the fatal flag is set to True. :param: cmd: str: The yum command to run. :param: fatal: bool: Whether the command's output should be checked and retried. """ env = os.environ.copy() if fa...
Run an YUM command. Checks the output and retry if the fatal flag is set to True. :param: cmd: str: The yum command to run. :param: fatal: bool: Whether the command's output should be checked and retried.
Below is the the instruction that describes the task: ### Input: Run an YUM command. Checks the output and retry if the fatal flag is set to True. :param: cmd: str: The yum command to run. :param: fatal: bool: Whether the command's output should be checked and retried. ### Response: def _run_...
def _get_point_data_handler_for(self, point): """Used by point instances and data callbacks""" with self.__point_data_handlers: try: return self.__point_data_handlers[point] except KeyError: return self.__point_data_handlers.setdefault(point, Point...
Used by point instances and data callbacks
Below is the the instruction that describes the task: ### Input: Used by point instances and data callbacks ### Response: def _get_point_data_handler_for(self, point): """Used by point instances and data callbacks""" with self.__point_data_handlers: try: return self.__po...
def _stat(file): """ Get the Ownership information from a file. :param file: The path to a file to stat :type file: str :returns: owner, group, and mode of the specified file :rtype: Ownership :raises subprocess.CalledProcessError: If the underlying stat fails """ out = subprocess.c...
Get the Ownership information from a file. :param file: The path to a file to stat :type file: str :returns: owner, group, and mode of the specified file :rtype: Ownership :raises subprocess.CalledProcessError: If the underlying stat fails
Below is the the instruction that describes the task: ### Input: Get the Ownership information from a file. :param file: The path to a file to stat :type file: str :returns: owner, group, and mode of the specified file :rtype: Ownership :raises subprocess.CalledProcessError: If the underlying s...
def series_strip(series, startswith=None, endswith=None, startsorendswith=None, ignorecase=True): """ Strip a suffix/prefix str (`endswith`/`startswith` str) from a `df` columns or pd.Series of type str """ if ignorecase: mask = series.str.lower() endswith = endswith.lower() else: ma...
Strip a suffix/prefix str (`endswith`/`startswith` str) from a `df` columns or pd.Series of type str
Below is the the instruction that describes the task: ### Input: Strip a suffix/prefix str (`endswith`/`startswith` str) from a `df` columns or pd.Series of type str ### Response: def series_strip(series, startswith=None, endswith=None, startsorendswith=None, ignorecase=True): """ Strip a suffix/prefix str (`e...
def _forget_page(self, page): """Remove a page from document page dict.""" pid = id(page) if pid in self._page_refs: self._page_refs[pid] = None
Remove a page from document page dict.
Below is the the instruction that describes the task: ### Input: Remove a page from document page dict. ### Response: def _forget_page(self, page): """Remove a page from document page dict.""" pid = id(page) if pid in self._page_refs: self._page_refs[pid] = None
def do_list(self, args): """List all connected resources.""" try: resources = self.resource_manager.list_resources_info() except Exception as e: print(e) else: self.resources = [] for ndx, (resource_name, value) in enumerate(resources.item...
List all connected resources.
Below is the the instruction that describes the task: ### Input: List all connected resources. ### Response: def do_list(self, args): """List all connected resources.""" try: resources = self.resource_manager.list_resources_info() except Exception as e: print(e) ...
def link(self): """ Registers the Link """ if self.source in self.registry: links = self.registry[self.source] params = { k: v for k, v in self.get_param_values() if k != 'name'} for link in links: link_params = { ...
Registers the Link
Below is the the instruction that describes the task: ### Input: Registers the Link ### Response: def link(self): """ Registers the Link """ if self.source in self.registry: links = self.registry[self.source] params = { k: v for k, v in self.g...
def __get_dbms_version(self, make_connection=True): """ Returns the 'DBMS Version' string """ major, minor, _, _ = self.get_server_version(make_connection=make_connection) return '{}.{}'.format(major, minor)
Returns the 'DBMS Version' string
Below is the the instruction that describes the task: ### Input: Returns the 'DBMS Version' string ### Response: def __get_dbms_version(self, make_connection=True): """ Returns the 'DBMS Version' string """ major, minor, _, _ = self.get_server_version(make_connection=make_connection...
def SSLCertificates(self): """ Lists certificates. """ url = self._url + "/SSLCertificate" params = {"f" : "json"} return self._post(url=url, param_dict=params, proxy_url=self._proxy_url, proxy_...
Lists certificates.
Below is the the instruction that describes the task: ### Input: Lists certificates. ### Response: def SSLCertificates(self): """ Lists certificates. """ url = self._url + "/SSLCertificate" params = {"f" : "json"} return self._post(url=url, ...
def notes_assumptions_extractor(impact_report, component_metadata): """Extracting notes and assumptions of the exposure layer :param impact_report: the impact report that acts as a proxy to fetch all the data that extractor needed :type impact_report: safe.report.impact_report.ImpactReport :pa...
Extracting notes and assumptions of the exposure layer :param impact_report: the impact report that acts as a proxy to fetch all the data that extractor needed :type impact_report: safe.report.impact_report.ImpactReport :param component_metadata: the component metadata. Used to obtain info...
Below is the the instruction that describes the task: ### Input: Extracting notes and assumptions of the exposure layer :param impact_report: the impact report that acts as a proxy to fetch all the data that extractor needed :type impact_report: safe.report.impact_report.ImpactReport :param co...
def load_values(self, dictionary, as_defaults=False, flat=False): """ Import config values from a dictionary. When ``as_defaults`` is set to ``True``, the values imported will be set as defaults. This can be used to declare the sections and items of configuration. Values...
Import config values from a dictionary. When ``as_defaults`` is set to ``True``, the values imported will be set as defaults. This can be used to declare the sections and items of configuration. Values of sections and items in ``dictionary`` can be dictionaries as well as instan...
Below is the the instruction that describes the task: ### Input: Import config values from a dictionary. When ``as_defaults`` is set to ``True``, the values imported will be set as defaults. This can be used to declare the sections and items of configuration. Values of sections and ...
def flat_list(lst): """This function flatten given nested list. Argument: nested list Returns: flat list """ if isinstance(lst, list): for item in lst: for i in flat_list(item): yield i else: yield lst
This function flatten given nested list. Argument: nested list Returns: flat list
Below is the the instruction that describes the task: ### Input: This function flatten given nested list. Argument: nested list Returns: flat list ### Response: def flat_list(lst): """This function flatten given nested list. Argument: nested list Returns: flat li...
def get_seq_number_from_id(id, id_template, prefix, **kw): """Return the sequence number of the given ID """ separator = kw.get("separator", "-") postfix = id.replace(prefix, "").strip(separator) postfix_segments = postfix.split(separator) seq_number = 0 possible_seq_nums = filter(lambda n: ...
Return the sequence number of the given ID
Below is the the instruction that describes the task: ### Input: Return the sequence number of the given ID ### Response: def get_seq_number_from_id(id, id_template, prefix, **kw): """Return the sequence number of the given ID """ separator = kw.get("separator", "-") postfix = id.replace(prefix, ""...
def is_connected(self): """ Test if the graph is connected. Return True if connected, False otherwise """ try: return nx.is_weakly_connected(self.graph) except nx.exception.NetworkXException: return False
Test if the graph is connected. Return True if connected, False otherwise
Below is the the instruction that describes the task: ### Input: Test if the graph is connected. Return True if connected, False otherwise ### Response: def is_connected(self): """ Test if the graph is connected. Return True if connected, False otherwise """ try: ...
def moments(data, n_neighbors=30, n_pcs=30, mode='connectivities', method='umap', metric='euclidean', use_rep=None, recurse_neighbors=False, renormalize=False, copy=False): """Computes moments for velocity estimation. Arguments --------- data: :class:`~anndata.AnnData` Annotated dat...
Computes moments for velocity estimation. Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. n_neighbors: `int` (default: 30) Number of neighbors to use. n_pcs: `int` (default: 30) Number of principal components to use. mode: `'connectivities'` or...
Below is the the instruction that describes the task: ### Input: Computes moments for velocity estimation. Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. n_neighbors: `int` (default: 30) Number of neighbors to use. n_pcs: `int` (default: 30) N...
def update(self, other_info, graph, metric_value, model_id): """ Update the controller with evaluation result of a neural architecture. Parameters ---------- other_info: any object In our case it is the father ID in the search tree. graph: Graph An instan...
Update the controller with evaluation result of a neural architecture. Parameters ---------- other_info: any object In our case it is the father ID in the search tree. graph: Graph An instance of Graph. The trained neural architecture. metric_value: float...
Below is the the instruction that describes the task: ### Input: Update the controller with evaluation result of a neural architecture. Parameters ---------- other_info: any object In our case it is the father ID in the search tree. graph: Graph An instance o...
def url(self): """The url ``str`` for :tl:`KeyboardButtonUrl` objects.""" if isinstance(self.button, types.KeyboardButtonUrl): return self.button.url
The url ``str`` for :tl:`KeyboardButtonUrl` objects.
Below is the the instruction that describes the task: ### Input: The url ``str`` for :tl:`KeyboardButtonUrl` objects. ### Response: def url(self): """The url ``str`` for :tl:`KeyboardButtonUrl` objects.""" if isinstance(self.button, types.KeyboardButtonUrl): return self.button.url
def _get_plugin_stats(self, name): ''' Used for getting stats for Plugin based stuff, like Kafka Monitor and Redis Monitor @param name: the main class stats name @return: A formatted dict of stats ''' the_dict = {} keys = self.redis_conn.keys('stats:{n}:...
Used for getting stats for Plugin based stuff, like Kafka Monitor and Redis Monitor @param name: the main class stats name @return: A formatted dict of stats
Below is the the instruction that describes the task: ### Input: Used for getting stats for Plugin based stuff, like Kafka Monitor and Redis Monitor @param name: the main class stats name @return: A formatted dict of stats ### Response: def _get_plugin_stats(self, name): ''' ...
def push(self, path, name, tag=None): '''push an image to Singularity Registry path: should correspond to an absolte image path (or derive it) name: should be the complete uri that the user has requested to push. tag: should correspond with an image tag. This is provided to mirror Docker ''' ...
push an image to Singularity Registry path: should correspond to an absolte image path (or derive it) name: should be the complete uri that the user has requested to push. tag: should correspond with an image tag. This is provided to mirror Docker
Below is the the instruction that describes the task: ### Input: push an image to Singularity Registry path: should correspond to an absolte image path (or derive it) name: should be the complete uri that the user has requested to push. tag: should correspond with an image tag. This is provided to ...
def _send_data(self, data): """ Try to send all data in buffer. """ try: self.socket.sendall(data) self._reset_errors() except: self._close() self._throttle_error("GraphiteHandler: Socket error, " "t...
Try to send all data in buffer.
Below is the the instruction that describes the task: ### Input: Try to send all data in buffer. ### Response: def _send_data(self, data): """ Try to send all data in buffer. """ try: self.socket.sendall(data) self._reset_errors() except: ...
def prior_rev(C, alpha=-1.0): r"""Prior counts for sampling of reversible transition matrices. Prior is defined as b_ij= alpha if i<=j b_ij=0 else The reversible prior adds -1 to the upper triagular part of the given count matrix. This prior respects the fact that for a revers...
r"""Prior counts for sampling of reversible transition matrices. Prior is defined as b_ij= alpha if i<=j b_ij=0 else The reversible prior adds -1 to the upper triagular part of the given count matrix. This prior respects the fact that for a reversible transition matrix the degrees...
Below is the the instruction that describes the task: ### Input: r"""Prior counts for sampling of reversible transition matrices. Prior is defined as b_ij= alpha if i<=j b_ij=0 else The reversible prior adds -1 to the upper triagular part of the given count matrix. This prior resp...
def authorizer(self, schemes, resource, action, request_args): """Construct the Authorization header for a request. Args: schemes (list of str): Authentication schemes supported for the requested action. resource (str): Object upon which an action is being performed. ...
Construct the Authorization header for a request. Args: schemes (list of str): Authentication schemes supported for the requested action. resource (str): Object upon which an action is being performed. action (str): Action being performed. request_args (list ...
Below is the the instruction that describes the task: ### Input: Construct the Authorization header for a request. Args: schemes (list of str): Authentication schemes supported for the requested action. resource (str): Object upon which an action is being performed. ...
def replace_nones(dict_or_list): """Update a dict or list in place to replace 'none' string values with Python None.""" def replace_none_in_value(value): if isinstance(value, basestring) and value.lower() == "none": return None return value items = dict_or_list.iteritems() ...
Update a dict or list in place to replace 'none' string values with Python None.
Below is the the instruction that describes the task: ### Input: Update a dict or list in place to replace 'none' string values with Python None. ### Response: def replace_nones(dict_or_list): """Update a dict or list in place to replace 'none' string values with Python None.""" def replace_none_i...
def resolve(self, other: Type) -> Optional[Type]: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None expected_second = ComplexType(NUMBER_TYPE, ComplexType(ANY_TYPE, ComplexType(ComplexType(ANY_TYPE, ANY_...
See ``PlaceholderType.resolve``
Below is the the instruction that describes the task: ### Input: See ``PlaceholderType.resolve`` ### Response: def resolve(self, other: Type) -> Optional[Type]: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None expected_second = Complex...
def mine_patterns(self, threshold): """ Mine the constructed FP tree for frequent patterns. """ if self.tree_has_single_path(self.root): return self.generate_pattern_list() else: return self.zip_patterns(self.mine_sub_trees(threshold))
Mine the constructed FP tree for frequent patterns.
Below is the the instruction that describes the task: ### Input: Mine the constructed FP tree for frequent patterns. ### Response: def mine_patterns(self, threshold): """ Mine the constructed FP tree for frequent patterns. """ if self.tree_has_single_path(self.root): ret...
def put_if_absent(self, key, value, ttl=-1): """ Associates the specified key with the given value if it is not already associated. If ttl is provided, entry will expire and get evicted after the ttl. This is equivalent to: >>> if not map.contains_key(key): >>> ...
Associates the specified key with the given value if it is not already associated. If ttl is provided, entry will expire and get evicted after the ttl. This is equivalent to: >>> if not map.contains_key(key): >>> return map.put(key,value) >>> else: >>...
Below is the the instruction that describes the task: ### Input: Associates the specified key with the given value if it is not already associated. If ttl is provided, entry will expire and get evicted after the ttl. This is equivalent to: >>> if not map.contains_key(key): >...
def instruction_ROL_memory(self, opcode, ea, m): """ Rotate memory left """ r = self.ROL(m) # log.debug("$%x ROL memory value $%x << 1 | Carry = $%x and write it to $%x \t| %s" % ( # self.program_counter, # m, r, ea, # self.cfg.mem_info.get_shortest(ea) # )...
Rotate memory left
Below is the the instruction that describes the task: ### Input: Rotate memory left ### Response: def instruction_ROL_memory(self, opcode, ea, m): """ Rotate memory left """ r = self.ROL(m) # log.debug("$%x ROL memory value $%x << 1 | Carry = $%x and write it to $%x \t| %s" % ( # ...
def verbose_option(default=False): """ Attaches the option ``verbose`` with its *default* value to the keyword arguments when the option does not exist. All positional arguments and keyword arguments are forwarded unchanged. """ def decorator(method): @wraps(method) def wrapper(*arg...
Attaches the option ``verbose`` with its *default* value to the keyword arguments when the option does not exist. All positional arguments and keyword arguments are forwarded unchanged.
Below is the the instruction that describes the task: ### Input: Attaches the option ``verbose`` with its *default* value to the keyword arguments when the option does not exist. All positional arguments and keyword arguments are forwarded unchanged. ### Response: def verbose_option(default=False): """...
def load_build_configuration_from_source(build_configuration, backends=None): """Installs pants backend packages to provide BUILD file symbols and cli goals. :param BuildConfiguration build_configuration: The BuildConfiguration (for adding aliases). :param backends: An optional list of additional packages to loa...
Installs pants backend packages to provide BUILD file symbols and cli goals. :param BuildConfiguration build_configuration: The BuildConfiguration (for adding aliases). :param backends: An optional list of additional packages to load backends from. :raises: :class:``pants.base.exceptions.BuildConfigurationError`...
Below is the the instruction that describes the task: ### Input: Installs pants backend packages to provide BUILD file symbols and cli goals. :param BuildConfiguration build_configuration: The BuildConfiguration (for adding aliases). :param backends: An optional list of additional packages to load backends fro...
def profile_to_cross_section(profile, lefthand=False, start_count=1, min_vertices=20): r""" Converts a thread profile to it's equivalent cross-section. **Profile:** The thread profile contains a single wire along the XZ plane (note: wire will be projected onto the XZ plane; Y-coords will be ignore...
r""" Converts a thread profile to it's equivalent cross-section. **Profile:** The thread profile contains a single wire along the XZ plane (note: wire will be projected onto the XZ plane; Y-coords will be ignored). The profile is expected to be of 1 thread rotation, so it's height (along the Z...
Below is the the instruction that describes the task: ### Input: r""" Converts a thread profile to it's equivalent cross-section. **Profile:** The thread profile contains a single wire along the XZ plane (note: wire will be projected onto the XZ plane; Y-coords will be ignored). The profile is...
def generate_covariance(ts, sigma, tau): r"""Generates a covariance matrix according to an squared-exponential autocovariance .. math:: \left\langle x_i x_j \right\rangle = \sigma_0^2 \delta_{ij} + \sigma^2 \exp\left[ - \frac{\left| t_i - t_j\right|^2}{2 \tau^2} \right] """ ndim = ...
r"""Generates a covariance matrix according to an squared-exponential autocovariance .. math:: \left\langle x_i x_j \right\rangle = \sigma_0^2 \delta_{ij} + \sigma^2 \exp\left[ - \frac{\left| t_i - t_j\right|^2}{2 \tau^2} \right]
Below is the the instruction that describes the task: ### Input: r"""Generates a covariance matrix according to an squared-exponential autocovariance .. math:: \left\langle x_i x_j \right\rangle = \sigma_0^2 \delta_{ij} + \sigma^2 \exp\left[ - \frac{\left| t_i - t_j\right|^2}{2 \tau^2} \righ...
def json(self): """Returns the json-encoded content of the response, if any.""" if hasattr(self, '_json'): return self._json try: self._json = json.loads(self.text or self.content) except ValueError: self._json = None return self._json
Returns the json-encoded content of the response, if any.
Below is the the instruction that describes the task: ### Input: Returns the json-encoded content of the response, if any. ### Response: def json(self): """Returns the json-encoded content of the response, if any.""" if hasattr(self, '_json'): return self._json try: ...