code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def exists_using_casper(self, filename): """Check for the existence of a package file. Unlike other DistributionPoint types, JDS and CDP types have no documented interface for checking whether the server and its children have a complete copy of a file. The best we can do is chec...
Check for the existence of a package file. Unlike other DistributionPoint types, JDS and CDP types have no documented interface for checking whether the server and its children have a complete copy of a file. The best we can do is check for an object using the API /packages URL--JSS.Pac...
Below is the the instruction that describes the task: ### Input: Check for the existence of a package file. Unlike other DistributionPoint types, JDS and CDP types have no documented interface for checking whether the server and its children have a complete copy of a file. The best we can d...
def bundle_changed(self, event): # type: (BundleEvent) -> None """ A bundle event has been triggered :param event: The bundle event """ kind = event.get_kind() bundle = event.get_bundle() if kind == BundleEvent.STOPPING_PRECLEAN: # A bundle i...
A bundle event has been triggered :param event: The bundle event
Below is the the instruction that describes the task: ### Input: A bundle event has been triggered :param event: The bundle event ### Response: def bundle_changed(self, event): # type: (BundleEvent) -> None """ A bundle event has been triggered :param event: The bundle eve...
def timestr_to_seconds( x: Union[dt.date, str], *, inverse: bool = False, mod24: bool = False ) -> int: """ Given an HH:MM:SS time string ``x``, return the number of seconds past midnight that it represents. In keeping with GTFS standards, the hours entry may be greater than 23. If ``mod24``...
Given an HH:MM:SS time string ``x``, return the number of seconds past midnight that it represents. In keeping with GTFS standards, the hours entry may be greater than 23. If ``mod24``, then return the number of seconds modulo ``24*3600``. If ``inverse``, then do the inverse operation. In this c...
Below is the the instruction that describes the task: ### Input: Given an HH:MM:SS time string ``x``, return the number of seconds past midnight that it represents. In keeping with GTFS standards, the hours entry may be greater than 23. If ``mod24``, then return the number of seconds modulo ``24*360...
def build_job_configs(self, args): """Hook to build job configurations """ job_configs = {} components = Component.build_from_yamlfile(args['comp']) NAME_FACTORY.update_base_dict(args['data']) if self._comp_dict is None or self._comp_dict_file != args['library']: ...
Hook to build job configurations
Below is the the instruction that describes the task: ### Input: Hook to build job configurations ### Response: def build_job_configs(self, args): """Hook to build job configurations """ job_configs = {} components = Component.build_from_yamlfile(args['comp']) NAME_FACTORY....
def take(list_, index_list): """ Selects a subset of a list based on a list of indices. This is similar to np.take, but pure python. Args: list_ (list): some indexable object index_list (list, slice, int): some indexing object Returns: list or scalar: subset of the list ...
Selects a subset of a list based on a list of indices. This is similar to np.take, but pure python. Args: list_ (list): some indexable object index_list (list, slice, int): some indexing object Returns: list or scalar: subset of the list CommandLine: python -m utool.ut...
Below is the the instruction that describes the task: ### Input: Selects a subset of a list based on a list of indices. This is similar to np.take, but pure python. Args: list_ (list): some indexable object index_list (list, slice, int): some indexing object Returns: list or sc...
def validate(cls, mapper_spec): """Inherit docs.""" super(RawDatastoreInputReader, cls).validate(mapper_spec) params = _get_params(mapper_spec) entity_kind = params[cls.ENTITY_KIND_PARAM] if "." in entity_kind: logging.warning( ". detected in entity kind %s specified for reader %s." ...
Inherit docs.
Below is the the instruction that describes the task: ### Input: Inherit docs. ### Response: def validate(cls, mapper_spec): """Inherit docs.""" super(RawDatastoreInputReader, cls).validate(mapper_spec) params = _get_params(mapper_spec) entity_kind = params[cls.ENTITY_KIND_PARAM] if "." in enti...
def get_input(input_func, input_str): """ Get input from the user given an input function and an input string """ val = input_func("Please enter your {0}: ".format(input_str)) while not val or not len(val.strip()): val = input_func("You didn't enter a valid {0}, please try again: ".format(in...
Get input from the user given an input function and an input string
Below is the the instruction that describes the task: ### Input: Get input from the user given an input function and an input string ### Response: def get_input(input_func, input_str): """ Get input from the user given an input function and an input string """ val = input_func("Please enter your {0...
def attowiki_distro_path(): """return the absolute complete path where attowiki is located .. todo:: use pkg_resources ? """ attowiki_path = os.path.abspath(__file__) if attowiki_path[-1] != '/': attowiki_path = attowiki_path[:attowiki_path.rfind('/')] else: attowiki_path = atto...
return the absolute complete path where attowiki is located .. todo:: use pkg_resources ?
Below is the the instruction that describes the task: ### Input: return the absolute complete path where attowiki is located .. todo:: use pkg_resources ? ### Response: def attowiki_distro_path(): """return the absolute complete path where attowiki is located .. todo:: use pkg_resources ? """ ...
def _is_utf_8(txt): """ Check a string is utf-8 encoded :param bytes txt: utf-8 string :return: Whether the string\ is utf-8 encoded or not :rtype: bool """ assert isinstance(txt, six.binary_type) try: _ = six.text_type(txt, 'utf-8') except (TypeError, UnicodeEncodeErro...
Check a string is utf-8 encoded :param bytes txt: utf-8 string :return: Whether the string\ is utf-8 encoded or not :rtype: bool
Below is the the instruction that describes the task: ### Input: Check a string is utf-8 encoded :param bytes txt: utf-8 string :return: Whether the string\ is utf-8 encoded or not :rtype: bool ### Response: def _is_utf_8(txt): """ Check a string is utf-8 encoded :param bytes txt: utf...
def reply_webapi(self, text, attachments=None, as_user=True, in_thread=None): """ Send a reply to the sender using Web API (This function supports formatted message when using a bot integration) If the message was send in a thread, answer in a thread per default...
Send a reply to the sender using Web API (This function supports formatted message when using a bot integration) If the message was send in a thread, answer in a thread per default.
Below is the the instruction that describes the task: ### Input: Send a reply to the sender using Web API (This function supports formatted message when using a bot integration) If the message was send in a thread, answer in a thread per default. ### Response: def reply_webapi...
def _dump_cml_molecule(f, molecule): """Dump a single molecule to a CML file Arguments: | ``f`` -- a file-like object | ``molecule`` -- a Molecule instance """ extra = getattr(molecule, "extra", {}) attr_str = " ".join("%s='%s'" % (key, value) for key, value in extra.items())...
Dump a single molecule to a CML file Arguments: | ``f`` -- a file-like object | ``molecule`` -- a Molecule instance
Below is the the instruction that describes the task: ### Input: Dump a single molecule to a CML file Arguments: | ``f`` -- a file-like object | ``molecule`` -- a Molecule instance ### Response: def _dump_cml_molecule(f, molecule): """Dump a single molecule to a CML file Arg...
def appt_exists(self, complex: str, house: str, appt: str) -> bool: """ Shortcut to check if appt exists in our database. """ try: self.check_appt(complex, house, appt) except exceptions.RumetrApptNotFound: return False return True
Shortcut to check if appt exists in our database.
Below is the the instruction that describes the task: ### Input: Shortcut to check if appt exists in our database. ### Response: def appt_exists(self, complex: str, house: str, appt: str) -> bool: """ Shortcut to check if appt exists in our database. """ try: self.check_...
def _kill_worker_threads(self): """This function coerces the consumer/worker threads to kill themselves. When called by the queuing thread, one death token will be placed on the queue for each thread. Each worker thread is always looking for the death token. When it encounters it, it ...
This function coerces the consumer/worker threads to kill themselves. When called by the queuing thread, one death token will be placed on the queue for each thread. Each worker thread is always looking for the death token. When it encounters it, it immediately runs to completion with...
Below is the the instruction that describes the task: ### Input: This function coerces the consumer/worker threads to kill themselves. When called by the queuing thread, one death token will be placed on the queue for each thread. Each worker thread is always looking for the death token. ...
def measure_power(self, hz, duration, tag, offset=30): """Measure power consumption of the attached device. Because it takes some time for the device to calm down after the usb connection is cut, an offset is set for each measurement. The default is 30s. The total time taken to measure ...
Measure power consumption of the attached device. Because it takes some time for the device to calm down after the usb connection is cut, an offset is set for each measurement. The default is 30s. The total time taken to measure will be (duration + offset). Args: hz: Number...
Below is the the instruction that describes the task: ### Input: Measure power consumption of the attached device. Because it takes some time for the device to calm down after the usb connection is cut, an offset is set for each measurement. The default is 30s. The total time taken to measu...
def has_pkgs_signed_with(self, allowed_keys): """ Check signature of packages installed in image. Raises exception when * rpm binary is not installed in image * parsing of rpm fails * there are packages in image that are not signed with one of allowed keys :para...
Check signature of packages installed in image. Raises exception when * rpm binary is not installed in image * parsing of rpm fails * there are packages in image that are not signed with one of allowed keys :param allowed_keys: list of allowed keys :return: bool
Below is the the instruction that describes the task: ### Input: Check signature of packages installed in image. Raises exception when * rpm binary is not installed in image * parsing of rpm fails * there are packages in image that are not signed with one of allowed keys :p...
def check_permissions(self, request): """ Check if the request should be permitted. Raises an appropriate exception if the request is not permitted. """ permissions = [permission() for permission in self.permission_classes] for permission in permissions: if no...
Check if the request should be permitted. Raises an appropriate exception if the request is not permitted.
Below is the the instruction that describes the task: ### Input: Check if the request should be permitted. Raises an appropriate exception if the request is not permitted. ### Response: def check_permissions(self, request): """ Check if the request should be permitted. Raises an app...
def encrypt_assertion(self, statement, enc_key, template, key_type='des-192', node_xpath=None): """ Will encrypt an assertion :param statement: A XML document that contains the assertion to encrypt :param enc_key: File name of a file containing the encryption key :param template...
Will encrypt an assertion :param statement: A XML document that contains the assertion to encrypt :param enc_key: File name of a file containing the encryption key :param template: A template for the encryption part to be added. :param key_type: The type of session key to use. :...
Below is the the instruction that describes the task: ### Input: Will encrypt an assertion :param statement: A XML document that contains the assertion to encrypt :param enc_key: File name of a file containing the encryption key :param template: A template for the encryption part to be adde...
def state_in_ec(self, ec_index): '''Get the state of the component in an execution context. @param ec_index The index of the execution context to check the state in. This index is into the total array of contexts, that is both owned and participating cont...
Get the state of the component in an execution context. @param ec_index The index of the execution context to check the state in. This index is into the total array of contexts, that is both owned and participating contexts. If the value o...
Below is the the instruction that describes the task: ### Input: Get the state of the component in an execution context. @param ec_index The index of the execution context to check the state in. This index is into the total array of contexts, that is both own...
def dynamics_from_bundle_bs(b, times, compute=None, return_roche_euler=False, **kwargs): """ Parse parameters in the bundle and call :func:`dynamics`. See :func:`dynamics` for more detailed information. NOTE: you must either provide compute (the label) OR all relevant options as kwargs (ltte) ...
Parse parameters in the bundle and call :func:`dynamics`. See :func:`dynamics` for more detailed information. NOTE: you must either provide compute (the label) OR all relevant options as kwargs (ltte) Args: b: (Bundle) the bundle with a set hierarchy times: (list or array) times at wh...
Below is the the instruction that describes the task: ### Input: Parse parameters in the bundle and call :func:`dynamics`. See :func:`dynamics` for more detailed information. NOTE: you must either provide compute (the label) OR all relevant options as kwargs (ltte) Args: b: (Bundle) the b...
def parse_application_name(setup_filename): """Parse a setup.py file for the name. Returns: name, or None """ with open(setup_filename, 'rt') as setup_file: fst = RedBaron(setup_file.read()) for node in fst: if ( no...
Parse a setup.py file for the name. Returns: name, or None
Below is the the instruction that describes the task: ### Input: Parse a setup.py file for the name. Returns: name, or None ### Response: def parse_application_name(setup_filename): """Parse a setup.py file for the name. Returns: name, or None """ w...
def open_ext_pack_file(self, path): """Attempts to open an extension pack file in preparation for installation. in path of type str The path of the extension pack tarball. This can optionally be followed by a "::SHA-256=hex-digit" of the tarball. return file_p o...
Attempts to open an extension pack file in preparation for installation. in path of type str The path of the extension pack tarball. This can optionally be followed by a "::SHA-256=hex-digit" of the tarball. return file_p of type :class:`IExtPackFile` The in...
Below is the the instruction that describes the task: ### Input: Attempts to open an extension pack file in preparation for installation. in path of type str The path of the extension pack tarball. This can optionally be followed by a "::SHA-256=hex-digit" of the tarball. ...
def getlist(self, key, default=[]): """ Returns: The list of values for <key> if <key> is in the dictionary, else <default>. If <default> is not provided, an empty list is returned. """ if key in self: return [node.value for node in self._map[key]] ret...
Returns: The list of values for <key> if <key> is in the dictionary, else <default>. If <default> is not provided, an empty list is returned.
Below is the the instruction that describes the task: ### Input: Returns: The list of values for <key> if <key> is in the dictionary, else <default>. If <default> is not provided, an empty list is returned. ### Response: def getlist(self, key, default=[]): """ Returns: The list of v...
def sort(expr, field = None, keytype=None, ascending=True): """ Sorts the vector. If the field parameter is provided then the sort operators on a vector of structs where the sort key is the field of the struct. Args: expr (WeldObject) field (Int) """ weld_obj = WeldObject(en...
Sorts the vector. If the field parameter is provided then the sort operators on a vector of structs where the sort key is the field of the struct. Args: expr (WeldObject) field (Int)
Below is the the instruction that describes the task: ### Input: Sorts the vector. If the field parameter is provided then the sort operators on a vector of structs where the sort key is the field of the struct. Args: expr (WeldObject) field (Int) ### Response: def sort(expr, field = N...
def list_subdomains(self, limit=None, offset=None): """ Returns a list of all subdomains for this domain. """ return self.manager.list_subdomains(self, limit=limit, offset=offset)
Returns a list of all subdomains for this domain.
Below is the the instruction that describes the task: ### Input: Returns a list of all subdomains for this domain. ### Response: def list_subdomains(self, limit=None, offset=None): """ Returns a list of all subdomains for this domain. """ return self.manager.list_subdomains(self, li...
def from_str(cls, coordinate): """Build a TikZCoordinate object from a string.""" m = cls._coordinate_str_regex.match(coordinate) if m is None: raise ValueError('invalid coordinate string') if m.group(1) == '++': relative = True else: relati...
Build a TikZCoordinate object from a string.
Below is the the instruction that describes the task: ### Input: Build a TikZCoordinate object from a string. ### Response: def from_str(cls, coordinate): """Build a TikZCoordinate object from a string.""" m = cls._coordinate_str_regex.match(coordinate) if m is None: raise Val...
def saveData(self, dataOutputFile, categoriesOutputFile): """ Save the processed data and the associated category mapping. @param dataOutputFile (str) Location to save data @param categoriesOutputFile (str) Location to save category map @return (str) Path to the saved...
Save the processed data and the associated category mapping. @param dataOutputFile (str) Location to save data @param categoriesOutputFile (str) Location to save category map @return (str) Path to the saved data file iff saveData() is s...
Below is the the instruction that describes the task: ### Input: Save the processed data and the associated category mapping. @param dataOutputFile (str) Location to save data @param categoriesOutputFile (str) Location to save category map @return (str) Path to the saved ...
def _cram_to_fastq_region(cram_file, work_dir, base_name, region, data): """Convert CRAM to fastq in a specified region. """ ref_file = tz.get_in(["reference", "fasta", "base"], data) resources = config_utils.get_resources("bamtofastq", data["config"]) cores = tz.get_in(["config", "algorithm", "num_...
Convert CRAM to fastq in a specified region.
Below is the the instruction that describes the task: ### Input: Convert CRAM to fastq in a specified region. ### Response: def _cram_to_fastq_region(cram_file, work_dir, base_name, region, data): """Convert CRAM to fastq in a specified region. """ ref_file = tz.get_in(["reference", "fasta", "base"], d...
def ladders(session, game_id): """Get a list of ladder IDs.""" if isinstance(game_id, str): game_id = lookup_game_id(game_id) lobbies = get_lobbies(session, game_id) ladder_ids = set() for lobby in lobbies: ladder_ids |= set(lobby['ladders']) return list(ladder_ids)
Get a list of ladder IDs.
Below is the the instruction that describes the task: ### Input: Get a list of ladder IDs. ### Response: def ladders(session, game_id): """Get a list of ladder IDs.""" if isinstance(game_id, str): game_id = lookup_game_id(game_id) lobbies = get_lobbies(session, game_id) ladder_ids = set() ...
def ProcessAllReadyRequests(self): """Processes all requests that are due to run. Returns: The number of processed requests. """ request_dict = data_store.REL_DB.ReadFlowRequestsReadyForProcessing( self.rdf_flow.client_id, self.rdf_flow.flow_id, next_needed_request=self.rd...
Processes all requests that are due to run. Returns: The number of processed requests.
Below is the the instruction that describes the task: ### Input: Processes all requests that are due to run. Returns: The number of processed requests. ### Response: def ProcessAllReadyRequests(self): """Processes all requests that are due to run. Returns: The number of processed requests...
def register_column(self, column, expr, deltas=None, checkpoints=None, odo_kwargs=None): """Explicitly map a single bound column to a collection of blaze expressions. The expressions n...
Explicitly map a single bound column to a collection of blaze expressions. The expressions need to have ``timestamp`` and ``as_of`` columns. Parameters ---------- column : BoundColumn The pipeline dataset to map to the given expressions. expr : Expr ...
Below is the the instruction that describes the task: ### Input: Explicitly map a single bound column to a collection of blaze expressions. The expressions need to have ``timestamp`` and ``as_of`` columns. Parameters ---------- column : BoundColumn The pipeline d...
def validator( *fields: str, pre: bool = False, whole: bool = False, always: bool = False, check_fields: bool = True ) -> Callable[[AnyCallable], classmethod]: """ Decorate methods on the class indicating that they should be used to validate fields :param fields: which field(s) the method should be call...
Decorate methods on the class indicating that they should be used to validate fields :param fields: which field(s) the method should be called on :param pre: whether or not this validator should be called before the standard validators (else after) :param whole: for complex objects (sets, lists etc.) whethe...
Below is the the instruction that describes the task: ### Input: Decorate methods on the class indicating that they should be used to validate fields :param fields: which field(s) the method should be called on :param pre: whether or not this validator should be called before the standard validators (else a...
def write_yara(self, output_file): """ Write out yara signatures to a file. """ fout = open(output_file, 'wb') fout.write('\n') for iocid in self.yara_signatures: signature = self.yara_signatures[iocid] fout.write(signature) fout.write...
Write out yara signatures to a file.
Below is the the instruction that describes the task: ### Input: Write out yara signatures to a file. ### Response: def write_yara(self, output_file): """ Write out yara signatures to a file. """ fout = open(output_file, 'wb') fout.write('\n') for iocid in self.yara...
def ip_rtm_config_route_static_route_oif_vrf_static_route_oif_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def") rtm_config = ET.SubElement(ip, "rtm-config", xmlns="urn:b...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def ip_rtm_config_route_static_route_oif_vrf_static_route_oif_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ip = ET.SubElement(config, "ip", xmlns="urn...
def create_archaius(self): """Create S3 bucket for Archaius.""" utils.banner("Creating S3") s3.init_properties(env=self.env, app=self.app)
Create S3 bucket for Archaius.
Below is the the instruction that describes the task: ### Input: Create S3 bucket for Archaius. ### Response: def create_archaius(self): """Create S3 bucket for Archaius.""" utils.banner("Creating S3") s3.init_properties(env=self.env, app=self.app)
def copy(self): """Create a copy of the current one.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.identifiers = object.__new__(self.identifiers.__class__) rv.identifiers.__dict__.update(self.identifiers.__dict__) return rv
Create a copy of the current one.
Below is the the instruction that describes the task: ### Input: Create a copy of the current one. ### Response: def copy(self): """Create a copy of the current one.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.identifiers = object.__new__(self.identif...
def split_action_id (id): """ Splits an id in the toolset and specific rule parts. E.g. 'gcc.compile.c++' returns ('gcc', 'compile.c++') """ assert isinstance(id, basestring) split = id.split ('.', 1) toolset = split [0] name = '' if len (split) > 1: name = split [1] retu...
Splits an id in the toolset and specific rule parts. E.g. 'gcc.compile.c++' returns ('gcc', 'compile.c++')
Below is the the instruction that describes the task: ### Input: Splits an id in the toolset and specific rule parts. E.g. 'gcc.compile.c++' returns ('gcc', 'compile.c++') ### Response: def split_action_id (id): """ Splits an id in the toolset and specific rule parts. E.g. 'gcc.compile.c++' ret...
def routeevent(self, path, routinemethod, container = None, host = None, vhost = None, method = [b'GET', b'HEAD']): ''' Route specified path to a routine factory :param path: path to match, can be a regular expression :param routinemethod: factory function routinemetho...
Route specified path to a routine factory :param path: path to match, can be a regular expression :param routinemethod: factory function routinemethod(event), event is the HttpRequestEvent :param container: routine container. If None, default to self for bound method,...
Below is the the instruction that describes the task: ### Input: Route specified path to a routine factory :param path: path to match, can be a regular expression :param routinemethod: factory function routinemethod(event), event is the HttpRequestEvent :param con...
def saveVarsInMat(filename, varNamesStr, outOf=None, **opts): """Hacky convinience function to dump a couple of python variables in a .mat file. See `awmstools.saveVars`. """ from mlabwrap import mlab filename, varnames, outOf = __saveVarsHelper( filename, varNamesStr, outOf, '.mat', **op...
Hacky convinience function to dump a couple of python variables in a .mat file. See `awmstools.saveVars`.
Below is the the instruction that describes the task: ### Input: Hacky convinience function to dump a couple of python variables in a .mat file. See `awmstools.saveVars`. ### Response: def saveVarsInMat(filename, varNamesStr, outOf=None, **opts): """Hacky convinience function to dump a couple of python ...
def LoadImage(filename): '''return an image from the images/ directory''' app_dir = os.path.dirname(os.path.realpath(__file__)) path = os.path.join(app_dir, 'images', filename) return Tkinter.PhotoImage(file=path)
return an image from the images/ directory
Below is the the instruction that describes the task: ### Input: return an image from the images/ directory ### Response: def LoadImage(filename): '''return an image from the images/ directory''' app_dir = os.path.dirname(os.path.realpath(__file__)) path = os.path.join(app_dir, 'images', filename) ...
def from_xml(cls, xml): """ Returns a new Text from the given XML string. """ s = parse_string(xml) return Sentence(s.split("\n")[0], token=s.tags, language=s.language)
Returns a new Text from the given XML string.
Below is the the instruction that describes the task: ### Input: Returns a new Text from the given XML string. ### Response: def from_xml(cls, xml): """ Returns a new Text from the given XML string. """ s = parse_string(xml) return Sentence(s.split("\n")[0], token=s.tags, language=s...
def rule_command_cmdlist_interface_h_interface_ge_leaf_interface_gigabitethernet_leaf(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa") index_key = ET.SubElement(rule, "index") ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def rule_command_cmdlist_interface_h_interface_ge_leaf_interface_gigabitethernet_leaf(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") rule = ET.SubElement(con...
def transformed(self, t): """ Transforms an m-dimensional Rect using t, an nxn matrix that can transform vectors in the form: [x, y, z, …, 1]. The Rect is padded to n dimensions. """ assert t.shape[0] == t.shape[1] extra_dimensions = t.shape[0] - self.dimensions -...
Transforms an m-dimensional Rect using t, an nxn matrix that can transform vectors in the form: [x, y, z, …, 1]. The Rect is padded to n dimensions.
Below is the the instruction that describes the task: ### Input: Transforms an m-dimensional Rect using t, an nxn matrix that can transform vectors in the form: [x, y, z, …, 1]. The Rect is padded to n dimensions. ### Response: def transformed(self, t): """ Transforms an m-dimension...
def _expand(self, normalization, csphase, **kwargs): """Expand the grid into real spherical harmonics.""" if normalization.lower() == '4pi': norm = 1 elif normalization.lower() == 'schmidt': norm = 2 elif normalization.lower() == 'unnorm': norm = 3 ...
Expand the grid into real spherical harmonics.
Below is the the instruction that describes the task: ### Input: Expand the grid into real spherical harmonics. ### Response: def _expand(self, normalization, csphase, **kwargs): """Expand the grid into real spherical harmonics.""" if normalization.lower() == '4pi': norm = 1 eli...
def set_members(self, name, members, mode=None): """Configures the array of member interfaces for the Port-Channel Args: name(str): The Port-Channel interface name to configure the member interfaces members(list): The list of Ethernet interfaces that should be ...
Configures the array of member interfaces for the Port-Channel Args: name(str): The Port-Channel interface name to configure the member interfaces members(list): The list of Ethernet interfaces that should be member interfaces mode(str): The...
Below is the the instruction that describes the task: ### Input: Configures the array of member interfaces for the Port-Channel Args: name(str): The Port-Channel interface name to configure the member interfaces members(list): The list of Ethernet interfaces that sh...
def list(self, args, unknown): """List all addons that can be launched :param args: arguments from the launch parser :type args: Namespace :param unknown: list of unknown arguments :type unknown: list :returns: None :rtype: None :raises: None """ ...
List all addons that can be launched :param args: arguments from the launch parser :type args: Namespace :param unknown: list of unknown arguments :type unknown: list :returns: None :rtype: None :raises: None
Below is the the instruction that describes the task: ### Input: List all addons that can be launched :param args: arguments from the launch parser :type args: Namespace :param unknown: list of unknown arguments :type unknown: list :returns: None :rtype: None ...
def getElementsByClassName(self, className, root='root', useIndex=True): ''' getElementsByClassName - Searches and returns all elements containing a given class name. @param className <str> - A one-word class name @param root <AdvancedTag/'root'> - Sea...
getElementsByClassName - Searches and returns all elements containing a given class name. @param className <str> - A one-word class name @param root <AdvancedTag/'root'> - Search starting at a specific node, if provided. if string 'root', the root of the parsed tree will ...
Below is the the instruction that describes the task: ### Input: getElementsByClassName - Searches and returns all elements containing a given class name. @param className <str> - A one-word class name @param root <AdvancedTag/'root'> - Search starting at a specific n...
def copy_from(self, other): """Copy properties from another ChemicalEntity """ # Need to copy all attributes, fields, relations self.__attributes__ = {k: v.copy() for k, v in other.__attributes__.items()} self.__fields__ = {k: v.copy() for k, v in other.__fields__.items(...
Copy properties from another ChemicalEntity
Below is the the instruction that describes the task: ### Input: Copy properties from another ChemicalEntity ### Response: def copy_from(self, other): """Copy properties from another ChemicalEntity """ # Need to copy all attributes, fields, relations self.__attributes__ = {...
def max_normal_germline_depth(in_file, params, somatic_info): """Calculate threshold for excluding potential heterozygotes based on normal depth. """ bcf_in = pysam.VariantFile(in_file) depths = [] for rec in bcf_in: stats = _is_possible_loh(rec, bcf_in, params, somatic_info) if tz.g...
Calculate threshold for excluding potential heterozygotes based on normal depth.
Below is the the instruction that describes the task: ### Input: Calculate threshold for excluding potential heterozygotes based on normal depth. ### Response: def max_normal_germline_depth(in_file, params, somatic_info): """Calculate threshold for excluding potential heterozygotes based on normal depth. "...
def import_image_from_image(self, image, repository=None, tag=None, changes=None): """ Like :py:meth:`~docker.api.image.ImageApiMixin.import_image`, but only supports importing from another image, like the ``FROM`` Dockerfile parameter. Args: ...
Like :py:meth:`~docker.api.image.ImageApiMixin.import_image`, but only supports importing from another image, like the ``FROM`` Dockerfile parameter. Args: image (str): Image name to import from repository (str): The repository to create tag (str): The tag to...
Below is the the instruction that describes the task: ### Input: Like :py:meth:`~docker.api.image.ImageApiMixin.import_image`, but only supports importing from another image, like the ``FROM`` Dockerfile parameter. Args: image (str): Image name to import from reposit...
async def parseResults(self, api_data): """ See CoverSource.parseResults. """ results = [] # get xml results list xml_text = api_data.decode("utf-8") xml_root = xml.etree.ElementTree.fromstring(xml_text) status = xml_root.get("status") if status != "ok": raise Exception("Unexpected La...
See CoverSource.parseResults.
Below is the the instruction that describes the task: ### Input: See CoverSource.parseResults. ### Response: async def parseResults(self, api_data): """ See CoverSource.parseResults. """ results = [] # get xml results list xml_text = api_data.decode("utf-8") xml_root = xml.etree.ElementTree.fr...
def iterfields(klass): """Iterate over the input class members and yield its TypedFields. Args: klass: A class (usually an Entity subclass). Yields: (class attribute name, TypedField instance) tuples. """ is_field = lambda x: isinstance(x, TypedField) for name, field in inspec...
Iterate over the input class members and yield its TypedFields. Args: klass: A class (usually an Entity subclass). Yields: (class attribute name, TypedField instance) tuples.
Below is the the instruction that describes the task: ### Input: Iterate over the input class members and yield its TypedFields. Args: klass: A class (usually an Entity subclass). Yields: (class attribute name, TypedField instance) tuples. ### Response: def iterfields(klass): """Itera...
def subject(self) -> Optional[UnstructuredHeader]: """The ``Subject`` header.""" try: return cast(UnstructuredHeader, self[b'subject'][0]) except (KeyError, IndexError): return None
The ``Subject`` header.
Below is the the instruction that describes the task: ### Input: The ``Subject`` header. ### Response: def subject(self) -> Optional[UnstructuredHeader]: """The ``Subject`` header.""" try: return cast(UnstructuredHeader, self[b'subject'][0]) except (KeyError, IndexError): ...
def typestring(obj): """Make a string for the object's type Parameters ---------- obj : obj Python object. Returns ------- `str` String representation of the object's type. This is the type's importable namespace. Examples -------- >>> import docutils.n...
Make a string for the object's type Parameters ---------- obj : obj Python object. Returns ------- `str` String representation of the object's type. This is the type's importable namespace. Examples -------- >>> import docutils.nodes >>> para = docutils...
Below is the the instruction that describes the task: ### Input: Make a string for the object's type Parameters ---------- obj : obj Python object. Returns ------- `str` String representation of the object's type. This is the type's importable namespace. Exampl...
def clone(self): """Create a complete copy of the stream. :returns: A new MaterialStream object.""" result = copy.copy(self) result._compound_mfrs = copy.deepcopy(self._compound_mfrs) return result
Create a complete copy of the stream. :returns: A new MaterialStream object.
Below is the the instruction that describes the task: ### Input: Create a complete copy of the stream. :returns: A new MaterialStream object. ### Response: def clone(self): """Create a complete copy of the stream. :returns: A new MaterialStream object.""" result = copy.copy(self)...
def nmtoken_from_string(text): """ Returns a Nmtoken from a string. It is useful to produce XHTML valid values for the 'name' attribute of an anchor. CAUTION: the function is surjective: 2 different texts might lead to the same result. This is improbable on a single page. Nmtoken is the ty...
Returns a Nmtoken from a string. It is useful to produce XHTML valid values for the 'name' attribute of an anchor. CAUTION: the function is surjective: 2 different texts might lead to the same result. This is improbable on a single page. Nmtoken is the type that is a mixture of characters supporte...
Below is the the instruction that describes the task: ### Input: Returns a Nmtoken from a string. It is useful to produce XHTML valid values for the 'name' attribute of an anchor. CAUTION: the function is surjective: 2 different texts might lead to the same result. This is improbable on a single pa...
def p_statement_break(p): '''statement : BREAK SEMI | BREAK expr SEMI''' if len(p) == 3: p[0] = ast.Break(None, lineno=p.lineno(1)) else: p[0] = ast.Break(p[2], lineno=p.lineno(1))
statement : BREAK SEMI | BREAK expr SEMI
Below is the the instruction that describes the task: ### Input: statement : BREAK SEMI | BREAK expr SEMI ### Response: def p_statement_break(p): '''statement : BREAK SEMI | BREAK expr SEMI''' if len(p) == 3: p[0] = ast.Break(None, lineno=p.lineno(1)) else: ...
def path(self): """str: URL path for the model's APIs.""" return "/projects/%s/datasets/%s/models/%s" % ( self._proto.project_id, self._proto.dataset_id, self._proto.model_id, )
str: URL path for the model's APIs.
Below is the the instruction that describes the task: ### Input: str: URL path for the model's APIs. ### Response: def path(self): """str: URL path for the model's APIs.""" return "/projects/%s/datasets/%s/models/%s" % ( self._proto.project_id, self._proto.dataset_id, ...
def split_into(max_num_chunks, list_to_chunk): """ Yields the list with a max total size of max_num_chunks """ max_chunk_size = math.ceil(len(list_to_chunk) / max_num_chunks) return chunks_of(max_chunk_size, list_to_chunk)
Yields the list with a max total size of max_num_chunks
Below is the the instruction that describes the task: ### Input: Yields the list with a max total size of max_num_chunks ### Response: def split_into(max_num_chunks, list_to_chunk): """ Yields the list with a max total size of max_num_chunks """ max_chunk_size = math.ceil(len(list_to_chunk) / max_n...
def ranking_metric_tensor(exprs, method, permutation_num, pos, neg, classes, ascending, rs=np.random.RandomState()): """Build shuffled ranking matrix when permutation_type eq to phenotype. :param exprs: gene_expression DataFrame, gene_name indexed. :param str method: calc...
Build shuffled ranking matrix when permutation_type eq to phenotype. :param exprs: gene_expression DataFrame, gene_name indexed. :param str method: calculate correlation or ranking. methods including: 1. 'signal_to_noise'. 2. 't_test'. ...
Below is the the instruction that describes the task: ### Input: Build shuffled ranking matrix when permutation_type eq to phenotype. :param exprs: gene_expression DataFrame, gene_name indexed. :param str method: calculate correlation or ranking. methods including: 1. 's...
def ws_db004(self, value=None): """ Corresponds to IDD Field `ws_db004` Mean wind speed coincident with 0.4% dry-bulb temperature Args: value (float): value for IDD Field `ws_db004` Unit: m/s if `value` is None it will not be checked against the ...
Corresponds to IDD Field `ws_db004` Mean wind speed coincident with 0.4% dry-bulb temperature Args: value (float): value for IDD Field `ws_db004` Unit: m/s if `value` is None it will not be checked against the specification and is assumed to b...
Below is the the instruction that describes the task: ### Input: Corresponds to IDD Field `ws_db004` Mean wind speed coincident with 0.4% dry-bulb temperature Args: value (float): value for IDD Field `ws_db004` Unit: m/s if `value` is None it will not be ...
def alias(self, alias): """Returns a new :class:`DataFrame` with an alias set. :param alias: string, an alias name to be set for the DataFrame. >>> from pyspark.sql.functions import * >>> df_as1 = df.alias("df_as1") >>> df_as2 = df.alias("df_as2") >>> joined_df = df_as1...
Returns a new :class:`DataFrame` with an alias set. :param alias: string, an alias name to be set for the DataFrame. >>> from pyspark.sql.functions import * >>> df_as1 = df.alias("df_as1") >>> df_as2 = df.alias("df_as2") >>> joined_df = df_as1.join(df_as2, col("df_as1.name") ==...
Below is the the instruction that describes the task: ### Input: Returns a new :class:`DataFrame` with an alias set. :param alias: string, an alias name to be set for the DataFrame. >>> from pyspark.sql.functions import * >>> df_as1 = df.alias("df_as1") >>> df_as2 = df.alias("df_as...
def reshape_text(buffer, from_row, to_row): """ Reformat text, taking the width into account. `to_row` is included. (Vi 'gq' operator.) """ lines = buffer.text.splitlines(True) lines_before = lines[:from_row] lines_after = lines[to_row + 1:] lines_to_reformat = lines[from_row:to_row ...
Reformat text, taking the width into account. `to_row` is included. (Vi 'gq' operator.)
Below is the the instruction that describes the task: ### Input: Reformat text, taking the width into account. `to_row` is included. (Vi 'gq' operator.) ### Response: def reshape_text(buffer, from_row, to_row): """ Reformat text, taking the width into account. `to_row` is included. (Vi 'gq'...
def get_recipe_instances_for_badges(self, badges): """ Takes a list of badge slugs and returns a tuple: ``(valid, invalid)``. """ from .exceptions import BadgeNotFound valid, invalid = [], [] if not isinstance(badges, (list, tuple)): badges = [badges] ...
Takes a list of badge slugs and returns a tuple: ``(valid, invalid)``.
Below is the the instruction that describes the task: ### Input: Takes a list of badge slugs and returns a tuple: ``(valid, invalid)``. ### Response: def get_recipe_instances_for_badges(self, badges): """ Takes a list of badge slugs and returns a tuple: ``(valid, invalid)``. """ fro...
def aes_encrypt(self, plain, sec_key, enable_b64=True): """ 使用 ``aes`` 加密数据, 并由 ``base64编码`` 加密后的数据 - ``sec_key`` 加密 ``msg``, 最后选择 ``是否由base64编码数据`` - msg长度为16位数, 不足则补 'ascii \\0' .. warning:: msg长度为16位数, 不足则补 'ascii \\0' :param plain: :type pl...
使用 ``aes`` 加密数据, 并由 ``base64编码`` 加密后的数据 - ``sec_key`` 加密 ``msg``, 最后选择 ``是否由base64编码数据`` - msg长度为16位数, 不足则补 'ascii \\0' .. warning:: msg长度为16位数, 不足则补 'ascii \\0' :param plain: :type plain: str :param sec_key: :type sec_key: str :param enab...
Below is the the instruction that describes the task: ### Input: 使用 ``aes`` 加密数据, 并由 ``base64编码`` 加密后的数据 - ``sec_key`` 加密 ``msg``, 最后选择 ``是否由base64编码数据`` - msg长度为16位数, 不足则补 'ascii \\0' .. warning:: msg长度为16位数, 不足则补 'ascii \\0' :param plain: :type plain: str ...
def auto_schedule_hosting_devices(self, plugin, context, agent_host): """Schedules unassociated hosting devices to Cisco cfg agent. Schedules hosting devices to agent running on <agent_host>. """ query = context.session.query(bc.Agent) query = query.filter_by(agent_type=c_consta...
Schedules unassociated hosting devices to Cisco cfg agent. Schedules hosting devices to agent running on <agent_host>.
Below is the the instruction that describes the task: ### Input: Schedules unassociated hosting devices to Cisco cfg agent. Schedules hosting devices to agent running on <agent_host>. ### Response: def auto_schedule_hosting_devices(self, plugin, context, agent_host): """Schedules unassociated host...
def eq_(result, expected, msg=None): """ Shadow of the Nose builtin which presents easier to read multiline output. """ params = {'expected': expected, 'result': result} aka = """ --------------------------------- aka ----------------------------------------- Expected: %(expected)r Got: %(result)...
Shadow of the Nose builtin which presents easier to read multiline output.
Below is the the instruction that describes the task: ### Input: Shadow of the Nose builtin which presents easier to read multiline output. ### Response: def eq_(result, expected, msg=None): """ Shadow of the Nose builtin which presents easier to read multiline output. """ params = {'expected': exp...
def rgb2gray(image_rgb_array): """! @brief Returns image as 1-dimension (gray colored) matrix, where one element of list describes pixel. @details Luma coding is used for transformation and that is calculated directly from gamma-compressed primary intensities as a weighted sum: \f[Y = 0.2989R ...
! @brief Returns image as 1-dimension (gray colored) matrix, where one element of list describes pixel. @details Luma coding is used for transformation and that is calculated directly from gamma-compressed primary intensities as a weighted sum: \f[Y = 0.2989R + 0.587G + 0.114B\f] @param[...
Below is the the instruction that describes the task: ### Input: ! @brief Returns image as 1-dimension (gray colored) matrix, where one element of list describes pixel. @details Luma coding is used for transformation and that is calculated directly from gamma-compressed primary intensities as a weighted s...
def telegram(): '''Install Telegram desktop client for linux (x64). More infos: https://telegram.org https://desktop.telegram.org/ ''' if not exists('~/bin/Telegram', msg='Download and install Telegram:'): run('mkdir -p /tmp/telegram') run('cd /tmp/telegram && wget https:/...
Install Telegram desktop client for linux (x64). More infos: https://telegram.org https://desktop.telegram.org/
Below is the the instruction that describes the task: ### Input: Install Telegram desktop client for linux (x64). More infos: https://telegram.org https://desktop.telegram.org/ ### Response: def telegram(): '''Install Telegram desktop client for linux (x64). More infos: https://tele...
def set_fan_mode(self, mode): """Set the fan mode""" self.set_service_value( self.thermostat_fan_service, 'Mode', 'NewMode', mode) self.set_cache_value('fanmode', mode)
Set the fan mode
Below is the the instruction that describes the task: ### Input: Set the fan mode ### Response: def set_fan_mode(self, mode): """Set the fan mode""" self.set_service_value( self.thermostat_fan_service, 'Mode', 'NewMode', mode) self.set_cache_v...
def fit_polynomial(pixel_data, mask, clip=True): '''Return an "image" which is a polynomial fit to the pixel data Fit the image to the polynomial Ax**2+By**2+Cxy+Dx+Ey+F pixel_data - a two-dimensional numpy array to be fitted mask - a mask of pixels whose intensities should be considered ...
Return an "image" which is a polynomial fit to the pixel data Fit the image to the polynomial Ax**2+By**2+Cxy+Dx+Ey+F pixel_data - a two-dimensional numpy array to be fitted mask - a mask of pixels whose intensities should be considered in the least squares fit clip...
Below is the the instruction that describes the task: ### Input: Return an "image" which is a polynomial fit to the pixel data Fit the image to the polynomial Ax**2+By**2+Cxy+Dx+Ey+F pixel_data - a two-dimensional numpy array to be fitted mask - a mask of pixels whose intensities should b...
def assemble( iterable, patterns=None, minimum_items=2, case_sensitive=True, assume_padded_when_ambiguous=False ): '''Assemble items in *iterable* into discreet collections. *patterns* may be specified as a list of regular expressions to limit the returned collection possibilities. Use this when in...
Assemble items in *iterable* into discreet collections. *patterns* may be specified as a list of regular expressions to limit the returned collection possibilities. Use this when interested in collections that only match specific patterns. Each pattern must contain the expression from :py:data:`DIGITS_...
Below is the the instruction that describes the task: ### Input: Assemble items in *iterable* into discreet collections. *patterns* may be specified as a list of regular expressions to limit the returned collection possibilities. Use this when interested in collections that only match specific patterns...
def find_lt(array, x): """ Find rightmost value less than x. :type array: list :param array: an iterable object that support inex :param x: a comparable value Example:: >>> find_lt([0, 1, 2, 3], 2.5) 2 **中文文档** 寻找最大的小于x的数。 """ i = bisect.bisect_left(array, x...
Find rightmost value less than x. :type array: list :param array: an iterable object that support inex :param x: a comparable value Example:: >>> find_lt([0, 1, 2, 3], 2.5) 2 **中文文档** 寻找最大的小于x的数。
Below is the the instruction that describes the task: ### Input: Find rightmost value less than x. :type array: list :param array: an iterable object that support inex :param x: a comparable value Example:: >>> find_lt([0, 1, 2, 3], 2.5) 2 **中文文档** 寻找最大的小于x的数。 ### Respo...
def serial_udb_extra_f5_send(self, sue_YAWKP_AILERON, sue_YAWKD_AILERON, sue_ROLLKP, sue_ROLLKD, sue_YAW_STABILIZATION_AILERON, sue_AILERON_BOOST, force_mavlink1=False): ''' Backwards compatible version of SERIAL_UDB_EXTRA F5: format sue_YAWKP_AILERON : Serial UD...
Backwards compatible version of SERIAL_UDB_EXTRA F5: format sue_YAWKP_AILERON : Serial UDB YAWKP_AILERON Gain for Proporional control of navigation (float) sue_YAWKD_AILERON : Serial UDB YAWKD_AILERON Gain for Rate control of navigation (float) sue_ROLLKP...
Below is the the instruction that describes the task: ### Input: Backwards compatible version of SERIAL_UDB_EXTRA F5: format sue_YAWKP_AILERON : Serial UDB YAWKP_AILERON Gain for Proporional control of navigation (float) sue_YAWKD_AILERON : Serial UDB YAWKD_AILERON G...
def search(self, query, page=0, order=7, category=0, multipage=False): """ Searches TPB for query and returns a list of paginated Torrents capable of changing query, categories and orders. """ search = Search(self.base_url, query, page, order, category) if multipage: ...
Searches TPB for query and returns a list of paginated Torrents capable of changing query, categories and orders.
Below is the the instruction that describes the task: ### Input: Searches TPB for query and returns a list of paginated Torrents capable of changing query, categories and orders. ### Response: def search(self, query, page=0, order=7, category=0, multipage=False): """ Searches TPB for query ...
def search(self, category, term='', index=0, count=100): """Search for an item in a category. Args: category (str): The search category to use. Standard Sonos search categories are 'artists', 'albums', 'tracks', 'playlists', 'genres', 'stations', 'tags'. Not ...
Search for an item in a category. Args: category (str): The search category to use. Standard Sonos search categories are 'artists', 'albums', 'tracks', 'playlists', 'genres', 'stations', 'tags'. Not all are available for each music service. Call avail...
Below is the the instruction that describes the task: ### Input: Search for an item in a category. Args: category (str): The search category to use. Standard Sonos search categories are 'artists', 'albums', 'tracks', 'playlists', 'genres', 'stations', 'tags'. Not...
def image_file(path=None, zscript='self[1:]', xscript='[0,1]', yscript='d[0]', g=None, **kwargs): """ Loads an data file and plots it with color. Data file must have columns of the same length! Parameters ---------- path=None Path to data file. zscript='self[1:]' Determines...
Loads an data file and plots it with color. Data file must have columns of the same length! Parameters ---------- path=None Path to data file. zscript='self[1:]' Determines how to get data from the columns xscript='[0,1]', yscript='d[0]' Determine the x and y arrays us...
Below is the the instruction that describes the task: ### Input: Loads an data file and plots it with color. Data file must have columns of the same length! Parameters ---------- path=None Path to data file. zscript='self[1:]' Determines how to get data from the columns xsc...
def trylock(self): "Try to acquire lock and return True; if cannot acquire the lock at this moment, return False." if self.locked: return True if self.lockroutine: return False waiter = self.scheduler.send(LockEvent(self.context, self.key, self)) if waiter...
Try to acquire lock and return True; if cannot acquire the lock at this moment, return False.
Below is the the instruction that describes the task: ### Input: Try to acquire lock and return True; if cannot acquire the lock at this moment, return False. ### Response: def trylock(self): "Try to acquire lock and return True; if cannot acquire the lock at this moment, return False." if self.loc...
def newDocProp(self, name, value): """Create a new property carried by a document. """ ret = libxml2mod.xmlNewDocProp(self._o, name, value) if ret is None:raise treeError('xmlNewDocProp() failed') __tmp = xmlAttr(_obj=ret) return __tmp
Create a new property carried by a document.
Below is the the instruction that describes the task: ### Input: Create a new property carried by a document. ### Response: def newDocProp(self, name, value): """Create a new property carried by a document. """ ret = libxml2mod.xmlNewDocProp(self._o, name, value) if ret is None:raise treeEr...
def execute_command(self, verb, verb_arguments): """Executes command (ex. add) via a dedicated http object. Async APIs may take minutes to complete. Therefore, callers are encouraged to leverage concurrent.futures (or similar) to place long running commands on a separate threads. ...
Executes command (ex. add) via a dedicated http object. Async APIs may take minutes to complete. Therefore, callers are encouraged to leverage concurrent.futures (or similar) to place long running commands on a separate threads. Args: verb (str): Method to execute on the co...
Below is the the instruction that describes the task: ### Input: Executes command (ex. add) via a dedicated http object. Async APIs may take minutes to complete. Therefore, callers are encouraged to leverage concurrent.futures (or similar) to place long running commands on a separate thread...
def load_rocstories_dataset(dataset_path): """ Output a list of tuples(story, 1st continuation, 2nd continuation, label) """ with open(dataset_path, encoding='utf_8') as f: f = csv.reader(f) output = [] next(f) # skip the first line for line in tqdm(f): output.append(...
Output a list of tuples(story, 1st continuation, 2nd continuation, label)
Below is the the instruction that describes the task: ### Input: Output a list of tuples(story, 1st continuation, 2nd continuation, label) ### Response: def load_rocstories_dataset(dataset_path): """ Output a list of tuples(story, 1st continuation, 2nd continuation, label) """ with open(dataset_path, encod...
def as_table(self, name=None): """ Return an alias to a table """ if name is None: name = self._id return alias(self.subquery(), name=name)
Return an alias to a table
Below is the the instruction that describes the task: ### Input: Return an alias to a table ### Response: def as_table(self, name=None): """ Return an alias to a table """ if name is None: name = self._id return alias(self.subquery(), name=name)
def load_directory(self, directory, ext=None): """Load RiveScript documents from a directory. :param str directory: The directory of RiveScript documents to load replies from. :param []str ext: List of file extensions to consider as RiveScript documents. The default is `...
Load RiveScript documents from a directory. :param str directory: The directory of RiveScript documents to load replies from. :param []str ext: List of file extensions to consider as RiveScript documents. The default is ``[".rive", ".rs"]``.
Below is the the instruction that describes the task: ### Input: Load RiveScript documents from a directory. :param str directory: The directory of RiveScript documents to load replies from. :param []str ext: List of file extensions to consider as RiveScript documents. The d...
def reply_regexp(self, user, regexp): """Prepares a trigger for the regular expression engine. :param str user: The user ID invoking a reply. :param str regexp: The original trigger text to be turned into a regexp. :return regexp: The final regexp object.""" if regexp in self....
Prepares a trigger for the regular expression engine. :param str user: The user ID invoking a reply. :param str regexp: The original trigger text to be turned into a regexp. :return regexp: The final regexp object.
Below is the the instruction that describes the task: ### Input: Prepares a trigger for the regular expression engine. :param str user: The user ID invoking a reply. :param str regexp: The original trigger text to be turned into a regexp. :return regexp: The final regexp object. ### Respon...
def exception_to_signal(sig: Union[SignalException, signal.Signals]): """ Rollback any changes done by :py:func:`signal_to_exception`. """ if isinstance(sig, SignalException): signum = sig.signum else: signum = sig.value signal.signal(signum, signal.SIG_DFL)
Rollback any changes done by :py:func:`signal_to_exception`.
Below is the the instruction that describes the task: ### Input: Rollback any changes done by :py:func:`signal_to_exception`. ### Response: def exception_to_signal(sig: Union[SignalException, signal.Signals]): """ Rollback any changes done by :py:func:`signal_to_exception`. """ if isinstance(sig, S...
def is_instance_running(self, instance_id): """Checks if the instance is up and running. :param str instance_id: instance identifier :return: bool - True if running, False otherwise """ instance = self._load_instance(instance_id) if instance.update() == "running": ...
Checks if the instance is up and running. :param str instance_id: instance identifier :return: bool - True if running, False otherwise
Below is the the instruction that describes the task: ### Input: Checks if the instance is up and running. :param str instance_id: instance identifier :return: bool - True if running, False otherwise ### Response: def is_instance_running(self, instance_id): """Checks if the instance is up...
def organization_subscription_delete(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/organization_subscriptions#delete-organization-subscription" api_path = "/api/v2/organization_subscriptions/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, ...
https://developer.zendesk.com/rest_api/docs/core/organization_subscriptions#delete-organization-subscription
Below is the the instruction that describes the task: ### Input: https://developer.zendesk.com/rest_api/docs/core/organization_subscriptions#delete-organization-subscription ### Response: def organization_subscription_delete(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/organizatio...
def inference(self, state_arr, limit=1000): ''' Infernce. Args: state_arr: `np.ndarray` of state. limit: The number of inferencing. Returns: `list of `np.ndarray` of an optimal route. ''' self.__inferencing_f...
Infernce. Args: state_arr: `np.ndarray` of state. limit: The number of inferencing. Returns: `list of `np.ndarray` of an optimal route.
Below is the the instruction that describes the task: ### Input: Infernce. Args: state_arr: `np.ndarray` of state. limit: The number of inferencing. Returns: `list of `np.ndarray` of an optimal route. ### Response: def inference(self, ...
def from_mask_and_sub_grid_size(cls, mask, sub_grid_size=1): """Setup a sub-grid of the unmasked pixels, using a mask and a specified sub-grid size. The center of \ every unmasked pixel's sub-pixels give the grid's (y,x) arc-second coordinates. Parameters ----------- mask : Mask...
Setup a sub-grid of the unmasked pixels, using a mask and a specified sub-grid size. The center of \ every unmasked pixel's sub-pixels give the grid's (y,x) arc-second coordinates. Parameters ----------- mask : Mask The mask whose masked pixels are used to setup the sub-pixe...
Below is the the instruction that describes the task: ### Input: Setup a sub-grid of the unmasked pixels, using a mask and a specified sub-grid size. The center of \ every unmasked pixel's sub-pixels give the grid's (y,x) arc-second coordinates. Parameters ----------- mask : Mask ...
def generateToken(bits=32): """ Generates a random token based on the given parameters. :return <str> """ if bits == 64: hasher = hashlib.sha256 elif bits == 32: hasher = hashlib.md5 else: raise StandardError('Unknown bit level.') return hasher(nstr(rando...
Generates a random token based on the given parameters. :return <str>
Below is the the instruction that describes the task: ### Input: Generates a random token based on the given parameters. :return <str> ### Response: def generateToken(bits=32): """ Generates a random token based on the given parameters. :return <str> """ if bits == 64: ...
def MempoolCheck(self): """ Checks the Mempool and removes any tx found on the Blockchain Implemented to resolve https://github.com/CityOfZion/neo-python/issues/703 """ txs = [] values = self.MemPool.values() for tx in values: txs.append(tx) f...
Checks the Mempool and removes any tx found on the Blockchain Implemented to resolve https://github.com/CityOfZion/neo-python/issues/703
Below is the the instruction that describes the task: ### Input: Checks the Mempool and removes any tx found on the Blockchain Implemented to resolve https://github.com/CityOfZion/neo-python/issues/703 ### Response: def MempoolCheck(self): """ Checks the Mempool and removes any tx found on ...
def format_h2(s, format="text", indents=0): """ Encloses string in format text Args, Returns: see format_h1() >>> print("\\n".join(format_h2("Header 2", indents=2))) Header 2 -------- >>> print("\\n".join(format_h2("Header 2", "markdown", 2))) ## Header 2 """ ...
Encloses string in format text Args, Returns: see format_h1() >>> print("\\n".join(format_h2("Header 2", indents=2))) Header 2 -------- >>> print("\\n".join(format_h2("Header 2", "markdown", 2))) ## Header 2
Below is the the instruction that describes the task: ### Input: Encloses string in format text Args, Returns: see format_h1() >>> print("\\n".join(format_h2("Header 2", indents=2))) Header 2 -------- >>> print("\\n".join(format_h2("Header 2", "markdown", 2))) ## Header 2 ###...
def to_dict(self): """ MobID representation as dict """ material = {'Data1': self.Data1, 'Data2': self.Data2, 'Data3': self.Data3, 'Data4': list(self.Data4) } return {'material':material, ...
MobID representation as dict
Below is the the instruction that describes the task: ### Input: MobID representation as dict ### Response: def to_dict(self): """ MobID representation as dict """ material = {'Data1': self.Data1, 'Data2': self.Data2, 'Data3': self.Data3, ...
def from_voxels(voxels): """ Converts a voxel list to an ndarray. Arguments: voxels (tuple[]): A list of coordinates indicating coordinates of populated voxels in an ndarray. Returns: numpy.ndarray The result of the transformation. """ dimensions = len(voxels[0]) ...
Converts a voxel list to an ndarray. Arguments: voxels (tuple[]): A list of coordinates indicating coordinates of populated voxels in an ndarray. Returns: numpy.ndarray The result of the transformation.
Below is the the instruction that describes the task: ### Input: Converts a voxel list to an ndarray. Arguments: voxels (tuple[]): A list of coordinates indicating coordinates of populated voxels in an ndarray. Returns: numpy.ndarray The result of the transformation. ### Respon...
def enable_mp_crash_reporting(): """ Monkey-patch the multiprocessing.Process class with our own CrashReportingProcess. Any subsequent imports of multiprocessing.Process will reference CrashReportingProcess instead. This function must be called before any imports to mulitprocessing in order for the mon...
Monkey-patch the multiprocessing.Process class with our own CrashReportingProcess. Any subsequent imports of multiprocessing.Process will reference CrashReportingProcess instead. This function must be called before any imports to mulitprocessing in order for the monkey-patching to work.
Below is the the instruction that describes the task: ### Input: Monkey-patch the multiprocessing.Process class with our own CrashReportingProcess. Any subsequent imports of multiprocessing.Process will reference CrashReportingProcess instead. This function must be called before any imports to mulitprocess...
def _init_converters(types_map): """Prepares the converters for conversion of java types to python objects. types_map: Mapping of java.sql.Types field name to java.sql.Types field constant value""" global _converters _converters = {} for i in _DEFAULT_CONVERTERS: const_val = types_ma...
Prepares the converters for conversion of java types to python objects. types_map: Mapping of java.sql.Types field name to java.sql.Types field constant value
Below is the the instruction that describes the task: ### Input: Prepares the converters for conversion of java types to python objects. types_map: Mapping of java.sql.Types field name to java.sql.Types field constant value ### Response: def _init_converters(types_map): """Prepares the converters f...
def export(self, name, columns, points): """Export the stats to the Statsd server.""" if name == self.plugins_to_export()[0] and self.buffer != {}: # One complete loop have been done logger.debug("Export stats ({}) to RESTful endpoint ({})".format(listkeys(self.buffer), ...
Export the stats to the Statsd server.
Below is the the instruction that describes the task: ### Input: Export the stats to the Statsd server. ### Response: def export(self, name, columns, points): """Export the stats to the Statsd server.""" if name == self.plugins_to_export()[0] and self.buffer != {}: # One complete loop h...
def x_values_ref(self, series): """ The Excel worksheet reference to the X values for this chart (not including the column label). """ top_row = self.series_table_row_offset(series) + 2 bottom_row = top_row + len(series) - 1 return "Sheet1!$A$%d:$A$%d" % (top_row,...
The Excel worksheet reference to the X values for this chart (not including the column label).
Below is the the instruction that describes the task: ### Input: The Excel worksheet reference to the X values for this chart (not including the column label). ### Response: def x_values_ref(self, series): """ The Excel worksheet reference to the X values for this chart (not includi...
async def run_async(self): """ Starts the run loop and manages exceptions and cleanup. """ try: await self.run_loop_async() except Exception as err: # pylint: disable=broad-except _logger.error("Run loop failed %r", err) try: _logger....
Starts the run loop and manages exceptions and cleanup.
Below is the the instruction that describes the task: ### Input: Starts the run loop and manages exceptions and cleanup. ### Response: async def run_async(self): """ Starts the run loop and manages exceptions and cleanup. """ try: await self.run_loop_async() exce...
def animation_dialog(images, delay_s=1., loop=True, **kwargs): ''' .. versionadded:: v0.19 Parameters ---------- images : list Filepaths to images or :class:`gtk.Pixbuf` instances. delay_s : float, optional Number of seconds to display each frame. Default: ``1.0``. ...
.. versionadded:: v0.19 Parameters ---------- images : list Filepaths to images or :class:`gtk.Pixbuf` instances. delay_s : float, optional Number of seconds to display each frame. Default: ``1.0``. loop : bool, optional If ``True``, restart animation after last ima...
Below is the the instruction that describes the task: ### Input: .. versionadded:: v0.19 Parameters ---------- images : list Filepaths to images or :class:`gtk.Pixbuf` instances. delay_s : float, optional Number of seconds to display each frame. Default: ``1.0``. loop :...
def parent_of(self, name): """ go to parent of node with name, and set as cur_node. Useful for creating new paragraphs """ if not self._in_tag(name): return node = self.cur_node while node.tag != name: node = node.getparent() self....
go to parent of node with name, and set as cur_node. Useful for creating new paragraphs
Below is the the instruction that describes the task: ### Input: go to parent of node with name, and set as cur_node. Useful for creating new paragraphs ### Response: def parent_of(self, name): """ go to parent of node with name, and set as cur_node. Useful for creating new paragr...