code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_structure_from_mp(formula):
"""
Convenience method to get a crystal from the Materials Project database via
the API. Requires PMG_MAPI_KEY to be set.
Args:
formula (str): A formula
Returns:
(Structure) The lowest energy structure in Materials Project with that
f... | Convenience method to get a crystal from the Materials Project database via
the API. Requires PMG_MAPI_KEY to be set.
Args:
formula (str): A formula
Returns:
(Structure) The lowest energy structure in Materials Project with that
formula. | Below is the the instruction that describes the task:
### Input:
Convenience method to get a crystal from the Materials Project database via
the API. Requires PMG_MAPI_KEY to be set.
Args:
formula (str): A formula
Returns:
(Structure) The lowest energy structure in Materials Project wi... |
def make_ica_funs(observed_dimension, latent_dimension):
"""These functions implement independent component analysis.
The model is:
latents are drawn i.i.d. for each data point from a product of student-ts.
weights are the same across all datapoints.
each data = latents * weghts + noise."""
de... | These functions implement independent component analysis.
The model is:
latents are drawn i.i.d. for each data point from a product of student-ts.
weights are the same across all datapoints.
each data = latents * weghts + noise. | Below is the the instruction that describes the task:
### Input:
These functions implement independent component analysis.
The model is:
latents are drawn i.i.d. for each data point from a product of student-ts.
weights are the same across all datapoints.
each data = latents * weghts + noise.
### R... |
def patterned(self):
"""Selects the pattern fill type.
Note that calling this method does not by itself set a foreground or
background color of the pattern. Rather it enables subsequent
assignments to properties like fore_color to set the pattern and
colors.
"""
... | Selects the pattern fill type.
Note that calling this method does not by itself set a foreground or
background color of the pattern. Rather it enables subsequent
assignments to properties like fore_color to set the pattern and
colors. | Below is the the instruction that describes the task:
### Input:
Selects the pattern fill type.
Note that calling this method does not by itself set a foreground or
background color of the pattern. Rather it enables subsequent
assignments to properties like fore_color to set the pattern and... |
def run(self):
"""Run charge balance command"""
# Load compound information
def compound_name(id):
if id not in self._model.compounds:
return id
return self._model.compounds[id].properties.get('name', id)
# Create a set of excluded reactions
... | Run charge balance command | Below is the the instruction that describes the task:
### Input:
Run charge balance command
### Response:
def run(self):
"""Run charge balance command"""
# Load compound information
def compound_name(id):
if id not in self._model.compounds:
return id
... |
def variantsGenerator(self, request):
"""
Returns a generator over the (variant, nextPageToken) pairs defined
by the specified request.
"""
compoundId = datamodel.VariantSetCompoundId \
.parse(request.variant_set_id)
dataset = self.getDataRepository().getDatas... | Returns a generator over the (variant, nextPageToken) pairs defined
by the specified request. | Below is the the instruction that describes the task:
### Input:
Returns a generator over the (variant, nextPageToken) pairs defined
by the specified request.
### Response:
def variantsGenerator(self, request):
"""
Returns a generator over the (variant, nextPageToken) pairs defined
... |
def flaskrun(app, default_host="127.0.0.1", default_port="8000"):
"""
Takes a flask.Flask instance and runs it. Parses
command-line flags to configure the app.
"""
# Set up the command-line options
parser = optparse.OptionParser()
parser.add_option(
"-H",
"--host",
h... | Takes a flask.Flask instance and runs it. Parses
command-line flags to configure the app. | Below is the the instruction that describes the task:
### Input:
Takes a flask.Flask instance and runs it. Parses
command-line flags to configure the app.
### Response:
def flaskrun(app, default_host="127.0.0.1", default_port="8000"):
"""
Takes a flask.Flask instance and runs it. Parses
command-lin... |
def set_connected(self, connected):
"""
:param bool connected:
"""
with self.__connect_wait_condition:
self.connected = connected
if connected:
self.__connect_wait_condition.notify() | :param bool connected: | Below is the the instruction that describes the task:
### Input:
:param bool connected:
### Response:
def set_connected(self, connected):
"""
:param bool connected:
"""
with self.__connect_wait_condition:
self.connected = connected
if connected:
... |
def ls(obj=None):
"""List available layers, or infos on a given layer"""
if obj is None:
import builtins
all = builtins.__dict__.copy()
all.update(globals())
objlst = sorted(conf.layers, key=lambda x:x.__name__)
for o in objlst:
print("%-10s : %s" %(... | List available layers, or infos on a given layer | Below is the the instruction that describes the task:
### Input:
List available layers, or infos on a given layer
### Response:
def ls(obj=None):
"""List available layers, or infos on a given layer"""
if obj is None:
import builtins
all = builtins.__dict__.copy()
all.upda... |
def _build_models_query(self, query):
"""
Builds a query from `query` that filters to documents only from registered models.
"""
registered_models_ct = self.build_models_list()
if registered_models_ct:
restrictions = [xapian.Query('%s%s' % (TERM_PREFIXES[DJANGO_CT], m... | Builds a query from `query` that filters to documents only from registered models. | Below is the the instruction that describes the task:
### Input:
Builds a query from `query` that filters to documents only from registered models.
### Response:
def _build_models_query(self, query):
"""
Builds a query from `query` that filters to documents only from registered models.
"""
... |
def _initialize_with_array(self, data, rowBased=True):
"""Set the matrix values from a two dimensional list."""
if rowBased:
self.matrix = []
if len(data) != self._rows:
raise ValueError("Size of Matrix does not match")
for col in xrange(self._columns)... | Set the matrix values from a two dimensional list. | Below is the the instruction that describes the task:
### Input:
Set the matrix values from a two dimensional list.
### Response:
def _initialize_with_array(self, data, rowBased=True):
"""Set the matrix values from a two dimensional list."""
if rowBased:
self.matrix = []
if ... |
def save_assessment_part(self, assessment_part_form, *args, **kwargs):
"""Pass through to provider AssessmentPartAdminSession.update_assessment_part"""
# Implemented from kitosid template for -
# osid.resource.ResourceAdminSession.update_resource
if assessment_part_form.is_for_update():
... | Pass through to provider AssessmentPartAdminSession.update_assessment_part | Below is the the instruction that describes the task:
### Input:
Pass through to provider AssessmentPartAdminSession.update_assessment_part
### Response:
def save_assessment_part(self, assessment_part_form, *args, **kwargs):
"""Pass through to provider AssessmentPartAdminSession.update_assessment_part"""
... |
def run(self):
"""Connect to SABnzbd and get the data."""
try:
answer = urlopen(self.url + "&mode=queue").read().decode()
except (HTTPError, URLError) as error:
self.output = {
"full_text": str(error.reason),
"color": "#FF0000"
... | Connect to SABnzbd and get the data. | Below is the the instruction that describes the task:
### Input:
Connect to SABnzbd and get the data.
### Response:
def run(self):
"""Connect to SABnzbd and get the data."""
try:
answer = urlopen(self.url + "&mode=queue").read().decode()
except (HTTPError, URLError) as error:
... |
def _op_method(self, data):
"""Operator
This method returns the input data operated on by all of the operators
Parameters
----------
data : np.ndarray
Input data array
Returns
-------
np.ndarray linear operation results
"""
... | Operator
This method returns the input data operated on by all of the operators
Parameters
----------
data : np.ndarray
Input data array
Returns
-------
np.ndarray linear operation results | Below is the the instruction that describes the task:
### Input:
Operator
This method returns the input data operated on by all of the operators
Parameters
----------
data : np.ndarray
Input data array
Returns
-------
np.ndarray linear operation... |
def _row_selector(self, other):
"""
Where other is an SArray of identical length as the current Frame,
this returns a selection of a subset of rows in the current SFrame
where the corresponding row in the selector is non-zero.
"""
if type(other) is SArray:
if ... | Where other is an SArray of identical length as the current Frame,
this returns a selection of a subset of rows in the current SFrame
where the corresponding row in the selector is non-zero. | Below is the the instruction that describes the task:
### Input:
Where other is an SArray of identical length as the current Frame,
this returns a selection of a subset of rows in the current SFrame
where the corresponding row in the selector is non-zero.
### Response:
def _row_selector(self, other... |
def submit_response(self, assessment_section_id, item_id, answer_form):
"""Submits an answer to an item.
arg: assessment_section_id (osid.id.Id): ``Id`` of the
``AssessmentSection``
arg: item_id (osid.id.Id): ``Id`` of the ``Item``
arg: answer_form (osid.assessm... | Submits an answer to an item.
arg: assessment_section_id (osid.id.Id): ``Id`` of the
``AssessmentSection``
arg: item_id (osid.id.Id): ``Id`` of the ``Item``
arg: answer_form (osid.assessment.AnswerForm): the response
raise: IllegalState - ``has_assessment_secti... | Below is the the instruction that describes the task:
### Input:
Submits an answer to an item.
arg: assessment_section_id (osid.id.Id): ``Id`` of the
``AssessmentSection``
arg: item_id (osid.id.Id): ``Id`` of the ``Item``
arg: answer_form (osid.assessment.AnswerForm... |
def _none_rejecter(validation_callable # type: Callable
):
# type: (...) -> Callable
"""
Wraps the given validation callable to reject None values. When a None value is received by the wrapper,
it is not passed to the validation_callable and instead this function will raise a Wrappin... | Wraps the given validation callable to reject None values. When a None value is received by the wrapper,
it is not passed to the validation_callable and instead this function will raise a WrappingFailure. When any other value is
received the validation_callable is called as usual.
:param validation_callabl... | Below is the the instruction that describes the task:
### Input:
Wraps the given validation callable to reject None values. When a None value is received by the wrapper,
it is not passed to the validation_callable and instead this function will raise a WrappingFailure. When any other value is
received the v... |
def traverse_bfs(self):
'''Perform a Breadth-First Search (BFS) starting at this ``Node`` object'. Yields (``Node``, distance) tuples
Args:
``include_self`` (``bool``): ``True`` to include self in the traversal, otherwise ``False``
'''
if not isinstance(include_self,... | Perform a Breadth-First Search (BFS) starting at this ``Node`` object'. Yields (``Node``, distance) tuples
Args:
``include_self`` (``bool``): ``True`` to include self in the traversal, otherwise ``False`` | Below is the the instruction that describes the task:
### Input:
Perform a Breadth-First Search (BFS) starting at this ``Node`` object'. Yields (``Node``, distance) tuples
Args:
``include_self`` (``bool``): ``True`` to include self in the traversal, otherwise ``False``
### Response:
de... |
def status(name, sig=None):
'''
Return the status for a service via daemontools, return pid if running
CLI Example:
.. code-block:: bash
salt '*' daemontools.status <service name>
'''
cmd = 'svstat {0}'.format(_service_path(name))
out = __salt__['cmd.run_stdout'](cmd, python_shell... | Return the status for a service via daemontools, return pid if running
CLI Example:
.. code-block:: bash
salt '*' daemontools.status <service name> | Below is the the instruction that describes the task:
### Input:
Return the status for a service via daemontools, return pid if running
CLI Example:
.. code-block:: bash
salt '*' daemontools.status <service name>
### Response:
def status(name, sig=None):
'''
Return the status for a servi... |
def p_startswith(self, st, ignorecase=False):
"Return True if the input starts with `st` at current position"
length = len(st)
matcher = result = self.input[self.pos:self.pos + length]
if ignorecase:
matcher = result.lower()
st = st.lower()
if matcher == s... | Return True if the input starts with `st` at current position | Below is the the instruction that describes the task:
### Input:
Return True if the input starts with `st` at current position
### Response:
def p_startswith(self, st, ignorecase=False):
"Return True if the input starts with `st` at current position"
length = len(st)
matcher = result = self... |
def _non_framed_body_length(header, plaintext_length):
"""Calculates the length of a non-framed message body, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int plaintext_length: Length of plaintext in bytes
:r... | Calculates the length of a non-framed message body, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int plaintext_length: Length of plaintext in bytes
:rtype: int | Below is the the instruction that describes the task:
### Input:
Calculates the length of a non-framed message body, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int plaintext_length: Length of plaintext in bytes... |
def predict(data, training_dir=None, model_name=None, model_version=None, cloud=False):
"""Runs prediction locally or on the cloud.
Args:
data: List of csv strings or a Pandas DataFrame that match the model schema.
training_dir: local path to the trained output folder.
model_name: deployed model name
... | Runs prediction locally or on the cloud.
Args:
data: List of csv strings or a Pandas DataFrame that match the model schema.
training_dir: local path to the trained output folder.
model_name: deployed model name
model_version: depoyed model version
cloud: bool. If False, does local prediction and ... | Below is the the instruction that describes the task:
### Input:
Runs prediction locally or on the cloud.
Args:
data: List of csv strings or a Pandas DataFrame that match the model schema.
training_dir: local path to the trained output folder.
model_name: deployed model name
model_version: depoye... |
def load_plugin(plugin_name):
"""
Given a plugin name, load plugin cls from plugin directory.
Will throw an exception if no plugin can be found.
"""
plugin_cls = plugin_map.get(plugin_name, None)
if not plugin_cls:
try:
plugin_module_name, plugin_cls_name = plugin_name.split(... | Given a plugin name, load plugin cls from plugin directory.
Will throw an exception if no plugin can be found. | Below is the the instruction that describes the task:
### Input:
Given a plugin name, load plugin cls from plugin directory.
Will throw an exception if no plugin can be found.
### Response:
def load_plugin(plugin_name):
"""
Given a plugin name, load plugin cls from plugin directory.
Will throw an e... |
def get_start_array(self, *start_words, **kwargs):
"""
Генерирует начало предложения.
:start_words: Попытаться начать предложение с этих слов.
"""
if not self.start_arrays:
raise MarkovTextExcept("Не с чего начинать генерацию.")
if not start_words:
... | Генерирует начало предложения.
:start_words: Попытаться начать предложение с этих слов. | Below is the the instruction that describes the task:
### Input:
Генерирует начало предложения.
:start_words: Попытаться начать предложение с этих слов.
### Response:
def get_start_array(self, *start_words, **kwargs):
"""
Генерирует начало предложения.
:start_words: Попытаться начат... |
def sample(self, iter, length=None, verbose=0):
"""
Draws iter samples from the posterior.
"""
self._cur_trace_index = 0
self.max_trace_length = iter
self._iter = iter
self.verbose = verbose or 0
self.seed()
# Assign Trace instances to tallyable o... | Draws iter samples from the posterior. | Below is the the instruction that describes the task:
### Input:
Draws iter samples from the posterior.
### Response:
def sample(self, iter, length=None, verbose=0):
"""
Draws iter samples from the posterior.
"""
self._cur_trace_index = 0
self.max_trace_length = iter
... |
def _filenames_from_arg(filename):
"""Utility function to deal with polymorphic filenames argument."""
if isinstance(filename, string_types):
filenames = [filename]
elif isinstance(filename, (list, tuple)):
filenames = filename
else:
raise Exception('filename argument must be str... | Utility function to deal with polymorphic filenames argument. | Below is the the instruction that describes the task:
### Input:
Utility function to deal with polymorphic filenames argument.
### Response:
def _filenames_from_arg(filename):
"""Utility function to deal with polymorphic filenames argument."""
if isinstance(filename, string_types):
filenames = [fil... |
def insertPrimaryDataset(self):
"""
API to insert A primary dataset in DBS
:param primaryDSObj: primary dataset object
:type primaryDSObj: dict
:key primary_ds_type: TYPE (out of valid types in DBS, MC, DATA) (Required)
:key primary_ds_name: Name of the primary dataset (... | API to insert A primary dataset in DBS
:param primaryDSObj: primary dataset object
:type primaryDSObj: dict
:key primary_ds_type: TYPE (out of valid types in DBS, MC, DATA) (Required)
:key primary_ds_name: Name of the primary dataset (Required) | Below is the the instruction that describes the task:
### Input:
API to insert A primary dataset in DBS
:param primaryDSObj: primary dataset object
:type primaryDSObj: dict
:key primary_ds_type: TYPE (out of valid types in DBS, MC, DATA) (Required)
:key primary_ds_name: Name of the ... |
def list_view_on_selected(self, widget, selected_item_key):
""" The selection event of the listView, returns a key of the clicked event.
You can retrieve the item rapidly
"""
self.lbl.set_text('List selection: ' + self.listView.children[selected_item_key].get_text()) | The selection event of the listView, returns a key of the clicked event.
You can retrieve the item rapidly | Below is the the instruction that describes the task:
### Input:
The selection event of the listView, returns a key of the clicked event.
You can retrieve the item rapidly
### Response:
def list_view_on_selected(self, widget, selected_item_key):
""" The selection event of the listView, returns ... |
def ready(self):
'''Whether or not enough time has passed since the last failure'''
if self._last_failed:
delta = time.time() - self._last_failed
return delta >= self.backoff()
return True | Whether or not enough time has passed since the last failure | Below is the the instruction that describes the task:
### Input:
Whether or not enough time has passed since the last failure
### Response:
def ready(self):
'''Whether or not enough time has passed since the last failure'''
if self._last_failed:
delta = time.time() - self._last_failed
... |
def create_subscription(self, client_id, client_secret, callback_url,
object_type=model.Subscription.OBJECT_TYPE_ACTIVITY,
aspect_type=model.Subscription.ASPECT_TYPE_CREATE,
verify_token=model.Subscription.VERIFY_TOKEN_DEFAULT):
... | Creates a webhook event subscription.
http://strava.github.io/api/partner/v3/events/#create-a-subscription
:param client_id: application's ID, obtained during registration
:type client_id: int
:param client_secret: application's secret, obtained during registration
:type clien... | Below is the the instruction that describes the task:
### Input:
Creates a webhook event subscription.
http://strava.github.io/api/partner/v3/events/#create-a-subscription
:param client_id: application's ID, obtained during registration
:type client_id: int
:param client_secret: a... |
def get_transactions(self, include_investment=False):
"""Returns the transaction data as a Pandas DataFrame."""
assert_pd()
s = StringIO(self.get_transactions_csv(
include_investment=include_investment))
s.seek(0)
df = pd.read_csv(s, parse_dates=['Date'])
df.c... | Returns the transaction data as a Pandas DataFrame. | Below is the the instruction that describes the task:
### Input:
Returns the transaction data as a Pandas DataFrame.
### Response:
def get_transactions(self, include_investment=False):
"""Returns the transaction data as a Pandas DataFrame."""
assert_pd()
s = StringIO(self.get_transactions_c... |
def clean_extra(self):
"""Clean extra files/directories specified by get_extra_paths()"""
extra_paths = self.get_extra_paths()
for path in extra_paths:
if not os.path.exists(path):
continue
if os.path.isdir(path):
self._clean_directory(path... | Clean extra files/directories specified by get_extra_paths() | Below is the the instruction that describes the task:
### Input:
Clean extra files/directories specified by get_extra_paths()
### Response:
def clean_extra(self):
"""Clean extra files/directories specified by get_extra_paths()"""
extra_paths = self.get_extra_paths()
for path in extra_paths:... |
def coverage_pileup(self, space, start, end):
"""Retrieve pileup coverage across a specified region.
"""
return ((col.pos, self._normalize(col.n, self._total))
for col in self._bam.pileup(space, start, end)) | Retrieve pileup coverage across a specified region. | Below is the the instruction that describes the task:
### Input:
Retrieve pileup coverage across a specified region.
### Response:
def coverage_pileup(self, space, start, end):
"""Retrieve pileup coverage across a specified region.
"""
return ((col.pos, self._normalize(col.n, self._total))
... |
def is_dir(dirname):
'''Checks if a path is an actual directory that exists'''
if not os.path.isdir(dirname):
msg = "{0} is not a directory".format(dirname)
raise argparse.ArgumentTypeError(msg)
else:
return dirname | Checks if a path is an actual directory that exists | Below is the the instruction that describes the task:
### Input:
Checks if a path is an actual directory that exists
### Response:
def is_dir(dirname):
'''Checks if a path is an actual directory that exists'''
if not os.path.isdir(dirname):
msg = "{0} is not a directory".format(dirname)
rai... |
def get_amount_arrears_transactions(self, billing_cycle):
"""Get the sum of all transaction legs in to_account during given billing cycle"""
previous_billing_cycle = billing_cycle.get_previous()
if not previous_billing_cycle:
return Decimal(0)
return self.to_account.balance(
... | Get the sum of all transaction legs in to_account during given billing cycle | Below is the the instruction that describes the task:
### Input:
Get the sum of all transaction legs in to_account during given billing cycle
### Response:
def get_amount_arrears_transactions(self, billing_cycle):
"""Get the sum of all transaction legs in to_account during given billing cycle"""
pr... |
def to_internal_value(self, data):
"""Convert to internal value."""
user = getattr(self.context.get('request'), 'user')
queryset = self.get_queryset()
permission = get_full_perm('view', queryset.model)
try:
return get_objects_for_user(
user,
... | Convert to internal value. | Below is the the instruction that describes the task:
### Input:
Convert to internal value.
### Response:
def to_internal_value(self, data):
"""Convert to internal value."""
user = getattr(self.context.get('request'), 'user')
queryset = self.get_queryset()
permission = get_full_perm... |
def exec_command(command, cwd=None):
r'''
Helper to exec locally (subprocess) or remotely (paramiko)
'''
rc = None
stdout = stderr = None
if ssh_conn is None:
ld_library_path = {'LD_LIBRARY_PATH': '.:%s' % os.environ.get('LD_LIBRARY_PATH', '')}
p = subprocess.Popen(command, stdo... | r'''
Helper to exec locally (subprocess) or remotely (paramiko) | Below is the the instruction that describes the task:
### Input:
r'''
Helper to exec locally (subprocess) or remotely (paramiko)
### Response:
def exec_command(command, cwd=None):
r'''
Helper to exec locally (subprocess) or remotely (paramiko)
'''
rc = None
stdout = stderr = None
if ss... |
def publish_to_target(self, target_arn, message):
"""
Publish a message to a topic or an endpoint.
:param target_arn: either a TopicArn or an EndpointArn
:type target_arn: str
:param message: the default message you want to send
:param message: str
"""
c... | Publish a message to a topic or an endpoint.
:param target_arn: either a TopicArn or an EndpointArn
:type target_arn: str
:param message: the default message you want to send
:param message: str | Below is the the instruction that describes the task:
### Input:
Publish a message to a topic or an endpoint.
:param target_arn: either a TopicArn or an EndpointArn
:type target_arn: str
:param message: the default message you want to send
:param message: str
### Response:
def publ... |
def update(path,value,timestamp=None):
"""update(path,value,timestamp=None)
path is a string
value is a float
timestamp is either an int or float
"""
value = float(value)
fh = None
try:
fh = open(path,'r+b')
return file_update(fh, value, timestamp)
finally:
if fh:
fh.close() | update(path,value,timestamp=None)
path is a string
value is a float
timestamp is either an int or float | Below is the the instruction that describes the task:
### Input:
update(path,value,timestamp=None)
path is a string
value is a float
timestamp is either an int or float
### Response:
def update(path,value,timestamp=None):
"""update(path,value,timestamp=None)
path is a string
value is a float
timestamp is eithe... |
def detectAndroid(self):
"""Return detection of an Android device
Detects *any* Android OS-based device: phone, tablet, and multi-media player.
Also detects Google TV.
"""
if UAgentInfo.deviceAndroid in self.__userAgent \
or self.detectGoogleTV():
return T... | Return detection of an Android device
Detects *any* Android OS-based device: phone, tablet, and multi-media player.
Also detects Google TV. | Below is the the instruction that describes the task:
### Input:
Return detection of an Android device
Detects *any* Android OS-based device: phone, tablet, and multi-media player.
Also detects Google TV.
### Response:
def detectAndroid(self):
"""Return detection of an Android device
... |
def add_field(self, field, **kwargs):
"""Add each field as a private field."""
getattr(self, self._private_fields_name).append(field)
self._expire_cache(reverse=True)
self._expire_cache(reverse=False) | Add each field as a private field. | Below is the the instruction that describes the task:
### Input:
Add each field as a private field.
### Response:
def add_field(self, field, **kwargs):
"""Add each field as a private field."""
getattr(self, self._private_fields_name).append(field)
self._expire_cache(reverse=True)
se... |
def launch(self, args=None):
"""
This method triggers the parsing of arguments.
"""
self.options = self.parse_args(args)
if self.options.saveinputmeta:
# save original input options
self.save_input_meta()
if self.options.inputmeta:
# re... | This method triggers the parsing of arguments. | Below is the the instruction that describes the task:
### Input:
This method triggers the parsing of arguments.
### Response:
def launch(self, args=None):
"""
This method triggers the parsing of arguments.
"""
self.options = self.parse_args(args)
if self.options.saveinputmet... |
def _create_ids(self, home_teams, away_teams):
"""
Creates IDs for both players/teams
"""
categories = pd.Categorical(np.append(home_teams,away_teams))
home_id, away_id = categories.codes[0:int(len(categories)/2)], categories.codes[int(len(categories)/2):len(categories)+1]
... | Creates IDs for both players/teams | Below is the the instruction that describes the task:
### Input:
Creates IDs for both players/teams
### Response:
def _create_ids(self, home_teams, away_teams):
"""
Creates IDs for both players/teams
"""
categories = pd.Categorical(np.append(home_teams,away_teams))
home_id, ... |
def get_all_floating_ips(self):
"""
This function returns a list of FloatingIP objects.
"""
data = self.get_data("floating_ips")
floating_ips = list()
for jsoned in data['floating_ips']:
floating_ip = FloatingIP(**jsoned)
floating_ip.token = se... | This function returns a list of FloatingIP objects. | Below is the the instruction that describes the task:
### Input:
This function returns a list of FloatingIP objects.
### Response:
def get_all_floating_ips(self):
"""
This function returns a list of FloatingIP objects.
"""
data = self.get_data("floating_ips")
floating_ip... |
def create_session(self):
"""Create a session.
First we look in self.key_file for a path to a json file with the
credentials. The key file should have 'AWSAccessKeyId' and 'AWSSecretKey'.
Next we look at self.profile for a profile name and try
to use the Session call to automat... | Create a session.
First we look in self.key_file for a path to a json file with the
credentials. The key file should have 'AWSAccessKeyId' and 'AWSSecretKey'.
Next we look at self.profile for a profile name and try
to use the Session call to automatically pick up the keys for the profi... | Below is the the instruction that describes the task:
### Input:
Create a session.
First we look in self.key_file for a path to a json file with the
credentials. The key file should have 'AWSAccessKeyId' and 'AWSSecretKey'.
Next we look at self.profile for a profile name and try
to... |
def get_port_profile_status_output_port_profile_mac_association_applied_interface_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_profile_status = ET.Element("get_port_profile_status")
config = get_port_profile_status
outp... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_port_profile_status_output_port_profile_mac_association_applied_interface_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_prof... |
def connect(self, task_spec):
"""
Connect the *following* task to this one. In other words, the
given task is added as an output task.
task -- the task to connect to.
"""
self.thread_starter.outputs.append(task_spec)
task_spec._connect_notify(self.thread_starter) | Connect the *following* task to this one. In other words, the
given task is added as an output task.
task -- the task to connect to. | Below is the the instruction that describes the task:
### Input:
Connect the *following* task to this one. In other words, the
given task is added as an output task.
task -- the task to connect to.
### Response:
def connect(self, task_spec):
"""
Connect the *following* task to this... |
def time_estimate(self, duration, **kwargs):
"""Set an estimated time of work for the object.
Args:
duration (str): Duration in human format (e.g. 3h30)
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentic... | Set an estimated time of work for the object.
Args:
duration (str): Duration in human format (e.g. 3h30)
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTimeTrackingError... | Below is the the instruction that describes the task:
### Input:
Set an estimated time of work for the object.
Args:
duration (str): Duration in human format (e.g. 3h30)
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError:... |
def create_model(self, model_server_workers=None, role=None, vpc_config_override=VPC_CONFIG_DEFAULT):
"""Create a SageMaker ``ChainerModel`` object that can be deployed to an ``Endpoint``.
Args:
role (str): The ``ExecutionRoleArn`` IAM Role ARN for the ``Model``, which is also used during
... | Create a SageMaker ``ChainerModel`` object that can be deployed to an ``Endpoint``.
Args:
role (str): The ``ExecutionRoleArn`` IAM Role ARN for the ``Model``, which is also used during
transform jobs. If not specified, the role from the Estimator will be used.
model_serv... | Below is the the instruction that describes the task:
### Input:
Create a SageMaker ``ChainerModel`` object that can be deployed to an ``Endpoint``.
Args:
role (str): The ``ExecutionRoleArn`` IAM Role ARN for the ``Model``, which is also used during
transform jobs. If not specif... |
async def raw(self, command, *args, _conn=None, **kwargs):
"""
Send the raw command to the underlying client. Note that by using this CMD you
will lose compatibility with other backends.
Due to limitations with aiomcache client, args have to be provided as bytes.
For rest of bac... | Send the raw command to the underlying client. Note that by using this CMD you
will lose compatibility with other backends.
Due to limitations with aiomcache client, args have to be provided as bytes.
For rest of backends, str.
:param command: str with the command.
:param timeo... | Below is the the instruction that describes the task:
### Input:
Send the raw command to the underlying client. Note that by using this CMD you
will lose compatibility with other backends.
Due to limitations with aiomcache client, args have to be provided as bytes.
For rest of backends, str... |
def get_conn(self, aws_access_key=None, aws_secret_key=None):
'''
Hook point for overriding how the CounterPool gets its connection to
AWS.
'''
return boto.connect_dynamodb(
aws_access_key_id=aws_access_key,
aws_secret_access_key=aws_secret_key,
) | Hook point for overriding how the CounterPool gets its connection to
AWS. | Below is the the instruction that describes the task:
### Input:
Hook point for overriding how the CounterPool gets its connection to
AWS.
### Response:
def get_conn(self, aws_access_key=None, aws_secret_key=None):
'''
Hook point for overriding how the CounterPool gets its connection to
... |
def build_skeleton(nodes, independencies):
"""Estimates a graph skeleton (UndirectedGraph) from a set of independencies
using (the first part of) the PC algorithm. The independencies can either be
provided as an instance of the `Independencies`-class or by passing a
decision function tha... | Estimates a graph skeleton (UndirectedGraph) from a set of independencies
using (the first part of) the PC algorithm. The independencies can either be
provided as an instance of the `Independencies`-class or by passing a
decision function that decides any conditional independency assertion.
... | Below is the the instruction that describes the task:
### Input:
Estimates a graph skeleton (UndirectedGraph) from a set of independencies
using (the first part of) the PC algorithm. The independencies can either be
provided as an instance of the `Independencies`-class or by passing a
decisi... |
def _import_module(self, module_path):
"""Dynamically import a module returning a handle to it.
:param str module_path: The module path
:rtype: module
"""
LOGGER.debug('Importing %s', module_path)
try:
return __import__(module_path)
except ImportErro... | Dynamically import a module returning a handle to it.
:param str module_path: The module path
:rtype: module | Below is the the instruction that describes the task:
### Input:
Dynamically import a module returning a handle to it.
:param str module_path: The module path
:rtype: module
### Response:
def _import_module(self, module_path):
"""Dynamically import a module returning a handle to it.
... |
def pl_resolution(KB, alpha):
"Propositional-logic resolution: say if alpha follows from KB. [Fig. 7.12]"
clauses = KB.clauses + conjuncts(to_cnf(~alpha))
new = set()
while True:
n = len(clauses)
pairs = [(clauses[i], clauses[j])
for i in range(n) for j in range(i+1, n)]... | Propositional-logic resolution: say if alpha follows from KB. [Fig. 7.12] | Below is the the instruction that describes the task:
### Input:
Propositional-logic resolution: say if alpha follows from KB. [Fig. 7.12]
### Response:
def pl_resolution(KB, alpha):
"Propositional-logic resolution: say if alpha follows from KB. [Fig. 7.12]"
clauses = KB.clauses + conjuncts(to_cnf(~alpha))... |
def _get_model_fitting(self, con_est_id):
"""
Retreive model fitting that corresponds to contrast with identifier
'con_id'
from the list of model fitting objects stored in self.model_fittings
"""
for (mpe_id, pe_ids), contrasts in self.contrasts.items():
for c... | Retreive model fitting that corresponds to contrast with identifier
'con_id'
from the list of model fitting objects stored in self.model_fittings | Below is the the instruction that describes the task:
### Input:
Retreive model fitting that corresponds to contrast with identifier
'con_id'
from the list of model fitting objects stored in self.model_fittings
### Response:
def _get_model_fitting(self, con_est_id):
"""
Retreive mod... |
def new(self, sources_by_grp):
"""
Generate a new CompositeSourceModel from the given dictionary.
:param sources_by_group: a dictionary grp_id -> sources
:returns: a new CompositeSourceModel instance
"""
source_models = []
for sm in self.source_models:
... | Generate a new CompositeSourceModel from the given dictionary.
:param sources_by_group: a dictionary grp_id -> sources
:returns: a new CompositeSourceModel instance | Below is the the instruction that describes the task:
### Input:
Generate a new CompositeSourceModel from the given dictionary.
:param sources_by_group: a dictionary grp_id -> sources
:returns: a new CompositeSourceModel instance
### Response:
def new(self, sources_by_grp):
"""
Gen... |
def parse_args():
"""Parses command line arguments."""
parser = argparse.ArgumentParser(
description='Tool to run attacks and defenses.')
parser.add_argument('--attacks_dir', required=True,
help='Location of all attacks.')
parser.add_argument('--targeted_attacks_dir', required=True,
... | Parses command line arguments. | Below is the the instruction that describes the task:
### Input:
Parses command line arguments.
### Response:
def parse_args():
"""Parses command line arguments."""
parser = argparse.ArgumentParser(
description='Tool to run attacks and defenses.')
parser.add_argument('--attacks_dir', required=True,
... |
def iter_setup_packages(srcdir, packages):
""" A generator that finds and imports all of the ``setup_package.py``
modules in the source packages.
Returns
-------
modgen : generator
A generator that yields (modname, mod), where `mod` is the module and
`modname` is the module name for... | A generator that finds and imports all of the ``setup_package.py``
modules in the source packages.
Returns
-------
modgen : generator
A generator that yields (modname, mod), where `mod` is the module and
`modname` is the module name for the ``setup_package.py`` modules. | Below is the the instruction that describes the task:
### Input:
A generator that finds and imports all of the ``setup_package.py``
modules in the source packages.
Returns
-------
modgen : generator
A generator that yields (modname, mod), where `mod` is the module and
`modname` is t... |
def gpg_download_key( key_id, key_server, config_dir=None ):
"""
Download a GPG key from a key server.
Do not import it into any keyrings.
Return the ASCII-armored key
"""
config_dir = get_config_dir( config_dir )
tmpdir = make_gpg_tmphome( prefix="download", config_dir=config_dir )
gpg... | Download a GPG key from a key server.
Do not import it into any keyrings.
Return the ASCII-armored key | Below is the the instruction that describes the task:
### Input:
Download a GPG key from a key server.
Do not import it into any keyrings.
Return the ASCII-armored key
### Response:
def gpg_download_key( key_id, key_server, config_dir=None ):
"""
Download a GPG key from a key server.
Do not imp... |
def add_image(self, figure, dpi=72):
'''
Adds an image to the last chapter/section.
The image will be stored in the `{self.title}_files` directory.
:param matplotlib.figure figure:
A matplotlib figure to be saved into the report
'''
name = os.path.join(self._... | Adds an image to the last chapter/section.
The image will be stored in the `{self.title}_files` directory.
:param matplotlib.figure figure:
A matplotlib figure to be saved into the report | Below is the the instruction that describes the task:
### Input:
Adds an image to the last chapter/section.
The image will be stored in the `{self.title}_files` directory.
:param matplotlib.figure figure:
A matplotlib figure to be saved into the report
### Response:
def add_image(self,... |
def dump(self, out=sys.stdout, row_fn=repr, limit=-1, indent=0):
"""Dump out the contents of this table in a nested listing.
@param out: output stream to write to
@param row_fn: function to call to display individual rows
@param limit: number of records to show at deepest level ... | Dump out the contents of this table in a nested listing.
@param out: output stream to write to
@param row_fn: function to call to display individual rows
@param limit: number of records to show at deepest level of pivot (-1=show all)
@param indent: current nesting level | Below is the the instruction that describes the task:
### Input:
Dump out the contents of this table in a nested listing.
@param out: output stream to write to
@param row_fn: function to call to display individual rows
@param limit: number of records to show at deepest level of pivo... |
def remove(name=None, pkgs=None, recursive=True, **kwargs):
'''
name
The name of the package to be deleted.
recursive
Also remove dependent packages (not required elsewhere).
Default mode: enabled.
Multiple Package Options:
pkgs
A list of packages to delete. Must b... | name
The name of the package to be deleted.
recursive
Also remove dependent packages (not required elsewhere).
Default mode: enabled.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignore... | Below is the the instruction that describes the task:
### Input:
name
The name of the package to be deleted.
recursive
Also remove dependent packages (not required elsewhere).
Default mode: enabled.
Multiple Package Options:
pkgs
A list of packages to delete. Must be p... |
def split_fusion_transcript(annotation_path, transcripts):
"""
Finds the breakpoint in the fusion transcript and splits the 5' donor from the 3' acceptor
:param str annotation_path: Path to transcript annotation file
:param dict transcripts: Dictionary of fusion transcripts
:return: 5' donor sequen... | Finds the breakpoint in the fusion transcript and splits the 5' donor from the 3' acceptor
:param str annotation_path: Path to transcript annotation file
:param dict transcripts: Dictionary of fusion transcripts
:return: 5' donor sequences and 3' acceptor sequences
:rtype: tuple | Below is the the instruction that describes the task:
### Input:
Finds the breakpoint in the fusion transcript and splits the 5' donor from the 3' acceptor
:param str annotation_path: Path to transcript annotation file
:param dict transcripts: Dictionary of fusion transcripts
:return: 5' donor sequence... |
def register(lifter, arch_name):
"""
Registers a Lifter or Postprocessor to be used by pyvex. Lifters are are given priority based on the order
in which they are registered. Postprocessors will be run in registration order.
:param lifter: The Lifter or Postprocessor to register
:vartype lifte... | Registers a Lifter or Postprocessor to be used by pyvex. Lifters are are given priority based on the order
in which they are registered. Postprocessors will be run in registration order.
:param lifter: The Lifter or Postprocessor to register
:vartype lifter: :class:`Lifter` or :class:`Postprocess... | Below is the the instruction that describes the task:
### Input:
Registers a Lifter or Postprocessor to be used by pyvex. Lifters are are given priority based on the order
in which they are registered. Postprocessors will be run in registration order.
:param lifter: The Lifter or Postprocessor to reg... |
def logger_init():
"""Initialize logger instance."""
log = logging.getLogger("pyinotify")
console_handler = logging.StreamHandler()
console_handler.setFormatter(
logging.Formatter("[%(asctime)s %(name)s %(levelname)s] %(message)s"))
log.addHandler(console_handler)
log.setLevel(20)
re... | Initialize logger instance. | Below is the the instruction that describes the task:
### Input:
Initialize logger instance.
### Response:
def logger_init():
"""Initialize logger instance."""
log = logging.getLogger("pyinotify")
console_handler = logging.StreamHandler()
console_handler.setFormatter(
logging.Formatter("[%(... |
def get_file_stream_api(self):
"""This creates a new file pusher thread. Call start to initiate the thread that talks to W&B"""
if not self._file_stream_api:
if self._current_run_id is None:
raise UsageError(
'Must have a current run to use file stream AP... | This creates a new file pusher thread. Call start to initiate the thread that talks to W&B | Below is the the instruction that describes the task:
### Input:
This creates a new file pusher thread. Call start to initiate the thread that talks to W&B
### Response:
def get_file_stream_api(self):
"""This creates a new file pusher thread. Call start to initiate the thread that talks to W&B"""
... |
def push_design_documents(self, design_path):
"""
Push the design documents stored in `design_path` to the server
"""
for db_name in os.listdir(design_path):
if db_name.startswith("__") or db_name.startswith("."):
continue
db_path = os.path.join(de... | Push the design documents stored in `design_path` to the server | Below is the the instruction that describes the task:
### Input:
Push the design documents stored in `design_path` to the server
### Response:
def push_design_documents(self, design_path):
"""
Push the design documents stored in `design_path` to the server
"""
for db_name in os.list... |
def edges_to_dict_of_dataframes(grid, edges):
"""
Export edges to DataFrame
Parameters
----------
grid: ding0.Network
edges: list
Edges of Ding0.Network graph
Returns
-------
edges_dict: dict
"""
omega = 2 * pi * 50
srid = int(cfg_ding0.get('geo', 'srid'))
... | Export edges to DataFrame
Parameters
----------
grid: ding0.Network
edges: list
Edges of Ding0.Network graph
Returns
-------
edges_dict: dict | Below is the the instruction that describes the task:
### Input:
Export edges to DataFrame
Parameters
----------
grid: ding0.Network
edges: list
Edges of Ding0.Network graph
Returns
-------
edges_dict: dict
### Response:
def edges_to_dict_of_dataframes(grid, edges):
"""
... |
def _secondary_max(self):
"""Getter for the maximum series value"""
return (
self.secondary_range[1]
if (self.secondary_range
and self.secondary_range[1] is not None) else
(max(self._secondary_values) if self._secondary_values else None)
) | Getter for the maximum series value | Below is the the instruction that describes the task:
### Input:
Getter for the maximum series value
### Response:
def _secondary_max(self):
"""Getter for the maximum series value"""
return (
self.secondary_range[1]
if (self.secondary_range
and self.secondary... |
def _connect(self):
"""Connect to the serial port. This should be run in a new thread."""
while self.protocol:
_LOGGER.info('Trying to connect to %s', self.port)
try:
ser = serial.serial_for_url(
self.port, self.baud, timeout=self.timeout)
... | Connect to the serial port. This should be run in a new thread. | Below is the the instruction that describes the task:
### Input:
Connect to the serial port. This should be run in a new thread.
### Response:
def _connect(self):
"""Connect to the serial port. This should be run in a new thread."""
while self.protocol:
_LOGGER.info('Trying to connect t... |
def add(self, *args, **kwargs):
"""Add Cookie objects by their names, or create new ones under
specified names.
Any unnamed arguments are interpreted as existing cookies, and
are added under the value in their .name attribute. With keyword
arguments, the key is interpreted as th... | Add Cookie objects by their names, or create new ones under
specified names.
Any unnamed arguments are interpreted as existing cookies, and
are added under the value in their .name attribute. With keyword
arguments, the key is interpreted as the cookie name and the
value as the ... | Below is the the instruction that describes the task:
### Input:
Add Cookie objects by their names, or create new ones under
specified names.
Any unnamed arguments are interpreted as existing cookies, and
are added under the value in their .name attribute. With keyword
arguments, th... |
def get_model_name(model):
"""
Detects the model name for a Scikit-Learn model or pipeline.
Parameters
----------
model: class or instance
The object to determine the name for. If the model is an estimator it
returns the class name; if it is a Pipeline it returns the class name
... | Detects the model name for a Scikit-Learn model or pipeline.
Parameters
----------
model: class or instance
The object to determine the name for. If the model is an estimator it
returns the class name; if it is a Pipeline it returns the class name
of the final transformer or estimat... | Below is the the instruction that describes the task:
### Input:
Detects the model name for a Scikit-Learn model or pipeline.
Parameters
----------
model: class or instance
The object to determine the name for. If the model is an estimator it
returns the class name; if it is a Pipeline ... |
def predict(self, control=None, control_matrix=None,
process_matrix=None, process_covariance=None):
"""
Predict the next *a priori* state mean and covariance given the last
posterior. As a special case the first call to this method will
initialise the posterior and prior ... | Predict the next *a priori* state mean and covariance given the last
posterior. As a special case the first call to this method will
initialise the posterior and prior estimates from the
*initial_state_estimate* and *initial_covariance* arguments passed when
this object was created. In t... | Below is the the instruction that describes the task:
### Input:
Predict the next *a priori* state mean and covariance given the last
posterior. As a special case the first call to this method will
initialise the posterior and prior estimates from the
*initial_state_estimate* and *initial_co... |
def hosted_number_orders(self):
"""
:rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderList
"""
if self._hosted_number_orders is None:
self._hosted_number_orders = HostedNumberOrderList(self)
return self._hosted_number_orders | :rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderList | Below is the the instruction that describes the task:
### Input:
:rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderList
### Response:
def hosted_number_orders(self):
"""
:rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderList
"""
... |
def condition_from_code(condcode):
"""Get the condition name from the condition code."""
if condcode in __BRCONDITIONS:
cond_data = __BRCONDITIONS[condcode]
return {CONDCODE: condcode,
CONDITION: cond_data[0],
DETAILED: cond_data[1],
EXACT: cond_d... | Get the condition name from the condition code. | Below is the the instruction that describes the task:
### Input:
Get the condition name from the condition code.
### Response:
def condition_from_code(condcode):
"""Get the condition name from the condition code."""
if condcode in __BRCONDITIONS:
cond_data = __BRCONDITIONS[condcode]
return... |
def is_polynomial(self):
"""
Tells whether it is a linear combination of natural powers of ``x``.
"""
return all(isinstance(k, INT_TYPES) and k >= 0 for k in self._data) | Tells whether it is a linear combination of natural powers of ``x``. | Below is the the instruction that describes the task:
### Input:
Tells whether it is a linear combination of natural powers of ``x``.
### Response:
def is_polynomial(self):
"""
Tells whether it is a linear combination of natural powers of ``x``.
"""
return all(isinstance(k, INT_TYPES) and k >= 0 fo... |
def main():
data = {'demo':{'foo': '<foo>', 'bar': ['1', '2']}}
# xml写入文件 提供文件名
lazyxml.dump(data, 'xml/dump.xml')
# xml写入文件 提供文件句柄
with open('xml/dump-fp.xml', 'w') as fp:
lazyxml.dump(data, fp)
# xml写入文件 提供类文件对象
from cStringIO import StringIO
buffer = StringIO()
lazyxml.... | <root a1="1" a2="2">
<test1 a="1" b="2" c="3">
<normal index="5" required="false">
<bar><![CDATA[1]]></bar>
<bar><![CDATA[2]]></bar>
<foo><![CDATA[<foo-1>]]></foo>
</normal>
<repeat1 index="1" required="false">
<... | Below is the the instruction that describes the task:
### Input:
<root a1="1" a2="2">
<test1 a="1" b="2" c="3">
<normal index="5" required="false">
<bar><![CDATA[1]]></bar>
<bar><![CDATA[2]]></bar>
<foo><![CDATA[<foo-1>]]></foo>
</norma... |
def cells_rt_meta(workbook, sheet, row, col):
"""
Traverse all cells in a row. If you find new data in a cell, add it to the list.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:return list: Cell data for a specific row
"""
logger_excel.info("enter cells_rt_m... | Traverse all cells in a row. If you find new data in a cell, add it to the list.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:return list: Cell data for a specific row | Below is the the instruction that describes the task:
### Input:
Traverse all cells in a row. If you find new data in a cell, add it to the list.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:return list: Cell data for a specific row
### Response:
def cells_rt_meta(wor... |
def get_list(self, terms, limit=0, sort=False, ranks=None):
"""
Get the specified cards from the stack.
:arg term:
The search term. Can be a card full name, value, suit,
abbreviation, or stack indice.
:arg int limit:
The number of items to retrieve fo... | Get the specified cards from the stack.
:arg term:
The search term. Can be a card full name, value, suit,
abbreviation, or stack indice.
:arg int limit:
The number of items to retrieve for each term.
:arg bool sort:
Whether or not to sort the resu... | Below is the the instruction that describes the task:
### Input:
Get the specified cards from the stack.
:arg term:
The search term. Can be a card full name, value, suit,
abbreviation, or stack indice.
:arg int limit:
The number of items to retrieve for each term... |
def _get_pattern(self, pattern_id):
"""Get pattern item by id."""
for key in ('PATTERNS1', 'PATTERNS2', 'PATTERNS3'):
if key in self.tagged_blocks:
data = self.tagged_blocks.get_data(key)
for pattern in data:
if pattern.pattern_id == patter... | Get pattern item by id. | Below is the the instruction that describes the task:
### Input:
Get pattern item by id.
### Response:
def _get_pattern(self, pattern_id):
"""Get pattern item by id."""
for key in ('PATTERNS1', 'PATTERNS2', 'PATTERNS3'):
if key in self.tagged_blocks:
data = self.tagged_b... |
def uuid(cls):
"""UUID column, or synonym to existing :attr:`id` column if that is a UUID"""
if hasattr(cls, '__uuid_primary_key__') and cls.__uuid_primary_key__:
return synonym('id')
else:
return immutable(Column(UUIDType(binary=False), default=uuid_.uuid4, unique=True, ... | UUID column, or synonym to existing :attr:`id` column if that is a UUID | Below is the the instruction that describes the task:
### Input:
UUID column, or synonym to existing :attr:`id` column if that is a UUID
### Response:
def uuid(cls):
"""UUID column, or synonym to existing :attr:`id` column if that is a UUID"""
if hasattr(cls, '__uuid_primary_key__') and cls.__uuid_... |
def continuousGenerator(self, request):
"""
Returns a generator over the (continuous, nextPageToken) pairs
defined by the (JSON string) request.
"""
compoundId = None
if request.continuous_set_id != "":
compoundId = datamodel.ContinuousSetCompoundId.parse(
... | Returns a generator over the (continuous, nextPageToken) pairs
defined by the (JSON string) request. | Below is the the instruction that describes the task:
### Input:
Returns a generator over the (continuous, nextPageToken) pairs
defined by the (JSON string) request.
### Response:
def continuousGenerator(self, request):
"""
Returns a generator over the (continuous, nextPageToken) pairs
... |
def render_addPersonForm(self, ctx, data):
"""
Create and return a L{liveform.LiveForm} for creating a new L{Person}.
"""
addPersonForm = liveform.LiveForm(
self.addPerson, self._baseParameters, description='Add Person')
addPersonForm.compact()
addPersonForm.j... | Create and return a L{liveform.LiveForm} for creating a new L{Person}. | Below is the the instruction that describes the task:
### Input:
Create and return a L{liveform.LiveForm} for creating a new L{Person}.
### Response:
def render_addPersonForm(self, ctx, data):
"""
Create and return a L{liveform.LiveForm} for creating a new L{Person}.
"""
addPersonFo... |
def add_rpt(self, sequence, mod, pt):
"""Add a repeater to the previous sequence"""
modstr = self.value(mod)
if modstr == '!!':
# cursor on the REPEATER
self._stream.restore_context()
# log the error
self.diagnostic.notify(
error.Severity.ERROR,
"Canno... | Add a repeater to the previous sequence | Below is the the instruction that describes the task:
### Input:
Add a repeater to the previous sequence
### Response:
def add_rpt(self, sequence, mod, pt):
"""Add a repeater to the previous sequence"""
modstr = self.value(mod)
if modstr == '!!':
# cursor on the REPEATER
self._stream.re... |
def _ss(self, class_def):
"""calculates sum of squares for a class"""
yc = self.y[class_def]
css = yc - yc.mean()
css *= css
return sum(css) | calculates sum of squares for a class | Below is the the instruction that describes the task:
### Input:
calculates sum of squares for a class
### Response:
def _ss(self, class_def):
"""calculates sum of squares for a class"""
yc = self.y[class_def]
css = yc - yc.mean()
css *= css
return sum(css) |
def backwards(self, orm):
"Write your backwards methods here."
from django.contrib.auth.models import Group
projects = orm['samples.Project'].objects.all()
names = [PROJECT_GROUP_TEMPLATE.format(p.name) for p in projects]
# Remove groups named after these teams
Group.ob... | Write your backwards methods here. | Below is the the instruction that describes the task:
### Input:
Write your backwards methods here.
### Response:
def backwards(self, orm):
"Write your backwards methods here."
from django.contrib.auth.models import Group
projects = orm['samples.Project'].objects.all()
names = [PRO... |
def git_remote(git_repo):
"""Return the URL for remote git repository.
Depending on the system setup it returns ssh or https remote.
"""
github_token = os.getenv(GITHUB_TOKEN_KEY)
if github_token:
return 'https://{0}@github.com/{1}'.format(
github_token, git_repo)
return 'gi... | Return the URL for remote git repository.
Depending on the system setup it returns ssh or https remote. | Below is the the instruction that describes the task:
### Input:
Return the URL for remote git repository.
Depending on the system setup it returns ssh or https remote.
### Response:
def git_remote(git_repo):
"""Return the URL for remote git repository.
Depending on the system setup it returns ssh or... |
def toListInt(value):
"""
Convert a value to list of ints, if possible.
"""
if TypeConverters._can_convert_to_list(value):
value = TypeConverters.toList(value)
if all(map(lambda v: TypeConverters._is_integer(v), value)):
return [int(v) for v in val... | Convert a value to list of ints, if possible. | Below is the the instruction that describes the task:
### Input:
Convert a value to list of ints, if possible.
### Response:
def toListInt(value):
"""
Convert a value to list of ints, if possible.
"""
if TypeConverters._can_convert_to_list(value):
value = TypeConverters.... |
def _set_typeahead(cls, el, value):
"""
Convert given `el` to typeahead input and set it to `value`.
This method also sets the dropdown icons and descriptors.
Args:
el (obj): Element reference to the input you want to convert to
typeahead.
value ... | Convert given `el` to typeahead input and set it to `value`.
This method also sets the dropdown icons and descriptors.
Args:
el (obj): Element reference to the input you want to convert to
typeahead.
value (list): List of dicts with two keys: ``source`` and ``va... | Below is the the instruction that describes the task:
### Input:
Convert given `el` to typeahead input and set it to `value`.
This method also sets the dropdown icons and descriptors.
Args:
el (obj): Element reference to the input you want to convert to
typeahead.
... |
def velocity_dispersion(self, kwargs_lens, kwargs_lens_light, lens_light_model_bool_list=None, aniso_param=1,
r_eff=None, R_slit=0.81, dR_slit=0.1, psf_fwhm=0.7, num_evaluate=1000):
"""
computes the LOS velocity dispersion of the lens within a slit of size R_slit x dR_slit an... | computes the LOS velocity dispersion of the lens within a slit of size R_slit x dR_slit and seeing psf_fwhm.
The assumptions are a Hernquist light profile and the spherical power-law lens model at the first position.
Further information can be found in the AnalyticKinematics() class.
:param kw... | Below is the the instruction that describes the task:
### Input:
computes the LOS velocity dispersion of the lens within a slit of size R_slit x dR_slit and seeing psf_fwhm.
The assumptions are a Hernquist light profile and the spherical power-law lens model at the first position.
Further informati... |
def reset(self, seed):
"""
Reset this generator's seed generator and any clones.
"""
logger.debug(f'Resetting {self} (seed={seed})')
self.seed_generator.reset(seed)
for c in self.clones:
c.reset(seed) | Reset this generator's seed generator and any clones. | Below is the the instruction that describes the task:
### Input:
Reset this generator's seed generator and any clones.
### Response:
def reset(self, seed):
"""
Reset this generator's seed generator and any clones.
"""
logger.debug(f'Resetting {self} (seed={seed})')
self.seed... |
def _query_compressed(options, collection_name, num_to_skip,
num_to_return, query, field_selector,
opts, check_keys=False, ctx=None):
"""Internal compressed query message helper."""
op_query, max_bson_size = _query(
options,
collection_name,
nu... | Internal compressed query message helper. | Below is the the instruction that describes the task:
### Input:
Internal compressed query message helper.
### Response:
def _query_compressed(options, collection_name, num_to_skip,
num_to_return, query, field_selector,
opts, check_keys=False, ctx=None):
"""Internal ... |
def _compute_dependencies(self):
"""Recompute this distribution's dependencies."""
from _markerlib import compile as compile_marker
dm = self.__dep_map = {None: []}
reqs = []
# Including any condition expressions
for req in self._parsed_pkg_info.get_all('Requires-Dist') ... | Recompute this distribution's dependencies. | Below is the the instruction that describes the task:
### Input:
Recompute this distribution's dependencies.
### Response:
def _compute_dependencies(self):
"""Recompute this distribution's dependencies."""
from _markerlib import compile as compile_marker
dm = self.__dep_map = {None: []}
... |
def write_lammpsdata(structure, filename, atom_style='full'):
"""Output a LAMMPS data file.
Outputs a LAMMPS data file in the 'full' atom style format. Assumes use
of 'real' units. See http://lammps.sandia.gov/doc/atom_style.html for
more information on atom styles.
Parameters
----------
... | Output a LAMMPS data file.
Outputs a LAMMPS data file in the 'full' atom style format. Assumes use
of 'real' units. See http://lammps.sandia.gov/doc/atom_style.html for
more information on atom styles.
Parameters
----------
structure : parmed.Structure
ParmEd structure object
f... | Below is the the instruction that describes the task:
### Input:
Output a LAMMPS data file.
Outputs a LAMMPS data file in the 'full' atom style format. Assumes use
of 'real' units. See http://lammps.sandia.gov/doc/atom_style.html for
more information on atom styles.
Parameters
----------
... |
def get_profile_histogram(x, y, n_bins=100):
'''Takes 2D point data (x,y) and creates a profile histogram similar to the TProfile in ROOT. It calculates
the y mean for every bin at the bin center and gives the y mean error as error bars.
Parameters
----------
x : array like
data x positions... | Takes 2D point data (x,y) and creates a profile histogram similar to the TProfile in ROOT. It calculates
the y mean for every bin at the bin center and gives the y mean error as error bars.
Parameters
----------
x : array like
data x positions
y : array like
data y positions
n_b... | Below is the the instruction that describes the task:
### Input:
Takes 2D point data (x,y) and creates a profile histogram similar to the TProfile in ROOT. It calculates
the y mean for every bin at the bin center and gives the y mean error as error bars.
Parameters
----------
x : array like
... |
def unpack(self, buff, offset=0):
"""Unpack a binary message into this object's attributes.
Unpack the binary value *buff* and update this object attributes based
on the results.
Args:
buff (bytes): Binary data package to be unpacked.
offset (int): Where to begi... | Unpack a binary message into this object's attributes.
Unpack the binary value *buff* and update this object attributes based
on the results.
Args:
buff (bytes): Binary data package to be unpacked.
offset (int): Where to begin unpacking.
Raises:
Exc... | Below is the the instruction that describes the task:
### Input:
Unpack a binary message into this object's attributes.
Unpack the binary value *buff* and update this object attributes based
on the results.
Args:
buff (bytes): Binary data package to be unpacked.
off... |
def _deinterlace(self, raw):
"""
Read raw pixel data, undo filters, deinterlace, and flatten.
Return a single array of values.
"""
# Values per row (of the target image)
vpr = self.width * self.planes
# Values per image
vpi = vpr * self.height
# ... | Read raw pixel data, undo filters, deinterlace, and flatten.
Return a single array of values. | Below is the the instruction that describes the task:
### Input:
Read raw pixel data, undo filters, deinterlace, and flatten.
Return a single array of values.
### Response:
def _deinterlace(self, raw):
"""
Read raw pixel data, undo filters, deinterlace, and flatten.
Return a single ... |
def _set_collector_profile(self, v, load=False):
"""
Setter method for collector_profile, mapped from YANG variable /telemetry/collector/collector_profile (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_collector_profile is considered as a private
method. Back... | Setter method for collector_profile, mapped from YANG variable /telemetry/collector/collector_profile (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_collector_profile is considered as a private
method. Backends looking to populate this variable should
do so via c... | Below is the the instruction that describes the task:
### Input:
Setter method for collector_profile, mapped from YANG variable /telemetry/collector/collector_profile (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_collector_profile is considered as a private
meth... |
def autocorrelated_relaxed_clock(self, root_rate, autocorrel,
distribution='lognormal'):
"""
Attaches rates to each node according to autocorrelated lognormal
model from Kishino et al.(2001), or autocorrelated exponential
"""
optioncheck(distr... | Attaches rates to each node according to autocorrelated lognormal
model from Kishino et al.(2001), or autocorrelated exponential | Below is the the instruction that describes the task:
### Input:
Attaches rates to each node according to autocorrelated lognormal
model from Kishino et al.(2001), or autocorrelated exponential
### Response:
def autocorrelated_relaxed_clock(self, root_rate, autocorrel,
... |
def hil_gps_send(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, vn, ve, vd, cog, satellites_visible, force_mavlink1=False):
'''
The global position, as returned by the Global Positioning System
(GPS). This is NOT the global
posit... | The global position, as returned by the Global Positioning System
(GPS). This is NOT the global
position estimate of the sytem, but rather a RAW
sensor value. See message GLOBAL_POSITION for the
global position estimate. Coordinate frame i... | Below is the the instruction that describes the task:
### Input:
The global position, as returned by the Global Positioning System
(GPS). This is NOT the global
position estimate of the sytem, but rather a RAW
sensor value. See message GLOBAL_POSITION... |
def tsne(adata, **kwargs) -> Union[Axes, List[Axes], None]:
"""\
Scatter plot in tSNE basis.
Parameters
----------
{adata_color_etc}
{edges_arrows}
{scatter_bulk}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
"""
r... | \
Scatter plot in tSNE basis.
Parameters
----------
{adata_color_etc}
{edges_arrows}
{scatter_bulk}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it. | Below is the the instruction that describes the task:
### Input:
\
Scatter plot in tSNE basis.
Parameters
----------
{adata_color_etc}
{edges_arrows}
{scatter_bulk}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
### Respons... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.