code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def tarball_context(url, target_dir=None, runner=None, pushd=pushd):
"""
Get a tarball, extract it, change to that directory, yield, then
clean up.
`runner` is the function to invoke commands.
`pushd` is a context manager for changing the directory.
"""
if target_dir is None:
target_dir = os.path.basename(url)... | Get a tarball, extract it, change to that directory, yield, then
clean up.
`runner` is the function to invoke commands.
`pushd` is a context manager for changing the directory. |
def delete_external_feed_groups(self, group_id, external_feed_id):
"""
Delete an external feed.
Deletes the external feed.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
... | Delete an external feed.
Deletes the external feed. |
def get_device_hybrid_interfaces(auth, url, devid=None, devip=None):
"""
Function takes devId as input to RESTFUL call to HP IMC platform
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.au... | Function takes devId as input to RESTFUL call to HP IMC platform
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:param devid: str requires devid of the target device
:param de... |
def body_block_supplementary_material_render(supp_tags, base_url=None):
"""fig and media tag caption may have supplementary material"""
source_data = []
for supp_tag in supp_tags:
for block_content in body_block_content_render(supp_tag, base_url=base_url):
if block_content != {}:
... | fig and media tag caption may have supplementary material |
def _encode(data, convert_to_float):
"""Convert the Python values to values suitable to send to Octave.
"""
ctf = convert_to_float
# Handle variable pointer.
if isinstance(data, (OctaveVariablePtr)):
return _encode(data.value, ctf)
# Handle a user defined object.
if isins... | Convert the Python values to values suitable to send to Octave. |
def select_mask(cls, dataset, selection):
"""
Given a Dataset object and a dictionary with dimension keys and
selection keys (i.e tuple ranges, slices, sets, lists or literals)
return a boolean mask over the rows in the Dataset object that
have been selected.
"""
... | Given a Dataset object and a dictionary with dimension keys and
selection keys (i.e tuple ranges, slices, sets, lists or literals)
return a boolean mask over the rows in the Dataset object that
have been selected. |
def handle_validation_error(self, error, bundle_errors):
"""Called when an error is raised while parsing. Aborts the request
with a 400 status and an error message
:param error: the error that was raised
:param bundle_errors: do not abort when first error occurs, return a
di... | Called when an error is raised while parsing. Aborts the request
with a 400 status and an error message
:param error: the error that was raised
:param bundle_errors: do not abort when first error occurs, return a
dict with the name of the argument and the error message to be
... |
def predict(self, data, output_margin=False, ntree_limit=0, pred_leaf=False,
pred_contribs=False, approx_contribs=False, pred_interactions=False,
validate_features=True):
"""
Predict with data.
.. note:: This function is not thread safe.
For each boost... | Predict with data.
.. note:: This function is not thread safe.
For each booster object, predict can only be called from one thread.
If you want to run prediction using multiple thread, call ``bst.copy()`` to make copies
of model object and then call ``predict()``.
.. not... |
def sanitize(self, val):
"""Given a Variable and a value, cleans it out"""
if self.type == NUMBER:
try:
return clamp(self.min, self.max, float(val))
except ValueError:
return 0.0
elif self.type == TEXT:
try:
retu... | Given a Variable and a value, cleans it out |
def run_cli():
"Command line interface to hiwenet."
features_path, groups_path, weight_method, num_bins, edge_range, \
trim_outliers, trim_percentile, return_networkx_graph, out_weights_path = parse_args()
# TODO add the possibility to process multiple combinations of parameters: diff subjects, diff m... | Command line interface to hiwenet. |
def escape_velocity(M,R):
"""
escape velocity.
Parameters
----------
M : float
Mass in solar masses.
R : float
Radius in solar radiu.
Returns
-------
v_escape
in km/s.
"""
ve = np.sqrt(2.*grav_const*M*msun_g/(R*rsun_cm))
ve = ve*1.... | escape velocity.
Parameters
----------
M : float
Mass in solar masses.
R : float
Radius in solar radiu.
Returns
-------
v_escape
in km/s. |
def _RemoveForwardedIps(self, forwarded_ips, interface):
"""Remove the forwarded IP addresses from the network interface.
Args:
forwarded_ips: list, the forwarded IP address strings to delete.
interface: string, the output device to use.
"""
for address in forwarded_ips:
self.ip_forwa... | Remove the forwarded IP addresses from the network interface.
Args:
forwarded_ips: list, the forwarded IP address strings to delete.
interface: string, the output device to use. |
def restart_container(self, ip):
"""重启容器
重启指定IP的容器。
Args:
- ip: 容器ip
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回空dict{},失败返回{"error": "<errMsg string>"}
- ResponseInfo 请求的Response信息
"""
... | 重启容器
重启指定IP的容器。
Args:
- ip: 容器ip
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回空dict{},失败返回{"error": "<errMsg string>"}
- ResponseInfo 请求的Response信息 |
def single(C, namespace=None):
"""An element maker with a single namespace that uses that namespace as the default"""
if namespace is None:
B = C()._
else:
B = C(default=namespace, _=namespace)._
return B | An element maker with a single namespace that uses that namespace as the default |
def get_thermostat_state_by_name(self, name):
"""Retrieves a thermostat state object by its assigned name
:param name: The name of the thermostat state
:return: The thermostat state object
"""
self._validate_thermostat_state_name(name)
return next((state for state in sel... | Retrieves a thermostat state object by its assigned name
:param name: The name of the thermostat state
:return: The thermostat state object |
def clean_username(self):
"""
Ensure the username doesn't exist or contain invalid chars.
We limit it to slugifiable chars since it's used as the slug
for the user's profile view.
"""
username = self.cleaned_data.get("username")
if username.lower() != slugify(user... | Ensure the username doesn't exist or contain invalid chars.
We limit it to slugifiable chars since it's used as the slug
for the user's profile view. |
def oem_init(self):
"""Initialize the command object for OEM capabilities
A number of capabilities are either totally OEM defined or
else augmented somehow by knowledge of the OEM. This
method does an interrogation to identify the OEM.
"""
if self._oemknown:
... | Initialize the command object for OEM capabilities
A number of capabilities are either totally OEM defined or
else augmented somehow by knowledge of the OEM. This
method does an interrogation to identify the OEM. |
def device_measurement(device,
ts=None,
part=None,
result=None,
code=None,
**kwargs):
"""Returns a JSON MeasurementPayload ready to be send through a
transport.
If `ts` is not given, the curre... | Returns a JSON MeasurementPayload ready to be send through a
transport.
If `ts` is not given, the current time is used. `part` is an
optional `Part` object, and `result` and `code` are the respective
fields of the `Measurement` object. All other arguments are
interpreted as dimensions.
Minimal... |
def IndexedDB_requestData(self, securityOrigin, databaseName,
objectStoreName, indexName, skipCount, pageSize, **kwargs):
"""
Function path: IndexedDB.requestData
Domain: IndexedDB
Method name: requestData
Parameters:
Required arguments:
'securityOrigin' (type: string) -> Security origin.
... | Function path: IndexedDB.requestData
Domain: IndexedDB
Method name: requestData
Parameters:
Required arguments:
'securityOrigin' (type: string) -> Security origin.
'databaseName' (type: string) -> Database name.
'objectStoreName' (type: string) -> Object store name.
'indexName' (type... |
def getInput():
"""Read the input buffer without blocking the system."""
input = ''
if sys.platform == 'win32':
import msvcrt
if msvcrt.kbhit(): # Check for a keyboard hit.
input += msvcrt.getch()
print_(input)
else:
time.sleep(.1)
else: # ... | Read the input buffer without blocking the system. |
def register(cls, barset, name=None):
""" Register a new BarSet as a member/attribute of this class.
Returns the new BarSet.
Arguments:
barset : An existing BarSet, or an iterable of strings.
name : New name for the BarSet, also used as the
... | Register a new BarSet as a member/attribute of this class.
Returns the new BarSet.
Arguments:
barset : An existing BarSet, or an iterable of strings.
name : New name for the BarSet, also used as the
classes attribute name.
... |
def get_and_update(cls, id, **kwargs):
"""Returns an updated instance of the service's model class.
Args:
model: the model to update
**kwargs: update parameters
"""
model = cls.get(id)
for k, v in cls._preprocess_params(kwargs).items():
setatt... | Returns an updated instance of the service's model class.
Args:
model: the model to update
**kwargs: update parameters |
def reload(self):
'''
Clear plugin manager state and reload plugins.
This method will make use of :meth:`clear` and :meth:`load_plugin`,
so all internal state will be cleared, and all plugins defined in
:data:`self.app.config['plugin_modules']` will be loaded.
'''
... | Clear plugin manager state and reload plugins.
This method will make use of :meth:`clear` and :meth:`load_plugin`,
so all internal state will be cleared, and all plugins defined in
:data:`self.app.config['plugin_modules']` will be loaded. |
def init_runner(self, parser, tracers, projinfo):
''' initial some instances for preparing to run test case
@note: should not override
@param parser: instance of TestCaseParser
@param tracers: dict type for the instance of Tracer. Such as {"":tracer_obj} or {"192.168.0.1:5555":trace... | initial some instances for preparing to run test case
@note: should not override
@param parser: instance of TestCaseParser
@param tracers: dict type for the instance of Tracer. Such as {"":tracer_obj} or {"192.168.0.1:5555":tracer_obj1, "192.168.0.2:5555":tracer_obj2}
@param proj_i... |
def _fully_random_weights(n_features, lam_scale, prng):
"""Generate a symmetric random matrix with zeros along the diagonal."""
weights = np.zeros((n_features, n_features))
n_off_diag = int((n_features ** 2 - n_features) / 2)
weights[np.triu_indices(n_features, k=1)] = 0.1 * lam_scale * prng.randn(
... | Generate a symmetric random matrix with zeros along the diagonal. |
def ConnectionUpdate(self, settings):
'''Update settings on a connection.
settings is a String String Variant Map Map. See
https://developer.gnome.org/NetworkManager/0.9/spec.html
#type-String_String_Variant_Map_Map
'''
connection_path = self.connection_path
NM = dbusmock.get_object(MA... | Update settings on a connection.
settings is a String String Variant Map Map. See
https://developer.gnome.org/NetworkManager/0.9/spec.html
#type-String_String_Variant_Map_Map |
def _check_lods(parts, tumor_thresh, normal_thresh, indexes):
"""Ensure likelihoods for tumor and normal pass thresholds.
Skipped if no FreeBayes GL annotations available.
"""
try:
gl_index = parts[8].split(":").index("GL")
except ValueError:
return True
try:
tumor_gls =... | Ensure likelihoods for tumor and normal pass thresholds.
Skipped if no FreeBayes GL annotations available. |
def p_case_clause(self, p):
"""case_clause : CASE expr COLON source_elements"""
p[0] = self.asttypes.Case(expr=p[2], elements=p[4])
p[0].setpos(p) | case_clause : CASE expr COLON source_elements |
def from_key(cls, *args):
"""
Return flyweight object with specified key, if it has already been created.
Returns:
cls or None: Previously constructed flyweight object with given
key or None if key not found
"""
key = args if len(args) > 1 else args[0]
... | Return flyweight object with specified key, if it has already been created.
Returns:
cls or None: Previously constructed flyweight object with given
key or None if key not found |
def add_component(self, kind, **kwargs):
"""
Add a new component (star or orbit) to the system. If not provided,
'component' (the name of the new star or orbit) will be created for
you and can be accessed by the 'component' attribute of the returned
ParameterSet.
>>> b.... | Add a new component (star or orbit) to the system. If not provided,
'component' (the name of the new star or orbit) will be created for
you and can be accessed by the 'component' attribute of the returned
ParameterSet.
>>> b.add_component(component.star)
or
>>> b.add_... |
def set_timezone(self, timezone: str):
""" sets the timezone for the AP. e.g. "Europe/Berlin"
Args:
timezone(str): the new timezone
"""
data = {"timezoneId": timezone}
return self._restCall("home/setTimezone", body=json.dumps(data)) | sets the timezone for the AP. e.g. "Europe/Berlin"
Args:
timezone(str): the new timezone |
def get_mysql_cfg():
"""
Get the appropriate MySQL configuration
"""
environment = get_project_configuration()['environment']
cfg = get_database_configuration()
if environment == 'production':
mysql = cfg['mysql_online']
else:
mysql = cfg['mysql_dev']
return mysql | Get the appropriate MySQL configuration |
def save(self, obj):
"""Add ``obj`` to the SQLAlchemy session and commit the changes back to
the database.
:param obj: SQLAlchemy object being saved
:returns: The saved object
"""
session = self.get_db_session()
session.add(obj)
session.commit()
... | Add ``obj`` to the SQLAlchemy session and commit the changes back to
the database.
:param obj: SQLAlchemy object being saved
:returns: The saved object |
def _convert_pooling_param(param):
"""Convert the pooling layer parameter
"""
param_string = "pooling_convention='full', "
if param.global_pooling:
param_string += "global_pool=True, kernel=(1,1)"
else:
param_string += "pad=(%d,%d), kernel=(%d,%d), stride=(%d,%d)" % (
par... | Convert the pooling layer parameter |
def parseConfig(opt):
"""Parse configuration
:params opt: dict-like object with config and messages keys
:returns: restarter, path
"""
places = ctllib.Places(config=opt['config'], messages=opt['messages'])
restarter = functools.partial(ctllib.restart, places)
path = filepath.FilePath(opt['c... | Parse configuration
:params opt: dict-like object with config and messages keys
:returns: restarter, path |
def init_class(self, class_, step_func=None):
"""
This method simulates the loading of a class by the JVM, during which
parts of the class (e.g. static fields) are initialized. For this, we
run the class initializer method <clinit> (if available) and update
the state accordingly.... | This method simulates the loading of a class by the JVM, during which
parts of the class (e.g. static fields) are initialized. For this, we
run the class initializer method <clinit> (if available) and update
the state accordingly.
Note: Initialization is skipped, if the class has alread... |
def printStatistics(completion, concordance, tpedSamples, oldSamples, prefix):
"""Print the statistics in a file.
:param completion: the completion of each duplicated samples.
:param concordance: the concordance of each duplicated samples.
:param tpedSamples: the updated position of the samples in the ... | Print the statistics in a file.
:param completion: the completion of each duplicated samples.
:param concordance: the concordance of each duplicated samples.
:param tpedSamples: the updated position of the samples in the tped
containing only duplicated samples.
:param oldSamples... |
def set_color(index, color):
"""Convert a hex color to a text color sequence."""
if OS == "Darwin" and index < 20:
return "\033]P%1x%s\033\\" % (index, color.strip("#"))
return "\033]4;%s;%s\033\\" % (index, color) | Convert a hex color to a text color sequence. |
def fetch_token(self, **kwargs):
"""Fetch a new token using the supplied code.
:param str code: A previously obtained auth code.
"""
if 'client_secret' not in kwargs:
kwargs.update(client_secret=self.client_secret)
return self.session.fetch_token(token_url, **kwargs... | Fetch a new token using the supplied code.
:param str code: A previously obtained auth code. |
def get_trend(self):
"""
Get the trend for the last two metric values using the interval defined in the metric
:return: a tuple with the metric value for the last interval and the
trend percentage between the last two intervals
"""
""" """
# TODO: We j... | Get the trend for the last two metric values using the interval defined in the metric
:return: a tuple with the metric value for the last interval and the
trend percentage between the last two intervals |
def commit(self, message, parent_commits=None, head=True, author=None,
committer=None, author_date=None, commit_date=None,
skip_hooks=False):
"""Commit the current default index file, creating a commit object.
For more information on the arguments, see tree.commit.
... | Commit the current default index file, creating a commit object.
For more information on the arguments, see tree.commit.
:note: If you have manually altered the .entries member of this instance,
don't forget to write() your changes to disk beforehand.
Passing skip_hooks=Tr... |
def _is_valid_channel(self, channel,
conda_url='https://conda.anaconda.org'):
"""Callback for is_valid_channel."""
if channel.startswith('https://') or channel.startswith('http://'):
url = channel
else:
url = "{0}/{1}".format(conda_url, channel)
... | Callback for is_valid_channel. |
def inject(self):
"""
Recursively inject aXe into all iframes and the top level document.
:param script_url: location of the axe-core script.
:type script_url: string
"""
with open(self.script_url, "r", encoding="utf8") as f:
self.selenium.execute_script(f.re... | Recursively inject aXe into all iframes and the top level document.
:param script_url: location of the axe-core script.
:type script_url: string |
def _mute(self):
""" mute vlc """
if self.muted:
self._sendCommand("volume {}\n".format(self.actual_volume))
if logger.isEnabledFor(logging.DEBUG):
logger.debug('VLC unmuted: {0} ({1}%)'.format(self.actual_volume, int(100 * self.actual_volume / self.max_volume)))... | mute vlc |
def _clear(self):
"""
Helper that clears the composition.
"""
draw = ImageDraw.Draw(self._background_image)
draw.rectangle(self._device.bounding_box,
fill="black")
del draw | Helper that clears the composition. |
def remove_image_info_cb(self, gshell, channel, iminfo):
"""Delete entries related to deleted image."""
chname = channel.name
if chname not in self.name_dict:
return
fileDict = self.name_dict[chname]
name = iminfo.name
if name not in fileDict:
re... | Delete entries related to deleted image. |
def replace_namespaced_stateful_set_scale(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_stateful_set_scale # noqa: E501
replace scale of the specified StatefulSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronou... | replace_namespaced_stateful_set_scale # noqa: E501
replace scale of the specified StatefulSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_stateful_set_scale(n... |
def Trans(self, stateFrom, *condAndNextState):
"""
:param stateFrom: apply when FSM is in this state
:param condAndNextState: tupes (condition, newState),
last does not to have condition
:attention: transitions has priority, first has the biggest
:attention: if state... | :param stateFrom: apply when FSM is in this state
:param condAndNextState: tupes (condition, newState),
last does not to have condition
:attention: transitions has priority, first has the biggest
:attention: if stateFrom is None it is evaluated as default |
def retrieve(cls, *args, **kwargs):
"""Return parent method."""
return super(Subscription, cls).retrieve(*args, **kwargs) | Return parent method. |
def get_path(self):
"""
Calculate item's path in configuration tree.
Use this sparingly -- path is calculated by going up the configuration tree.
For a large number of items, it is more efficient to use iterators that return paths
as keys.
Path value is stable only once ... | Calculate item's path in configuration tree.
Use this sparingly -- path is calculated by going up the configuration tree.
For a large number of items, it is more efficient to use iterators that return paths
as keys.
Path value is stable only once the configuration tree is completely ini... |
def _rotate(img, angle):
'''
angle [DEG]
'''
s = img.shape
if angle == 0:
return img
else:
M = cv2.getRotationMatrix2D((s[1] // 2,
s[0] // 2), angle, 1)
return cv2.warpAffine(img, M, (s... | angle [DEG] |
def back_slash_to_front_converter(string):
"""
Replacing all \ in the str to /
:param string: single string to modify
:type string: str
"""
try:
if not string or not isinstance(string, str):
return string
return string.replace('\\', '/')
except Exception:
... | Replacing all \ in the str to /
:param string: single string to modify
:type string: str |
def imap(self, coords):
"""Inverse map coordinates
Parameters
----------
coords : array-like
Coordinates to inverse map.
Returns
-------
coords : ndarray
Coordinates.
"""
for tr in self.transforms:
coords = tr.... | Inverse map coordinates
Parameters
----------
coords : array-like
Coordinates to inverse map.
Returns
-------
coords : ndarray
Coordinates. |
def exceptions(self):
"""A dict of dates -> [Period time tuples] representing exceptions
to the base recurrence pattern."""
ex = {}
for sd in self.root.xpath('exceptions/exception'):
bits = str(sd.text).split(' ')
date = text_to_date(bits.pop(0))
ex.se... | A dict of dates -> [Period time tuples] representing exceptions
to the base recurrence pattern. |
def is_stable(self,species):
'''
This routine accepts input formatted like 'He-3' and checks with
stable_el list if occurs in there. If it does, the routine
returns True, otherwise False.
Notes
-----
this method is designed to work with an se instance from
... | This routine accepts input formatted like 'He-3' and checks with
stable_el list if occurs in there. If it does, the routine
returns True, otherwise False.
Notes
-----
this method is designed to work with an se instance from
nugridse.py. In order to make it work with ppn... |
def put_task(self, dp, callback=None):
"""
Same as in :meth:`AsyncPredictorBase.put_task`.
"""
f = Future()
if callback is not None:
f.add_done_callback(callback)
self.input_queue.put((dp, f))
return f | Same as in :meth:`AsyncPredictorBase.put_task`. |
def SegmentProd(a, ids):
"""
Segmented prod op.
"""
func = lambda idxs: reduce(np.multiply, a[idxs])
return seg_map(func, a, ids), | Segmented prod op. |
def avg(self, property):
"""Getting average according to given property
:@param property
:@type property: string
:@return average: int/float
"""
self.__prepare()
return self.sum(property) / self.count() | Getting average according to given property
:@param property
:@type property: string
:@return average: int/float |
def add_sources_argument(cls, group, allow_filters=True, prefix=None, add_root_paths=False):
"""
Subclasses may call this to add sources and source_filters arguments.
Args:
group: arparse.ArgumentGroup, the extension argument group
allow_filters: bool, Whether the exten... | Subclasses may call this to add sources and source_filters arguments.
Args:
group: arparse.ArgumentGroup, the extension argument group
allow_filters: bool, Whether the extension wishes to expose a
source_filters argument.
prefix: str, arguments have to be na... |
def register_name(self, register_index):
"""Retrives and returns the name of an ARM CPU register.
Args:
self (JLink): the ``JLink`` instance
register_index (int): index of the register whose name to retrieve
Returns:
Name of the register.
"""
resul... | Retrives and returns the name of an ARM CPU register.
Args:
self (JLink): the ``JLink`` instance
register_index (int): index of the register whose name to retrieve
Returns:
Name of the register. |
def output(self, _in, out, **kwargs):
"""Wrap translation in Angular module."""
out.write(
'angular.module("{0}", ["gettext"]).run('
'["gettextCatalog", function (gettextCatalog) {{'.format(
self.catalog_name
)
)
out.write(_in.read())
... | Wrap translation in Angular module. |
def generateDrawSpecs(self, p):
"""
Calls tickValues() and tickStrings() to determine where and how ticks should
be drawn, then generates from this a set of drawing commands to be
interpreted by drawPicture().
"""
profiler = debug.Profiler()
# bounds = self.bound... | Calls tickValues() and tickStrings() to determine where and how ticks should
be drawn, then generates from this a set of drawing commands to be
interpreted by drawPicture(). |
def attach_tcp_service(cls, tcp_service: TCPService):
""" Attaches a service for hosting
:param tcp_service: A TCPService instance
"""
if cls._services['_tcp_service'] is None:
cls._services['_tcp_service'] = tcp_service
cls._set_bus(tcp_service)
else:
... | Attaches a service for hosting
:param tcp_service: A TCPService instance |
def destroy(self):
"""
Delete the page. May delete the whole document if it's actually the
last page.
"""
logger.info("Destroying page: %s" % self)
if self.doc.nb_pages <= 1:
self.doc.destroy()
return
doc_pages = self.doc.pages[:]
c... | Delete the page. May delete the whole document if it's actually the
last page. |
def paste(region, img, left, above, right, down):
"""
将扣的图粘贴到制定图片上
当你粘贴矩形选区的时候必须保证尺寸一致。此外,矩形选区不能在图像外。然而你不必保证矩形选区和原图的颜色模式一致,
因为矩形选区会被自动转换颜色,遗憾的是,只能扣矩形图。
:param region: 扣出的图
:param img: 指定图片
:param left: 左
:param above: 上
:param right: 右
:param down: 下
:return: 被修改过的图片对象,还在内存中... | 将扣的图粘贴到制定图片上
当你粘贴矩形选区的时候必须保证尺寸一致。此外,矩形选区不能在图像外。然而你不必保证矩形选区和原图的颜色模式一致,
因为矩形选区会被自动转换颜色,遗憾的是,只能扣矩形图。
:param region: 扣出的图
:param img: 指定图片
:param left: 左
:param above: 上
:param right: 右
:param down: 下
:return: 被修改过的图片对象,还在内存中,未保存。 |
def matches(self, properties):
"""
Tests if the given criterion matches this LDAP criterion
:param properties: A dictionary of properties
:return: True if the properties matches this criterion, else False
"""
try:
# Use the comparator
return self.... | Tests if the given criterion matches this LDAP criterion
:param properties: A dictionary of properties
:return: True if the properties matches this criterion, else False |
def price_dataframe(symbols='sp5002012',
start=datetime.datetime(2008, 1, 1),
end=datetime.datetime(2009, 12, 31),
price_type='actual_close',
cleaner=clean_dataframe,
):
"""Retrieve the prices of a list of equities as a DataFrame (columns = symbols)
Arguments:
symbols (list of str):... | Retrieve the prices of a list of equities as a DataFrame (columns = symbols)
Arguments:
symbols (list of str): Ticker symbols like "GOOG", "AAPL", etc
e.g. ["AAPL", " slv ", GLD", "GOOG", "$SPX", "XOM", "msft"]
start (datetime): The date at the start of the period being analyzed.
end (dat... |
def validate(self):
"""Returns whether this plugin does what it claims to have done"""
try:
response = self.client.get_access_key_last_used(
AccessKeyId=self.access_key_id
)
username = response['UserName']
access_keys = self.client.list_ac... | Returns whether this plugin does what it claims to have done |
def from_file(cls, filename, sr=22050):
""" Loads an audiofile, uses sr=22050 by default. """
y, sr = librosa.load(filename, sr=sr)
return cls(y, sr) | Loads an audiofile, uses sr=22050 by default. |
def urlencode(self):
"""
Convert dictionary into a query string; keys are
assumed to always be str
"""
output = ('%s=%s' % (k, quote(v)) for k, v in self.items())
return '&'.join(output) | Convert dictionary into a query string; keys are
assumed to always be str |
def _validate_frequency(cls, index, freq, **kwargs):
"""
Validate that a frequency is compatible with the values of a given
Datetime Array/Index or Timedelta Array/Index
Parameters
----------
index : DatetimeIndex or TimedeltaIndex
The index on which to deter... | Validate that a frequency is compatible with the values of a given
Datetime Array/Index or Timedelta Array/Index
Parameters
----------
index : DatetimeIndex or TimedeltaIndex
The index on which to determine if the given frequency is valid
freq : DateOffset
... |
def add(self, scheduler, max_iteration, bigdl_type="float"):
"""
Add a learning rate scheduler to the contained `schedules`
:param scheduler: learning rate scheduler to be add
:param max_iteration: iteration numbers this scheduler will run
"""
return callBigDlFunc(bigdl_... | Add a learning rate scheduler to the contained `schedules`
:param scheduler: learning rate scheduler to be add
:param max_iteration: iteration numbers this scheduler will run |
def create_route(self, uri, sub_service):
"""Create the route for the URI.
:param uri: string - URI to be routed
:param sub_service: boolean - is the URI for a sub-service
:returns: n/a
"""
if uri not in self.routes.keys():
logger.debug('Service ({0}): Creat... | Create the route for the URI.
:param uri: string - URI to be routed
:param sub_service: boolean - is the URI for a sub-service
:returns: n/a |
def add_nodes(self, nodes, nesting=1):
"""
Adds edges indicating the call-tree for the procedures listed in
the nodes.
"""
hopNodes = set() # nodes in this hop
hopEdges = [] # edges in this hop
# get nodes and edges for this hop
for i, n in zip(range(... | Adds edges indicating the call-tree for the procedures listed in
the nodes. |
def get_deposit_address(self, currency):
"""Get deposit address for a currency
https://docs.kucoin.com/#get-deposit-address
:param currency: Name of currency
:type currency: string
.. code:: python
address = client.get_deposit_address('NEO')
:returns: Api... | Get deposit address for a currency
https://docs.kucoin.com/#get-deposit-address
:param currency: Name of currency
:type currency: string
.. code:: python
address = client.get_deposit_address('NEO')
:returns: ApiResponse
.. code:: python
{
... |
def _recalculate_extents_and_offsets(self, index, logical_block_size):
# type: (int, int) -> Tuple[int, int]
'''
Internal method to recalculate the extents and offsets associated with
children of this directory record.
Parameters:
index - The index at which to start the... | Internal method to recalculate the extents and offsets associated with
children of this directory record.
Parameters:
index - The index at which to start the recalculation.
logical_block_size - The block size to use for comparisons.
Returns:
A tuple where the first el... |
def _build_basemap(self):
'''
Creates the map according to the input configuration
'''
if self.config['min_lon'] >= self.config['max_lon']:
raise ValueError('Upper limit of long is smaller than lower limit')
if self.config['min_lon'] >= self.config['max_lon']:
... | Creates the map according to the input configuration |
def augpath(path, augsuf='', augext='', augpref='', augdir=None, newext=None,
newfname=None, ensure=False, prefix=None, suffix=None):
"""
augments end of path before the extension.
augpath
Args:
path (str):
augsuf (str): augment filename before extension
Returns:
... | augments end of path before the extension.
augpath
Args:
path (str):
augsuf (str): augment filename before extension
Returns:
str: newpath
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> path = 'somefile.txt'
>>> au... |
def get_publisher():
"""get_publisher"""
log.info("initializing publisher")
pub = None
auth_url = ""
if FORWARD_ENDPOINT_TYPE == "redis":
auth_url = FORWARD_BROKER_URL
else:
auth_url = FORWARD_BROKER_URL
pub = Publisher(name="{}_{}".format(SOURCE, "-redis"),
... | get_publisher |
def versions(self):
""" Read versions from the table
The versions are kept in cache for the next reads.
"""
if self._versions is None:
with self.database.cursor_autocommit() as cursor:
query = """
SELECT number,
date_sta... | Read versions from the table
The versions are kept in cache for the next reads. |
def adjacency2graph(adjacency, edge_type=None, adjust=1, **kwargs):
"""Takes an adjacency list, dict, or matrix and returns a graph.
The purpose of this function is take an adjacency list (or matrix)
and return a :class:`.QueueNetworkDiGraph` that can be used with a
:class:`.QueueNetwork` instance. The... | Takes an adjacency list, dict, or matrix and returns a graph.
The purpose of this function is take an adjacency list (or matrix)
and return a :class:`.QueueNetworkDiGraph` that can be used with a
:class:`.QueueNetwork` instance. The Graph returned has the
``edge_type`` edge property set for each edge. ... |
def index_template(self, tpl):
"""
Indexes a template by `name` into the `name_to_template` dictionary.
:param tpl: The template to index
:type tpl: alignak.objects.item.Item
:return: None
"""
objcls = self.inner_class.my_type
name = getattr(tpl, 'name', ... | Indexes a template by `name` into the `name_to_template` dictionary.
:param tpl: The template to index
:type tpl: alignak.objects.item.Item
:return: None |
def add_suffix(file_path, suffix='modified', sep='_', ext=None):
"""Adds suffix to a file name seperated by an underscore and returns file path."""
return _add_suffix(file_path, suffix, sep, ext) | Adds suffix to a file name seperated by an underscore and returns file path. |
def tab(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Tap ``tab`` key for ``n`` times, with ``interval`` seconds of interval.
**中文文档**
以 ``interval`` 中定义的频率按下某个tab键 ``n`` 次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.tab_key, n, interval)
self.delay(po... | Tap ``tab`` key for ``n`` times, with ``interval`` seconds of interval.
**中文文档**
以 ``interval`` 中定义的频率按下某个tab键 ``n`` 次。 |
def paint_cube(self, x, y):
"""
Paints a cube at a certain position a color.
Parameters
----------
x: int
Horizontal position of the upper left corner of the cube.
y: int
Vertical position of the upper left corner of the cube.
"""
... | Paints a cube at a certain position a color.
Parameters
----------
x: int
Horizontal position of the upper left corner of the cube.
y: int
Vertical position of the upper left corner of the cube. |
def get_schema_validator(self, schema_name):
"""
Had to remove the id property from map.json or it uses URLs for validation
See various issues at https://github.com/Julian/jsonschema/pull/306
"""
if schema_name not in self.schemas:
schema_file = self.get_schema_file(... | Had to remove the id property from map.json or it uses URLs for validation
See various issues at https://github.com/Julian/jsonschema/pull/306 |
def turn_left():
"""turns RedBot to the Left"""
motors.left_motor(150) # spin CCW
motors.right_motor(150) # spin CCW
board.sleep(0.5)
motors.brake();
board.sleep(0.1) | turns RedBot to the Left |
def _get_leader_for_partition(self, topic, partition):
"""
Returns the leader for a partition or None if the partition exists
but has no leader.
Raises:
UnknownTopicOrPartitionError: If the topic or partition is not part
of the metadata.
LeaderNot... | Returns the leader for a partition or None if the partition exists
but has no leader.
Raises:
UnknownTopicOrPartitionError: If the topic or partition is not part
of the metadata.
LeaderNotAvailableError: If the server has metadata, but there is no
current... |
def ones_matrix_band_part(rows, cols, num_lower, num_upper, out_shape=None):
"""Matrix band part of ones.
Args:
rows: int determining number of rows in output
cols: int
num_lower: int, maximum distance backward. Negative values indicate
unlimited.
num_upper: int, maximum distance forward. Neg... | Matrix band part of ones.
Args:
rows: int determining number of rows in output
cols: int
num_lower: int, maximum distance backward. Negative values indicate
unlimited.
num_upper: int, maximum distance forward. Negative values indicate
unlimited.
out_shape: shape to reshape output by.
... |
def handle_lock_expired(
payment_state: InitiatorPaymentState,
state_change: ReceiveLockExpired,
channelidentifiers_to_channels: ChannelMap,
block_number: BlockNumber,
) -> TransitionResult[InitiatorPaymentState]:
"""Initiator also needs to handle LockExpired messages when refund tra... | Initiator also needs to handle LockExpired messages when refund transfers are involved.
A -> B -> C
- A sends locked transfer to B
- B attempted to forward to C but has not enough capacity
- B sends a refund transfer with the same secrethash back to A
- When the lock expires B will also send a Loc... |
def dp004(self, value=None):
""" Corresponds to IDD Field `dp004`
Dew-point temperature corresponding to 0.4% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `dp004`
Unit: C
if `value` is None it will not be checked... | Corresponds to IDD Field `dp004`
Dew-point temperature corresponding to 0.4% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `dp004`
Unit: C
if `value` is None it will not be checked against the
specification... |
def update_cloud_integration(self, id, **kwargs): # noqa: E501
"""Update a specific cloud integration # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_c... | Update a specific cloud integration # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_cloud_integration(id, async_req=True)
>>> result = thread.get()
... |
def set_sticker_position_in_set(self, sticker, position):
"""
Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success.
https://core.telegram.org/bots/api#setstickerpositioninset
Parameters:
:param sticker:... | Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success.
https://core.telegram.org/bots/api#setstickerpositioninset
Parameters:
:param sticker: File identifier of the sticker
:type sticker: str|unicode
... |
def tidy(args):
"""
%prog tidy agpfile componentfasta
Given an agp file, run through the following steps:
1. Trim components with dangling N's
2. Merge adjacent gaps
3. Trim gaps at the end of an object
4. Reindex the agp
Final output is in `.tidy.agp`.
"""
p = OptionParser(tid... | %prog tidy agpfile componentfasta
Given an agp file, run through the following steps:
1. Trim components with dangling N's
2. Merge adjacent gaps
3. Trim gaps at the end of an object
4. Reindex the agp
Final output is in `.tidy.agp`. |
def parse_python_version(output):
"""Parse a Python version output returned by `python --version`.
Return a dict with three keys: major, minor, and micro. Each value is a
string containing a version part.
Note: The micro part would be `'0'` if it's missing from the input string.
"""
version_li... | Parse a Python version output returned by `python --version`.
Return a dict with three keys: major, minor, and micro. Each value is a
string containing a version part.
Note: The micro part would be `'0'` if it's missing from the input string. |
def get_lines(data_nts, prtfmt=None, nt_fields=None, **kws):
"""Print list of namedtuples into a table using prtfmt."""
lines = []
# optional keyword args: prt_if sort_by
if prtfmt is None:
prtfmt = mk_fmtfld(data_nts[0], kws.get('joinchr', ' '), kws.get('eol', '\n'))
# if nt_fields arg is N... | Print list of namedtuples into a table using prtfmt. |
def encode_fetch_request(cls, client_id, correlation_id, payloads=None,
max_wait_time=100, min_bytes=4096):
"""
Encodes some FetchRequest structs
:param bytes client_id:
:param int correlation_id:
:param list payloads: list of :class:`FetchRequest`
... | Encodes some FetchRequest structs
:param bytes client_id:
:param int correlation_id:
:param list payloads: list of :class:`FetchRequest`
:param int max_wait_time: how long to block waiting on min_bytes of data
:param int min_bytes:
the minimum number of bytes to accu... |
def _convert_to_style(cls, style_dict):
"""
converts a style_dict to an openpyxl style object
Parameters
----------
style_dict : style dictionary to convert
"""
from openpyxl.style import Style
xls_style = Style()
for key, value in style_dict.item... | converts a style_dict to an openpyxl style object
Parameters
----------
style_dict : style dictionary to convert |
def setupMovie(self):
"""Setup button handler."""
if self.state == self.INIT:
self.sendRtspRequest(self.SETUP) | Setup button handler. |
def get_issuer(self):
"""
Gets the Issuer of the Logout Response Message
:return: The Issuer
:rtype: string
"""
issuer = None
issuer_nodes = self.__query('/samlp:LogoutResponse/saml:Issuer')
if len(issuer_nodes) == 1:
issuer = OneLogin_Saml2_Ut... | Gets the Issuer of the Logout Response Message
:return: The Issuer
:rtype: string |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.