code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def getprefixes(self):
"""Add prefixes for each namespace referenced by parameter types."""
namespaces = []
for l in (self.params, self.types):
for t,r in l:
ns = r.namespace()
if ns[1] is None: continue
if ns[1] in namespaces: continue... | Add prefixes for each namespace referenced by parameter types. |
def select(table, key='default'):
"""Select dialect
:param key: a key for your dabtabase you wanna use
"""
database = choice(__db[key + '.slave'])
return database.select(table) | Select dialect
:param key: a key for your dabtabase you wanna use |
def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalDelete, self).dispatch(*args, **kwargs) | This decorator sets this view to have restricted permissions. |
def evolve(self, new_date):
"""
evolve to the new process state at the next date, i.e. do one step in the simulation
:param date new_date: date of the new state
:return State:
"""
self.state = [p.evolve(new_date) for p in self.producers]
return self.state | evolve to the new process state at the next date, i.e. do one step in the simulation
:param date new_date: date of the new state
:return State: |
def run(self):
"""Lunch checks and triggers updates on BIRD configuration."""
# Lunch a thread for each configuration
if not self.services:
self.log.warning("no service checks are configured")
else:
self.log.info("going to lunch %s threads", len(self.services))
... | Lunch checks and triggers updates on BIRD configuration. |
def open_using_pefile(input_name, input_bytes):
''' Open the PE File using the Python pefile module. '''
try:
pef = pefile.PE(data=input_bytes, fast_load=False)
except (AttributeError, pefile.PEFormatError), error:
print 'warning: pe_fail (with exception from pefile modul... | Open the PE File using the Python pefile module. |
def get(self):
"""Retrieve a formated text string"""
output = ''
for f in self.functions:
output += self.underline(f) + '\n\n'
if f in self.synopsises and isinstance(self.synopsises[f], str):
output += self.format(self.synopsises[f]) + '\n'
if ... | Retrieve a formated text string |
def _space_delimited_list(value):
'''
validate that a value contains one or more space-delimited values
'''
if isinstance(value, six.string_types):
items = value.split(' ')
valid = items and all(items)
else:
valid = hasattr(value, '__iter__') and (value != [])
if valid:
... | validate that a value contains one or more space-delimited values |
def numpy_weighted_median(data, weights=None):
"""Calculate the weighted median of an array/list using numpy."""
import numpy as np
if weights is None:
return np.median(np.array(data).flatten())
data, weights = np.array(data).flatten(), np.array(weights).flatten()
if any(weights > 0):
... | Calculate the weighted median of an array/list using numpy. |
def impersonate(self, user, enterprise):
""" Impersonate a user in a enterprise
Args:
user: the name of the user to impersonate
enterprise: the name of the enterprise where to use impersonation
"""
if not user or not enterprise:
raise Val... | Impersonate a user in a enterprise
Args:
user: the name of the user to impersonate
enterprise: the name of the enterprise where to use impersonation |
def copy_foreign_keys(self, event):
"""Copies possible foreign key values from the object into the Event,
skipping common keys like modified and created.
Args:
event (Event): The Event instance to copy the FKs into
obj (fleaker.db.Model): The object to pull the values fr... | Copies possible foreign key values from the object into the Event,
skipping common keys like modified and created.
Args:
event (Event): The Event instance to copy the FKs into
obj (fleaker.db.Model): The object to pull the values from |
def parse_source_file(file_name):
"""
Parses the AST of Python file for lines containing
references to the argparse module.
returns the collection of ast objects found.
Example client code:
1. parser = ArgumentParser(desc="My help Message")
2. parser.add_argument('filename', help="Nam... | Parses the AST of Python file for lines containing
references to the argparse module.
returns the collection of ast objects found.
Example client code:
1. parser = ArgumentParser(desc="My help Message")
2. parser.add_argument('filename', help="Name of the file to load")
3. parser.add_ar... |
def _deactivate(self):
"""Remove the fetcher from cache and mark it not active."""
self.cache.remove_fetcher(self)
if self.active:
self._deactivated() | Remove the fetcher from cache and mark it not active. |
def GetAttributeNames(self):
"""Retrieves the names of all attributes.
Returns:
list[str]: attribute names.
"""
attribute_names = []
for attribute_name in iter(self.__dict__.keys()):
# Not using startswith to improve performance.
if attribute_name[0] == '_':
continue
... | Retrieves the names of all attributes.
Returns:
list[str]: attribute names. |
def yaml_conf_as_dict(file_path, encoding=None):
"""
读入 yaml 配置文件,返回根据配置文件内容生成的字典类型变量
:param:
* file_path: (string) 需要读入的 yaml 配置文件长文件名
* encoding: (string) 文件编码
* msg: (string) 读取配置信息
:return:
* flag: (bool) 读取配置文件是否正确,正确返回 True,错误返回 False
* d: (dict) 如果读取配置文件正... | 读入 yaml 配置文件,返回根据配置文件内容生成的字典类型变量
:param:
* file_path: (string) 需要读入的 yaml 配置文件长文件名
* encoding: (string) 文件编码
* msg: (string) 读取配置信息
:return:
* flag: (bool) 读取配置文件是否正确,正确返回 True,错误返回 False
* d: (dict) 如果读取配置文件正确返回的包含配置文件内容的字典,字典内容顺序与配置文件顺序保持一致
举例如下::
print(... |
def crawl(plugin):
'''Performs a breadth-first crawl of all possible routes from the
starting path. Will only visit a URL once, even if it is referenced
multiple times in a plugin. Requires user interaction in between each
fetch.
'''
# TODO: use OrderedSet?
paths_visited = set()
paths_to... | Performs a breadth-first crawl of all possible routes from the
starting path. Will only visit a URL once, even if it is referenced
multiple times in a plugin. Requires user interaction in between each
fetch. |
def _get_gos_upper(self, ntpltgo1, max_upper, go2parentids):
"""Plot a GO DAG for the upper portion of a single Group of user GOs."""
# Get GO IDs which are in the hdrgo path
goids_possible = ntpltgo1.gosubdag.go2obj.keys()
# Get upper GO IDs which have the most descendants
retur... | Plot a GO DAG for the upper portion of a single Group of user GOs. |
def docker_fabric(*args, **kwargs):
"""
:param args: Positional arguments to Docker client.
:param kwargs: Keyword arguments to Docker client.
:return: Docker client.
:rtype: dockerfabric.apiclient.DockerFabricClient | dockerfabric.cli.DockerCliClient
"""
ci = kwargs.get('client_implementati... | :param args: Positional arguments to Docker client.
:param kwargs: Keyword arguments to Docker client.
:return: Docker client.
:rtype: dockerfabric.apiclient.DockerFabricClient | dockerfabric.cli.DockerCliClient |
def _hashable_bytes(data):
"""
Coerce strings to hashable bytes.
"""
if isinstance(data, bytes):
return data
elif isinstance(data, str):
return data.encode('ascii') # Fail on anything non-ASCII.
else:
raise TypeError(data) | Coerce strings to hashable bytes. |
def displacements(self):
"""Return displacements
Returns
-------
There are two types of displacement dataset. See the docstring
of set_displacement_dataset about types 1 and 2 for displacement
dataset format.
Type-1, List of list
The internal list ha... | Return displacements
Returns
-------
There are two types of displacement dataset. See the docstring
of set_displacement_dataset about types 1 and 2 for displacement
dataset format.
Type-1, List of list
The internal list has 4 elements such as [32, 0.01, 0.0,... |
def get_sync_binding_cmds(self, switch_bindings, expected_bindings):
"""Returns the list of commands required to synchronize ACL bindings
1. Delete any unexpected bindings
2. Add any missing bindings
"""
switch_cmds = list()
# Update any necessary switch interface ACLs
... | Returns the list of commands required to synchronize ACL bindings
1. Delete any unexpected bindings
2. Add any missing bindings |
def tcl_list_2_py_list(tcl_list, within_tcl_str=False):
""" Convert Tcl list to Python list using Tcl interpreter.
:param tcl_list: string representing the Tcl string.
:param within_tcl_str: True - Tcl list is embedded within Tcl str. False - native Tcl string.
:return: Python list equivalent to the Tc... | Convert Tcl list to Python list using Tcl interpreter.
:param tcl_list: string representing the Tcl string.
:param within_tcl_str: True - Tcl list is embedded within Tcl str. False - native Tcl string.
:return: Python list equivalent to the Tcl ist.
:rtye: list |
def select_image_layer(infiles, output_file, log, context):
"""Selects the image layer for the output page. If possible this is the
orientation-corrected input page, or an image of the whole page converted
to PDF."""
options = context.get_options()
page_pdf = next(ii for ii in infiles if ii.endswit... | Selects the image layer for the output page. If possible this is the
orientation-corrected input page, or an image of the whole page converted
to PDF. |
def getSenderNumberMgtURL(self, CorpNum, UserID):
""" 팩스 전송내역 팝업 URL
args
CorpNum : 회원 사업자번호
UserID : 회원 팝빌아이디
return
30초 보안 토큰을 포함한 url
raise
PopbillException
"""
result = self._httpget('/FAX/?T... | 팩스 전송내역 팝업 URL
args
CorpNum : 회원 사업자번호
UserID : 회원 팝빌아이디
return
30초 보안 토큰을 포함한 url
raise
PopbillException |
def approximator(molecules, options, sort_order=None, frameworks=[], ensemble=[]):
"""
recursively rank queries
:param molecules:
:param options:
:param sort_order:
:param frameworks:
:param ensemble:
:return:
"""
# set variables
ensemble_size = options.ensemble_size
if... | recursively rank queries
:param molecules:
:param options:
:param sort_order:
:param frameworks:
:param ensemble:
:return: |
def delete_option_value_by_id(cls, option_value_id, **kwargs):
"""Delete OptionValue
Delete an instance of OptionValue by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_option_... | Delete OptionValue
Delete an instance of OptionValue by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_option_value_by_id(option_value_id, async=True)
>>> result = thread.get()... |
def sort_canonical(keyword, stmts):
"""Sort all `stmts` in the canonical order defined by `keyword`.
Return the sorted list. The `stmt` list is not modified.
If `keyword` does not have a canonical order, the list is returned
as is.
"""
try:
(_arg_type, subspec) = stmt_map[keyword]
... | Sort all `stmts` in the canonical order defined by `keyword`.
Return the sorted list. The `stmt` list is not modified.
If `keyword` does not have a canonical order, the list is returned
as is. |
def render_arrow(self, label, start, end, direction, i):
"""Render individual arrow.
label (unicode): Dependency label.
start (int): Index of start word.
end (int): Index of end word.
direction (unicode): Arrow direction, 'left' or 'right'.
i (int): Unique ID, typically ... | Render individual arrow.
label (unicode): Dependency label.
start (int): Index of start word.
end (int): Index of end word.
direction (unicode): Arrow direction, 'left' or 'right'.
i (int): Unique ID, typically arrow index.
RETURNS (unicode): Rendered SVG markup. |
def _get_top_level_secrets(self):
"""
Convert the top-level 'secrets' directive to the Docker format
:return: secrets dict
"""
top_level_secrets = dict()
if self.secrets:
for secret, secret_definition in iteritems(self.secrets):
if isinstance(s... | Convert the top-level 'secrets' directive to the Docker format
:return: secrets dict |
def write_file(self, fileobject, skip_unknown=False):
"""Write the PKG-INFO format data to a file object."""
self.set_metadata_version()
for field in _version2fieldlist(self['Metadata-Version']):
values = self.get(field)
if skip_unknown and values in ('UNKNOWN', [], ['UN... | Write the PKG-INFO format data to a file object. |
def _execute_comprehension(self, node: Union[ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp]) -> Any:
"""Compile the generator or comprehension from the node and execute the compiled code."""
args = [ast.arg(arg=name) for name in sorted(self._name_to_value.keys())]
func_def_node = as... | Compile the generator or comprehension from the node and execute the compiled code. |
def date(name=None):
"""
Creates the grammar for a Date (D) field, accepting only numbers in a
certain pattern.
:param name: name for the field
:return: grammar for the date field
"""
if name is None:
name = 'Date Field'
# Basic field
# This regex allows values from 000001... | Creates the grammar for a Date (D) field, accepting only numbers in a
certain pattern.
:param name: name for the field
:return: grammar for the date field |
def set_color_temperature(self, temperature, effect=EFFECT_SUDDEN, transition_time=MIN_TRANSITION_TIME):
"""
Set the white color temperature. The bulb must be switched on.
:param temperature: color temperature to set. It can be between 1700 and 6500 K
:param effect: if the c... | Set the white color temperature. The bulb must be switched on.
:param temperature: color temperature to set. It can be between 1700 and 6500 K
:param effect: if the change is made suddenly or smoothly
:param transition_time: in case the change is made smoothly, time in ms that chang... |
def output_to_terminal(sources):
"""Print statistics to the terminal"""
results = OrderedDict()
for source in sources:
if source.get_is_available():
source.update()
results.update(source.get_summary())
for key, value in results.items():
sys.stdout.write(str(key) +... | Print statistics to the terminal |
def reverse_transform(self, column):
"""Applies the natural logarithm function to turn positive values into real ranged values.
Args:
column (pandas.DataFrame): Data to transform.
Returns:
pd.DataFrame
"""
self.check_data_type()
return pd.DataFr... | Applies the natural logarithm function to turn positive values into real ranged values.
Args:
column (pandas.DataFrame): Data to transform.
Returns:
pd.DataFrame |
def link(self, mu, dist):
"""
glm link function
this is useful for going from mu to the linear prediction
Parameters
----------
mu : array-like of legth n
dist : Distribution instance
Returns
-------
lp : np.array of length n
"""
... | glm link function
this is useful for going from mu to the linear prediction
Parameters
----------
mu : array-like of legth n
dist : Distribution instance
Returns
-------
lp : np.array of length n |
def node2geoff(node_name, properties, encoder):
"""converts a NetworkX node into a Geoff string.
Parameters
----------
node_name : str or int
the ID of a NetworkX node
properties : dict
a dictionary of node attributes
encoder : json.JSONEncoder
an instance of a JSON enco... | converts a NetworkX node into a Geoff string.
Parameters
----------
node_name : str or int
the ID of a NetworkX node
properties : dict
a dictionary of node attributes
encoder : json.JSONEncoder
an instance of a JSON encoder (e.g. `json.JSONEncoder`)
Returns
-------
... |
def data(self):
"""load and cache data in json format
"""
if self.is_obsolete():
data = self.get_data()
for datum in data:
if 'published_parsed' in datum:
datum['published_parsed'] = \
self.parse_time(datum['pub... | load and cache data in json format |
def enabled(self, value):
"""
Setter for **self.__enabled** attribute.
:param value: Attribute value.
:type value: bool
"""
if value is not None:
assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("enabled", value)
self._... | Setter for **self.__enabled** attribute.
:param value: Attribute value.
:type value: bool |
def set_target(self, target):
'''
:param target: target object
'''
self.target = target
if target:
self.target.set_fuzzer(self)
return self | :param target: target object |
def _create_hashes(self,count):
"""
Breaks up our hash into slots, so we can pull them out later.
Essentially, it splits our SHA/MD5/etc into X parts.
"""
for i in range(0,count):
#Get 1/numblocks of the hash
blocksize = int(len(self.hexdigest) / count)
... | Breaks up our hash into slots, so we can pull them out later.
Essentially, it splits our SHA/MD5/etc into X parts. |
def render_tag(tag, attrs=None, content=None, close=True):
"""
Render a HTML tag
"""
builder = "<{tag}{attrs}>{content}"
if content or close:
builder += "</{tag}>"
return format_html(
builder,
tag=tag,
attrs=mark_safe(flatatt(attrs)) if attrs else "",
cont... | Render a HTML tag |
def extract_data(self, page):
"""Extract the AppNexus object or list of objects from the response"""
response_keys = set(page.keys())
uncommon_keys = response_keys - self.common_keys
for possible_data_key in uncommon_keys:
element = page[possible_data_key]
if isi... | Extract the AppNexus object or list of objects from the response |
def balance(address):
"""
Takes a single address and returns the current balance.
"""
txhistory = Address.transactions(address)
balance = 0
for i in txhistory:
if i.recipientId == address:
balance += i.amount
if i.senderId == addres... | Takes a single address and returns the current balance. |
def set(self, section, key, value):
"""
Creates the section value if it does not exists and sets the value.
Use write_config to actually set the value.
"""
if not section in self.config:
self.config.add_section(section)
self.config.set(section, key, va... | Creates the section value if it does not exists and sets the value.
Use write_config to actually set the value. |
def form_valid(self, form):
"""
Processes a valid form submittal.
:param form: the form instance.
:rtype: django.http.HttpResponse.
"""
#noinspection PyAttributeOutsideInit
self.object = form.save()
meta = getattr(self.object, '_meta')
# I... | Processes a valid form submittal.
:param form: the form instance.
:rtype: django.http.HttpResponse. |
def profile_form_factory():
"""Create a profile form."""
if current_app.config['USERPROFILES_EMAIL_ENABLED']:
return EmailProfileForm(
formdata=None,
username=current_userprofile.username,
full_name=current_userprofile.full_name,
email=current_user.email,
... | Create a profile form. |
def remove_properties_containing_None(properties_dict):
"""
removes keys from a dict those values == None
json schema validation might fail if they are set and
the type or format of the property does not match
"""
# remove empty properties - as validations may fail
new_dict = dict()
for... | removes keys from a dict those values == None
json schema validation might fail if they are set and
the type or format of the property does not match |
def replace_in_files(search, replace, depth=0, paths=None, confirm=True):
"""
Does a line-by-line search and replace, but only up to the "depth" line.
"""
# have the user select some files
if paths==None:
paths = _s.dialogs.MultipleFiles('DIS AND DAT|*.*')
if paths == []: return
fo... | Does a line-by-line search and replace, but only up to the "depth" line. |
def host_create(host, groups, interfaces, **kwargs):
'''
.. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documenta... | .. versionadded:: 2016.3.0
Create new host
.. note::
This function accepts all standard host properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
:param host: ... |
def create_app():
""" Flask application factory """
# Setup Flask and load app.config
app = Flask(__name__)
app.config.from_object(__name__+'.ConfigClass')
# Setup Flask-MongoEngine
db = MongoEngine(app)
# Define the User document.
# NB: Make sure to add flask_user UserMixin !!!
... | Flask application factory |
def _app_exec(self, package, action, params=None):
"""
meta method for all interactions with apps
:param package: name of package/app
:type package: str
:param action: the action to be executed
:type action: str
:param params: optional parameters for this action
... | meta method for all interactions with apps
:param package: name of package/app
:type package: str
:param action: the action to be executed
:type action: str
:param params: optional parameters for this action
:type params: dict
:return: None
:rtype: None |
def copy(self, tx_ins=None, tx_outs=None, lock_time=None,
expiry_height=None, tx_joinsplits=None, joinsplit_pubkey=None,
joinsplit_sig=None):
'''
OverwinterTx, ... -> OverwinterTx
Makes a copy. Allows over-writing specific pieces.
'''
return OverwinterT... | OverwinterTx, ... -> OverwinterTx
Makes a copy. Allows over-writing specific pieces. |
def _merge_patches(self):
"""Injects object patches into their original object definitions."""
for patched_item, patched_namespace in self._patch_data_by_canonical_name.values():
patched_item_base_name = self._get_base_name(patched_item.name, patched_namespace.name)
if patched_it... | Injects object patches into their original object definitions. |
def from_pyfile(cls: Type["Config"], filename: FilePath) -> "Config":
"""Create a configuration from a Python file.
.. code-block:: python
Config.from_pyfile('hypercorn_config.py')
Arguments:
filename: The filename which gives the path to the file.
"""
... | Create a configuration from a Python file.
.. code-block:: python
Config.from_pyfile('hypercorn_config.py')
Arguments:
filename: The filename which gives the path to the file. |
def _get_existing_report(self, mask, report):
"""Returns the aggregated report that matches report"""
for existing_report in self._reports:
if existing_report['namespace'] == report['namespace']:
if mask == existing_report['queryMask']:
return existing_rep... | Returns the aggregated report that matches report |
def _marker(self, lat, long, text, xmap, color=None, icon=None,
text_mark=False, style=None):
"""
Adds a marker to the default map
"""
kwargs = {}
if icon is not None:
kwargs["icon"] = icon
if color is not None:
kwargs["color"] = co... | Adds a marker to the default map |
def tokenize(self, data):
'''
Tokenize sentence.
Args:
[n-gram, n-gram, n-gram, ...]
'''
super().tokenize(data)
token_tuple_zip = self.n_gram.generate_tuple_zip(self.token, self.n)
token_list = []
self.token = ["".join(list(token_tuple)) for ... | Tokenize sentence.
Args:
[n-gram, n-gram, n-gram, ...] |
def _cleaned(_pipeline_objects):
"""Return standardized pipeline objects to be used for comparing
Remove year, month, and day components of the startDateTime so that data
pipelines with the same time of day but different days are considered
equal.
"""
pipeline_objects = copy.deepcopy(_pipeline_... | Return standardized pipeline objects to be used for comparing
Remove year, month, and day components of the startDateTime so that data
pipelines with the same time of day but different days are considered
equal. |
def simulate(self, steps, stimulus):
"""!
@brief Simulates chaotic neural network with extrnal stimulus during specified steps.
@details Stimulus are considered as a coordinates of neurons and in line with that weights
are initialized.
@param[in] steps (ui... | !
@brief Simulates chaotic neural network with extrnal stimulus during specified steps.
@details Stimulus are considered as a coordinates of neurons and in line with that weights
are initialized.
@param[in] steps (uint): Amount of steps for simulation.
@pa... |
def length(min=None, max=None):
"""
Validates that a field value's length is between the bounds given to this
validator.
"""
def validate(value):
if min and len(value) < min:
return e("{} does not have a length of at least {}", value, min)
if max and len(value) > max:
... | Validates that a field value's length is between the bounds given to this
validator. |
def reset(self, clear=False):
"""
Overridden to customize the order that the banners are printed
"""
if self._executing:
self._executing = False
self._request_info['execute'] = {}
self._reading = False
self._highlighter.highlighting_on = False
... | Overridden to customize the order that the banners are printed |
def handle_request(self, environ, start_response):
"""Handle an HTTP request from the client.
This is the entry point of the Engine.IO application, using the same
interface as a WSGI application. For the typical usage, this function
is invoked by the :class:`Middleware` instance, but it... | Handle an HTTP request from the client.
This is the entry point of the Engine.IO application, using the same
interface as a WSGI application. For the typical usage, this function
is invoked by the :class:`Middleware` instance, but it can be invoked
directly when the middleware is not us... |
def delete_policy(self, scaling_group, policy):
"""
Deletes the specified policy from the scaling group.
"""
uri = "/%s/%s/policies/%s" % (self.uri_base,
utils.get_id(scaling_group), utils.get_id(policy))
resp, resp_body = self.api.method_delete(uri) | Deletes the specified policy from the scaling group. |
def songs(self):
"""Get a listing of library songs.
Returns:
list: Song dicts.
"""
song_list = []
for chunk in self.songs_iter(page_size=49995):
song_list.extend(chunk)
return song_list | Get a listing of library songs.
Returns:
list: Song dicts. |
def models_descriptive(self):
""" list all stored models in given file.
Returns
-------
dict: {model_name: {'repr' : 'string representation, 'created': 'human readable date', ...}
"""
f = self._parent
return {name: {a: f[name].attrs[a]
for... | list all stored models in given file.
Returns
-------
dict: {model_name: {'repr' : 'string representation, 'created': 'human readable date', ...} |
def set_mode(self, controlmode, drivemode):
"""Higher level abstraction for setting the mode register. This will
set the mode according the the @controlmode and @drivemode you specify.
@controlmode and @drivemode should come from the ControlMode and DriveMode
class respectively."""
... | Higher level abstraction for setting the mode register. This will
set the mode according the the @controlmode and @drivemode you specify.
@controlmode and @drivemode should come from the ControlMode and DriveMode
class respectively. |
def parameters(self, parameters):
"""Setter method; for a description see the getter method."""
# pylint: disable=attribute-defined-outside-init
self._parameters = NocaseDict()
if parameters:
try:
# This is used for iterables:
iterator = parame... | Setter method; for a description see the getter method. |
def validate_url(url):
"""Validate URL is valid
NOTE: only support http & https
"""
schemes = ['http', 'https']
netloc_re = re.compile(
r'^'
r'(?:\S+(?::\S*)?@)?' # user:pass auth
r'(?:[a-z0-9]|[a-z0-9][a-z0-9\-]{0,61}[a-z0-9])'
r'(?:\.(?:[a-z0-9]|[a-z0-9][a-z0-9\-]... | Validate URL is valid
NOTE: only support http & https |
def from_geo(geo, level):
"""
Constucts a quadkey representation from geo and level
geo => (lat, lon)
If lat or lon are outside of bounds, they will be clipped
If level is outside of bounds, an AssertionError is raised
"""
pixel = TileSystem.geo_to_pixel(geo, level)
tile = TileSystem.pi... | Constucts a quadkey representation from geo and level
geo => (lat, lon)
If lat or lon are outside of bounds, they will be clipped
If level is outside of bounds, an AssertionError is raised |
def _server_error_handler(self, code: int):
"""处理500~599段状态码,抛出对应警告.
Parameters:
(code): - 响应的状态码
Return:
(bool): - 已知的警告类型则返回True,否则返回False
Raise:
(ServerException): - 当返回为服务异常时则抛出对应异常
"""
if code == 501:
self._login_fu... | 处理500~599段状态码,抛出对应警告.
Parameters:
(code): - 响应的状态码
Return:
(bool): - 已知的警告类型则返回True,否则返回False
Raise:
(ServerException): - 当返回为服务异常时则抛出对应异常 |
def cli(file1, file2, comments) -> int:
""" Compare file1 to file2 using a filter """
sys.exit(compare_files(file1, file2, comments)) | Compare file1 to file2 using a filter |
def _generate_packets(file_h, header, layers=0):
"""
Read packets one by one from the capture file. Expects the file
handle to point to the location immediately after the header (24
bytes).
"""
hdrp = ctypes.pointer(header)
while True:
pkt = _read_a_packet(file_h, hdrp, layers)
... | Read packets one by one from the capture file. Expects the file
handle to point to the location immediately after the header (24
bytes). |
def init_blueprint(self, blueprint):
"""Initialize a Flask Blueprint, similar to init_app, but without the access
to the application config.
Keyword Arguments:
blueprint {Flask Blueprint} -- Flask Blueprint instance to initialize (Default: {None})
"""
if self._route i... | Initialize a Flask Blueprint, similar to init_app, but without the access
to the application config.
Keyword Arguments:
blueprint {Flask Blueprint} -- Flask Blueprint instance to initialize (Default: {None}) |
def get_info_content(go_id, termcounts):
'''
Calculates the information content of a GO term.
'''
# Get the observed frequency of the GO term
freq = termcounts.get_term_freq(go_id)
# Calculate the information content (i.e., -log("freq of GO term")
return -1.0 * math.log(freq) if freq el... | Calculates the information content of a GO term. |
def create_capitan_images(self, raw_data_directory: str,
destination_directory: str,
stroke_thicknesses: List[int]) -> None:
"""
Creates a visual representation of the Capitan strokes by parsing all text-files and the symbols as specified
... | Creates a visual representation of the Capitan strokes by parsing all text-files and the symbols as specified
by the parameters by drawing lines that connect the points from each stroke of each symbol.
:param raw_data_directory: The directory, that contains the raw capitan dataset
:param destin... |
def __make_response(self, data, default_renderer=None):
"""
Creates a Flask response object from the specified data.
The appropriated encoder is taken based on the request header Accept.
If there is not data to be serialized the response status code is 204.
:param data: The Pyth... | Creates a Flask response object from the specified data.
The appropriated encoder is taken based on the request header Accept.
If there is not data to be serialized the response status code is 204.
:param data: The Python object to be serialized.
:return: A Flask response object. |
def update_variant(self, variant_obj):
"""Update one variant document in the database.
This means that the variant in the database will be replaced by variant_obj.
Args:
variant_obj(dict)
Returns:
new_variant(dict)
"""
LOG.debug('Updating varian... | Update one variant document in the database.
This means that the variant in the database will be replaced by variant_obj.
Args:
variant_obj(dict)
Returns:
new_variant(dict) |
def _get_or_create_service_key(self):
"""
Get a service key or create one if needed.
"""
keys = self.service._get_service_keys(self.name)
for key in keys['resources']:
if key['entity']['name'] == self.service_name:
return self.service.get_service_key(s... | Get a service key or create one if needed. |
def check_var_coverage_content_type(self, ds):
'''
Check coverage content type against valid ISO-19115-1 codes
:param netCDF4.Dataset ds: An open netCDF dataset
'''
results = []
for variable in cfutil.get_geophysical_variables(ds):
msgs = []
ctype... | Check coverage content type against valid ISO-19115-1 codes
:param netCDF4.Dataset ds: An open netCDF dataset |
def QA_fetch_stock_full(date, format='numpy', collections=DATABASE.stock_day):
'获取全市场的某一日的数据'
Date = str(date)[0:10]
if QA_util_date_valid(Date) is True:
__data = []
for item in collections.find({
"date_stamp": QA_util_date_stamp(Date)}, batch_size=10000):
__data... | 获取全市场的某一日的数据 |
def export(self, directory):
"""Exports the ConnectorDB user into the given directory.
The resulting export can be imported by using the import command(cdb.import(directory)),
Note that Python cannot export passwords, since the REST API does
not expose password hashes. Therefore, the im... | Exports the ConnectorDB user into the given directory.
The resulting export can be imported by using the import command(cdb.import(directory)),
Note that Python cannot export passwords, since the REST API does
not expose password hashes. Therefore, the imported user will have
password s... |
def pop(self, index=-1):
"""
Remove and return item at *index* (default last). Raises IndexError if
set is empty or index is out of range. Negative indexes are supported,
as for slice indices.
"""
# pylint: disable=arguments-differ
value = self._list.pop(index)
... | Remove and return item at *index* (default last). Raises IndexError if
set is empty or index is out of range. Negative indexes are supported,
as for slice indices. |
def learnTransitions(self):
"""
Train the location layer to do path integration. For every location, teach
it each previous-location + motor command pair.
"""
print "Learning transitions"
for (i, j), locationSDR in self.locations.iteritems():
print "i, j", (i, j)
for (di, dj), trans... | Train the location layer to do path integration. For every location, teach
it each previous-location + motor command pair. |
def get_default_config(self):
"""
Return the default config for the handler
"""
config = super(GraphitePickleHandler, self).get_default_config()
config.update({
'port': 2004,
})
return config | Return the default config for the handler |
def company_vat(self):
"""
Returns 10 character tax identification number,
Polish: Numer identyfikacji podatkowej.
https://pl.wikipedia.org/wiki/NIP
"""
vat_digits = []
for _ in range(3):
vat_digits.append(self.random_digit_not_null())
for _... | Returns 10 character tax identification number,
Polish: Numer identyfikacji podatkowej.
https://pl.wikipedia.org/wiki/NIP |
def read(self, len=1024, buffer=None):
"""Read data from connection
Read up to len bytes and return them.
Arguments:
len -- maximum number of bytes to read
Return value:
string containing read bytes
"""
try:
return self._wrap_socket_library_... | Read data from connection
Read up to len bytes and return them.
Arguments:
len -- maximum number of bytes to read
Return value:
string containing read bytes |
def list(self, url_components=()):
"""
Send list request for all members of a collection
"""
resp = self.get(url_components)
return resp.get(self.result_key, []) | Send list request for all members of a collection |
def getFoundIn(self, foundin_name, projectarea_id=None,
projectarea_name=None, archived=False):
"""Get :class:`rtcclient.models.FoundIn` object by its name
:param foundin_name: the foundin name
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
... | Get :class:`rtcclient.models.FoundIn` object by its name
:param foundin_name: the foundin name
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the project area name
:param archived: (default is False) whether the foundin is ... |
def group_audit_ranks(filenames, measurer, similarity_bound=0.05):
"""
Given a list of audit files, rank them using the `measurer` and
return the features that never deviate more than `similarity_bound`
across repairs.
"""
def _partition_groups(feature_scores):
groups = []
for feature, score in fea... | Given a list of audit files, rank them using the `measurer` and
return the features that never deviate more than `similarity_bound`
across repairs. |
def key_press(self, key, x, y):
"Close the application when the player presses ESCAPE"
if ord(key) == 27:
# print "Escape!"
if bool(glutLeaveMainLoop):
glutLeaveMainLoop()
else:
raise Exception("Application quit") | Close the application when the player presses ESCAPE |
def parseAnchorName(
anchorName,
markPrefix=MARK_PREFIX,
ligaSeparator=LIGA_SEPARATOR,
ligaNumRE=LIGA_NUM_RE,
ignoreRE=None,
):
"""Parse anchor name and return a tuple that specifies:
1) whether the anchor is a "mark" anchor (bool);
2) the "key" name of the anchor, i.e. the name after st... | Parse anchor name and return a tuple that specifies:
1) whether the anchor is a "mark" anchor (bool);
2) the "key" name of the anchor, i.e. the name after stripping all the
prefixes and suffixes, which identifies the class it belongs to (str);
3) An optional number (int), starting from 1, which ident... |
def arp_ip(opcode, src_mac, src_ip, dst_mac, dst_ip):
"""A convenient wrapper for IPv4 ARP for Ethernet.
This is an equivalent of the following code.
arp(ARP_HW_TYPE_ETHERNET, ether.ETH_TYPE_IP, \
6, 4, opcode, src_mac, src_ip, dst_mac, dst_ip)
"""
return arp(ARP_HW_TYPE_ETHERNE... | A convenient wrapper for IPv4 ARP for Ethernet.
This is an equivalent of the following code.
arp(ARP_HW_TYPE_ETHERNET, ether.ETH_TYPE_IP, \
6, 4, opcode, src_mac, src_ip, dst_mac, dst_ip) |
def get_yes_no(self, question):
"""Checks if question is yes (True) or no (False)
:param question: Question to ask user
:return: User answer
"""
user_answer = self.get_answer(question).lower()
if user_answer in self.yes_input:
return True
if user_ans... | Checks if question is yes (True) or no (False)
:param question: Question to ask user
:return: User answer |
def request(self, name, *args, **kwargs):
"""Wrapper for nvim.request."""
return self._session.request(name, self, *args, **kwargs) | Wrapper for nvim.request. |
def __retry_session(self, retries=10, backoff_factor=0.3,
status_forcelist=(500, 502, 504),
session=None):
"""
Retry the connection using requests if it fails. Use this as a wrapper
to request from datapoint
"""
# requests.Session ... | Retry the connection using requests if it fails. Use this as a wrapper
to request from datapoint |
def open_url_in_browser(url, browsername=None, fallback=False):
r"""
Opens a url in the specified or default browser
Args:
url (str): web url
CommandLine:
python -m utool.util_grabdata --test-open_url_in_browser
Example:
>>> # DISABLE_DOCTEST
>>> # SCRIPT
>... | r"""
Opens a url in the specified or default browser
Args:
url (str): web url
CommandLine:
python -m utool.util_grabdata --test-open_url_in_browser
Example:
>>> # DISABLE_DOCTEST
>>> # SCRIPT
>>> from utool.util_grabdata import * # NOQA
>>> url = 'http... |
def putcell(self, rownr, value):
"""Put a value into one or more table cells.
(see :func:`table.putcell`)"""
return self._table.putcell(self._column, rownr, value) | Put a value into one or more table cells.
(see :func:`table.putcell`) |
def array(self):
"""Get all resources and return the result as an array
Returns:
array of str: Array of resources
"""
url = "{}/{}".format(__endpoint__, self.type.RESOURCE)
return RestClient.get(url, self.params)[self.type.RESOURCE] | Get all resources and return the result as an array
Returns:
array of str: Array of resources |
def search(self, filters=None, fields=None, limit=None, page=1):
"""
Retrieve order list by options using search api. Using this result can
be paginated
:param options: Dictionary of options.
:param filters: `{<attribute>:{<operator>:<value>}}`
:param fields: [<String: ... | Retrieve order list by options using search api. Using this result can
be paginated
:param options: Dictionary of options.
:param filters: `{<attribute>:{<operator>:<value>}}`
:param fields: [<String: magento field names>, ...]
:param limit: `page limit`
:param page: `c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.