code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def string_tag(name, value):
"""Create a DMAP tag with string data."""
return name.encode('utf-8') + \
len(value).to_bytes(4, byteorder='big') + \
value.encode('utf-8') | Create a DMAP tag with string data. | Below is the the instruction that describes the task:
### Input:
Create a DMAP tag with string data.
### Response:
def string_tag(name, value):
"""Create a DMAP tag with string data."""
return name.encode('utf-8') + \
len(value).to_bytes(4, byteorder='big') + \
value.encode('utf-8') |
def evaluate_normal(self, value):
"""Evaluate normal string."""
if value.startswith('L'):
size = self.wide_charset_size
encoding = self.wide_exec_charset
value = value[2:-1]
pack = BYTE_STORE[size | CURRENT_ENDIAN]
else:
size = self.ch... | Evaluate normal string. | Below is the the instruction that describes the task:
### Input:
Evaluate normal string.
### Response:
def evaluate_normal(self, value):
"""Evaluate normal string."""
if value.startswith('L'):
size = self.wide_charset_size
encoding = self.wide_exec_charset
value... |
def get_real_data(self):
"""
Grab actual data from the system
"""
ret = []
username = os.environ.get('USER')
if username:
ret.append(username)
editor = os.environ.get('EDITOR')
if editor:
editor = editor.split('/')[-1]
... | Grab actual data from the system | Below is the the instruction that describes the task:
### Input:
Grab actual data from the system
### Response:
def get_real_data(self):
"""
Grab actual data from the system
"""
ret = []
username = os.environ.get('USER')
if username:
ret.append(username... |
def get_source_link(file, line, display_text="[source]", **kwargs)->str:
"Returns github link for given file"
link = f"{SOURCE_URL}{file}#L{line}"
if display_text is None: return link
return f'<a href="{link}" class="source_link" style="float:right">{display_text}</a>' | Returns github link for given file | Below is the the instruction that describes the task:
### Input:
Returns github link for given file
### Response:
def get_source_link(file, line, display_text="[source]", **kwargs)->str:
"Returns github link for given file"
link = f"{SOURCE_URL}{file}#L{line}"
if display_text is None: return link
r... |
def get_active_pitch_range(self):
"""
Return the active pitch range as a tuple (lowest, highest).
Returns
-------
lowest : int
The lowest active pitch in the pianoroll.
highest : int
The highest active pitch in the pianoroll.
"""
... | Return the active pitch range as a tuple (lowest, highest).
Returns
-------
lowest : int
The lowest active pitch in the pianoroll.
highest : int
The highest active pitch in the pianoroll. | Below is the the instruction that describes the task:
### Input:
Return the active pitch range as a tuple (lowest, highest).
Returns
-------
lowest : int
The lowest active pitch in the pianoroll.
highest : int
The highest active pitch in the pianoroll.
### Re... |
def exclude_invert(self):
# type:() -> None
"""
Inverts the values in self.exclude
.. code-block:: python
>>> import pydarksky
>>> darksky = pydarksky.DarkSky('0' * 32)
>>> darksky.EXCLUDES
('currently', 'minutely', 'hourly', 'daily', 'a... | Inverts the values in self.exclude
.. code-block:: python
>>> import pydarksky
>>> darksky = pydarksky.DarkSky('0' * 32)
>>> darksky.EXCLUDES
('currently', 'minutely', 'hourly', 'daily', 'alerts', 'flags')
>>> darksky.exclude = ["alerts", "flags"]
... | Below is the the instruction that describes the task:
### Input:
Inverts the values in self.exclude
.. code-block:: python
>>> import pydarksky
>>> darksky = pydarksky.DarkSky('0' * 32)
>>> darksky.EXCLUDES
('currently', 'minutely', 'hourly', 'daily', 'aler... |
def get_autype_list(self, code_list):
"""
获取给定股票列表的复权因子
:param code_list: 股票列表,例如['HK.00700']
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下
ret != RET_OK 返回错误字符串
===================== =========== ====... | 获取给定股票列表的复权因子
:param code_list: 股票列表,例如['HK.00700']
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下
ret != RET_OK 返回错误字符串
===================== =========== ==============================================================... | Below is the the instruction that describes the task:
### Input:
获取给定股票列表的复权因子
:param code_list: 股票列表,例如['HK.00700']
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下
ret != RET_OK 返回错误字符串
===================== =======... |
def _build_file(self, nmrstar_str):
"""Build :class:`~nmrstarlib.nmrstarlib.NMRStarFile` object.
:param nmrstar_str: NMR-STAR-formatted string.
:type nmrstar_str: :py:class:`str` or :py:class:`bytes`
:return: instance of :class:`~nmrstarlib.nmrstarlib.NMRStarFile`.
:rtype: :clas... | Build :class:`~nmrstarlib.nmrstarlib.NMRStarFile` object.
:param nmrstar_str: NMR-STAR-formatted string.
:type nmrstar_str: :py:class:`str` or :py:class:`bytes`
:return: instance of :class:`~nmrstarlib.nmrstarlib.NMRStarFile`.
:rtype: :class:`~nmrstarlib.nmrstarlib.NMRStarFile` | Below is the the instruction that describes the task:
### Input:
Build :class:`~nmrstarlib.nmrstarlib.NMRStarFile` object.
:param nmrstar_str: NMR-STAR-formatted string.
:type nmrstar_str: :py:class:`str` or :py:class:`bytes`
:return: instance of :class:`~nmrstarlib.nmrstarlib.NMRStarFile`.... |
def set_memory(self, total=None, static=None):
"""
Set the maxium allowed memory.
Args:
total: The total memory. Integer. Unit: MBytes. If set to None,
this parameter will be neglected.
static: The static memory. Integer. Unit MBytes. If set to None,
... | Set the maxium allowed memory.
Args:
total: The total memory. Integer. Unit: MBytes. If set to None,
this parameter will be neglected.
static: The static memory. Integer. Unit MBytes. If set to None,
this parameterwill be neglected. | Below is the the instruction that describes the task:
### Input:
Set the maxium allowed memory.
Args:
total: The total memory. Integer. Unit: MBytes. If set to None,
this parameter will be neglected.
static: The static memory. Integer. Unit MBytes. If set to None,
... |
def get_binary_iterator(self):
"""
Generator to read a file piece by piece.
"""
CHUNK_SIZE = 1024
file_object = open(self.path)
while True:
data = file_object.read(CHUNK_SIZE)
if not data:
break
yield data
file... | Generator to read a file piece by piece. | Below is the the instruction that describes the task:
### Input:
Generator to read a file piece by piece.
### Response:
def get_binary_iterator(self):
"""
Generator to read a file piece by piece.
"""
CHUNK_SIZE = 1024
file_object = open(self.path)
while True:
... |
def create_from_raw_data(self, klass, raw_data, headers={}):
"""
Creates an object from raw_data previously obtained by :attr:`github.GithubObject.GithubObject.raw_data`,
and optionaly headers previously obtained by :attr:`github.GithubObject.GithubObject.raw_headers`.
:param klass: the... | Creates an object from raw_data previously obtained by :attr:`github.GithubObject.GithubObject.raw_data`,
and optionaly headers previously obtained by :attr:`github.GithubObject.GithubObject.raw_headers`.
:param klass: the class of the object to create
:param raw_data: dict
:param heade... | Below is the the instruction that describes the task:
### Input:
Creates an object from raw_data previously obtained by :attr:`github.GithubObject.GithubObject.raw_data`,
and optionaly headers previously obtained by :attr:`github.GithubObject.GithubObject.raw_headers`.
:param klass: the class of th... |
async def auto_detect_at_address(cls, address, auth):
'''Try to detect a SOCKS proxy at address using the authentication method (or None).
SOCKS5, SOCKS4a and SOCKS are tried in order. If a SOCKS proxy is detected a
SOCKSProxy object is returned.
Returning a SOCKSProxy does not mean it... | Try to detect a SOCKS proxy at address using the authentication method (or None).
SOCKS5, SOCKS4a and SOCKS are tried in order. If a SOCKS proxy is detected a
SOCKSProxy object is returned.
Returning a SOCKSProxy does not mean it is functioning - for example, it may have
no network con... | Below is the the instruction that describes the task:
### Input:
Try to detect a SOCKS proxy at address using the authentication method (or None).
SOCKS5, SOCKS4a and SOCKS are tried in order. If a SOCKS proxy is detected a
SOCKSProxy object is returned.
Returning a SOCKSProxy does not mea... |
def dispatch_command(self, command, params=None):
"""Dispatch device commands to the appropriate handler."""
try:
if command in self.handlers:
self.handlers[command](**params)
else:
logging.warning('Unsupported command: %s: %s',
... | Dispatch device commands to the appropriate handler. | Below is the the instruction that describes the task:
### Input:
Dispatch device commands to the appropriate handler.
### Response:
def dispatch_command(self, command, params=None):
"""Dispatch device commands to the appropriate handler."""
try:
if command in self.handlers:
... |
def parse_perfctr_event(perfctr):
"""
Parse events in machine description to tuple representation used in Benchmark module.
Examples:
>>> parse_perfctr_event('PERF_EVENT:REG[0-3]')
('PERF_EVENT', 'REG[0-3]')
>>> parse_perfctr_event('PERF_EVENT:REG[0-3]:STAY:FOO=23:BAR=0x... | Parse events in machine description to tuple representation used in Benchmark module.
Examples:
>>> parse_perfctr_event('PERF_EVENT:REG[0-3]')
('PERF_EVENT', 'REG[0-3]')
>>> parse_perfctr_event('PERF_EVENT:REG[0-3]:STAY:FOO=23:BAR=0x23')
('PERF_EVENT', 'REG[0-3]', {'STAY': None,... | Below is the the instruction that describes the task:
### Input:
Parse events in machine description to tuple representation used in Benchmark module.
Examples:
>>> parse_perfctr_event('PERF_EVENT:REG[0-3]')
('PERF_EVENT', 'REG[0-3]')
>>> parse_perfctr_event('PERF_EVENT:REG[0-3]:STA... |
def write_two_phases(filename, data, io):
"""
Writes a file in two phase to the filesystem.
First write the data to a temporary file (in the same directory) and than renames the temporary file. If the
file already exists and its content is equal to the data that must be written no actio... | Writes a file in two phase to the filesystem.
First write the data to a temporary file (in the same directory) and than renames the temporary file. If the
file already exists and its content is equal to the data that must be written no action is taken. This has the
following advantages:
... | Below is the the instruction that describes the task:
### Input:
Writes a file in two phase to the filesystem.
First write the data to a temporary file (in the same directory) and than renames the temporary file. If the
file already exists and its content is equal to the data that must be written n... |
def find_class_properties(cls):
"""Find property members in a class.
Returns all the property members of a class in a list of
(name, value) pairs. Only those members defined with `property`
decorator will be included in the list.
:param cls: class where property members will be searched
:retu... | Find property members in a class.
Returns all the property members of a class in a list of
(name, value) pairs. Only those members defined with `property`
decorator will be included in the list.
:param cls: class where property members will be searched
:returns: list of properties | Below is the the instruction that describes the task:
### Input:
Find property members in a class.
Returns all the property members of a class in a list of
(name, value) pairs. Only those members defined with `property`
decorator will be included in the list.
:param cls: class where property membe... |
def account_block_count(self, account):
"""
Get number of blocks for a specific **account**
:param account: Account to get number of blocks for
:type account: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.account_block_count(account="xrb_3t6k35gi95xu6tergt6p69ck... | Get number of blocks for a specific **account**
:param account: Account to get number of blocks for
:type account: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.account_block_count(account="xrb_3t6k35gi95xu6tergt6p69ck76ogmitsa8mnijtpxm9fkcm736xtoncuohr3")
19 | Below is the the instruction that describes the task:
### Input:
Get number of blocks for a specific **account**
:param account: Account to get number of blocks for
:type account: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.account_block_count(account="xrb_3t6k35gi95xu6te... |
def normalize(value, unit):
"""Converts the value so that it belongs to some expected range.
Returns the new value and new unit.
E.g:
>>> normalize(1024, 'KB')
(1, 'MB')
>>> normalize(90, 'min')
(1.5, 'hr')
>>> normalize(1.0, 'object')
(1, 'object')
"""
if value < 0:
... | Converts the value so that it belongs to some expected range.
Returns the new value and new unit.
E.g:
>>> normalize(1024, 'KB')
(1, 'MB')
>>> normalize(90, 'min')
(1.5, 'hr')
>>> normalize(1.0, 'object')
(1, 'object') | Below is the the instruction that describes the task:
### Input:
Converts the value so that it belongs to some expected range.
Returns the new value and new unit.
E.g:
>>> normalize(1024, 'KB')
(1, 'MB')
>>> normalize(90, 'min')
(1.5, 'hr')
>>> normalize(1.0, 'object')
(1, 'object... |
def multiput(client, objs, **options):
"""Executes a parallel-store across multiple threads. Returns a list
containing booleans or :class:`~riak.riak_object.RiakObject`
If a ``pool`` option is included, the request will use the given worker
pool and not a transient :class:`~riak.client.multi.MultiPutPo... | Executes a parallel-store across multiple threads. Returns a list
containing booleans or :class:`~riak.riak_object.RiakObject`
If a ``pool`` option is included, the request will use the given worker
pool and not a transient :class:`~riak.client.multi.MultiPutPool`. This
option will be passed by the cli... | Below is the the instruction that describes the task:
### Input:
Executes a parallel-store across multiple threads. Returns a list
containing booleans or :class:`~riak.riak_object.RiakObject`
If a ``pool`` option is included, the request will use the given worker
pool and not a transient :class:`~riak.... |
def create_mysql_db(db_url):
"""
To simplify deployment, create the mysql DB if it's not there.
Accepts a URL with or without a DB name stated, and returns a db url
containing the db name for use in the main sqlalchemy engine.
THe formats can take the following form:
mysql+... | To simplify deployment, create the mysql DB if it's not there.
Accepts a URL with or without a DB name stated, and returns a db url
containing the db name for use in the main sqlalchemy engine.
THe formats can take the following form:
mysql+driver://username:password@hostname
m... | Below is the the instruction that describes the task:
### Input:
To simplify deployment, create the mysql DB if it's not there.
Accepts a URL with or without a DB name stated, and returns a db url
containing the db name for use in the main sqlalchemy engine.
THe formats can take the followi... |
def calculate_size(transaction_id, thread_id):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(transaction_id)
data_size += LONG_SIZE_IN_BYTES
return data_size | Calculates the request payload size | Below is the the instruction that describes the task:
### Input:
Calculates the request payload size
### Response:
def calculate_size(transaction_id, thread_id):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(transaction_id)
data_size += LONG_SIZE_IN_BYTES
... |
def request_time(self) -> float:
"""Returns the amount of time it took for this request to execute."""
if self._finish_time is None:
return time.time() - self._start_time
else:
return self._finish_time - self._start_time | Returns the amount of time it took for this request to execute. | Below is the the instruction that describes the task:
### Input:
Returns the amount of time it took for this request to execute.
### Response:
def request_time(self) -> float:
"""Returns the amount of time it took for this request to execute."""
if self._finish_time is None:
return time... |
def pretty_print(self, indent=0):
"""Print the document without tags using indentation
"""
s = tab = ' '*indent
s += '%s: ' %self.tag
if isinstance(self.value, basestring):
s += self.value
else:
s += '\n'
for e in self.value:
... | Print the document without tags using indentation | Below is the the instruction that describes the task:
### Input:
Print the document without tags using indentation
### Response:
def pretty_print(self, indent=0):
"""Print the document without tags using indentation
"""
s = tab = ' '*indent
s += '%s: ' %self.tag
if isinstan... |
def roc_auc_xlim(x_bla, y_bla, xlim=0.1):
"""
Computes the ROC Area Under Curve until a certain FPR value.
Parameters
----------
fg_vals : array_like
list of values for positive set
bg_vals : array_like
list of values for negative set
xlim : float, optional
FPR val... | Computes the ROC Area Under Curve until a certain FPR value.
Parameters
----------
fg_vals : array_like
list of values for positive set
bg_vals : array_like
list of values for negative set
xlim : float, optional
FPR value
Returns
-------
score : float
... | Below is the the instruction that describes the task:
### Input:
Computes the ROC Area Under Curve until a certain FPR value.
Parameters
----------
fg_vals : array_like
list of values for positive set
bg_vals : array_like
list of values for negative set
xlim : float, optional
... |
def _CopyFromDateTimeValues(self, date_time_values):
"""Copies time elements from date and time values.
Args:
date_time_values (dict[str, int]): date and time values, such as year,
month, day of month, hours, minutes, seconds, microseconds.
"""
year = date_time_values.get('year', 0)
... | Copies time elements from date and time values.
Args:
date_time_values (dict[str, int]): date and time values, such as year,
month, day of month, hours, minutes, seconds, microseconds. | Below is the the instruction that describes the task:
### Input:
Copies time elements from date and time values.
Args:
date_time_values (dict[str, int]): date and time values, such as year,
month, day of month, hours, minutes, seconds, microseconds.
### Response:
def _CopyFromDateTimeValues(s... |
def link_user_to_group(self, user_id, group_id, headers=None, endpoint_url=None):
"""
Links a user to a group
:param str user_id: identified user's ID
:param str group_id: group ID
:param dict headers: custom request headers (if isn't set default values are used)
:param ... | Links a user to a group
:param str user_id: identified user's ID
:param str group_id: group ID
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send the request (if isn't set default value is used)
:return: Resp... | Below is the the instruction that describes the task:
### Input:
Links a user to a group
:param str user_id: identified user's ID
:param str group_id: group ID
:param dict headers: custom request headers (if isn't set default values are used)
:param str endpoint_url: where to send t... |
def get_scaled_cutout_basic(self, x1, y1, x2, y2, scale_x, scale_y,
method='basic'):
"""Extract a region of the image defined by corners (x1, y1) and
(x2, y2) and scale it by scale factors (scale_x, scale_y).
`method` describes the method of interpolation used, w... | Extract a region of the image defined by corners (x1, y1) and
(x2, y2) and scale it by scale factors (scale_x, scale_y).
`method` describes the method of interpolation used, where the
default "basic" is nearest neighbor. | Below is the the instruction that describes the task:
### Input:
Extract a region of the image defined by corners (x1, y1) and
(x2, y2) and scale it by scale factors (scale_x, scale_y).
`method` describes the method of interpolation used, where the
default "basic" is nearest neighbor.
### R... |
def dispatch(self, req):
"""
Called by the Routes middleware to dispatch the request to the
appropriate controller. If a webob exception is raised, it is
returned; if some other exception is raised, the webob
`HTTPInternalServerError` exception is raised. Otherwise, the
... | Called by the Routes middleware to dispatch the request to the
appropriate controller. If a webob exception is raised, it is
returned; if some other exception is raised, the webob
`HTTPInternalServerError` exception is raised. Otherwise, the
return value of the controller is returned. | Below is the the instruction that describes the task:
### Input:
Called by the Routes middleware to dispatch the request to the
appropriate controller. If a webob exception is raised, it is
returned; if some other exception is raised, the webob
`HTTPInternalServerError` exception is raised.... |
def morphChunkedDataLists(fromDataList, toDataList, stepList):
'''
Morph one set of data into another, in a stepwise fashion
A convenience function. Given a set of paired data lists,
this will morph each one individually.
Returns a single list with all data combined together.
'''
assert(... | Morph one set of data into another, in a stepwise fashion
A convenience function. Given a set of paired data lists,
this will morph each one individually.
Returns a single list with all data combined together. | Below is the the instruction that describes the task:
### Input:
Morph one set of data into another, in a stepwise fashion
A convenience function. Given a set of paired data lists,
this will morph each one individually.
Returns a single list with all data combined together.
### Response:
def morphCh... |
def within_bbox(self, bbox):
"""
:param bbox:
a quartet (min_lon, min_lat, max_lon, max_lat)
:returns:
site IDs within the bounding box
"""
min_lon, min_lat, max_lon, max_lat = bbox
lons, lats = self.array['lon'], self.array['lat']
if cross... | :param bbox:
a quartet (min_lon, min_lat, max_lon, max_lat)
:returns:
site IDs within the bounding box | Below is the the instruction that describes the task:
### Input:
:param bbox:
a quartet (min_lon, min_lat, max_lon, max_lat)
:returns:
site IDs within the bounding box
### Response:
def within_bbox(self, bbox):
"""
:param bbox:
a quartet (min_lon, min_lat... |
def initial_populate(self, data):
"""
Populate a newly created config object with data.
If it was populated, this returns True. If it wasn't, this returns False.
It is recommended to run a .dump() and .reload() after running this.
"""
if self.config.parsed:
... | Populate a newly created config object with data.
If it was populated, this returns True. If it wasn't, this returns False.
It is recommended to run a .dump() and .reload() after running this. | Below is the the instruction that describes the task:
### Input:
Populate a newly created config object with data.
If it was populated, this returns True. If it wasn't, this returns False.
It is recommended to run a .dump() and .reload() after running this.
### Response:
def initial_populate(self... |
def unit(x1, x2, block_num, depth, num_layers, dim='2d',
bottleneck=True, first_batch_norm=True, stride=1, training=True):
"""Implements bottleneck RevNet unit from authors' RevNet architecture.
Args:
x1: [N, H, W, C] tensor of network activations.
x2: [N, H, W, C] tensor of network activations.
... | Implements bottleneck RevNet unit from authors' RevNet architecture.
Args:
x1: [N, H, W, C] tensor of network activations.
x2: [N, H, W, C] tensor of network activations.
block_num: integer ID of block
depth: First depth in bottleneck residual unit.
num_layers: Number of layers in the RevNet bloc... | Below is the the instruction that describes the task:
### Input:
Implements bottleneck RevNet unit from authors' RevNet architecture.
Args:
x1: [N, H, W, C] tensor of network activations.
x2: [N, H, W, C] tensor of network activations.
block_num: integer ID of block
depth: First depth in bottlene... |
def time_bin_magseries(times, mags,
binsize=540.0,
minbinelems=7):
'''Bins the given mag/flux time-series in time using the bin size given.
Parameters
----------
times,mags : np.array
The magnitude/flux time-series to bin in time. Non-finite elemen... | Bins the given mag/flux time-series in time using the bin size given.
Parameters
----------
times,mags : np.array
The magnitude/flux time-series to bin in time. Non-finite elements will
be removed from these arrays. At least 10 elements in each array are
required for this function ... | Below is the the instruction that describes the task:
### Input:
Bins the given mag/flux time-series in time using the bin size given.
Parameters
----------
times,mags : np.array
The magnitude/flux time-series to bin in time. Non-finite elements will
be removed from these arrays. At le... |
def createTempFile(self, suffix=None, prefix=None, secure=True) -> 'File':
""" Create File
Creates a new file within the directory with a temporary file like name.
@return: Created file.
"""
if not secure:
raise NotImplementedError("We only support secure files at t... | Create File
Creates a new file within the directory with a temporary file like name.
@return: Created file. | Below is the the instruction that describes the task:
### Input:
Create File
Creates a new file within the directory with a temporary file like name.
@return: Created file.
### Response:
def createTempFile(self, suffix=None, prefix=None, secure=True) -> 'File':
""" Create File
Cr... |
def layer_permutation(self, layer_partition, layout, qubit_subset):
"""Find a swap circuit that implements a permutation for this layer.
The goal is to swap qubits such that qubits in the same two-qubit gates
are adjacent.
Based on Sergey Bravyi's algorithm.
The layer_partitio... | Find a swap circuit that implements a permutation for this layer.
The goal is to swap qubits such that qubits in the same two-qubit gates
are adjacent.
Based on Sergey Bravyi's algorithm.
The layer_partition is a list of (qu)bit lists and each qubit is a
tuple (qreg, index).
... | Below is the the instruction that describes the task:
### Input:
Find a swap circuit that implements a permutation for this layer.
The goal is to swap qubits such that qubits in the same two-qubit gates
are adjacent.
Based on Sergey Bravyi's algorithm.
The layer_partition is a lis... |
def round(self, ndigits=0):
"""
Rounds the amount using the current ``Decimal`` rounding algorithm.
"""
if ndigits is None:
ndigits = 0
return self.__class__(
amount=self.amount.quantize(Decimal('1e' + str(-ndigits))),
currency=self.currency) | Rounds the amount using the current ``Decimal`` rounding algorithm. | Below is the the instruction that describes the task:
### Input:
Rounds the amount using the current ``Decimal`` rounding algorithm.
### Response:
def round(self, ndigits=0):
"""
Rounds the amount using the current ``Decimal`` rounding algorithm.
"""
if ndigits is None:
... |
def load_map_info(self, map_file):
"""
Load map projection information and create latitude, longitude, x, y, i, and j grids for the projection.
Args:
map_file: File specifying the projection information.
"""
if self.ensemble_name.upper() == "SSEF":
proj_d... | Load map projection information and create latitude, longitude, x, y, i, and j grids for the projection.
Args:
map_file: File specifying the projection information. | Below is the the instruction that describes the task:
### Input:
Load map projection information and create latitude, longitude, x, y, i, and j grids for the projection.
Args:
map_file: File specifying the projection information.
### Response:
def load_map_info(self, map_file):
"""
... |
def lock(self):
"""
Lock the config database.
Use if Locking/Unlocking is not performaed automatically by lock=False
"""
if not self.locked:
rpc_command = '<Lock/>'
try:
self._execute_rpc(rpc_command)
except XMLCLIError:
... | Lock the config database.
Use if Locking/Unlocking is not performaed automatically by lock=False | Below is the the instruction that describes the task:
### Input:
Lock the config database.
Use if Locking/Unlocking is not performaed automatically by lock=False
### Response:
def lock(self):
"""
Lock the config database.
Use if Locking/Unlocking is not performaed automatically by... |
def add(self, variant, arch, nevra, path, sigkey, category, srpm_nevra=None):
"""
Map RPM to to variant and arch.
:param variant: compose variant UID
:type variant: str
:param arch: compose architecture
:type arch: str
:param nevra: name-epoch:version-r... | Map RPM to to variant and arch.
:param variant: compose variant UID
:type variant: str
:param arch: compose architecture
:type arch: str
:param nevra: name-epoch:version-release.arch
:type nevra: str
:param sigkey: sigkey hash
:type sigkey:... | Below is the the instruction that describes the task:
### Input:
Map RPM to to variant and arch.
:param variant: compose variant UID
:type variant: str
:param arch: compose architecture
:type arch: str
:param nevra: name-epoch:version-release.arch
:type ne... |
def replace_relative_url_to_absolute(self, content):
"""Replace '../' leaded url with absolute uri.
"""
p = os.path.join(os.getcwd(), './src', '../')
return content.replace('../', p) | Replace '../' leaded url with absolute uri. | Below is the the instruction that describes the task:
### Input:
Replace '../' leaded url with absolute uri.
### Response:
def replace_relative_url_to_absolute(self, content):
"""Replace '../' leaded url with absolute uri.
"""
p = os.path.join(os.getcwd(), './src', '../')
return co... |
def vel_critical(self):
"""The average vertical velocity of the water inside the LFOM pipe
at the very bottom of the bottom row of orifices The speed of
falling water is 0.841 m/s for all linear flow orifice meters of
height 20 cm, independent of total plant flow rate. """
return... | The average vertical velocity of the water inside the LFOM pipe
at the very bottom of the bottom row of orifices The speed of
falling water is 0.841 m/s for all linear flow orifice meters of
height 20 cm, independent of total plant flow rate. | Below is the the instruction that describes the task:
### Input:
The average vertical velocity of the water inside the LFOM pipe
at the very bottom of the bottom row of orifices The speed of
falling water is 0.841 m/s for all linear flow orifice meters of
height 20 cm, independent of total p... |
def clone(self, forced_version_date=None, in_bulk=False):
"""
Clones a Versionable and returns a fresh copy of the original object.
Original source: ClonableMixin snippet
(http://djangosnippets.org/snippets/1271), with the pk/id change
suggested in the comments
:param fo... | Clones a Versionable and returns a fresh copy of the original object.
Original source: ClonableMixin snippet
(http://djangosnippets.org/snippets/1271), with the pk/id change
suggested in the comments
:param forced_version_date: a timestamp including tzinfo; this value
is usu... | Below is the the instruction that describes the task:
### Input:
Clones a Versionable and returns a fresh copy of the original object.
Original source: ClonableMixin snippet
(http://djangosnippets.org/snippets/1271), with the pk/id change
suggested in the comments
:param forced_vers... |
def _get_input_buffer(self, force=False):
""" The text that the user has entered entered at the current prompt.
If the console is currently executing, the text that is executing will
always be returned.
"""
# If we're executing, the input buffer may not even exist anymore due to... | The text that the user has entered entered at the current prompt.
If the console is currently executing, the text that is executing will
always be returned. | Below is the the instruction that describes the task:
### Input:
The text that the user has entered entered at the current prompt.
If the console is currently executing, the text that is executing will
always be returned.
### Response:
def _get_input_buffer(self, force=False):
""" The text... |
def urlize_twitter(text):
"""
Replace #hashtag and @username references in a tweet with HTML text.
"""
html = TwitterText(text).autolink.auto_link()
return mark_safe(html.replace(
'twitter.com/search?q=', 'twitter.com/search/realtime/')) | Replace #hashtag and @username references in a tweet with HTML text. | Below is the the instruction that describes the task:
### Input:
Replace #hashtag and @username references in a tweet with HTML text.
### Response:
def urlize_twitter(text):
"""
Replace #hashtag and @username references in a tweet with HTML text.
"""
html = TwitterText(text).autolink.auto_link()
... |
def take_reference_screenshot(webdriver, file_name):
"""
Captures a screenshot as a reference screenshot.
Args:
webdriver (WebDriver) - Selenium webdriver.
file_name (str) - File name to save screenshot as.
"""
folder_location = os.path.join(ProjectUtils.... | Captures a screenshot as a reference screenshot.
Args:
webdriver (WebDriver) - Selenium webdriver.
file_name (str) - File name to save screenshot as. | Below is the the instruction that describes the task:
### Input:
Captures a screenshot as a reference screenshot.
Args:
webdriver (WebDriver) - Selenium webdriver.
file_name (str) - File name to save screenshot as.
### Response:
def take_reference_screenshot(webdriver, file_name):
... |
def schema(self, schema):
"""sets the stream's schema. An empty schema is "{}". The schemas allow you to set a specific data type.
Both python dicts and strings are accepted."""
if isinstance(schema, basestring):
strschema = schema
schema = json.loads(schema)
els... | sets the stream's schema. An empty schema is "{}". The schemas allow you to set a specific data type.
Both python dicts and strings are accepted. | Below is the the instruction that describes the task:
### Input:
sets the stream's schema. An empty schema is "{}". The schemas allow you to set a specific data type.
Both python dicts and strings are accepted.
### Response:
def schema(self, schema):
"""sets the stream's schema. An empty schema is... |
def create_account(
self,
account_name,
registrar=None,
referrer="1.2.0",
referrer_percent=50,
owner_key=None,
active_key=None,
memo_key=None,
password=None,
additional_owner_keys=[],
additional_active_keys=[],
additional_ow... | Create new account on PeerPlays
The brainkey/password can be used to recover all generated keys
(see `peerplaysbase.account` for more details.
By default, this call will use ``default_account`` to
register a new name ``account_name`` with all keys being
deri... | Below is the the instruction that describes the task:
### Input:
Create new account on PeerPlays
The brainkey/password can be used to recover all generated keys
(see `peerplaysbase.account` for more details.
By default, this call will use ``default_account`` to
regi... |
def _read(self, cnt):
"""Read from pipe."""
# normal read is usually enough
data = self._fd.read(cnt)
if len(data) == cnt or not data:
return data
# short read, try looping
buf = [data]
cnt -= len(data)
while cnt > 0:
data = self.... | Read from pipe. | Below is the the instruction that describes the task:
### Input:
Read from pipe.
### Response:
def _read(self, cnt):
"""Read from pipe."""
# normal read is usually enough
data = self._fd.read(cnt)
if len(data) == cnt or not data:
return data
# short read, try l... |
def run(self):
"""Main loop of KIRA thread."""
while not self.stopped.isSet():
try:
# if the current state is idle, just block and wait forever
# if the current state is any other state, then a timeout of 200ms should
# be reasonable in all cas... | Main loop of KIRA thread. | Below is the the instruction that describes the task:
### Input:
Main loop of KIRA thread.
### Response:
def run(self):
"""Main loop of KIRA thread."""
while not self.stopped.isSet():
try:
# if the current state is idle, just block and wait forever
# if t... |
def get_download_link(self):
""" Get direct download link with soudcloud's redirect system. """
url = None
if not self.get("downloadable"):
try:
url = self.client.get_location(
self.client.STREAM_URL % self.get("id"))
except serror as e... | Get direct download link with soudcloud's redirect system. | Below is the the instruction that describes the task:
### Input:
Get direct download link with soudcloud's redirect system.
### Response:
def get_download_link(self):
""" Get direct download link with soudcloud's redirect system. """
url = None
if not self.get("downloadable"):
t... |
def get_response_dict(self, attrs, context, is_formset):
"""
Returns a dictionary with all the parameters necessary to render the form/formset in a template.
:param attrs: Dictionary with the helper's attributes used for rendering the form/formset
:param context: `django.templat... | Returns a dictionary with all the parameters necessary to render the form/formset in a template.
:param attrs: Dictionary with the helper's attributes used for rendering the form/formset
:param context: `django.template.Context` for the node
:param is_formset: Boolean value. If set to T... | Below is the the instruction that describes the task:
### Input:
Returns a dictionary with all the parameters necessary to render the form/formset in a template.
:param attrs: Dictionary with the helper's attributes used for rendering the form/formset
:param context: `django.template.Contex... |
def __calculate_weight(self, stimulus1, stimulus2):
"""!
@brief Calculate weight between neurons that have external stimulus1 and stimulus2.
@param[in] stimulus1 (list): External stimulus of the first neuron.
@param[in] stimulus2 (list): External stimulus of the second neur... | !
@brief Calculate weight between neurons that have external stimulus1 and stimulus2.
@param[in] stimulus1 (list): External stimulus of the first neuron.
@param[in] stimulus2 (list): External stimulus of the second neuron.
@return (double) Weight between neurons t... | Below is the the instruction that describes the task:
### Input:
!
@brief Calculate weight between neurons that have external stimulus1 and stimulus2.
@param[in] stimulus1 (list): External stimulus of the first neuron.
@param[in] stimulus2 (list): External stimulus of the second... |
def try_add_variable(self, variable_name: str, replacement: VariableReplacement) -> None:
"""Try to add the variable with its replacement to the substitution.
This considers an existing replacement and will only succeed if the new replacement
can be merged with the old replacement. Merging can ... | Try to add the variable with its replacement to the substitution.
This considers an existing replacement and will only succeed if the new replacement
can be merged with the old replacement. Merging can occur if either the two replacements
are equivalent. Replacements can also be merged if the o... | Below is the the instruction that describes the task:
### Input:
Try to add the variable with its replacement to the substitution.
This considers an existing replacement and will only succeed if the new replacement
can be merged with the old replacement. Merging can occur if either the two replacem... |
def _find_address_values_in_chain(self, base_contexts, addresses_to_find):
"""Breadth first search through the chain of contexts searching for
the bytes values at the addresses in addresses_to_find.
Args:
base_contexts (list of str): The context ids to start with.
addres... | Breadth first search through the chain of contexts searching for
the bytes values at the addresses in addresses_to_find.
Args:
base_contexts (list of str): The context ids to start with.
addresses_to_find (list of str): Addresses to find values in the
chain of co... | Below is the the instruction that describes the task:
### Input:
Breadth first search through the chain of contexts searching for
the bytes values at the addresses in addresses_to_find.
Args:
base_contexts (list of str): The context ids to start with.
addresses_to_find (list... |
def dot(self, other_tf):
"""Compose this rigid transform with another.
This transform is on the left-hand side of the composition.
Parameters
----------
other_tf : :obj:`RigidTransform`
The other RigidTransform to compose with this one.
Returns
----... | Compose this rigid transform with another.
This transform is on the left-hand side of the composition.
Parameters
----------
other_tf : :obj:`RigidTransform`
The other RigidTransform to compose with this one.
Returns
-------
:obj:`RigidTransform`
... | Below is the the instruction that describes the task:
### Input:
Compose this rigid transform with another.
This transform is on the left-hand side of the composition.
Parameters
----------
other_tf : :obj:`RigidTransform`
The other RigidTransform to compose with this o... |
def get_value(self, index, col, takeable=False):
"""
Quickly retrieve single value at passed column and index.
.. deprecated:: 0.21.0
Use .at[] or .iat[] accessors instead.
Parameters
----------
index : row label
col : column label
takeable :... | Quickly retrieve single value at passed column and index.
.. deprecated:: 0.21.0
Use .at[] or .iat[] accessors instead.
Parameters
----------
index : row label
col : column label
takeable : interpret the index/col as indexers, default False
Returns
... | Below is the the instruction that describes the task:
### Input:
Quickly retrieve single value at passed column and index.
.. deprecated:: 0.21.0
Use .at[] or .iat[] accessors instead.
Parameters
----------
index : row label
col : column label
takeable :... |
def delete(device_id):
'''
Delete a device from Server Density. For more information, see the `API
docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Deleting
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.delete 51f7eafcdba4bb235e000ae4
'''
... | Delete a device from Server Density. For more information, see the `API
docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Deleting
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.delete 51f7eafcdba4bb235e000ae4 | Below is the the instruction that describes the task:
### Input:
Delete a device from Server Density. For more information, see the `API
docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Deleting
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.delete 51f... |
def write_mesh(fname, vertices, faces, normals, texcoords, name='',
format='obj', overwrite=False, reshape_faces=True):
""" Write mesh data to file.
Parameters
----------
fname : str
Filename to write. Must end with ".obj" or ".gz".
vertices : array
Vertices.
face... | Write mesh data to file.
Parameters
----------
fname : str
Filename to write. Must end with ".obj" or ".gz".
vertices : array
Vertices.
faces : array | None
Triangle face definitions.
normals : array
Normals for the mesh.
texcoords : array | None
Text... | Below is the the instruction that describes the task:
### Input:
Write mesh data to file.
Parameters
----------
fname : str
Filename to write. Must end with ".obj" or ".gz".
vertices : array
Vertices.
faces : array | None
Triangle face definitions.
normals : array
... |
def wait_for_task(upid, timeout=300):
'''
Wait until a the task has been finished successfully
'''
start_time = time.time()
info = _lookup_proxmox_task(upid)
if not info:
log.error('wait_for_task: No task information '
'retrieved based on given criteria.')
raise... | Wait until a the task has been finished successfully | Below is the the instruction that describes the task:
### Input:
Wait until a the task has been finished successfully
### Response:
def wait_for_task(upid, timeout=300):
'''
Wait until a the task has been finished successfully
'''
start_time = time.time()
info = _lookup_proxmox_task(upid)
i... |
def _get_speed(element_duration, wpm, word_ref=WORD):
"""
Returns
element duration when element_duration and/or code speed is given
wpm
>>> _get_speed(0.2, None)
(0.2, 5.999999999999999)
>>> _get_speed(None, 15)
(0.08, 15)
>>> _get_speed(None, None)
(0.08, 15)
"""
... | Returns
element duration when element_duration and/or code speed is given
wpm
>>> _get_speed(0.2, None)
(0.2, 5.999999999999999)
>>> _get_speed(None, 15)
(0.08, 15)
>>> _get_speed(None, None)
(0.08, 15) | Below is the the instruction that describes the task:
### Input:
Returns
element duration when element_duration and/or code speed is given
wpm
>>> _get_speed(0.2, None)
(0.2, 5.999999999999999)
>>> _get_speed(None, 15)
(0.08, 15)
>>> _get_speed(None, None)
(0.08, 15)
### R... |
def gettrace(self, burn=0, thin=1, chain=-1, slicing=None):
"""Return the trace.
:Stochastics:
- burn (int): The number of transient steps to skip.
- thin (int): Keep one in thin.
- chain (int): The index of the chain to fetch. If None, return all chains.
- slici... | Return the trace.
:Stochastics:
- burn (int): The number of transient steps to skip.
- thin (int): Keep one in thin.
- chain (int): The index of the chain to fetch. If None, return all chains.
- slicing: A slice, overriding burn and thin assignement. | Below is the the instruction that describes the task:
### Input:
Return the trace.
:Stochastics:
- burn (int): The number of transient steps to skip.
- thin (int): Keep one in thin.
- chain (int): The index of the chain to fetch. If None, return all chains.
- slicing... |
def listext(self, ext, stream=sys.stdout):
"""
Print to the given `stream` a table with the list of the output files
with the given `ext` produced by the flow.
"""
nodes_files = []
for node in self.iflat_nodes():
filepath = node.outdir.has_abiext(ext)
... | Print to the given `stream` a table with the list of the output files
with the given `ext` produced by the flow. | Below is the the instruction that describes the task:
### Input:
Print to the given `stream` a table with the list of the output files
with the given `ext` produced by the flow.
### Response:
def listext(self, ext, stream=sys.stdout):
"""
Print to the given `stream` a table with the list of... |
def _copyToNewWorkingDir(newdir,input):
""" Copy input file and all related files necessary for processing to the new working directory.
This function works in a greedy manner, in that all files associated
with all inputs(have the same rootname) will be copied to the new
working directory.
... | Copy input file and all related files necessary for processing to the new working directory.
This function works in a greedy manner, in that all files associated
with all inputs(have the same rootname) will be copied to the new
working directory. | Below is the the instruction that describes the task:
### Input:
Copy input file and all related files necessary for processing to the new working directory.
This function works in a greedy manner, in that all files associated
with all inputs(have the same rootname) will be copied to the new
... |
def get_magicc_region_to_openscm_region_mapping(inverse=False):
"""Get the mappings from MAGICC to OpenSCM regions.
This is not a pure inverse of the other way around. For example, we never provide
"GLOBAL" as a MAGICC return value because it's unnecesarily confusing when we also
have "World". Fortunat... | Get the mappings from MAGICC to OpenSCM regions.
This is not a pure inverse of the other way around. For example, we never provide
"GLOBAL" as a MAGICC return value because it's unnecesarily confusing when we also
have "World". Fortunately MAGICC doesn't ever read the name "GLOBAL" so this
shouldn't ma... | Below is the the instruction that describes the task:
### Input:
Get the mappings from MAGICC to OpenSCM regions.
This is not a pure inverse of the other way around. For example, we never provide
"GLOBAL" as a MAGICC return value because it's unnecesarily confusing when we also
have "World". Fortunatel... |
def _generate_struct_class_h(self, struct):
"""Defines an Obj C header file that represents a struct in Stone."""
self._generate_init_imports_h(struct)
self._generate_imports_h(self._get_imports_h(struct))
self.emit()
self.emit('NS_ASSUME_NONNULL_BEGIN')
self.emit()
... | Defines an Obj C header file that represents a struct in Stone. | Below is the the instruction that describes the task:
### Input:
Defines an Obj C header file that represents a struct in Stone.
### Response:
def _generate_struct_class_h(self, struct):
"""Defines an Obj C header file that represents a struct in Stone."""
self._generate_init_imports_h(struct)
... |
def p_param_arg_noname_exp(self, p):
'param_arg_noname : expression'
p[0] = ParamArg(None, p[1], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | param_arg_noname : expression | Below is the the instruction that describes the task:
### Input:
param_arg_noname : expression
### Response:
def p_param_arg_noname_exp(self, p):
'param_arg_noname : expression'
p[0] = ParamArg(None, p[1], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
def create(model_config, model, source, optimizer, start_lr=1e-5, end_lr=10, iterations=100, freeze=False,
interpolation='logscale', stop_dv=True, divergence_threshold=4.0, metric='loss'):
""" Vel factory function """
return LrFindCommand(
model_config=model_config,
model=model,
... | Vel factory function | Below is the the instruction that describes the task:
### Input:
Vel factory function
### Response:
def create(model_config, model, source, optimizer, start_lr=1e-5, end_lr=10, iterations=100, freeze=False,
interpolation='logscale', stop_dv=True, divergence_threshold=4.0, metric='loss'):
""" Vel fac... |
def loadtoc(self):
"""Load the table of contents into memory."""
self.toc = self.TOCTMPLT()
self.lib.seek(self.pkgstart+self.tocpos)
tocstr = self.lib.read(self.toclen)
self.toc.frombinary(tocstr) | Load the table of contents into memory. | Below is the the instruction that describes the task:
### Input:
Load the table of contents into memory.
### Response:
def loadtoc(self):
"""Load the table of contents into memory."""
self.toc = self.TOCTMPLT()
self.lib.seek(self.pkgstart+self.tocpos)
tocstr = self.lib.read(self.toc... |
def output(id, url):
"""
View the files from a job.
"""
try:
experiment = ExperimentClient().get(normalize_job_name(id))
except FloydException:
experiment = ExperimentClient().get(id)
output_dir_url = "%s/%s/files" % (floyd.floyd_web_host, experiment.name)
if url:
fl... | View the files from a job. | Below is the the instruction that describes the task:
### Input:
View the files from a job.
### Response:
def output(id, url):
"""
View the files from a job.
"""
try:
experiment = ExperimentClient().get(normalize_job_name(id))
except FloydException:
experiment = ExperimentClient... |
def get_annotation_urls_and_checksums(species, release=None, ftp=None):
"""Get FTP URLs and checksums for Ensembl genome annotations.
Parameters
----------
species : str or list of str
The species or list of species for which to get genome annotations
(e.g., "Homo_sapiens").
rel... | Get FTP URLs and checksums for Ensembl genome annotations.
Parameters
----------
species : str or list of str
The species or list of species for which to get genome annotations
(e.g., "Homo_sapiens").
release : int, optional
The release number to look up. If `None`, use late... | Below is the the instruction that describes the task:
### Input:
Get FTP URLs and checksums for Ensembl genome annotations.
Parameters
----------
species : str or list of str
The species or list of species for which to get genome annotations
(e.g., "Homo_sapiens").
release : int... |
def devno_free_if_allocated(self, devno):
"""
Free a device number allocated with :meth:`devno_alloc`.
If the device number is not currently allocated or not in the pool
range, nothing happens.
Parameters:
devno (string): The device number as four hexadecimal digits.
... | Free a device number allocated with :meth:`devno_alloc`.
If the device number is not currently allocated or not in the pool
range, nothing happens.
Parameters:
devno (string): The device number as four hexadecimal digits. | Below is the the instruction that describes the task:
### Input:
Free a device number allocated with :meth:`devno_alloc`.
If the device number is not currently allocated or not in the pool
range, nothing happens.
Parameters:
devno (string): The device number as four hexadecimal d... |
def delete(self, instance, acl):
"""Delete an ACL by ID belonging to the instance specified by name.
:param str instance: The name of the instance on which the ACL exists.
:param str acll: The ID of the ACL to delete.
"""
base_url = self._url.format(instance=instance)
ur... | Delete an ACL by ID belonging to the instance specified by name.
:param str instance: The name of the instance on which the ACL exists.
:param str acll: The ID of the ACL to delete. | Below is the the instruction that describes the task:
### Input:
Delete an ACL by ID belonging to the instance specified by name.
:param str instance: The name of the instance on which the ACL exists.
:param str acll: The ID of the ACL to delete.
### Response:
def delete(self, instance, acl):
... |
def _materialize_dict(bundle: dict, separator: str = '.') -> t.Generator[t.Tuple[str, t.Any], None, None]:
"""
Traverses and transforms a given dict ``bundle`` into tuples of ``(key_path, value)``.
:param bundle: a dict to traverse
:param separator: build paths with a given separator
:return: a gen... | Traverses and transforms a given dict ``bundle`` into tuples of ``(key_path, value)``.
:param bundle: a dict to traverse
:param separator: build paths with a given separator
:return: a generator of tuples ``(materialized_path, value)``
Example:
>>> list(_materialize_dict({'test': {'path': 1}, 'key... | Below is the the instruction that describes the task:
### Input:
Traverses and transforms a given dict ``bundle`` into tuples of ``(key_path, value)``.
:param bundle: a dict to traverse
:param separator: build paths with a given separator
:return: a generator of tuples ``(materialized_path, value)``
... |
def most_common(self, n=None):
'''List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
'''
if n is None:
retu... | List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)] | Below is the the instruction that describes the task:
### Input:
List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
### Response:
def most_... |
def list(host=None, quiet=False, hyper=None): # pylint: disable=redefined-builtin
'''
List the virtual machines on each host, this is a simplified query,
showing only the virtual machine names belonging to each host.
A single host can be passed in to specify an individual host
to list.
'''
... | List the virtual machines on each host, this is a simplified query,
showing only the virtual machine names belonging to each host.
A single host can be passed in to specify an individual host
to list. | Below is the the instruction that describes the task:
### Input:
List the virtual machines on each host, this is a simplified query,
showing only the virtual machine names belonging to each host.
A single host can be passed in to specify an individual host
to list.
### Response:
def list(host=None, qui... |
def incremental(self, allow_deletion=False,
change_list_uri=None, from_datetime=None):
"""Incremental synchronization.
Use Change List to do incremental sync
"""
self.logger.debug("Starting incremental sync")
# 0. Sanity checks
if (len(self.mapper) < ... | Incremental synchronization.
Use Change List to do incremental sync | Below is the the instruction that describes the task:
### Input:
Incremental synchronization.
Use Change List to do incremental sync
### Response:
def incremental(self, allow_deletion=False,
change_list_uri=None, from_datetime=None):
"""Incremental synchronization.
Use... |
def _get_auto_rank(self, rank):
"""Tries to figure out what rank we should use for analyses"""
if rank == "auto":
# if we're an accessor for a ClassificationsDataFrame, use its _rank property
if self.__class__.__name__ == "OneCodexAccessor":
return self._rank
... | Tries to figure out what rank we should use for analyses | Below is the the instruction that describes the task:
### Input:
Tries to figure out what rank we should use for analyses
### Response:
def _get_auto_rank(self, rank):
"""Tries to figure out what rank we should use for analyses"""
if rank == "auto":
# if we're an accessor for a Classif... |
def iter(self, keyed=False, extended=False):
'''Iterate over the rows.
Each row is returned in a format that depends on the arguments `keyed`
and `extended`. By default, each row is returned as list of their
values.
Args:
keyed (bool, optional): When True, each retu... | Iterate over the rows.
Each row is returned in a format that depends on the arguments `keyed`
and `extended`. By default, each row is returned as list of their
values.
Args:
keyed (bool, optional): When True, each returned row will be a
`dict` mapping the he... | Below is the the instruction that describes the task:
### Input:
Iterate over the rows.
Each row is returned in a format that depends on the arguments `keyed`
and `extended`. By default, each row is returned as list of their
values.
Args:
keyed (bool, optional): When Tr... |
def OnAddCards(self, addedcards):
"""Called when a card is inserted.
Adds the smart card child to the reader node."""
self.mutex.acquire()
try:
parentnode = self.root
for cardtoadd in addedcards:
(childReader, cookie) = self.GetFirstChild(parentnod... | Called when a card is inserted.
Adds the smart card child to the reader node. | Below is the the instruction that describes the task:
### Input:
Called when a card is inserted.
Adds the smart card child to the reader node.
### Response:
def OnAddCards(self, addedcards):
"""Called when a card is inserted.
Adds the smart card child to the reader node."""
self.mut... |
def p_reserved_word(self, p):
"""reserved_word : BREAK
| CASE
| CATCH
| CONTINUE
| DEBUGGER
| DEFAULT
| DELETE
| DO
... | reserved_word : BREAK
| CASE
| CATCH
| CONTINUE
| DEBUGGER
| DEFAULT
| DELETE
| DO
| ELSE
| FIN... | Below is the the instruction that describes the task:
### Input:
reserved_word : BREAK
| CASE
| CATCH
| CONTINUE
| DEBUGGER
| DEFAULT
| DELETE
... |
def color_toggle(self):
"""Toggle between the currently active color scheme and NoColor."""
if self.color_scheme_table.active_scheme_name == 'NoColor':
self.color_scheme_table.set_active_scheme(self.old_scheme)
self.Colors = self.color_scheme_table.active_colors
else:
... | Toggle between the currently active color scheme and NoColor. | Below is the the instruction that describes the task:
### Input:
Toggle between the currently active color scheme and NoColor.
### Response:
def color_toggle(self):
"""Toggle between the currently active color scheme and NoColor."""
if self.color_scheme_table.active_scheme_name == 'NoColor':
... |
def find_sift(im_source, im_search, min_match_count=4):
'''
SIFT特征点匹配
'''
res = find_all_sift(im_source, im_search, min_match_count, maxcnt=1)
if not res:
return None
return res[0] | SIFT特征点匹配 | Below is the the instruction that describes the task:
### Input:
SIFT特征点匹配
### Response:
def find_sift(im_source, im_search, min_match_count=4):
'''
SIFT特征点匹配
'''
res = find_all_sift(im_source, im_search, min_match_count, maxcnt=1)
if not res:
return None
return res[0] |
def remove_directory(self, relativePath, clean=False, raiseError=True, ntrials=3):
"""
Remove directory from repository tracking.
:Parameters:
#. relativePath (string): The relative to the repository path of the
directory to remove from the repository.
#. ... | Remove directory from repository tracking.
:Parameters:
#. relativePath (string): The relative to the repository path of the
directory to remove from the repository.
#. clean (boolean): Whether to os remove directory. If False only
tracked files will be rem... | Below is the the instruction that describes the task:
### Input:
Remove directory from repository tracking.
:Parameters:
#. relativePath (string): The relative to the repository path of the
directory to remove from the repository.
#. clean (boolean): Whether to os rem... |
def sigfig_int(values, sigfig):
"""
Convert a set of floating point values into integers with a specified number
of significant figures and an exponent.
Parameters
------------
values: (n,) float or int, array of values
sigfig: (n,) int, number of significant figures to keep
Returns
... | Convert a set of floating point values into integers with a specified number
of significant figures and an exponent.
Parameters
------------
values: (n,) float or int, array of values
sigfig: (n,) int, number of significant figures to keep
Returns
------------
as_int: (n,) int, ev... | Below is the the instruction that describes the task:
### Input:
Convert a set of floating point values into integers with a specified number
of significant figures and an exponent.
Parameters
------------
values: (n,) float or int, array of values
sigfig: (n,) int, number of significant figure... |
def next_power_of_2(n):
""" Return next power of 2 greater than or equal to n """
n -= 1 # greater than OR EQUAL TO n
shift = 1
while (n + 1) & n: # n+1 is not a power of 2 yet
n |= n >> shift
shift *= 2
return max(4, n + 1) | Return next power of 2 greater than or equal to n | Below is the the instruction that describes the task:
### Input:
Return next power of 2 greater than or equal to n
### Response:
def next_power_of_2(n):
""" Return next power of 2 greater than or equal to n """
n -= 1 # greater than OR EQUAL TO n
shift = 1
while (n + 1) & n: # n+1 is not a power ... |
def image_size(self, pnmfile):
"""Get width and height of pnm file.
simeon@homebox src>pnmfile /tmp/214-2.png
/tmp/214-2.png:PPM raw, 100 by 100 maxval 255
"""
pout = os.popen(self.shellsetup + self.pnmfile + ' ' + pnmfile, 'r')
pnmfileout = pout.read(200)
pout.... | Get width and height of pnm file.
simeon@homebox src>pnmfile /tmp/214-2.png
/tmp/214-2.png:PPM raw, 100 by 100 maxval 255 | Below is the the instruction that describes the task:
### Input:
Get width and height of pnm file.
simeon@homebox src>pnmfile /tmp/214-2.png
/tmp/214-2.png:PPM raw, 100 by 100 maxval 255
### Response:
def image_size(self, pnmfile):
"""Get width and height of pnm file.
simeon@home... |
def get_marginal_distribution(self, index_points=None):
"""Compute the marginal of this GP over function values at `index_points`.
Args:
index_points: `float` `Tensor` representing finite (batch of) vector(s) of
points in the index set over which the GP is defined. Shape has the form
`[b1... | Compute the marginal of this GP over function values at `index_points`.
Args:
index_points: `float` `Tensor` representing finite (batch of) vector(s) of
points in the index set over which the GP is defined. Shape has the form
`[b1, ..., bB, e, f1, ..., fF]` where `F` is the number of feature
... | Below is the the instruction that describes the task:
### Input:
Compute the marginal of this GP over function values at `index_points`.
Args:
index_points: `float` `Tensor` representing finite (batch of) vector(s) of
points in the index set over which the GP is defined. Shape has the form
... |
def _print_map_dict(self, argkey, filename, append):
"""Prints a dictionary that has variable => value mappings."""
result = []
skeys = list(sorted(self.curargs[argkey].keys()))
for key in skeys:
result.append("'{}' => {}".format(key, self.curargs[argkey][key]))
self.... | Prints a dictionary that has variable => value mappings. | Below is the the instruction that describes the task:
### Input:
Prints a dictionary that has variable => value mappings.
### Response:
def _print_map_dict(self, argkey, filename, append):
"""Prints a dictionary that has variable => value mappings."""
result = []
skeys = list(sorted(self.cu... |
def count_sign(values, min_value):
"""
>>> count_sign([3,-1,-2], 0)
(1, 2)
>>> count_sign([3,-1,-2], 2)
(1, 0)
>>> count_sign([0,-1],0)
(0, 1)
"""
positive_count = 0
negative_count = 0
for value in values:
if value > min_value:
positive_count += 1
... | >>> count_sign([3,-1,-2], 0)
(1, 2)
>>> count_sign([3,-1,-2], 2)
(1, 0)
>>> count_sign([0,-1],0)
(0, 1) | Below is the the instruction that describes the task:
### Input:
>>> count_sign([3,-1,-2], 0)
(1, 2)
>>> count_sign([3,-1,-2], 2)
(1, 0)
>>> count_sign([0,-1],0)
(0, 1)
### Response:
def count_sign(values, min_value):
"""
>>> count_sign([3,-1,-2], 0)
(1, 2)
>>> count_sign([3,-1,... |
def get_instance(self, payload):
"""
Build an instance of TaskQueueInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance
:rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance
... | Build an instance of TaskQueueInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance
:rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance | Below is the the instruction that describes the task:
### Input:
Build an instance of TaskQueueInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance
:rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQ... |
def pickAttachment(self):
"""
Prompts the user to select an attachment to add to this edit.
"""
filename = QFileDialog.getOpenFileName(self.window(),
'Select Attachment',
'',
... | Prompts the user to select an attachment to add to this edit. | Below is the the instruction that describes the task:
### Input:
Prompts the user to select an attachment to add to this edit.
### Response:
def pickAttachment(self):
"""
Prompts the user to select an attachment to add to this edit.
"""
filename = QFileDialog.getOpenFileName(sel... |
def run_attack_work(self, work_id):
"""Runs one attack work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
"""
adv_batch_id = (
s... | Runs one attack work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution. | Below is the the instruction that describes the task:
### Input:
Runs one attack work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
### Response... |
def window_design(self, window_length, beta):
"""Kaiser window design
Args:
window_length: Length of the window in number of samples
beta: Beta value for Kaiser window design
Returns:
window: Window designed using the beta and length provided as inpu... | Kaiser window design
Args:
window_length: Length of the window in number of samples
beta: Beta value for Kaiser window design
Returns:
window: Window designed using the beta and length provided as inputs | Below is the the instruction that describes the task:
### Input:
Kaiser window design
Args:
window_length: Length of the window in number of samples
beta: Beta value for Kaiser window design
Returns:
window: Window designed using the beta and length provi... |
def update_tree(root, executed_acts, total_rew):
"""
Given the tree, a list of actions that were executed before the game ended, and a reward, update the tree
so that the path formed by the executed actions are all updated to the new reward.
"""
root.value = max(total_rew, root.value)
root.visit... | Given the tree, a list of actions that were executed before the game ended, and a reward, update the tree
so that the path formed by the executed actions are all updated to the new reward. | Below is the the instruction that describes the task:
### Input:
Given the tree, a list of actions that were executed before the game ended, and a reward, update the tree
so that the path formed by the executed actions are all updated to the new reward.
### Response:
def update_tree(root, executed_acts, total_... |
def cumulative_distribution(self, X):
"""Cumulative distribution function for gaussian distribution.
Arguments:
X: `np.ndarray` of shape (n, 1).
Returns:
np.ndarray: Cumulative density for X.
"""
self.check_fit()
return norm.cdf(X, loc=self.mean,... | Cumulative distribution function for gaussian distribution.
Arguments:
X: `np.ndarray` of shape (n, 1).
Returns:
np.ndarray: Cumulative density for X. | Below is the the instruction that describes the task:
### Input:
Cumulative distribution function for gaussian distribution.
Arguments:
X: `np.ndarray` of shape (n, 1).
Returns:
np.ndarray: Cumulative density for X.
### Response:
def cumulative_distribution(self, X):
... |
def add(message, level=0, user=None, message_short=None,log_file_name='%s/pyscada_daemon.log' % settings.BASE_DIR,):
"""
add a new massage/error notice to the log
<0 - Debug
1 - Emergency
2 - Critical
3 - Errors
4 - Alerts
5 - Warnings
6 - Notification (webnotice)
7 - Information... | add a new massage/error notice to the log
<0 - Debug
1 - Emergency
2 - Critical
3 - Errors
4 - Alerts
5 - Warnings
6 - Notification (webnotice)
7 - Information (webinfo)
8 - Notification (notice)
9 - Information (info) | Below is the the instruction that describes the task:
### Input:
add a new massage/error notice to the log
<0 - Debug
1 - Emergency
2 - Critical
3 - Errors
4 - Alerts
5 - Warnings
6 - Notification (webnotice)
7 - Information (webinfo)
8 - Notification (notice)
9 - Information... |
def __get_resource_entry_data(self, bundleId, languageId, resourceKey,
fallback=False):
"""``GET /{serviceInstanceId}/v2/bundles/{bundleId}/{languageId}
/{resourceKey}``
Gets the resource entry information.
"""
url = self.__get_base_bundl... | ``GET /{serviceInstanceId}/v2/bundles/{bundleId}/{languageId}
/{resourceKey}``
Gets the resource entry information. | Below is the the instruction that describes the task:
### Input:
``GET /{serviceInstanceId}/v2/bundles/{bundleId}/{languageId}
/{resourceKey}``
Gets the resource entry information.
### Response:
def __get_resource_entry_data(self, bundleId, languageId, resourceKey,
... |
def balance(self, symbol):
""" Obtain the balance of a specific Asset. This call returns instances of
:class:`amount.Amount`.
"""
if isinstance(symbol, dict) and "symbol" in symbol:
symbol = symbol["symbol"]
balances = self.balances
for b in balances:
... | Obtain the balance of a specific Asset. This call returns instances of
:class:`amount.Amount`. | Below is the the instruction that describes the task:
### Input:
Obtain the balance of a specific Asset. This call returns instances of
:class:`amount.Amount`.
### Response:
def balance(self, symbol):
""" Obtain the balance of a specific Asset. This call returns instances of
:class:... |
def create_replication_interface(self, sp, ip_port, ip_address,
netmask=None, v6_prefix_length=None,
gateway=None, vlan_id=None):
"""
Creates a replication interface.
:param sp: `UnityStorageProcessor` object. Storage pro... | Creates a replication interface.
:param sp: `UnityStorageProcessor` object. Storage processor on which
the replication interface is running.
:param ip_port: `UnityIpPort` object. Physical port or link aggregation
on the storage processor on which the interface is running.
... | Below is the the instruction that describes the task:
### Input:
Creates a replication interface.
:param sp: `UnityStorageProcessor` object. Storage processor on which
the replication interface is running.
:param ip_port: `UnityIpPort` object. Physical port or link aggregation
... |
def enable_nvm():
'''add to ~/.bashrc: Export of $NVM env variable and load nvm command.'''
bash_snippet = '~/.bashrc_nvm'
install_file_legacy(path=bash_snippet)
prefix = flo('if [ -f {bash_snippet} ]; ')
enabler = flo('if [ -f {bash_snippet} ]; then source {bash_snippet}; fi')
if env.host == '... | add to ~/.bashrc: Export of $NVM env variable and load nvm command. | Below is the the instruction that describes the task:
### Input:
add to ~/.bashrc: Export of $NVM env variable and load nvm command.
### Response:
def enable_nvm():
'''add to ~/.bashrc: Export of $NVM env variable and load nvm command.'''
bash_snippet = '~/.bashrc_nvm'
install_file_legacy(path=bash_s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.