code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_urls(self, controllers=None, prefix_path=''):
"""
Return a list of all valid urls (minus args and kwargs, just the program paths)
for this manifest. If a single program has two urls, both will be returned.
"""
tag_match = lambda program: set(program.controllers) & set(con... | Return a list of all valid urls (minus args and kwargs, just the program paths)
for this manifest. If a single program has two urls, both will be returned. | Below is the the instruction that describes the task:
### Input:
Return a list of all valid urls (minus args and kwargs, just the program paths)
for this manifest. If a single program has two urls, both will be returned.
### Response:
def get_urls(self, controllers=None, prefix_path=''):
"""
... |
def closest_pair(arr, give="indicies"):
"""Find the pair of indices corresponding to the closest elements in an array.
If multiple pairs are equally close, both pairs of indicies are returned.
Optionally returns the closest distance itself.
I am sure that this could be written as a cheaper operation. ... | Find the pair of indices corresponding to the closest elements in an array.
If multiple pairs are equally close, both pairs of indicies are returned.
Optionally returns the closest distance itself.
I am sure that this could be written as a cheaper operation. I
wrote this as a quick and dirty method be... | Below is the the instruction that describes the task:
### Input:
Find the pair of indices corresponding to the closest elements in an array.
If multiple pairs are equally close, both pairs of indicies are returned.
Optionally returns the closest distance itself.
I am sure that this could be written as... |
def parse(cls, data):
"""
Extracts message informations from `data`.
:param data: received line.
:type data: unicode
:return: extracted informations (source, destination, command, args).
:rtype: tuple(Source, str, str, list)
:raise: :class:`fatbotslim.irc.NullMes... | Extracts message informations from `data`.
:param data: received line.
:type data: unicode
:return: extracted informations (source, destination, command, args).
:rtype: tuple(Source, str, str, list)
:raise: :class:`fatbotslim.irc.NullMessage` if `data` is empty. | Below is the the instruction that describes the task:
### Input:
Extracts message informations from `data`.
:param data: received line.
:type data: unicode
:return: extracted informations (source, destination, command, args).
:rtype: tuple(Source, str, str, list)
:raise: :cl... |
def feature_index(*feature_names):
'''Returns a index creation function.
Returns a valid index ``create`` function for the feature names
given. This can be used with the :meth:`Store.define_index`
method to create indexes on any combination of features in a
feature collection.
:type feature_na... | Returns a index creation function.
Returns a valid index ``create`` function for the feature names
given. This can be used with the :meth:`Store.define_index`
method to create indexes on any combination of features in a
feature collection.
:type feature_names: list(unicode)
:rtype: ``(val -> i... | Below is the the instruction that describes the task:
### Input:
Returns a index creation function.
Returns a valid index ``create`` function for the feature names
given. This can be used with the :meth:`Store.define_index`
method to create indexes on any combination of features in a
feature collec... |
def connect_model(self, model):
"""Link the Database to the Model instance.
In case a new database is created from scratch, ``connect_model``
creates Trace objects for all tallyable pymc objects defined in
`model`.
If the database is being loaded from an existing file, ``connec... | Link the Database to the Model instance.
In case a new database is created from scratch, ``connect_model``
creates Trace objects for all tallyable pymc objects defined in
`model`.
If the database is being loaded from an existing file, ``connect_model``
restore the objects trace... | Below is the the instruction that describes the task:
### Input:
Link the Database to the Model instance.
In case a new database is created from scratch, ``connect_model``
creates Trace objects for all tallyable pymc objects defined in
`model`.
If the database is being loaded from ... |
def lightcurve_flux_measures(ftimes, fmags, ferrs, magsarefluxes=False):
'''This calculates percentiles and percentile ratios of the flux.
Parameters
----------
ftimes,fmags,ferrs : np.array
The input mag/flux time-series with all non-finite elements removed.
magsarefluxes : bool
... | This calculates percentiles and percentile ratios of the flux.
Parameters
----------
ftimes,fmags,ferrs : np.array
The input mag/flux time-series with all non-finite elements removed.
magsarefluxes : bool
If the `fmags` array actually contains fluxes, will not convert `mags`
t... | Below is the the instruction that describes the task:
### Input:
This calculates percentiles and percentile ratios of the flux.
Parameters
----------
ftimes,fmags,ferrs : np.array
The input mag/flux time-series with all non-finite elements removed.
magsarefluxes : bool
If the `fma... |
def init_dict(data, index, columns, dtype=None):
"""
Segregate Series based on type and coerce into matrices.
Needs to handle a lot of exceptional cases.
"""
if columns is not None:
from pandas.core.series import Series
arrays = Series(data, index=columns, dtype=object)
data_... | Segregate Series based on type and coerce into matrices.
Needs to handle a lot of exceptional cases. | Below is the the instruction that describes the task:
### Input:
Segregate Series based on type and coerce into matrices.
Needs to handle a lot of exceptional cases.
### Response:
def init_dict(data, index, columns, dtype=None):
"""
Segregate Series based on type and coerce into matrices.
Needs to ... |
def filter_data_frame(self, data_frame, centre=False, keep_cols=['anno']):
"""
This method filters a data frame signal as suggested in [1]. First step is to high pass filter the data
frame using a butter Butterworth digital and analog filter
(https://docs.scipy.org/doc/scipy... | This method filters a data frame signal as suggested in [1]. First step is to high pass filter the data
frame using a butter Butterworth digital and analog filter
(https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.butter.html). Then the method
filter the data... | Below is the the instruction that describes the task:
### Input:
This method filters a data frame signal as suggested in [1]. First step is to high pass filter the data
frame using a butter Butterworth digital and analog filter
(https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/sc... |
def execute(self, triple_map, output, **kwargs):
"""Method executes mapping between JSON source and
output RDF
Args:
-----
triple_map: SimpleNamespace
"""
subjects = []
logical_src_iterator = str(triple_map.logicalSource.iterator)
json_object... | Method executes mapping between JSON source and
output RDF
Args:
-----
triple_map: SimpleNamespace | Below is the the instruction that describes the task:
### Input:
Method executes mapping between JSON source and
output RDF
Args:
-----
triple_map: SimpleNamespace
### Response:
def execute(self, triple_map, output, **kwargs):
"""Method executes mapping between JSON so... |
def check_secure():
"""Check request, return False if using SSL or local connection."""
if this.request.is_secure():
return True # using SSL
elif this.request.META['REMOTE_ADDR'] in [
'localhost',
'127.0.0.1',
]:
return True # loc... | Check request, return False if using SSL or local connection. | Below is the the instruction that describes the task:
### Input:
Check request, return False if using SSL or local connection.
### Response:
def check_secure():
"""Check request, return False if using SSL or local connection."""
if this.request.is_secure():
return True # using SSL
... |
def get_included_databases(self):
"""Return the databases we want to include, or empty list for all.
"""
databases = set()
databases.update(self._plain_db.keys())
for _, namespace in self._regex_map:
database_name, _ = namespace.source_name.split(".", 1)
... | Return the databases we want to include, or empty list for all. | Below is the the instruction that describes the task:
### Input:
Return the databases we want to include, or empty list for all.
### Response:
def get_included_databases(self):
"""Return the databases we want to include, or empty list for all.
"""
databases = set()
databases.update(... |
def convert_to_float_list(value):
""" Converts a comma separate string to a list
:param value:
the format must be 1.2,-3.5 (commas with no space)
:type value:
String
:returns:
List
:example:
>>> convert_to_integer_list('003,003,004,004')
[1.2, -3.5]
""... | Converts a comma separate string to a list
:param value:
the format must be 1.2,-3.5 (commas with no space)
:type value:
String
:returns:
List
:example:
>>> convert_to_integer_list('003,003,004,004')
[1.2, -3.5] | Below is the the instruction that describes the task:
### Input:
Converts a comma separate string to a list
:param value:
the format must be 1.2,-3.5 (commas with no space)
:type value:
String
:returns:
List
:example:
>>> convert_to_integer_list('003,003,004,004')
... |
def check(self):
"""
Check that this table is complete, that is, every character of this
table can be followed by a new character.
:return: True if the table is complete, False otherwise.
"""
for character, followers in self.items():
for follower in followers... | Check that this table is complete, that is, every character of this
table can be followed by a new character.
:return: True if the table is complete, False otherwise. | Below is the the instruction that describes the task:
### Input:
Check that this table is complete, that is, every character of this
table can be followed by a new character.
:return: True if the table is complete, False otherwise.
### Response:
def check(self):
"""
Check that this... |
def invoke_shell(self, locs, banner):
"""
Invokes the appropriate flavor of the python shell.
Falls back on the native python shell if the requested
flavor (ipython, bpython,etc) is not installed.
"""
shell = self.SHELLS[self.args.shell]
try:
shell().i... | Invokes the appropriate flavor of the python shell.
Falls back on the native python shell if the requested
flavor (ipython, bpython,etc) is not installed. | Below is the the instruction that describes the task:
### Input:
Invokes the appropriate flavor of the python shell.
Falls back on the native python shell if the requested
flavor (ipython, bpython,etc) is not installed.
### Response:
def invoke_shell(self, locs, banner):
"""
Invokes... |
def _F(self, x, p):
"""
solution of the projection integal (kappa)
arctanh / arctan function
:param x: r/Rs
:param p: r_core / Rs
:return:
"""
prefactor = 0.5 * (1 + p ** 2) ** -1 * p
if isinstance(x, np.ndarray):
inds0 = np.where(x ... | solution of the projection integal (kappa)
arctanh / arctan function
:param x: r/Rs
:param p: r_core / Rs
:return: | Below is the the instruction that describes the task:
### Input:
solution of the projection integal (kappa)
arctanh / arctan function
:param x: r/Rs
:param p: r_core / Rs
:return:
### Response:
def _F(self, x, p):
"""
solution of the projection integal (kappa)
... |
def _add_q(self, q_object):
"""Add a Q-object to the current filter."""
self._criteria = self._criteria._combine(q_object, q_object.connector) | Add a Q-object to the current filter. | Below is the the instruction that describes the task:
### Input:
Add a Q-object to the current filter.
### Response:
def _add_q(self, q_object):
"""Add a Q-object to the current filter."""
self._criteria = self._criteria._combine(q_object, q_object.connector) |
def optimize_auto(self,max_iters=10000,verbose=True):
"""
Optimize the model parameters through a pre-defined protocol.
:param int max_iters: the maximum number of iterations.
:param boolean verbose: print the progress of optimization or not.
"""
self.Z.fix(warning=False... | Optimize the model parameters through a pre-defined protocol.
:param int max_iters: the maximum number of iterations.
:param boolean verbose: print the progress of optimization or not. | Below is the the instruction that describes the task:
### Input:
Optimize the model parameters through a pre-defined protocol.
:param int max_iters: the maximum number of iterations.
:param boolean verbose: print the progress of optimization or not.
### Response:
def optimize_auto(self,max_iters=1... |
def region_size(im):
r"""
Replace each voxel with size of region to which it belongs
Parameters
----------
im : ND-array
Either a boolean image wtih ``True`` indicating the features of
interest, in which case ``scipy.ndimage.label`` will be applied to
find regions, or a grey... | r"""
Replace each voxel with size of region to which it belongs
Parameters
----------
im : ND-array
Either a boolean image wtih ``True`` indicating the features of
interest, in which case ``scipy.ndimage.label`` will be applied to
find regions, or a greyscale image with integer ... | Below is the the instruction that describes the task:
### Input:
r"""
Replace each voxel with size of region to which it belongs
Parameters
----------
im : ND-array
Either a boolean image wtih ``True`` indicating the features of
interest, in which case ``scipy.ndimage.label`` will b... |
def values(self) -> typing.Dict[str, str]:
"""The field values of this object's name as a dictionary in the form of {field: value}."""
return {k: v for k, v in self._items if v is not None} | The field values of this object's name as a dictionary in the form of {field: value}. | Below is the the instruction that describes the task:
### Input:
The field values of this object's name as a dictionary in the form of {field: value}.
### Response:
def values(self) -> typing.Dict[str, str]:
"""The field values of this object's name as a dictionary in the form of {field: value}."""
... |
def send_caught_exception_stack_proceeded(self, thread):
"""Sends that some thread was resumed and is no longer showing an exception trace.
"""
thread_id = get_thread_id(thread)
int_cmd = InternalSendCurrExceptionTraceProceeded(thread_id)
self.post_internal_command(int_cmd, threa... | Sends that some thread was resumed and is no longer showing an exception trace. | Below is the the instruction that describes the task:
### Input:
Sends that some thread was resumed and is no longer showing an exception trace.
### Response:
def send_caught_exception_stack_proceeded(self, thread):
"""Sends that some thread was resumed and is no longer showing an exception trace.
... |
def add_route(self, view: View, path: str, exact: bool = True) -> None:
"""Add a view to the app.
Parameters
----------
view : View
path : str
exact : bool, optional
"""
if path[0] != '/':
path = '/' + path
for route in self._routes:
... | Add a view to the app.
Parameters
----------
view : View
path : str
exact : bool, optional | Below is the the instruction that describes the task:
### Input:
Add a view to the app.
Parameters
----------
view : View
path : str
exact : bool, optional
### Response:
def add_route(self, view: View, path: str, exact: bool = True) -> None:
"""Add a view to the app... |
def restore(self):
"""
This method constructs the restoring beam and then adds the convolution to the residual.
"""
clean_beam, beam_params = beam_fit(self.psf_data, self.cdelt1, self.cdelt2)
if np.all(np.array(self.psf_data_shape)==2*np.array(self.dirty_data_shape)):
... | This method constructs the restoring beam and then adds the convolution to the residual. | Below is the the instruction that describes the task:
### Input:
This method constructs the restoring beam and then adds the convolution to the residual.
### Response:
def restore(self):
"""
This method constructs the restoring beam and then adds the convolution to the residual.
"""
... |
def containing_triangle(self, xi, yi):
"""
Returns indices of the triangles containing xi yi
Parameters
----------
xi : float / array of floats, shape (l,)
Cartesian coordinates in the x direction
yi : float / array of floats, shape (l,)
Cartesi... | Returns indices of the triangles containing xi yi
Parameters
----------
xi : float / array of floats, shape (l,)
Cartesian coordinates in the x direction
yi : float / array of floats, shape (l,)
Cartesian coordinates in the y direction
Returns
... | Below is the the instruction that describes the task:
### Input:
Returns indices of the triangles containing xi yi
Parameters
----------
xi : float / array of floats, shape (l,)
Cartesian coordinates in the x direction
yi : float / array of floats, shape (l,)
... |
def _get_env_list(obj, env):
"""Creates the list of environments to read
:param obj: the settings instance
:param env: settings env default='DYNACONF'
:return: a list of working environments
"""
# add the [default] env
env_list = [obj.get("DEFAULT_ENV_FOR_DYNACONF")]
# compatibility wit... | Creates the list of environments to read
:param obj: the settings instance
:param env: settings env default='DYNACONF'
:return: a list of working environments | Below is the the instruction that describes the task:
### Input:
Creates the list of environments to read
:param obj: the settings instance
:param env: settings env default='DYNACONF'
:return: a list of working environments
### Response:
def _get_env_list(obj, env):
"""Creates the list of environm... |
def estimate_B(
xray_table, vhe_table, photon_energy_density=0.261 * u.eV / u.cm ** 3
):
""" Estimate magnetic field from synchrotron to Inverse Compton luminosity
ratio
Estimate the magnetic field from the ratio of X-ray to gamma-ray emission
according to:
.. math::
\\frac{L_\mathrm{... | Estimate magnetic field from synchrotron to Inverse Compton luminosity
ratio
Estimate the magnetic field from the ratio of X-ray to gamma-ray emission
according to:
.. math::
\\frac{L_\mathrm{xray}}{L_\gamma} =
\\frac{u_\mathrm{B}}{u_\mathrm{ph}} =
\\frac{B^2}{ 8 \pi u_\mathrm... | Below is the the instruction that describes the task:
### Input:
Estimate magnetic field from synchrotron to Inverse Compton luminosity
ratio
Estimate the magnetic field from the ratio of X-ray to gamma-ray emission
according to:
.. math::
\\frac{L_\mathrm{xray}}{L_\gamma} =
\\fra... |
def save_device_info(self):
"""Save all device information to the device info file."""
if self._workdir is not None:
devices = []
for addr in self._devices:
device = self._devices.get(addr)
if not device.address.is_x10:
aldb = {... | Save all device information to the device info file. | Below is the the instruction that describes the task:
### Input:
Save all device information to the device info file.
### Response:
def save_device_info(self):
"""Save all device information to the device info file."""
if self._workdir is not None:
devices = []
for addr in s... |
def networkCoAuthor(self, detailedInfo = False, weighted = True, dropNonJournals = False, count = True, useShortNames = False, citeProfile = False):
"""Creates a coauthorship network for the RecordCollection.
# Parameters
_detailedInfo_ : `optional [bool or iterable[WOS tag Strings]]`
... | Creates a coauthorship network for the RecordCollection.
# Parameters
_detailedInfo_ : `optional [bool or iterable[WOS tag Strings]]`
> Default `False`, if `True` all nodes will be given info strings composed of information from the Record objects themselves. This is Equivalent to passing the... | Below is the the instruction that describes the task:
### Input:
Creates a coauthorship network for the RecordCollection.
# Parameters
_detailedInfo_ : `optional [bool or iterable[WOS tag Strings]]`
> Default `False`, if `True` all nodes will be given info strings composed of information ... |
def announcements_view(request):
''' The view of manager announcements. '''
page_name = "Manager Announcements"
userProfile = UserProfile.objects.get(user=request.user)
announcement_form = None
manager_positions = Manager.objects.filter(incumbent=userProfile)
if manager_positions:
announ... | The view of manager announcements. | Below is the the instruction that describes the task:
### Input:
The view of manager announcements.
### Response:
def announcements_view(request):
''' The view of manager announcements. '''
page_name = "Manager Announcements"
userProfile = UserProfile.objects.get(user=request.user)
announcement_for... |
def modified_files(root, tracked_only=False, commit=None):
"""Returns a list of files that has been modified since the last commit.
Args:
root: the root of the repository, it has to be an absolute path.
tracked_only: exclude untracked files when True.
commit: SHA1 of the commit. If None, it w... | Returns a list of files that has been modified since the last commit.
Args:
root: the root of the repository, it has to be an absolute path.
tracked_only: exclude untracked files when True.
commit: SHA1 of the commit. If None, it will get the modified files in the
working copy.
Retur... | Below is the the instruction that describes the task:
### Input:
Returns a list of files that has been modified since the last commit.
Args:
root: the root of the repository, it has to be an absolute path.
tracked_only: exclude untracked files when True.
commit: SHA1 of the commit. If None, i... |
def compare(self, node, prev_value=None, prev_index=None):
"""Raises :exc:`TestFailed` if the node is not matched with
`prev_value` or `prev_index`.
"""
if prev_value is not None and node.value != prev_value or \
prev_index is not None and node.index != prev_index:
... | Raises :exc:`TestFailed` if the node is not matched with
`prev_value` or `prev_index`. | Below is the the instruction that describes the task:
### Input:
Raises :exc:`TestFailed` if the node is not matched with
`prev_value` or `prev_index`.
### Response:
def compare(self, node, prev_value=None, prev_index=None):
"""Raises :exc:`TestFailed` if the node is not matched with
`prev_... |
def read_pdb(pdbfname, as_string=False):
"""Reads a given PDB file and returns a Pybel Molecule."""
pybel.ob.obErrorLog.StopLogging() # Suppress all OpenBabel warnings
if os.name != 'nt': # Resource module not available for Windows
maxsize = resource.getrlimit(resource.RLIMIT_STACK)[-1]
re... | Reads a given PDB file and returns a Pybel Molecule. | Below is the the instruction that describes the task:
### Input:
Reads a given PDB file and returns a Pybel Molecule.
### Response:
def read_pdb(pdbfname, as_string=False):
"""Reads a given PDB file and returns a Pybel Molecule."""
pybel.ob.obErrorLog.StopLogging() # Suppress all OpenBabel warnings
if... |
def make_specified_size_gctoo(og_gctoo, num_entries, dim):
"""
Subsets a GCToo instance along either rows or columns to obtain a specified size.
Input:
- og_gctoo (GCToo): a GCToo instance
- num_entries (int): the number of entries to keep
- dim (str): the dimension along which to subset. Must be "row" or... | Subsets a GCToo instance along either rows or columns to obtain a specified size.
Input:
- og_gctoo (GCToo): a GCToo instance
- num_entries (int): the number of entries to keep
- dim (str): the dimension along which to subset. Must be "row" or "col"
Output:
- new_gctoo (GCToo): the GCToo instance subsetted... | Below is the the instruction that describes the task:
### Input:
Subsets a GCToo instance along either rows or columns to obtain a specified size.
Input:
- og_gctoo (GCToo): a GCToo instance
- num_entries (int): the number of entries to keep
- dim (str): the dimension along which to subset. Must be "row" o... |
def truncate(self, app_label, schema_editor, models):
"""Truncate tables."""
for model_name in models:
model = '%s_%s' % (app_label, model_name)
schema_editor.execute(
'TRUNCATE TABLE %s RESTART IDENTITY CASCADE' % (
model.lower(),
... | Truncate tables. | Below is the the instruction that describes the task:
### Input:
Truncate tables.
### Response:
def truncate(self, app_label, schema_editor, models):
"""Truncate tables."""
for model_name in models:
model = '%s_%s' % (app_label, model_name)
schema_editor.execute(
... |
def __feed_backend_arthur(self, repo):
""" Feed Ocean with backend data collected from arthur redis queue"""
# Always get pending items from arthur for all data sources
self.__feed_arthur()
tag = self.backend_tag(repo)
logger.debug("Arthur items available for %s", self.arthur_... | Feed Ocean with backend data collected from arthur redis queue | Below is the the instruction that describes the task:
### Input:
Feed Ocean with backend data collected from arthur redis queue
### Response:
def __feed_backend_arthur(self, repo):
""" Feed Ocean with backend data collected from arthur redis queue"""
# Always get pending items from arthur for all ... |
def get_asset_composition_design_session(self, proxy):
"""Gets the session for creating asset compositions.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.AssetCompositionDesignSession) - an
``AssetCompositionDesignSession``
raise: NullArgument - ``p... | Gets the session for creating asset compositions.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.AssetCompositionDesignSession) - an
``AssetCompositionDesignSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable to com... | Below is the the instruction that describes the task:
### Input:
Gets the session for creating asset compositions.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.AssetCompositionDesignSession) - an
``AssetCompositionDesignSession``
raise: NullArgument - ... |
def extension (network, session, version, scn_extension, start_snapshot,
end_snapshot, **kwargs):
"""
Function that adds an additional network to the existing network container.
The new network can include every PyPSA-component (e.g. buses, lines, links).
To connect it to the existing ... | Function that adds an additional network to the existing network container.
The new network can include every PyPSA-component (e.g. buses, lines, links).
To connect it to the existing network, transformers are needed.
All components and its timeseries of the additional scenario need to be insert... | Below is the the instruction that describes the task:
### Input:
Function that adds an additional network to the existing network container.
The new network can include every PyPSA-component (e.g. buses, lines, links).
To connect it to the existing network, transformers are needed.
All compo... |
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
opts=__opts__,
provider=__active_provider_name__ or __virtualname__,
aliases=__virtual_aliases__,
required_keys=('personal_access_token',)
) | Return the first configured instance. | Below is the the instruction that describes the task:
### Input:
Return the first configured instance.
### Response:
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
opts=__opts__,
provider=__active_provider_name__ or... |
def chroma(chromagram, times, fs, **kwargs):
"""Reverse synthesis of a chromagram (semitone matrix)
Parameters
----------
chromagram : np.ndarray, shape=(12, times.shape[0])
Chromagram matrix, where each row represents a semitone [C->Bb]
i.e., ``chromagram[3, j]`` is the magnitude of D#... | Reverse synthesis of a chromagram (semitone matrix)
Parameters
----------
chromagram : np.ndarray, shape=(12, times.shape[0])
Chromagram matrix, where each row represents a semitone [C->Bb]
i.e., ``chromagram[3, j]`` is the magnitude of D# from ``times[j]`` to
``times[j + 1]``
t... | Below is the the instruction that describes the task:
### Input:
Reverse synthesis of a chromagram (semitone matrix)
Parameters
----------
chromagram : np.ndarray, shape=(12, times.shape[0])
Chromagram matrix, where each row represents a semitone [C->Bb]
i.e., ``chromagram[3, j]`` is th... |
def _get_nets_arin(self, *args, **kwargs):
"""
Deprecated. This will be removed in a future release.
"""
from warnings import warn
warn('Whois._get_nets_arin() has been deprecated and will be '
'removed. You should now use Whois.get_nets_arin().')
return sel... | Deprecated. This will be removed in a future release. | Below is the the instruction that describes the task:
### Input:
Deprecated. This will be removed in a future release.
### Response:
def _get_nets_arin(self, *args, **kwargs):
"""
Deprecated. This will be removed in a future release.
"""
from warnings import warn
warn('Whoi... |
def get_tables(self):
"""
Adds tables to the network.
Example
-------
>>> writer = UAIWriter(model)
>>> writer.get_tables()
"""
if isinstance(self.model, BayesianModel):
cpds = self.model.get_cpds()
cpds.sort(key=lambda x: x.variab... | Adds tables to the network.
Example
-------
>>> writer = UAIWriter(model)
>>> writer.get_tables() | Below is the the instruction that describes the task:
### Input:
Adds tables to the network.
Example
-------
>>> writer = UAIWriter(model)
>>> writer.get_tables()
### Response:
def get_tables(self):
"""
Adds tables to the network.
Example
-------
... |
def image_consumer(socket, hdf5_file, num_expected, shuffle_seed=None,
offset=0):
"""Fill an HDF5 file with incoming images from a socket.
Parameters
----------
socket : :class:`zmq.Socket`
PULL socket on which to receive images.
hdf5_file : :class:`h5py.File` instance
... | Fill an HDF5 file with incoming images from a socket.
Parameters
----------
socket : :class:`zmq.Socket`
PULL socket on which to receive images.
hdf5_file : :class:`h5py.File` instance
HDF5 file handle to which to write. Assumes `features`, `targets`
and `filenames` already exis... | Below is the the instruction that describes the task:
### Input:
Fill an HDF5 file with incoming images from a socket.
Parameters
----------
socket : :class:`zmq.Socket`
PULL socket on which to receive images.
hdf5_file : :class:`h5py.File` instance
HDF5 file handle to which to writ... |
def formfield(self, form_class=None, choices_form_class=None, **kwargs):
"""
Returns a django.forms.Field instance for this database Field.
"""
defaults = {
'required': not self.blank,
'label': capfirst(self.verbose_name),
'help_text': self.help_text,
... | Returns a django.forms.Field instance for this database Field. | Below is the the instruction that describes the task:
### Input:
Returns a django.forms.Field instance for this database Field.
### Response:
def formfield(self, form_class=None, choices_form_class=None, **kwargs):
"""
Returns a django.forms.Field instance for this database Field.
"""
... |
def sample_hull(hull,domain,isDomainFinite):
"""sample_hull: Sample the upper hull
Input:
hull - hull structure (see setup_hull for a definition of this)
domain - [.,.] upper and lower limit to the domain
isDomainFinite - [.,.] is there a lower/upper limit to the domain?
... | sample_hull: Sample the upper hull
Input:
hull - hull structure (see setup_hull for a definition of this)
domain - [.,.] upper and lower limit to the domain
isDomainFinite - [.,.] is there a lower/upper limit to the domain?
Output:
a sample from the hull
Histor... | Below is the the instruction that describes the task:
### Input:
sample_hull: Sample the upper hull
Input:
hull - hull structure (see setup_hull for a definition of this)
domain - [.,.] upper and lower limit to the domain
isDomainFinite - [.,.] is there a lower/upper limit ... |
def _register_webhook(self, webhook_url, events):
"""Register webhook."""
response = self._request(
MINUT_WEBHOOKS_URL,
request_type='POST',
json={
'url': webhook_url,
'events': events,
},
)
return response | Register webhook. | Below is the the instruction that describes the task:
### Input:
Register webhook.
### Response:
def _register_webhook(self, webhook_url, events):
"""Register webhook."""
response = self._request(
MINUT_WEBHOOKS_URL,
request_type='POST',
json={
'u... |
def closeConnection(self):
"""close current serial port connection"""
print '%s call closeConnection' % self.port
try:
if self.handle:
self.handle.close()
self.handle = None
except Exception, e:
ModuleHelper.WriteIntoDebugLogger("cl... | close current serial port connection | Below is the the instruction that describes the task:
### Input:
close current serial port connection
### Response:
def closeConnection(self):
"""close current serial port connection"""
print '%s call closeConnection' % self.port
try:
if self.handle:
self.handle.... |
def unpack(self, token, **kwargs):
"""
Unpacks a JWT into its parts and base64 decodes the parts
individually
:param token: The JWT
:param kwargs: A possible empty set of claims to verify the header
against.
"""
if isinstance(token, str):
... | Unpacks a JWT into its parts and base64 decodes the parts
individually
:param token: The JWT
:param kwargs: A possible empty set of claims to verify the header
against. | Below is the the instruction that describes the task:
### Input:
Unpacks a JWT into its parts and base64 decodes the parts
individually
:param token: The JWT
:param kwargs: A possible empty set of claims to verify the header
against.
### Response:
def unpack(self, token, **kwar... |
def import_file(source, use_32bit_registry=False):
'''
Import registry settings from a Windows ``REG`` file by invoking ``REG.EXE``.
.. versionadded:: 2018.3.0
Args:
source (str):
The full path of the ``REG`` file. This can be either a local file
path or a URL type sup... | Import registry settings from a Windows ``REG`` file by invoking ``REG.EXE``.
.. versionadded:: 2018.3.0
Args:
source (str):
The full path of the ``REG`` file. This can be either a local file
path or a URL type supported by salt (e.g. ``salt://salt_master_path``)
use_... | Below is the the instruction that describes the task:
### Input:
Import registry settings from a Windows ``REG`` file by invoking ``REG.EXE``.
.. versionadded:: 2018.3.0
Args:
source (str):
The full path of the ``REG`` file. This can be either a local file
path or a URL ty... |
def sync_month_metric(self, unique_identifier, metric, start_date, end_date):
"""
Uses the count for each day in the date range to recalculate the counters for the months for
the ``metric`` for ``unique_identifier``. Useful for updating the counters for week and month after using set_metric_by_d... | Uses the count for each day in the date range to recalculate the counters for the months for
the ``metric`` for ``unique_identifier``. Useful for updating the counters for week and month after using set_metric_by_day.
The redis backend supports lists for both ``unique_identifier`` and ``metric`` allowi... | Below is the the instruction that describes the task:
### Input:
Uses the count for each day in the date range to recalculate the counters for the months for
the ``metric`` for ``unique_identifier``. Useful for updating the counters for week and month after using set_metric_by_day.
The redis backen... |
def _purge_jobs(timestamp):
'''
Purge records from the returner tables.
:param job_age_in_seconds: Purge jobs older than this
:return:
'''
with _get_serv() as cursor:
try:
sql = 'delete from jids where jid in (select distinct jid from salt_returns where alter_time < %s)'
... | Purge records from the returner tables.
:param job_age_in_seconds: Purge jobs older than this
:return: | Below is the the instruction that describes the task:
### Input:
Purge records from the returner tables.
:param job_age_in_seconds: Purge jobs older than this
:return:
### Response:
def _purge_jobs(timestamp):
'''
Purge records from the returner tables.
:param job_age_in_seconds: Purge jobs o... |
def show_command(endpoint_id, rule_id):
"""
Executor for `globus endpoint permission show`
"""
client = get_client()
rule = client.get_endpoint_acl_rule(endpoint_id, rule_id)
formatted_print(
rule,
text_format=FORMAT_TEXT_RECORD,
fields=(
("Rule ID", "id"),
... | Executor for `globus endpoint permission show` | Below is the the instruction that describes the task:
### Input:
Executor for `globus endpoint permission show`
### Response:
def show_command(endpoint_id, rule_id):
"""
Executor for `globus endpoint permission show`
"""
client = get_client()
rule = client.get_endpoint_acl_rule(endpoint_id, ru... |
def append(self, key, value=MARKER, replace=True):
'''
Append the item to the metadata.
'''
return self.add_item(key, value, replace=replace) | Append the item to the metadata. | Below is the the instruction that describes the task:
### Input:
Append the item to the metadata.
### Response:
def append(self, key, value=MARKER, replace=True):
'''
Append the item to the metadata.
'''
return self.add_item(key, value, replace=replace) |
def ray_trace(self, origin, end_point, first_point=False, plot=False,
off_screen=False):
"""
Performs a single ray trace calculation given a mesh and a line segment
defined by an origin and end_point.
Parameters
----------
origin : np.ndarray or list
... | Performs a single ray trace calculation given a mesh and a line segment
defined by an origin and end_point.
Parameters
----------
origin : np.ndarray or list
Start of the line segment.
end_point : np.ndarray or list
End of the line segment.
firs... | Below is the the instruction that describes the task:
### Input:
Performs a single ray trace calculation given a mesh and a line segment
defined by an origin and end_point.
Parameters
----------
origin : np.ndarray or list
Start of the line segment.
end_point : ... |
def increment(method):
"""
Static method used to increment the depth of a context belonging to 'method'
:param function method: A method with a context
:rtype: caliendo.hooks.Context
:returns: The context instance for the method.
"""
if not hasattr(method, '__co... | Static method used to increment the depth of a context belonging to 'method'
:param function method: A method with a context
:rtype: caliendo.hooks.Context
:returns: The context instance for the method. | Below is the the instruction that describes the task:
### Input:
Static method used to increment the depth of a context belonging to 'method'
:param function method: A method with a context
:rtype: caliendo.hooks.Context
:returns: The context instance for the method.
### Response:
def inc... |
def _remap_cortex_out(cortex_out, region, out_file):
"""Remap coordinates in local cortex variant calls to the original global region.
"""
def _remap_vcf_line(line, contig, start):
parts = line.split("\t")
if parts[0] == "" or parts[1] == "":
return None
parts[0] = contig... | Remap coordinates in local cortex variant calls to the original global region. | Below is the the instruction that describes the task:
### Input:
Remap coordinates in local cortex variant calls to the original global region.
### Response:
def _remap_cortex_out(cortex_out, region, out_file):
"""Remap coordinates in local cortex variant calls to the original global region.
"""
def _r... |
def normalize_alleles_left(ref, start, stop, alleles, bound, ref_step, shuffle=True):
"""
Normalize loci by removing extraneous reference padding
>>> normalize_alleles_left('A', 1, 2, 'A', 1, 2)
shuffled_alleles(start=1, stop=2, alleles='A')
"""
normalized_alleles = namedtuple('shuffled_allel... | Normalize loci by removing extraneous reference padding
>>> normalize_alleles_left('A', 1, 2, 'A', 1, 2)
shuffled_alleles(start=1, stop=2, alleles='A') | Below is the the instruction that describes the task:
### Input:
Normalize loci by removing extraneous reference padding
>>> normalize_alleles_left('A', 1, 2, 'A', 1, 2)
shuffled_alleles(start=1, stop=2, alleles='A')
### Response:
def normalize_alleles_left(ref, start, stop, alleles, bound, ref_step, shuf... |
def do_help(self, arg):
"""
Show help on all commands.
"""
print(self.response_prompt, file=self.stdout)
return cmd.Cmd.do_help(self, arg) | Show help on all commands. | Below is the the instruction that describes the task:
### Input:
Show help on all commands.
### Response:
def do_help(self, arg):
"""
Show help on all commands.
"""
print(self.response_prompt, file=self.stdout)
return cmd.Cmd.do_help(self, arg) |
def set_canonical_host(self, canonical_host):
"""
Set host and port from a canonical host string as for the Host HTTP
header specification.
"""
parts = canonical_host.lower().split(":")
self.host = parts[0]
if len(parts) > 1 and parts[1]:
self.port = i... | Set host and port from a canonical host string as for the Host HTTP
header specification. | Below is the the instruction that describes the task:
### Input:
Set host and port from a canonical host string as for the Host HTTP
header specification.
### Response:
def set_canonical_host(self, canonical_host):
"""
Set host and port from a canonical host string as for the Host HTTP
... |
def load_maf_dataframe(path, nrows=None, raise_on_error=True, encoding=None):
"""
Load the guaranteed columns of a TCGA MAF file into a DataFrame
Parameters
----------
path : str
Path to MAF file
nrows : int
Optional limit to number of rows loaded
raise_on_error : bool
... | Load the guaranteed columns of a TCGA MAF file into a DataFrame
Parameters
----------
path : str
Path to MAF file
nrows : int
Optional limit to number of rows loaded
raise_on_error : bool
Raise an exception upon encountering an error or log an error
encoding : str, op... | Below is the the instruction that describes the task:
### Input:
Load the guaranteed columns of a TCGA MAF file into a DataFrame
Parameters
----------
path : str
Path to MAF file
nrows : int
Optional limit to number of rows loaded
raise_on_error : bool
Raise an excepti... |
def find_element_by_partial_link_text(self, link_text):
"""
Finds an element by a partial match of its link text.
:Args:
- link_text: The text of the element to partially match on.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuc... | Finds an element by a partial match of its link text.
:Args:
- link_text: The text of the element to partially match on.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
... | Below is the the instruction that describes the task:
### Input:
Finds an element by a partial match of its link text.
:Args:
- link_text: The text of the element to partially match on.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElemen... |
def get_all_rotated_notes(notes):
""" Get all rotated notes
get_all_rotated_notes([1,3,5]) -> [[1,3,5],[3,5,1],[5,1,3]]
:type notes: list[str]
:rtype: list[list[str]]
"""
notes_list = []
for x in range(len(notes)):
notes_list.append(notes[x:] + notes[:x])
return notes_list | Get all rotated notes
get_all_rotated_notes([1,3,5]) -> [[1,3,5],[3,5,1],[5,1,3]]
:type notes: list[str]
:rtype: list[list[str]] | Below is the the instruction that describes the task:
### Input:
Get all rotated notes
get_all_rotated_notes([1,3,5]) -> [[1,3,5],[3,5,1],[5,1,3]]
:type notes: list[str]
:rtype: list[list[str]]
### Response:
def get_all_rotated_notes(notes):
""" Get all rotated notes
get_all_rotated_notes([1... |
def create(self, request, *args, **kwargs):
"""
To create new push hook issue **POST** against */api/hooks-push/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-push/ HTTP... | To create new push hook issue **POST** against */api/hooks-push/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-push/ HTTP/1.1
Content-Type: application/json
Acce... | Below is the the instruction that describes the task:
### Input:
To create new push hook issue **POST** against */api/hooks-push/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-push/... |
def end_of_paragraph(self, count=1, after=False):
"""
Return the end of the current paragraph. (Relative cursor position.)
"""
def match_func(text):
return not text or text.isspace()
line_index = self.find_next_matching_line(match_func=match_func, count=count)
... | Return the end of the current paragraph. (Relative cursor position.) | Below is the the instruction that describes the task:
### Input:
Return the end of the current paragraph. (Relative cursor position.)
### Response:
def end_of_paragraph(self, count=1, after=False):
"""
Return the end of the current paragraph. (Relative cursor position.)
"""
def matc... |
def add_event_source(event_source, lambda_arn, target_function, boto_session, dry=False):
"""
Given an event_source dictionary, create the object and add the event source.
"""
event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False)
# TODO: ... | Given an event_source dictionary, create the object and add the event source. | Below is the the instruction that describes the task:
### Input:
Given an event_source dictionary, create the object and add the event source.
### Response:
def add_event_source(event_source, lambda_arn, target_function, boto_session, dry=False):
"""
Given an event_source dictionary, create the object and ... |
def _insert_optional_roles(cursor, model, ident):
"""Inserts the optional roles if values for the optional roles
exist.
"""
optional_roles = [
# (<metadata-attr>, <db-role-id>,),
('translators', 4,),
('editors', 5,),
]
for attr, role_id in optional_roles:
roles = ... | Inserts the optional roles if values for the optional roles
exist. | Below is the the instruction that describes the task:
### Input:
Inserts the optional roles if values for the optional roles
exist.
### Response:
def _insert_optional_roles(cursor, model, ident):
"""Inserts the optional roles if values for the optional roles
exist.
"""
optional_roles = [
... |
def modify(db=None, sql=None):
'''
Issue an SQL query to sqlite3 (with no return data), usually used
to modify the database in some way (insert, delete, create, etc)
CLI Example:
.. code-block:: bash
salt '*' sqlite3.modify /root/test.db 'CREATE TABLE test(id INT, testdata TEXT);'
'''... | Issue an SQL query to sqlite3 (with no return data), usually used
to modify the database in some way (insert, delete, create, etc)
CLI Example:
.. code-block:: bash
salt '*' sqlite3.modify /root/test.db 'CREATE TABLE test(id INT, testdata TEXT);' | Below is the the instruction that describes the task:
### Input:
Issue an SQL query to sqlite3 (with no return data), usually used
to modify the database in some way (insert, delete, create, etc)
CLI Example:
.. code-block:: bash
salt '*' sqlite3.modify /root/test.db 'CREATE TABLE test(id INT... |
def _set_residue_map(self):
"""
map each residue to the corresponding molecule.
"""
self.map_residue_to_mol = {}
lookup = {}
for idx, mol in enumerate(self.mols):
if not mol.formula in lookup:
mol.translate_sites(indices=range(len(mol)),
... | map each residue to the corresponding molecule. | Below is the the instruction that describes the task:
### Input:
map each residue to the corresponding molecule.
### Response:
def _set_residue_map(self):
"""
map each residue to the corresponding molecule.
"""
self.map_residue_to_mol = {}
lookup = {}
for idx, mol in... |
def __get_activities(self, search):
"""returns list of activities for autocomplete,
activity names converted to lowercase"""
query = """
SELECT a.name AS name, b.name AS category
FROM activities a
LEFT JOIN categories b ON coalesce(b.id... | returns list of activities for autocomplete,
activity names converted to lowercase | Below is the the instruction that describes the task:
### Input:
returns list of activities for autocomplete,
activity names converted to lowercase
### Response:
def __get_activities(self, search):
"""returns list of activities for autocomplete,
activity names converted to lowercase""... |
def remove_out_of_bounds_bins(df, chromosome_size):
# type: (pd.DataFrame, int) -> pd.DataFrame
"""Remove all reads that were shifted outside of the genome endpoints."""
# The dataframe is empty and contains no bins out of bounds
if "Bin" not in df:
return df
df = df.drop(df[df.Bin > chrom... | Remove all reads that were shifted outside of the genome endpoints. | Below is the the instruction that describes the task:
### Input:
Remove all reads that were shifted outside of the genome endpoints.
### Response:
def remove_out_of_bounds_bins(df, chromosome_size):
# type: (pd.DataFrame, int) -> pd.DataFrame
"""Remove all reads that were shifted outside of the genome endp... |
def main(argv=None):
"""
Run wake on lan as a CLI application.
"""
parser = argparse.ArgumentParser(
description='Wake one or more computers using the wake on lan'
' protocol.')
parser.add_argument(
'macs',
metavar='mac address',
nargs='+',
... | Run wake on lan as a CLI application. | Below is the the instruction that describes the task:
### Input:
Run wake on lan as a CLI application.
### Response:
def main(argv=None):
"""
Run wake on lan as a CLI application.
"""
parser = argparse.ArgumentParser(
description='Wake one or more computers using the wake on lan'
... |
def deflections_from_grid(self, grid):
"""
Calculate the deflection angles at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on.
"""
... | Calculate the deflection angles at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on. | Below is the the instruction that describes the task:
### Input:
Calculate the deflection angles at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on.
### R... |
def equivalent_release_for_product(self, product):
"""
Returns the release for a specified product with the same
channel and major version with the highest minor version,
or None if no such releases exist
"""
releases = self._default_manager.filter(
version__s... | Returns the release for a specified product with the same
channel and major version with the highest minor version,
or None if no such releases exist | Below is the the instruction that describes the task:
### Input:
Returns the release for a specified product with the same
channel and major version with the highest minor version,
or None if no such releases exist
### Response:
def equivalent_release_for_product(self, product):
"""
... |
def configure_scraper(self, scraper_config):
"""
Configures a PrometheusScaper object with query credentials
:param scraper: valid PrometheusScaper object
:param endpoint: url that will be scraped
"""
endpoint = scraper_config['prometheus_url']
scraper_config.upda... | Configures a PrometheusScaper object with query credentials
:param scraper: valid PrometheusScaper object
:param endpoint: url that will be scraped | Below is the the instruction that describes the task:
### Input:
Configures a PrometheusScaper object with query credentials
:param scraper: valid PrometheusScaper object
:param endpoint: url that will be scraped
### Response:
def configure_scraper(self, scraper_config):
"""
Configu... |
def create_folder(self, dir_name: str, parent_dir_id: str) -> str:
"""
Create folder into Google Drive
:param dir_name:
:param parent_dir_name:
:return:
"""
service = self.__get_service()
file_metadata = {
'name': dir_name,
'mimeTyp... | Create folder into Google Drive
:param dir_name:
:param parent_dir_name:
:return: | Below is the the instruction that describes the task:
### Input:
Create folder into Google Drive
:param dir_name:
:param parent_dir_name:
:return:
### Response:
def create_folder(self, dir_name: str, parent_dir_id: str) -> str:
"""
Create folder into Google Drive
:pa... |
def replace_namespaced_replication_controller_status(self, name, namespace, body, **kwargs):
"""
replace status of the specified ReplicationController
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thr... | replace status of the specified ReplicationController
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_replication_controller_status(name, namespace, body, async_req=True)
>>> res... | Below is the the instruction that describes the task:
### Input:
replace status of the specified ReplicationController
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_replication_con... |
def check_origin(self):
"""Do some simple checking of the zone's origin.
@raises dns.zone.NoSOA: there is no SOA RR
@raises dns.zone.NoNS: there is no NS RRset
@raises KeyError: there is no origin node
"""
if self.relativize:
name = dns.name.empty
els... | Do some simple checking of the zone's origin.
@raises dns.zone.NoSOA: there is no SOA RR
@raises dns.zone.NoNS: there is no NS RRset
@raises KeyError: there is no origin node | Below is the the instruction that describes the task:
### Input:
Do some simple checking of the zone's origin.
@raises dns.zone.NoSOA: there is no SOA RR
@raises dns.zone.NoNS: there is no NS RRset
@raises KeyError: there is no origin node
### Response:
def check_origin(self):
"""D... |
def save(self):
"""
Saves changes made to the locally cached Document object's data
structures to the remote database. If the document does not exist
remotely then it is created in the remote database. If the object
does exist remotely then the document is updated remotely. In... | Saves changes made to the locally cached Document object's data
structures to the remote database. If the document does not exist
remotely then it is created in the remote database. If the object
does exist remotely then the document is updated remotely. In either
case the locally cac... | Below is the the instruction that describes the task:
### Input:
Saves changes made to the locally cached Document object's data
structures to the remote database. If the document does not exist
remotely then it is created in the remote database. If the object
does exist remotely then the ... |
def preferred_mmol(code):
""" Get mmol number of preferred biological assembly as listed in the PDBe.
Notes
-----
First checks for code in mmols.json.
If code not yet in this json dictionary, uses requests module to scrape the PDBE for the preferred mmol number.
Parameters
----------
c... | Get mmol number of preferred biological assembly as listed in the PDBe.
Notes
-----
First checks for code in mmols.json.
If code not yet in this json dictionary, uses requests module to scrape the PDBE for the preferred mmol number.
Parameters
----------
code : str
A PDB code.
... | Below is the the instruction that describes the task:
### Input:
Get mmol number of preferred biological assembly as listed in the PDBe.
Notes
-----
First checks for code in mmols.json.
If code not yet in this json dictionary, uses requests module to scrape the PDBE for the preferred mmol number.
... |
def _float_check(self, attribute_array, value, irow, key):
'''Checks if value is valid float, appends to array if valid, appends
nan if not'''
value = value.strip(' ')
try:
if value:
attribute_array = np.hstack([attribute_array, float(value)])
else... | Checks if value is valid float, appends to array if valid, appends
nan if not | Below is the the instruction that describes the task:
### Input:
Checks if value is valid float, appends to array if valid, appends
nan if not
### Response:
def _float_check(self, attribute_array, value, irow, key):
'''Checks if value is valid float, appends to array if valid, appends
nan i... |
def transform_dataframe(self, dataframe):
"""
Unstack the dataframe so header fields are across the top.
"""
dataframe.columns.name = ""
for i in range(len(self.get_header_fields())):
dataframe = dataframe.unstack()
# Remove blank rows / columns
data... | Unstack the dataframe so header fields are across the top. | Below is the the instruction that describes the task:
### Input:
Unstack the dataframe so header fields are across the top.
### Response:
def transform_dataframe(self, dataframe):
"""
Unstack the dataframe so header fields are across the top.
"""
dataframe.columns.name = ""
... |
def add(self, child, min_occurs=1):
"""Add a child node.
@param child: The schema for the child node.
@param min_occurs: The minimum number of times the child node must
occur, if C{None} is given the default is 1.
"""
if not min_occurs in (0, 1):
raise Ru... | Add a child node.
@param child: The schema for the child node.
@param min_occurs: The minimum number of times the child node must
occur, if C{None} is given the default is 1. | Below is the the instruction that describes the task:
### Input:
Add a child node.
@param child: The schema for the child node.
@param min_occurs: The minimum number of times the child node must
occur, if C{None} is given the default is 1.
### Response:
def add(self, child, min_occurs=... |
def boxplot(df, plot_mean=False, plot_ids=None, title=None, xlabel=None, ylabel=None):
"""
Plot boxplots
Plot the boxplots of a dataframe in time
Parameters
----------
df: Pandas Dataframe
Every collumn is a timeseries
plot_mean: bool
Wether or not to plot the means
plo... | Plot boxplots
Plot the boxplots of a dataframe in time
Parameters
----------
df: Pandas Dataframe
Every collumn is a timeseries
plot_mean: bool
Wether or not to plot the means
plot_ids: [str]
List of id's to plot
Returns
-------
matplotlib figure | Below is the the instruction that describes the task:
### Input:
Plot boxplots
Plot the boxplots of a dataframe in time
Parameters
----------
df: Pandas Dataframe
Every collumn is a timeseries
plot_mean: bool
Wether or not to plot the means
plot_ids: [str]
List of i... |
def send_notifications(self, notification_type, *args):
""" Fires off the notification for the specific event. Uses var args to pass in a
arbitrary list of parameter according to which notification type was fired.
Args:
notification_type: Type of notification to fire (String from .helpers.enums.... | Fires off the notification for the specific event. Uses var args to pass in a
arbitrary list of parameter according to which notification type was fired.
Args:
notification_type: Type of notification to fire (String from .helpers.enums.NotificationTypes)
args: variable list of arguments to the... | Below is the the instruction that describes the task:
### Input:
Fires off the notification for the specific event. Uses var args to pass in a
arbitrary list of parameter according to which notification type was fired.
Args:
notification_type: Type of notification to fire (String from .helpers.e... |
def assets(self):
"""
Provides access to asset management methods.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets
:return: :class:`EnvironmentAssetsProxy <contentful_management.environment_assets_proxy.EnvironmentAssetsPro... | Provides access to asset management methods.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets
:return: :class:`EnvironmentAssetsProxy <contentful_management.environment_assets_proxy.EnvironmentAssetsProxy>` object.
:rtype: contentfu... | Below is the the instruction that describes the task:
### Input:
Provides access to asset management methods.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets
:return: :class:`EnvironmentAssetsProxy <contentful_management.environment_as... |
def print_upper_triangular_matrix_as_complete(matrix):
"""Prints a CVRP data dict upper triangular matrix as a normal matrix
Doesn't print headers.
Arguments
---------
matrix : dict
Description
"""
for i in sorted(matrix.keys()):
for j in sorted(matrix.keys... | Prints a CVRP data dict upper triangular matrix as a normal matrix
Doesn't print headers.
Arguments
---------
matrix : dict
Description | Below is the the instruction that describes the task:
### Input:
Prints a CVRP data dict upper triangular matrix as a normal matrix
Doesn't print headers.
Arguments
---------
matrix : dict
Description
### Response:
def print_upper_triangular_matrix_as_complete(matrix):
"""Prin... |
def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argument(key) | Get the value of a command argument. | Below is the the instruction that describes the task:
### Input:
Get the value of a command argument.
### Response:
def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argumen... |
def find_once(self, locator):
"""
Find wrapper to run a single find
@type locator: webdriverwrapper.support.locator.Locator
@param locator: locator used in search
@type find_all: bool
@param find_all: should I find all elements, or just on... | Find wrapper to run a single find
@type locator: webdriverwrapper.support.locator.Locator
@param locator: locator used in search
@type find_all: bool
@param find_all: should I find all elements, or just one?
@rtype: WebElementWrap... | Below is the the instruction that describes the task:
### Input:
Find wrapper to run a single find
@type locator: webdriverwrapper.support.locator.Locator
@param locator: locator used in search
@type find_all: bool
@param find_all: should I find all e... |
def process(self, metric):
"""
Process a metric by sending it to Librato
"""
path = metric.getCollectorPath()
path += '.'
path += metric.getMetricPath()
if self.config['apply_metric_prefix']:
path = metric.getPathPrefix() + '.' + path
if self.... | Process a metric by sending it to Librato | Below is the the instruction that describes the task:
### Input:
Process a metric by sending it to Librato
### Response:
def process(self, metric):
"""
Process a metric by sending it to Librato
"""
path = metric.getCollectorPath()
path += '.'
path += metric.getMetric... |
def query_json(json_content, query, delimiter='.'):
""" Do an xpath-like query with json_content.
Args:
json_content (dict/list/string): content to be queried.
query (str): query string.
delimiter (str): delimiter symbol.
Returns:
str: queried result.
Examples:
... | Do an xpath-like query with json_content.
Args:
json_content (dict/list/string): content to be queried.
query (str): query string.
delimiter (str): delimiter symbol.
Returns:
str: queried result.
Examples:
>>> json_content = {
"ids": [1, 2, 3, 4],
... | Below is the the instruction that describes the task:
### Input:
Do an xpath-like query with json_content.
Args:
json_content (dict/list/string): content to be queried.
query (str): query string.
delimiter (str): delimiter symbol.
Returns:
str: queried result.
Examples... |
def remove_line(self, section, line):
"""Remove all instances of a line.
Returns:
int: the number of lines removed
"""
try:
s = self._get_section(section, create=False)
except KeyError:
# No such section, skip.
return 0
re... | Remove all instances of a line.
Returns:
int: the number of lines removed | Below is the the instruction that describes the task:
### Input:
Remove all instances of a line.
Returns:
int: the number of lines removed
### Response:
def remove_line(self, section, line):
"""Remove all instances of a line.
Returns:
int: the number of lines remov... |
def save_df_output(
df_output: pd.DataFrame,
freq_s: int = 3600,
site: str = '',
path_dir_save: Path = Path('.'),)->list:
'''save supy output dataframe to txt files
Parameters
----------
df_output : pd.DataFrame
output dataframe of supy simulation
freq_s : in... | save supy output dataframe to txt files
Parameters
----------
df_output : pd.DataFrame
output dataframe of supy simulation
freq_s : int, optional
output frequency in second (the default is 3600, which indicates the a txt with hourly values)
path_dir_save : Path, optional
dir... | Below is the the instruction that describes the task:
### Input:
save supy output dataframe to txt files
Parameters
----------
df_output : pd.DataFrame
output dataframe of supy simulation
freq_s : int, optional
output frequency in second (the default is 3600, which indicates the a t... |
def add_file(self, path, parent=None, tree=TreeType.SOURCE_ROOT, target_name=None, force=True, file_options=FileOptions()):
"""
Adds a file to the project, taking care of the type of the file and creating additional structures depending on
the file type. For instance, frameworks will be linked, ... | Adds a file to the project, taking care of the type of the file and creating additional structures depending on
the file type. For instance, frameworks will be linked, embedded and search paths will be adjusted automatically.
Header file will be added to the headers sections, but not compiled, whereas t... | Below is the the instruction that describes the task:
### Input:
Adds a file to the project, taking care of the type of the file and creating additional structures depending on
the file type. For instance, frameworks will be linked, embedded and search paths will be adjusted automatically.
Header fi... |
def command_py2to3(args):
"""
Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.
"""
from lib2to3.main import main
sys.exit(main("lib2to3.fixes", args=args.sources)) | Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources. | Below is the the instruction that describes the task:
### Input:
Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.
### Response:
def command_py2to3(args):
"""
Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.
"""
from lib2to3.main import main
sys.... |
def get_static_dependencies(self, dependencies=None, include_beta=None):
"""Resolves the project -> dependencies section of cumulusci.yml
to convert dynamic github dependencies into static dependencies
by inspecting the referenced repositories
Keyword arguments:
:param d... | Resolves the project -> dependencies section of cumulusci.yml
to convert dynamic github dependencies into static dependencies
by inspecting the referenced repositories
Keyword arguments:
:param dependencies: a list of dependencies to resolve
:param include_beta: when tru... | Below is the the instruction that describes the task:
### Input:
Resolves the project -> dependencies section of cumulusci.yml
to convert dynamic github dependencies into static dependencies
by inspecting the referenced repositories
Keyword arguments:
:param dependencies: a ... |
def buildout(directory='.',
config='buildout.cfg',
parts=None,
runas=None,
env=(),
buildout_ver=None,
test_release=False,
distribute=None,
new_st=None,
offline=False,
newest=False,
... | Run buildout in a directory.
directory
directory to execute in
config
buildout config to use
parts
specific buildout parts to run
runas
user used to run buildout as
env
environment variables to set when running
buildout_ver
force a specific b... | Below is the the instruction that describes the task:
### Input:
Run buildout in a directory.
directory
directory to execute in
config
buildout config to use
parts
specific buildout parts to run
runas
user used to run buildout as
env
environment varia... |
def _named_tuple_converter(tuple_type):
# type: (Type[Tuple]) -> _AggregateConverter
"""Return an _AggregateConverter for named tuples of the given type."""
def _from_dict(dict_value):
if dict_value:
return tuple_type(**dict_value)
# Cannot construct a namedtuple value from an e... | Return an _AggregateConverter for named tuples of the given type. | Below is the the instruction that describes the task:
### Input:
Return an _AggregateConverter for named tuples of the given type.
### Response:
def _named_tuple_converter(tuple_type):
# type: (Type[Tuple]) -> _AggregateConverter
"""Return an _AggregateConverter for named tuples of the given type."""
d... |
def set_attribute(self, name, value):
""" Default handler for those not explicitly defined """
if value is True:
self.widget.set(name, name)
elif value is False:
del self.widget.attrib[name]
else:
self.widget.set(name, str(value)) | Default handler for those not explicitly defined | Below is the the instruction that describes the task:
### Input:
Default handler for those not explicitly defined
### Response:
def set_attribute(self, name, value):
""" Default handler for those not explicitly defined """
if value is True:
self.widget.set(name, name)
elif value... |
def timestr2time(time_str):
'''
Turns a string into a datetime.time object. This will only work if the
format can be "guessed", so the string must have one of the formats from
VALID_TIME_FORMATS_TEXT.
Args:
time_str (str) a string that represents a date
Returns:
datetime.time o... | Turns a string into a datetime.time object. This will only work if the
format can be "guessed", so the string must have one of the formats from
VALID_TIME_FORMATS_TEXT.
Args:
time_str (str) a string that represents a date
Returns:
datetime.time object
Raises:
ValueError if ... | Below is the the instruction that describes the task:
### Input:
Turns a string into a datetime.time object. This will only work if the
format can be "guessed", so the string must have one of the formats from
VALID_TIME_FORMATS_TEXT.
Args:
time_str (str) a string that represents a date
Ret... |
def p_qualifierType_2(p):
"""qualifierType_2 : ':' dataType
| ':' dataType defaultValue
"""
dv = None
if len(p) == 4:
dv = p[3]
p[0] = (p[2], False, None, dv) | qualifierType_2 : ':' dataType
| ':' dataType defaultValue | Below is the the instruction that describes the task:
### Input:
qualifierType_2 : ':' dataType
| ':' dataType defaultValue
### Response:
def p_qualifierType_2(p):
"""qualifierType_2 : ':' dataType
| ':' dataType defaultValue
"""
dv = Non... |
def _encode_penman(self, g, top=None):
"""
Walk graph g and find a spanning dag, then serialize the result.
First, depth-first traversal of preferred orientations (whether
true or inverted) to create graph p.
If any triples remain, select the first remaining triple whose
... | Walk graph g and find a spanning dag, then serialize the result.
First, depth-first traversal of preferred orientations (whether
true or inverted) to create graph p.
If any triples remain, select the first remaining triple whose
source in the dispreferred orientation exists in p, where... | Below is the the instruction that describes the task:
### Input:
Walk graph g and find a spanning dag, then serialize the result.
First, depth-first traversal of preferred orientations (whether
true or inverted) to create graph p.
If any triples remain, select the first remaining triple wh... |
def get_previous_month(self):
"""Returns date range for the previous full month."""
end = utils.get_month_start() - relativedelta(days=1)
end = utils.to_datetime(end)
start = utils.get_month_start(end)
return start, end | Returns date range for the previous full month. | Below is the the instruction that describes the task:
### Input:
Returns date range for the previous full month.
### Response:
def get_previous_month(self):
"""Returns date range for the previous full month."""
end = utils.get_month_start() - relativedelta(days=1)
end = utils.to_datetime(en... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.