code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _Rforce(self, R, z, phi=0, t=0):
"""
NAME:
_Rforce
PURPOSE:
evaluate the radial force at (R,z, phi)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
rad... | NAME:
_Rforce
PURPOSE:
evaluate the radial force at (R,z, phi)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
radial force at (R,z, phi)
HISTORY:
2016-... | Below is the the instruction that describes the task:
### Input:
NAME:
_Rforce
PURPOSE:
evaluate the radial force at (R,z, phi)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... |
def get_week_URL(date, day=0):
"""
Returns the week view URL for a given date.
:param date: A date instance.
:param day: Day number in a month.
"""
if day < 1:
day = 1
date = datetime(year=date.year, month=date.month, day=day, tzinfo=utc)
return reverse('calendar_week', kwargs=... | Returns the week view URL for a given date.
:param date: A date instance.
:param day: Day number in a month. | Below is the the instruction that describes the task:
### Input:
Returns the week view URL for a given date.
:param date: A date instance.
:param day: Day number in a month.
### Response:
def get_week_URL(date, day=0):
"""
Returns the week view URL for a given date.
:param date: A date instan... |
def create_photo(self, blogname, **kwargs):
"""
Create a photo post or photoset on a blog
:param blogname: a string, the url of the blog you want to post to.
:param state: a string, The state of the post.
:param tags: a list of tags that you want applied to the post
:par... | Create a photo post or photoset on a blog
:param blogname: a string, the url of the blog you want to post to.
:param state: a string, The state of the post.
:param tags: a list of tags that you want applied to the post
:param tweet: a string, the customized tweet that you want
:... | Below is the the instruction that describes the task:
### Input:
Create a photo post or photoset on a blog
:param blogname: a string, the url of the blog you want to post to.
:param state: a string, The state of the post.
:param tags: a list of tags that you want applied to the post
... |
def get_account_details(self, account):
"""
This method can be used in a number of scenarios:
1. When it is necessary to very account information
2. When there's a need to filter transactions by an account id
3. When account details (e.g. name of account) are needed
"""
... | This method can be used in a number of scenarios:
1. When it is necessary to very account information
2. When there's a need to filter transactions by an account id
3. When account details (e.g. name of account) are needed | Below is the the instruction that describes the task:
### Input:
This method can be used in a number of scenarios:
1. When it is necessary to very account information
2. When there's a need to filter transactions by an account id
3. When account details (e.g. name of account) are needed
### ... |
def constant_jump_targets(self):
"""
A set of the static jump targets of the basic block.
"""
exits = set()
if self.exit_statements:
for _, _, stmt_ in self.exit_statements:
exits.add(stmt_.dst.value)
default_target = self.default_exit_target... | A set of the static jump targets of the basic block. | Below is the the instruction that describes the task:
### Input:
A set of the static jump targets of the basic block.
### Response:
def constant_jump_targets(self):
"""
A set of the static jump targets of the basic block.
"""
exits = set()
if self.exit_statements:
... |
def bilinear_interpolation_weights(self, lon, lat):
"""
Get the four neighbours for each (lon, lat) position and the weight
associated with each one for bilinear interpolation.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude an... | Get the four neighbours for each (lon, lat) position and the weight
associated with each one for bilinear interpolation.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as
:class:`~astropy.units.Quantity` instan... | Below is the the instruction that describes the task:
### Input:
Get the four neighbours for each (lon, lat) position and the weight
associated with each one for bilinear interpolation.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and l... |
def sibling(self, offs=1):
'''
Return sibling node by relative offset from self.
'''
indx = self.pindex + offs
if indx < 0:
return None
if indx >= len(self.parent.kids):
return None
return self.parent.kids[indx] | Return sibling node by relative offset from self. | Below is the the instruction that describes the task:
### Input:
Return sibling node by relative offset from self.
### Response:
def sibling(self, offs=1):
'''
Return sibling node by relative offset from self.
'''
indx = self.pindex + offs
if indx < 0:
return No... |
def update_pypsa_storage(pypsa, storages, storages_lines):
"""
Adds storages and their lines to pypsa representation of the edisgo graph.
This function effects the following attributes of the pypsa network:
components ('StorageUnit'), storage_units, storage_units_t (p_set, q_set),
buses, lines
... | Adds storages and their lines to pypsa representation of the edisgo graph.
This function effects the following attributes of the pypsa network:
components ('StorageUnit'), storage_units, storage_units_t (p_set, q_set),
buses, lines
Parameters
-----------
pypsa : :pypsa:`pypsa.Network<network>`... | Below is the the instruction that describes the task:
### Input:
Adds storages and their lines to pypsa representation of the edisgo graph.
This function effects the following attributes of the pypsa network:
components ('StorageUnit'), storage_units, storage_units_t (p_set, q_set),
buses, lines
P... |
def syslog(logger_to_update=logger, facility=SysLogHandler.LOG_USER, disableStderrLogger=True):
"""
Setup logging to syslog and disable other internal loggers
:param logger_to_update: the logger to enable syslog logging for
:param facility: syslog facility to log to
:param disableStderrLogger: shoul... | Setup logging to syslog and disable other internal loggers
:param logger_to_update: the logger to enable syslog logging for
:param facility: syslog facility to log to
:param disableStderrLogger: should the default stderr logger be disabled? defaults to True
:return the new SysLogHandler, which can be mo... | Below is the the instruction that describes the task:
### Input:
Setup logging to syslog and disable other internal loggers
:param logger_to_update: the logger to enable syslog logging for
:param facility: syslog facility to log to
:param disableStderrLogger: should the default stderr logger be disabled... |
def _is_builtin(obj):
"""
Checks if the type of the given object is a built-in one or not
:param obj: An object
:return: True if the object is of a built-in type
"""
module_ = inspect.getmodule(obj)
if module_ in (None, builtins):
return True
return module_.__name__ in ("", "__... | Checks if the type of the given object is a built-in one or not
:param obj: An object
:return: True if the object is of a built-in type | Below is the the instruction that describes the task:
### Input:
Checks if the type of the given object is a built-in one or not
:param obj: An object
:return: True if the object is of a built-in type
### Response:
def _is_builtin(obj):
"""
Checks if the type of the given object is a built-in one ... |
def comic_archive_uncompress(filename, image_format):
"""
Uncompress comic archives.
Return the name of the working directory we uncompressed into.
"""
if not Settings.comics:
report = ['Skipping archive file: {}'.format(filename)]
return None, ReportStats(filename, report=report)
... | Uncompress comic archives.
Return the name of the working directory we uncompressed into. | Below is the the instruction that describes the task:
### Input:
Uncompress comic archives.
Return the name of the working directory we uncompressed into.
### Response:
def comic_archive_uncompress(filename, image_format):
"""
Uncompress comic archives.
Return the name of the working directory we... |
def scope_in(ctx):
"""
- build new scope on the top of stack
- and current scope will wait for it result
:param ctx:
:return:
"""
logger.debug('# scope_in')
logger.debug(ctx)
ctx = ctx.clone()
compiled_story = None
if not ctx.is_empty_stack():
compiled_story = ctx.g... | - build new scope on the top of stack
- and current scope will wait for it result
:param ctx:
:return: | Below is the the instruction that describes the task:
### Input:
- build new scope on the top of stack
- and current scope will wait for it result
:param ctx:
:return:
### Response:
def scope_in(ctx):
"""
- build new scope on the top of stack
- and current scope will wait for it result
... |
def timing(self, stats, value):
"""
Log timing information
>>> client = StatsdClient()
>>> client.timing('example.timing', 500)
>>> client.timing(('example.timing23', 'example.timing29'), 500)
"""
self.update_stats(stats, value, self.SC_TIMING) | Log timing information
>>> client = StatsdClient()
>>> client.timing('example.timing', 500)
>>> client.timing(('example.timing23', 'example.timing29'), 500) | Below is the the instruction that describes the task:
### Input:
Log timing information
>>> client = StatsdClient()
>>> client.timing('example.timing', 500)
>>> client.timing(('example.timing23', 'example.timing29'), 500)
### Response:
def timing(self, stats, value):
"""
Lo... |
def _parse_triggered_hits(self, file_obj):
"""Parse and store triggered hits."""
for _ in range(self.n_triggered_hits):
dom_id, pmt_id = unpack('<ib', file_obj.read(5))
tdc_time = unpack('>I', file_obj.read(4))[0]
tot = unpack('<b', file_obj.read(1))[0]
tr... | Parse and store triggered hits. | Below is the the instruction that describes the task:
### Input:
Parse and store triggered hits.
### Response:
def _parse_triggered_hits(self, file_obj):
"""Parse and store triggered hits."""
for _ in range(self.n_triggered_hits):
dom_id, pmt_id = unpack('<ib', file_obj.read(5))
... |
def get_sql_update_by_first_field(table: str,
fieldlist: Sequence[str],
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns SQL for an UPDATE statement, to update all fields except the
first field (PK) using the PK as the key."""
return ... | Returns SQL for an UPDATE statement, to update all fields except the
first field (PK) using the PK as the key. | Below is the the instruction that describes the task:
### Input:
Returns SQL for an UPDATE statement, to update all fields except the
first field (PK) using the PK as the key.
### Response:
def get_sql_update_by_first_field(table: str,
fieldlist: Sequence[str],
... |
def fix_lib64(lib_dir, symlink=True):
"""
Some platforms (particularly Gentoo on x64) put things in lib64/pythonX.Y
instead of lib/pythonX.Y. If this is such a platform we'll just create a
symlink so lib64 points to lib
"""
# PyPy's library path scheme is not affected by this.
# Return earl... | Some platforms (particularly Gentoo on x64) put things in lib64/pythonX.Y
instead of lib/pythonX.Y. If this is such a platform we'll just create a
symlink so lib64 points to lib | Below is the the instruction that describes the task:
### Input:
Some platforms (particularly Gentoo on x64) put things in lib64/pythonX.Y
instead of lib/pythonX.Y. If this is such a platform we'll just create a
symlink so lib64 points to lib
### Response:
def fix_lib64(lib_dir, symlink=True):
"""
... |
def encode(data, scheme=None, size=None):
"""
Encodes `data` in a DataMatrix image.
For now bpp is the libdmtx default which is 24
Args:
data: bytes instance
scheme: encoding scheme - one of `ENCODING_SCHEME_NAMES`, or `None`.
If `None`, defaults to 'Ascii'.
size: i... | Encodes `data` in a DataMatrix image.
For now bpp is the libdmtx default which is 24
Args:
data: bytes instance
scheme: encoding scheme - one of `ENCODING_SCHEME_NAMES`, or `None`.
If `None`, defaults to 'Ascii'.
size: image dimensions - one of `ENCODING_SIZE_NAMES`, or `No... | Below is the the instruction that describes the task:
### Input:
Encodes `data` in a DataMatrix image.
For now bpp is the libdmtx default which is 24
Args:
data: bytes instance
scheme: encoding scheme - one of `ENCODING_SCHEME_NAMES`, or `None`.
If `None`, defaults to 'Ascii'.
... |
def alias(col, mapping):
""" Returns a collection of dictionaries with the keys renamed according to
the mapping
>>> libraries = [{"isbn": 1, "ed": 1}, {"isbn": 2, "ed": 2}]
>>> alias(libraries, {"ed": "edition"})
[{'edition': 1, 'isbn': 1}, {'edition': 2, 'isbn': 2}]
>>> a... | Returns a collection of dictionaries with the keys renamed according to
the mapping
>>> libraries = [{"isbn": 1, "ed": 1}, {"isbn": 2, "ed": 2}]
>>> alias(libraries, {"ed": "edition"})
[{'edition': 1, 'isbn': 1}, {'edition': 2, 'isbn': 2}]
>>> alias({"a": 1}, {"a": "b"})
... | Below is the the instruction that describes the task:
### Input:
Returns a collection of dictionaries with the keys renamed according to
the mapping
>>> libraries = [{"isbn": 1, "ed": 1}, {"isbn": 2, "ed": 2}]
>>> alias(libraries, {"ed": "edition"})
[{'edition': 1, 'isbn': 1}, {'edi... |
def dump(database, output, min_occurences=1, max_occurences=250, returncmd=False):
"""
Dumps output from kmc database into tab-delimited format.
:param database: Database generated by kmc.
:param output: Name for output.
:param min_occurences: Minimum number of times kmer must be in database to be d... | Dumps output from kmc database into tab-delimited format.
:param database: Database generated by kmc.
:param output: Name for output.
:param min_occurences: Minimum number of times kmer must be in database to be dumped.
:param max_occurences: Maximum number of times a kmer can be seen and still be dumpe... | Below is the the instruction that describes the task:
### Input:
Dumps output from kmc database into tab-delimited format.
:param database: Database generated by kmc.
:param output: Name for output.
:param min_occurences: Minimum number of times kmer must be in database to be dumped.
:param max_occu... |
def is_valid_sound(sound, ts):
"""Check the consistency of a given transcription system conversino"""
if isinstance(sound, (Marker, UnknownSound)):
return False
s1 = ts[sound.name]
s2 = ts[sound.s]
return s1.name == s2.name and s1.s == s2.s | Check the consistency of a given transcription system conversino | Below is the the instruction that describes the task:
### Input:
Check the consistency of a given transcription system conversino
### Response:
def is_valid_sound(sound, ts):
"""Check the consistency of a given transcription system conversino"""
if isinstance(sound, (Marker, UnknownSound)):
return ... |
def warm_up_cache(self):
"""Warms up the cache for the slice or table.
Note for slices a force refresh occurs.
"""
slices = None
session = db.session()
slice_id = request.args.get('slice_id')
table_name = request.args.get('table_name')
db_name = request.a... | Warms up the cache for the slice or table.
Note for slices a force refresh occurs. | Below is the the instruction that describes the task:
### Input:
Warms up the cache for the slice or table.
Note for slices a force refresh occurs.
### Response:
def warm_up_cache(self):
"""Warms up the cache for the slice or table.
Note for slices a force refresh occurs.
"""
... |
def write_config(self, cfg, slot=1):
""" Write a configuration to the YubiKey. """
cfg_req_ver = cfg.version_required()
if cfg_req_ver > self.version_num():
raise yubikey_base.YubiKeyVersionError('Configuration requires YubiKey version %i.%i (this is %s)' % \
... | Write a configuration to the YubiKey. | Below is the the instruction that describes the task:
### Input:
Write a configuration to the YubiKey.
### Response:
def write_config(self, cfg, slot=1):
""" Write a configuration to the YubiKey. """
cfg_req_ver = cfg.version_required()
if cfg_req_ver > self.version_num():
raise... |
def submit_job(job_ini, username, hazard_job_id=None):
"""
Create a job object from the given job.ini file in the job directory
and run it in a new process. Returns the job ID and PID.
"""
job_id = logs.init('job')
oq = engine.job_from_file(
job_ini, job_id, username, hazard_calculation_... | Create a job object from the given job.ini file in the job directory
and run it in a new process. Returns the job ID and PID. | Below is the the instruction that describes the task:
### Input:
Create a job object from the given job.ini file in the job directory
and run it in a new process. Returns the job ID and PID.
### Response:
def submit_job(job_ini, username, hazard_job_id=None):
"""
Create a job object from the given job.... |
def result(self):
"""
The result from realising the future
If the result is not available, block until done.
:return: result of the future
:raises: any exception encountered during realising the future
"""
if self._result is None:
self.await_result()... | The result from realising the future
If the result is not available, block until done.
:return: result of the future
:raises: any exception encountered during realising the future | Below is the the instruction that describes the task:
### Input:
The result from realising the future
If the result is not available, block until done.
:return: result of the future
:raises: any exception encountered during realising the future
### Response:
def result(self):
"""
... |
def get_calculated_display_values(self, immediate: bool=False) -> DisplayValues:
"""Return the display values.
Return the current (possibly uncalculated) display values unless 'immediate' is specified.
If 'immediate', return the existing (calculated) values if they exist. Using the 'immediate'... | Return the display values.
Return the current (possibly uncalculated) display values unless 'immediate' is specified.
If 'immediate', return the existing (calculated) values if they exist. Using the 'immediate' values
avoids calculation except in cases where the display values haven't already ... | Below is the the instruction that describes the task:
### Input:
Return the display values.
Return the current (possibly uncalculated) display values unless 'immediate' is specified.
If 'immediate', return the existing (calculated) values if they exist. Using the 'immediate' values
avoids ... |
def calculate_imf_steadiness(inst, steady_window=15, min_window_frac=0.75,
max_clock_angle_std=90.0/np.pi, max_bmag_cv=0.5):
""" Calculate IMF steadiness using clock angle standard deviation and
the coefficient of variation of the IMF magnitude in the GSM Y-Z plane
Parameters
... | Calculate IMF steadiness using clock angle standard deviation and
the coefficient of variation of the IMF magnitude in the GSM Y-Z plane
Parameters
-----------
inst : pysat.Instrument
Instrument with OMNI HRO data
steady_window : int
Window for calculating running statistical moment... | Below is the the instruction that describes the task:
### Input:
Calculate IMF steadiness using clock angle standard deviation and
the coefficient of variation of the IMF magnitude in the GSM Y-Z plane
Parameters
-----------
inst : pysat.Instrument
Instrument with OMNI HRO data
steady_w... |
def do(ruby, command, runas=None, cwd=None, env=None): # pylint: disable=C0103
'''
Execute a command in an RVM controlled environment.
ruby
Which ruby to use
command
The rvm command to execute
runas
The user under which to run rvm. If not specified, then rvm will be run
... | Execute a command in an RVM controlled environment.
ruby
Which ruby to use
command
The rvm command to execute
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
cwd
The directory from which to... | Below is the the instruction that describes the task:
### Input:
Execute a command in an RVM controlled environment.
ruby
Which ruby to use
command
The rvm command to execute
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user unde... |
def compute_duration_measures(self):
""" Helper function for computing measures derived from timing information.
These are only computed if the response is textgrid with timing information.
All times are in seconds.
"""
prefix = "TIMING_" + self.current_similarity_measure + "_... | Helper function for computing measures derived from timing information.
These are only computed if the response is textgrid with timing information.
All times are in seconds. | Below is the the instruction that describes the task:
### Input:
Helper function for computing measures derived from timing information.
These are only computed if the response is textgrid with timing information.
All times are in seconds.
### Response:
def compute_duration_measures(self):
... |
def normalize_path():
"""
Normalizes sys.path to avoid the use of relative folders
"""
# Normalize Python paths
whole_path = [
os.path.abspath(path) for path in sys.path if os.path.exists(path)
]
# Keep the "dynamic" current folder indicator and add the "static"
# current path
... | Normalizes sys.path to avoid the use of relative folders | Below is the the instruction that describes the task:
### Input:
Normalizes sys.path to avoid the use of relative folders
### Response:
def normalize_path():
"""
Normalizes sys.path to avoid the use of relative folders
"""
# Normalize Python paths
whole_path = [
os.path.abspath(path) fo... |
def Lehrer(m, Dtank, Djacket, H, Dinlet, rho, Cp, k, mu, muw=None,
isobaric_expansion=None, dT=None, inlettype='tangential',
inletlocation='auto'):
r'''Calculates average heat transfer coefficient for a jacket around a
vessel according to [1]_ as described in [2]_.
.. math::
N... | r'''Calculates average heat transfer coefficient for a jacket around a
vessel according to [1]_ as described in [2]_.
.. math::
Nu_{S,L} = \left[\frac{0.03Re_S^{0.75}Pr}{1 + \frac{1.74(Pr-1)}
{Re_S^{0.125}}}\right]\left(\frac{\mu}{\mu_w}\right)^{0.14}
d_g = \left(\frac{8}{3}\right)^{0.... | Below is the the instruction that describes the task:
### Input:
r'''Calculates average heat transfer coefficient for a jacket around a
vessel according to [1]_ as described in [2]_.
.. math::
Nu_{S,L} = \left[\frac{0.03Re_S^{0.75}Pr}{1 + \frac{1.74(Pr-1)}
{Re_S^{0.125}}}\right]\left(\frac{... |
def define_singleton(carrier, name, cls, cls_args = {}):
"""Creates a property with the given name, but the cls will created only with the first call
Args:
carrier: an instance of the class where want to reach the cls instance
name (str): the variable name of the cls instance
cls (type)... | Creates a property with the given name, but the cls will created only with the first call
Args:
carrier: an instance of the class where want to reach the cls instance
name (str): the variable name of the cls instance
cls (type): the singleton object type
cls_args (dict): optional di... | Below is the the instruction that describes the task:
### Input:
Creates a property with the given name, but the cls will created only with the first call
Args:
carrier: an instance of the class where want to reach the cls instance
name (str): the variable name of the cls instance
cls (... |
def _spawn_fork_workers(self):
"""
通过线程启动多个worker
"""
thread = Thread(target=self._fork_workers, args=())
thread.daemon = True
thread.start() | 通过线程启动多个worker | Below is the the instruction that describes the task:
### Input:
通过线程启动多个worker
### Response:
def _spawn_fork_workers(self):
"""
通过线程启动多个worker
"""
thread = Thread(target=self._fork_workers, args=())
thread.daemon = True
thread.start() |
def ip_access_control_list_mappings(self):
"""
Access the ip_access_control_list_mappings
:returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingList
:rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAc... | Access the ip_access_control_list_mappings
:returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingList
:rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingList | Below is the the instruction that describes the task:
### Input:
Access the ip_access_control_list_mappings
:returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingList
:rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mappin... |
def create():
"""
Factory method instanciating and returning the right wrapper.
"""
# First, try to use ctypes.
if ctypes:
inotify = _CtypesLibcINotifyWrapper()
if inotify.init():
return inotify
# Second, see if C extension is compi... | Factory method instanciating and returning the right wrapper. | Below is the the instruction that describes the task:
### Input:
Factory method instanciating and returning the right wrapper.
### Response:
def create():
"""
Factory method instanciating and returning the right wrapper.
"""
# First, try to use ctypes.
if ctypes:
... |
def score(
self,
data,
metric="accuracy",
break_ties="random",
verbose=True,
print_confusion_matrix=True,
**kwargs,
):
"""Scores the predictive performance of the Classifier on all tasks
Args:
data: a Pytorch DataLoader, Dataset, o... | Scores the predictive performance of the Classifier on all tasks
Args:
data: a Pytorch DataLoader, Dataset, or tuple with Tensors (X,Y):
X: The input for the predict method
Y: An [n] or [n, 1] torch.Tensor or np.ndarray of target labels
in {1,...,... | Below is the the instruction that describes the task:
### Input:
Scores the predictive performance of the Classifier on all tasks
Args:
data: a Pytorch DataLoader, Dataset, or tuple with Tensors (X,Y):
X: The input for the predict method
Y: An [n] or [n, 1] torch... |
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the g... | Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output. | Below is the the instruction that describes the task:
### Input:
Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to c... |
def collides_axisaligned_rect(self, other):
"""Returns collision with axis aligned other rect"""
# Shift both rects so that self is centered at origin
self_shifted = RotoOriginRect(self.width, self.height, -self.angle)
s_a = self.sin_a()
c_a = self.cos_a()
center_x = ... | Returns collision with axis aligned other rect | Below is the the instruction that describes the task:
### Input:
Returns collision with axis aligned other rect
### Response:
def collides_axisaligned_rect(self, other):
"""Returns collision with axis aligned other rect"""
# Shift both rects so that self is centered at origin
self_shifted... |
def stop_service(name):
"""
Stop the service given by name.
@warn: This method requires UAC elevation in Windows Vista and above.
@see: L{get_services}, L{get_active_services},
L{start_service}, L{pause_service}, L{resume_service}
"""
with win32.OpenSCManage... | Stop the service given by name.
@warn: This method requires UAC elevation in Windows Vista and above.
@see: L{get_services}, L{get_active_services},
L{start_service}, L{pause_service}, L{resume_service} | Below is the the instruction that describes the task:
### Input:
Stop the service given by name.
@warn: This method requires UAC elevation in Windows Vista and above.
@see: L{get_services}, L{get_active_services},
L{start_service}, L{pause_service}, L{resume_service}
### Response:
def... |
def ossos_release_with_metadata():
"""
Wrap the objects from the Version Releases together with the objects instantiated from fitting their mpc lines
"""
# discoveries = ossos_release_parser()
discoveries = []
observations = ossos_discoveries()
for obj in observations:
discov = [n fo... | Wrap the objects from the Version Releases together with the objects instantiated from fitting their mpc lines | Below is the the instruction that describes the task:
### Input:
Wrap the objects from the Version Releases together with the objects instantiated from fitting their mpc lines
### Response:
def ossos_release_with_metadata():
"""
Wrap the objects from the Version Releases together with the objects instantia... |
def stop(self, bIgnoreExceptions = True):
"""
Stops debugging all processes.
If the kill on exit mode is on, debugged processes are killed when the
debugger is stopped. Otherwise when the debugger stops it detaches from
all debugged processes and leaves them running (default). F... | Stops debugging all processes.
If the kill on exit mode is on, debugged processes are killed when the
debugger is stopped. Otherwise when the debugger stops it detaches from
all debugged processes and leaves them running (default). For more
details see: L{__init__}
@note: This ... | Below is the the instruction that describes the task:
### Input:
Stops debugging all processes.
If the kill on exit mode is on, debugged processes are killed when the
debugger is stopped. Otherwise when the debugger stops it detaches from
all debugged processes and leaves them running (defa... |
def _parseBoundImportDirectory(self, rva, size, magic = consts.PE32):
"""
Parses the bound import directory.
@type rva: int
@param rva: The RVA where the bound import directory starts.
@type size: int
@param size: The size of the bound import directory.... | Parses the bound import directory.
@type rva: int
@param rva: The RVA where the bound import directory starts.
@type size: int
@param size: The size of the bound import directory.
@type magic: int
@param magic: (Optional) The type of PE. This v... | Below is the the instruction that describes the task:
### Input:
Parses the bound import directory.
@type rva: int
@param rva: The RVA where the bound import directory starts.
@type size: int
@param size: The size of the bound import directory.
@ty... |
def reflect_ghost(self, p0):
"""This method creates the ghost point p0', namely p0 reflected along the edge
p1--p2, and the point q at the perpendicular intersection of the reflection.
p0
_/| \\__
_/ | \\__
/ | \\
p1----|q-----... | This method creates the ghost point p0', namely p0 reflected along the edge
p1--p2, and the point q at the perpendicular intersection of the reflection.
p0
_/| \\__
_/ | \\__
/ | \\
p1----|q-------p2
\\_ | __/
... | Below is the the instruction that describes the task:
### Input:
This method creates the ghost point p0', namely p0 reflected along the edge
p1--p2, and the point q at the perpendicular intersection of the reflection.
p0
_/| \\__
_/ | \\__
/ | ... |
def get_secret(
end_state: NettingChannelEndState,
secrethash: SecretHash,
) -> Optional[Secret]:
"""Returns `secret` if the `secrethash` is for a lock with a known secret."""
partial_unlock_proof = end_state.secrethashes_to_unlockedlocks.get(secrethash)
if partial_unlock_proof is None:
... | Returns `secret` if the `secrethash` is for a lock with a known secret. | Below is the the instruction that describes the task:
### Input:
Returns `secret` if the `secrethash` is for a lock with a known secret.
### Response:
def get_secret(
end_state: NettingChannelEndState,
secrethash: SecretHash,
) -> Optional[Secret]:
"""Returns `secret` if the `secrethash` is for... |
def precompute_optimzation_S(laplacian_matrix,n_samples,relaxation_kwds):
"""compute Rk, A, ATAinv, neighbors and pairs for projected mode"""
relaxation_kwds.setdefault('presave',False)
relaxation_kwds.setdefault('presave_name','pre_comp_current.npy')
relaxation_kwds.setdefault('verbose',False)
if r... | compute Rk, A, ATAinv, neighbors and pairs for projected mode | Below is the the instruction that describes the task:
### Input:
compute Rk, A, ATAinv, neighbors and pairs for projected mode
### Response:
def precompute_optimzation_S(laplacian_matrix,n_samples,relaxation_kwds):
"""compute Rk, A, ATAinv, neighbors and pairs for projected mode"""
relaxation_kwds.setdefau... |
def zremrangebyrank(self, name, rank_start, rank_end):
"""
Remove the elements of the zset which have rank in the range
[rank_start,rank_end].
.. note:: The range is [``rank_start``, ``rank_end``]
:param string name: the zset name
:param int rank_start: zero or ... | Remove the elements of the zset which have rank in the range
[rank_start,rank_end].
.. note:: The range is [``rank_start``, ``rank_end``]
:param string name: the zset name
:param int rank_start: zero or positive,the start position
:param int rank_end: zero or positive,t... | Below is the the instruction that describes the task:
### Input:
Remove the elements of the zset which have rank in the range
[rank_start,rank_end].
.. note:: The range is [``rank_start``, ``rank_end``]
:param string name: the zset name
:param int rank_start: zero or positi... |
def count_above_mean(x):
"""
Returns the number of values in x that are higher than the mean of x
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
m = np.mean(x)
return np.where(x > m)[0].size | Returns the number of values in x that are higher than the mean of x
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float | Below is the the instruction that describes the task:
### Input:
Returns the number of values in x that are higher than the mean of x
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
### Response:
def count_above_me... |
def _recurse(self, inputs, output, depth, max_depth):
'''We work out all combinations using this internal recursion method'''
if depth < max_depth:
for index, option in enumerate(inputs):
my_output = list(output)
my_output.append(option)
self._... | We work out all combinations using this internal recursion method | Below is the the instruction that describes the task:
### Input:
We work out all combinations using this internal recursion method
### Response:
def _recurse(self, inputs, output, depth, max_depth):
'''We work out all combinations using this internal recursion method'''
if depth < max_depth:
... |
def should_remove(self, point, node):
""" checks if self's point (and maybe identity) matches """
if not self.data == point:
return False
return (node is None) or (node is self) | checks if self's point (and maybe identity) matches | Below is the the instruction that describes the task:
### Input:
checks if self's point (and maybe identity) matches
### Response:
def should_remove(self, point, node):
""" checks if self's point (and maybe identity) matches """
if not self.data == point:
return False
return (n... |
def infer_dtype_from_scalar(val, pandas_dtype=False):
"""
interpret the dtype from a scalar
Parameters
----------
pandas_dtype : bool, default False
whether to infer dtype including pandas extension types.
If False, scalar belongs to pandas extension types is inferred as
obj... | interpret the dtype from a scalar
Parameters
----------
pandas_dtype : bool, default False
whether to infer dtype including pandas extension types.
If False, scalar belongs to pandas extension types is inferred as
object | Below is the the instruction that describes the task:
### Input:
interpret the dtype from a scalar
Parameters
----------
pandas_dtype : bool, default False
whether to infer dtype including pandas extension types.
If False, scalar belongs to pandas extension types is inferred as
... |
def play(self):
"""
Starts game and returns one of 3 results .
Iterates between methods ``white_move()`` and
``black_move()`` until game ends. Each
method calls the respective player's ``generate_move()``
method.
:rtype: int
"""
colors = [lambda:... | Starts game and returns one of 3 results .
Iterates between methods ``white_move()`` and
``black_move()`` until game ends. Each
method calls the respective player's ``generate_move()``
method.
:rtype: int | Below is the the instruction that describes the task:
### Input:
Starts game and returns one of 3 results .
Iterates between methods ``white_move()`` and
``black_move()`` until game ends. Each
method calls the respective player's ``generate_move()``
method.
:rtype: int
### ... |
def set_user_profile_photo(
self,
photo: str
) -> bool:
"""Use this method to set a new profile photo.
This method only works for Users.
Bots profile photos must be set using BotFather.
Args:
photo (``str``):
Profile photo to set.
... | Use this method to set a new profile photo.
This method only works for Users.
Bots profile photos must be set using BotFather.
Args:
photo (``str``):
Profile photo to set.
Pass a file path as string to upload a new photo that exists on your local mac... | Below is the the instruction that describes the task:
### Input:
Use this method to set a new profile photo.
This method only works for Users.
Bots profile photos must be set using BotFather.
Args:
photo (``str``):
Profile photo to set.
Pass a fi... |
async def connect(self, conn_id, connection_string):
"""Connect to a device.
See :meth:`AbstractDeviceAdapter.connect`.
"""
self._logger.info("Inside connect, conn_id=%d, conn_string=%s", conn_id, connection_string)
try:
self._setup_connection(conn_id, connection_s... | Connect to a device.
See :meth:`AbstractDeviceAdapter.connect`. | Below is the the instruction that describes the task:
### Input:
Connect to a device.
See :meth:`AbstractDeviceAdapter.connect`.
### Response:
async def connect(self, conn_id, connection_string):
"""Connect to a device.
See :meth:`AbstractDeviceAdapter.connect`.
"""
self.... |
def get_token(self,
grant_type,
client_id,
client_secret,
redirect_uri,
code,
**params):
"""Generate access token HTTP response.
:param grant_type: Desired grant type. Must be "authorization_code... | Generate access token HTTP response.
:param grant_type: Desired grant type. Must be "authorization_code".
:type grant_type: str
:param client_id: Client ID.
:type client_id: str
:param client_secret: Client secret.
:type client_secret: str
:param redirect_uri: Cl... | Below is the the instruction that describes the task:
### Input:
Generate access token HTTP response.
:param grant_type: Desired grant type. Must be "authorization_code".
:type grant_type: str
:param client_id: Client ID.
:type client_id: str
:param client_secret: Client sec... |
def make_script():
""" Return the full testing script, with all the tests. """
# tests
easy = [
'misra1a', 'chwirut2', 'chwirut1', 'lanczos3',
'gauss1', 'gauss2', 'danwood', 'misra1b',
]
medium = [
'kirby2', 'hahn1', 'nelson', 'mgh17', 'lanczos1',
'lanczos2', 'gau... | Return the full testing script, with all the tests. | Below is the the instruction that describes the task:
### Input:
Return the full testing script, with all the tests.
### Response:
def make_script():
""" Return the full testing script, with all the tests. """
# tests
easy = [
'misra1a', 'chwirut2', 'chwirut1', 'lanczos3',
'gauss1', 'ga... |
def status(self, status, headers=None):
'''
Respond with given status and no content
:type status: int
:param status: status code to return
:type headers: dict
:param headers: dictionary of headers to add to response
:returns: itself
:rtype: Rule
... | Respond with given status and no content
:type status: int
:param status: status code to return
:type headers: dict
:param headers: dictionary of headers to add to response
:returns: itself
:rtype: Rule | Below is the the instruction that describes the task:
### Input:
Respond with given status and no content
:type status: int
:param status: status code to return
:type headers: dict
:param headers: dictionary of headers to add to response
:returns: itself
:rtype: Ru... |
def get_proxy_version(self):
"""
Returns version of the Cloud SQL Proxy.
"""
self._download_sql_proxy_if_needed()
command_to_run = [self.sql_proxy_path]
command_to_run.extend(['--version'])
command_to_run.extend(self._get_credential_parameters())
result = ... | Returns version of the Cloud SQL Proxy. | Below is the the instruction that describes the task:
### Input:
Returns version of the Cloud SQL Proxy.
### Response:
def get_proxy_version(self):
"""
Returns version of the Cloud SQL Proxy.
"""
self._download_sql_proxy_if_needed()
command_to_run = [self.sql_proxy_path]
... |
def _create_cache_key(source_file):
"""
return the cache key for a header file.
:param source_file: Header file name
:type source_file: str
:rtype: str
"""
path, name = os.path.split(source_file)
return name + str(hash(path)) | return the cache key for a header file.
:param source_file: Header file name
:type source_file: str
:rtype: str | Below is the the instruction that describes the task:
### Input:
return the cache key for a header file.
:param source_file: Header file name
:type source_file: str
:rtype: str
### Response:
def _create_cache_key(source_file):
"""
return the cache key for a header file.
... |
def get_connection_params(self):
"""Returns a dict of parameters suitable for get_new_connection."""
from django.conf import settings
settings_dict = self.settings_dict
options = settings_dict.get('OPTIONS', {})
autocommit = options.get('autocommit', False)
conn_params = ... | Returns a dict of parameters suitable for get_new_connection. | Below is the the instruction that describes the task:
### Input:
Returns a dict of parameters suitable for get_new_connection.
### Response:
def get_connection_params(self):
"""Returns a dict of parameters suitable for get_new_connection."""
from django.conf import settings
settings_dict = ... |
def ReadDictionary(self, file):
"""Parse a dictionary file.
Reads a RADIUS dictionary file and merges its contents into the
class instance.
:param file: Name of dictionary file to parse or a file-like object
:type file: string or file-like object
"""
fil = dict... | Parse a dictionary file.
Reads a RADIUS dictionary file and merges its contents into the
class instance.
:param file: Name of dictionary file to parse or a file-like object
:type file: string or file-like object | Below is the the instruction that describes the task:
### Input:
Parse a dictionary file.
Reads a RADIUS dictionary file and merges its contents into the
class instance.
:param file: Name of dictionary file to parse or a file-like object
:type file: string or file-like object
### R... |
def get_resource_from_handle(self, resource_handle, verify_repo=True):
"""Get a resource.
Args:
resource_handle (`ResourceHandle`): Handle of the resource.
Returns:
`PackageRepositoryResource` instance.
"""
if verify_repo:
# we could fix the ... | Get a resource.
Args:
resource_handle (`ResourceHandle`): Handle of the resource.
Returns:
`PackageRepositoryResource` instance. | Below is the the instruction that describes the task:
### Input:
Get a resource.
Args:
resource_handle (`ResourceHandle`): Handle of the resource.
Returns:
`PackageRepositoryResource` instance.
### Response:
def get_resource_from_handle(self, resource_handle, verify_repo=T... |
def validate_sdl(
document_ast: DocumentNode,
schema_to_extend: GraphQLSchema = None,
rules: Sequence[RuleType] = None,
) -> List[GraphQLError]:
"""Validate an SDL document."""
context = SDLValidationContext(document_ast, schema_to_extend)
if rules is None:
rules = specified_sdl_rules
... | Validate an SDL document. | Below is the the instruction that describes the task:
### Input:
Validate an SDL document.
### Response:
def validate_sdl(
document_ast: DocumentNode,
schema_to_extend: GraphQLSchema = None,
rules: Sequence[RuleType] = None,
) -> List[GraphQLError]:
"""Validate an SDL document."""
context = SDL... |
def check_response(headers: Headers, key: str) -> None:
"""
Check a handshake response received from the server.
``key`` comes from :func:`build_request`.
If the handshake is valid, this function returns ``None``.
Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake`
exception... | Check a handshake response received from the server.
``key`` comes from :func:`build_request`.
If the handshake is valid, this function returns ``None``.
Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake`
exception.
This function doesn't verify that the response is an HTTP/1.1... | Below is the the instruction that describes the task:
### Input:
Check a handshake response received from the server.
``key`` comes from :func:`build_request`.
If the handshake is valid, this function returns ``None``.
Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake`
exceptio... |
def href_name (txt):
"""Return the name part of the first <a href="">name</a> link in txt."""
name = u""
endtag = a_end_search(txt)
if not endtag:
return name
name = txt[:endtag.start()]
if img_re.search(name):
return image_name(name)
return _unquote(name) | Return the name part of the first <a href="">name</a> link in txt. | Below is the the instruction that describes the task:
### Input:
Return the name part of the first <a href="">name</a> link in txt.
### Response:
def href_name (txt):
"""Return the name part of the first <a href="">name</a> link in txt."""
name = u""
endtag = a_end_search(txt)
if not endtag:
... |
def reflect_table(conn, table_name, schema='public'):
"""Reflect basic table attributes."""
column_meta = list(get_column_metadata(conn, table_name, schema=schema))
primary_key_columns = list(get_primary_keys(conn, table_name, schema=schema))
columns = [Column(**column_data) for column_data in column_... | Reflect basic table attributes. | Below is the the instruction that describes the task:
### Input:
Reflect basic table attributes.
### Response:
def reflect_table(conn, table_name, schema='public'):
"""Reflect basic table attributes."""
column_meta = list(get_column_metadata(conn, table_name, schema=schema))
primary_key_columns = list... |
def filename_items_for_filetype(filenames, filetype_info):
"""Iterator over the filenames matching *filetype_info*."""
matched_files = []
for pattern in filetype_info['file_patterns']:
for filename in match_filenames(filenames, pattern):
if filename in matched_files:
... | Iterator over the filenames matching *filetype_info*. | Below is the the instruction that describes the task:
### Input:
Iterator over the filenames matching *filetype_info*.
### Response:
def filename_items_for_filetype(filenames, filetype_info):
"""Iterator over the filenames matching *filetype_info*."""
matched_files = []
for pattern in filet... |
def routing(self, debug=False, anim=None):
""" Performs routing on Load Area centres to build MV grid with ring topology.
Args
----
debug: bool, defaults to False
If True, information is printed while routing
anim: type, defaults to None
Descr #TODO
... | Performs routing on Load Area centres to build MV grid with ring topology.
Args
----
debug: bool, defaults to False
If True, information is printed while routing
anim: type, defaults to None
Descr #TODO | Below is the the instruction that describes the task:
### Input:
Performs routing on Load Area centres to build MV grid with ring topology.
Args
----
debug: bool, defaults to False
If True, information is printed while routing
anim: type, defaults to None
Des... |
def posterior(self, x):
"""Model is X_1,...,X_n ~ N(0, 1/theta), theta ~ Gamma(a, b)"""
return Gamma(a=self.a + 0.5 * x.size,
b=self.b + 0.5 * np.sum(x**2)) | Model is X_1,...,X_n ~ N(0, 1/theta), theta ~ Gamma(a, b) | Below is the the instruction that describes the task:
### Input:
Model is X_1,...,X_n ~ N(0, 1/theta), theta ~ Gamma(a, b)
### Response:
def posterior(self, x):
"""Model is X_1,...,X_n ~ N(0, 1/theta), theta ~ Gamma(a, b)"""
return Gamma(a=self.a + 0.5 * x.size,
b=self.b + 0.5 ... |
def _initilize(self, state: State) -> State:
"""Initialize program state. Called by program.run() and .evolve()"""
targets = {}
for pc, instr in enumerate(self):
if isinstance(instr, Label):
targets[instr.target] = pc
state = state.update({PC: 0,
... | Initialize program state. Called by program.run() and .evolve() | Below is the the instruction that describes the task:
### Input:
Initialize program state. Called by program.run() and .evolve()
### Response:
def _initilize(self, state: State) -> State:
"""Initialize program state. Called by program.run() and .evolve()"""
targets = {}
for pc, instr in en... |
def addNode(self, node):
'''
Update the shared map with my in-construction node
'''
self.mybldgbuids[node.buid] = node
self.allbldgbuids[node.buid] = (node, self.doneevent) | Update the shared map with my in-construction node | Below is the the instruction that describes the task:
### Input:
Update the shared map with my in-construction node
### Response:
def addNode(self, node):
'''
Update the shared map with my in-construction node
'''
self.mybldgbuids[node.buid] = node
self.allbldgbuids[node.bui... |
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"):
""" Draws the component """
x_origin = self.x_origin
y_origin = self.y_origin
gc.save_state()
try:
# self._draw_bounds(gc)
gc.begin_path()
gc.translate_ctm(x_origin, y_origin)
... | Draws the component | Below is the the instruction that describes the task:
### Input:
Draws the component
### Response:
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"):
""" Draws the component """
x_origin = self.x_origin
y_origin = self.y_origin
gc.save_state()
try:
# ... |
def wait_for_all(self, objects, timeout=120):
"""
Wait until all of given UI proxies show up before timeout.
All UI proxies will be polled periodically. See option :py:class:`poll_interval <poco.pocofw.Poco>` in
``Poco``'s initialization for more details.
Args:
obje... | Wait until all of given UI proxies show up before timeout.
All UI proxies will be polled periodically. See option :py:class:`poll_interval <poco.pocofw.Poco>` in
``Poco``'s initialization for more details.
Args:
objects (Iterable<:py:class:`UIObjectProxy <poco.proxy.UIObjectProxy>`... | Below is the the instruction that describes the task:
### Input:
Wait until all of given UI proxies show up before timeout.
All UI proxies will be polled periodically. See option :py:class:`poll_interval <poco.pocofw.Poco>` in
``Poco``'s initialization for more details.
Args:
o... |
def _load_significant_pathways_file(path_to_file):
"""Read in the significant pathways file as a
pandas.DataFrame.
"""
feature_pathway_df = pd.read_table(
path_to_file, header=0,
usecols=["feature", "side", "pathway"])
feature_pathway_df = feature_pathway_df.sort_values(
by=[... | Read in the significant pathways file as a
pandas.DataFrame. | Below is the the instruction that describes the task:
### Input:
Read in the significant pathways file as a
pandas.DataFrame.
### Response:
def _load_significant_pathways_file(path_to_file):
"""Read in the significant pathways file as a
pandas.DataFrame.
"""
feature_pathway_df = pd.read_table(
... |
def save_config(self):
"""Save configuration: tree widget state"""
for option, value in list(self.explorer.get_options().items()):
self.set_option(option, value)
self.set_option('expanded_state',
self.explorer.treewidget.get_expanded_state())
sel... | Save configuration: tree widget state | Below is the the instruction that describes the task:
### Input:
Save configuration: tree widget state
### Response:
def save_config(self):
"""Save configuration: tree widget state"""
for option, value in list(self.explorer.get_options().items()):
self.set_option(option, value)
... |
def set_cropped_metadata(input_doc, output_doc, metadata_info):
"""Set the metadata for the output document. Mostly just copied over, but
"Producer" has a string appended to indicate that this program modified the
file. That allows for the undo operation to make sure that this
program cropped the file... | Set the metadata for the output document. Mostly just copied over, but
"Producer" has a string appended to indicate that this program modified the
file. That allows for the undo operation to make sure that this
program cropped the file in the first place. | Below is the the instruction that describes the task:
### Input:
Set the metadata for the output document. Mostly just copied over, but
"Producer" has a string appended to indicate that this program modified the
file. That allows for the undo operation to make sure that this
program cropped the file i... |
def options(self):
"""
Returns an iterable of sorted option names in order to loop
through all the configuration directives specified in the class.
"""
keys = self.__class__.__dict__.copy()
keys.update(self.__dict__)
keys = sorted(keys.keys())
for opt in ... | Returns an iterable of sorted option names in order to loop
through all the configuration directives specified in the class. | Below is the the instruction that describes the task:
### Input:
Returns an iterable of sorted option names in order to loop
through all the configuration directives specified in the class.
### Response:
def options(self):
"""
Returns an iterable of sorted option names in order to loop
... |
def fill(self, rgb, x=0, y=0, w=None, h=None, name=""):
"""Creates a new fill layer.
Creates a new layer filled with the given rgb color.
For example, fill((255,0,0)) creates a red fill.
The layers fills the entire canvas by default.
"""
if w == None:... | Creates a new fill layer.
Creates a new layer filled with the given rgb color.
For example, fill((255,0,0)) creates a red fill.
The layers fills the entire canvas by default. | Below is the the instruction that describes the task:
### Input:
Creates a new fill layer.
Creates a new layer filled with the given rgb color.
For example, fill((255,0,0)) creates a red fill.
The layers fills the entire canvas by default.
### Response:
def fill(self, rgb, x=0, y=0, w=... |
def _get_dim_modifier(self, modifiers, dimstring=None):
"""Extracts the dimension information from the string of modifiers extracted by
the regex.
:arg modifiers: the list of modifiers identified by the regex.
"""
if dimstring is None:
suffix = modifiers.spli... | Extracts the dimension information from the string of modifiers extracted by
the regex.
:arg modifiers: the list of modifiers identified by the regex. | Below is the the instruction that describes the task:
### Input:
Extracts the dimension information from the string of modifiers extracted by
the regex.
:arg modifiers: the list of modifiers identified by the regex.
### Response:
def _get_dim_modifier(self, modifiers, dimstring=None):
... |
def request(self, method, url=None, **kwargs):
"""
Perform a request.
:param: method:
The HTTP method to use (example is `GET`).
:param: url:
The URL to use. The default value is the URL this client was
created with (`self.url`) (example is `http://lo... | Perform a request.
:param: method:
The HTTP method to use (example is `GET`).
:param: url:
The URL to use. The default value is the URL this client was
created with (`self.url`) (example is `http://localhost:8080`)
:param: kwargs:
Any other parame... | Below is the the instruction that describes the task:
### Input:
Perform a request.
:param: method:
The HTTP method to use (example is `GET`).
:param: url:
The URL to use. The default value is the URL this client was
created with (`self.url`) (example is `http://... |
def update_redis(project: str, environment: str, feature: str, state: str) \
-> None:
"""
Update redis state for a feature flag.
:param project: LaunchDarkly project key.
:param environment: LaunchDarkly environment key.
:param feature: LaunchDarkly feature key.
:param state: State for ... | Update redis state for a feature flag.
:param project: LaunchDarkly project key.
:param environment: LaunchDarkly environment key.
:param feature: LaunchDarkly feature key.
:param state: State for a feature flag. | Below is the the instruction that describes the task:
### Input:
Update redis state for a feature flag.
:param project: LaunchDarkly project key.
:param environment: LaunchDarkly environment key.
:param feature: LaunchDarkly feature key.
:param state: State for a feature flag.
### Response:
def up... |
def get_datacenters(service_instance, datacenter_names=None,
get_all_datacenters=False):
'''
Returns all datacenters in a vCenter.
service_instance
The Service Instance Object from which to obtain cluster.
datacenter_names
List of datacenter names to filter by. Defa... | Returns all datacenters in a vCenter.
service_instance
The Service Instance Object from which to obtain cluster.
datacenter_names
List of datacenter names to filter by. Default value is None.
get_all_datacenters
Flag specifying whether to retrieve all datacenters.
Default ... | Below is the the instruction that describes the task:
### Input:
Returns all datacenters in a vCenter.
service_instance
The Service Instance Object from which to obtain cluster.
datacenter_names
List of datacenter names to filter by. Default value is None.
get_all_datacenters
... |
def discretize_bezier(points,
count=None,
scale=1.0):
"""
Parameters
----------
points : (order, dimension) float
Control points of the bezier curve
For a 2D cubic bezier, order=3, dimension=2
count : int, or None
Number of segments
s... | Parameters
----------
points : (order, dimension) float
Control points of the bezier curve
For a 2D cubic bezier, order=3, dimension=2
count : int, or None
Number of segments
scale : float
Scale of curve
Returns
----------
discrete: (n,d) list of points, a polyline re... | Below is the the instruction that describes the task:
### Input:
Parameters
----------
points : (order, dimension) float
Control points of the bezier curve
For a 2D cubic bezier, order=3, dimension=2
count : int, or None
Number of segments
scale : float
Scale of curve
Ret... |
def inventory(self, modules_inventory=False):
""" Get chassis inventory.
:param modules_inventory: True - read modules inventory, false - don't read.
"""
self.c_info = self.get_attributes()
for m_index, m_portcounts in enumerate(self.c_info['c_portcounts'].split()):
... | Get chassis inventory.
:param modules_inventory: True - read modules inventory, false - don't read. | Below is the the instruction that describes the task:
### Input:
Get chassis inventory.
:param modules_inventory: True - read modules inventory, false - don't read.
### Response:
def inventory(self, modules_inventory=False):
""" Get chassis inventory.
:param modules_inventory: True - read... |
def foldOneLine(outbuf, input, lineLength = 75):
"""
Folding line procedure that ensures multi-byte utf-8 sequences are not
broken across lines
TO-DO: This all seems odd. Is it still needed, especially in python3?
"""
if len(input) < lineLength:
# Optimize for unfolded line case
... | Folding line procedure that ensures multi-byte utf-8 sequences are not
broken across lines
TO-DO: This all seems odd. Is it still needed, especially in python3? | Below is the the instruction that describes the task:
### Input:
Folding line procedure that ensures multi-byte utf-8 sequences are not
broken across lines
TO-DO: This all seems odd. Is it still needed, especially in python3?
### Response:
def foldOneLine(outbuf, input, lineLength = 75):
"""
Foldi... |
def get(url, last_modified=None):
"""Performs a get request to a given url. Returns an empty str on error.
"""
try:
with closing(urllib2.urlopen(url)) as page:
if last_modified is not None:
last_mod = dateutil.parser.parse(dict(page.info())['last-modified'])
... | Performs a get request to a given url. Returns an empty str on error. | Below is the the instruction that describes the task:
### Input:
Performs a get request to a given url. Returns an empty str on error.
### Response:
def get(url, last_modified=None):
"""Performs a get request to a given url. Returns an empty str on error.
"""
try:
with closing(urllib2.urlopen(u... |
def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
dry_run=0, owner=None, group=None, logger=None):
"""Create an archive file (eg. zip or tar).
'base_name' is the name of the file to create, minus any format-specific
extension; 'format' is the archive format: one ... | Create an archive file (eg. zip or tar).
'base_name' is the name of the file to create, minus any format-specific
extension; 'format' is the archive format: one of "zip", "tar", "bztar"
or "gztar".
'root_dir' is a directory that will be the root directory of the
archive; ie. we typically chdir int... | Below is the the instruction that describes the task:
### Input:
Create an archive file (eg. zip or tar).
'base_name' is the name of the file to create, minus any format-specific
extension; 'format' is the archive format: one of "zip", "tar", "bztar"
or "gztar".
'root_dir' is a directory that will... |
def pformat_program_dump(self, program_dump, program_start=None):
"""
format a BASIC program dump. Useful for debugging.
returns a list of formated string lines.
"""
assert isinstance(program_dump, bytearray)
if program_start is None:
program_start = self.DEF... | format a BASIC program dump. Useful for debugging.
returns a list of formated string lines. | Below is the the instruction that describes the task:
### Input:
format a BASIC program dump. Useful for debugging.
returns a list of formated string lines.
### Response:
def pformat_program_dump(self, program_dump, program_start=None):
"""
format a BASIC program dump. Useful for debugging.... |
def updateCurrentNetworkInNdex(self, body, verbose=None):
"""
Update current network's record in NDEx
:param body: Properties required to update a network record in NDEx.
:param verbose: print more
:returns: 200: successful operation; 404: Network does not exist
"""
... | Update current network's record in NDEx
:param body: Properties required to update a network record in NDEx.
:param verbose: print more
:returns: 200: successful operation; 404: Network does not exist | Below is the the instruction that describes the task:
### Input:
Update current network's record in NDEx
:param body: Properties required to update a network record in NDEx.
:param verbose: print more
:returns: 200: successful operation; 404: Network does not exist
### Response:
def updat... |
def overview():
"""
Provides an overview of the duplicate credentials.
"""
search = Credential.search()
search.aggs.bucket('password_count', 'terms', field='secret', order={'_count': 'desc'}, size=20)\
.metric('username_count', 'cardinality', field='username') \
.metric('host_cou... | Provides an overview of the duplicate credentials. | Below is the the instruction that describes the task:
### Input:
Provides an overview of the duplicate credentials.
### Response:
def overview():
"""
Provides an overview of the duplicate credentials.
"""
search = Credential.search()
search.aggs.bucket('password_count', 'terms', field='secr... |
def show(key=None, display_toolbar=True):
"""Shows the current context figure in the output area.
Parameters
----------
key : hashable, optional
Any variable that can be used as a key for a dictionary.
display_toolbar: bool (default: True)
If True, a toolbar for different mouse int... | Shows the current context figure in the output area.
Parameters
----------
key : hashable, optional
Any variable that can be used as a key for a dictionary.
display_toolbar: bool (default: True)
If True, a toolbar for different mouse interaction is displayed with
the figure.
... | Below is the the instruction that describes the task:
### Input:
Shows the current context figure in the output area.
Parameters
----------
key : hashable, optional
Any variable that can be used as a key for a dictionary.
display_toolbar: bool (default: True)
If True, a toolbar for... |
def add_query_to_url(url, extra_query):
'''Adds an extra query to URL, returning the new URL.
Extra query may be a dict or a list as returned by
:func:`urllib.parse.parse_qsl()` and :func:`urllib.parse.parse_qs()`.
'''
split = urllib.parse.urlsplit(url)
merged_query = urllib.parse.parse_qsl(sp... | Adds an extra query to URL, returning the new URL.
Extra query may be a dict or a list as returned by
:func:`urllib.parse.parse_qsl()` and :func:`urllib.parse.parse_qs()`. | Below is the the instruction that describes the task:
### Input:
Adds an extra query to URL, returning the new URL.
Extra query may be a dict or a list as returned by
:func:`urllib.parse.parse_qsl()` and :func:`urllib.parse.parse_qs()`.
### Response:
def add_query_to_url(url, extra_query):
'''Adds an ... |
def function_name(self):
"""
Returns name of the function to invoke. If no function identifier is provided, this method will return name of
the only function from the template
:return string: Name of the function
:raises InvokeContextException: If function identifier is not prov... | Returns name of the function to invoke. If no function identifier is provided, this method will return name of
the only function from the template
:return string: Name of the function
:raises InvokeContextException: If function identifier is not provided | Below is the the instruction that describes the task:
### Input:
Returns name of the function to invoke. If no function identifier is provided, this method will return name of
the only function from the template
:return string: Name of the function
:raises InvokeContextException: If functio... |
def get_install_id(filename):
""" Return install id from library named in `filename`
Returns None if no install id, or if this is not an object file.
Parameters
----------
filename : str
filename of library
Returns
-------
install_id : str
install id of library `filena... | Return install id from library named in `filename`
Returns None if no install id, or if this is not an object file.
Parameters
----------
filename : str
filename of library
Returns
-------
install_id : str
install id of library `filename`, or None if no install id | Below is the the instruction that describes the task:
### Input:
Return install id from library named in `filename`
Returns None if no install id, or if this is not an object file.
Parameters
----------
filename : str
filename of library
Returns
-------
install_id : str
... |
def _get_wait_in(self, flag=True, all_domain=True):
"""
Set `wait_inputs` flags for data nodes that:
- are estimated from functions with a domain function, and
- are waiting inputs.
:param flag:
Value to be set. If None `wait_inputs` are just cleaned.
... | Set `wait_inputs` flags for data nodes that:
- are estimated from functions with a domain function, and
- are waiting inputs.
:param flag:
Value to be set. If None `wait_inputs` are just cleaned.
:type flag: bool, None, optional
:param all_domain:
... | Below is the the instruction that describes the task:
### Input:
Set `wait_inputs` flags for data nodes that:
- are estimated from functions with a domain function, and
- are waiting inputs.
:param flag:
Value to be set. If None `wait_inputs` are just cleaned.
:... |
def get_uint32(self):
"""Read the next token and interpret it as a 32-bit unsigned
integer.
@raises dns.exception.SyntaxError:
@rtype: int
"""
token = self.get().unescape()
if not token.is_identifier():
raise dns.exception.SyntaxError('expecting an i... | Read the next token and interpret it as a 32-bit unsigned
integer.
@raises dns.exception.SyntaxError:
@rtype: int | Below is the the instruction that describes the task:
### Input:
Read the next token and interpret it as a 32-bit unsigned
integer.
@raises dns.exception.SyntaxError:
@rtype: int
### Response:
def get_uint32(self):
"""Read the next token and interpret it as a 32-bit unsigned
... |
def parse_obj(o):
"""
Parses a given dictionary with the key being the OBD PID and the value its
returned value by the OBD interface
:param dict o:
:return:
"""
r = {}
for k, v in o.items():
if is_unable_to_connect(v):
r[k] = None
try:
r[k] = pars... | Parses a given dictionary with the key being the OBD PID and the value its
returned value by the OBD interface
:param dict o:
:return: | Below is the the instruction that describes the task:
### Input:
Parses a given dictionary with the key being the OBD PID and the value its
returned value by the OBD interface
:param dict o:
:return:
### Response:
def parse_obj(o):
"""
Parses a given dictionary with the key being the OBD PID an... |
def _handle_account(self, data, ts):
""" Handles Account related data.
translation table for channel names:
Data Channels
os - Orders
hos - Historical Orders
ps - Positions
hts - Trades (snapshot)
te ... | Handles Account related data.
translation table for channel names:
Data Channels
os - Orders
hos - Historical Orders
ps - Positions
hts - Trades (snapshot)
te - Trade Event
tu - Trade Upd... | Below is the the instruction that describes the task:
### Input:
Handles Account related data.
translation table for channel names:
Data Channels
os - Orders
hos - Historical Orders
ps - Positions
hts - Trades (snapshot)
... |
def new(name):
"""Make a new interpolator by name.
Make a new interpolator from the libvips class nickname. For example::
inter = pyvips.Interpolator.new('bicubic')
You can get a list of all supported interpolators from the command-line
with::
$ vips -l interp... | Make a new interpolator by name.
Make a new interpolator from the libvips class nickname. For example::
inter = pyvips.Interpolator.new('bicubic')
You can get a list of all supported interpolators from the command-line
with::
$ vips -l interpolate
See for exa... | Below is the the instruction that describes the task:
### Input:
Make a new interpolator by name.
Make a new interpolator from the libvips class nickname. For example::
inter = pyvips.Interpolator.new('bicubic')
You can get a list of all supported interpolators from the command-line
... |
def retinotopy_model(name='benson17', hemi=None,
radius=np.pi/2.5, sphere_radius=100.0,
search_paths=None, update=False):
'''
retinotopy_model() yields a standard retinotopy model of V1, V2, and V3 as well as other areas
(depending on the options). The model itself ... | retinotopy_model() yields a standard retinotopy model of V1, V2, and V3 as well as other areas
(depending on the options). The model itself is represented as a RegisteredRetinotopyModel
object, which may internally store a set of meshes with values at the vertices that define the
polar angle and eccentricit... | Below is the the instruction that describes the task:
### Input:
retinotopy_model() yields a standard retinotopy model of V1, V2, and V3 as well as other areas
(depending on the options). The model itself is represented as a RegisteredRetinotopyModel
object, which may internally store a set of meshes with v... |
def autodoc_applicationmodel(module):
"""Improves the docstrings of application models when called
at the bottom of the respective module.
|autodoc_applicationmodel| requires, similar to
|autodoc_basemodel|, that both the application model and its
base model are defined in the conventional way.
... | Improves the docstrings of application models when called
at the bottom of the respective module.
|autodoc_applicationmodel| requires, similar to
|autodoc_basemodel|, that both the application model and its
base model are defined in the conventional way. | Below is the the instruction that describes the task:
### Input:
Improves the docstrings of application models when called
at the bottom of the respective module.
|autodoc_applicationmodel| requires, similar to
|autodoc_basemodel|, that both the application model and its
base model are defined in t... |
def fetch_host_ip_and_country(host: str) -> Tuple:
"""
Fetch ip and country by host
"""
ip = fetch_host_ip(host)
if not host:
return '', ''
country = fetch_country_by_ip(ip)
return ip, country | Fetch ip and country by host | Below is the the instruction that describes the task:
### Input:
Fetch ip and country by host
### Response:
def fetch_host_ip_and_country(host: str) -> Tuple:
"""
Fetch ip and country by host
"""
ip = fetch_host_ip(host)
if not host:
return '', ''
country = fetch_country_by_ip(ip)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.