code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def output(self, pin, value): """Set the specified pin the provided high/low value. Value should be either HIGH/LOW or a boolean (true = high).""" if pin < 0 or pin > 15: raise ValueError('Pin must be between 0 and 15 (inclusive).') self._output_pin(pin, value) self....
Set the specified pin the provided high/low value. Value should be either HIGH/LOW or a boolean (true = high).
Below is the the instruction that describes the task: ### Input: Set the specified pin the provided high/low value. Value should be either HIGH/LOW or a boolean (true = high). ### Response: def output(self, pin, value): """Set the specified pin the provided high/low value. Value should be ...
def group_and_sort_statements(stmt_list, ev_totals=None): """Group statements by type and arguments, and sort by prevalence. Parameters ---------- stmt_list : list[Statement] A list of INDRA statements. ev_totals : dict{int: int} A dictionary, keyed by statement hash (shallow) with ...
Group statements by type and arguments, and sort by prevalence. Parameters ---------- stmt_list : list[Statement] A list of INDRA statements. ev_totals : dict{int: int} A dictionary, keyed by statement hash (shallow) with counts of total evidence as the values. Including this wi...
Below is the the instruction that describes the task: ### Input: Group statements by type and arguments, and sort by prevalence. Parameters ---------- stmt_list : list[Statement] A list of INDRA statements. ev_totals : dict{int: int} A dictionary, keyed by statement hash (shallow) w...
def great_circle_distance(self, other): """ Return the great-circle distance, in meters, from this geographic coordinates to the specified other point, i.e., the shortest distance over the earth’s surface, ‘as-the-crow-flies’ distance between the points, ignoring any natural elev...
Return the great-circle distance, in meters, from this geographic coordinates to the specified other point, i.e., the shortest distance over the earth’s surface, ‘as-the-crow-flies’ distance between the points, ignoring any natural elevations of the ground. Haversine formula:: ...
Below is the the instruction that describes the task: ### Input: Return the great-circle distance, in meters, from this geographic coordinates to the specified other point, i.e., the shortest distance over the earth’s surface, ‘as-the-crow-flies’ distance between the points, ignoring any nat...
def get_eval_metrics(logits, labels, params): """Return dictionary of model evaluation metrics.""" metrics = { "accuracy": _convert_to_eval_metric(padded_accuracy)(logits, labels), "accuracy_top5": _convert_to_eval_metric(padded_accuracy_top5)( logits, labels), "accuracy_per_sequence": _...
Return dictionary of model evaluation metrics.
Below is the the instruction that describes the task: ### Input: Return dictionary of model evaluation metrics. ### Response: def get_eval_metrics(logits, labels, params): """Return dictionary of model evaluation metrics.""" metrics = { "accuracy": _convert_to_eval_metric(padded_accuracy)(logits, labels)...
def enbw(data): r"""Computes the equivalent noise bandwidth .. math:: ENBW = N \frac{\sum_{n=1}^{N} w_n^2}{\left(\sum_{n=1}^{N} w_n \right)^2} .. doctest:: >>> from spectrum import create_window, enbw >>> w = create_window(64, 'rectangular') >>> enbw(w) 1.0 The follow...
r"""Computes the equivalent noise bandwidth .. math:: ENBW = N \frac{\sum_{n=1}^{N} w_n^2}{\left(\sum_{n=1}^{N} w_n \right)^2} .. doctest:: >>> from spectrum import create_window, enbw >>> w = create_window(64, 'rectangular') >>> enbw(w) 1.0 The following table contains t...
Below is the the instruction that describes the task: ### Input: r"""Computes the equivalent noise bandwidth .. math:: ENBW = N \frac{\sum_{n=1}^{N} w_n^2}{\left(\sum_{n=1}^{N} w_n \right)^2} .. doctest:: >>> from spectrum import create_window, enbw >>> w = create_window(64, 'rectangular'...
def spherical_histogram(data=None, radial_bins="numpy", theta_bins=16, phi_bins=16, transformed=False, *args, **kwargs): """Facade construction function for the SphericalHistogram. """ dropna = kwargs.pop("dropna", True) data = _prepare_data(data, transformed=transformed, klass=SphericalHistogram, dro...
Facade construction function for the SphericalHistogram.
Below is the the instruction that describes the task: ### Input: Facade construction function for the SphericalHistogram. ### Response: def spherical_histogram(data=None, radial_bins="numpy", theta_bins=16, phi_bins=16, transformed=False, *args, **kwargs): """Facade construction function for the SphericalHisto...
def _convert_operator(self, node_name, op_name, attrs, inputs): """Convert from onnx operator to mxnet operator. The converter must specify conversions explicitly for incompatible name, and apply handlers to operator attributes. Parameters ---------- :param node_name : s...
Convert from onnx operator to mxnet operator. The converter must specify conversions explicitly for incompatible name, and apply handlers to operator attributes. Parameters ---------- :param node_name : str name of the node to be translated. :param op_name : ...
Below is the the instruction that describes the task: ### Input: Convert from onnx operator to mxnet operator. The converter must specify conversions explicitly for incompatible name, and apply handlers to operator attributes. Parameters ---------- :param node_name : str ...
def default_software_reset_type(self, reset_type): """! @brief Modify the default software reset method. @param self @param reset_type Must be one of the software reset types: Target.ResetType.SW_SYSRESETREQ, Target.ResetType.SW_VECTRESET, or Target.ResetType.SW_EMULATED. """...
! @brief Modify the default software reset method. @param self @param reset_type Must be one of the software reset types: Target.ResetType.SW_SYSRESETREQ, Target.ResetType.SW_VECTRESET, or Target.ResetType.SW_EMULATED.
Below is the the instruction that describes the task: ### Input: ! @brief Modify the default software reset method. @param self @param reset_type Must be one of the software reset types: Target.ResetType.SW_SYSRESETREQ, Target.ResetType.SW_VECTRESET, or Target.ResetType.SW_EMULATED. ### ...
def get_choices_for(self, field): """ Get the choices for the given fields. Args: field (str): Name of field. Returns: List of tuples. [(name, value),...] """ choices = self._fields[field].choices if isinstance(choices, six.string_types):...
Get the choices for the given fields. Args: field (str): Name of field. Returns: List of tuples. [(name, value),...]
Below is the the instruction that describes the task: ### Input: Get the choices for the given fields. Args: field (str): Name of field. Returns: List of tuples. [(name, value),...] ### Response: def get_choices_for(self, field): """ Get the choices for the...
def set_time(self, vfy_time): """ Set the time against which the certificates are verified. Normally the current time is used. .. note:: For example, you can determine if a certificate was valid at a given time. .. versionadded:: 17.0.0 :param dat...
Set the time against which the certificates are verified. Normally the current time is used. .. note:: For example, you can determine if a certificate was valid at a given time. .. versionadded:: 17.0.0 :param datetime vfy_time: The verification time to set on th...
Below is the the instruction that describes the task: ### Input: Set the time against which the certificates are verified. Normally the current time is used. .. note:: For example, you can determine if a certificate was valid at a given time. .. versionadded:: 17.0.0 ...
def default_username_algo(email): """Generate username for the Django user. :arg str/unicode email: the email address to use to generate a username :returns: str/unicode """ # bluntly stolen from django-browserid # store the username as a base64 encoded sha224 of the email address # this ...
Generate username for the Django user. :arg str/unicode email: the email address to use to generate a username :returns: str/unicode
Below is the the instruction that describes the task: ### Input: Generate username for the Django user. :arg str/unicode email: the email address to use to generate a username :returns: str/unicode ### Response: def default_username_algo(email): """Generate username for the Django user. :arg str...
def push_new_themes(catalog, portal_url, apikey): """Toma un catálogo y escribe los temas de la taxonomía que no están presentes. Args: catalog (DataJson): El catálogo de origen que contiene la taxonomía. portal_url (str): La URL del portal CKAN de destino. ...
Toma un catálogo y escribe los temas de la taxonomía que no están presentes. Args: catalog (DataJson): El catálogo de origen que contiene la taxonomía. portal_url (str): La URL del portal CKAN de destino. apikey (str): La apikey de un usuario con los perm...
Below is the the instruction that describes the task: ### Input: Toma un catálogo y escribe los temas de la taxonomía que no están presentes. Args: catalog (DataJson): El catálogo de origen que contiene la taxonomía. portal_url (str): La URL del portal CKAN de de...
def vecs_to_datmesh(x, y): """ Converts input arguments x and y to a 2d meshgrid, suitable for calling Means, Covariances and Realizations. """ x, y = meshgrid(x, y) out = zeros(x.shape + (2,), dtype=float) out[:, :, 0] = x out[:, :, 1] = y return out
Converts input arguments x and y to a 2d meshgrid, suitable for calling Means, Covariances and Realizations.
Below is the the instruction that describes the task: ### Input: Converts input arguments x and y to a 2d meshgrid, suitable for calling Means, Covariances and Realizations. ### Response: def vecs_to_datmesh(x, y): """ Converts input arguments x and y to a 2d meshgrid, suitable for calling Means, C...
def get_nonoauth_parameters(self): """Get any non-OAuth parameters.""" return dict([(k, v) for k, v in self.items() if not k.startswith('oauth_')])
Get any non-OAuth parameters.
Below is the the instruction that describes the task: ### Input: Get any non-OAuth parameters. ### Response: def get_nonoauth_parameters(self): """Get any non-OAuth parameters.""" return dict([(k, v) for k, v in self.items() if not k.startswith('oauth_')])
def _row_to_str(self, row): # type: (List[str]) -> str """Converts a list of strings to a correctly spaced and formatted row string. e.g. ['some', 'foo', 'bar'] --> '| some | foo | bar |' :param row: list :return: str """ _row_text = '' ...
Converts a list of strings to a correctly spaced and formatted row string. e.g. ['some', 'foo', 'bar'] --> '| some | foo | bar |' :param row: list :return: str
Below is the the instruction that describes the task: ### Input: Converts a list of strings to a correctly spaced and formatted row string. e.g. ['some', 'foo', 'bar'] --> '| some | foo | bar |' :param row: list :return: str ### Response: def _row_to_str(self, row): ...
def qos(self, prefetch_size=0, prefetch_count=0, is_global=False): ''' Set QoS on this channel. ''' args = Writer() args.write_long(prefetch_size).\ write_short(prefetch_count).\ write_bit(is_global) self.send_frame(MethodFrame(self.channel_id, 60,...
Set QoS on this channel.
Below is the the instruction that describes the task: ### Input: Set QoS on this channel. ### Response: def qos(self, prefetch_size=0, prefetch_count=0, is_global=False): ''' Set QoS on this channel. ''' args = Writer() args.write_long(prefetch_size).\ write_shor...
def kw_changelist_view(self, request: HttpRequest, extra_context=None, **kw): """ Changelist view which allow key-value arguments. :param request: HttpRequest :param extra_context: Extra context dict :param kw: Key-value dict :return: See changelist_view() """ ...
Changelist view which allow key-value arguments. :param request: HttpRequest :param extra_context: Extra context dict :param kw: Key-value dict :return: See changelist_view()
Below is the the instruction that describes the task: ### Input: Changelist view which allow key-value arguments. :param request: HttpRequest :param extra_context: Extra context dict :param kw: Key-value dict :return: See changelist_view() ### Response: def kw_changelist_view(self, ...
def setCurrentProfile(self, prof): """ Sets the current profile for this toolbar to the inputed profile. :param prof | <projexui.widgets.xviewwidget.XViewProfile> || <str> """ if prof is None: self.clearActive() return ...
Sets the current profile for this toolbar to the inputed profile. :param prof | <projexui.widgets.xviewwidget.XViewProfile> || <str>
Below is the the instruction that describes the task: ### Input: Sets the current profile for this toolbar to the inputed profile. :param prof | <projexui.widgets.xviewwidget.XViewProfile> || <str> ### Response: def setCurrentProfile(self, prof): """ Sets the current profi...
def clear_annotation_data(self): """Clear annotation data. Parameters ---------- Returns ------- None """ self.genes = set() self.annotations = [] self.term_annotations = {} self.gene_annotations = {}
Clear annotation data. Parameters ---------- Returns ------- None
Below is the the instruction that describes the task: ### Input: Clear annotation data. Parameters ---------- Returns ------- None ### Response: def clear_annotation_data(self): """Clear annotation data. Parameters ---------- Returns ...
def fast_maxwell_boltzmann(mass, file_name=None, return_code=False): r"""Return a function that returns values of a Maxwell-Boltzmann distribution. >>> from fast import Atom >>> mass = Atom("Rb", 87).mass >>> f = fast_maxwell_boltzmann(mass) >>> print f(0, 273.15+20) ...
r"""Return a function that returns values of a Maxwell-Boltzmann distribution. >>> from fast import Atom >>> mass = Atom("Rb", 87).mass >>> f = fast_maxwell_boltzmann(mass) >>> print f(0, 273.15+20) 0.00238221482739 >>> import numpy as np >>> v = np.linspace(-600, 600, 101) >>> dis...
Below is the the instruction that describes the task: ### Input: r"""Return a function that returns values of a Maxwell-Boltzmann distribution. >>> from fast import Atom >>> mass = Atom("Rb", 87).mass >>> f = fast_maxwell_boltzmann(mass) >>> print f(0, 273.15+20) 0.00238221482739 >>> i...
def deserialize(self, xml_input, *args, **kwargs): """ Convert XML to dict object """ return xmltodict.parse(xml_input, *args, **kwargs)
Convert XML to dict object
Below is the the instruction that describes the task: ### Input: Convert XML to dict object ### Response: def deserialize(self, xml_input, *args, **kwargs): """ Convert XML to dict object """ return xmltodict.parse(xml_input, *args, **kwargs)
def cmd_join(self, connection, sender, target, payload): """ Asks the bot to join a channel """ if payload: connection.join(payload) else: raise ValueError("No channel given")
Asks the bot to join a channel
Below is the the instruction that describes the task: ### Input: Asks the bot to join a channel ### Response: def cmd_join(self, connection, sender, target, payload): """ Asks the bot to join a channel """ if payload: connection.join(payload) else: ra...
def sqliteRowsToDicts(sqliteRows): """ Unpacks sqlite rows as returned by fetchall into an array of simple dicts. :param sqliteRows: array of rows returned from fetchall DB call :return: array of dicts, keyed by the column names. """ return map(lambda r: dict(zip(r.keys(), r)), sqliteRows)
Unpacks sqlite rows as returned by fetchall into an array of simple dicts. :param sqliteRows: array of rows returned from fetchall DB call :return: array of dicts, keyed by the column names.
Below is the the instruction that describes the task: ### Input: Unpacks sqlite rows as returned by fetchall into an array of simple dicts. :param sqliteRows: array of rows returned from fetchall DB call :return: array of dicts, keyed by the column names. ### Response: def sqliteRowsToDicts(sqliteRow...
def make_strain_from_inj_object(self, inj, delta_t, detector_name, distance_scale=1): """Make a h(t) strain time-series from an injection object as read from an hdf file. Parameters ----------- inj : injection object The injection ...
Make a h(t) strain time-series from an injection object as read from an hdf file. Parameters ----------- inj : injection object The injection object to turn into a strain h(t). delta_t : float Sample rate to make injection at. detector_name : stri...
Below is the the instruction that describes the task: ### Input: Make a h(t) strain time-series from an injection object as read from an hdf file. Parameters ----------- inj : injection object The injection object to turn into a strain h(t). delta_t : float ...
def acoustic_similarity_directories(directories, analysis_function, distance_function, stop_check=None, call_back=None, multiprocessing=True): """ Analyze many directories. Parameters ---------- directories : list of str List of fully specified paths to the directories to be analyzed "...
Analyze many directories. Parameters ---------- directories : list of str List of fully specified paths to the directories to be analyzed
Below is the the instruction that describes the task: ### Input: Analyze many directories. Parameters ---------- directories : list of str List of fully specified paths to the directories to be analyzed ### Response: def acoustic_similarity_directories(directories, analysis_function, distance_...
def clear(self): """ convinience function to empty this fastrun container """ self.prop_dt_map = dict() self.prop_data = dict() self.rev_lookup = defaultdict(set)
convinience function to empty this fastrun container
Below is the the instruction that describes the task: ### Input: convinience function to empty this fastrun container ### Response: def clear(self): """ convinience function to empty this fastrun container """ self.prop_dt_map = dict() self.prop_data = dict() self.re...
def flush_all(self, conn): """Its effect is to invalidate all existing items immediately""" command = b'flush_all\r\n' response = yield from self._execute_simple_command( conn, command) if const.OK != response: raise ClientException('Memcached flush_all failed', ...
Its effect is to invalidate all existing items immediately
Below is the the instruction that describes the task: ### Input: Its effect is to invalidate all existing items immediately ### Response: def flush_all(self, conn): """Its effect is to invalidate all existing items immediately""" command = b'flush_all\r\n' response = yield from self._execut...
def spearmanr(x, y): """ Michiel de Hoon's library (available in BioPython or standalone as PyCluster) returns Spearman rsb which does include a tie correction. >>> x = [5.05, 6.75, 3.21, 2.66] >>> y = [1.65, 26.5, -5.93, 7.96] >>> z = [1.65, 2.64, 2.64, 6.95] >>> round(spearmanr(x, y), 4) ...
Michiel de Hoon's library (available in BioPython or standalone as PyCluster) returns Spearman rsb which does include a tie correction. >>> x = [5.05, 6.75, 3.21, 2.66] >>> y = [1.65, 26.5, -5.93, 7.96] >>> z = [1.65, 2.64, 2.64, 6.95] >>> round(spearmanr(x, y), 4) 0.4 >>> round(spearmanr(x...
Below is the the instruction that describes the task: ### Input: Michiel de Hoon's library (available in BioPython or standalone as PyCluster) returns Spearman rsb which does include a tie correction. >>> x = [5.05, 6.75, 3.21, 2.66] >>> y = [1.65, 26.5, -5.93, 7.96] >>> z = [1.65, 2.64, 2.64, 6.95...
def get_profiles(self): """Returns set of profile names referenced in this Feature :returns: set of profile names """ out = set(x.profile for x in self.requires if x.profile) out.update(x.profile for x in self.removes if x.profile) return out
Returns set of profile names referenced in this Feature :returns: set of profile names
Below is the the instruction that describes the task: ### Input: Returns set of profile names referenced in this Feature :returns: set of profile names ### Response: def get_profiles(self): """Returns set of profile names referenced in this Feature :returns: set of profile names "...
def group_dashboard(request, group_slug): """Dashboard for managing a TenantGroup.""" groups = get_user_groups(request.user) group = get_object_or_404(groups, slug=group_slug) tenants = get_user_tenants(request.user, group) can_edit_group = request.user.has_perm('multitenancy.change_tenantgroup', gr...
Dashboard for managing a TenantGroup.
Below is the the instruction that describes the task: ### Input: Dashboard for managing a TenantGroup. ### Response: def group_dashboard(request, group_slug): """Dashboard for managing a TenantGroup.""" groups = get_user_groups(request.user) group = get_object_or_404(groups, slug=group_slug) tenant...
def broadcast(self, event): """Broadcasts an event either to all users or clients, depending on event flag""" try: if event.broadcasttype == "users": if len(self._users) > 0: self.log("Broadcasting to all users:", event...
Broadcasts an event either to all users or clients, depending on event flag
Below is the the instruction that describes the task: ### Input: Broadcasts an event either to all users or clients, depending on event flag ### Response: def broadcast(self, event): """Broadcasts an event either to all users or clients, depending on event flag""" try: i...
def BTC(cpu, dest, src): """ Bit test and complement. Selects the bit in a bit string (specified with the first operand, called the bit base) at the bit-position designated by the bit offset operand (second operand), stores the value of the bit in the CF flag, and complements ...
Bit test and complement. Selects the bit in a bit string (specified with the first operand, called the bit base) at the bit-position designated by the bit offset operand (second operand), stores the value of the bit in the CF flag, and complements the selected bit in the bit string. ...
Below is the the instruction that describes the task: ### Input: Bit test and complement. Selects the bit in a bit string (specified with the first operand, called the bit base) at the bit-position designated by the bit offset operand (second operand), stores the value of the bit in the CF ...
def get(self, date=datetime.date.today(), country=None): """ Get the CPI value for a specific time. Defaults to today. This uses the closest method internally but sets limit to one day. """ if not country: country = self.country if country == "all": ...
Get the CPI value for a specific time. Defaults to today. This uses the closest method internally but sets limit to one day.
Below is the the instruction that describes the task: ### Input: Get the CPI value for a specific time. Defaults to today. This uses the closest method internally but sets limit to one day. ### Response: def get(self, date=datetime.date.today(), country=None): """ Get the CPI value for a sp...
def check(f): """ Wraps the function with a decorator that runs all of the pre/post conditions. """ if hasattr(f, 'wrapped_fn'): return f else: @wraps(f) def decorated(*args, **kwargs): return check_conditions(f, args, kwargs) decorated.wrapped_fn = f ...
Wraps the function with a decorator that runs all of the pre/post conditions.
Below is the the instruction that describes the task: ### Input: Wraps the function with a decorator that runs all of the pre/post conditions. ### Response: def check(f): """ Wraps the function with a decorator that runs all of the pre/post conditions. """ if hasattr(f, 'wrapped_fn'): ...
def upload(self, file_path, timeout=-1): """ Upload an SPP ISO image file or a hotfix file to the appliance. The API supports upload of one hotfix at a time into the system. For the successful upload of a hotfix, ensure its original name and extension are not altered. Args: ...
Upload an SPP ISO image file or a hotfix file to the appliance. The API supports upload of one hotfix at a time into the system. For the successful upload of a hotfix, ensure its original name and extension are not altered. Args: file_path: Full path to firmware. timeout...
Below is the the instruction that describes the task: ### Input: Upload an SPP ISO image file or a hotfix file to the appliance. The API supports upload of one hotfix at a time into the system. For the successful upload of a hotfix, ensure its original name and extension are not altered. Ar...
def _load_wm_map(exclude_auto=None): """Load an ontology map for world models. exclude_auto : None or list[tuple] A list of ontology mappings for which automated mappings should be excluded, e.g. [(HUME, UN)] would result in not using mappings from HUME to UN. """ exclude_auto =...
Load an ontology map for world models. exclude_auto : None or list[tuple] A list of ontology mappings for which automated mappings should be excluded, e.g. [(HUME, UN)] would result in not using mappings from HUME to UN.
Below is the the instruction that describes the task: ### Input: Load an ontology map for world models. exclude_auto : None or list[tuple] A list of ontology mappings for which automated mappings should be excluded, e.g. [(HUME, UN)] would result in not using mappings from HUME to UN. #...
def unregister_transform(self, node_class, transform, predicate=None): """Unregister the given transform.""" self.transforms[node_class].remove((transform, predicate))
Unregister the given transform.
Below is the the instruction that describes the task: ### Input: Unregister the given transform. ### Response: def unregister_transform(self, node_class, transform, predicate=None): """Unregister the given transform.""" self.transforms[node_class].remove((transform, predicate))
def cwd_filt2(depth): """Return the last depth elements of the current working directory. $HOME is always replaced with '~'. If depth==0, the full path is returned.""" full_cwd = os.getcwdu() cwd = full_cwd.replace(HOME,"~").split(os.sep) if '~' in cwd and len(cwd) == depth+1: depth +=...
Return the last depth elements of the current working directory. $HOME is always replaced with '~'. If depth==0, the full path is returned.
Below is the the instruction that describes the task: ### Input: Return the last depth elements of the current working directory. $HOME is always replaced with '~'. If depth==0, the full path is returned. ### Response: def cwd_filt2(depth): """Return the last depth elements of the current working dire...
def cancel(self): """ Cancels an event in Exchange. :: event = service.calendar().get_event(id='KEY HERE') event.cancel() This will send notifications to anyone who has not declined the meeting. """ if not self.id: raise TypeError(u"You can't delete an event that hasn't been...
Cancels an event in Exchange. :: event = service.calendar().get_event(id='KEY HERE') event.cancel() This will send notifications to anyone who has not declined the meeting.
Below is the the instruction that describes the task: ### Input: Cancels an event in Exchange. :: event = service.calendar().get_event(id='KEY HERE') event.cancel() This will send notifications to anyone who has not declined the meeting. ### Response: def cancel(self): """ Cancels an...
def recovery(self, using=None, **kwargs): """ The indices recovery API provides insight into on-going shard recoveries for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.recovery`` unchanged. """ return self._get_connection(...
The indices recovery API provides insight into on-going shard recoveries for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.recovery`` unchanged.
Below is the the instruction that describes the task: ### Input: The indices recovery API provides insight into on-going shard recoveries for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.recovery`` unchanged. ### Response: def recovery(self, using=N...
def getLabelByName(self, name): """Gets a label widget by it component name :param name: name of the AbstractStimulusComponent which this label is named after :type name: str :returns: :class:`DragLabel<sparkle.gui.drag_label.DragLabel>` """ name = name.lower() i...
Gets a label widget by it component name :param name: name of the AbstractStimulusComponent which this label is named after :type name: str :returns: :class:`DragLabel<sparkle.gui.drag_label.DragLabel>`
Below is the the instruction that describes the task: ### Input: Gets a label widget by it component name :param name: name of the AbstractStimulusComponent which this label is named after :type name: str :returns: :class:`DragLabel<sparkle.gui.drag_label.DragLabel>` ### Response: def getL...
def _gen_doc(cls, summary, full_name, identifier, example_call, doc_str, show_examples): """Generate the documentation docstring for a PlotMethod""" # leave out the first argument example_call = ', '.join(map(str.strip, example_call.split(',')[1:])) ret = docstrings.dede...
Generate the documentation docstring for a PlotMethod
Below is the the instruction that describes the task: ### Input: Generate the documentation docstring for a PlotMethod ### Response: def _gen_doc(cls, summary, full_name, identifier, example_call, doc_str, show_examples): """Generate the documentation docstring for a PlotMethod""" ...
def parse_name_altree(record): """Parse NAME structure assuming ALTREE dialect. In ALTREE dialect maiden name (if present) is saved as SURN sub-record and is also appended to family name in parens. Given name is saved in GIVN sub-record. Few examples: No maiden name: 1 NAME John /Smith/ ...
Parse NAME structure assuming ALTREE dialect. In ALTREE dialect maiden name (if present) is saved as SURN sub-record and is also appended to family name in parens. Given name is saved in GIVN sub-record. Few examples: No maiden name: 1 NAME John /Smith/ 2 GIVN John With maiden na...
Below is the the instruction that describes the task: ### Input: Parse NAME structure assuming ALTREE dialect. In ALTREE dialect maiden name (if present) is saved as SURN sub-record and is also appended to family name in parens. Given name is saved in GIVN sub-record. Few examples: No maiden name:...
def _coerce_json_to_collection(self, json_repr): """Use to ensure that a JSON string (if found) is parsed to the equivalent dict in python. If the incoming value is already parsed, do nothing. If a string fails to parse, return None.""" if isinstance(json_repr, dict): collection = js...
Use to ensure that a JSON string (if found) is parsed to the equivalent dict in python. If the incoming value is already parsed, do nothing. If a string fails to parse, return None.
Below is the the instruction that describes the task: ### Input: Use to ensure that a JSON string (if found) is parsed to the equivalent dict in python. If the incoming value is already parsed, do nothing. If a string fails to parse, return None. ### Response: def _coerce_json_to_collection(self, json_repr...
def getDirectory(*args): """ Normalizes the getDirectory method between the different Qt wrappers. :return (<str> filename, <bool> accepted) """ result = QtGui.QFileDialog.getDirectory(*args) # PyQt4 returns just a string if...
Normalizes the getDirectory method between the different Qt wrappers. :return (<str> filename, <bool> accepted)
Below is the the instruction that describes the task: ### Input: Normalizes the getDirectory method between the different Qt wrappers. :return (<str> filename, <bool> accepted) ### Response: def getDirectory(*args): """ Normalizes the getDirectory method between th...
def get_configuration_set_by_id(self, id): '''Finds a configuration set in the component by its ID. @param id The ID of the configuration set to search for. @return The ConfigurationSet object for the set, or None if it was not found. ''' for cs in self.configuration_se...
Finds a configuration set in the component by its ID. @param id The ID of the configuration set to search for. @return The ConfigurationSet object for the set, or None if it was not found.
Below is the the instruction that describes the task: ### Input: Finds a configuration set in the component by its ID. @param id The ID of the configuration set to search for. @return The ConfigurationSet object for the set, or None if it was not found. ### Response: def get_configuration_...
def onBatchRejected(self, ledger_id): """ A batch of requests has been rejected, if stateRoot is None, reject the current batch. :param ledger_id: :param stateRoot: state root after the batch was created :return: """ if ledger_id == POOL_LEDGER_ID: ...
A batch of requests has been rejected, if stateRoot is None, reject the current batch. :param ledger_id: :param stateRoot: state root after the batch was created :return:
Below is the the instruction that describes the task: ### Input: A batch of requests has been rejected, if stateRoot is None, reject the current batch. :param ledger_id: :param stateRoot: state root after the batch was created :return: ### Response: def onBatchRejected(self, ledger_...
def getR(self, i=5, j=6): """ return transport matrix element, indexed by i, j, be default, return dispersion value, i.e. getR(5,6) in [m] :param i: row index, with initial index of 1 :param j: col indx, with initial index of 1 :return: transport matrix element """ ...
return transport matrix element, indexed by i, j, be default, return dispersion value, i.e. getR(5,6) in [m] :param i: row index, with initial index of 1 :param j: col indx, with initial index of 1 :return: transport matrix element
Below is the the instruction that describes the task: ### Input: return transport matrix element, indexed by i, j, be default, return dispersion value, i.e. getR(5,6) in [m] :param i: row index, with initial index of 1 :param j: col indx, with initial index of 1 :return: transport m...
def dynamic_content_item_variant_delete(self, item_id, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/dynamic_content#delete-variant" api_path = "/api/v2/dynamic_content/items/{item_id}/variants/{id}.json" api_path = api_path.format(item_id=item_id, id=id) return self.c...
https://developer.zendesk.com/rest_api/docs/core/dynamic_content#delete-variant
Below is the the instruction that describes the task: ### Input: https://developer.zendesk.com/rest_api/docs/core/dynamic_content#delete-variant ### Response: def dynamic_content_item_variant_delete(self, item_id, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/dynamic_content#delete-varia...
def _read_linguas_from_files(env, linguas_files=None): """ Parse `LINGUAS` file and return list of extracted languages """ import SCons.Util import SCons.Environment global _re_comment global _re_lang if not SCons.Util.is_List(linguas_files) \ and not SCons.Util.is_String(linguas_fil...
Parse `LINGUAS` file and return list of extracted languages
Below is the the instruction that describes the task: ### Input: Parse `LINGUAS` file and return list of extracted languages ### Response: def _read_linguas_from_files(env, linguas_files=None): """ Parse `LINGUAS` file and return list of extracted languages """ import SCons.Util import SCons.Environmen...
def winsorize(x, axis=0, limits=0.01): """ `Winsorize <https://en.wikipedia.org/wiki/Winsorizing>`_ values based on limits """ # operate on copy x = x.copy() if isinstance(x, pd.DataFrame): return x.apply(_winsorize_wrapper, axis=axis, args=(limits, )) else: return pd.Series...
`Winsorize <https://en.wikipedia.org/wiki/Winsorizing>`_ values based on limits
Below is the the instruction that describes the task: ### Input: `Winsorize <https://en.wikipedia.org/wiki/Winsorizing>`_ values based on limits ### Response: def winsorize(x, axis=0, limits=0.01): """ `Winsorize <https://en.wikipedia.org/wiki/Winsorizing>`_ values based on limits """ # operate on ...
def AFF4Path(self, client_urn): """Returns the AFF4 URN this pathspec will be stored under. Args: client_urn: A ClientURN. Returns: A urn that corresponds to this pathspec. Raises: ValueError: If pathspec is not of the correct type. """ # If the first level is OS and the sec...
Returns the AFF4 URN this pathspec will be stored under. Args: client_urn: A ClientURN. Returns: A urn that corresponds to this pathspec. Raises: ValueError: If pathspec is not of the correct type.
Below is the the instruction that describes the task: ### Input: Returns the AFF4 URN this pathspec will be stored under. Args: client_urn: A ClientURN. Returns: A urn that corresponds to this pathspec. Raises: ValueError: If pathspec is not of the correct type. ### Response: def A...
def absent( name, force=False, region=None, key=None, keyid=None, profile=None, remove_lc=False): ''' Ensure the named autoscale group is deleted. name Name of the autoscale group. force Force deletion of autoscale group. rem...
Ensure the named autoscale group is deleted. name Name of the autoscale group. force Force deletion of autoscale group. remove_lc Delete the launch config as well. region The region to connect to. key Secret key to be used. keyid Access key t...
Below is the the instruction that describes the task: ### Input: Ensure the named autoscale group is deleted. name Name of the autoscale group. force Force deletion of autoscale group. remove_lc Delete the launch config as well. region The region to connect to. ...
def getBody(self, url, method='GET', headers={}, data=None, socket=None): """Make an HTTP request and return the body """ if not 'User-Agent' in headers: headers['User-Agent'] = ['Tensor HTTP checker'] return self.request(url, method, headers, data, socket)
Make an HTTP request and return the body
Below is the the instruction that describes the task: ### Input: Make an HTTP request and return the body ### Response: def getBody(self, url, method='GET', headers={}, data=None, socket=None): """Make an HTTP request and return the body """ if not 'User-Agent' in headers: head...
def requiv_contact_min(b, component, solve_for=None, **kwargs): """ Create a constraint to determine the critical (at L1) value of requiv at which a constact will underflow. This will only be used for contacts for requiv_min :parameter b: the :class:`phoebe.frontend.bundle.Bundle` :parameter s...
Create a constraint to determine the critical (at L1) value of requiv at which a constact will underflow. This will only be used for contacts for requiv_min :parameter b: the :class:`phoebe.frontend.bundle.Bundle` :parameter str component: the label of the star in which this constraint should ...
Below is the the instruction that describes the task: ### Input: Create a constraint to determine the critical (at L1) value of requiv at which a constact will underflow. This will only be used for contacts for requiv_min :parameter b: the :class:`phoebe.frontend.bundle.Bundle` :parameter str comp...
def authenticate(self): """ Authenticate against the HP Cloud Identity Service. This is the first step in any hpcloud.com session, although this method is automatically called when accessing higher-level methods/attributes. **Examples of Credentials Configuration** - B...
Authenticate against the HP Cloud Identity Service. This is the first step in any hpcloud.com session, although this method is automatically called when accessing higher-level methods/attributes. **Examples of Credentials Configuration** - Bare minimum for authentication using HP API ...
Below is the the instruction that describes the task: ### Input: Authenticate against the HP Cloud Identity Service. This is the first step in any hpcloud.com session, although this method is automatically called when accessing higher-level methods/attributes. **Examples of Credentials Con...
def frombed(args): """ %prog frombed bedfile contigfasta readfasta Convert read placement to contig format. This is useful before running BAMBUS. """ from jcvi.formats.fasta import Fasta from jcvi.formats.bed import Bed from jcvi.utils.cbook import fill p = OptionParser(frombed.__doc__...
%prog frombed bedfile contigfasta readfasta Convert read placement to contig format. This is useful before running BAMBUS.
Below is the the instruction that describes the task: ### Input: %prog frombed bedfile contigfasta readfasta Convert read placement to contig format. This is useful before running BAMBUS. ### Response: def frombed(args): """ %prog frombed bedfile contigfasta readfasta Convert read placement to co...
def is_instance_of(self, some_class): """Asserts that val is an instance of the given class.""" try: if not isinstance(self.val, some_class): if hasattr(self.val, '__name__'): t = self.val.__name__ elif hasattr(self.val, '__class__'): ...
Asserts that val is an instance of the given class.
Below is the the instruction that describes the task: ### Input: Asserts that val is an instance of the given class. ### Response: def is_instance_of(self, some_class): """Asserts that val is an instance of the given class.""" try: if not isinstance(self.val, some_class): ...
def _set_autobw_threshold_table_summary(self, v, load=False): """ Setter method for autobw_threshold_table_summary, mapped from YANG variable /mpls_state/autobw_threshold_table_summary (container) If this variable is read-only (config: false) in the source YANG file, then _set_autobw_threshold_table_sum...
Setter method for autobw_threshold_table_summary, mapped from YANG variable /mpls_state/autobw_threshold_table_summary (container) If this variable is read-only (config: false) in the source YANG file, then _set_autobw_threshold_table_summary is considered as a private method. Backends looking to populate t...
Below is the the instruction that describes the task: ### Input: Setter method for autobw_threshold_table_summary, mapped from YANG variable /mpls_state/autobw_threshold_table_summary (container) If this variable is read-only (config: false) in the source YANG file, then _set_autobw_threshold_table_summary ...
def get_token(self, hash): """ Looks up a token by hash Args: hash (UInt160): The token to look up Returns: SmartContractEvent: A smart contract event with a contract that is an NEP5 Token """ tokens_snapshot = self.db.prefixed_db(NotificationPref...
Looks up a token by hash Args: hash (UInt160): The token to look up Returns: SmartContractEvent: A smart contract event with a contract that is an NEP5 Token
Below is the the instruction that describes the task: ### Input: Looks up a token by hash Args: hash (UInt160): The token to look up Returns: SmartContractEvent: A smart contract event with a contract that is an NEP5 Token ### Response: def get_token(self, hash): ""...
def _AddEvent(self, event): """Adds an event. Args: event (EventObject): event. """ if hasattr(event, 'event_data_row_identifier'): event_data_identifier = identifiers.SQLTableIdentifier( self._CONTAINER_TYPE_EVENT_DATA, event.event_data_row_identifier) lookup_key ...
Adds an event. Args: event (EventObject): event.
Below is the the instruction that describes the task: ### Input: Adds an event. Args: event (EventObject): event. ### Response: def _AddEvent(self, event): """Adds an event. Args: event (EventObject): event. """ if hasattr(event, 'event_data_row_identifier'): event_data_iden...
async def traverse(self, func): """ Traverses an async function or generator, yielding each result. This function is private. The class should be used as an iterator instead of using this method. """ # this allows the reference to be stolen async_executor = self ...
Traverses an async function or generator, yielding each result. This function is private. The class should be used as an iterator instead of using this method.
Below is the the instruction that describes the task: ### Input: Traverses an async function or generator, yielding each result. This function is private. The class should be used as an iterator instead of using this method. ### Response: async def traverse(self, func): """ Traverses an as...
def load_texture(self, texture_version): ''' Expect a texture version number as an integer, load the texture version from /is/ps/shared/data/body/template/texture_coordinates/. Currently there are versions [0, 1, 2, 3] availiable. ''' import numpy as np lowres_tex_templat...
Expect a texture version number as an integer, load the texture version from /is/ps/shared/data/body/template/texture_coordinates/. Currently there are versions [0, 1, 2, 3] availiable.
Below is the the instruction that describes the task: ### Input: Expect a texture version number as an integer, load the texture version from /is/ps/shared/data/body/template/texture_coordinates/. Currently there are versions [0, 1, 2, 3] availiable. ### Response: def load_texture(self, texture_version): ...
def list(args): """Lists the jobs in the given database.""" jm = setup(args) jm.list(job_ids=get_ids(args.job_ids), print_array_jobs=args.print_array_jobs, print_dependencies=args.print_dependencies, status=args.status, long=args.long, print_times=args.print_times, ids_only=args.ids_only, names=args.names)
Lists the jobs in the given database.
Below is the the instruction that describes the task: ### Input: Lists the jobs in the given database. ### Response: def list(args): """Lists the jobs in the given database.""" jm = setup(args) jm.list(job_ids=get_ids(args.job_ids), print_array_jobs=args.print_array_jobs, print_dependencies=args.print_depend...
def do_lzop_get(creds, url, path, decrypt, do_retry): """ Get and decompress a URL This streams the content directly to lzop; the compressed version is never stored on disk. """ assert url.endswith('.lzo'), 'Expect an lzop-compressed file' with files.DeleteOnError(path) as decomp_out: ...
Get and decompress a URL This streams the content directly to lzop; the compressed version is never stored on disk.
Below is the the instruction that describes the task: ### Input: Get and decompress a URL This streams the content directly to lzop; the compressed version is never stored on disk. ### Response: def do_lzop_get(creds, url, path, decrypt, do_retry): """ Get and decompress a URL This streams th...
def split_by(self, layer, sep=' '): """Split the text into multiple instances defined by elements of given layer. The spans for layer elements are extracted and feed to :py:meth:`~estnltk.text.Text.split_given_spans` method. Parameters ---------- layer: str ...
Split the text into multiple instances defined by elements of given layer. The spans for layer elements are extracted and feed to :py:meth:`~estnltk.text.Text.split_given_spans` method. Parameters ---------- layer: str String determining the layer that is used to de...
Below is the the instruction that describes the task: ### Input: Split the text into multiple instances defined by elements of given layer. The spans for layer elements are extracted and feed to :py:meth:`~estnltk.text.Text.split_given_spans` method. Parameters ---------- l...
def locate_profile(profile='default'): """Find the path to the folder associated with a given profile. I.e. find $IPYTHONDIR/profile_whatever. """ from IPython.core.profiledir import ProfileDir, ProfileDirError try: pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile) ...
Find the path to the folder associated with a given profile. I.e. find $IPYTHONDIR/profile_whatever.
Below is the the instruction that describes the task: ### Input: Find the path to the folder associated with a given profile. I.e. find $IPYTHONDIR/profile_whatever. ### Response: def locate_profile(profile='default'): """Find the path to the folder associated with a given profile. I.e. find ...
def zone_helper(zone): """ Zone finder by name. If zone doesn't exist, create it and return the href :param str zone: name of zone (if href, will be returned as is) :return str href: href of zone """ if zone is None: return None elif isinstance(zone, Zone): return zone.h...
Zone finder by name. If zone doesn't exist, create it and return the href :param str zone: name of zone (if href, will be returned as is) :return str href: href of zone
Below is the the instruction that describes the task: ### Input: Zone finder by name. If zone doesn't exist, create it and return the href :param str zone: name of zone (if href, will be returned as is) :return str href: href of zone ### Response: def zone_helper(zone): """ Zone finder by name...
def stop_scan(self): """Stop to scan.""" try: self.bable.stop_scan(sync=True) except bable_interface.BaBLEException: # If we errored our it is because we were not currently scanning pass self.scanning = False
Stop to scan.
Below is the the instruction that describes the task: ### Input: Stop to scan. ### Response: def stop_scan(self): """Stop to scan.""" try: self.bable.stop_scan(sync=True) except bable_interface.BaBLEException: # If we errored our it is because we were not currently s...
def build_requirements(docs_path, package_name="yacms"): """ Updates the requirements file with yacms's version number. """ mezz_string = "yacms==" project_path = os.path.join(docs_path, "..") requirements_file = os.path.join(project_path, package_name, "proj...
Updates the requirements file with yacms's version number.
Below is the the instruction that describes the task: ### Input: Updates the requirements file with yacms's version number. ### Response: def build_requirements(docs_path, package_name="yacms"): """ Updates the requirements file with yacms's version number. """ mezz_string = "yacms==" project_p...
def forward(self, X): """Forward function. :param X: The input (batch) of the model contains word sequences for lstm, features and feature weights. :type X: For word sequences: a list of torch.Tensor pair (word sequence and word mask) of shape (batch_size, sequence_lengt...
Forward function. :param X: The input (batch) of the model contains word sequences for lstm, features and feature weights. :type X: For word sequences: a list of torch.Tensor pair (word sequence and word mask) of shape (batch_size, sequence_length). For features: tor...
Below is the the instruction that describes the task: ### Input: Forward function. :param X: The input (batch) of the model contains word sequences for lstm, features and feature weights. :type X: For word sequences: a list of torch.Tensor pair (word sequence and word mask) ...
def info(self): """ Print header information and other derived information. """ print("\n--- File Info ---") for key, val in self.file_header.items(): if key == 'src_raj': val = val.to_string(unit=u.hour, sep=':') if key == 'src_dej': val...
Print header information and other derived information.
Below is the the instruction that describes the task: ### Input: Print header information and other derived information. ### Response: def info(self): """ Print header information and other derived information. """ print("\n--- File Info ---") for key, val in self.file_header.items(): ...
def get_page_of_iterator(iterator, page_size, page_number): """ Get a page from an interator, handling invalid input from the page number by defaulting to the first page. """ try: page_number = validate_page_number(page_number) except (PageNotAnInteger, EmptyPage): page_number = ...
Get a page from an interator, handling invalid input from the page number by defaulting to the first page.
Below is the the instruction that describes the task: ### Input: Get a page from an interator, handling invalid input from the page number by defaulting to the first page. ### Response: def get_page_of_iterator(iterator, page_size, page_number): """ Get a page from an interator, handling invalid input ...
def mm_top1( n_items, data, initial_params=None, alpha=0.0, max_iter=10000, tol=1e-8): """Compute the ML estimate of model parameters using the MM algorithm. This function computes the maximum-likelihood (ML) estimate of model parameters given top-1 data (see :ref:`data-top1`), using the ...
Compute the ML estimate of model parameters using the MM algorithm. This function computes the maximum-likelihood (ML) estimate of model parameters given top-1 data (see :ref:`data-top1`), using the minorization-maximization (MM) algorithm [Hun04]_, [CD12]_. If ``alpha > 0``, the function returns the ...
Below is the the instruction that describes the task: ### Input: Compute the ML estimate of model parameters using the MM algorithm. This function computes the maximum-likelihood (ML) estimate of model parameters given top-1 data (see :ref:`data-top1`), using the minorization-maximization (MM) algorith...
def update_issue_remote_link_by_id(self, issue_key, link_id, url, title, global_id=None, relationship=None): """ Update existing Remote Link on Issue :param issue_key: str :param link_id: str :param url: str :param title: str :param global_id: str, OPTIONAL: ...
Update existing Remote Link on Issue :param issue_key: str :param link_id: str :param url: str :param title: str :param global_id: str, OPTIONAL: :param relationship: str, Optional. Default by built-in method: 'Web Link'
Below is the the instruction that describes the task: ### Input: Update existing Remote Link on Issue :param issue_key: str :param link_id: str :param url: str :param title: str :param global_id: str, OPTIONAL: :param relationship: str, Optional. Default by built-in m...
def update_reach_number_data(self): """ Update the reach number data for the namelist based on input files. .. warning:: You need to make sure you set *rapid_connect_file* and *riv_bas_id_file* before running this function. Example: .. code:: python ...
Update the reach number data for the namelist based on input files. .. warning:: You need to make sure you set *rapid_connect_file* and *riv_bas_id_file* before running this function. Example: .. code:: python from RAPIDpy import RAPID rapid_man...
Below is the the instruction that describes the task: ### Input: Update the reach number data for the namelist based on input files. .. warning:: You need to make sure you set *rapid_connect_file* and *riv_bas_id_file* before running this function. Example: .. code::...
def expand(self, url): """Expand implementation for Adf.ly Args: url: the URL you want to expand Returns: A string containing the expanded URL Raises: BadAPIResponseException: If the data is malformed or we got a bad status code on API re...
Expand implementation for Adf.ly Args: url: the URL you want to expand Returns: A string containing the expanded URL Raises: BadAPIResponseException: If the data is malformed or we got a bad status code on API response ShorteningError...
Below is the the instruction that describes the task: ### Input: Expand implementation for Adf.ly Args: url: the URL you want to expand Returns: A string containing the expanded URL Raises: BadAPIResponseException: If the data is malformed or we got a ba...
def get_anchor_point(self, anchor_name): """Return an anchor point of the node, if it exists.""" if anchor_name in self._possible_anchors: return TikZNodeAnchor(self.handle, anchor_name) else: try: anchor = int(anchor_name.split('_')[1]) excep...
Return an anchor point of the node, if it exists.
Below is the the instruction that describes the task: ### Input: Return an anchor point of the node, if it exists. ### Response: def get_anchor_point(self, anchor_name): """Return an anchor point of the node, if it exists.""" if anchor_name in self._possible_anchors: return TikZNodeAnc...
def correlation(T, obs1, obs2=None, times=(1), maxtime=None, k=None, ncv=None, return_times=False): r"""Time-correlation for equilibrium experiment. Parameters ---------- T : (M, M) ndarray or scipy.sparse matrix Transition matrix obs1 : (M,) ndarray Observable, represented as vecto...
r"""Time-correlation for equilibrium experiment. Parameters ---------- T : (M, M) ndarray or scipy.sparse matrix Transition matrix obs1 : (M,) ndarray Observable, represented as vector on state space obs2 : (M,) ndarray (optional) Second observable, for cross-correlations ...
Below is the the instruction that describes the task: ### Input: r"""Time-correlation for equilibrium experiment. Parameters ---------- T : (M, M) ndarray or scipy.sparse matrix Transition matrix obs1 : (M,) ndarray Observable, represented as vector on state space obs2 : (M,) nd...
def setup(self, phase, entry_pressure='', pore_volume='', throat_volume=''): r""" Set up the required parameters for the algorithm Parameters ---------- phase : OpenPNM Phase object The phase to be injected into the Network. The Phase must have the capil...
r""" Set up the required parameters for the algorithm Parameters ---------- phase : OpenPNM Phase object The phase to be injected into the Network. The Phase must have the capillary entry pressure values for the system. entry_pressure : string ...
Below is the the instruction that describes the task: ### Input: r""" Set up the required parameters for the algorithm Parameters ---------- phase : OpenPNM Phase object The phase to be injected into the Network. The Phase must have the capillary entry press...
def add_metadata(self, metadata_matrix, meta_index_store): ''' Returns a new corpus with a the metadata matrix and index store integrated. :param metadata_matrix: scipy.sparse matrix (# docs, # metadata) :param meta_index_store: IndexStore of metadata values :return: TermDocMatr...
Returns a new corpus with a the metadata matrix and index store integrated. :param metadata_matrix: scipy.sparse matrix (# docs, # metadata) :param meta_index_store: IndexStore of metadata values :return: TermDocMatrixWithoutCategories
Below is the the instruction that describes the task: ### Input: Returns a new corpus with a the metadata matrix and index store integrated. :param metadata_matrix: scipy.sparse matrix (# docs, # metadata) :param meta_index_store: IndexStore of metadata values :return: TermDocMatrixWithoutC...
def permission_set(self, name, func=None): """Define a new permission set (directly, or as a decorator). E.g.:: @authz.permission_set('HTTP') def is_http_perm(perm): return perm.startswith('http.') """ if func is None: return functoo...
Define a new permission set (directly, or as a decorator). E.g.:: @authz.permission_set('HTTP') def is_http_perm(perm): return perm.startswith('http.')
Below is the the instruction that describes the task: ### Input: Define a new permission set (directly, or as a decorator). E.g.:: @authz.permission_set('HTTP') def is_http_perm(perm): return perm.startswith('http.') ### Response: def permission_set(self, name, fun...
def clean(self): """ Cleans the data and throws ValidationError on failure """ errors = {} cleaned = {} for name, validator in self.validate_schema.items(): val = getattr(self, name, None) try: cleaned[name] = validator.to_python(val) ...
Cleans the data and throws ValidationError on failure
Below is the the instruction that describes the task: ### Input: Cleans the data and throws ValidationError on failure ### Response: def clean(self): """ Cleans the data and throws ValidationError on failure """ errors = {} cleaned = {} for name, validator in self.validate_schema.i...
def folderitem(self, obj, item, index): """Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by...
Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by the template :index: current i...
Below is the the instruction that describes the task: ### Input: Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the ob...
def inplace_filter(func, sequence): """ Like Python's filter() builtin, but modifies the sequence in place. Example: >>> l = range(10) >>> inplace_filter(lambda x: x > 5, l) >>> l [6, 7, 8, 9] Performance considerations: the function iterates over the sequence, shuffling surviving members down and deleting...
Like Python's filter() builtin, but modifies the sequence in place. Example: >>> l = range(10) >>> inplace_filter(lambda x: x > 5, l) >>> l [6, 7, 8, 9] Performance considerations: the function iterates over the sequence, shuffling surviving members down and deleting whatever top part of the sequence is lef...
Below is the the instruction that describes the task: ### Input: Like Python's filter() builtin, but modifies the sequence in place. Example: >>> l = range(10) >>> inplace_filter(lambda x: x > 5, l) >>> l [6, 7, 8, 9] Performance considerations: the function iterates over the sequence, shuffling survivin...
def is_all_field_none(self): """ :rtype: bool """ if self._BillingInvoice is not None: return False if self._DraftPayment is not None: return False if self._MasterCardAction is not None: return False if self._Payment is not ...
:rtype: bool
Below is the the instruction that describes the task: ### Input: :rtype: bool ### Response: def is_all_field_none(self): """ :rtype: bool """ if self._BillingInvoice is not None: return False if self._DraftPayment is not None: return False ...
def biclique(self, xmin, xmax, ymin, ymax): """Compute a maximum-sized complete bipartite graph contained in the rectangle defined by ``xmin, xmax, ymin, ymax`` where each chain of qubits is either a vertical line or a horizontal line. INPUTS: xmin,xmax,ymin,ymax: integers d...
Compute a maximum-sized complete bipartite graph contained in the rectangle defined by ``xmin, xmax, ymin, ymax`` where each chain of qubits is either a vertical line or a horizontal line. INPUTS: xmin,xmax,ymin,ymax: integers defining the bounds of a rectangle where we ...
Below is the the instruction that describes the task: ### Input: Compute a maximum-sized complete bipartite graph contained in the rectangle defined by ``xmin, xmax, ymin, ymax`` where each chain of qubits is either a vertical line or a horizontal line. INPUTS: xmin,xmax,ymin,ym...
def _make_cmap(colors, position=None, bit=False): ''' _make_cmap takes a list of tuples which contain RGB values. The RGB values may either be in 8-bit [0 to 255] (in which bit must be set to True when called) or arithmetic [0 to 1] (default). _make_cmap returns a cmap with equally spaced colors. ...
_make_cmap takes a list of tuples which contain RGB values. The RGB values may either be in 8-bit [0 to 255] (in which bit must be set to True when called) or arithmetic [0 to 1] (default). _make_cmap returns a cmap with equally spaced colors. Arrange your tuples so that the first color is the lowest va...
Below is the the instruction that describes the task: ### Input: _make_cmap takes a list of tuples which contain RGB values. The RGB values may either be in 8-bit [0 to 255] (in which bit must be set to True when called) or arithmetic [0 to 1] (default). _make_cmap returns a cmap with equally spaced col...
def fromOPEndpointURL(cls, op_endpoint_url): """Construct an OP-Identifier OpenIDServiceEndpoint object for a given OP Endpoint URL @param op_endpoint_url: The URL of the endpoint @rtype: OpenIDServiceEndpoint """ service = cls() service.server_url = op_endpoint_...
Construct an OP-Identifier OpenIDServiceEndpoint object for a given OP Endpoint URL @param op_endpoint_url: The URL of the endpoint @rtype: OpenIDServiceEndpoint
Below is the the instruction that describes the task: ### Input: Construct an OP-Identifier OpenIDServiceEndpoint object for a given OP Endpoint URL @param op_endpoint_url: The URL of the endpoint @rtype: OpenIDServiceEndpoint ### Response: def fromOPEndpointURL(cls, op_endpoint_url): ...
def get_field_mappings(self, field): """Converts ES field mappings to .kibana field mappings""" retdict = {} retdict['indexed'] = False retdict['analyzed'] = False for (key, val) in iteritems(field): if key in self.mappings: if (key == 'type' and ...
Converts ES field mappings to .kibana field mappings
Below is the the instruction that describes the task: ### Input: Converts ES field mappings to .kibana field mappings ### Response: def get_field_mappings(self, field): """Converts ES field mappings to .kibana field mappings""" retdict = {} retdict['indexed'] = False retdict['analyz...
def bind(self, server, net=None, address=None): """Create a network adapter object and bind.""" if _debug: NetworkServiceAccessPoint._debug("bind %r net=%r address=%r", server, net, address) # make sure this hasn't already been called with this network if net in self.adapters: ...
Create a network adapter object and bind.
Below is the the instruction that describes the task: ### Input: Create a network adapter object and bind. ### Response: def bind(self, server, net=None, address=None): """Create a network adapter object and bind.""" if _debug: NetworkServiceAccessPoint._debug("bind %r net=%r address=%r", server, n...
def extract_ast_species(ast): """Extract species from ast.species set of tuples (id, label)""" species_id = "None" species_label = "None" species = [ (species_id, species_label) for (species_id, species_label) in ast.species if species_id ] if len(species) == 1: (species_id, sp...
Extract species from ast.species set of tuples (id, label)
Below is the the instruction that describes the task: ### Input: Extract species from ast.species set of tuples (id, label) ### Response: def extract_ast_species(ast): """Extract species from ast.species set of tuples (id, label)""" species_id = "None" species_label = "None" species = [ (s...
def accepts(*argtypes, **kwargtypes): """A function decorator to specify argument types of the function. Types may be specified either in the order that they appear in the function or via keyword arguments (just as if you were calling the function). Example usage: | @accepts(Positive0) ...
A function decorator to specify argument types of the function. Types may be specified either in the order that they appear in the function or via keyword arguments (just as if you were calling the function). Example usage: | @accepts(Positive0) | def square_root(x): | ...
Below is the the instruction that describes the task: ### Input: A function decorator to specify argument types of the function. Types may be specified either in the order that they appear in the function or via keyword arguments (just as if you were calling the function). Example usage: | ...
def add_at(self, moment: float, fn_process: Callable, *args: Any, **kwargs: Any) -> 'Process': """ Adds a process to the simulation, which is made to start at the given exact time on the simulated clock. Note that times in the past when compared to the current moment on the simulated clock are f...
Adds a process to the simulation, which is made to start at the given exact time on the simulated clock. Note that times in the past when compared to the current moment on the simulated clock are forbidden. See method add() for more details.
Below is the the instruction that describes the task: ### Input: Adds a process to the simulation, which is made to start at the given exact time on the simulated clock. Note that times in the past when compared to the current moment on the simulated clock are forbidden. See method add() for more d...
def m2i(self, pkt, s): """ The good thing about safedec is that it may still decode ASN1 even if there is a mismatch between the expected tag (self.ASN1_tag) and the actual tag; the decoded ASN1 object will simply be put into an ASN1_BADTAG object. However, safedec prevents the r...
The good thing about safedec is that it may still decode ASN1 even if there is a mismatch between the expected tag (self.ASN1_tag) and the actual tag; the decoded ASN1 object will simply be put into an ASN1_BADTAG object. However, safedec prevents the raising of exceptions needed for ASN...
Below is the the instruction that describes the task: ### Input: The good thing about safedec is that it may still decode ASN1 even if there is a mismatch between the expected tag (self.ASN1_tag) and the actual tag; the decoded ASN1 object will simply be put into an ASN1_BADTAG object. Howev...
def regex(pattern, flags: int = 0): """Filter messages that match a given RegEx pattern. Args: pattern (``str``): The RegEx pattern as string, it will be applied to the text of a message. When a pattern matches, all the `Match Objects <https://docs.python.org...
Filter messages that match a given RegEx pattern. Args: pattern (``str``): The RegEx pattern as string, it will be applied to the text of a message. When a pattern matches, all the `Match Objects <https://docs.python.org/3/library/re.html#match-objects>`_ ...
Below is the the instruction that describes the task: ### Input: Filter messages that match a given RegEx pattern. Args: pattern (``str``): The RegEx pattern as string, it will be applied to the text of a message. When a pattern matches, all the `Match Objects <h...
def create_aggregator(self, subordinates): """Creates an aggregator event source, collecting events from multiple sources. This way a single listener can listen for events coming from multiple sources, using a single blocking :py:func:`get_event` on the returned aggregator. in subordin...
Creates an aggregator event source, collecting events from multiple sources. This way a single listener can listen for events coming from multiple sources, using a single blocking :py:func:`get_event` on the returned aggregator. in subordinates of type :class:`IEventSource` Subordi...
Below is the the instruction that describes the task: ### Input: Creates an aggregator event source, collecting events from multiple sources. This way a single listener can listen for events coming from multiple sources, using a single blocking :py:func:`get_event` on the returned aggregator. ...
def write_json(json_obj, filename, mode="w", print_pretty=True): '''write_json will (optionally,pretty print) a json object to file Parameters ========== json_obj: the dict to print to json filename: the output file to write to pretty_print: if True, will use nicer formatting ...
write_json will (optionally,pretty print) a json object to file Parameters ========== json_obj: the dict to print to json filename: the output file to write to pretty_print: if True, will use nicer formatting
Below is the the instruction that describes the task: ### Input: write_json will (optionally,pretty print) a json object to file Parameters ========== json_obj: the dict to print to json filename: the output file to write to pretty_print: if True, will use nicer formatting ### Re...
def make_mujoco_env(env_id, seed, reward_scale=1.0): """ Create a wrapped, monitored gym.Env for MuJoCo. """ rank = MPI.COMM_WORLD.Get_rank() myseed = seed + 1000 * rank if seed is not None else None set_global_seeds(myseed) env = gym.make(env_id) logger_path = None if logger.get_dir() ...
Create a wrapped, monitored gym.Env for MuJoCo.
Below is the the instruction that describes the task: ### Input: Create a wrapped, monitored gym.Env for MuJoCo. ### Response: def make_mujoco_env(env_id, seed, reward_scale=1.0): """ Create a wrapped, monitored gym.Env for MuJoCo. """ rank = MPI.COMM_WORLD.Get_rank() myseed = seed + 1000 * ra...
def is_finished(self): """Returns whether all trials have finished running.""" if self._total_time > self._global_time_limit: logger.warning("Exceeded global time limit {} / {}".format( self._total_time, self._global_time_limit)) return True trials_done ...
Returns whether all trials have finished running.
Below is the the instruction that describes the task: ### Input: Returns whether all trials have finished running. ### Response: def is_finished(self): """Returns whether all trials have finished running.""" if self._total_time > self._global_time_limit: logger.warning("Exceeded global...