code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def write_event(self, event): """Writes an ``Event`` object to Splunk. :param event: An ``Event`` object. """ if not self.header_written: self._out.write("<stream>") self.header_written = True event.write_to(self._out)
Writes an ``Event`` object to Splunk. :param event: An ``Event`` object.
Below is the the instruction that describes the task: ### Input: Writes an ``Event`` object to Splunk. :param event: An ``Event`` object. ### Response: def write_event(self, event): """Writes an ``Event`` object to Splunk. :param event: An ``Event`` object. """ if not sel...
def build_agg_vec(agg_vec, **source): """ Builds an combined aggregation vector based on various classifications This function build an aggregation vector based on the order in agg_vec. The naming and actual mapping is given in source, either explicitly or by pointing to a folder with the mapping. ...
Builds an combined aggregation vector based on various classifications This function build an aggregation vector based on the order in agg_vec. The naming and actual mapping is given in source, either explicitly or by pointing to a folder with the mapping. >>> build_agg_vec(['EU', 'OECD'], path = 'tes...
Below is the the instruction that describes the task: ### Input: Builds an combined aggregation vector based on various classifications This function build an aggregation vector based on the order in agg_vec. The naming and actual mapping is given in source, either explicitly or by pointing to a folder...
def _current_user_manager(self, session=None): """Return the current user, or SYSTEM user.""" if session is None: session = db.session() try: user = g.user except Exception: return session.query(User).get(0) if sa.orm.object_session(user) is ...
Return the current user, or SYSTEM user.
Below is the the instruction that describes the task: ### Input: Return the current user, or SYSTEM user. ### Response: def _current_user_manager(self, session=None): """Return the current user, or SYSTEM user.""" if session is None: session = db.session() try: user...
def create_txt_record(self, name, values, ttl=60, weight=None, region=None, set_identifier=None): """ Creates a TXT record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings ...
Creates a TXT record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings for the record. :keyword int ttl: The time-to-live of the record (in seconds). :keyword int weight: *For weighted record sets on...
Below is the the instruction that describes the task: ### Input: Creates a TXT record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings for the record. :keyword int ttl: The time-to-live of the record (i...
def zGetRefresh(self): """Copy lens in UI to headless ZOS COM server""" OpticalSystem._dde_link.zGetRefresh() OpticalSystem._dde_link.zSaveFile(self._sync_ui_file) self._iopticalsystem.LoadFile (self._sync_ui_file, False)
Copy lens in UI to headless ZOS COM server
Below is the the instruction that describes the task: ### Input: Copy lens in UI to headless ZOS COM server ### Response: def zGetRefresh(self): """Copy lens in UI to headless ZOS COM server""" OpticalSystem._dde_link.zGetRefresh() OpticalSystem._dde_link.zSaveFile(self._sync_ui_file) ...
def get_events_df(self, num_items=100, params=None, columns=None, drop_columns=None, convert_ips=True): """ Get events as pandas DataFrame :param int num_items: Max items to retrieve :param dict params: Additional params dictionary according to: https://www.alienvault.com/doc...
Get events as pandas DataFrame :param int num_items: Max items to retrieve :param dict params: Additional params dictionary according to: https://www.alienvault.com/documentation/api/usm-anywhere-api.htm#/events :parama list columns: list of columns to include in DataFrame :r...
Below is the the instruction that describes the task: ### Input: Get events as pandas DataFrame :param int num_items: Max items to retrieve :param dict params: Additional params dictionary according to: https://www.alienvault.com/documentation/api/usm-anywhere-api.htm#/events :pa...
def write_file(self, filename=None, buffer=None, fileobj=None): """Write this NBT file to a file.""" closefile = True if buffer: self.filename = None self.file = buffer closefile = False elif filename: self.filename = filename s...
Write this NBT file to a file.
Below is the the instruction that describes the task: ### Input: Write this NBT file to a file. ### Response: def write_file(self, filename=None, buffer=None, fileobj=None): """Write this NBT file to a file.""" closefile = True if buffer: self.filename = None self.fi...
def set_event(self, simulation_start=None, simulation_duration=None, simulation_end=None, rain_intensity=2, rain_duration=timedelta(seconds=30*60), event_type='EVENT', ): """ Init...
Initializes event for GSSHA model
Below is the the instruction that describes the task: ### Input: Initializes event for GSSHA model ### Response: def set_event(self, simulation_start=None, simulation_duration=None, simulation_end=None, rain_intensity=2, rain...
def series_fetch_by_relname(self, name, column): """ Construct DataFrame with component timeseries data from filtered table data. Parameters ---------- name : str Component name. column : str Component field with timevarying data. Returns...
Construct DataFrame with component timeseries data from filtered table data. Parameters ---------- name : str Component name. column : str Component field with timevarying data. Returns ------- pd.DataFrame Component d...
Below is the the instruction that describes the task: ### Input: Construct DataFrame with component timeseries data from filtered table data. Parameters ---------- name : str Component name. column : str Component field with timevarying data. ...
def Reynolds(V, D, rho=None, mu=None, nu=None): r'''Calculates Reynolds number or `Re` for a fluid with the given properties for the specified velocity and diameter. .. math:: Re = \frac{D \cdot V}{\nu} = \frac{\rho V D}{\mu} Inputs either of any of the following sets: * V, D, density `rh...
r'''Calculates Reynolds number or `Re` for a fluid with the given properties for the specified velocity and diameter. .. math:: Re = \frac{D \cdot V}{\nu} = \frac{\rho V D}{\mu} Inputs either of any of the following sets: * V, D, density `rho` and kinematic viscosity `mu` * V, D, and dyna...
Below is the the instruction that describes the task: ### Input: r'''Calculates Reynolds number or `Re` for a fluid with the given properties for the specified velocity and diameter. .. math:: Re = \frac{D \cdot V}{\nu} = \frac{\rho V D}{\mu} Inputs either of any of the following sets: * ...
def get_database(self, database_name=None, username=None, password=None): """ Get a pymongo database handle, after authenticating. Authenticates using the username/password in the DB URI given to __init__() unless username/password is supplied as arguments. :param database_name...
Get a pymongo database handle, after authenticating. Authenticates using the username/password in the DB URI given to __init__() unless username/password is supplied as arguments. :param database_name: (optional) Name of database :param username: (optional) Username to login with ...
Below is the the instruction that describes the task: ### Input: Get a pymongo database handle, after authenticating. Authenticates using the username/password in the DB URI given to __init__() unless username/password is supplied as arguments. :param database_name: (optional) Name of data...
def doInteractions(self, number=1): """ Directly maps the agents and the tasks. """ t0 = time.time() for _ in range(number): self._oneInteraction() elapsed = time.time() - t0 logger.info("%d interactions executed in %.3fs." % (number, elapsed)) retu...
Directly maps the agents and the tasks.
Below is the the instruction that describes the task: ### Input: Directly maps the agents and the tasks. ### Response: def doInteractions(self, number=1): """ Directly maps the agents and the tasks. """ t0 = time.time() for _ in range(number): self._oneInteraction() ...
def check_dependencies(model, model_queue, avaliable_models): """ Check that all the depenedencies for this model are already in the queue. """ # A list of allowed links: existing fields, itself and the special case ContentType allowed_links = [m.model.__name__ for m in model_queue] + [model.__name__, 'Cont...
Check that all the depenedencies for this model are already in the queue.
Below is the the instruction that describes the task: ### Input: Check that all the depenedencies for this model are already in the queue. ### Response: def check_dependencies(model, model_queue, avaliable_models): """ Check that all the depenedencies for this model are already in the queue. """ # A list o...
def build_project(self): """ Build IAR project """ # > IarBuild [project_path] -build [project_name] proj_path = join(getcwd(), self.workspace['files']['ewp']) if proj_path.split('.')[-1] != 'ewp': proj_path += '.ewp' if not os.path.exists(proj_path): logg...
Build IAR project
Below is the the instruction that describes the task: ### Input: Build IAR project ### Response: def build_project(self): """ Build IAR project """ # > IarBuild [project_path] -build [project_name] proj_path = join(getcwd(), self.workspace['files']['ewp']) if proj_path.split('.')[-1...
def _prepare_temp_dir(self): """Cleans up and prepare temporary directory.""" if not shell_call(['sudo', 'rm', '-rf', os.path.join(self._temp_dir, '*')]): logging.error('Failed to cleanup temporary directory.') sys.exit(1) # NOTE: we do not create self._extracted_submission_dir # this is int...
Cleans up and prepare temporary directory.
Below is the the instruction that describes the task: ### Input: Cleans up and prepare temporary directory. ### Response: def _prepare_temp_dir(self): """Cleans up and prepare temporary directory.""" if not shell_call(['sudo', 'rm', '-rf', os.path.join(self._temp_dir, '*')]): logging.error('Failed to...
def range_expr(arg): ''' Accepts a range expression which generates a range of values for a variable. Linear space range: "linspace:1,2,10" (start, stop, num) as in numpy.linspace Pythonic range: "range:1,10,2" (start, stop[, step]) as in Python's range Case range: "case:a,b,c" (comma-separated str...
Accepts a range expression which generates a range of values for a variable. Linear space range: "linspace:1,2,10" (start, stop, num) as in numpy.linspace Pythonic range: "range:1,10,2" (start, stop[, step]) as in Python's range Case range: "case:a,b,c" (comma-separated strings)
Below is the the instruction that describes the task: ### Input: Accepts a range expression which generates a range of values for a variable. Linear space range: "linspace:1,2,10" (start, stop, num) as in numpy.linspace Pythonic range: "range:1,10,2" (start, stop[, step]) as in Python's range Case rang...
def deconvolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, apply_w=None, apply_b=None): """ Deconvolution layer. Args: ...
Deconvolution layer. Args: inp (~nnabla.Variable): N-D array. outmaps (int): Number of deconvolution kernels (which is equal to the number of output channels). For example, to apply deconvolution on an input with 16 types of filters, specify 16. kernel (:obj:`tuple` of :obj:`int`): Convolut...
Below is the the instruction that describes the task: ### Input: Deconvolution layer. Args: inp (~nnabla.Variable): N-D array. outmaps (int): Number of deconvolution kernels (which is equal to the number of output channels). For example, to apply deconvolution on an input with 16 types of filte...
def cachedir_index_del(minion_id, base=None): ''' Delete an entry from the cachedir index. This generally only needs to happen when an instance is deleted. ''' base = init_cachedir(base) index_file = os.path.join(base, 'index.p') lock_file(index_file) if os.path.exists(index_file): ...
Delete an entry from the cachedir index. This generally only needs to happen when an instance is deleted.
Below is the the instruction that describes the task: ### Input: Delete an entry from the cachedir index. This generally only needs to happen when an instance is deleted. ### Response: def cachedir_index_del(minion_id, base=None): ''' Delete an entry from the cachedir index. This generally only needs t...
def instance(): """Return an PyVabamorf instance. It returns the previously initialized instance or creates a new one if nothing exists. Also creates new instance in case the process has been forked. """ if not hasattr(Vabamorf, 'pid') or Vabamorf.pid != os.getpid(): ...
Return an PyVabamorf instance. It returns the previously initialized instance or creates a new one if nothing exists. Also creates new instance in case the process has been forked.
Below is the the instruction that describes the task: ### Input: Return an PyVabamorf instance. It returns the previously initialized instance or creates a new one if nothing exists. Also creates new instance in case the process has been forked. ### Response: def instance(): """Ret...
def Calls(self, conditions=None): """Find the methods that evaluate data that meets this condition. Args: conditions: A tuple of (artifact, os_name, cpe, label) Returns: A list of methods that evaluate the data. """ results = set() if conditions is None: conditions = [None] ...
Find the methods that evaluate data that meets this condition. Args: conditions: A tuple of (artifact, os_name, cpe, label) Returns: A list of methods that evaluate the data.
Below is the the instruction that describes the task: ### Input: Find the methods that evaluate data that meets this condition. Args: conditions: A tuple of (artifact, os_name, cpe, label) Returns: A list of methods that evaluate the data. ### Response: def Calls(self, conditions=None): "...
def list_members(self, retrieve_all=True, **_params): """Fetches a list of all load balancer members for a project.""" # Pass filters in "params" argument to do_request return self.list('members', self.members_path, retrieve_all, **_params)
Fetches a list of all load balancer members for a project.
Below is the the instruction that describes the task: ### Input: Fetches a list of all load balancer members for a project. ### Response: def list_members(self, retrieve_all=True, **_params): """Fetches a list of all load balancer members for a project.""" # Pass filters in "params" argument to do_...
def focus_prev_matching(self, querystring): """focus previous matching message in depth first order""" self.focus_property(lambda x: x._message.matches(querystring), self._tree.prev_position)
focus previous matching message in depth first order
Below is the the instruction that describes the task: ### Input: focus previous matching message in depth first order ### Response: def focus_prev_matching(self, querystring): """focus previous matching message in depth first order""" self.focus_property(lambda x: x._message.matches(querystring), ...
def raw_query(self, query, query_parameters=None): """ To get all the document that equal to the query @param str query: The rql query @param dict query_parameters: Add query parameters to the query {key : value} """ self.assert_no_raw_query() if len(self._where...
To get all the document that equal to the query @param str query: The rql query @param dict query_parameters: Add query parameters to the query {key : value}
Below is the the instruction that describes the task: ### Input: To get all the document that equal to the query @param str query: The rql query @param dict query_parameters: Add query parameters to the query {key : value} ### Response: def raw_query(self, query, query_parameters=None): ""...
def step5(self): """step5() removes a final -e if m() > 1, and changes -ll to -l if m() > 1. """ self.j = self.k if self.b[self.k] == "e": a = self.m() if a > 1 or (a == 1 and not self.cvc(self.k - 1)): self.k = self.k - 1 if self.b...
step5() removes a final -e if m() > 1, and changes -ll to -l if m() > 1.
Below is the the instruction that describes the task: ### Input: step5() removes a final -e if m() > 1, and changes -ll to -l if m() > 1. ### Response: def step5(self): """step5() removes a final -e if m() > 1, and changes -ll to -l if m() > 1. """ self.j = self.k if...
def YamlLoader(string): """Load an AFF4 object from a serialized YAML representation.""" representation = yaml.Parse(string) result_cls = aff4.FACTORY.AFF4Object(representation["aff4_class"]) aff4_attributes = {} for predicate, values in iteritems(representation["attributes"]): attribute = aff4.Attribute....
Load an AFF4 object from a serialized YAML representation.
Below is the the instruction that describes the task: ### Input: Load an AFF4 object from a serialized YAML representation. ### Response: def YamlLoader(string): """Load an AFF4 object from a serialized YAML representation.""" representation = yaml.Parse(string) result_cls = aff4.FACTORY.AFF4Object(represent...
def init_default(required, default, optional_default): """ Returns optional default if field is not required and default was not provided. :param bool required: whether the field is required in a given model. :param default: default provided by creator of field. :param optional_default: default...
Returns optional default if field is not required and default was not provided. :param bool required: whether the field is required in a given model. :param default: default provided by creator of field. :param optional_default: default for the data type if none provided. :return: default or option...
Below is the the instruction that describes the task: ### Input: Returns optional default if field is not required and default was not provided. :param bool required: whether the field is required in a given model. :param default: default provided by creator of field. :param optional_default: defau...
def to_envvars(self): """ Export property values to a dictionary with environment variable names as keys. """ export = {} for prop_name in self.profile_properties: prop = self._get_prop(prop_name) value = self[prop_name] if value is not None: ...
Export property values to a dictionary with environment variable names as keys.
Below is the the instruction that describes the task: ### Input: Export property values to a dictionary with environment variable names as keys. ### Response: def to_envvars(self): """ Export property values to a dictionary with environment variable names as keys. """ export = {} ...
def get_ip_info(ip_str): """ Given a string, it returns a tuple of (IP, Routable). """ ip = None is_routable_ip = False if is_valid_ip(ip_str): ip = ip_str is_routable_ip = is_public_ip(ip) return ip, is_routable_ip
Given a string, it returns a tuple of (IP, Routable).
Below is the the instruction that describes the task: ### Input: Given a string, it returns a tuple of (IP, Routable). ### Response: def get_ip_info(ip_str): """ Given a string, it returns a tuple of (IP, Routable). """ ip = None is_routable_ip = False if is_valid_ip(ip_str): ip = i...
def update_detector(self, detector_id, detector): """Update an existing detector. Args: detector_id (string): the ID of the detector. detector (object): the detector model object. Will be serialized as JSON. Returns: dictionary of the response...
Update an existing detector. Args: detector_id (string): the ID of the detector. detector (object): the detector model object. Will be serialized as JSON. Returns: dictionary of the response (updated detector model).
Below is the the instruction that describes the task: ### Input: Update an existing detector. Args: detector_id (string): the ID of the detector. detector (object): the detector model object. Will be serialized as JSON. Returns: dictionary of the ...
def zk_client(host, scheme, credential): """ returns a connected (and possibly authenticated) ZK client """ if not re.match(r".*:\d+$", host): host = "%s:%d" % (host, DEFAULT_ZK_PORT) client = KazooClient(hosts=host) client.start() if scheme != "": client.add_auth(scheme, credenti...
returns a connected (and possibly authenticated) ZK client
Below is the the instruction that describes the task: ### Input: returns a connected (and possibly authenticated) ZK client ### Response: def zk_client(host, scheme, credential): """ returns a connected (and possibly authenticated) ZK client """ if not re.match(r".*:\d+$", host): host = "%s:%d" % ...
def set_stim_by_index(self, index): """Sets the stimulus to be generated to the one referenced by index :param index: index number of stimulus to set from this class's internal list of stimuli :type index: int """ # remove any current components self.stimulus.clearCompon...
Sets the stimulus to be generated to the one referenced by index :param index: index number of stimulus to set from this class's internal list of stimuli :type index: int
Below is the the instruction that describes the task: ### Input: Sets the stimulus to be generated to the one referenced by index :param index: index number of stimulus to set from this class's internal list of stimuli :type index: int ### Response: def set_stim_by_index(self, index): """S...
def create(lr, alpha, momentum=0, weight_decay=0, epsilon=1e-8): """ Vel factory function """ return RMSpropTFFactory(lr=lr, alpha=alpha, momentum=momentum, weight_decay=weight_decay, eps=float(epsilon))
Vel factory function
Below is the the instruction that describes the task: ### Input: Vel factory function ### Response: def create(lr, alpha, momentum=0, weight_decay=0, epsilon=1e-8): """ Vel factory function """ return RMSpropTFFactory(lr=lr, alpha=alpha, momentum=momentum, weight_decay=weight_decay, eps=float(epsilon))
def blobs(n_variables=11, n_centers=5, cluster_std=1.0, n_observations=640) -> AnnData: """Gaussian Blobs. Parameters ---------- n_variables : `int`, optional (default: 11) Dimension of feature space. n_centers : `int`, optional (default: 5) Number of cluster centers. cluster_st...
Gaussian Blobs. Parameters ---------- n_variables : `int`, optional (default: 11) Dimension of feature space. n_centers : `int`, optional (default: 5) Number of cluster centers. cluster_std : `float`, optional (default: 1.0) Standard deviation of clusters. n_observations...
Below is the the instruction that describes the task: ### Input: Gaussian Blobs. Parameters ---------- n_variables : `int`, optional (default: 11) Dimension of feature space. n_centers : `int`, optional (default: 5) Number of cluster centers. cluster_std : `float`, optional (def...
def _encode_request(self, request): """Encode a request object""" return pickle.dumps(request_to_dict(request, self.spider), protocol=-1)
Encode a request object
Below is the the instruction that describes the task: ### Input: Encode a request object ### Response: def _encode_request(self, request): """Encode a request object""" return pickle.dumps(request_to_dict(request, self.spider), protocol=-1)
def check_calendar_dates( feed: "Feed", *, as_df: bool = False, include_warnings: bool = False ) -> List: """ Analog of :func:`check_agency` for ``feed.calendar_dates``. """ table = "calendar_dates" problems = [] # Preliminary checks if feed.calendar_dates is None: return proble...
Analog of :func:`check_agency` for ``feed.calendar_dates``.
Below is the the instruction that describes the task: ### Input: Analog of :func:`check_agency` for ``feed.calendar_dates``. ### Response: def check_calendar_dates( feed: "Feed", *, as_df: bool = False, include_warnings: bool = False ) -> List: """ Analog of :func:`check_agency` for ``feed.calendar_dat...
def get(self, attr_name, *args): """ Get the most retrieval attribute in the configuration file. This method will recursively look through the configuration file for the attribute specified and return the last found value or None. The values can be referenced by the key name provided in...
Get the most retrieval attribute in the configuration file. This method will recursively look through the configuration file for the attribute specified and return the last found value or None. The values can be referenced by the key name provided in the configuration file or that value normali...
Below is the the instruction that describes the task: ### Input: Get the most retrieval attribute in the configuration file. This method will recursively look through the configuration file for the attribute specified and return the last found value or None. The values can be referenced by ...
def count_alleles(self, max_allele=None, subpop=None): """Count the number of calls of each allele per variant. Parameters ---------- max_allele : int, optional The highest allele index to count. Alleles above this will be ignored. subpop : sequence of in...
Count the number of calls of each allele per variant. Parameters ---------- max_allele : int, optional The highest allele index to count. Alleles above this will be ignored. subpop : sequence of ints, optional Indices of samples to include in count. ...
Below is the the instruction that describes the task: ### Input: Count the number of calls of each allele per variant. Parameters ---------- max_allele : int, optional The highest allele index to count. Alleles above this will be ignored. subpop : sequence of...
def select_catalogue(self, selector, distance, distance_metric='joyner-boore', upper_eq_depth=None, lower_eq_depth=None): ''' Selects earthquakes within a distance of the fault :param selector: Populated instance of :class: ...
Selects earthquakes within a distance of the fault :param selector: Populated instance of :class: `openquake.hmtk.seismicity.selector.CatalogueSelector` :param distance: Distance from point (km) for selection :param str distance_metric Choice of...
Below is the the instruction that describes the task: ### Input: Selects earthquakes within a distance of the fault :param selector: Populated instance of :class: `openquake.hmtk.seismicity.selector.CatalogueSelector` :param distance: Distance from point (km) fo...
def from_dict(self, document): """Create image group object from JSON document retrieved from database. Parameters ---------- document : JSON Json document in database Returns ------- ImageGroupHandle Handle for image group object ...
Create image group object from JSON document retrieved from database. Parameters ---------- document : JSON Json document in database Returns ------- ImageGroupHandle Handle for image group object
Below is the the instruction that describes the task: ### Input: Create image group object from JSON document retrieved from database. Parameters ---------- document : JSON Json document in database Returns ------- ImageGroupHandle Handle for...
def check_image_evaluation(self, image, show_history=False, detail=False, tag=None, policy=None): '''**Description** Check the latest policy evaluation for an image **Arguments** - image: Input image can be in the following formats: registry/repo:tag - show_history: ...
**Description** Check the latest policy evaluation for an image **Arguments** - image: Input image can be in the following formats: registry/repo:tag - show_history: Show all previous policy evaluations - detail: Show detailed policy evaluation report ...
Below is the the instruction that describes the task: ### Input: **Description** Check the latest policy evaluation for an image **Arguments** - image: Input image can be in the following formats: registry/repo:tag - show_history: Show all previous policy evaluations ...
def process_pool(self, limited_run=False): """Return a pool for multiprocess operations, sized either to the number of CPUS, or a configured value""" from multiprocessing import cpu_count from ambry.bundle.concurrent import Pool, init_library if self.processes: cpus = self....
Return a pool for multiprocess operations, sized either to the number of CPUS, or a configured value
Below is the the instruction that describes the task: ### Input: Return a pool for multiprocess operations, sized either to the number of CPUS, or a configured value ### Response: def process_pool(self, limited_run=False): """Return a pool for multiprocess operations, sized either to the number of CPUS, or...
def create_login_manager(self, app) -> LoginManager: """ Override to implement your custom login manager instance :param app: Flask app """ lm = LoginManager(app) lm.login_view = "login" lm.user_loader(self.load_user) return lm
Override to implement your custom login manager instance :param app: Flask app
Below is the the instruction that describes the task: ### Input: Override to implement your custom login manager instance :param app: Flask app ### Response: def create_login_manager(self, app) -> LoginManager: """ Override to implement your custom login manager instance ...
def _valid_other_type(x, types): """ Do all elements of x have a type from types? """ return all(any(isinstance(el, t) for t in types) for el in np.ravel(x))
Do all elements of x have a type from types?
Below is the the instruction that describes the task: ### Input: Do all elements of x have a type from types? ### Response: def _valid_other_type(x, types): """ Do all elements of x have a type from types? """ return all(any(isinstance(el, t) for t in types) for el in np.ravel(x))
def _parse_logo(self, parsed_content): """ Parses the guild logo and saves it to the instance. Parameters ---------- parsed_content: :class:`bs4.Tag` The parsed content of the page. Returns ------- :class:`bool` Whether the logo w...
Parses the guild logo and saves it to the instance. Parameters ---------- parsed_content: :class:`bs4.Tag` The parsed content of the page. Returns ------- :class:`bool` Whether the logo was found or not.
Below is the the instruction that describes the task: ### Input: Parses the guild logo and saves it to the instance. Parameters ---------- parsed_content: :class:`bs4.Tag` The parsed content of the page. Returns ------- :class:`bool` Whether ...
def observed_vis(self, context): """ Observed visibility data source """ lrow, urow = MS.row_extents(context) data = self._manager.ordered_main_table.getcol( self._vis_column, startrow=lrow, nrow=urow-lrow) return data.reshape(context.shape).astype(context.dtype)
Observed visibility data source
Below is the the instruction that describes the task: ### Input: Observed visibility data source ### Response: def observed_vis(self, context): """ Observed visibility data source """ lrow, urow = MS.row_extents(context) data = self._manager.ordered_main_table.getcol( self._vis...
def get_endpoints(): """ get all endpoints known on the Ariane server :return: """ LOGGER.debug("EndpointService.get_endpoints") params = SessionService.complete_transactional_req(None) if params is None: if MappingService.driver_type != DriverFactory....
get all endpoints known on the Ariane server :return:
Below is the the instruction that describes the task: ### Input: get all endpoints known on the Ariane server :return: ### Response: def get_endpoints(): """ get all endpoints known on the Ariane server :return: """ LOGGER.debug("EndpointService.get_endpoints") ...
def cache_call_signatures(source, user_pos, stmt): """This function calculates the cache key.""" index = user_pos[0] - 1 lines = source.splitlines() or [''] if source and source[-1] == '\n': lines.append('') before_cursor = lines[index][:user_pos[1]] other_lines = lines[stmt.start_pos[0...
This function calculates the cache key.
Below is the the instruction that describes the task: ### Input: This function calculates the cache key. ### Response: def cache_call_signatures(source, user_pos, stmt): """This function calculates the cache key.""" index = user_pos[0] - 1 lines = source.splitlines() or [''] if source and source[-1...
def parse_variable(lexer: Lexer) -> VariableNode: """Variable: $Name""" start = lexer.token expect_token(lexer, TokenKind.DOLLAR) return VariableNode(name=parse_name(lexer), loc=loc(lexer, start))
Variable: $Name
Below is the the instruction that describes the task: ### Input: Variable: $Name ### Response: def parse_variable(lexer: Lexer) -> VariableNode: """Variable: $Name""" start = lexer.token expect_token(lexer, TokenKind.DOLLAR) return VariableNode(name=parse_name(lexer), loc=loc(lexer, start))
def _create_sequence_maps(self): '''Get all of the SequenceMaps - Rosetta->ATOM, ATOM->SEQRES/FASTA, SEQRES->UniParc.''' if self.sifts: self.sifts_atom_to_seqres_sequence_maps = self.sifts.atom_to_seqres_sequence_maps self.sifts_seqres_to_uniparc_sequence_maps = self.sifts.seqre...
Get all of the SequenceMaps - Rosetta->ATOM, ATOM->SEQRES/FASTA, SEQRES->UniParc.
Below is the the instruction that describes the task: ### Input: Get all of the SequenceMaps - Rosetta->ATOM, ATOM->SEQRES/FASTA, SEQRES->UniParc. ### Response: def _create_sequence_maps(self): '''Get all of the SequenceMaps - Rosetta->ATOM, ATOM->SEQRES/FASTA, SEQRES->UniParc.''' if self.sifts: ...
def _update_state_from_response(self, response_json): """ :param response_json: the json obj returned from query :return: """ if 'data' in response_json and response_json['data']['object_type'] == "cloud_clock": cloud_clock = response_json.get('data') ...
:param response_json: the json obj returned from query :return:
Below is the the instruction that describes the task: ### Input: :param response_json: the json obj returned from query :return: ### Response: def _update_state_from_response(self, response_json): """ :param response_json: the json obj returned from query :return: """ ...
def conference_play(self, call_params): """REST Conference Play helper """ path = '/' + self.api_version + '/ConferencePlay/' method = 'POST' return self.request(path, method, call_params)
REST Conference Play helper
Below is the the instruction that describes the task: ### Input: REST Conference Play helper ### Response: def conference_play(self, call_params): """REST Conference Play helper """ path = '/' + self.api_version + '/ConferencePlay/' method = 'POST' return self.request(path, ...
def detect_extracellular_compartment(model): """Detect the identifier for equations with extracellular compartments. Args: model: :class:`NativeModel`. """ extracellular_key = Counter() for reaction in model.reactions: equation = reaction.equation if equation is None: ...
Detect the identifier for equations with extracellular compartments. Args: model: :class:`NativeModel`.
Below is the the instruction that describes the task: ### Input: Detect the identifier for equations with extracellular compartments. Args: model: :class:`NativeModel`. ### Response: def detect_extracellular_compartment(model): """Detect the identifier for equations with extracellular compartments...
def _conv_adr(adr, entry): """Converts to Abook address format""" if adr.value.street: entry['address'] = adr.value.street if adr.value.extended: entry['address2'] = adr.value.extended if adr.value.city: entry['city'] = adr.value.city if adr.va...
Converts to Abook address format
Below is the the instruction that describes the task: ### Input: Converts to Abook address format ### Response: def _conv_adr(adr, entry): """Converts to Abook address format""" if adr.value.street: entry['address'] = adr.value.street if adr.value.extended: entry['ad...
def process_files(): """ Process files with a single progress bar """ with enlighten.Counter(total=100, desc='Simple', unit='ticks') as pbar: for num in range(100): # pylint: disable=unused-variable time.sleep(0.05) pbar.update()
Process files with a single progress bar
Below is the the instruction that describes the task: ### Input: Process files with a single progress bar ### Response: def process_files(): """ Process files with a single progress bar """ with enlighten.Counter(total=100, desc='Simple', unit='ticks') as pbar: for num in range(100): # py...
def get_bucket(self, environment, name, filename, source): """Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`. """ key = self.get_cache_key(name, filename) checksum = self.get_source_checksum(source) bucket = Bucket(en...
Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`.
Below is the the instruction that describes the task: ### Input: Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`. ### Response: def get_bucket(self, environment, name, filename, source): """Return a cache bucket for the given template. All argu...
def parse_link(value): """Return a list of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" :rtype: list """ links = [] replace_chars = ' \'"' value = value.strip(replace_chars) if not value...
Return a list of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" :rtype: list
Below is the the instruction that describes the task: ### Input: Return a list of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" :rtype: list ### Response: def parse_link(value): """Return a list of parsed ...
def remove_udp_port(self, port): """ Removes an associated UDP port number from this project. :param port: UDP port number """ if port in self._used_udp_ports: self._used_udp_ports.remove(port)
Removes an associated UDP port number from this project. :param port: UDP port number
Below is the the instruction that describes the task: ### Input: Removes an associated UDP port number from this project. :param port: UDP port number ### Response: def remove_udp_port(self, port): """ Removes an associated UDP port number from this project. :param port: UDP port ...
def make_prefetchitem_accessedfilelist_accessedfile(accessed_file, condition='contains', negate=False, preserve_case=False): """ Create a node for PrefetchItem/AccessedFileList/AccessedFile :return: A IndicatorItem represented as an Element node "...
Create a node for PrefetchItem/AccessedFileList/AccessedFile :return: A IndicatorItem represented as an Element node
Below is the the instruction that describes the task: ### Input: Create a node for PrefetchItem/AccessedFileList/AccessedFile :return: A IndicatorItem represented as an Element node ### Response: def make_prefetchitem_accessedfilelist_accessedfile(accessed_file, condition='contains', negate=False, ...
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_2_0): """ Write the Attributes structure encoding to the data stream. Args: output_stream (stream): A data stream in which to encode Attributes structure data, supporting a write method. k...
Write the Attributes structure encoding to the data stream. Args: output_stream (stream): A data stream in which to encode Attributes structure data, supporting a write method. kmip_version (enum): A KMIPVersion enumeration defining the KMIP version with ...
Below is the the instruction that describes the task: ### Input: Write the Attributes structure encoding to the data stream. Args: output_stream (stream): A data stream in which to encode Attributes structure data, supporting a write method. kmip_version (enum): A KM...
def _aix_get_machine_id(): ''' Parse the output of lsattr -El sys0 for os_uuid ''' grains = {} cmd = salt.utils.path.which('lsattr') if cmd: data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')] ...
Parse the output of lsattr -El sys0 for os_uuid
Below is the the instruction that describes the task: ### Input: Parse the output of lsattr -El sys0 for os_uuid ### Response: def _aix_get_machine_id(): ''' Parse the output of lsattr -El sys0 for os_uuid ''' grains = {} cmd = salt.utils.path.which('lsattr') if cmd: data = __salt__...
def t_NUMBER(self, t): r'(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?(kb|gb|mb|tb|pb|Kb|Gb|Mb|Tb|Pb)?' if re.match(r'^(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?(kb|gb|mb|tb|pb|Kb|Gb|Mb|Tb|Pb)?$',t.value): multiplyer = 1 try: suffix = (t.value[-2:]).lower() if suffix...
r'(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?(kb|gb|mb|tb|pb|Kb|Gb|Mb|Tb|Pb)?
Below is the the instruction that describes the task: ### Input: r'(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?(kb|gb|mb|tb|pb|Kb|Gb|Mb|Tb|Pb)? ### Response: def t_NUMBER(self, t): r'(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?(kb|gb|mb|tb|pb|Kb|Gb|Mb|Tb|Pb)?' if re.match(r'^(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?(kb|gb|mb...
def _search(self, words, include=None, exclude=None, lookup=None): '''Full text search. Return a list of queries to intersect.''' lookup = lookup or 'contains' query = self.router.worditem.query() if include: query = query.filter(model_type__in=include) if exclu...
Full text search. Return a list of queries to intersect.
Below is the the instruction that describes the task: ### Input: Full text search. Return a list of queries to intersect. ### Response: def _search(self, words, include=None, exclude=None, lookup=None): '''Full text search. Return a list of queries to intersect.''' lookup = lookup or 'contains' ...
def set_size(self, width_in_points, height_in_points): """Changes the size of a PostScript surface for the current (and subsequent) pages. This method should only be called before any drawing operations have been performed on the current page. The simplest way to do this is to c...
Changes the size of a PostScript surface for the current (and subsequent) pages. This method should only be called before any drawing operations have been performed on the current page. The simplest way to do this is to call this method immediately after creating the surface ...
Below is the the instruction that describes the task: ### Input: Changes the size of a PostScript surface for the current (and subsequent) pages. This method should only be called before any drawing operations have been performed on the current page. The simplest way to do this is t...
def is_outlier(df, item_id, segment_id, price): """ Verify if a item is an outlier compared to the other occurrences of the same item, based on his price. Args: item_id: idPlanilhaItens segment_id: idSegmento price: VlUnitarioAprovado """ if (segment_id, item_id) not in...
Verify if a item is an outlier compared to the other occurrences of the same item, based on his price. Args: item_id: idPlanilhaItens segment_id: idSegmento price: VlUnitarioAprovado
Below is the the instruction that describes the task: ### Input: Verify if a item is an outlier compared to the other occurrences of the same item, based on his price. Args: item_id: idPlanilhaItens segment_id: idSegmento price: VlUnitarioAprovado ### Response: def is_outlier(df, i...
def redo(self): """Called when an image is set in the channel.""" image = self.channel.get_current_image() if image is None: return True path = image.get('path', None) if path is None: self.fv.show_error( "Cannot open image: no value for m...
Called when an image is set in the channel.
Below is the the instruction that describes the task: ### Input: Called when an image is set in the channel. ### Response: def redo(self): """Called when an image is set in the channel.""" image = self.channel.get_current_image() if image is None: return True path = ima...
def Softsign(a): """ Softsign op. """ return np.divide(a, np.add(np.abs(a), 1)),
Softsign op.
Below is the the instruction that describes the task: ### Input: Softsign op. ### Response: def Softsign(a): """ Softsign op. """ return np.divide(a, np.add(np.abs(a), 1)),
def send_template_email(recipients, title_template, body_template, context, language): """Sends e-mail using templating system""" send_emails = getattr(settings, 'SEND_PLANS_EMAILS', True) if not send_emails: return site_name = getattr(settings, 'SITE_NAME', 'Please define settings.SITE_NAME')...
Sends e-mail using templating system
Below is the the instruction that describes the task: ### Input: Sends e-mail using templating system ### Response: def send_template_email(recipients, title_template, body_template, context, language): """Sends e-mail using templating system""" send_emails = getattr(settings, 'SEND_PLANS_EMAILS', True) ...
def uniqued(layer, column=0): """Group inputs to a layer, so that the layer only has to compute for the unique values. The data is transformed back before output, and the same transformation is applied for the gradient. Effectively, this is a cache local to each minibatch. The uniqued wrapper is us...
Group inputs to a layer, so that the layer only has to compute for the unique values. The data is transformed back before output, and the same transformation is applied for the gradient. Effectively, this is a cache local to each minibatch. The uniqued wrapper is useful for word inputs, because common ...
Below is the the instruction that describes the task: ### Input: Group inputs to a layer, so that the layer only has to compute for the unique values. The data is transformed back before output, and the same transformation is applied for the gradient. Effectively, this is a cache local to each minibatch...
def dict_of(validate_key, validate_item): """Returns a validator function that succeeds only if the input is a dict, and each key and value in the dict passes as input to the provided validators validate_key and validate_item, respectively. :param callable validate_key: the validator function for keys in t...
Returns a validator function that succeeds only if the input is a dict, and each key and value in the dict passes as input to the provided validators validate_key and validate_item, respectively. :param callable validate_key: the validator function for keys in the dict :param callable validate_item: the va...
Below is the the instruction that describes the task: ### Input: Returns a validator function that succeeds only if the input is a dict, and each key and value in the dict passes as input to the provided validators validate_key and validate_item, respectively. :param callable validate_key: the validator fu...
def upvote(self): """ Upvote :class:`Issue`. """ self.requester.post( '/{endpoint}/{id}/upvote', endpoint=self.endpoint, id=self.id ) return self
Upvote :class:`Issue`.
Below is the the instruction that describes the task: ### Input: Upvote :class:`Issue`. ### Response: def upvote(self): """ Upvote :class:`Issue`. """ self.requester.post( '/{endpoint}/{id}/upvote', endpoint=self.endpoint, id=self.id ) return ...
def plot_neuron_on_density(population, # pylint: disable=too-many-arguments bins=100, new_fig=True, subplot=111, levels=None, plane='xy', colorlabel='Nodes per unit area', labelfontsize=16, color_map='Reds', no_colorbar=False, threshold=0....
Plots the 2d histogram of the center coordinates of segments in the selected plane and superimposes the view of the first neurite of the collection.
Below is the the instruction that describes the task: ### Input: Plots the 2d histogram of the center coordinates of segments in the selected plane and superimposes the view of the first neurite of the collection. ### Response: def plot_neuron_on_density(population, # pylint: disable=too-many-argumen...
def normalize_lons(l1, l2): """ An international date line safe way of returning a range of longitudes. >>> normalize_lons(20, 30) # no IDL within the range [(20, 30)] >>> normalize_lons(-17, +17) # no IDL within the range [(-17, 17)] >>> normalize_lons(-178, +179) [(-180, -178), (179...
An international date line safe way of returning a range of longitudes. >>> normalize_lons(20, 30) # no IDL within the range [(20, 30)] >>> normalize_lons(-17, +17) # no IDL within the range [(-17, 17)] >>> normalize_lons(-178, +179) [(-180, -178), (179, 180)] >>> normalize_lons(178, -179...
Below is the the instruction that describes the task: ### Input: An international date line safe way of returning a range of longitudes. >>> normalize_lons(20, 30) # no IDL within the range [(20, 30)] >>> normalize_lons(-17, +17) # no IDL within the range [(-17, 17)] >>> normalize_lons(-178, ...
def encryptfile(filename, passphrase, algo='srp'): """ Encrypt a file and write it with .cryptoshop extension. :param filename: a string with the path to the file to encrypt. :param passphrase: a string with the user passphrase. :param algo: a string with the algorithm. Can be srp, aes, twf. Default...
Encrypt a file and write it with .cryptoshop extension. :param filename: a string with the path to the file to encrypt. :param passphrase: a string with the user passphrase. :param algo: a string with the algorithm. Can be srp, aes, twf. Default is srp. :return: a string with "successfully encrypted" or...
Below is the the instruction that describes the task: ### Input: Encrypt a file and write it with .cryptoshop extension. :param filename: a string with the path to the file to encrypt. :param passphrase: a string with the user passphrase. :param algo: a string with the algorithm. Can be srp, aes, twf. D...
def logItems(self, level=logging.DEBUG): """ rootItem """ rootItem = self.rootItem() if rootItem is None: logger.debug("No items in: {}".format(self)) else: rootItem.logBranch(level=level)
rootItem
Below is the the instruction that describes the task: ### Input: rootItem ### Response: def logItems(self, level=logging.DEBUG): """ rootItem """ rootItem = self.rootItem() if rootItem is None: logger.debug("No items in: {}".format(self)) else: rootIt...
def repo( state, host, name, baseurl, present=True, description=None, enabled=True, gpgcheck=True, gpgkey=None, ): ''' Add/remove/update yum repositories. + name: filename for the repo (in ``/etc/yum/repos.d/``) + baseurl: the baseurl of the repo + present: whether the ``.repo`` file should...
Add/remove/update yum repositories. + name: filename for the repo (in ``/etc/yum/repos.d/``) + baseurl: the baseurl of the repo + present: whether the ``.repo`` file should be present + description: optional verbose description + gpgcheck: whether set ``gpgcheck=1`` + gpgkey: the URL to the gpg...
Below is the the instruction that describes the task: ### Input: Add/remove/update yum repositories. + name: filename for the repo (in ``/etc/yum/repos.d/``) + baseurl: the baseurl of the repo + present: whether the ``.repo`` file should be present + description: optional verbose description + ...
def prettify_metrics(metrics: List[Tuple[str, float]], precision: int = 4) -> OrderedDict: """Prettifies the dictionary of metrics.""" prettified_metrics = OrderedDict() for key, value in metrics: value = round(value, precision) prettified_metrics[key] = value return prettified_metrics
Prettifies the dictionary of metrics.
Below is the the instruction that describes the task: ### Input: Prettifies the dictionary of metrics. ### Response: def prettify_metrics(metrics: List[Tuple[str, float]], precision: int = 4) -> OrderedDict: """Prettifies the dictionary of metrics.""" prettified_metrics = OrderedDict() for key, value i...
def get_table(self, id_or_name): """ Retrieves a Table by id or name :param str id_or_name: The id or name of the column :return: a Table instance """ url = self.build_url(self._endpoints.get('get_table').format(id=id_or_name)) response = self.session.get(url) ...
Retrieves a Table by id or name :param str id_or_name: The id or name of the column :return: a Table instance
Below is the the instruction that describes the task: ### Input: Retrieves a Table by id or name :param str id_or_name: The id or name of the column :return: a Table instance ### Response: def get_table(self, id_or_name): """ Retrieves a Table by id or name :param str id_or_...
def extract_hosted_zip(data_url, save_dir, exclude_term=None): """Downloads, then extracts a zip file.""" zip_name = os.path.join(save_dir, 'temp.zip') # get the zip file try: print('Downloading %r to %r' % (data_url, zip_name)) zip_name, hdrs = urllib.request.urlretrieve(url=data_url,...
Downloads, then extracts a zip file.
Below is the the instruction that describes the task: ### Input: Downloads, then extracts a zip file. ### Response: def extract_hosted_zip(data_url, save_dir, exclude_term=None): """Downloads, then extracts a zip file.""" zip_name = os.path.join(save_dir, 'temp.zip') # get the zip file try: ...
def build(self, response): """ Deserialize the returned objects and return either a single Zenpy object, or a ResultGenerator in the case of multiple results. :param response: the requests Response object. """ response_json = response.json() # Special case for t...
Deserialize the returned objects and return either a single Zenpy object, or a ResultGenerator in the case of multiple results. :param response: the requests Response object.
Below is the the instruction that describes the task: ### Input: Deserialize the returned objects and return either a single Zenpy object, or a ResultGenerator in the case of multiple results. :param response: the requests Response object. ### Response: def build(self, response): """ ...
def playbooks(playbook, rundir=None, check=False, diff=False, extra_vars=None, flush_cache=False, forks=5, inventory=None, limit=None, list_hosts=False, list_tags=False, list_tasks=False, module_path=None, skip_tags=None, start_at_task=None, syntax_check=False, ta...
Run Ansible Playbooks :param playbook: Which playbook to run. :param rundir: Directory to run `ansible-playbook` in. (Default: None) :param check: don't make any changes; instead, try to predict some of the changes that may occur (Default: False) :param diff: when changing (small) fil...
Below is the the instruction that describes the task: ### Input: Run Ansible Playbooks :param playbook: Which playbook to run. :param rundir: Directory to run `ansible-playbook` in. (Default: None) :param check: don't make any changes; instead, try to predict some of the changes that ...
def _locate(self, name): """ Gets a dependency locator by its name. :param name: the name of the dependency to locate. :return: the dependency locator or null if locator was not configured. """ if name == None: raise Exception("Dependency name cannot be null"...
Gets a dependency locator by its name. :param name: the name of the dependency to locate. :return: the dependency locator or null if locator was not configured.
Below is the the instruction that describes the task: ### Input: Gets a dependency locator by its name. :param name: the name of the dependency to locate. :return: the dependency locator or null if locator was not configured. ### Response: def _locate(self, name): """ Gets a depend...
def blast(request, blast_form, template_init, template_result, blast_commandline, sample_fasta_path, extra_context=None): """ Process blastn/tblastn (blast+) query or set up initial blast form. """ if request.method == 'POST': form = blast_form(request.POST) if form.is_valid...
Process blastn/tblastn (blast+) query or set up initial blast form.
Below is the the instruction that describes the task: ### Input: Process blastn/tblastn (blast+) query or set up initial blast form. ### Response: def blast(request, blast_form, template_init, template_result, blast_commandline, sample_fasta_path, extra_context=None): """ Process blastn/tblastn (...
def get_request_kwargs(self): """Construct keyword parameters for Session.request() and Session.resolve_redirects().""" kwargs = dict(stream=True, timeout=self.aggregate.config["timeout"]) if self.proxy: kwargs["proxies"] = {self.proxytype: self.proxy} if self.scheme ...
Construct keyword parameters for Session.request() and Session.resolve_redirects().
Below is the the instruction that describes the task: ### Input: Construct keyword parameters for Session.request() and Session.resolve_redirects(). ### Response: def get_request_kwargs(self): """Construct keyword parameters for Session.request() and Session.resolve_redirects().""" ...
def get_es(urls=None, timeout=DEFAULT_TIMEOUT, force_new=False, **settings): """Create an elasticsearch `Elasticsearch` object and return it. This will aggressively re-use `Elasticsearch` objects with the following rules: 1. if you pass the same argument values to `get_es()`, then it will retur...
Create an elasticsearch `Elasticsearch` object and return it. This will aggressively re-use `Elasticsearch` objects with the following rules: 1. if you pass the same argument values to `get_es()`, then it will return the same `Elasticsearch` object 2. if you pass different argument values to `g...
Below is the the instruction that describes the task: ### Input: Create an elasticsearch `Elasticsearch` object and return it. This will aggressively re-use `Elasticsearch` objects with the following rules: 1. if you pass the same argument values to `get_es()`, then it will return the same `Ela...
def reexport_tf_summary(): """Re-export all symbols from the original tf.summary. This function finds the original tf.summary V2 API and re-exports all the symbols from it within this module as well, so that when this module is patched into the TF API namespace as the new tf.summary, the effect is an overlay...
Re-export all symbols from the original tf.summary. This function finds the original tf.summary V2 API and re-exports all the symbols from it within this module as well, so that when this module is patched into the TF API namespace as the new tf.summary, the effect is an overlay that just adds TensorBoard-prov...
Below is the the instruction that describes the task: ### Input: Re-export all symbols from the original tf.summary. This function finds the original tf.summary V2 API and re-exports all the symbols from it within this module as well, so that when this module is patched into the TF API namespace as the new t...
def parseStep(self, line): """ Parse the line describing the mode. One of: variableStep chrom=<reference> [span=<window_size>] fixedStep chrom=<reference> start=<position> step=<step_interval> [span=<window_size>] Span is optional, defaulting to 1. It ...
Parse the line describing the mode. One of: variableStep chrom=<reference> [span=<window_size>] fixedStep chrom=<reference> start=<position> step=<step_interval> [span=<window_size>] Span is optional, defaulting to 1. It indicates that each value applies to re...
Below is the the instruction that describes the task: ### Input: Parse the line describing the mode. One of: variableStep chrom=<reference> [span=<window_size>] fixedStep chrom=<reference> start=<position> step=<step_interval> [span=<window_size>] Span is optional...
def Thome(m, x, D, rhol, rhog, mul, mug, kl, kg, Cpl, Cpg, Hvap, sigma, Psat, Pc, q=None, Te=None): r'''Calculates heat transfer coefficient for film boiling of saturated fluid in any orientation of flow. Correlation is as developed in [1]_ and [2]_, and also reviewed [3]_. This is a complic...
r'''Calculates heat transfer coefficient for film boiling of saturated fluid in any orientation of flow. Correlation is as developed in [1]_ and [2]_, and also reviewed [3]_. This is a complicated model, but expected to have more accuracy as a result. Either the heat flux or excess temperature is ...
Below is the the instruction that describes the task: ### Input: r'''Calculates heat transfer coefficient for film boiling of saturated fluid in any orientation of flow. Correlation is as developed in [1]_ and [2]_, and also reviewed [3]_. This is a complicated model, but expected to have more accuracy...
def handle_matches(self, match): """ Returns a response statement from a matched input statement. :param match: It is a valid matched pattern from the input statement :type: `_sre.SRE_Match` """ response = Statement(text='') from_parsed = match.group("from") ...
Returns a response statement from a matched input statement. :param match: It is a valid matched pattern from the input statement :type: `_sre.SRE_Match`
Below is the the instruction that describes the task: ### Input: Returns a response statement from a matched input statement. :param match: It is a valid matched pattern from the input statement :type: `_sre.SRE_Match` ### Response: def handle_matches(self, match): """ Returns a re...
def transformer_base_v2(): """Set of hyperparameters.""" hparams = transformer_base_v1() hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.layer_prepostprocess_dropout = 0.1 hparams.attention_dropout = 0.1 hparams.relu_dropout = 0.1 hparams.learning_rate_warmup_st...
Set of hyperparameters.
Below is the the instruction that describes the task: ### Input: Set of hyperparameters. ### Response: def transformer_base_v2(): """Set of hyperparameters.""" hparams = transformer_base_v1() hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.layer_prepostprocess_dr...
def _repack_archive (archive1, archive2, verbosity=0, interactive=True): """Repackage an archive to a different format.""" format1, compression1 = get_archive_format(archive1) format2, compression2 = get_archive_format(archive2) if format1 == format2 and compression1 == compression2: # same form...
Repackage an archive to a different format.
Below is the the instruction that describes the task: ### Input: Repackage an archive to a different format. ### Response: def _repack_archive (archive1, archive2, verbosity=0, interactive=True): """Repackage an archive to a different format.""" format1, compression1 = get_archive_format(archive1) form...
def match_rstring(self, tokens, item): """Match suffix string.""" name, suffix = tokens return self.match_mstring((None, name, suffix), item, use_bytes=suffix.startswith("b"))
Match suffix string.
Below is the the instruction that describes the task: ### Input: Match suffix string. ### Response: def match_rstring(self, tokens, item): """Match suffix string.""" name, suffix = tokens return self.match_mstring((None, name, suffix), item, use_bytes=suffix.startswith("b"))
def compute_bin_edges(features, num_bins, edge_range, trim_outliers, trim_percentile, use_orig_distr=False): "Compute the edges for the histogram bins to keep it the same for all nodes." if use_orig_distr: print('Using original distribution (without histogram) to compute edge weights!') edges=N...
Compute the edges for the histogram bins to keep it the same for all nodes.
Below is the the instruction that describes the task: ### Input: Compute the edges for the histogram bins to keep it the same for all nodes. ### Response: def compute_bin_edges(features, num_bins, edge_range, trim_outliers, trim_percentile, use_orig_distr=False): "Compute the edges for the histogram bins to ke...
def incr(self, name, amount=1): """ Increase the value at key ``name`` by ``amount``. If no key exists, the value will be initialized as ``amount`` . Like **Redis.INCR** :param string name: the key name :param int amount: increments :return: the integer value at...
Increase the value at key ``name`` by ``amount``. If no key exists, the value will be initialized as ``amount`` . Like **Redis.INCR** :param string name: the key name :param int amount: increments :return: the integer value at key ``name`` :rtype: int >>> ssdb....
Below is the the instruction that describes the task: ### Input: Increase the value at key ``name`` by ``amount``. If no key exists, the value will be initialized as ``amount`` . Like **Redis.INCR** :param string name: the key name :param int amount: increments :return: the...
def _is_bright(rgb): """Return whether a RGB color is bright or not.""" r, g, b = rgb gray = 0.299 * r + 0.587 * g + 0.114 * b return gray >= .5
Return whether a RGB color is bright or not.
Below is the the instruction that describes the task: ### Input: Return whether a RGB color is bright or not. ### Response: def _is_bright(rgb): """Return whether a RGB color is bright or not.""" r, g, b = rgb gray = 0.299 * r + 0.587 * g + 0.114 * b return gray >= .5
def CMP(self, params): """ CMP Rm, Rn CMP Rm, #imm8 Subtract Rn or imm8 from Rm, set the NZCV flags, and discard the result Rm and Rn can be R0-R14 """ Rm, Rn = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) if self.is_register(Rn): ...
CMP Rm, Rn CMP Rm, #imm8 Subtract Rn or imm8 from Rm, set the NZCV flags, and discard the result Rm and Rn can be R0-R14
Below is the the instruction that describes the task: ### Input: CMP Rm, Rn CMP Rm, #imm8 Subtract Rn or imm8 from Rm, set the NZCV flags, and discard the result Rm and Rn can be R0-R14 ### Response: def CMP(self, params): """ CMP Rm, Rn CMP Rm, #imm8 Subtr...
def touchPoint(self, x, y): ''' Touches a point in the device screen. The generated operation will use the units specified in L{coordinatesUnit} and the orientation in L{vc.display['orientation']}. ''' if DEBUG: print >> sys.stderr, 'touchPoint(%d, %d)' % (x,...
Touches a point in the device screen. The generated operation will use the units specified in L{coordinatesUnit} and the orientation in L{vc.display['orientation']}.
Below is the the instruction that describes the task: ### Input: Touches a point in the device screen. The generated operation will use the units specified in L{coordinatesUnit} and the orientation in L{vc.display['orientation']}. ### Response: def touchPoint(self, x, y): ''' Touche...
def get_app_list(region_name=None,filter_name=None): """ get local app list """ try: conn = get_conn() c = conn.cursor() cond = [] where_clause = "" if region_name: cond.append( "region='{0}' ".format(region_name) ) if filter_name: ...
get local app list
Below is the the instruction that describes the task: ### Input: get local app list ### Response: def get_app_list(region_name=None,filter_name=None): """ get local app list """ try: conn = get_conn() c = conn.cursor() cond = [] where_clause = "" if region_n...
def visit_invenio_keyword_query(self, node): """Transform an :class:`InvenioKeywordQuery` into a :class:`KeywordOp`. Notes: In case the value being a :class:`SimpleValueBooleanQuery`, the subtree is transformed to chained :class:`AndOp` queries containing :class:`KeywordOp`, who...
Transform an :class:`InvenioKeywordQuery` into a :class:`KeywordOp`. Notes: In case the value being a :class:`SimpleValueBooleanQuery`, the subtree is transformed to chained :class:`AndOp` queries containing :class:`KeywordOp`, whose keyword is the keyword of the current node and ...
Below is the the instruction that describes the task: ### Input: Transform an :class:`InvenioKeywordQuery` into a :class:`KeywordOp`. Notes: In case the value being a :class:`SimpleValueBooleanQuery`, the subtree is transformed to chained :class:`AndOp` queries containing :class:`Ke...
def is_time_variable(varname, var): """ Identifies if a variable is represents time """ satisfied = varname.lower() == 'time' satisfied |= getattr(var, 'standard_name', '') == 'time' satisfied |= getattr(var, 'axis', '') == 'T' satisfied |= units_convertible('seconds since 1900-01-01', getat...
Identifies if a variable is represents time
Below is the the instruction that describes the task: ### Input: Identifies if a variable is represents time ### Response: def is_time_variable(varname, var): """ Identifies if a variable is represents time """ satisfied = varname.lower() == 'time' satisfied |= getattr(var, 'standard_name', '')...
def get_dev_start_config(devId): """ function takes the devId of a specific device and issues a RESTFUL call to get the most current startup config file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the target device :return: str which cont...
function takes the devId of a specific device and issues a RESTFUL call to get the most current startup config file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the target device :return: str which contains the entire content of the target device ...
Below is the the instruction that describes the task: ### Input: function takes the devId of a specific device and issues a RESTFUL call to get the most current startup config file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the target device ...