code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def get_stable_id(self): """ Return a stable id. :rtype: string """ doc_id, _, parent_doc_char_start, _ = split_stable_id(self.sentence.stable_id) return ( f"{self.sentence.document.name}" f"::" f"{self._get_polymorphic_identity()}" ...
Return a stable id. :rtype: string
Below is the the instruction that describes the task: ### Input: Return a stable id. :rtype: string ### Response: def get_stable_id(self): """ Return a stable id. :rtype: string """ doc_id, _, parent_doc_char_start, _ = split_stable_id(self.sentence.stable_id) ...
def getDimensionForImage(filename, maxsize): """Return scaled image size in (width, height) format. The scaling preserves the aspect ratio. If PIL is not found returns None.""" try: from PIL import Image except ImportError: return None img = Image.open(filename) width, height...
Return scaled image size in (width, height) format. The scaling preserves the aspect ratio. If PIL is not found returns None.
Below is the the instruction that describes the task: ### Input: Return scaled image size in (width, height) format. The scaling preserves the aspect ratio. If PIL is not found returns None. ### Response: def getDimensionForImage(filename, maxsize): """Return scaled image size in (width, height) format...
def biopython_protein_analysis(inseq): """Utiize Biopython's ProteinAnalysis module to return general sequence properties of an amino acid string. For full definitions see: http://biopython.org/DIST/docs/api/Bio.SeqUtils.ProtParam.ProteinAnalysis-class.html Args: inseq: Amino acid sequence Re...
Utiize Biopython's ProteinAnalysis module to return general sequence properties of an amino acid string. For full definitions see: http://biopython.org/DIST/docs/api/Bio.SeqUtils.ProtParam.ProteinAnalysis-class.html Args: inseq: Amino acid sequence Returns: dict: Dictionary of sequence pr...
Below is the the instruction that describes the task: ### Input: Utiize Biopython's ProteinAnalysis module to return general sequence properties of an amino acid string. For full definitions see: http://biopython.org/DIST/docs/api/Bio.SeqUtils.ProtParam.ProteinAnalysis-class.html Args: inseq: Amin...
def _kraus_to_choi(data, input_dim, output_dim): """Transform Kraus representation to Choi representation.""" choi = 0 kraus_l, kraus_r = data if kraus_r is None: for i in kraus_l: vec = i.ravel(order='F') choi += np.outer(vec, vec.conj()) else: for i, j in zi...
Transform Kraus representation to Choi representation.
Below is the the instruction that describes the task: ### Input: Transform Kraus representation to Choi representation. ### Response: def _kraus_to_choi(data, input_dim, output_dim): """Transform Kraus representation to Choi representation.""" choi = 0 kraus_l, kraus_r = data if kraus_r is None: ...
def from_jvalue(jvalue, bigdl_type="float"): """ Create a Python Model base on the given java value :param jvalue: Java object create by Py4j :return: A Python Model """ model = Sequential(jvalue=jvalue) model.value = jvalue return model
Create a Python Model base on the given java value :param jvalue: Java object create by Py4j :return: A Python Model
Below is the the instruction that describes the task: ### Input: Create a Python Model base on the given java value :param jvalue: Java object create by Py4j :return: A Python Model ### Response: def from_jvalue(jvalue, bigdl_type="float"): """ Create a Python Model base on the give...
def get_course_or_program_context(self, enterprise_customer, course_id=None, program_uuid=None): """ Return a dict having course or program specific keys for data sharing consent page. """ context_data = {} if course_id: context_data.update({'course_id': course_id, 'c...
Return a dict having course or program specific keys for data sharing consent page.
Below is the the instruction that describes the task: ### Input: Return a dict having course or program specific keys for data sharing consent page. ### Response: def get_course_or_program_context(self, enterprise_customer, course_id=None, program_uuid=None): """ Return a dict having course or prog...
def _events(self): """Get the monitoring events from the daemon This is used by the arbiter to get the monitoring events from all its satellites :return: Events list serialized :rtype: list """ with self.app.events_lock: res = self.app.get_events() r...
Get the monitoring events from the daemon This is used by the arbiter to get the monitoring events from all its satellites :return: Events list serialized :rtype: list
Below is the the instruction that describes the task: ### Input: Get the monitoring events from the daemon This is used by the arbiter to get the monitoring events from all its satellites :return: Events list serialized :rtype: list ### Response: def _events(self): """Get the moni...
def get_relationship_search_session_for_family(self, family_id=None, proxy=None): """Gets the ``OsidSession`` associated with the relationship search service for the given family. arg: family_id (osid.id.Id): the ``Id`` of the family arg: proxy (osid.proxy.Proxy): a proxy return: ...
Gets the ``OsidSession`` associated with the relationship search service for the given family. arg: family_id (osid.id.Id): the ``Id`` of the family arg: proxy (osid.proxy.Proxy): a proxy return: (osid.relationship.RelationshipSearchSession) - a ``RelationshipSearchSession...
Below is the the instruction that describes the task: ### Input: Gets the ``OsidSession`` associated with the relationship search service for the given family. arg: family_id (osid.id.Id): the ``Id`` of the family arg: proxy (osid.proxy.Proxy): a proxy return: (osid.relationship.Relat...
def speed_d(self): """ The derivative constant for the speed regulation PID. """ self._speed_d, value = self.get_attr_int(self._speed_d, 'speed_pid/Kd') return value
The derivative constant for the speed regulation PID.
Below is the the instruction that describes the task: ### Input: The derivative constant for the speed regulation PID. ### Response: def speed_d(self): """ The derivative constant for the speed regulation PID. """ self._speed_d, value = self.get_attr_int(self._speed_d, 'speed_pid/Kd...
def drop_field(app_name, model_name, field_name): """ Drop the given field from the app's model """ app_config = apps.get_app_config(app_name) model = app_config.get_model(model_name) field = model._meta.get_field(field_name) with connection.schema_editor() as schema_editor: schema_e...
Drop the given field from the app's model
Below is the the instruction that describes the task: ### Input: Drop the given field from the app's model ### Response: def drop_field(app_name, model_name, field_name): """ Drop the given field from the app's model """ app_config = apps.get_app_config(app_name) model = app_config.get_model(mo...
def load_service(config): """ Load a restful service specified by some YAML file at config_path. :param config_path: A pathlib Path object that points to the yaml config :returns: A python module containing a Client class, call factory, and the definition of each of the APIs defined by the co...
Load a restful service specified by some YAML file at config_path. :param config_path: A pathlib Path object that points to the yaml config :returns: A python module containing a Client class, call factory, and the definition of each of the APIs defined by the config.
Below is the the instruction that describes the task: ### Input: Load a restful service specified by some YAML file at config_path. :param config_path: A pathlib Path object that points to the yaml config :returns: A python module containing a Client class, call factory, and the definition of e...
def solve(self, t0, y0, h=1.0, T=None, g=None, tol=None, integrator='dopri5', step=False, relax=False, **kwargs): r""" Solve the IVP by integrating the ODE given some initial condition. Parameters ---------- t0 : float Initial condition for the independ...
r""" Solve the IVP by integrating the ODE given some initial condition. Parameters ---------- t0 : float Initial condition for the independent variable. y0 : array_like (float, shape=(n,)) Initial condition for the dependent variables. h : float, ...
Below is the the instruction that describes the task: ### Input: r""" Solve the IVP by integrating the ODE given some initial condition. Parameters ---------- t0 : float Initial condition for the independent variable. y0 : array_like (float, shape=(n,)) ...
def render_it(self, *args, **kwargs): ''' Render without userinfo. fun(kind, num) fun(kind, num, with_tag = val1) fun(kind, num, with_tag = val1, glyph = val2) ''' kind = kwargs.get('kind', args[0]) num = kwargs.get('num', args[1] if len(args) > 1 else 6) ...
Render without userinfo. fun(kind, num) fun(kind, num, with_tag = val1) fun(kind, num, with_tag = val1, glyph = val2)
Below is the the instruction that describes the task: ### Input: Render without userinfo. fun(kind, num) fun(kind, num, with_tag = val1) fun(kind, num, with_tag = val1, glyph = val2) ### Response: def render_it(self, *args, **kwargs): ''' Render without userinfo. fun...
def obfn_g1(self, Y1): r"""Compute :math:`g_1(\mathbf{y_1})` component of ADMM objective function. """ return np.linalg.norm((self.wl1 * Y1).ravel(), 1)
r"""Compute :math:`g_1(\mathbf{y_1})` component of ADMM objective function.
Below is the the instruction that describes the task: ### Input: r"""Compute :math:`g_1(\mathbf{y_1})` component of ADMM objective function. ### Response: def obfn_g1(self, Y1): r"""Compute :math:`g_1(\mathbf{y_1})` component of ADMM objective function. """ return np.linalg...
def atleast_nd(n, u): """ If the input array has fewer than n dimensions, append singleton dimensions so that it is n dimensional. Note that the interface differs substantially from that of :func:`numpy.atleast_3d` etc. Parameters ---------- n : int Minimum number of required dimensio...
If the input array has fewer than n dimensions, append singleton dimensions so that it is n dimensional. Note that the interface differs substantially from that of :func:`numpy.atleast_3d` etc. Parameters ---------- n : int Minimum number of required dimensions u : array_like Input ...
Below is the the instruction that describes the task: ### Input: If the input array has fewer than n dimensions, append singleton dimensions so that it is n dimensional. Note that the interface differs substantially from that of :func:`numpy.atleast_3d` etc. Parameters ---------- n : int ...
def plotplanarPotentials(Pot,*args,**kwargs): """ NAME: plotplanarPotentials PURPOSE: plot a planar potential INPUT: Rrange - range (can be Quantity) xrange, yrange - if relevant (can be Quantity) grid, gridx, gridy - number of points to plot savefilenam...
NAME: plotplanarPotentials PURPOSE: plot a planar potential INPUT: Rrange - range (can be Quantity) xrange, yrange - if relevant (can be Quantity) grid, gridx, gridy - number of points to plot savefilename - save to or restore from this savefile (pickle) ...
Below is the the instruction that describes the task: ### Input: NAME: plotplanarPotentials PURPOSE: plot a planar potential INPUT: Rrange - range (can be Quantity) xrange, yrange - if relevant (can be Quantity) grid, gridx, gridy - number of points to plot ...
def search(description, all=False): """ Gets a list of :class:`language_tags.Subtag.Subtag` objects where the description matches. :param description: a string or compiled regular expression. For example: ``search(re.compile('\d{4}'))`` if the description of the returned subtag must...
Gets a list of :class:`language_tags.Subtag.Subtag` objects where the description matches. :param description: a string or compiled regular expression. For example: ``search(re.compile('\d{4}'))`` if the description of the returned subtag must contain four contiguous numerical digits. :type...
Below is the the instruction that describes the task: ### Input: Gets a list of :class:`language_tags.Subtag.Subtag` objects where the description matches. :param description: a string or compiled regular expression. For example: ``search(re.compile('\d{4}'))`` if the description of the returne...
async def _post(self, program_id: int = None, json: dict = None) -> dict: """Post data to a (non)existing program.""" return await self._request( 'post', 'program/{0}'.format(program_id), json=json)
Post data to a (non)existing program.
Below is the the instruction that describes the task: ### Input: Post data to a (non)existing program. ### Response: async def _post(self, program_id: int = None, json: dict = None) -> dict: """Post data to a (non)existing program.""" return await self._request( 'post', 'program/{0}'.fo...
def intround(value): """Given a float returns a rounded int. Should give the same result on both Py2/3 """ return int(decimal.Decimal.from_float( value).to_integral_value(decimal.ROUND_HALF_EVEN))
Given a float returns a rounded int. Should give the same result on both Py2/3
Below is the the instruction that describes the task: ### Input: Given a float returns a rounded int. Should give the same result on both Py2/3 ### Response: def intround(value): """Given a float returns a rounded int. Should give the same result on both Py2/3 """ return int(decimal.Decimal.fr...
def chconfig(cmd, *args, **kwargs): ''' This function is called by the :mod:`salt.modules.chassis.cmd <salt.modules.chassis.cmd>` shim. It then calls whatever is passed in ``cmd`` inside the :mod:`salt.modules.dracr <salt.modules.dracr>` module. :param cmd: The command to call inside salt.modu...
This function is called by the :mod:`salt.modules.chassis.cmd <salt.modules.chassis.cmd>` shim. It then calls whatever is passed in ``cmd`` inside the :mod:`salt.modules.dracr <salt.modules.dracr>` module. :param cmd: The command to call inside salt.modules.dracr :param args: Arguments that need t...
Below is the the instruction that describes the task: ### Input: This function is called by the :mod:`salt.modules.chassis.cmd <salt.modules.chassis.cmd>` shim. It then calls whatever is passed in ``cmd`` inside the :mod:`salt.modules.dracr <salt.modules.dracr>` module. :param cmd: The command to ...
def remove_oxidation_states(self): """ Removes oxidation states from a structure. """ for site in self.sites: new_sp = collections.defaultdict(float) for el, occu in site.species.items(): sym = el.symbol new_sp[Element(sym)] += occu...
Removes oxidation states from a structure.
Below is the the instruction that describes the task: ### Input: Removes oxidation states from a structure. ### Response: def remove_oxidation_states(self): """ Removes oxidation states from a structure. """ for site in self.sites: new_sp = collections.defaultdict(float)...
def stop(self): """停止引擎""" # 将引擎设为停止 self.__active = False # 停止计时器 self.__timer.stop() # 等待事件处理线程退出 self.__thread.join()
停止引擎
Below is the the instruction that describes the task: ### Input: 停止引擎 ### Response: def stop(self): """停止引擎""" # 将引擎设为停止 self.__active = False # 停止计时器 self.__timer.stop() # 等待事件处理线程退出 self.__thread.join()
def elcm_profile_set(irmc_info, input_data): """send an eLCM request to set param values To apply param values, a new session is spawned with status 'running'. When values are applied or error, the session ends. :param irmc_info: node info :param input_data: param values to apply, eg. { ...
send an eLCM request to set param values To apply param values, a new session is spawned with status 'running'. When values are applied or error, the session ends. :param irmc_info: node info :param input_data: param values to apply, eg. { 'Server': { 'SystemCon...
Below is the the instruction that describes the task: ### Input: send an eLCM request to set param values To apply param values, a new session is spawned with status 'running'. When values are applied or error, the session ends. :param irmc_info: node info :param input_data: param values to apply,...
def find_behind_subscriptions(): """ Finds any subscriptions that are behind according to where they should be, and creates a BehindSubscription entry for them. """ subscriptions = Subscription.objects.filter( active=True, completed=False, process_status=0 ).values_list("id", flat=True) ...
Finds any subscriptions that are behind according to where they should be, and creates a BehindSubscription entry for them.
Below is the the instruction that describes the task: ### Input: Finds any subscriptions that are behind according to where they should be, and creates a BehindSubscription entry for them. ### Response: def find_behind_subscriptions(): """ Finds any subscriptions that are behind according to where they...
def _entity_path(self, state): """Calculate the path to an entity to be returned. *state* should be the dictionary returned by :func:`_parse_atom_entry`. :func:`_entity_path` extracts the link to this entity from *state*, and strips all the namespace prefixes from it to leave on...
Calculate the path to an entity to be returned. *state* should be the dictionary returned by :func:`_parse_atom_entry`. :func:`_entity_path` extracts the link to this entity from *state*, and strips all the namespace prefixes from it to leave only the relative path of the entity ...
Below is the the instruction that describes the task: ### Input: Calculate the path to an entity to be returned. *state* should be the dictionary returned by :func:`_parse_atom_entry`. :func:`_entity_path` extracts the link to this entity from *state*, and strips all the namespace p...
def draw_graph( adata, layout='fa', init_pos=None, root=None, random_state=0, n_jobs=None, adjacency=None, key_added_ext=None, copy=False, **kwds): """Force-directed graph drawing [Islam11]_ [Jacomy14]_ [Chippada18]_. An alternativ...
Force-directed graph drawing [Islam11]_ [Jacomy14]_ [Chippada18]_. An alternative to tSNE that often preserves the topology of the data better. This requires to run :func:`~scanpy.api.pp.neighbors`, first. The default layout ('fa', `ForceAtlas2`) [Jacomy14]_ uses the package `fa2 <https://github.com/b...
Below is the the instruction that describes the task: ### Input: Force-directed graph drawing [Islam11]_ [Jacomy14]_ [Chippada18]_. An alternative to tSNE that often preserves the topology of the data better. This requires to run :func:`~scanpy.api.pp.neighbors`, first. The default layout ('fa', `Forc...
def get_term_pillar(filter_name, term_name, pillar_key='acl', pillarenv=None, saltenv=None): ''' Helper that can be used inside a state SLS, in order to get the term configuration given its name, under a certain filter uniqu...
Helper that can be used inside a state SLS, in order to get the term configuration given its name, under a certain filter uniquely identified by its name. filter_name The name of the filter. term_name The name of the term. pillar_key: ``acl`` The root key of the whole poli...
Below is the the instruction that describes the task: ### Input: Helper that can be used inside a state SLS, in order to get the term configuration given its name, under a certain filter uniquely identified by its name. filter_name The name of the filter. term_name The name of the ...
def trade_aggregations(self, resolution, base_asset_code, counter_asset_code, base_asset_issuer=None, counter_asset_issuer=None, start_time=None, end_time=None, order='asc', limit=10, offset=0): """Load a list of aggregated historical trade data, optionally ...
Load a list of aggregated historical trade data, optionally filtered by an orderbook. `GET /trade_aggregations <https://www.stellar.org/developers/horizon/reference/endpoints/trade_aggregations.html>`_ :param int start_time: Lower time boundary represented as millis since epoch. ...
Below is the the instruction that describes the task: ### Input: Load a list of aggregated historical trade data, optionally filtered by an orderbook. `GET /trade_aggregations <https://www.stellar.org/developers/horizon/reference/endpoints/trade_aggregations.html>`_ :param int star...
def expire(self, current_time=None): """Expire any old entries `current_time` Optional time to be used to clean up queue (can be used in unit tests) """ if not self._queue: return if current_time is None: current_time = time() while ...
Expire any old entries `current_time` Optional time to be used to clean up queue (can be used in unit tests)
Below is the the instruction that describes the task: ### Input: Expire any old entries `current_time` Optional time to be used to clean up queue (can be used in unit tests) ### Response: def expire(self, current_time=None): """Expire any old entries `current_time` ...
def check_url_does_not_exists(form, field): '''Ensure a reuse URL is not yet registered''' if field.data != field.object_data and Reuse.url_exists(field.data): raise validators.ValidationError(_('This URL is already registered'))
Ensure a reuse URL is not yet registered
Below is the the instruction that describes the task: ### Input: Ensure a reuse URL is not yet registered ### Response: def check_url_does_not_exists(form, field): '''Ensure a reuse URL is not yet registered''' if field.data != field.object_data and Reuse.url_exists(field.data): raise validators.Va...
def get_fd_waveform_from_td(**params): """ Return time domain version of fourier domain approximant. This returns a frequency domain version of a fourier domain approximant, with padding and tapering at the start of the waveform. Parameters ---------- params: dict The parameters defini...
Return time domain version of fourier domain approximant. This returns a frequency domain version of a fourier domain approximant, with padding and tapering at the start of the waveform. Parameters ---------- params: dict The parameters defining the waveform to generator. See `get_...
Below is the the instruction that describes the task: ### Input: Return time domain version of fourier domain approximant. This returns a frequency domain version of a fourier domain approximant, with padding and tapering at the start of the waveform. Parameters ---------- params: dict ...
def add_metric_group_definition(self, definition): """ Add a faked metric group definition. The definition will be used: * For later addition of faked metrics responses. * For returning the metric-group-info objects in the response of the Create Metrics Context operat...
Add a faked metric group definition. The definition will be used: * For later addition of faked metrics responses. * For returning the metric-group-info objects in the response of the Create Metrics Context operations. For defined metric groups, see chapter "Metric groups" i...
Below is the the instruction that describes the task: ### Input: Add a faked metric group definition. The definition will be used: * For later addition of faked metrics responses. * For returning the metric-group-info objects in the response of the Create Metrics Context operatio...
def properties(self): """All reaction properties as a dict""" properties = {'id': self._id, 'reversible': self._rev, 'equation': self._equation} if 'name' in self._root.attrib: properties['name'] = self._root.get('name') if self._lo...
All reaction properties as a dict
Below is the the instruction that describes the task: ### Input: All reaction properties as a dict ### Response: def properties(self): """All reaction properties as a dict""" properties = {'id': self._id, 'reversible': self._rev, 'equation': self._equatio...
def get_build_info(self): """Define additional build information.""" # Retrieve build by revision if self.revision: th = treeherder.Treeherder( APPLICATIONS_TO_FTP_DIRECTORY.get(self.application, self.application), self.branch, self.pla...
Define additional build information.
Below is the the instruction that describes the task: ### Input: Define additional build information. ### Response: def get_build_info(self): """Define additional build information.""" # Retrieve build by revision if self.revision: th = treeherder.Treeherder( APP...
def elekta_icon_space(shape=(448, 448, 448), **kwargs): """Default reconstruction space for the Elekta Icon CBCT. See the [whitepaper]_ for further information. Parameters ---------- shape : sequence of int, optional Shape of the space, in voxels. kwargs : Keyword arguments to ...
Default reconstruction space for the Elekta Icon CBCT. See the [whitepaper]_ for further information. Parameters ---------- shape : sequence of int, optional Shape of the space, in voxels. kwargs : Keyword arguments to pass to `uniform_discr` to modify the space, e.g. use a...
Below is the the instruction that describes the task: ### Input: Default reconstruction space for the Elekta Icon CBCT. See the [whitepaper]_ for further information. Parameters ---------- shape : sequence of int, optional Shape of the space, in voxels. kwargs : Keyword argumen...
def get_vehicle(vehicle_id): ''' Return a single vehicle ''' result = _get(vehicle_id, settings.VEHICLES) return Vehicle(result.content)
Return a single vehicle
Below is the the instruction that describes the task: ### Input: Return a single vehicle ### Response: def get_vehicle(vehicle_id): ''' Return a single vehicle ''' result = _get(vehicle_id, settings.VEHICLES) return Vehicle(result.content)
def css(self, css): """ Finds another node by a CSS selector relative to the current node. """ return [self.get_node_factory().create(node_id) for node_id in self._get_css_ids(css).split(",") if node_id]
Finds another node by a CSS selector relative to the current node.
Below is the the instruction that describes the task: ### Input: Finds another node by a CSS selector relative to the current node. ### Response: def css(self, css): """ Finds another node by a CSS selector relative to the current node. """ return [self.get_node_factory().create(node_id) for no...
def flip(self): '''Flip the DNA - swap the top and bottom strands. :returns: Flipped DNA (bottom strand is now top strand, etc.). :rtype: coral.DNA ''' copy = self.copy() copy.top, copy.bottom = copy.bottom, copy.top copy.features = [_flip_feature(f, len(self)) ...
Flip the DNA - swap the top and bottom strands. :returns: Flipped DNA (bottom strand is now top strand, etc.). :rtype: coral.DNA
Below is the the instruction that describes the task: ### Input: Flip the DNA - swap the top and bottom strands. :returns: Flipped DNA (bottom strand is now top strand, etc.). :rtype: coral.DNA ### Response: def flip(self): '''Flip the DNA - swap the top and bottom strands. :retur...
def time_to_first_byte(self): """ Time to first byte of the page request in ms """ # The unknown page is just a placeholder for entries with no page ID. # As such, it would not have a TTFB if self.page_id == 'unknown': return None ttfb = 0 for ...
Time to first byte of the page request in ms
Below is the the instruction that describes the task: ### Input: Time to first byte of the page request in ms ### Response: def time_to_first_byte(self): """ Time to first byte of the page request in ms """ # The unknown page is just a placeholder for entries with no page ID. ...
def readRGB(self): """ Read a RGB color """ self.reset_bits_pending(); r = self.readUI8() g = self.readUI8() b = self.readUI8() return (0xff << 24) | (r << 16) | (g << 8) | b
Read a RGB color
Below is the the instruction that describes the task: ### Input: Read a RGB color ### Response: def readRGB(self): """ Read a RGB color """ self.reset_bits_pending(); r = self.readUI8() g = self.readUI8() b = self.readUI8() return (0xff << 24) | (r << 16) | (g << 8) ...
def load_config(name, base='conf'): """Load config dict from JSON""" fname = pjoin(base, name + '.json') if not os.path.exists(fname): return {} try: with open(fname) as f: cfg = json.load(f) except Exception as e: warn("Couldn't load %s: %s" % (fname, e)) ...
Load config dict from JSON
Below is the the instruction that describes the task: ### Input: Load config dict from JSON ### Response: def load_config(name, base='conf'): """Load config dict from JSON""" fname = pjoin(base, name + '.json') if not os.path.exists(fname): return {} try: with open(fname) as f: ...
def subjects(self): """ Return identifiers for all the subjects that are in the cache. :return: list of subject identifiers """ subj = [i["subject_id"] for i in self._cache.find()] return list(set(subj))
Return identifiers for all the subjects that are in the cache. :return: list of subject identifiers
Below is the the instruction that describes the task: ### Input: Return identifiers for all the subjects that are in the cache. :return: list of subject identifiers ### Response: def subjects(self): """ Return identifiers for all the subjects that are in the cache. :return: list of subjec...
def spin_thread(self, interval=1): """call Client.spin() in a background thread on some regular interval This helps ensure that messages don't pile up too much in the zmq queue while you are working on other things, or just leaving an idle terminal. It also helps limit ...
call Client.spin() in a background thread on some regular interval This helps ensure that messages don't pile up too much in the zmq queue while you are working on other things, or just leaving an idle terminal. It also helps limit potential padding of the `received` timestamp ...
Below is the the instruction that describes the task: ### Input: call Client.spin() in a background thread on some regular interval This helps ensure that messages don't pile up too much in the zmq queue while you are working on other things, or just leaving an idle terminal. ...
def unwrap(tensor): """Returns the underlying tensor if tensor is wrapped or tensor. Args: tensor: The tensor to unwrap. Returns: Tensor or if it is a pretty tensor, the unwrapped version. Raises: ValueError: if tensor holds a sequence. """ while isinstance(tensor, (PrettyTensor, Loss)): te...
Returns the underlying tensor if tensor is wrapped or tensor. Args: tensor: The tensor to unwrap. Returns: Tensor or if it is a pretty tensor, the unwrapped version. Raises: ValueError: if tensor holds a sequence.
Below is the the instruction that describes the task: ### Input: Returns the underlying tensor if tensor is wrapped or tensor. Args: tensor: The tensor to unwrap. Returns: Tensor or if it is a pretty tensor, the unwrapped version. Raises: ValueError: if tensor holds a sequence. ### Response: def...
def fuzzyload(self, cachedir=None, partial_cfgstr='', **kwargs): """ Try and load from a partially specified configuration string """ valid_targets = self.glob_valid_targets(cachedir, partial_cfgstr) if len(valid_targets) != 1: import utool as ut msg = 'ne...
Try and load from a partially specified configuration string
Below is the the instruction that describes the task: ### Input: Try and load from a partially specified configuration string ### Response: def fuzzyload(self, cachedir=None, partial_cfgstr='', **kwargs): """ Try and load from a partially specified configuration string """ valid_tar...
def import_sql_table(connection_url, table, username, password, columns=None, optimize=True, fetch_mode=None): """ Import SQL table to H2OFrame in memory. Assumes that the SQL table is not being updated and is stable. Runs multiple SELECT SQL queries concurrently for parallel ingestion. Be sure to ...
Import SQL table to H2OFrame in memory. Assumes that the SQL table is not being updated and is stable. Runs multiple SELECT SQL queries concurrently for parallel ingestion. Be sure to start the h2o.jar in the terminal with your downloaded JDBC driver in the classpath:: java -cp <path_to_h2o_jar>:<...
Below is the the instruction that describes the task: ### Input: Import SQL table to H2OFrame in memory. Assumes that the SQL table is not being updated and is stable. Runs multiple SELECT SQL queries concurrently for parallel ingestion. Be sure to start the h2o.jar in the terminal with your downloaded...
def _process_event(event: Event, sdp_state: SDPState, service_states: List[ServiceState]): """Process a SDP state change event.""" LOG.debug('Event detected! (id : "%s", type: "%s", data: "%s")', event.object_id, event.type, event.data) if event.object_id == 'SDP' and event...
Process a SDP state change event.
Below is the the instruction that describes the task: ### Input: Process a SDP state change event. ### Response: def _process_event(event: Event, sdp_state: SDPState, service_states: List[ServiceState]): """Process a SDP state change event.""" LOG.debug('Event detected! (id : "%s", type:...
def bind(self, container, method_name): """ Get an instance of this Entrypoint to bind to `container` with `method_name`. """ instance = super(Entrypoint, self).bind(container) instance.method_name = method_name return instance
Get an instance of this Entrypoint to bind to `container` with `method_name`.
Below is the the instruction that describes the task: ### Input: Get an instance of this Entrypoint to bind to `container` with `method_name`. ### Response: def bind(self, container, method_name): """ Get an instance of this Entrypoint to bind to `container` with `method_name`. """ ...
def task_webhook(fun): """Decorator turning a function into a task webhook. If an exception is raised within the function, the decorated function catches this and returns an error JSON response, otherwise it returns the result as a JSON response. Example: .. code-block:: python @tas...
Decorator turning a function into a task webhook. If an exception is raised within the function, the decorated function catches this and returns an error JSON response, otherwise it returns the result as a JSON response. Example: .. code-block:: python @task_webhook def add(requ...
Below is the the instruction that describes the task: ### Input: Decorator turning a function into a task webhook. If an exception is raised within the function, the decorated function catches this and returns an error JSON response, otherwise it returns the result as a JSON response. Example: ...
def confd_state_ha_mode(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") ha = ET.SubElement(confd_state, "ha") mode = ET.SubElement(ha, "mode") ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def confd_state_ha_mode(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd...
def avgwaittime_get(self, service_staff_id, start_date, end_date, session): '''taobao.wangwang.eservice.avgwaittime.get 平均等待时长 根据客服ID和日期,获取该客服"当日接待的所有客户的平均等待时长"。 备注: - 1、如果是操作者ID=被查者ID,返回被查者ID的"当日接待的所有客户的平均等待时长"。 - 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"当日接待的所有客户的平均等待时长"。 ...
taobao.wangwang.eservice.avgwaittime.get 平均等待时长 根据客服ID和日期,获取该客服"当日接待的所有客户的平均等待时长"。 备注: - 1、如果是操作者ID=被查者ID,返回被查者ID的"当日接待的所有客户的平均等待时长"。 - 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"当日接待的所有客户的平均等待时长"。 - 3、如果操作者是主账户,他可以查询所有子帐号的"当日接待的所有客户的平均等待时长"。 - 4、被查者ID可以是多个,用 "," 隔开,id数不能...
Below is the the instruction that describes the task: ### Input: taobao.wangwang.eservice.avgwaittime.get 平均等待时长 根据客服ID和日期,获取该客服"当日接待的所有客户的平均等待时长"。 备注: - 1、如果是操作者ID=被查者ID,返回被查者ID的"当日接待的所有客户的平均等待时长"。 - 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"当日接待的所有客户的平均等待时长"。 - 3、如果操作者是主账户,...
def Create(self, parent, id, evtHandler): "Called to create the control, which must derive from wxControl." self._tc = wx.ComboBox(parent, id, "", (100, 50)) self.SetControl(self._tc) # pushing a different event handler instead evtHandler: self._tc.PushEventHandler(w...
Called to create the control, which must derive from wxControl.
Below is the the instruction that describes the task: ### Input: Called to create the control, which must derive from wxControl. ### Response: def Create(self, parent, id, evtHandler): "Called to create the control, which must derive from wxControl." self._tc = wx.ComboBox(parent, id, "",...
def _legacy_status(stat): """Legacy status method from the 'qsmobile.js' library. Pass in the 'val' from &devices or the 'data' received after calling a specific ID. """ # 2d0c00002a0000 if stat[:2] == '30' or stat[:2] == '47': # RX1 CT ooo = stat[4:5] # console.log("legstat. "...
Legacy status method from the 'qsmobile.js' library. Pass in the 'val' from &devices or the 'data' received after calling a specific ID.
Below is the the instruction that describes the task: ### Input: Legacy status method from the 'qsmobile.js' library. Pass in the 'val' from &devices or the 'data' received after calling a specific ID. ### Response: def _legacy_status(stat): """Legacy status method from the 'qsmobile.js' library. ...
def sharedInterfaces(): """ This attribute is the public interface for code which wishes to discover the list of interfaces allowed by this Share. It is a list of Interface objects. """ def get(self): if not self.sharedInterfaceNames: return (...
This attribute is the public interface for code which wishes to discover the list of interfaces allowed by this Share. It is a list of Interface objects.
Below is the the instruction that describes the task: ### Input: This attribute is the public interface for code which wishes to discover the list of interfaces allowed by this Share. It is a list of Interface objects. ### Response: def sharedInterfaces(): """ This attribute is the...
def main(): """ main method """ # initialize parser usage = "usage: %prog [-u USER] [-p PASSWORD] [-t TITLE] [-s selection] url" parser = OptionParser(usage, version="%prog "+instapaperlib.__version__) parser.add_option("-u", "--user", action="store", dest="user", m...
main method
Below is the the instruction that describes the task: ### Input: main method ### Response: def main(): """ main method """ # initialize parser usage = "usage: %prog [-u USER] [-p PASSWORD] [-t TITLE] [-s selection] url" parser = OptionParser(usage, version="%prog "+instapaperlib.__versi...
def obj_to_file(obj, filename, filetype='auto', ndarray_to_list=False, squeeze=True): '''Writes annotation in file. :param filetype: auto yaml pkl, pickle pklz, picklezip :param ndarray_to_list: convert ndarrays in obj to lists :param squeeze: squeeze ndarray ''' ...
Writes annotation in file. :param filetype: auto yaml pkl, pickle pklz, picklezip :param ndarray_to_list: convert ndarrays in obj to lists :param squeeze: squeeze ndarray
Below is the the instruction that describes the task: ### Input: Writes annotation in file. :param filetype: auto yaml pkl, pickle pklz, picklezip :param ndarray_to_list: convert ndarrays in obj to lists :param squeeze: squeeze ndarray ### Response: def obj_to_file(obj,...
def title(self): """ Returns the title for this axis. :return <str> """ if not self._title: return projex.text.pretty(self.name()) return self._title
Returns the title for this axis. :return <str>
Below is the the instruction that describes the task: ### Input: Returns the title for this axis. :return <str> ### Response: def title(self): """ Returns the title for this axis. :return <str> """ if not self._title: re...
def predict(self, dataset, new_observation_data=None, new_user_data=None, new_item_data=None): """ Return a score prediction for the user ids and item ids in the provided data set. Parameters ---------- dataset : SFrame Dataset in the same for...
Return a score prediction for the user ids and item ids in the provided data set. Parameters ---------- dataset : SFrame Dataset in the same form used for training. new_observation_data : SFrame, optional ``new_observation_data`` gives additional observa...
Below is the the instruction that describes the task: ### Input: Return a score prediction for the user ids and item ids in the provided data set. Parameters ---------- dataset : SFrame Dataset in the same form used for training. new_observation_data : SFrame, o...
def _init_dates(self): """Initialize all dates properties """ if self.total_transactions == 0: return None self.epoch_start = Result.select(Result.epoch).order_by(Result.epoch.asc()).limit(1).get().epoch self.epoch_finish = Result.select(Result.epoch).order_by(Result....
Initialize all dates properties
Below is the the instruction that describes the task: ### Input: Initialize all dates properties ### Response: def _init_dates(self): """Initialize all dates properties """ if self.total_transactions == 0: return None self.epoch_start = Result.select(Result.epoch).order_...
def swap_buffers(self): """ Swap buffers, set viewport, trigger events and increment frame counter """ self.widget.swapBuffers() self.set_default_viewport() self.app.processEvents() self.frames += 1
Swap buffers, set viewport, trigger events and increment frame counter
Below is the the instruction that describes the task: ### Input: Swap buffers, set viewport, trigger events and increment frame counter ### Response: def swap_buffers(self): """ Swap buffers, set viewport, trigger events and increment frame counter """ self.widget.swapBuffers() ...
def device_gen(chain, urls): """Device object generator.""" itr = iter(urls) last = next(itr) for url in itr: yield Device(chain, make_hop_info_from_url(last), driver_name='jumphost', is_target=False) last = url yield Device(chain, make_hop_info_from_url(last), driver_name='generic',...
Device object generator.
Below is the the instruction that describes the task: ### Input: Device object generator. ### Response: def device_gen(chain, urls): """Device object generator.""" itr = iter(urls) last = next(itr) for url in itr: yield Device(chain, make_hop_info_from_url(last), driver_name='jumphost', is_...
def verifyAccount(self, subject, vendorSpecific=None): """See Also: verifyAccountResponse() Args: subject: vendorSpecific: Returns: """ response = self.verifyAccountResponse(subject, vendorSpecific) return self._read_boolean_response(response)
See Also: verifyAccountResponse() Args: subject: vendorSpecific: Returns:
Below is the the instruction that describes the task: ### Input: See Also: verifyAccountResponse() Args: subject: vendorSpecific: Returns: ### Response: def verifyAccount(self, subject, vendorSpecific=None): """See Also: verifyAccountResponse() Args: ...
def sflow_collector_use_vrf(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") sflow = ET.SubElement(config, "sflow", xmlns="urn:brocade.com:mgmt:brocade-sflow") collector = ET.SubElement(sflow, "collector") collector_ip_address_key = ET.SubElement(...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def sflow_collector_use_vrf(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") sflow = ET.SubElement(config, "sflow", xmlns="urn:brocade.com:mgmt:brocade-sflow")...
def render_tree(tree, list_all=True, show_only=None, frozen=False, exclude=None): """Convert tree to string representation :param dict tree: the package tree :param bool list_all: whether to list all the pgks at the root level or only those that are the s...
Convert tree to string representation :param dict tree: the package tree :param bool list_all: whether to list all the pgks at the root level or only those that are the sub-dependencies :param set show_only: set of select packages to be shown in the ...
Below is the the instruction that describes the task: ### Input: Convert tree to string representation :param dict tree: the package tree :param bool list_all: whether to list all the pgks at the root level or only those that are the sub-dependencies ...
def export_intermediate_certificate(self, filename=None): """ Export the intermediate certificate. Returned certificate will be in string format. If filename is provided, the certificate will also be saved to the file specified. :raises CertificateExportError: error expo...
Export the intermediate certificate. Returned certificate will be in string format. If filename is provided, the certificate will also be saved to the file specified. :raises CertificateExportError: error exporting certificate, can occur if no intermediate certificate is ava...
Below is the the instruction that describes the task: ### Input: Export the intermediate certificate. Returned certificate will be in string format. If filename is provided, the certificate will also be saved to the file specified. :raises CertificateExportError: error exporting cer...
def _collapse_device(self, node, flat): """Collapse device hierarchy into a flat folder.""" items = [item for branch in node.branches for item in self._collapse_device(branch, flat) if item] show_all = not flat or self._quickmenu_actions == 'all...
Collapse device hierarchy into a flat folder.
Below is the the instruction that describes the task: ### Input: Collapse device hierarchy into a flat folder. ### Response: def _collapse_device(self, node, flat): """Collapse device hierarchy into a flat folder.""" items = [item for branch in node.branches for it...
def _parse(self, msg): """ Parses a Scratch message and returns a tuple with the first element as the message type, and the second element as the message payload. The payload for a 'broadcast' message is a string, and the payload for a 'sensor-update' message is a dict whose ke...
Parses a Scratch message and returns a tuple with the first element as the message type, and the second element as the message payload. The payload for a 'broadcast' message is a string, and the payload for a 'sensor-update' message is a dict whose keys are variables, and values are up...
Below is the the instruction that describes the task: ### Input: Parses a Scratch message and returns a tuple with the first element as the message type, and the second element as the message payload. The payload for a 'broadcast' message is a string, and the payload for a 'sensor-update' ...
def duplicate(self, contributor=None): """Duplicate (make a copy).""" if self.status not in [self.STATUS_DONE, self.STATUS_ERROR]: raise ValidationError('Data object must have done or error status to be duplicated') duplicate = Data.objects.get(id=self.id) duplicate.pk = Non...
Duplicate (make a copy).
Below is the the instruction that describes the task: ### Input: Duplicate (make a copy). ### Response: def duplicate(self, contributor=None): """Duplicate (make a copy).""" if self.status not in [self.STATUS_DONE, self.STATUS_ERROR]: raise ValidationError('Data object must have done or...
def _convert(self, test_record_obj): """Convert and cache a test record to a mfg-inspector proto.""" if self._cached_proto is None: self._cached_proto = self._converter(test_record_obj) return self._cached_proto
Convert and cache a test record to a mfg-inspector proto.
Below is the the instruction that describes the task: ### Input: Convert and cache a test record to a mfg-inspector proto. ### Response: def _convert(self, test_record_obj): """Convert and cache a test record to a mfg-inspector proto.""" if self._cached_proto is None: self._cached_proto = self._conv...
def cov2corr(cov): """Calculate the correlation matrix based on a covariance matrix Parameters ---------- cov: 2D array Returns ------- corr: 2D array correlation converted from the covarince matrix """ assert cov.ndim == 2, 'covariance matrix should be 2D array...
Calculate the correlation matrix based on a covariance matrix Parameters ---------- cov: 2D array Returns ------- corr: 2D array correlation converted from the covarince matrix
Below is the the instruction that describes the task: ### Input: Calculate the correlation matrix based on a covariance matrix Parameters ---------- cov: 2D array Returns ------- corr: 2D array correlation converted from the covarince matrix ### Response: def cov2corr(co...
def parse_name_string(full_name): """ Parse a full name into a Name object :param full_name: e.g. "John Smith" or "Smith, John" :return: Name object """ name = Name() if "," in full_name: toks = full_name.split(",") name.family = toks[0] name.given = ",".join(toks[1:...
Parse a full name into a Name object :param full_name: e.g. "John Smith" or "Smith, John" :return: Name object
Below is the the instruction that describes the task: ### Input: Parse a full name into a Name object :param full_name: e.g. "John Smith" or "Smith, John" :return: Name object ### Response: def parse_name_string(full_name): """ Parse a full name into a Name object :param full_name: e.g. "John...
def load_file_ui(self): """ Loads user chosen file(s) into **Script_Editor_tabWidget** Widget tab Model editor(s). :return: Method success. :rtype: bool :note: May require user interaction. """ editor = self.get_current_editor() file = editor and editor...
Loads user chosen file(s) into **Script_Editor_tabWidget** Widget tab Model editor(s). :return: Method success. :rtype: bool :note: May require user interaction.
Below is the the instruction that describes the task: ### Input: Loads user chosen file(s) into **Script_Editor_tabWidget** Widget tab Model editor(s). :return: Method success. :rtype: bool :note: May require user interaction. ### Response: def load_file_ui(self): """ Load...
def htmlDocContentDumpOutput(self, buf, encoding): """Dump an HTML document. Formating return/spaces are added. """ if buf is None: buf__o = None else: buf__o = buf._o libxml2mod.htmlDocContentDumpOutput(buf__o, self._o, encoding)
Dump an HTML document. Formating return/spaces are added.
Below is the the instruction that describes the task: ### Input: Dump an HTML document. Formating return/spaces are added. ### Response: def htmlDocContentDumpOutput(self, buf, encoding): """Dump an HTML document. Formating return/spaces are added. """ if buf is None: buf__o = None else: bu...
def coalesce(self, numPartitions, shuffle=False): """ Return a new RDD that is reduced into `numPartitions` partitions. >>> sc.parallelize([1, 2, 3, 4, 5], 3).glom().collect() [[1], [2, 3], [4, 5]] >>> sc.parallelize([1, 2, 3, 4, 5], 3).coalesce(1).glom().collect() [[1, ...
Return a new RDD that is reduced into `numPartitions` partitions. >>> sc.parallelize([1, 2, 3, 4, 5], 3).glom().collect() [[1], [2, 3], [4, 5]] >>> sc.parallelize([1, 2, 3, 4, 5], 3).coalesce(1).glom().collect() [[1, 2, 3, 4, 5]]
Below is the the instruction that describes the task: ### Input: Return a new RDD that is reduced into `numPartitions` partitions. >>> sc.parallelize([1, 2, 3, 4, 5], 3).glom().collect() [[1], [2, 3], [4, 5]] >>> sc.parallelize([1, 2, 3, 4, 5], 3).coalesce(1).glom().collect() [[1, 2...
def roots(self): """The list of word roots. Ambiguous cases are separated with pipe character by default. Use :py:meth:`~estnltk.text.Text.get_analysis_element` to specify custom separator for ambiguous entries. """ if not self.is_tagged(ANALYSIS): self.tag_analysis(...
The list of word roots. Ambiguous cases are separated with pipe character by default. Use :py:meth:`~estnltk.text.Text.get_analysis_element` to specify custom separator for ambiguous entries.
Below is the the instruction that describes the task: ### Input: The list of word roots. Ambiguous cases are separated with pipe character by default. Use :py:meth:`~estnltk.text.Text.get_analysis_element` to specify custom separator for ambiguous entries. ### Response: def roots(self): ""...
def is_isolated(self, p_id): """ Returns True iff the given node has no incoming or outgoing edges. """ return(len(self.incoming_neighbors(p_id)) == 0 and len(self.outgoing_neighbors(p_id)) == 0)
Returns True iff the given node has no incoming or outgoing edges.
Below is the the instruction that describes the task: ### Input: Returns True iff the given node has no incoming or outgoing edges. ### Response: def is_isolated(self, p_id): """ Returns True iff the given node has no incoming or outgoing edges. """ return(len(self.incoming_neighbor...
def check_webhook_validation(app_configs=None, **kwargs): """ Check that DJSTRIPE_WEBHOOK_VALIDATION is valid """ from . import settings as djstripe_settings messages = [] validation_options = ("verify_signature", "retrieve_event") if djstripe_settings.WEBHOOK_VALIDATION is None: messages.append( checks....
Check that DJSTRIPE_WEBHOOK_VALIDATION is valid
Below is the the instruction that describes the task: ### Input: Check that DJSTRIPE_WEBHOOK_VALIDATION is valid ### Response: def check_webhook_validation(app_configs=None, **kwargs): """ Check that DJSTRIPE_WEBHOOK_VALIDATION is valid """ from . import settings as djstripe_settings messages = [] validati...
def cpt2seg(file_name, sym=False, discrete=False): """Reads a .cpt palette and returns a segmented colormap. sym : If True, the returned colormap contains the palette and a mirrored copy. For example, a blue-red-green palette would return a blue-red-green-green-red-blue colormap. discrete : If t...
Reads a .cpt palette and returns a segmented colormap. sym : If True, the returned colormap contains the palette and a mirrored copy. For example, a blue-red-green palette would return a blue-red-green-green-red-blue colormap. discrete : If true, the returned colormap has a fixed number of uniform co...
Below is the the instruction that describes the task: ### Input: Reads a .cpt palette and returns a segmented colormap. sym : If True, the returned colormap contains the palette and a mirrored copy. For example, a blue-red-green palette would return a blue-red-green-green-red-blue colormap. discr...
def can(self, event): """ returns a list of states that can result from processing this event """ return [t.new_state for t in self._transitions if t.event.equals(event)]
returns a list of states that can result from processing this event
Below is the the instruction that describes the task: ### Input: returns a list of states that can result from processing this event ### Response: def can(self, event): """ returns a list of states that can result from processing this event """ return [t.new_state for t in self._tra...
def filter_labels(sent: Sequence[str], labels: Set[str] = None) -> List[str]: """ Returns only the tokens present in the sentence that are in labels.""" if labels: return [tok for tok in sent if tok in labels] return list(sent)
Returns only the tokens present in the sentence that are in labels.
Below is the the instruction that describes the task: ### Input: Returns only the tokens present in the sentence that are in labels. ### Response: def filter_labels(sent: Sequence[str], labels: Set[str] = None) -> List[str]: """ Returns only the tokens present in the sentence that are in labels.""" if lab...
def t_STRING(self, t): r'"[^"\n]*"' t.endlexpos = t.lexpos + len(t.value) return t
r'"[^"\n]*"
Below is the the instruction that describes the task: ### Input: r'"[^"\n]*" ### Response: def t_STRING(self, t): r'"[^"\n]*"' t.endlexpos = t.lexpos + len(t.value) return t
def rpc_get_num_names_cumulative( self, **con_info ): """ Get the number of names that have ever existed Return {'status': True, 'count': count} on success Return {'error': ...} on error """ db = get_db_state(self.working_dir) num_names = db.get_num_names(include_...
Get the number of names that have ever existed Return {'status': True, 'count': count} on success Return {'error': ...} on error
Below is the the instruction that describes the task: ### Input: Get the number of names that have ever existed Return {'status': True, 'count': count} on success Return {'error': ...} on error ### Response: def rpc_get_num_names_cumulative( self, **con_info ): """ Get the number of...
def storage_get(attribute=None, storage_id=None): """Get storage attributes""" _args = ['storage-get', '--format=json'] if storage_id: _args.extend(('-s', storage_id)) if attribute: _args.append(attribute) try: return json.loads(subprocess.check_output(_args).decode('UTF-8'))...
Get storage attributes
Below is the the instruction that describes the task: ### Input: Get storage attributes ### Response: def storage_get(attribute=None, storage_id=None): """Get storage attributes""" _args = ['storage-get', '--format=json'] if storage_id: _args.extend(('-s', storage_id)) if attribute: ...
def describe_reserved_instances_offerings(DryRun=None, ReservedInstancesOfferingIds=None, InstanceType=None, AvailabilityZone=None, ProductDescription=None, Filters=None, InstanceTenancy=None, OfferingType=None, NextToken=None, MaxResults=None, IncludeMarketplace=None, MinDuration=None, MaxDuration=None, MaxInstanceCou...
Describes Reserved Instance offerings that are available for purchase. With Reserved Instances, you purchase the right to launch instances for a period of time. During that time period, you do not receive insufficient capacity errors, and you pay a lower usage rate than the rate charged for On-Demand instances for the ...
Below is the the instruction that describes the task: ### Input: Describes Reserved Instance offerings that are available for purchase. With Reserved Instances, you purchase the right to launch instances for a period of time. During that time period, you do not receive insufficient capacity errors, and you pay a lo...
def get_group_by_class(self, definition): """ intantiates the processing class (Direct or Grouped) and returns it. """ group_by = definition["group"] series = definition["series"] if "formatter" in definition: formatter = {group_by: definition["formatter"]...
intantiates the processing class (Direct or Grouped) and returns it.
Below is the the instruction that describes the task: ### Input: intantiates the processing class (Direct or Grouped) and returns it. ### Response: def get_group_by_class(self, definition): """ intantiates the processing class (Direct or Grouped) and returns it. """ group_by = d...
def delete_resource(self, resource): """ Deletes the resource from the pool and destroys the associated resource. Not usually needed by users of the pool, but called internally when BadResource is raised. :param resource: the resource to remove :type resource: Resource ...
Deletes the resource from the pool and destroys the associated resource. Not usually needed by users of the pool, but called internally when BadResource is raised. :param resource: the resource to remove :type resource: Resource
Below is the the instruction that describes the task: ### Input: Deletes the resource from the pool and destroys the associated resource. Not usually needed by users of the pool, but called internally when BadResource is raised. :param resource: the resource to remove :type resource...
def writelog(logfile, contentlist, mode='replace'): # type: (AnyStr, Union[AnyStr, List[AnyStr], Tuple[AnyStr]], AnyStr) -> None """write log""" if logfile is None: # If logfile is not assigned, just print msg. print(UtilClass.print_msg(contentlist)) else: if os....
write log
Below is the the instruction that describes the task: ### Input: write log ### Response: def writelog(logfile, contentlist, mode='replace'): # type: (AnyStr, Union[AnyStr, List[AnyStr], Tuple[AnyStr]], AnyStr) -> None """write log""" if logfile is None: # If logfile is not assigned, just p...
def list_to_tree(cls, files): """Converts a list of filenames into a directory tree structure.""" def attach(branch, trunk): """Insert a branch of directories on its trunk.""" parts = branch.split('/', 1) if len(parts) == 1: # branch is a file trunk[...
Converts a list of filenames into a directory tree structure.
Below is the the instruction that describes the task: ### Input: Converts a list of filenames into a directory tree structure. ### Response: def list_to_tree(cls, files): """Converts a list of filenames into a directory tree structure.""" def attach(branch, trunk): """Insert a branch o...
def get_region(self, x1, y1, x2, y2): '''Get an image that refers to the given rectangle within this image. The image data is not actually copied; if the image region is rendered into, it will affect this image. :param int x1: left edge of the image region to return :param int y1: top ...
Get an image that refers to the given rectangle within this image. The image data is not actually copied; if the image region is rendered into, it will affect this image. :param int x1: left edge of the image region to return :param int y1: top edge of the image region to return :param...
Below is the the instruction that describes the task: ### Input: Get an image that refers to the given rectangle within this image. The image data is not actually copied; if the image region is rendered into, it will affect this image. :param int x1: left edge of the image region to return ...
def input_fn(is_training, data_dir, batch_size, num_epochs=1, num_gpus=None, dtype=tf.float32): """Input function which provides batches for train or eval. Args: is_training: A boolean denoting whether the input is for training. data_dir: The directory containing the input data. batch_size...
Input function which provides batches for train or eval. Args: is_training: A boolean denoting whether the input is for training. data_dir: The directory containing the input data. batch_size: The number of samples per batch. num_epochs: The number of epochs to repeat the dataset. num_gpus: The n...
Below is the the instruction that describes the task: ### Input: Input function which provides batches for train or eval. Args: is_training: A boolean denoting whether the input is for training. data_dir: The directory containing the input data. batch_size: The number of samples per batch. num_ep...
def parse_vep_header(vcf_obj): """Return a list with the VEP header The vep header is collected from CSQ in the vcf file All keys are capitalized Args: vcf_obj(cyvcf2.VCF) Returns: vep_header(list) """ vep_header = [] if 'CSQ' in vcf_obj: # Thi...
Return a list with the VEP header The vep header is collected from CSQ in the vcf file All keys are capitalized Args: vcf_obj(cyvcf2.VCF) Returns: vep_header(list)
Below is the the instruction that describes the task: ### Input: Return a list with the VEP header The vep header is collected from CSQ in the vcf file All keys are capitalized Args: vcf_obj(cyvcf2.VCF) Returns: vep_header(list) ### Response: def parse_vep_header(vcf_...
def remove_alert(thing_name, key, session=None): """Remove an alert for the given thing """ return _request('get', '/remove/alert/for/{0}'.format(thing_name), params={'key': key}, session=session)
Remove an alert for the given thing
Below is the the instruction that describes the task: ### Input: Remove an alert for the given thing ### Response: def remove_alert(thing_name, key, session=None): """Remove an alert for the given thing """ return _request('get', '/remove/alert/for/{0}'.format(thing_name), params={'key': key}, session=...
def gravatar_url(user_or_email, size=GRAVATAR_DEFAULT_SIZE): """ Builds a gravatar url from an user or email """ if hasattr(user_or_email, 'email'): email = user_or_email.email else: email = user_or_email try: return escape(get_gravatar_url(email=email, size=size)) except: ...
Builds a gravatar url from an user or email
Below is the the instruction that describes the task: ### Input: Builds a gravatar url from an user or email ### Response: def gravatar_url(user_or_email, size=GRAVATAR_DEFAULT_SIZE): """ Builds a gravatar url from an user or email """ if hasattr(user_or_email, 'email'): email = user_or_email.email...
def destroy(name, call=None): ''' To destroy a VM from the VMware environment CLI Example: .. code-block:: bash salt-cloud -d vmname salt-cloud --destroy vmname salt-cloud -a destroy vmname ''' if call == 'function': raise SaltCloudSystemExit( 'The ...
To destroy a VM from the VMware environment CLI Example: .. code-block:: bash salt-cloud -d vmname salt-cloud --destroy vmname salt-cloud -a destroy vmname
Below is the the instruction that describes the task: ### Input: To destroy a VM from the VMware environment CLI Example: .. code-block:: bash salt-cloud -d vmname salt-cloud --destroy vmname salt-cloud -a destroy vmname ### Response: def destroy(name, call=None): ''' To ...
def delete_events(self, event_collection, params): """ Deletes events via the Keen IO API. A master key must be set first. :param event_collection: string, the event collection from which event are being deleted """ url = "{0}/{1}/projects/{2}/events/{3}".format(self.base_url,...
Deletes events via the Keen IO API. A master key must be set first. :param event_collection: string, the event collection from which event are being deleted
Below is the the instruction that describes the task: ### Input: Deletes events via the Keen IO API. A master key must be set first. :param event_collection: string, the event collection from which event are being deleted ### Response: def delete_events(self, event_collection, params): """ ...
def get_type_data(name): """Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type """ name = name.upper() try: return { 'authority': 'birdland.mit.edu', 'namespace': 'time format', 'identifier': name, ...
Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type
Below is the the instruction that describes the task: ### Input: Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type ### Response: def get_type_data(name): """Return dictionary representation of type. Can be used to initialize primordium.type.primitives...
def extract_session_details(request_headers, session_header, secret_key): ''' a method to extract and validate jwt session token from request headers :param request_headers: dictionary with header fields from request :param session_header: string with name of session token header key :p...
a method to extract and validate jwt session token from request headers :param request_headers: dictionary with header fields from request :param session_header: string with name of session token header key :param secret_key: string with secret key to json web token encryption :return: dictionary ...
Below is the the instruction that describes the task: ### Input: a method to extract and validate jwt session token from request headers :param request_headers: dictionary with header fields from request :param session_header: string with name of session token header key :param secret_key: string w...
def run(): """This client generates a similarity graph from features in PE Files.""" # Grab server args args = client_helper.grab_server_args() # Start up workbench connection workbench = zerorpc.Client(timeout=300, heartbeat=60) workbench.connect('tcp://'+args['server']+':'+args['port']) ...
This client generates a similarity graph from features in PE Files.
Below is the the instruction that describes the task: ### Input: This client generates a similarity graph from features in PE Files. ### Response: def run(): """This client generates a similarity graph from features in PE Files.""" # Grab server args args = client_helper.grab_server_args() # Star...
def _get_original_site(structure, site): """Private convenience method for get_nn_info, gives original site index from ProvidedPeriodicSite.""" for i, s in enumerate(structure): if site.is_periodic_image(s): return i raise Exception('Site not found!')
Private convenience method for get_nn_info, gives original site index from ProvidedPeriodicSite.
Below is the the instruction that describes the task: ### Input: Private convenience method for get_nn_info, gives original site index from ProvidedPeriodicSite. ### Response: def _get_original_site(structure, site): """Private convenience method for get_nn_info, gives original site index f...
def extract_polygon_area(self, pid, polygon_points): """Extract all data points whose element centroid lies within the given polygon. Parameters ---------- Returns ------- """ polygon = shapgeo.Polygon(polygon_points) xy = self.grid.get_element_c...
Extract all data points whose element centroid lies within the given polygon. Parameters ---------- Returns -------
Below is the the instruction that describes the task: ### Input: Extract all data points whose element centroid lies within the given polygon. Parameters ---------- Returns ------- ### Response: def extract_polygon_area(self, pid, polygon_points): """Extract all da...