code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def load_bioassembly_info_from_file(self, biomol_num): """Load metadata about a bioassembly (such as chains and their transformations) from a structure file. """ # current functionality is to take in a pre-assembled bioassembly file, parse it's MODELs and get info from that pass ...
Load metadata about a bioassembly (such as chains and their transformations) from a structure file.
Below is the the instruction that describes the task: ### Input: Load metadata about a bioassembly (such as chains and their transformations) from a structure file. ### Response: def load_bioassembly_info_from_file(self, biomol_num): """Load metadata about a bioassembly (such as chains and their transforma...
def get_table(self, dbname, tbl_name): """ Parameters: - dbname - tbl_name """ self.send_get_table(dbname, tbl_name) return self.recv_get_table()
Parameters: - dbname - tbl_name
Below is the the instruction that describes the task: ### Input: Parameters: - dbname - tbl_name ### Response: def get_table(self, dbname, tbl_name): """ Parameters: - dbname - tbl_name """ self.send_get_table(dbname, tbl_name) return self.recv_get_table()
def apply(self, token, previous=(None, None), next=(None, None)): """ Applies lexical rules to the given token, which is a [word, tag] list. """ w = token[0] for r in self: if r[1] in self._cmd: # Rule = ly hassuf 2 RB x f, x, pos, cmd = bool(0), r[0], r[-2], ...
Applies lexical rules to the given token, which is a [word, tag] list.
Below is the the instruction that describes the task: ### Input: Applies lexical rules to the given token, which is a [word, tag] list. ### Response: def apply(self, token, previous=(None, None), next=(None, None)): """ Applies lexical rules to the given token, which is a [word, tag] list. """ ...
def is_ready(self): """Is thread & ioloop ready. :returns bool: """ if not self._thread: return False if not self._ready.is_set(): return False return True
Is thread & ioloop ready. :returns bool:
Below is the the instruction that describes the task: ### Input: Is thread & ioloop ready. :returns bool: ### Response: def is_ready(self): """Is thread & ioloop ready. :returns bool: """ if not self._thread: return False if not self._ready.is_set(): ...
def copy(self): """ Create a deep copy of this sequence Returns: :obj:`.FileSequence`: """ fs = self.__class__.__new__(self.__class__) fs.__dict__ = self.__dict__.copy() fs._frameSet = None if self._frameSet is not None: fs._frameS...
Create a deep copy of this sequence Returns: :obj:`.FileSequence`:
Below is the the instruction that describes the task: ### Input: Create a deep copy of this sequence Returns: :obj:`.FileSequence`: ### Response: def copy(self): """ Create a deep copy of this sequence Returns: :obj:`.FileSequence`: """ fs =...
def _check_flag_masks(self, ds, name): ''' Check a variable's flag_masks attribute for compliance under CF - flag_masks exists as an array - flag_masks is the same dtype as the variable - variable's dtype can support bit-field - flag_masks is the same length as flag_mean...
Check a variable's flag_masks attribute for compliance under CF - flag_masks exists as an array - flag_masks is the same dtype as the variable - variable's dtype can support bit-field - flag_masks is the same length as flag_meanings :param netCDF4.Dataset ds: An open netCDF dat...
Below is the the instruction that describes the task: ### Input: Check a variable's flag_masks attribute for compliance under CF - flag_masks exists as an array - flag_masks is the same dtype as the variable - variable's dtype can support bit-field - flag_masks is the same length as...
def create_composite_loss(losses=None, regularize=True, include_marked=True, name='cost'): """Creates a loss that is the sum of all specified losses. Args: losses: A sequence of losses to include. regularize: Whether or not to in...
Creates a loss that is the sum of all specified losses. Args: losses: A sequence of losses to include. regularize: Whether or not to include regularization losses. include_marked: Whether or not to use the marked losses. name: The name for this variable. Returns: A single tensor that is the sum...
Below is the the instruction that describes the task: ### Input: Creates a loss that is the sum of all specified losses. Args: losses: A sequence of losses to include. regularize: Whether or not to include regularization losses. include_marked: Whether or not to use the marked losses. name: The n...
def _resource_dump(pe, res): """Return the dump of the given resource.""" rva = res.data.struct.OffsetToData size = res.data.struct.Size dump = pe.get_data(rva, size) return dump
Return the dump of the given resource.
Below is the the instruction that describes the task: ### Input: Return the dump of the given resource. ### Response: def _resource_dump(pe, res): """Return the dump of the given resource.""" rva = res.data.struct.OffsetToData size = res.data.struct.Size dump = pe.get_data(rva, size) return du...
def get_ntstatus_code(self): """ @rtype: int @return: NTSTATUS status code that caused the exception. @note: This method is only meaningful for in-page memory error exceptions. @raise NotImplementedError: Not an in-page memory error. """ if self.get...
@rtype: int @return: NTSTATUS status code that caused the exception. @note: This method is only meaningful for in-page memory error exceptions. @raise NotImplementedError: Not an in-page memory error.
Below is the the instruction that describes the task: ### Input: @rtype: int @return: NTSTATUS status code that caused the exception. @note: This method is only meaningful for in-page memory error exceptions. @raise NotImplementedError: Not an in-page memory error. ### Respons...
def publishing_clone_relations(self, src_obj): """ Clone forward and reverse M2Ms. This code is difficult to follow because the logic it applies is confusing, but here is a summary that might help: - when a draft object is published, the "current" and definitive ...
Clone forward and reverse M2Ms. This code is difficult to follow because the logic it applies is confusing, but here is a summary that might help: - when a draft object is published, the "current" and definitive relationships are cloned to the published copy. The definitive ...
Below is the the instruction that describes the task: ### Input: Clone forward and reverse M2Ms. This code is difficult to follow because the logic it applies is confusing, but here is a summary that might help: - when a draft object is published, the "current" and definitive ...
def schedule_ping_frequency(self): # pragma: no cover "Send a ping message to slack every 20 seconds" ping = crontab('* * * * * */20', func=self.send_ping, start=False) ping.start()
Send a ping message to slack every 20 seconds
Below is the the instruction that describes the task: ### Input: Send a ping message to slack every 20 seconds ### Response: def schedule_ping_frequency(self): # pragma: no cover "Send a ping message to slack every 20 seconds" ping = crontab('* * * * * */20', func=self.send_ping, start=False) ...
def unmasked_for_shape_and_pixel_scale(cls, shape, pixel_scale, invert=False): """Setup a mask where all pixels are unmasked. Parameters ---------- shape : (int, int) The (y,x) shape of the mask in units of pixels. pixel_scale: float The arc-second to pix...
Setup a mask where all pixels are unmasked. Parameters ---------- shape : (int, int) The (y,x) shape of the mask in units of pixels. pixel_scale: float The arc-second to pixel conversion factor of each pixel.
Below is the the instruction that describes the task: ### Input: Setup a mask where all pixels are unmasked. Parameters ---------- shape : (int, int) The (y,x) shape of the mask in units of pixels. pixel_scale: float The arc-second to pixel conversion factor ...
def get_seed(self): """ Collects the required information to generate a data estructure that can be used to recreate exactly the same geometry object via *\*\*kwargs*. :returns: Object's sufficient info to initialize it. :rtype: dict """ ...
Collects the required information to generate a data estructure that can be used to recreate exactly the same geometry object via *\*\*kwargs*. :returns: Object's sufficient info to initialize it. :rtype: dict
Below is the the instruction that describes the task: ### Input: Collects the required information to generate a data estructure that can be used to recreate exactly the same geometry object via *\*\*kwargs*. :returns: Object's sufficient info to initialize it. :rtype:...
def get_credits_by_section_and_regid(section, regid): """ Returns a uw_sws.models.Registration object for the section and regid passed in. """ deprecation("Use get_credits_by_reg_url") # note trailing comma in URL, it's required for the optional dup_code param url = "{}{},{},{},{},{},{},.jso...
Returns a uw_sws.models.Registration object for the section and regid passed in.
Below is the the instruction that describes the task: ### Input: Returns a uw_sws.models.Registration object for the section and regid passed in. ### Response: def get_credits_by_section_and_regid(section, regid): """ Returns a uw_sws.models.Registration object for the section and regid passed in. ...
def get_library_citation(): '''Return a descriptive string and reference data for what users of the library should cite''' all_ref_data = api.get_reference_data() lib_refs_data = {k: all_ref_data[k] for k in _lib_refs} return (_lib_refs_desc, lib_refs_data)
Return a descriptive string and reference data for what users of the library should cite
Below is the the instruction that describes the task: ### Input: Return a descriptive string and reference data for what users of the library should cite ### Response: def get_library_citation(): '''Return a descriptive string and reference data for what users of the library should cite''' all_ref_data = ...
def load_segmented_data(filename): """ Helper function to load segmented gait time series data. :param filename: The full path of the file that contais our data. This should be a comma separated value (csv file). :type filename: str :return: The gait time series segmented data, wit...
Helper function to load segmented gait time series data. :param filename: The full path of the file that contais our data. This should be a comma separated value (csv file). :type filename: str :return: The gait time series segmented data, with a x, y, z, mag_acc_sum and segmented columns. ...
Below is the the instruction that describes the task: ### Input: Helper function to load segmented gait time series data. :param filename: The full path of the file that contais our data. This should be a comma separated value (csv file). :type filename: str :return: The gait time series s...
def parse_compartments(self): """Parse compartment information from model. Return tuple of: 1) iterator of :class:`psamm.datasource.entry.CompartmentEntry`; 2) Set of pairs defining the compartment boundaries of the model. """ compartments = OrderedDict() bounda...
Parse compartment information from model. Return tuple of: 1) iterator of :class:`psamm.datasource.entry.CompartmentEntry`; 2) Set of pairs defining the compartment boundaries of the model.
Below is the the instruction that describes the task: ### Input: Parse compartment information from model. Return tuple of: 1) iterator of :class:`psamm.datasource.entry.CompartmentEntry`; 2) Set of pairs defining the compartment boundaries of the model. ### Response: def parse_compartment...
def get(self, treeiter, *columns): """ :param treeiter: the :obj:`Gtk.TreeIter` :type treeiter: :obj:`Gtk.TreeIter` :param \\*columns: a list of column indices to fetch :type columns: (:obj:`int`) Returns a tuple of all values specified by their indices in `columns` ...
:param treeiter: the :obj:`Gtk.TreeIter` :type treeiter: :obj:`Gtk.TreeIter` :param \\*columns: a list of column indices to fetch :type columns: (:obj:`int`) Returns a tuple of all values specified by their indices in `columns` in the order the indices are contained in `columns...
Below is the the instruction that describes the task: ### Input: :param treeiter: the :obj:`Gtk.TreeIter` :type treeiter: :obj:`Gtk.TreeIter` :param \\*columns: a list of column indices to fetch :type columns: (:obj:`int`) Returns a tuple of all values specified by their indices in...
def libvlc_media_list_player_new(p_instance): '''Create new media_list_player. @param p_instance: libvlc instance. @return: media list player instance or NULL on error. ''' f = _Cfunctions.get('libvlc_media_list_player_new', None) or \ _Cfunction('libvlc_media_list_player_new', ((1,),), clas...
Create new media_list_player. @param p_instance: libvlc instance. @return: media list player instance or NULL on error.
Below is the the instruction that describes the task: ### Input: Create new media_list_player. @param p_instance: libvlc instance. @return: media list player instance or NULL on error. ### Response: def libvlc_media_list_player_new(p_instance): '''Create new media_list_player. @param p_instance: li...
def _handshake(self): """ Perform an initial TLS handshake """ session_context = None ssl_policy_ref = None crl_search_ref = None crl_policy_ref = None ocsp_search_ref = None ocsp_policy_ref = None policy_array_ref = None try: ...
Perform an initial TLS handshake
Below is the the instruction that describes the task: ### Input: Perform an initial TLS handshake ### Response: def _handshake(self): """ Perform an initial TLS handshake """ session_context = None ssl_policy_ref = None crl_search_ref = None crl_policy_ref =...
def addCity(self, fileName): """Add a JSON file and read the users. :param fileName: path to the JSON file. This file has to have a list of users, called users. :type fileName: str. """ with open(fileName) as data_file: data = load(data_file) for u in...
Add a JSON file and read the users. :param fileName: path to the JSON file. This file has to have a list of users, called users. :type fileName: str.
Below is the the instruction that describes the task: ### Input: Add a JSON file and read the users. :param fileName: path to the JSON file. This file has to have a list of users, called users. :type fileName: str. ### Response: def addCity(self, fileName): """Add a JSON file and r...
def QA_data_min_resample(min_data, type_='5min'): """分钟线采样成大周期 分钟线采样成子级别的分钟线 time+ OHLC==> resample Arguments: min {[type]} -- [description] raw_type {[type]} -- [description] new_type {[type]} -- [description] """ try: min_data = min_data.reset_index().set_i...
分钟线采样成大周期 分钟线采样成子级别的分钟线 time+ OHLC==> resample Arguments: min {[type]} -- [description] raw_type {[type]} -- [description] new_type {[type]} -- [description]
Below is the the instruction that describes the task: ### Input: 分钟线采样成大周期 分钟线采样成子级别的分钟线 time+ OHLC==> resample Arguments: min {[type]} -- [description] raw_type {[type]} -- [description] new_type {[type]} -- [description] ### Response: def QA_data_min_resample(min_data, typ...
def update(self, callback=None, errback=None, **kwargs): """ Update zone configuration. Pass a list of keywords and their values to update. For the list of keywords available for zone configuration, see :attr:`ns1.rest.zones.Zones.INT_FIELDS` and :attr:`ns1.rest.zones.Zones.PASST...
Update zone configuration. Pass a list of keywords and their values to update. For the list of keywords available for zone configuration, see :attr:`ns1.rest.zones.Zones.INT_FIELDS` and :attr:`ns1.rest.zones.Zones.PASSTHRU_FIELDS`
Below is the the instruction that describes the task: ### Input: Update zone configuration. Pass a list of keywords and their values to update. For the list of keywords available for zone configuration, see :attr:`ns1.rest.zones.Zones.INT_FIELDS` and :attr:`ns1.rest.zones.Zones.PASSTHRU_FIEL...
def _update_pathway_definitions(crosstalk_corrected_index_map, gene_row_names, pathway_column_names): """Helper function to convert the mapping of int (pathway id -> list of gene ids) to the corresponding pathway names and gene identifiers. ...
Helper function to convert the mapping of int (pathway id -> list of gene ids) to the corresponding pathway names and gene identifiers.
Below is the the instruction that describes the task: ### Input: Helper function to convert the mapping of int (pathway id -> list of gene ids) to the corresponding pathway names and gene identifiers. ### Response: def _update_pathway_definitions(crosstalk_corrected_index_map, ...
def _from_signer_and_info(cls, signer, info, **kwargs): """Creates a Credentials instance from a signer and service account info. Args: signer (google.auth.crypt.Signer): The signer used to sign JWTs. info (Mapping[str, str]): The service account info. kwargs...
Creates a Credentials instance from a signer and service account info. Args: signer (google.auth.crypt.Signer): The signer used to sign JWTs. info (Mapping[str, str]): The service account info. kwargs: Additional arguments to pass to the constructor. Returns...
Below is the the instruction that describes the task: ### Input: Creates a Credentials instance from a signer and service account info. Args: signer (google.auth.crypt.Signer): The signer used to sign JWTs. info (Mapping[str, str]): The service account info. kwar...
def recursion_error(self, repeated_parser: str): """Generate an error to indicate that infinite recursion was encountered. A parser can supply a representation of itself to this method and the reader will supply the context, including the location where the parser stalled. Args...
Generate an error to indicate that infinite recursion was encountered. A parser can supply a representation of itself to this method and the reader will supply the context, including the location where the parser stalled. Args: repeated_parser: A representation of the repea...
Below is the the instruction that describes the task: ### Input: Generate an error to indicate that infinite recursion was encountered. A parser can supply a representation of itself to this method and the reader will supply the context, including the location where the parser stalled. ...
def skip(self, n_batches, n_epochs=0): """ Skip N batches in the training. """ logging.info("skip %d epochs and %d batches" % (n_epochs, n_batches)) self._skip_batches = n_batches self._skip_epochs = n_epochs
Skip N batches in the training.
Below is the the instruction that describes the task: ### Input: Skip N batches in the training. ### Response: def skip(self, n_batches, n_epochs=0): """ Skip N batches in the training. """ logging.info("skip %d epochs and %d batches" % (n_epochs, n_batches)) self._skip_batc...
def find_unrelated(x, plim=0.1, axis=0): """Find indicies of insignificant un-/correlated variables Example: -------- i, j = find_unrelated(x, plim, rlim) """ # transpose if axis<>0 if axis is not 0: x = x.T # read dimensions and allocate variables _, c = x.shape p...
Find indicies of insignificant un-/correlated variables Example: -------- i, j = find_unrelated(x, plim, rlim)
Below is the the instruction that describes the task: ### Input: Find indicies of insignificant un-/correlated variables Example: -------- i, j = find_unrelated(x, plim, rlim) ### Response: def find_unrelated(x, plim=0.1, axis=0): """Find indicies of insignificant un-/correlated variables ...
def read_ipv4(self, length): """Read Internet Protocol version 4 (IPv4). Structure of IPv4 header [RFC 791]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+...
Read Internet Protocol version 4 (IPv4). Structure of IPv4 header [RFC 791]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ...
Below is the the instruction that describes the task: ### Input: Read Internet Protocol version 4 (IPv4). Structure of IPv4 header [RFC 791]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ...
def hexdigest(self): """Return the digest value as a string of hexadecimal digits.""" if self._pre_computed_hash is None: return libssdeep_wrapper.fuzzy_digest(self._state, 0) else: return self._pre_computed_hash
Return the digest value as a string of hexadecimal digits.
Below is the the instruction that describes the task: ### Input: Return the digest value as a string of hexadecimal digits. ### Response: def hexdigest(self): """Return the digest value as a string of hexadecimal digits.""" if self._pre_computed_hash is None: return libssdeep_wrapper.fu...
def is_on(self): """ Get sensor state. Assume offline or open (worst case). """ if self._type == 'Occupancy': return self.status not in CONST.STATUS_ONLINE return self.status not in (CONST.STATUS_OFF, CONST.STATUS_OFFLINE, C...
Get sensor state. Assume offline or open (worst case).
Below is the the instruction that describes the task: ### Input: Get sensor state. Assume offline or open (worst case). ### Response: def is_on(self): """ Get sensor state. Assume offline or open (worst case). """ if self._type == 'Occupancy': return se...
def _bgzip_from_cram(cram_file, dirs, data): """Create bgzipped fastq files from an input CRAM file in regions of interest. Returns a list with a single file, for single end CRAM files, or two files for paired end input. """ import pybedtools region_file = (tz.get_in(["config", "algorithm", "va...
Create bgzipped fastq files from an input CRAM file in regions of interest. Returns a list with a single file, for single end CRAM files, or two files for paired end input.
Below is the the instruction that describes the task: ### Input: Create bgzipped fastq files from an input CRAM file in regions of interest. Returns a list with a single file, for single end CRAM files, or two files for paired end input. ### Response: def _bgzip_from_cram(cram_file, dirs, data): """Cr...
def _format_value(self, operation, key, indent): """A value that exists in the operation but has value None is displayed. A value that does not exist in the operation is left out entirely. The value name in the operation must match the value name in the template, but the location does n...
A value that exists in the operation but has value None is displayed. A value that does not exist in the operation is left out entirely. The value name in the operation must match the value name in the template, but the location does not have to match.
Below is the the instruction that describes the task: ### Input: A value that exists in the operation but has value None is displayed. A value that does not exist in the operation is left out entirely. The value name in the operation must match the value name in the template, but the locati...
def sign(url, app_id, app_secret, hash_meth='sha1', **params): ''' A signature method which generates the necessary Ofly parameters. :param app_id: The oFlyAppId, i.e. "application ID". :type app_id: str :param app_secret: The oFlyAppSecret, i.e. "shared secret". :type a...
A signature method which generates the necessary Ofly parameters. :param app_id: The oFlyAppId, i.e. "application ID". :type app_id: str :param app_secret: The oFlyAppSecret, i.e. "shared secret". :type app_secret: str :param hash_meth: The hash method to use for signing, defaul...
Below is the the instruction that describes the task: ### Input: A signature method which generates the necessary Ofly parameters. :param app_id: The oFlyAppId, i.e. "application ID". :type app_id: str :param app_secret: The oFlyAppSecret, i.e. "shared secret". :type app_secret: str...
def p_directive(self, p): """ directive : AT name arguments | AT name """ arguments = p[3] if len(p) == 4 else None p[0] = Directive(name=p[2], arguments=arguments)
directive : AT name arguments | AT name
Below is the the instruction that describes the task: ### Input: directive : AT name arguments | AT name ### Response: def p_directive(self, p): """ directive : AT name arguments | AT name """ arguments = p[3] if len(p) == 4 else None p[0]...
def pore_to_pore(target): r""" Calculates throat vector as straight path between connected pores. Parameters ---------- geometry : OpenPNM Geometry object The object containing the geometrical properties of the throats Notes ----- There is an important impicit assumption here: ...
r""" Calculates throat vector as straight path between connected pores. Parameters ---------- geometry : OpenPNM Geometry object The object containing the geometrical properties of the throats Notes ----- There is an important impicit assumption here: the positive direction is ...
Below is the the instruction that describes the task: ### Input: r""" Calculates throat vector as straight path between connected pores. Parameters ---------- geometry : OpenPNM Geometry object The object containing the geometrical properties of the throats Notes ----- There is...
def get_ops(self, key): ''' Returns ops from the key if found otherwise raises a KeyError. ''' ops = self._store.get(key) if ops is None: raise KeyError( 'cannot get operations for {}'.format(key)) return ops
Returns ops from the key if found otherwise raises a KeyError.
Below is the the instruction that describes the task: ### Input: Returns ops from the key if found otherwise raises a KeyError. ### Response: def get_ops(self, key): ''' Returns ops from the key if found otherwise raises a KeyError. ''' ops = self._store.get(key) if ops is None: ...
def _build_gecos(gecos_dict): ''' Accepts a dictionary entry containing GECOS field names and their values, and returns a full GECOS comment string, to be used with usermod. ''' return '{0},{1},{2},{3}'.format(gecos_dict.get('fullname', ''), gecos_dict.get('roomnu...
Accepts a dictionary entry containing GECOS field names and their values, and returns a full GECOS comment string, to be used with usermod.
Below is the the instruction that describes the task: ### Input: Accepts a dictionary entry containing GECOS field names and their values, and returns a full GECOS comment string, to be used with usermod. ### Response: def _build_gecos(gecos_dict): ''' Accepts a dictionary entry containing GECOS field ...
def format(self, full_info: bool = False): """ :param full_info: If True, adds more info about the chat. Please, note that this additional info requires to make up to THREE synchronous api calls. """ chat = self.api_object if full_info: self.__format_full(...
:param full_info: If True, adds more info about the chat. Please, note that this additional info requires to make up to THREE synchronous api calls.
Below is the the instruction that describes the task: ### Input: :param full_info: If True, adds more info about the chat. Please, note that this additional info requires to make up to THREE synchronous api calls. ### Response: def format(self, full_info: bool = False): """ :param full_...
def get_calendar(self, listing_id, starting_month=datetime.datetime.now().month, starting_year=datetime.datetime.now().year, calendar_months=12): """ Get availability calendar for a given listing """ params = { 'year': str(starting_year), 'listing_id': str(listing...
Get availability calendar for a given listing
Below is the the instruction that describes the task: ### Input: Get availability calendar for a given listing ### Response: def get_calendar(self, listing_id, starting_month=datetime.datetime.now().month, starting_year=datetime.datetime.now().year, calendar_months=12): """ Get availability calenda...
def get_user_bookmarks(self, id, **data): """ GET /users/:id/bookmarks/ Gets all the user's saved events. In order to update the saved events list, the user must unsave or save each event. A user is authorized to only see his/her saved events. """ return ...
GET /users/:id/bookmarks/ Gets all the user's saved events. In order to update the saved events list, the user must unsave or save each event. A user is authorized to only see his/her saved events.
Below is the the instruction that describes the task: ### Input: GET /users/:id/bookmarks/ Gets all the user's saved events. In order to update the saved events list, the user must unsave or save each event. A user is authorized to only see his/her saved events. ### Response: def get_user_b...
def match_alphabet(self, pattern): """Initialise the alphabet for the Bitap algorithm. Args: pattern: The text to encode. Returns: Hash of character locations. """ s = {} for char in pattern: s[char] = 0 for i in range(len(pattern)): s[pattern[i]] |= 1 << (len(patte...
Initialise the alphabet for the Bitap algorithm. Args: pattern: The text to encode. Returns: Hash of character locations.
Below is the the instruction that describes the task: ### Input: Initialise the alphabet for the Bitap algorithm. Args: pattern: The text to encode. Returns: Hash of character locations. ### Response: def match_alphabet(self, pattern): """Initialise the alphabet for the Bitap algorithm. ...
def start(name): ''' Start the named container CLI Example: .. code-block:: bash salt myminion nspawn.start <name> ''' if _sd_version() >= 219: ret = _machinectl('start {0}'.format(name)) else: cmd = 'systemctl start systemd-nspawn@{0}'.format(name) ret = _...
Start the named container CLI Example: .. code-block:: bash salt myminion nspawn.start <name>
Below is the the instruction that describes the task: ### Input: Start the named container CLI Example: .. code-block:: bash salt myminion nspawn.start <name> ### Response: def start(name): ''' Start the named container CLI Example: .. code-block:: bash salt myminion n...
def read(filepath): """ Read a single InkML file Parameters ---------- filepath : string path to the (readable) InkML file Returns ------- HandwrittenData : The parsed InkML file as a HandwrittenData object """ import xml.etree.ElementTree root = xml.etree.E...
Read a single InkML file Parameters ---------- filepath : string path to the (readable) InkML file Returns ------- HandwrittenData : The parsed InkML file as a HandwrittenData object
Below is the the instruction that describes the task: ### Input: Read a single InkML file Parameters ---------- filepath : string path to the (readable) InkML file Returns ------- HandwrittenData : The parsed InkML file as a HandwrittenData object ### Response: def read(fi...
def load_truetype_font( path: str, tile_width: int, tile_height: int ) -> Tileset: """Return a new Tileset from a `.ttf` or `.otf` file. Same as :any:`set_truetype_font`, but returns a :any:`Tileset` instead. You can send this Tileset to :any:`set_default`. This function is provisional. The API m...
Return a new Tileset from a `.ttf` or `.otf` file. Same as :any:`set_truetype_font`, but returns a :any:`Tileset` instead. You can send this Tileset to :any:`set_default`. This function is provisional. The API may change.
Below is the the instruction that describes the task: ### Input: Return a new Tileset from a `.ttf` or `.otf` file. Same as :any:`set_truetype_font`, but returns a :any:`Tileset` instead. You can send this Tileset to :any:`set_default`. This function is provisional. The API may change. ### Response: ...
def isNXEnabled(self): """ Determines if the current L{PE} instance has the NXCOMPAT (Compatible with Data Execution Prevention) flag enabled. @see: U{http://msdn.microsoft.com/en-us/library/ms235442.aspx} @rtype: bool @return: Returns C{True} if the current L{PE} instance has t...
Determines if the current L{PE} instance has the NXCOMPAT (Compatible with Data Execution Prevention) flag enabled. @see: U{http://msdn.microsoft.com/en-us/library/ms235442.aspx} @rtype: bool @return: Returns C{True} if the current L{PE} instance has the NXCOMPAT flag enabled. Otherwise, return...
Below is the the instruction that describes the task: ### Input: Determines if the current L{PE} instance has the NXCOMPAT (Compatible with Data Execution Prevention) flag enabled. @see: U{http://msdn.microsoft.com/en-us/library/ms235442.aspx} @rtype: bool @return: Returns C{True} if the cu...
def parse_version(version): """ Return a comparable tuple from a version string. We try to force tuple to semver with version like 1.2.0 Replace pkg_resources.parse_version which now display a warning when use for comparing version with tuple :returns: Version string as comparable tuple """ r...
Return a comparable tuple from a version string. We try to force tuple to semver with version like 1.2.0 Replace pkg_resources.parse_version which now display a warning when use for comparing version with tuple :returns: Version string as comparable tuple
Below is the the instruction that describes the task: ### Input: Return a comparable tuple from a version string. We try to force tuple to semver with version like 1.2.0 Replace pkg_resources.parse_version which now display a warning when use for comparing version with tuple :returns: Version string as co...
def rebuild_tree(self, request): ''' Rebuilds the tree and clears the cache. ''' self.model.objects.rebuild() self.message_user(request, _('Menu Tree Rebuilt.')) return self.clean_cache(request)
Rebuilds the tree and clears the cache.
Below is the the instruction that describes the task: ### Input: Rebuilds the tree and clears the cache. ### Response: def rebuild_tree(self, request): ''' Rebuilds the tree and clears the cache. ''' self.model.objects.rebuild() self.message_user(request, _('Menu Tree Rebuil...
def copy(self): ''' Returns a copy of the macaroon. Note that the the new macaroon's namespace still points to the same underlying Namespace - copying the macaroon does not make a copy of the namespace. :return a Macaroon ''' m1 = Macaroon(None, None, version=self._versio...
Returns a copy of the macaroon. Note that the the new macaroon's namespace still points to the same underlying Namespace - copying the macaroon does not make a copy of the namespace. :return a Macaroon
Below is the the instruction that describes the task: ### Input: Returns a copy of the macaroon. Note that the the new macaroon's namespace still points to the same underlying Namespace - copying the macaroon does not make a copy of the namespace. :return a Macaroon ### Response: def copy(s...
def save_url_as(url, save_as): """ Download the file `url` and save it to the local disk as `save_as`. """ remote = requests.get(url, verify=False) if not remote.status_code == Constants.PULP_GET_OK: raise JuicerPulpError("A %s error occurred trying to get %s" % ...
Download the file `url` and save it to the local disk as `save_as`.
Below is the the instruction that describes the task: ### Input: Download the file `url` and save it to the local disk as `save_as`. ### Response: def save_url_as(url, save_as): """ Download the file `url` and save it to the local disk as `save_as`. """ remote = requests.get(url, verify=Fa...
def edit(directory=None, revision='current'): """Edit current revision.""" if alembic_version >= (0, 8, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.edit(config, revision) else: raise RuntimeError('Alembic 0.8.0 or greater is requi...
Edit current revision.
Below is the the instruction that describes the task: ### Input: Edit current revision. ### Response: def edit(directory=None, revision='current'): """Edit current revision.""" if alembic_version >= (0, 8, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) ...
def _create(self, cache_file): """Create the tables needed to store the information.""" conn = sqlite3.connect(cache_file) cur = conn.cursor() cur.execute("PRAGMA foreign_keys = ON") cur.execute(''' CREATE TABLE jobs( hash TEXT NOT NULL UNIQUE PRIMARY ...
Create the tables needed to store the information.
Below is the the instruction that describes the task: ### Input: Create the tables needed to store the information. ### Response: def _create(self, cache_file): """Create the tables needed to store the information.""" conn = sqlite3.connect(cache_file) cur = conn.cursor() cur.execut...
def prepend_model(self, value, model): """ Prepends model name if it is not already prepended. For example model is "Offer": key -> Offer.key -key -> -Offer.key Offer.key -> Offer.key -Offer.key -> -Offer.key """ if '.' not in valu...
Prepends model name if it is not already prepended. For example model is "Offer": key -> Offer.key -key -> -Offer.key Offer.key -> Offer.key -Offer.key -> -Offer.key
Below is the the instruction that describes the task: ### Input: Prepends model name if it is not already prepended. For example model is "Offer": key -> Offer.key -key -> -Offer.key Offer.key -> Offer.key -Offer.key -> -Offer.key ### Response: def prepend_m...
def separate_tour_and_o(row): """ The tour line typically contains contig list like: tig00044568+ tig00045748- tig00071055- tig00015093- tig00030900- This function separates the names from the orientations. """ tour = [] tour_o = [] for contig in row.split(): if contig[-1] in ('...
The tour line typically contains contig list like: tig00044568+ tig00045748- tig00071055- tig00015093- tig00030900- This function separates the names from the orientations.
Below is the the instruction that describes the task: ### Input: The tour line typically contains contig list like: tig00044568+ tig00045748- tig00071055- tig00015093- tig00030900- This function separates the names from the orientations. ### Response: def separate_tour_and_o(row): """ The tour lin...
def getLogger(cls): """ Get the logger that logs real-time to the leader. Note that if the returned logger is used on the leader, you will see the message twice, since it still goes to the normal log handlers, too. """ # Only do the setup once, so we don't add a ...
Get the logger that logs real-time to the leader. Note that if the returned logger is used on the leader, you will see the message twice, since it still goes to the normal log handlers, too.
Below is the the instruction that describes the task: ### Input: Get the logger that logs real-time to the leader. Note that if the returned logger is used on the leader, you will see the message twice, since it still goes to the normal log handlers, too. ### Response: def getLogger(cls): ...
def _read(self): """ Read a USB HID feature report from the YubiKey. """ request_type = _USB_TYPE_CLASS | _USB_RECIP_INTERFACE | _USB_ENDPOINT_IN value = _REPORT_TYPE_FEATURE << 8 # apparently required for YubiKey 1.3.2, but not 2.2.x recv = self._usb_handle.controlMsg(request_type, ...
Read a USB HID feature report from the YubiKey.
Below is the the instruction that describes the task: ### Input: Read a USB HID feature report from the YubiKey. ### Response: def _read(self): """ Read a USB HID feature report from the YubiKey. """ request_type = _USB_TYPE_CLASS | _USB_RECIP_INTERFACE | _USB_ENDPOINT_IN value = _REPORT_TY...
def setRaster(self, rows, columns): """ Sets the raster for the region, allowing sections to be indexed by row/column """ rows = int(rows) columns = int(columns) if rows <= 0 or columns <= 0: return self self._raster = (rows, columns) return self.getCell(0, 0)
Sets the raster for the region, allowing sections to be indexed by row/column
Below is the the instruction that describes the task: ### Input: Sets the raster for the region, allowing sections to be indexed by row/column ### Response: def setRaster(self, rows, columns): """ Sets the raster for the region, allowing sections to be indexed by row/column """ rows = int(rows) ...
def _GetNumberOfDaysInCentury(self, year): """Retrieves the number of days in a century. Args: year (int): year in the century e.g. 1970. Returns: int: number of (remaining) days in the century. Raises: ValueError: if the year value is out of bounds. """ if year < 0: r...
Retrieves the number of days in a century. Args: year (int): year in the century e.g. 1970. Returns: int: number of (remaining) days in the century. Raises: ValueError: if the year value is out of bounds.
Below is the the instruction that describes the task: ### Input: Retrieves the number of days in a century. Args: year (int): year in the century e.g. 1970. Returns: int: number of (remaining) days in the century. Raises: ValueError: if the year value is out of bounds. ### Response:...
def remove_photo(self, collection_id, photo_id): """ Remove a photo from one of the logged-in user’s collections. Requires the 'write_collections' scope. :param collection_id [string]: The collection’s ID. Required. :param photo_id [string]: The photo’s ID. Required. :re...
Remove a photo from one of the logged-in user’s collections. Requires the 'write_collections' scope. :param collection_id [string]: The collection’s ID. Required. :param photo_id [string]: The photo’s ID. Required. :return: [Tuple]: The Unsplash Collection and Photo
Below is the the instruction that describes the task: ### Input: Remove a photo from one of the logged-in user’s collections. Requires the 'write_collections' scope. :param collection_id [string]: The collection’s ID. Required. :param photo_id [string]: The photo’s ID. Required. :re...
def get_screen_settings(self, screen_id): """Returns the recording settings for a particular screen. in screen_id of type int Screen ID to retrieve recording screen settings for. return record_screen_settings of type :class:`IRecordingScreenSettings` Recording screen se...
Returns the recording settings for a particular screen. in screen_id of type int Screen ID to retrieve recording screen settings for. return record_screen_settings of type :class:`IRecordingScreenSettings` Recording screen settings for the requested screen.
Below is the the instruction that describes the task: ### Input: Returns the recording settings for a particular screen. in screen_id of type int Screen ID to retrieve recording screen settings for. return record_screen_settings of type :class:`IRecordingScreenSettings` Rec...
def _make_sj_out_panel(sj_outD, total_jxn_cov_cutoff=20): """Filter junctions from many sj_out files and make panel. Parameters ---------- sj_outD : dict Dict whose keys are sample names and values are sj_out dataframes total_jxn_cov_cutoff : int If the unique read coverage of a ju...
Filter junctions from many sj_out files and make panel. Parameters ---------- sj_outD : dict Dict whose keys are sample names and values are sj_out dataframes total_jxn_cov_cutoff : int If the unique read coverage of a junction summed over all samples is not greater than or equ...
Below is the the instruction that describes the task: ### Input: Filter junctions from many sj_out files and make panel. Parameters ---------- sj_outD : dict Dict whose keys are sample names and values are sj_out dataframes total_jxn_cov_cutoff : int If the unique read coverage of ...
def list_workers(config, *, filter_by_queues=None): """ Return a list of all available workers. Args: config (Config): Reference to the configuration object from which the settings are retrieved. filter_by_queues (list): Restrict the returned workers to workers that listen to ...
Return a list of all available workers. Args: config (Config): Reference to the configuration object from which the settings are retrieved. filter_by_queues (list): Restrict the returned workers to workers that listen to at least one of the queue names in this list. Ret...
Below is the the instruction that describes the task: ### Input: Return a list of all available workers. Args: config (Config): Reference to the configuration object from which the settings are retrieved. filter_by_queues (list): Restrict the returned workers to workers that listen ...
def get_autoregressive_bias(max_length: int, dtype: str = C.DTYPE_FP32) -> mx.sym.Symbol: """ Returns bias/mask to ensure position i can only attend to positions <i. :param max_length: Sequence length. :param dtype: dtype of bias :return: Bias symbol of shape (1, max_length, max_length). """ ...
Returns bias/mask to ensure position i can only attend to positions <i. :param max_length: Sequence length. :param dtype: dtype of bias :return: Bias symbol of shape (1, max_length, max_length).
Below is the the instruction that describes the task: ### Input: Returns bias/mask to ensure position i can only attend to positions <i. :param max_length: Sequence length. :param dtype: dtype of bias :return: Bias symbol of shape (1, max_length, max_length). ### Response: def get_autoregressive_bias(...
def graph_from_polygon(polygon, network_type='all_private', simplify=True, retain_all=False, truncate_by_edge=False, name='unnamed', timeout=180, memory=None, max_query_area_size=50*1000*50*1000, clean_periphery=True, infrastruc...
Create a networkx graph from OSM data within the spatial boundaries of the passed-in shapely polygon. Parameters ---------- polygon : shapely Polygon or MultiPolygon the shape to get network data within. coordinates should be in units of latitude-longitude degrees. network_type : st...
Below is the the instruction that describes the task: ### Input: Create a networkx graph from OSM data within the spatial boundaries of the passed-in shapely polygon. Parameters ---------- polygon : shapely Polygon or MultiPolygon the shape to get network data within. coordinates should be ...
def __interpret_slices(self, slices): """ Convert python slice objects into a more useful and computable form: - requested_bbox: A bounding box representing the volume requested - steps: the requested stride over x,y,z - channel_slice: A python slice object over the channel dimension Returned ...
Convert python slice objects into a more useful and computable form: - requested_bbox: A bounding box representing the volume requested - steps: the requested stride over x,y,z - channel_slice: A python slice object over the channel dimension Returned as a tuple: (requested_bbox, steps, channel_slice)
Below is the the instruction that describes the task: ### Input: Convert python slice objects into a more useful and computable form: - requested_bbox: A bounding box representing the volume requested - steps: the requested stride over x,y,z - channel_slice: A python slice object over the channel dimen...
def to_wire_dict (self): """Return a simplified transport object for logging and caching. The transport object must contain these attributes: - url_data.valid: bool Indicates if URL is valid - url_data.result: unicode Result string - url_data.warnings: list o...
Return a simplified transport object for logging and caching. The transport object must contain these attributes: - url_data.valid: bool Indicates if URL is valid - url_data.result: unicode Result string - url_data.warnings: list of tuples (tag, warning message) ...
Below is the the instruction that describes the task: ### Input: Return a simplified transport object for logging and caching. The transport object must contain these attributes: - url_data.valid: bool Indicates if URL is valid - url_data.result: unicode Result string ...
def generate_context(name='', argspec='', note='', math=False, collapse=False, img_path='', css_path=CSS_PATH): """ Generate the html_context dictionary for our Sphinx conf file. This is a set of variables to be passed to the Jinja template engine and that are used to control h...
Generate the html_context dictionary for our Sphinx conf file. This is a set of variables to be passed to the Jinja template engine and that are used to control how the webpage is rendered in connection with Sphinx Parameters ---------- name : str Object's name. note : str ...
Below is the the instruction that describes the task: ### Input: Generate the html_context dictionary for our Sphinx conf file. This is a set of variables to be passed to the Jinja template engine and that are used to control how the webpage is rendered in connection with Sphinx Parameters ...
def asVersion(self): """ Convert the version data in this item to a L{twisted.python.versions.Version}. """ return versions.Version(self.package, self.major, self.minor, self.micro)
Convert the version data in this item to a L{twisted.python.versions.Version}.
Below is the the instruction that describes the task: ### Input: Convert the version data in this item to a L{twisted.python.versions.Version}. ### Response: def asVersion(self): """ Convert the version data in this item to a L{twisted.python.versions.Version}. """ r...
def _send_request(self, path, data, method): """ Uses the HTTP transport to query the Route53 API. Runs the response through lxml's parser, before we hand it off for further picking apart by our call-specific parsers. :param str path: The RESTful path to tack on to the :py:attr:...
Uses the HTTP transport to query the Route53 API. Runs the response through lxml's parser, before we hand it off for further picking apart by our call-specific parsers. :param str path: The RESTful path to tack on to the :py:attr:`endpoint`. :param data: The params to send along with th...
Below is the the instruction that describes the task: ### Input: Uses the HTTP transport to query the Route53 API. Runs the response through lxml's parser, before we hand it off for further picking apart by our call-specific parsers. :param str path: The RESTful path to tack on to the :py:a...
def search_and_extract_orfs_matching_protein_database(self, unpack, search_method, maximum_range, thread...
As per aa_db_search() except slightly lower level. Search an input read set (unpack) and then extract the proteins that hit together with their containing nucleotide sequences. Parameters ---------- output_search_file: str path to hmmsearch output table or diamond ba...
Below is the the instruction that describes the task: ### Input: As per aa_db_search() except slightly lower level. Search an input read set (unpack) and then extract the proteins that hit together with their containing nucleotide sequences. Parameters ---------- output_sear...
def add_stream_logger(level=logging.DEBUG, name=None): """ Add a stream logger. This can be used for printing all SDK calls to stdout while working in an interactive session. Note this is a logger for the entire module, which will apply to all environments started in the same session. If you need a ...
Add a stream logger. This can be used for printing all SDK calls to stdout while working in an interactive session. Note this is a logger for the entire module, which will apply to all environments started in the same session. If you need a specific logger pass a ``logfile`` to :func:`~sdk.init` Ar...
Below is the the instruction that describes the task: ### Input: Add a stream logger. This can be used for printing all SDK calls to stdout while working in an interactive session. Note this is a logger for the entire module, which will apply to all environments started in the same session. If you need ...
def authorize(self): """ Use the magic of a unicorn and summon the set-top box to listen to us. / ,.. / ,' '; ,,.__ _,' /'; . :',' ~~~~ '. '~ :' ( ) )::, '. '. .=----=..-~ .;'...
Use the magic of a unicorn and summon the set-top box to listen to us. / ,.. / ,' '; ,,.__ _,' /'; . :',' ~~~~ '. '~ :' ( ) )::, '. '. .=----=..-~ .;' ' ;' :: ':. '" ...
Below is the the instruction that describes the task: ### Input: Use the magic of a unicorn and summon the set-top box to listen to us. / ,.. / ,' '; ,,.__ _,' /'; . :',' ~~~~ '. '~ :' ( ) ...
def intersperse_hs_in_std_res(slice_, hs_dims, res): """Perform the insertions of place-holding rows and cols for insertions.""" for dim, inds in enumerate(slice_.inserted_hs_indices()): if dim not in hs_dims: continue for i in inds: res = np.insert(res, i, np.nan, axis=(...
Perform the insertions of place-holding rows and cols for insertions.
Below is the the instruction that describes the task: ### Input: Perform the insertions of place-holding rows and cols for insertions. ### Response: def intersperse_hs_in_std_res(slice_, hs_dims, res): """Perform the insertions of place-holding rows and cols for insertions.""" for dim, inds in enumerate(sl...
def init(**config): """ Initialize the crypto backend. The backend can be one of two plugins: - 'x509' - Uses x509 certificates. - 'gpg' - Uses GnuPG keys. """ global _implementation global _validate_implementations if config.get('crypto_backend') == 'gpg': _implementa...
Initialize the crypto backend. The backend can be one of two plugins: - 'x509' - Uses x509 certificates. - 'gpg' - Uses GnuPG keys.
Below is the the instruction that describes the task: ### Input: Initialize the crypto backend. The backend can be one of two plugins: - 'x509' - Uses x509 certificates. - 'gpg' - Uses GnuPG keys. ### Response: def init(**config): """ Initialize the crypto backend. The backend can be...
def _config_win32_nameservers(self, nameservers): """Configure a NameServer registry entry.""" # we call str() on nameservers to convert it from unicode to ascii nameservers = str(nameservers) split_char = self._determine_split_char(nameservers) ns_list = nameservers.split(split_...
Configure a NameServer registry entry.
Below is the the instruction that describes the task: ### Input: Configure a NameServer registry entry. ### Response: def _config_win32_nameservers(self, nameservers): """Configure a NameServer registry entry.""" # we call str() on nameservers to convert it from unicode to ascii nameservers...
def properties(obj, type=None, set=None): ''' List properties for given btrfs object. The object can be path of BTRFS device, mount point, or any directories/files inside the BTRFS filesystem. General options: * **type**: Possible types are s[ubvol], f[ilesystem], i[node] and d[evice]. * **for...
List properties for given btrfs object. The object can be path of BTRFS device, mount point, or any directories/files inside the BTRFS filesystem. General options: * **type**: Possible types are s[ubvol], f[ilesystem], i[node] and d[evice]. * **force**: Force overwrite existing filesystem on the disk ...
Below is the the instruction that describes the task: ### Input: List properties for given btrfs object. The object can be path of BTRFS device, mount point, or any directories/files inside the BTRFS filesystem. General options: * **type**: Possible types are s[ubvol], f[ilesystem], i[node] and d[evic...
def _get_agent_grounding(agent): """Convert an agent to the corresponding PyBEL DSL object (to be filled with variants later).""" def _get_id(_agent, key): _id = _agent.db_refs.get(key) if isinstance(_id, list): _id = _id[0] return _id hgnc_id = _get_id(agent, 'HGNC') ...
Convert an agent to the corresponding PyBEL DSL object (to be filled with variants later).
Below is the the instruction that describes the task: ### Input: Convert an agent to the corresponding PyBEL DSL object (to be filled with variants later). ### Response: def _get_agent_grounding(agent): """Convert an agent to the corresponding PyBEL DSL object (to be filled with variants later).""" def _ge...
def _Pcn_crp(x, dsz, Nv, dimN=2, dimC=1): """ Projection onto dictionary update constraint set: support projection and normalisation. The result is cropped to the support of the largest filter in the dictionary. Parameters ---------- x : array_like Input array dsz : tuple ...
Projection onto dictionary update constraint set: support projection and normalisation. The result is cropped to the support of the largest filter in the dictionary. Parameters ---------- x : array_like Input array dsz : tuple Filter support size(s), specified using the same forma...
Below is the the instruction that describes the task: ### Input: Projection onto dictionary update constraint set: support projection and normalisation. The result is cropped to the support of the largest filter in the dictionary. Parameters ---------- x : array_like Input array dsz...
def record(until='escape', suppress=False, trigger_on_release=False): """ Records all keyboard events from all keyboards until the user presses the given hotkey. Then returns the list of events recorded, of type `keyboard.KeyboardEvent`. Pairs well with `play(events)`. Note: this is a blocking ...
Records all keyboard events from all keyboards until the user presses the given hotkey. Then returns the list of events recorded, of type `keyboard.KeyboardEvent`. Pairs well with `play(events)`. Note: this is a blocking function. Note: for more details on the keyboard hook and events see `hook`.
Below is the the instruction that describes the task: ### Input: Records all keyboard events from all keyboards until the user presses the given hotkey. Then returns the list of events recorded, of type `keyboard.KeyboardEvent`. Pairs well with `play(events)`. Note: this is a blocking function. ...
def days(start, end=None): """Iterate over the days between the given datetime_tzs. Args: start: datetime_tz to start from. end: (Optional) Date to end at, if not given the iterator will never terminate. Returns: An iterator which generates datetime_tz objects a day apart. ...
Iterate over the days between the given datetime_tzs. Args: start: datetime_tz to start from. end: (Optional) Date to end at, if not given the iterator will never terminate. Returns: An iterator which generates datetime_tz objects a day apart.
Below is the the instruction that describes the task: ### Input: Iterate over the days between the given datetime_tzs. Args: start: datetime_tz to start from. end: (Optional) Date to end at, if not given the iterator will never terminate. Returns: An iterator which generates d...
def deactivate(self): """ deactivate the environment """ try: self.phase = PHASE.DEACTIVATE self.logger.info("Deactivating environment %s..." % self.namespace) self.directory.rewrite_config = False self.instantiate_features() self._specialize()...
deactivate the environment
Below is the the instruction that describes the task: ### Input: deactivate the environment ### Response: def deactivate(self): """ deactivate the environment """ try: self.phase = PHASE.DEACTIVATE self.logger.info("Deactivating environment %s..." % self.namespace) ...
def getsdm(*args, **kwargs): """ Wrap sdmpy.SDM to get around schema change error """ try: sdm = sdmpy.SDM(*args, **kwargs) except XMLSyntaxError: kwargs['use_xsd'] = False sdm = sdmpy.SDM(*args, **kwargs) return sdm
Wrap sdmpy.SDM to get around schema change error
Below is the the instruction that describes the task: ### Input: Wrap sdmpy.SDM to get around schema change error ### Response: def getsdm(*args, **kwargs): """ Wrap sdmpy.SDM to get around schema change error """ try: sdm = sdmpy.SDM(*args, **kwargs) except XMLSyntaxError: kwargs['use...
def reload(self): """ Reload the configuration from the file. This is in its own function so that it can be called at any time by another class. """ self._conf = configparser.ConfigParser() # Preserve the case of sections and keys. self._conf.optionxform = str ...
Reload the configuration from the file. This is in its own function so that it can be called at any time by another class.
Below is the the instruction that describes the task: ### Input: Reload the configuration from the file. This is in its own function so that it can be called at any time by another class. ### Response: def reload(self): """ Reload the configuration from the file. This is in its own function...
def param_fetch_one(self, name): '''initiate fetch of one parameter''' try: idx = int(name) self.mav.param_request_read_send(self.target_system, self.target_component, "", idx) except Exception: self.mav.param_request_read_send(self.target_system, self.target_...
initiate fetch of one parameter
Below is the the instruction that describes the task: ### Input: initiate fetch of one parameter ### Response: def param_fetch_one(self, name): '''initiate fetch of one parameter''' try: idx = int(name) self.mav.param_request_read_send(self.target_system, self.target_compone...
def get_file_contents(source_path: str) -> str: """ Loads the contents of the source into a string for execution using multiple loading methods to handle cross-platform encoding edge cases. If none of the load methods work, a string is returned that contains an error function response that will be d...
Loads the contents of the source into a string for execution using multiple loading methods to handle cross-platform encoding edge cases. If none of the load methods work, a string is returned that contains an error function response that will be displayed when the step is run alert the user to the erro...
Below is the the instruction that describes the task: ### Input: Loads the contents of the source into a string for execution using multiple loading methods to handle cross-platform encoding edge cases. If none of the load methods work, a string is returned that contains an error function response that ...
def namedb_get_account_tokens(cur, address): """ Get an account's tokens Returns the list of tokens on success Returns None if not found """ sql = 'SELECT DISTINCT type FROM accounts WHERE address = ?;' args = (address,) rows = namedb_query_execute(cur, sql, args) ret = [] for r...
Get an account's tokens Returns the list of tokens on success Returns None if not found
Below is the the instruction that describes the task: ### Input: Get an account's tokens Returns the list of tokens on success Returns None if not found ### Response: def namedb_get_account_tokens(cur, address): """ Get an account's tokens Returns the list of tokens on success Returns None ...
def _backtrace(elt, dom): '''Return a "backtrace" from the given element to the DOM root, in XPath syntax. ''' s = '' while elt != dom: name, parent = elt.nodeName, elt.parentNode if parent is None: break matches = [ c for c in _child_elements(parent) ...
Return a "backtrace" from the given element to the DOM root, in XPath syntax.
Below is the the instruction that describes the task: ### Input: Return a "backtrace" from the given element to the DOM root, in XPath syntax. ### Response: def _backtrace(elt, dom): '''Return a "backtrace" from the given element to the DOM root, in XPath syntax. ''' s = '' while elt != dom...
def write_k_record(self, *args): """ Write a K record:: writer.write_k_record_extensions([ ('FXA', 3), ('SIU', 2), ('ENL', 3), ]) writer.write_k_record(datetime.time(2, 3, 4), ['023', 13, 2]) # -> J030810FXA1112SIU1315ENL # -...
Write a K record:: writer.write_k_record_extensions([ ('FXA', 3), ('SIU', 2), ('ENL', 3), ]) writer.write_k_record(datetime.time(2, 3, 4), ['023', 13, 2]) # -> J030810FXA1112SIU1315ENL # -> K02030402313002 :param time: UTC time of t...
Below is the the instruction that describes the task: ### Input: Write a K record:: writer.write_k_record_extensions([ ('FXA', 3), ('SIU', 2), ('ENL', 3), ]) writer.write_k_record(datetime.time(2, 3, 4), ['023', 13, 2]) # -> J030810FXA1112SIU1315ENL...
def mapper(module, entry_point, modpath='pkg_resources', globber='root', modname='es6', fext=JS_EXT, registry=_utils): """ General mapper Loads components from the micro registry. """ modname_f = modname if callable(modname) else _utils['modname'][modname] return { ...
General mapper Loads components from the micro registry.
Below is the the instruction that describes the task: ### Input: General mapper Loads components from the micro registry. ### Response: def mapper(module, entry_point, modpath='pkg_resources', globber='root', modname='es6', fext=JS_EXT, registry=_utils): """ General mapper L...
def set_secret_key(token): """ Initializes a Authentication and sets it as the new default global authentication. It also performs some checks before saving the authentication. :Example >>> # Expected format for secret key: >>> import payplug >>> payplug.set_secret_key('sk_test_somerandomc...
Initializes a Authentication and sets it as the new default global authentication. It also performs some checks before saving the authentication. :Example >>> # Expected format for secret key: >>> import payplug >>> payplug.set_secret_key('sk_test_somerandomcharacters') :param token: your sec...
Below is the the instruction that describes the task: ### Input: Initializes a Authentication and sets it as the new default global authentication. It also performs some checks before saving the authentication. :Example >>> # Expected format for secret key: >>> import payplug >>> payplug.set_s...
def valuecount(table, field, value, missing=None): """ Count the number of occurrences of `value` under the given field. Returns the absolute count and relative frequency as a pair. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar'], ... ['a', 1], ... ...
Count the number of occurrences of `value` under the given field. Returns the absolute count and relative frequency as a pair. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar'], ... ['a', 1], ... ['b', 2], ... ['b', 7]] >>> etl.valu...
Below is the the instruction that describes the task: ### Input: Count the number of occurrences of `value` under the given field. Returns the absolute count and relative frequency as a pair. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar'], ... ['a', 1], ... ...
def _calc_mask(self): """Computes a boolean mask from the user defined constraints.""" mask = [] for row in self._constraints: mask.append(tuple(x is None for x in row)) return tuple(mask)
Computes a boolean mask from the user defined constraints.
Below is the the instruction that describes the task: ### Input: Computes a boolean mask from the user defined constraints. ### Response: def _calc_mask(self): """Computes a boolean mask from the user defined constraints.""" mask = [] for row in self._constraints: mask.append(tuple(x is None for ...
def _background_gradient(s, cmap='PuBu', low=0, high=0, text_color_threshold=0.408): """ Color background in a range according to the data. """ if (not isinstance(text_color_threshold, (float, int)) or not 0 <= text_color_threshold <= 1): ...
Color background in a range according to the data.
Below is the the instruction that describes the task: ### Input: Color background in a range according to the data. ### Response: def _background_gradient(s, cmap='PuBu', low=0, high=0, text_color_threshold=0.408): """ Color background in a range according to the data. ...
def js_query(self, query: str) -> Awaitable: """Send query to related DOM on browser. :param str query: single string which indicates query type. """ if self.connected: self.js_exec(query, self.__reqid) fut = Future() # type: Future[str] self.__tasks...
Send query to related DOM on browser. :param str query: single string which indicates query type.
Below is the the instruction that describes the task: ### Input: Send query to related DOM on browser. :param str query: single string which indicates query type. ### Response: def js_query(self, query: str) -> Awaitable: """Send query to related DOM on browser. :param str query: single s...
def _ini_format(stream, options): """format options using the INI format""" for optname, optdict, value in options: value = _format_option_value(optdict, value) help_opt = optdict.get("help") if help_opt: help_opt = normalize_text(help_opt, line_len=79, indent="# ") ...
format options using the INI format
Below is the the instruction that describes the task: ### Input: format options using the INI format ### Response: def _ini_format(stream, options): """format options using the INI format""" for optname, optdict, value in options: value = _format_option_value(optdict, value) help_opt = optd...
def sanitize(vpc_config): """ Checks that an instance of VpcConfig has the expected keys and values, removes unexpected keys, and raises ValueErrors if any expectations are violated Args: vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds' Returns: A val...
Checks that an instance of VpcConfig has the expected keys and values, removes unexpected keys, and raises ValueErrors if any expectations are violated Args: vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds' Returns: A valid VpcConfig dict containing only 'Sub...
Below is the the instruction that describes the task: ### Input: Checks that an instance of VpcConfig has the expected keys and values, removes unexpected keys, and raises ValueErrors if any expectations are violated Args: vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupI...
def encode( self, word, max_length=4, var='American', reverse=False, zero_pad=True ): """Return the Soundex code for a word. Parameters ---------- word : str The word to transform max_length : int The length of the code returned (defaults to 4...
Return the Soundex code for a word. Parameters ---------- word : str The word to transform max_length : int The length of the code returned (defaults to 4) var : str The variant of the algorithm to employ (defaults to ``American``): ...
Below is the the instruction that describes the task: ### Input: Return the Soundex code for a word. Parameters ---------- word : str The word to transform max_length : int The length of the code returned (defaults to 4) var : str The vari...
def make_keys_safe(dct): """Modify the keys in |dct| to be valid attribute names.""" result = {} for key, val in dct.items(): key = key.replace('-', '_') if key in keyword.kwlist: key = key + '_' result[key] = val return result
Modify the keys in |dct| to be valid attribute names.
Below is the the instruction that describes the task: ### Input: Modify the keys in |dct| to be valid attribute names. ### Response: def make_keys_safe(dct): """Modify the keys in |dct| to be valid attribute names.""" result = {} for key, val in dct.items(): key = key.replace('-', '_') ...
def get_group_index(labels, shape, sort, xnull): """ For the particular label_list, gets the offsets into the hypothetical list representing the totally ordered cartesian product of all possible label combinations, *as long as* this space fits within int64 bounds; otherwise, though group indices ide...
For the particular label_list, gets the offsets into the hypothetical list representing the totally ordered cartesian product of all possible label combinations, *as long as* this space fits within int64 bounds; otherwise, though group indices identify unique combinations of labels, they cannot be decon...
Below is the the instruction that describes the task: ### Input: For the particular label_list, gets the offsets into the hypothetical list representing the totally ordered cartesian product of all possible label combinations, *as long as* this space fits within int64 bounds; otherwise, though group ind...
def get_search_index_for(catalog): """Returns the search index to query """ searchable_text_index = "SearchableText" listing_searchable_text_index = "listing_searchable_text" if catalog == CATALOG_ANALYSIS_REQUEST_LISTING: tool = api.get_tool(catalog) indexes = tool.indexes() ...
Returns the search index to query
Below is the the instruction that describes the task: ### Input: Returns the search index to query ### Response: def get_search_index_for(catalog): """Returns the search index to query """ searchable_text_index = "SearchableText" listing_searchable_text_index = "listing_searchable_text" if cat...