code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def makeStickyEdataFile(Economy,ignore_periods,description='',filename=None,save_data=False,calc_micro_stats=True,meas_err_base=None):
'''
Makes descriptive statistics and macroeconomic data file. Behaves slightly
differently for heterogeneous agents vs representative agent models.
Parameters
-----... | Makes descriptive statistics and macroeconomic data file. Behaves slightly
differently for heterogeneous agents vs representative agent models.
Parameters
----------
Economy : Market or AgentType
A representation of the model economy. For heterogeneous agents specifications,
this will ... | Below is the the instruction that describes the task:
### Input:
Makes descriptive statistics and macroeconomic data file. Behaves slightly
differently for heterogeneous agents vs representative agent models.
Parameters
----------
Economy : Market or AgentType
A representation of the model ... |
def widgetForName(self, name):
"""Gets a widget with *name*
:param name: the widgets in this container should all have
a name() method. This is the string to match to that result
:type name: str
"""
for iwidget in range(len(self)):
if self.widget(iwidget).na... | Gets a widget with *name*
:param name: the widgets in this container should all have
a name() method. This is the string to match to that result
:type name: str | Below is the the instruction that describes the task:
### Input:
Gets a widget with *name*
:param name: the widgets in this container should all have
a name() method. This is the string to match to that result
:type name: str
### Response:
def widgetForName(self, name):
"""Gets a ... |
def SetValue(self, value=None, act=True):
" main method to set value "
if value is None:
value = wx.TextCtrl.GetValue(self).strip()
self.__CheckValid(value)
self.__GetMark()
if value is not None:
wx.TextCtrl.SetValue(self, self.format % set_float(value))
... | main method to set value | Below is the the instruction that describes the task:
### Input:
main method to set value
### Response:
def SetValue(self, value=None, act=True):
" main method to set value "
if value is None:
value = wx.TextCtrl.GetValue(self).strip()
self.__CheckValid(value)
self.__Get... |
def peer_ips(peer_relation='cluster', addr_key='private-address'):
'''Return a dict of peers and their private-address'''
peers = {}
for r_id in relation_ids(peer_relation):
for unit in relation_list(r_id):
peers[unit] = relation_get(addr_key, rid=r_id, unit=unit)
return peers | Return a dict of peers and their private-address | Below is the the instruction that describes the task:
### Input:
Return a dict of peers and their private-address
### Response:
def peer_ips(peer_relation='cluster', addr_key='private-address'):
'''Return a dict of peers and their private-address'''
peers = {}
for r_id in relation_ids(peer_relation):
... |
def vmdk_to_ami(args):
"""
Calls methods to perform vmdk import
:param args:
:return:
"""
aws_importer = AWSUtilities.AWSUtils(args.directory, args.aws_profile, args.s3_bucket,
args.aws_regions, args.ami_name, args.vmdk_upload_file)
aws_importer.impor... | Calls methods to perform vmdk import
:param args:
:return: | Below is the the instruction that describes the task:
### Input:
Calls methods to perform vmdk import
:param args:
:return:
### Response:
def vmdk_to_ami(args):
"""
Calls methods to perform vmdk import
:param args:
:return:
"""
aws_importer = AWSUtilities.AWSUtils(args.directory, ar... |
def create_relationship(manager, handle_id, other_handle_id, rel_type):
"""
Makes a relationship from node to other_node depending on which
meta_type the nodes are. Returns the relationship or raises
NoRelationshipPossible exception.
"""
meta_type = get_node_meta_type(manager, handle_id)
if ... | Makes a relationship from node to other_node depending on which
meta_type the nodes are. Returns the relationship or raises
NoRelationshipPossible exception. | Below is the the instruction that describes the task:
### Input:
Makes a relationship from node to other_node depending on which
meta_type the nodes are. Returns the relationship or raises
NoRelationshipPossible exception.
### Response:
def create_relationship(manager, handle_id, other_handle_id, rel_type)... |
def isLoggedOn(rh, userid):
"""
Determine whether a virtual machine is logged on.
Input:
Request Handle:
userid being queried
Output:
Dictionary containing the following:
overallRC - overall return code, 0: success, non-zero: failure
rc - 0: if we got... | Determine whether a virtual machine is logged on.
Input:
Request Handle:
userid being queried
Output:
Dictionary containing the following:
overallRC - overall return code, 0: success, non-zero: failure
rc - 0: if we got status. Otherwise, it is the
... | Below is the the instruction that describes the task:
### Input:
Determine whether a virtual machine is logged on.
Input:
Request Handle:
userid being queried
Output:
Dictionary containing the following:
overallRC - overall return code, 0: success, non-zero: failure
... |
def get_properties(self):
"""
Returns all the properties of the features layer (iterator)
@rtype: L{Cproperty}
@return: list of properties
"""
if self.features_layer is not None:
for property in self.features_layer.get_properties():
yield prope... | Returns all the properties of the features layer (iterator)
@rtype: L{Cproperty}
@return: list of properties | Below is the the instruction that describes the task:
### Input:
Returns all the properties of the features layer (iterator)
@rtype: L{Cproperty}
@return: list of properties
### Response:
def get_properties(self):
"""
Returns all the properties of the features layer (iterator)
... |
def _on_close(self, socket):
"""
Called when the connection was closed.
"""
self.logger.debug('Connection closed.')
for subscription in self.subscriptions.values():
if subscription.state == 'subscribed':
subscription.state = 'connection_pending' | Called when the connection was closed. | Below is the the instruction that describes the task:
### Input:
Called when the connection was closed.
### Response:
def _on_close(self, socket):
"""
Called when the connection was closed.
"""
self.logger.debug('Connection closed.')
for subscription in self.subscriptions.v... |
def xmlparser(xml, objectify=True):
""" Parse xml
:param xml: XML element
:type xml: Union[text_type, lxml.etree._Element]
:rtype: lxml.etree._Element
:returns: An element object
:raises: TypeError if element is not in accepted type
"""
doclose = None
if isinstance(xml, (etree._Ele... | Parse xml
:param xml: XML element
:type xml: Union[text_type, lxml.etree._Element]
:rtype: lxml.etree._Element
:returns: An element object
:raises: TypeError if element is not in accepted type | Below is the the instruction that describes the task:
### Input:
Parse xml
:param xml: XML element
:type xml: Union[text_type, lxml.etree._Element]
:rtype: lxml.etree._Element
:returns: An element object
:raises: TypeError if element is not in accepted type
### Response:
def xmlparser(xml, obj... |
def software_breakpoint_set(self, addr, thumb=False, arm=False, flash=False, ram=False):
"""Sets a software breakpoint at the specified address.
If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if
``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a
no... | Sets a software breakpoint at the specified address.
If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if
``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a
normal breakpoint is set.
If ``flash`` is ``True``, the breakpoint is set in flash, otherwise... | Below is the the instruction that describes the task:
### Input:
Sets a software breakpoint at the specified address.
If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if
``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a
normal breakpoint is set.
... |
def find_differences(self, refindex: int):
"""
Search all differences between protocol messages regarding a reference message
:param refindex: index of reference message
:rtype: dict[int, set[int]]
"""
differences = defaultdict(set)
if refindex >= len(self.proto... | Search all differences between protocol messages regarding a reference message
:param refindex: index of reference message
:rtype: dict[int, set[int]] | Below is the the instruction that describes the task:
### Input:
Search all differences between protocol messages regarding a reference message
:param refindex: index of reference message
:rtype: dict[int, set[int]]
### Response:
def find_differences(self, refindex: int):
"""
Searc... |
def execute(self, sql, parameters=None, bulk_parameters=None):
"""
Prepare and execute a database operation (query or command).
"""
if self.connection._closed:
raise ProgrammingError("Connection closed")
if self._closed:
raise ProgrammingError("Cursor clo... | Prepare and execute a database operation (query or command). | Below is the the instruction that describes the task:
### Input:
Prepare and execute a database operation (query or command).
### Response:
def execute(self, sql, parameters=None, bulk_parameters=None):
"""
Prepare and execute a database operation (query or command).
"""
if self.con... |
def sort_by(self, *ids):
"""Update files order.
:param ids: List of ids specifying the final status of the list.
"""
# Support sorting by file_ids or keys.
files = {str(f_.file_id): f_.key for f_ in self}
# self.record['_files'] = [{'key': files.get(id_, id_)} for id_ in... | Update files order.
:param ids: List of ids specifying the final status of the list. | Below is the the instruction that describes the task:
### Input:
Update files order.
:param ids: List of ids specifying the final status of the list.
### Response:
def sort_by(self, *ids):
"""Update files order.
:param ids: List of ids specifying the final status of the list.
"""
... |
def worker_task(work_item, config):
"""The celery task which performs a single mutation and runs a test suite.
This runs `cosmic-ray worker` in a subprocess and returns the results,
passing `config` to it via stdin.
Args:
work_item: A dict describing a WorkItem.
config: The configurati... | The celery task which performs a single mutation and runs a test suite.
This runs `cosmic-ray worker` in a subprocess and returns the results,
passing `config` to it via stdin.
Args:
work_item: A dict describing a WorkItem.
config: The configuration to use for the test execution.
Retu... | Below is the the instruction that describes the task:
### Input:
The celery task which performs a single mutation and runs a test suite.
This runs `cosmic-ray worker` in a subprocess and returns the results,
passing `config` to it via stdin.
Args:
work_item: A dict describing a WorkItem.
... |
def determine_collections(self):
"""Try to determine which collections this record should belong to."""
for value in record_get_field_values(self.record, '980', code='a'):
if 'NOTE' in value.upper():
self.collections.add('NOTE')
if 'THESIS' in value.upper():
... | Try to determine which collections this record should belong to. | Below is the the instruction that describes the task:
### Input:
Try to determine which collections this record should belong to.
### Response:
def determine_collections(self):
"""Try to determine which collections this record should belong to."""
for value in record_get_field_values(self.record, '... |
def imshow(image, format, **kwargs):
"""Draw an image in the current context figure.
Parameters
----------
image: image data
Image data, depending on the passed format, can be one of:
- an instance of an ipywidgets Image
- a file name
- a raw byte string
f... | Draw an image in the current context figure.
Parameters
----------
image: image data
Image data, depending on the passed format, can be one of:
- an instance of an ipywidgets Image
- a file name
- a raw byte string
format: {'widget', 'filename', ...}
T... | Below is the the instruction that describes the task:
### Input:
Draw an image in the current context figure.
Parameters
----------
image: image data
Image data, depending on the passed format, can be one of:
- an instance of an ipywidgets Image
- a file name
... |
def gauge(self, stats, value):
"""
Log gauges
>>> client = StatsdClient()
>>> client.gauge('example.gauge', 47)
>>> client.gauge(('example.gauge41', 'example.gauge43'), 47)
"""
self.update_stats(stats, value, self.SC_GAUGE) | Log gauges
>>> client = StatsdClient()
>>> client.gauge('example.gauge', 47)
>>> client.gauge(('example.gauge41', 'example.gauge43'), 47) | Below is the the instruction that describes the task:
### Input:
Log gauges
>>> client = StatsdClient()
>>> client.gauge('example.gauge', 47)
>>> client.gauge(('example.gauge41', 'example.gauge43'), 47)
### Response:
def gauge(self, stats, value):
"""
Log gauges
>>... |
def convert_subject_ids(self, subject_ids):
"""
Convert subject ids to strings if they are integers
"""
# TODO: need to make this generalisable via a
# splitting+mapping function passed to the repository
if subject_ids is not None:
subject_ids = set(
... | Convert subject ids to strings if they are integers | Below is the the instruction that describes the task:
### Input:
Convert subject ids to strings if they are integers
### Response:
def convert_subject_ids(self, subject_ids):
"""
Convert subject ids to strings if they are integers
"""
# TODO: need to make this generalisable via a
... |
def reopen(self):
"""Reopen the tough connection.
It will not complain if the connection cannot be reopened.
"""
try:
self._con.reopen()
except Exception:
if self._transcation:
self._transaction = False
try:
... | Reopen the tough connection.
It will not complain if the connection cannot be reopened. | Below is the the instruction that describes the task:
### Input:
Reopen the tough connection.
It will not complain if the connection cannot be reopened.
### Response:
def reopen(self):
"""Reopen the tough connection.
It will not complain if the connection cannot be reopened.
"""
... |
def pool_args(function, sequence, kwargs):
"""Return a single iterator of n elements of lists of length 3, given a sequence of len n."""
return zip(itertools.repeat(function), sequence, itertools.repeat(kwargs)) | Return a single iterator of n elements of lists of length 3, given a sequence of len n. | Below is the the instruction that describes the task:
### Input:
Return a single iterator of n elements of lists of length 3, given a sequence of len n.
### Response:
def pool_args(function, sequence, kwargs):
"""Return a single iterator of n elements of lists of length 3, given a sequence of len n."""
ret... |
def run(tpu_job_name,
tpu,
gcp_project,
tpu_zone,
model_dir,
model_type="bitransformer",
vocabulary=gin.REQUIRED,
train_dataset_fn=None,
eval_dataset_fn=None,
dataset_split="train",
autostack=True,
checkpoint_path="",
mode="... | Run training/eval/inference.
Args:
tpu_job_name: string, name of TPU worker binary
tpu: string, the Cloud TPU to use for training
gcp_project: string, project name for the Cloud TPU-enabled project
tpu_zone: string, GCE zone where the Cloud TPU is located in
model_dir: string, estimator model_dir... | Below is the the instruction that describes the task:
### Input:
Run training/eval/inference.
Args:
tpu_job_name: string, name of TPU worker binary
tpu: string, the Cloud TPU to use for training
gcp_project: string, project name for the Cloud TPU-enabled project
tpu_zone: string, GCE zone where t... |
def request_doi_status_by_batch_id(self, doi_batch_id, data_type='result'):
"""
This method retrieve the DOI requests status.
file_name: Used as unique ID to identify a deposit.
data_type: [contents, result]
contents - retrieve the XML submited by the publisher
... | This method retrieve the DOI requests status.
file_name: Used as unique ID to identify a deposit.
data_type: [contents, result]
contents - retrieve the XML submited by the publisher
result - retrieve a XML with the status of the submission | Below is the the instruction that describes the task:
### Input:
This method retrieve the DOI requests status.
file_name: Used as unique ID to identify a deposit.
data_type: [contents, result]
contents - retrieve the XML submited by the publisher
result - retrieve a XML wit... |
def range(self, location, distance):
"""Test whether locations are within a given range of ``location``.
Args:
location (Point): Location to test range against
distance (float): Distance to test location is within
Returns:
list of list of Point: Groups of po... | Test whether locations are within a given range of ``location``.
Args:
location (Point): Location to test range against
distance (float): Distance to test location is within
Returns:
list of list of Point: Groups of points in range per segment | Below is the the instruction that describes the task:
### Input:
Test whether locations are within a given range of ``location``.
Args:
location (Point): Location to test range against
distance (float): Distance to test location is within
Returns:
list of list o... |
def convert(self, inp):
"""Converts a string representation of some quantity of units into a
quantities object.
Args:
inp (str): A textual representation of some quantity of units,
e.g., "fifty kilograms".
Returns:
A quantities object representin... | Converts a string representation of some quantity of units into a
quantities object.
Args:
inp (str): A textual representation of some quantity of units,
e.g., "fifty kilograms".
Returns:
A quantities object representing the described quantity and its
... | Below is the the instruction that describes the task:
### Input:
Converts a string representation of some quantity of units into a
quantities object.
Args:
inp (str): A textual representation of some quantity of units,
e.g., "fifty kilograms".
Returns:
... |
def find_by_project(self, project, params={}, **options):
"""Returns the compact records for all sections in the specified project.
Parameters
----------
project : {Id} The project to get sections from.
[params] : {Object} Parameters for the request
"""
path = "... | Returns the compact records for all sections in the specified project.
Parameters
----------
project : {Id} The project to get sections from.
[params] : {Object} Parameters for the request | Below is the the instruction that describes the task:
### Input:
Returns the compact records for all sections in the specified project.
Parameters
----------
project : {Id} The project to get sections from.
[params] : {Object} Parameters for the request
### Response:
def find_by_pr... |
def clean_previous_run(self):
"""Clean variables from previous configuration
:return: None
"""
# Execute the base class treatment...
super(Alignak, self).clean_previous_run()
# Clean all lists
self.pollers.clear()
self.reactionners.clear()
self.b... | Clean variables from previous configuration
:return: None | Below is the the instruction that describes the task:
### Input:
Clean variables from previous configuration
:return: None
### Response:
def clean_previous_run(self):
"""Clean variables from previous configuration
:return: None
"""
# Execute the base class treatment...
... |
def open_spreadsheet(self, path, as_template=False):
"""
Opens an exiting spreadsheet document on the local file system.
"""
desktop = self.cls(self.hostname, self.port)
return desktop.open_spreadsheet(path, as_template=as_template) | Opens an exiting spreadsheet document on the local file system. | Below is the the instruction that describes the task:
### Input:
Opens an exiting spreadsheet document on the local file system.
### Response:
def open_spreadsheet(self, path, as_template=False):
"""
Opens an exiting spreadsheet document on the local file system.
"""
desktop = self.... |
def close(self):
""" Stop overwriting display, or update parent. """
if self.parent:
self.parent.update(self.parent.offset + self.offset)
return
self.output.write("\n")
self.output.flush() | Stop overwriting display, or update parent. | Below is the the instruction that describes the task:
### Input:
Stop overwriting display, or update parent.
### Response:
def close(self):
""" Stop overwriting display, or update parent. """
if self.parent:
self.parent.update(self.parent.offset + self.offset)
return
... |
def create_singleplots(plotman, cov, mag, pha, pha_fpi, alpha, options):
'''Plot the data of the tomodir in individual plots.
'''
magunit = 'log_rho'
if not pha == []:
[real, imag] = calc_complex(mag, pha)
if not pha_fpi == []:
[real_fpi, imag_fpi] = calc_complex(mag, pha_fpi... | Plot the data of the tomodir in individual plots. | Below is the the instruction that describes the task:
### Input:
Plot the data of the tomodir in individual plots.
### Response:
def create_singleplots(plotman, cov, mag, pha, pha_fpi, alpha, options):
'''Plot the data of the tomodir in individual plots.
'''
magunit = 'log_rho'
if not pha == []:
... |
def _mean_prediction(self, lmda, Y, scores, h, t_params):
""" Creates a h-step ahead mean prediction
Parameters
----------
lmda : np.array
The past predicted values
Y : np.array
The past data
scores : np.array
The past scores
... | Creates a h-step ahead mean prediction
Parameters
----------
lmda : np.array
The past predicted values
Y : np.array
The past data
scores : np.array
The past scores
h : int
How many steps ahead for the prediction
... | Below is the the instruction that describes the task:
### Input:
Creates a h-step ahead mean prediction
Parameters
----------
lmda : np.array
The past predicted values
Y : np.array
The past data
scores : np.array
The past scores
... |
def better_print(self, printer=None):
"""
Print the value using a *printer*.
:param printer: Callable used to print the value, by default: :func:`pprint.pprint`
"""
printer = printer or pprint.pprint
printer(self.value) | Print the value using a *printer*.
:param printer: Callable used to print the value, by default: :func:`pprint.pprint` | Below is the the instruction that describes the task:
### Input:
Print the value using a *printer*.
:param printer: Callable used to print the value, by default: :func:`pprint.pprint`
### Response:
def better_print(self, printer=None):
"""
Print the value using a *printer*.
:param... |
def to_json(self, extras=None):
"""
Convert a model into a json using the playhouse shortcut.
"""
extras = extras or {}
to_dict = model_to_dict(self)
to_dict.update(extras)
return json.dumps(to_dict, cls=sel.serializers.JsonEncoder) | Convert a model into a json using the playhouse shortcut. | Below is the the instruction that describes the task:
### Input:
Convert a model into a json using the playhouse shortcut.
### Response:
def to_json(self, extras=None):
"""
Convert a model into a json using the playhouse shortcut.
"""
extras = extras or {}
to_dict = model_to... |
def create(cls, parent, child, relation_type, index=None):
"""Create a PID relation for given parent and child."""
try:
with db.session.begin_nested():
obj = cls(parent_id=parent.id,
child_id=child.id,
relation_type=relation... | Create a PID relation for given parent and child. | Below is the the instruction that describes the task:
### Input:
Create a PID relation for given parent and child.
### Response:
def create(cls, parent, child, relation_type, index=None):
"""Create a PID relation for given parent and child."""
try:
with db.session.begin_nested():
... |
def read_mutating_webhook_configuration(self, name, **kwargs): # noqa: E501
"""read_mutating_webhook_configuration # noqa: E501
read the specified MutatingWebhookConfiguration # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, ... | read_mutating_webhook_configuration # noqa: E501
read the specified MutatingWebhookConfiguration # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_mutating_webhook_configuration(... | Below is the the instruction that describes the task:
### Input:
read_mutating_webhook_configuration # noqa: E501
read the specified MutatingWebhookConfiguration # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_r... |
def get_locations(self):
'''
a method to retrieve all the locations tracked by the model
:return: dictionary with location id keys
NOTE: results are added to self.locations property
{
'location.id': {
'
... | a method to retrieve all the locations tracked by the model
:return: dictionary with location id keys
NOTE: results are added to self.locations property
{
'location.id': {
'
}
} | Below is the the instruction that describes the task:
### Input:
a method to retrieve all the locations tracked by the model
:return: dictionary with location id keys
NOTE: results are added to self.locations property
{
'location.id': {
... |
def save_file(self, filename = 'StockChart'):
""" save htmlcontent as .html file """
filename = filename + '.html'
with open(filename, 'w') as f:
#self.buildhtml()
f.write(self.htmlcontent)
f.closed | save htmlcontent as .html file | Below is the the instruction that describes the task:
### Input:
save htmlcontent as .html file
### Response:
def save_file(self, filename = 'StockChart'):
""" save htmlcontent as .html file """
filename = filename + '.html'
with open(filename, 'w') as f:
#self.buildhtm... |
def setup_build_path(build_path):
"""
Create build directory. If this already exists, print informative
error message and quit.
"""
if os.path.isdir(build_path):
fname = os.path.join(build_path, 'CMakeCache.txt')
if os.path.exists(fname):
sys.stderr.write('aborting setup\... | Create build directory. If this already exists, print informative
error message and quit. | Below is the the instruction that describes the task:
### Input:
Create build directory. If this already exists, print informative
error message and quit.
### Response:
def setup_build_path(build_path):
"""
Create build directory. If this already exists, print informative
error message and quit.
... |
def where(cls, **kwargs):
"""
Returns a generator which yields instances matching the given query
arguments.
For example, this would yield all :py:class:`.Project`::
Project.where()
And this would yield all launch approved :py:class:`.Project`::
Projec... | Returns a generator which yields instances matching the given query
arguments.
For example, this would yield all :py:class:`.Project`::
Project.where()
And this would yield all launch approved :py:class:`.Project`::
Project.where(launch_approved=True) | Below is the the instruction that describes the task:
### Input:
Returns a generator which yields instances matching the given query
arguments.
For example, this would yield all :py:class:`.Project`::
Project.where()
And this would yield all launch approved :py:class:`.Project... |
def get_iso_packet_buffer_list(transfer_p):
"""
Python-specific helper extracting a list of iso packet buffers.
"""
transfer = transfer_p.contents
offset = 0
result = []
append = result.append
for iso_transfer in _get_iso_packet_list(transfer):
length = iso_transfer.length
... | Python-specific helper extracting a list of iso packet buffers. | Below is the the instruction that describes the task:
### Input:
Python-specific helper extracting a list of iso packet buffers.
### Response:
def get_iso_packet_buffer_list(transfer_p):
"""
Python-specific helper extracting a list of iso packet buffers.
"""
transfer = transfer_p.contents
offse... |
def ackermann_naive(m: int, n: int) -> int:
"""Ackermann number.
"""
if m == 0:
return n + 1
elif n == 0:
return ackermann(m - 1, 1)
else:
return ackermann(m - 1, ackermann(m, n - 1)) | Ackermann number. | Below is the the instruction that describes the task:
### Input:
Ackermann number.
### Response:
def ackermann_naive(m: int, n: int) -> int:
"""Ackermann number.
"""
if m == 0:
return n + 1
elif n == 0:
return ackermann(m - 1, 1)
else:
return ackermann(m - 1, ackermann(m... |
def to_0d_array(value: Any) -> np.ndarray:
"""Given a value, wrap it in a 0-D numpy.ndarray.
"""
if np.isscalar(value) or (isinstance(value, np.ndarray) and
value.ndim == 0):
return np.array(value)
else:
return to_0d_object_array(value) | Given a value, wrap it in a 0-D numpy.ndarray. | Below is the the instruction that describes the task:
### Input:
Given a value, wrap it in a 0-D numpy.ndarray.
### Response:
def to_0d_array(value: Any) -> np.ndarray:
"""Given a value, wrap it in a 0-D numpy.ndarray.
"""
if np.isscalar(value) or (isinstance(value, np.ndarray) and
... |
def pcolor_axes(array, px_to_units=px_to_units):
"""
Return axes :code:`x, y` for *array* to be used with :func:`matplotlib.pyplot.color`.
*px_to_units* is a function to convert pixels to units. By default, returns pixels.
"""
# ======================================
# Coords need to be +1 larg... | Return axes :code:`x, y` for *array* to be used with :func:`matplotlib.pyplot.color`.
*px_to_units* is a function to convert pixels to units. By default, returns pixels. | Below is the the instruction that describes the task:
### Input:
Return axes :code:`x, y` for *array* to be used with :func:`matplotlib.pyplot.color`.
*px_to_units* is a function to convert pixels to units. By default, returns pixels.
### Response:
def pcolor_axes(array, px_to_units=px_to_units):
"""
... |
def umode(self, nick, modes=''):
"""
Sets/gets user modes.
Required arguments:
* nick - Nick to set/get user modes for.
Optional arguments:
* modes='' - Sets these user modes on a nick.
"""
with self.lock:
if not modes:
self.sen... | Sets/gets user modes.
Required arguments:
* nick - Nick to set/get user modes for.
Optional arguments:
* modes='' - Sets these user modes on a nick. | Below is the the instruction that describes the task:
### Input:
Sets/gets user modes.
Required arguments:
* nick - Nick to set/get user modes for.
Optional arguments:
* modes='' - Sets these user modes on a nick.
### Response:
def umode(self, nick, modes=''):
"""
Se... |
def _colorize_single_line(line, regexp, color_def):
"""Print single line to console with ability to colorize parts of it."""
match = regexp.match(line)
groupdict = match.groupdict()
groups = match.groups()
if not groupdict:
# no named groups, just colorize whole line
color = c... | Print single line to console with ability to colorize parts of it. | Below is the the instruction that describes the task:
### Input:
Print single line to console with ability to colorize parts of it.
### Response:
def _colorize_single_line(line, regexp, color_def):
"""Print single line to console with ability to colorize parts of it."""
match = regexp.match(line)
gr... |
def namedb_get_name_preorder( db, preorder_hash, current_block ):
"""
Get a (singular) name preorder record outstanding at the given block, given the preorder hash.
NOTE: returns expired preorders.
Return the preorder record on success.
Return None if not found.
"""
select_query = "SEL... | Get a (singular) name preorder record outstanding at the given block, given the preorder hash.
NOTE: returns expired preorders.
Return the preorder record on success.
Return None if not found. | Below is the the instruction that describes the task:
### Input:
Get a (singular) name preorder record outstanding at the given block, given the preorder hash.
NOTE: returns expired preorders.
Return the preorder record on success.
Return None if not found.
### Response:
def namedb_get_name_preord... |
def _parse_tree_structmap(self, tree, parent_elem, normative_parent_elem=None):
"""Recursively parse all the children of parent_elem, including amdSecs
and dmdSecs.
:param lxml._ElementTree tree: encodes the entire METS file.
:param lxml._Element parent_elem: the element whose children w... | Recursively parse all the children of parent_elem, including amdSecs
and dmdSecs.
:param lxml._ElementTree tree: encodes the entire METS file.
:param lxml._Element parent_elem: the element whose children we are
parsing.
:param lxml._Element normative_parent_elem: the normativ... | Below is the the instruction that describes the task:
### Input:
Recursively parse all the children of parent_elem, including amdSecs
and dmdSecs.
:param lxml._ElementTree tree: encodes the entire METS file.
:param lxml._Element parent_elem: the element whose children we are
pars... |
def get_fastq_dir(fc_dir):
"""Retrieve the fastq directory within Solexa flowcell output.
"""
full_goat_bc = glob.glob(os.path.join(fc_dir, "Data", "*Firecrest*", "Bustard*"))
bustard_bc = glob.glob(os.path.join(fc_dir, "Data", "Intensities", "*Bustard*"))
machine_bc = os.path.join(fc_dir, "Data", "... | Retrieve the fastq directory within Solexa flowcell output. | Below is the the instruction that describes the task:
### Input:
Retrieve the fastq directory within Solexa flowcell output.
### Response:
def get_fastq_dir(fc_dir):
"""Retrieve the fastq directory within Solexa flowcell output.
"""
full_goat_bc = glob.glob(os.path.join(fc_dir, "Data", "*Firecrest*", "... |
def Dir_anis_corr(InDir, AniSpec):
"""
takes the 6 element 's' vector and the Dec,Inc 'InDir' data,
performs simple anisotropy correction. returns corrected Dec, Inc
"""
Dir = np.zeros((3), 'f')
Dir[0] = InDir[0]
Dir[1] = InDir[1]
Dir[2] = 1.
chi, chi_inv = check_F(AniSpec)
if ch... | takes the 6 element 's' vector and the Dec,Inc 'InDir' data,
performs simple anisotropy correction. returns corrected Dec, Inc | Below is the the instruction that describes the task:
### Input:
takes the 6 element 's' vector and the Dec,Inc 'InDir' data,
performs simple anisotropy correction. returns corrected Dec, Inc
### Response:
def Dir_anis_corr(InDir, AniSpec):
"""
takes the 6 element 's' vector and the Dec,Inc 'InDir' dat... |
def _read_master_branch_resource(self, fn, is_json=False):
"""This will force the current branch to master! """
with self._master_branch_repo_lock:
ga = self._create_git_action_for_global_resource()
with ga.lock():
ga.checkout_master()
if os.path.e... | This will force the current branch to master! | Below is the the instruction that describes the task:
### Input:
This will force the current branch to master!
### Response:
def _read_master_branch_resource(self, fn, is_json=False):
"""This will force the current branch to master! """
with self._master_branch_repo_lock:
ga = self._cre... |
def change_and_save(self, update_only_changed_fields=False, **changed_fields):
"""
Changes a given `changed_fields` on each object in the queryset, saves objects
and returns the changed objects in the queryset.
"""
bulk_change_and_save(self, update_only_changed_fields=update_only... | Changes a given `changed_fields` on each object in the queryset, saves objects
and returns the changed objects in the queryset. | Below is the the instruction that describes the task:
### Input:
Changes a given `changed_fields` on each object in the queryset, saves objects
and returns the changed objects in the queryset.
### Response:
def change_and_save(self, update_only_changed_fields=False, **changed_fields):
"""
C... |
def log_file(self):
"""The path to the log file for this job.
"""
log_file = self.get('log')
if not log_file:
log_file = '%s.log' % (self.name)
self.set('log', log_file)
return os.path.join(self.initial_dir, self.get('log')) | The path to the log file for this job. | Below is the the instruction that describes the task:
### Input:
The path to the log file for this job.
### Response:
def log_file(self):
"""The path to the log file for this job.
"""
log_file = self.get('log')
if not log_file:
log_file = '%s.log' % (self.name)
... |
def avg_bp_from_range(self, bp):
""" Helper function - FastQC often gives base pair ranges (eg. 10-15)
which are not helpful when plotting. This returns the average from such
ranges as an int, which is helpful. If not a range, just returns the int """
try:
if '-' in bp:
... | Helper function - FastQC often gives base pair ranges (eg. 10-15)
which are not helpful when plotting. This returns the average from such
ranges as an int, which is helpful. If not a range, just returns the int | Below is the the instruction that describes the task:
### Input:
Helper function - FastQC often gives base pair ranges (eg. 10-15)
which are not helpful when plotting. This returns the average from such
ranges as an int, which is helpful. If not a range, just returns the int
### Response:
def avg_b... |
def human2bytes(s):
"""
>>> human2bytes('1M')
1048576
>>> human2bytes('1G')
1073741824
"""
symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
letter = s[-1:].strip().upper()
num = s[:-1]
assert num.isdigit() and letter in symbols, s
num = float(num)
prefix = {symbols... | >>> human2bytes('1M')
1048576
>>> human2bytes('1G')
1073741824 | Below is the the instruction that describes the task:
### Input:
>>> human2bytes('1M')
1048576
>>> human2bytes('1G')
1073741824
### Response:
def human2bytes(s):
"""
>>> human2bytes('1M')
1048576
>>> human2bytes('1G')
1073741824
"""
symbols = ('B', 'K', 'M', 'G', 'T', 'P', '... |
def parseDateText(self, dateString):
"""
Parse long-form date strings::
'May 31st, 2006'
'Jan 1st'
'July 2006'
@type dateString: string
@param dateString: text to convert to a datetime
@rtype: struct_time
@return: calcu... | Parse long-form date strings::
'May 31st, 2006'
'Jan 1st'
'July 2006'
@type dateString: string
@param dateString: text to convert to a datetime
@rtype: struct_time
@return: calculated C{struct_time} value of dateString | Below is the the instruction that describes the task:
### Input:
Parse long-form date strings::
'May 31st, 2006'
'Jan 1st'
'July 2006'
@type dateString: string
@param dateString: text to convert to a datetime
@rtype: struct_time
@ret... |
def generic_ref_formatter(view, context, model, name, lazy=False):
"""
For GenericReferenceField and LazyGenericReferenceField
See Also
--------
diff_formatter
"""
try:
if lazy:
rel_model = getattr(model, name).fetch()
else:
rel_model = getattr(model,... | For GenericReferenceField and LazyGenericReferenceField
See Also
--------
diff_formatter | Below is the the instruction that describes the task:
### Input:
For GenericReferenceField and LazyGenericReferenceField
See Also
--------
diff_formatter
### Response:
def generic_ref_formatter(view, context, model, name, lazy=False):
"""
For GenericReferenceField and LazyGenericReferenceField... |
def compose(self, *args, **kwargs):
"""
Compose layer and masks (mask, vector mask, and clipping layers).
:return: :py:class:`PIL.Image`, or `None` if the layer has no pixel.
"""
from psd_tools.api.composer import compose_layer
if self.bbox == (0, 0, 0, 0):
r... | Compose layer and masks (mask, vector mask, and clipping layers).
:return: :py:class:`PIL.Image`, or `None` if the layer has no pixel. | Below is the the instruction that describes the task:
### Input:
Compose layer and masks (mask, vector mask, and clipping layers).
:return: :py:class:`PIL.Image`, or `None` if the layer has no pixel.
### Response:
def compose(self, *args, **kwargs):
"""
Compose layer and masks (mask, vecto... |
def doc(inherit=None, **kwargs):
"""Annotate the decorated view function or class with the specified Swagger
attributes.
Usage:
.. code-block:: python
@doc(tags=['pet'], description='a pet store')
def get_pet(pet_id):
return Pet.query.filter(Pet.id == pet_id).one()
:p... | Annotate the decorated view function or class with the specified Swagger
attributes.
Usage:
.. code-block:: python
@doc(tags=['pet'], description='a pet store')
def get_pet(pet_id):
return Pet.query.filter(Pet.id == pet_id).one()
:param inherit: Inherit Swagger documentat... | Below is the the instruction that describes the task:
### Input:
Annotate the decorated view function or class with the specified Swagger
attributes.
Usage:
.. code-block:: python
@doc(tags=['pet'], description='a pet store')
def get_pet(pet_id):
return Pet.query.filter(Pe... |
def upload(ctx, release, rebuild):
""" Uploads distribuition files to pypi or pypitest. """
dist_path = Path(DIST_PATH)
if rebuild is False:
if not dist_path.exists() or not list(dist_path.glob('*')):
print("No distribution files found. Please run 'build' command first")
retu... | Uploads distribuition files to pypi or pypitest. | Below is the the instruction that describes the task:
### Input:
Uploads distribuition files to pypi or pypitest.
### Response:
def upload(ctx, release, rebuild):
""" Uploads distribuition files to pypi or pypitest. """
dist_path = Path(DIST_PATH)
if rebuild is False:
if not dist_path.exists() ... |
def get_fig_data_attrs(self, delimiter=None):
"""Join the data attributes with other plotters in the project
This method joins the attributes of the
:class:`~psyplot.InteractiveBase` instances in the project that
draw on the same figure as this instance does.
Parameters
... | Join the data attributes with other plotters in the project
This method joins the attributes of the
:class:`~psyplot.InteractiveBase` instances in the project that
draw on the same figure as this instance does.
Parameters
----------
delimiter: str
Specifies ... | Below is the the instruction that describes the task:
### Input:
Join the data attributes with other plotters in the project
This method joins the attributes of the
:class:`~psyplot.InteractiveBase` instances in the project that
draw on the same figure as this instance does.
Parame... |
def docoptcfg(doc, argv=None, env_prefix=None, config_option=None, ignore=None, *args, **kwargs):
"""Pass most args/kwargs to docopt. Handle `env_prefix` and `config_option`.
:raise DocoptcfgError: If `config_option` isn't found in docstring.
:raise DocoptcfgFileError: On any error while trying to read and... | Pass most args/kwargs to docopt. Handle `env_prefix` and `config_option`.
:raise DocoptcfgError: If `config_option` isn't found in docstring.
:raise DocoptcfgFileError: On any error while trying to read and parse config file (if enabled).
:param str doc: Docstring passed to docopt.
:param iter argv: s... | Below is the the instruction that describes the task:
### Input:
Pass most args/kwargs to docopt. Handle `env_prefix` and `config_option`.
:raise DocoptcfgError: If `config_option` isn't found in docstring.
:raise DocoptcfgFileError: On any error while trying to read and parse config file (if enabled).
... |
def without_global_scope(self, scope):
"""
Remove a registered global scope.
:param scope: The scope to remove
:type scope: Scope or str
:rtype: Builder
"""
if isinstance(scope, basestring):
del self._scopes[scope]
return self
k... | Remove a registered global scope.
:param scope: The scope to remove
:type scope: Scope or str
:rtype: Builder | Below is the the instruction that describes the task:
### Input:
Remove a registered global scope.
:param scope: The scope to remove
:type scope: Scope or str
:rtype: Builder
### Response:
def without_global_scope(self, scope):
"""
Remove a registered global scope.
... |
def setup(self, loop):
"""Start the watcher, registering new watches if any."""
self._loop = loop
self._fd = LibC.inotify_init()
for alias, (path, flags) in self.requests.items():
self._setup_watch(alias, path, flags)
# We pass ownership of the fd to the transport; ... | Start the watcher, registering new watches if any. | Below is the the instruction that describes the task:
### Input:
Start the watcher, registering new watches if any.
### Response:
def setup(self, loop):
"""Start the watcher, registering new watches if any."""
self._loop = loop
self._fd = LibC.inotify_init()
for alias, (path, flags... |
def _get_types(self):
""" extracts the needed types from the configspace for faster retrival later
type = 0 - numerical (continuous or integer) parameter
type >=1 - categorical parameter
TODO: figure out a way to properly handle ordinal parameters
"""
types = []
num_values = []
for hp in se... | extracts the needed types from the configspace for faster retrival later
type = 0 - numerical (continuous or integer) parameter
type >=1 - categorical parameter
TODO: figure out a way to properly handle ordinal parameters | Below is the the instruction that describes the task:
### Input:
extracts the needed types from the configspace for faster retrival later
type = 0 - numerical (continuous or integer) parameter
type >=1 - categorical parameter
TODO: figure out a way to properly handle ordinal parameters
### Response:... |
def tensors_to(tensors, *args, **kwargs):
""" Apply ``torch.Tensor.to`` to tensors in a generic data structure.
Inspired by:
https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31
Args:
tensors (tensor, dict, list, namedtuple or tuple): Data structure with tensor... | Apply ``torch.Tensor.to`` to tensors in a generic data structure.
Inspired by:
https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31
Args:
tensors (tensor, dict, list, namedtuple or tuple): Data structure with tensor values to
move.
*args: Argume... | Below is the the instruction that describes the task:
### Input:
Apply ``torch.Tensor.to`` to tensors in a generic data structure.
Inspired by:
https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31
Args:
tensors (tensor, dict, list, namedtuple or tuple): Data st... |
def submitEntry(self):
"""Process user inputs and subit logbook entry when user clicks Submit button"""
# logType = self.logui.logType.currentText()
mcclogs, physlogs = self.selectedLogs()
success = True
if mcclogs != []:
if not self.acceptedUser("MC... | Process user inputs and subit logbook entry when user clicks Submit button | Below is the the instruction that describes the task:
### Input:
Process user inputs and subit logbook entry when user clicks Submit button
### Response:
def submitEntry(self):
"""Process user inputs and subit logbook entry when user clicks Submit button"""
# logType = self.logui.logType.c... |
def n_cap(self, n_cap='acetyl', cap_dihedral=None):
"""Adds an N-terminal acetamide cap.
Notes
-----
Default behaviour is to duplicate the dihedral angle of the
succeeding residues such that the orientation of the carbonyl
of the acetyl will resemble that of the first re... | Adds an N-terminal acetamide cap.
Notes
-----
Default behaviour is to duplicate the dihedral angle of the
succeeding residues such that the orientation of the carbonyl
of the acetyl will resemble that of the first residue. This
can be adjusted by supplying a cap_dihedral... | Below is the the instruction that describes the task:
### Input:
Adds an N-terminal acetamide cap.
Notes
-----
Default behaviour is to duplicate the dihedral angle of the
succeeding residues such that the orientation of the carbonyl
of the acetyl will resemble that of the fi... |
def get_bytes(self, bridge):
"""
Gets the full command as bytes.
:param bridge: The bridge, to which the command should be sent.
"""
if self.cmd_2 is not None:
cmd = [self.cmd_1, self.cmd_2]
else:
cmd = [self.cmd_1, self.SUFFIX_BYTE]
if br... | Gets the full command as bytes.
:param bridge: The bridge, to which the command should be sent. | Below is the the instruction that describes the task:
### Input:
Gets the full command as bytes.
:param bridge: The bridge, to which the command should be sent.
### Response:
def get_bytes(self, bridge):
"""
Gets the full command as bytes.
:param bridge: The bridge, to which the com... |
def new(project_name):
"""Creates a new project"""
try:
locale.setlocale(locale.LC_ALL, '')
except:
print("Warning: Unable to set locale. Expect encoding problems.")
config = utils.get_config()
config['new_project']['project_name'] = project_name
values = new_project_ui(confi... | Creates a new project | Below is the the instruction that describes the task:
### Input:
Creates a new project
### Response:
def new(project_name):
"""Creates a new project"""
try:
locale.setlocale(locale.LC_ALL, '')
except:
print("Warning: Unable to set locale. Expect encoding problems.")
config = util... |
def word_under_mouse_cursor(self):
"""
Selects the word under the **mouse** cursor.
:return: A QTextCursor with the word under mouse cursor selected.
"""
editor = self._editor
text_cursor = editor.cursorForPosition(editor._last_mouse_pos)
text_cursor = self.word_... | Selects the word under the **mouse** cursor.
:return: A QTextCursor with the word under mouse cursor selected. | Below is the the instruction that describes the task:
### Input:
Selects the word under the **mouse** cursor.
:return: A QTextCursor with the word under mouse cursor selected.
### Response:
def word_under_mouse_cursor(self):
"""
Selects the word under the **mouse** cursor.
:return... |
def comments(self, ticket, include_inline_images=False):
"""
Retrieve the comments for a ticket.
:param ticket: Ticket object or id
:param include_inline_images: Boolean. If `True`, inline image attachments will be
returned in each comments' `attachments` field alongside non... | Retrieve the comments for a ticket.
:param ticket: Ticket object or id
:param include_inline_images: Boolean. If `True`, inline image attachments will be
returned in each comments' `attachments` field alongside non-inline attachments | Below is the the instruction that describes the task:
### Input:
Retrieve the comments for a ticket.
:param ticket: Ticket object or id
:param include_inline_images: Boolean. If `True`, inline image attachments will be
returned in each comments' `attachments` field alongside non-inline ... |
def add_granule(self, data, store, workspace=None):
'''Harvest/add a granule into an existing imagemosaic'''
ext = os.path.splitext(data)[-1]
if ext == ".zip":
type = "file.imagemosaic"
upload_data = open(data, 'rb')
headers = {
"Content-type":... | Harvest/add a granule into an existing imagemosaic | Below is the the instruction that describes the task:
### Input:
Harvest/add a granule into an existing imagemosaic
### Response:
def add_granule(self, data, store, workspace=None):
'''Harvest/add a granule into an existing imagemosaic'''
ext = os.path.splitext(data)[-1]
if ext == ".zip":
... |
def set_user_session(user):
"""
Set user session
:param user: user object chould be model instance or dict
:return:
"""
from uliweb import settings, request
user_fieldname = settings.get_var('AUTH/GET_AUTH_USER_FIELDNAME', 'id')
share_session = settings.get_var('AUTH/AUTH_SHARE... | Set user session
:param user: user object chould be model instance or dict
:return: | Below is the the instruction that describes the task:
### Input:
Set user session
:param user: user object chould be model instance or dict
:return:
### Response:
def set_user_session(user):
"""
Set user session
:param user: user object chould be model instance or dict
:return:
"... |
def read_examples(input_files, batch_size, shuffle, num_epochs=None):
"""Creates readers and queues for reading example protos."""
files = []
for e in input_files:
for path in e.split(','):
files.extend(file_io.get_matching_files(path))
thread_count = multiprocessing.cpu_count()
# The minimum numbe... | Creates readers and queues for reading example protos. | Below is the the instruction that describes the task:
### Input:
Creates readers and queues for reading example protos.
### Response:
def read_examples(input_files, batch_size, shuffle, num_epochs=None):
"""Creates readers and queues for reading example protos."""
files = []
for e in input_files:
for pat... |
def _check_pillar_exact_minions(self, expr, delimiter, greedy):
'''
Return the minions found by looking via pillar
'''
return self._check_cache_minions(expr,
delimiter,
greedy,
... | Return the minions found by looking via pillar | Below is the the instruction that describes the task:
### Input:
Return the minions found by looking via pillar
### Response:
def _check_pillar_exact_minions(self, expr, delimiter, greedy):
'''
Return the minions found by looking via pillar
'''
return self._check_cache_minions(expr,... |
def run_qaml(self):
"""
Create and run the GenomeQAML system call
"""
logging.info('Running GenomeQAML quality assessment')
qaml_call = 'classify.py -t {tf} -r {rf}'\
.format(tf=self.qaml_path,
rf=self.qaml_report)
make_path(self.reportpath... | Create and run the GenomeQAML system call | Below is the the instruction that describes the task:
### Input:
Create and run the GenomeQAML system call
### Response:
def run_qaml(self):
"""
Create and run the GenomeQAML system call
"""
logging.info('Running GenomeQAML quality assessment')
qaml_call = 'classify.py -t {t... |
def _rule_option(self):
""" Parses the production rule::
option : NAME value ';'
Returns list (name, value_list).
"""
name = self._get_token(self.RE_NAME)
value = self._rule_value()
self._expect_token(';')
return [name, value] | Parses the production rule::
option : NAME value ';'
Returns list (name, value_list). | Below is the the instruction that describes the task:
### Input:
Parses the production rule::
option : NAME value ';'
Returns list (name, value_list).
### Response:
def _rule_option(self):
""" Parses the production rule::
option : NAME value ';'
Ret... |
def compare_schemas(one, two):
"""Compare two structures that represents JSON schemas.
For comparison you can't use normal comparison, because in JSON schema
lists DO NOT keep order (and Python lists do), so this must be taken into
account during comparison.
Note this wont check all configurations... | Compare two structures that represents JSON schemas.
For comparison you can't use normal comparison, because in JSON schema
lists DO NOT keep order (and Python lists do), so this must be taken into
account during comparison.
Note this wont check all configurations, only first one that seems to
mat... | Below is the the instruction that describes the task:
### Input:
Compare two structures that represents JSON schemas.
For comparison you can't use normal comparison, because in JSON schema
lists DO NOT keep order (and Python lists do), so this must be taken into
account during comparison.
Note thi... |
def pathstrip(path, n):
""" Strip n leading components from the given path """
pathlist = [path]
while os.path.dirname(pathlist[0]) != b'':
pathlist[0:1] = os.path.split(pathlist[0])
return b'/'.join(pathlist[n:]) | Strip n leading components from the given path | Below is the the instruction that describes the task:
### Input:
Strip n leading components from the given path
### Response:
def pathstrip(path, n):
""" Strip n leading components from the given path """
pathlist = [path]
while os.path.dirname(pathlist[0]) != b'':
pathlist[0:1] = os.path.split(pathlist[... |
def Main(url):
'''
Entry Point.
Args:
url: target url.
'''
# The object of Web-Scraping.
web_scrape = WebScraping()
# Execute Web-Scraping.
document = web_scrape.scrape(url)
# The object of automatic summarization with N-gram.
auto_abstractor = NgramAutoAbstractor... | Entry Point.
Args:
url: target url. | Below is the the instruction that describes the task:
### Input:
Entry Point.
Args:
url: target url.
### Response:
def Main(url):
'''
Entry Point.
Args:
url: target url.
'''
# The object of Web-Scraping.
web_scrape = WebScraping()
# Execute Web-Scrapi... |
def write(filename, data):
"""
Create a new BibTeX file.
:param filename: The name of the BibTeX file to write.
:param data: A ``bibtexparser.BibDatabase`` object.
"""
with open(filename, 'w') as fh:
fh.write(bibdatabase2bibtex(data)) | Create a new BibTeX file.
:param filename: The name of the BibTeX file to write.
:param data: A ``bibtexparser.BibDatabase`` object. | Below is the the instruction that describes the task:
### Input:
Create a new BibTeX file.
:param filename: The name of the BibTeX file to write.
:param data: A ``bibtexparser.BibDatabase`` object.
### Response:
def write(filename, data):
"""
Create a new BibTeX file.
:param filename: The nam... |
def getmoduleinfo(path):
"""Get the module name, suffix, mode, and module type for a given file."""
filename = os.path.basename(path)
suffixes = map(lambda (suffix, mode, mtype):
(-len(suffix), suffix, mode, mtype), imp.get_suffixes())
suffixes.sort() # try longest suffixes first, in ... | Get the module name, suffix, mode, and module type for a given file. | Below is the the instruction that describes the task:
### Input:
Get the module name, suffix, mode, and module type for a given file.
### Response:
def getmoduleinfo(path):
"""Get the module name, suffix, mode, and module type for a given file."""
filename = os.path.basename(path)
suffixes = map(lambda... |
def spawn_managed_host(config_file, manager, connect_on_start=True):
"""
Spawns a managed host, if it is not already running
"""
data = manager.request_host_status(config_file)
is_running = data['started']
# Managed hosts run as persistent processes, so it may already be running
if is_run... | Spawns a managed host, if it is not already running | Below is the the instruction that describes the task:
### Input:
Spawns a managed host, if it is not already running
### Response:
def spawn_managed_host(config_file, manager, connect_on_start=True):
"""
Spawns a managed host, if it is not already running
"""
data = manager.request_host_status(con... |
def decodeTagAttributes(self, text):
"""docstring for decodeTagAttributes"""
attribs = {}
if text.strip() == u'':
return attribs
scanner = _attributePat.scanner(text)
match = scanner.search()
while match:
key, val1, val2, val3, val4 = match.groups()
value = val1 or val2 or val3 or val4
if value:... | docstring for decodeTagAttributes | Below is the the instruction that describes the task:
### Input:
docstring for decodeTagAttributes
### Response:
def decodeTagAttributes(self, text):
"""docstring for decodeTagAttributes"""
attribs = {}
if text.strip() == u'':
return attribs
scanner = _attributePat.scanner(text)
match = scanner.search... |
def find_button(browser, value):
"""
Find a button with the given value.
Searches for the following different kinds of buttons:
<input type="submit">
<input type="reset">
<input type="button">
<input type="image">
<button>
<{a,p,div,span,...} role="button">
... | Find a button with the given value.
Searches for the following different kinds of buttons:
<input type="submit">
<input type="reset">
<input type="button">
<input type="image">
<button>
<{a,p,div,span,...} role="button">
Returns: an :class:`ElementSelector` | Below is the the instruction that describes the task:
### Input:
Find a button with the given value.
Searches for the following different kinds of buttons:
<input type="submit">
<input type="reset">
<input type="button">
<input type="image">
<button>
<{a,p,div,s... |
def to_record_per_alt(self):
'''Returns list of vcf_records. One per variant
in the ALT column. Does not change INFO/FORMAT etc columns, which
means that they are now broken'''
record_list = []
for alt in self.ALT:
record_list.append(copy.copy(self))
recor... | Returns list of vcf_records. One per variant
in the ALT column. Does not change INFO/FORMAT etc columns, which
means that they are now broken | Below is the the instruction that describes the task:
### Input:
Returns list of vcf_records. One per variant
in the ALT column. Does not change INFO/FORMAT etc columns, which
means that they are now broken
### Response:
def to_record_per_alt(self):
'''Returns list of vcf_records. One per v... |
def from_config(config, **options):
"""Instantiate an `SyncedRotationEventStores` from config.
Parameters:
config -- the configuration file options read from file(s).
**options -- various options given to the specific event store. Shall
not be used with this even... | Instantiate an `SyncedRotationEventStores` from config.
Parameters:
config -- the configuration file options read from file(s).
**options -- various options given to the specific event store. Shall
not be used with this event store. Warning will be logged
... | Below is the the instruction that describes the task:
### Input:
Instantiate an `SyncedRotationEventStores` from config.
Parameters:
config -- the configuration file options read from file(s).
**options -- various options given to the specific event store. Shall
not ... |
def refund_order(self, request, pk):
"""Refund the order specified by the pk
"""
order = Order.objects.get(id=pk)
order.refund()
return Response(status=status.HTTP_204_NO_CONTENT) | Refund the order specified by the pk | Below is the the instruction that describes the task:
### Input:
Refund the order specified by the pk
### Response:
def refund_order(self, request, pk):
"""Refund the order specified by the pk
"""
order = Order.objects.get(id=pk)
order.refund()
return Response(status=status.... |
def PopupGetFolder(message, title=None, default_path='', no_window=False, size=(None, None), button_color=None,
background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False,
grab_anywhere=False, keep_on_top=False, location=(None, None), initial_fol... | Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
... | Below is the the instruction that describes the task:
### Input:
Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
... |
def create_friendship(self, access_token,
user_id=None, user_name=None):
"""doc: http://open.youku.com/docs/doc?id=28
"""
url = 'https://openapi.youku.com/v2/users/friendship/create.json'
data = {
'client_id': self.client_id,
'access_toke... | doc: http://open.youku.com/docs/doc?id=28 | Below is the the instruction that describes the task:
### Input:
doc: http://open.youku.com/docs/doc?id=28
### Response:
def create_friendship(self, access_token,
user_id=None, user_name=None):
"""doc: http://open.youku.com/docs/doc?id=28
"""
url = 'https://openapi... |
def _rename(self):
"""
Called during a PUT request where the action specifies
a rename operation. Returns resource URI of the renamed file.
"""
newname = self.action['newname']
try:
newpath = self.fs.rename(self.fp,newname)
except OSError:
... | Called during a PUT request where the action specifies
a rename operation. Returns resource URI of the renamed file. | Below is the the instruction that describes the task:
### Input:
Called during a PUT request where the action specifies
a rename operation. Returns resource URI of the renamed file.
### Response:
def _rename(self):
"""
Called during a PUT request where the action specifies
a rename ... |
def main(arguments=None):
"""
*The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command*
"""
# setup the command-line util settings
su = tools(
arguments=arguments,
docString=__doc__,
logLevel="WARNING",
opti... | *The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command* | Below is the the instruction that describes the task:
### Input:
*The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command*
### Response:
def main(arguments=None):
"""
*The main function used when ``cl_utils.py`` is run as a single script from the... |
def wr_txt_section_hdrgos(self, fout_txt, sortby=None, prt_section=True):
"""Write high GO IDs that are actually used to group current set of GO IDs."""
sec2d_go = self.grprobj.get_sections_2d() # lists of GO IDs
sec2d_nt = self.get_sections_2dnt(sec2d_go) # lists of GO Grouper namedtuples
... | Write high GO IDs that are actually used to group current set of GO IDs. | Below is the the instruction that describes the task:
### Input:
Write high GO IDs that are actually used to group current set of GO IDs.
### Response:
def wr_txt_section_hdrgos(self, fout_txt, sortby=None, prt_section=True):
"""Write high GO IDs that are actually used to group current set of GO IDs."""
... |
def replaceChild(self, child, content):
"""
Replace I{child} with the specified I{content}.
@param child: A child element.
@type child: L{Element}
@param content: An element or collection of elements.
@type content: L{Element} or [L{Element},]
"""
if child... | Replace I{child} with the specified I{content}.
@param child: A child element.
@type child: L{Element}
@param content: An element or collection of elements.
@type content: L{Element} or [L{Element},] | Below is the the instruction that describes the task:
### Input:
Replace I{child} with the specified I{content}.
@param child: A child element.
@type child: L{Element}
@param content: An element or collection of elements.
@type content: L{Element} or [L{Element},]
### Response:
def ... |
def get_space_information(self, space_key, expand=None, callback=None):
"""
Returns information about a space.
:param space_key (string): A string containing the key of the space.
:param expand (string): OPTIONAL: A comma separated list of properties to expand on the space. Default: Empt... | Returns information about a space.
:param space_key (string): A string containing the key of the space.
:param expand (string): OPTIONAL: A comma separated list of properties to expand on the space. Default: Empty.
:param callback: OPTIONAL: The callback to execute on the resulting data, before ... | Below is the the instruction that describes the task:
### Input:
Returns information about a space.
:param space_key (string): A string containing the key of the space.
:param expand (string): OPTIONAL: A comma separated list of properties to expand on the space. Default: Empty.
:param callb... |
def _handle_default(value, script_name):
""" There are two potential variants of these scripts,
the Bash scripts that are meant to be run within PULSAR_ROOT
for older-style installs and the binaries created by setup.py
as part of a proper pulsar installation.
This method first looks for the newer s... | There are two potential variants of these scripts,
the Bash scripts that are meant to be run within PULSAR_ROOT
for older-style installs and the binaries created by setup.py
as part of a proper pulsar installation.
This method first looks for the newer style variant of these
scripts and returns the... | Below is the the instruction that describes the task:
### Input:
There are two potential variants of these scripts,
the Bash scripts that are meant to be run within PULSAR_ROOT
for older-style installs and the binaries created by setup.py
as part of a proper pulsar installation.
This method first l... |
def returner(load):
'''
Return data to a postgres server
'''
conn = _get_conn()
if conn is None:
return None
cur = conn.cursor()
sql = '''INSERT INTO salt_returns
(fun, jid, return, id, success)
VALUES (%s, %s, %s, %s, %s)'''
try:
ret = six.text_ty... | Return data to a postgres server | Below is the the instruction that describes the task:
### Input:
Return data to a postgres server
### Response:
def returner(load):
'''
Return data to a postgres server
'''
conn = _get_conn()
if conn is None:
return None
cur = conn.cursor()
sql = '''INSERT INTO salt_returns
... |
def load_stubs(self, log_mem=False):
"""Load all events in their `stub` (name, alias, etc only) form.
Used in `update` mode.
"""
# Initialize parameter related to diagnostic output of memory usage
if log_mem:
import psutil
process = psutil.Process(os.getp... | Load all events in their `stub` (name, alias, etc only) form.
Used in `update` mode. | Below is the the instruction that describes the task:
### Input:
Load all events in their `stub` (name, alias, etc only) form.
Used in `update` mode.
### Response:
def load_stubs(self, log_mem=False):
"""Load all events in their `stub` (name, alias, etc only) form.
Used in `update` mode.
... |
def display_reports(self, layout):
"""Issues the final PyLint score as a TeamCity build statistic value"""
try:
score = self.linter.stats['global_note']
except (AttributeError, KeyError):
pass
else:
self.tc.message('buildStatisticValue', key='PyLintSco... | Issues the final PyLint score as a TeamCity build statistic value | Below is the the instruction that describes the task:
### Input:
Issues the final PyLint score as a TeamCity build statistic value
### Response:
def display_reports(self, layout):
"""Issues the final PyLint score as a TeamCity build statistic value"""
try:
score = self.linter.stats['glo... |
def _contextkey(jail=None, chroot=None, root=None, prefix='pkg.list_pkgs'):
'''
As this module is designed to manipulate packages in jails and chroots, use
the passed jail/chroot to ensure that a key in the __context__ dict that is
unique to that jail/chroot is used.
'''
if jail:
return ... | As this module is designed to manipulate packages in jails and chroots, use
the passed jail/chroot to ensure that a key in the __context__ dict that is
unique to that jail/chroot is used. | Below is the the instruction that describes the task:
### Input:
As this module is designed to manipulate packages in jails and chroots, use
the passed jail/chroot to ensure that a key in the __context__ dict that is
unique to that jail/chroot is used.
### Response:
def _contextkey(jail=None, chroot=None, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.