code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def flush(self):
# type: () -> BatchClient
"""Send buffered metrics in batch requests"""
address = self.remote_address
while len(self._batches) > 0:
self._socket.sendto(self._batches[0], address)
self._batches.popleft()
return self | Send buffered metrics in batch requests |
def fetch_raw(self):
"""
Execute the query and return by batches.
Optional keyword arguments are passed to Query.execute(). Whether
this is real-time or stored logs is dependent on the value of
``fetch_type``.
:return: generator of dict results
"""
... | Execute the query and return by batches.
Optional keyword arguments are passed to Query.execute(). Whether
this is real-time or stored logs is dependent on the value of
``fetch_type``.
:return: generator of dict results |
def response_handler(msg: Dict[str, str]) -> None:
"""Handle response sent by browser."""
from wdom.document import getElementByWdomId
id = msg['id']
elm = getElementByWdomId(id)
if elm:
elm.on_response(msg)
else:
logger.warning('No such element: wdom_id={}'.format(id)) | Handle response sent by browser. |
def estimate_noiseperbl(data):
""" Takes large data array and sigma clips it to find noise per bl for input to detect_bispectra.
Takes mean across pols and channels for now, as in detect_bispectra.
"""
# define noise per baseline for data seen by detect_bispectra or image
datamean = data.mean(a... | Takes large data array and sigma clips it to find noise per bl for input to detect_bispectra.
Takes mean across pols and channels for now, as in detect_bispectra. |
def worker(self):
"""
Calculates the quartet weights for the test at a random
subsampled chunk of loci.
"""
## subsample loci
fullseqs = self.sample_loci()
## find all iterations of samples for this quartet
liters = itertools.product(*self.imap.values())
## run tree inference fo... | Calculates the quartet weights for the test at a random
subsampled chunk of loci. |
def from_config(cls, config, name, section_key="score_caches"):
"""
score_caches:
redis_sentinel:
class: ores.score_caches.RedisSentinel
prefix: ores-derp
ttl: 9001
socket_timeout: 0.1
cluster: mymaster
... | score_caches:
redis_sentinel:
class: ores.score_caches.RedisSentinel
prefix: ores-derp
ttl: 9001
socket_timeout: 0.1
cluster: mymaster
hosts:
- localhost:5000
- localhost:5001
... |
def most_probable_alleles(allele_list):
"""
This module accepts a list of tuples of (allele, p_value) pairs. It returns the 2 most probable
alleles for that group.
"""
all_alleles = defaultdict()
# First collect all the keys. Make a dict with allele as key and list of pvalues as value
for a... | This module accepts a list of tuples of (allele, p_value) pairs. It returns the 2 most probable
alleles for that group. |
def package_info(pkg_name):
"""Prints the information of a package.
Args:
pkg_name (str): The name of the desired package to get information
"""
indent = " "
for config, _ in _iter_packages():
if pkg_name == config["name"]:
print("Package:", pkg_name)
print(... | Prints the information of a package.
Args:
pkg_name (str): The name of the desired package to get information |
def line(self, plunge, bearing, *args, **kwargs):
"""
Plot points representing linear features on the axes. Additional
arguments and keyword arguments are passed on to `plot`.
Parameters
----------
plunge, bearing : number or sequence of numbers
The plunge an... | Plot points representing linear features on the axes. Additional
arguments and keyword arguments are passed on to `plot`.
Parameters
----------
plunge, bearing : number or sequence of numbers
The plunge and bearing of the line(s) in degrees. The plunge is
measur... |
def variance(numbers, type='population'):
"""
Calculates the population or sample variance of a list of numbers.
A large number means the results are all over the place, while a
small number means the results are comparatively close to the average.
Args:
numbers: a list of integers or floa... | Calculates the population or sample variance of a list of numbers.
A large number means the results are all over the place, while a
small number means the results are comparatively close to the average.
Args:
numbers: a list of integers or floating point numbers to compare.
type: string, ... |
def domain(value,
allow_empty = False,
allow_ips = False,
**kwargs):
"""Validate that ``value`` is a valid domain name.
.. caution::
This validator does not verify that ``value`` **exists** as a domain. It
merely verifies that its contents *might* exist as a domain... | Validate that ``value`` is a valid domain name.
.. caution::
This validator does not verify that ``value`` **exists** as a domain. It
merely verifies that its contents *might* exist as a domain.
.. note::
This validator checks to validate that ``value`` resembles a valid
domain name.... |
def calcTightAnchors(args, d, patches):
"""
Recursively generates the number of anchor points specified in the
patches argument, such that all patches are d cells away
from their nearest neighbors.
"""
centerPoint = (int(args.worldSize/2), int(args.worldSize/2))
anchors = []
if patches =... | Recursively generates the number of anchor points specified in the
patches argument, such that all patches are d cells away
from their nearest neighbors. |
def create_conf_file (self):
"""Create configuration file."""
cmd_obj = self.distribution.get_command_obj("install")
cmd_obj.ensure_finalized()
# we have to write a configuration file because we need the
# <install_data> directory (and other stuff like author, url, ...)
#... | Create configuration file. |
def _set_config(c):
"""Set gl configuration for GLFW """
glfw.glfwWindowHint(glfw.GLFW_RED_BITS, c['red_size'])
glfw.glfwWindowHint(glfw.GLFW_GREEN_BITS, c['green_size'])
glfw.glfwWindowHint(glfw.GLFW_BLUE_BITS, c['blue_size'])
glfw.glfwWindowHint(glfw.GLFW_ALPHA_BITS, c['alpha_size'])
glfw.glf... | Set gl configuration for GLFW |
def video_in_option(self, param, profile='Day'):
"""
Return video input option.
Params:
param - parameter, such as 'DayNightColor'
profile - 'Day', 'Night' or 'Normal'
"""
if profile == 'Day':
field = param
else:
field = '{... | Return video input option.
Params:
param - parameter, such as 'DayNightColor'
profile - 'Day', 'Night' or 'Normal' |
def open(self):
""" Open connection.
"""
# Only connect once
if self._rpc is not None:
return self._rpc
# Get connection URL from rtorrent.rc
self.load_config()
# Reading abilities are on the downfall, so...
if not config.scgi_url:
... | Open connection. |
def convert_table(self, markup):
""" Subtitutes <table> content to Wikipedia markup.
"""
for table in re.findall(self.re["html-table"], markup):
wiki = table
wiki = re.sub(r"<table(.*?)>", "{|\\1", wiki)
wiki = re.sub(r"<tr(.*?)>", "|-\\1", w... | Subtitutes <table> content to Wikipedia markup. |
def merge(self, schema):
"""
Merge the contents from the schema. Only objects not already contained
in this schema's collections are merged. This is to provide for
bidirectional import which produce cyclic includes.
@returns: self
@rtype: L{Schema}
"""
f... | Merge the contents from the schema. Only objects not already contained
in this schema's collections are merged. This is to provide for
bidirectional import which produce cyclic includes.
@returns: self
@rtype: L{Schema} |
def _setup_redis(self):
"""Returns a Redis Client"""
if not self.closed:
try:
self.logger.debug("Creating redis connection to host " +
str(self.settings['REDIS_HOST']))
self.redis_conn = redis.StrictRedis(host=self.settings['R... | Returns a Redis Client |
def convert_column(data, schemae):
"""Convert known types from primitive to rich."""
ctype = schemae.converted_type
if ctype == parquet_thrift.ConvertedType.DECIMAL:
scale_factor = Decimal("10e-{}".format(schemae.scale))
if schemae.type == parquet_thrift.Type.INT32 or schemae.type == parquet... | Convert known types from primitive to rich. |
def _add_scheme():
"""
urllib.parse doesn't support the mongodb scheme, but it's easy
to make it so.
"""
lists = [
urllib.parse.uses_relative,
urllib.parse.uses_netloc,
urllib.parse.uses_query,
]
for l in lists:
l.append('mongodb') | urllib.parse doesn't support the mongodb scheme, but it's easy
to make it so. |
def get_body_region(defined):
"""Return the start and end offsets of function body"""
scope = defined.get_scope()
pymodule = defined.get_module()
lines = pymodule.lines
node = defined.get_ast()
start_line = node.lineno
if defined.get_doc() is None:
start_line = node.body[0].lineno
... | Return the start and end offsets of function body |
def delta_crl_distribution_points(self):
"""
Returns delta CRL URLs - only applies to complete CRLs
:return:
A list of zero or more DistributionPoint objects
"""
if self._delta_crl_distribution_points is None:
self._delta_crl_distribution_points = []
... | Returns delta CRL URLs - only applies to complete CRLs
:return:
A list of zero or more DistributionPoint objects |
def on_train_begin(self, **kwargs:Any)->None:
"Initializes the best value."
self.best = float('inf') if self.operator == np.less else -float('inf') | Initializes the best value. |
def get_selected_subassistant_path(self, **kwargs):
"""Recursively searches self._tree - has format of (Assistant: [list_of_subassistants]) -
for specific path from first to last selected subassistants.
Args:
kwargs: arguments containing names of the given assistants in form of
... | Recursively searches self._tree - has format of (Assistant: [list_of_subassistants]) -
for specific path from first to last selected subassistants.
Args:
kwargs: arguments containing names of the given assistants in form of
subassistant_0 = 'name', subassistant_1 = 'another_name... |
def _browser_init(self):
"""
Init the browsing instance if not setup
:rtype: None
"""
if self.session:
return
self.session = requests.Session()
headers = {}
if self.user_agent:
headers['User-agent'] = self.user_agent
self... | Init the browsing instance if not setup
:rtype: None |
def readShocks(self):
'''
Reads values of shock variables for the current period from history arrays. For each var-
iable X named in self.shock_vars, this attribute of self is set to self.X_hist[self.t_sim,:].
This method is only ever called if self.read_shocks is True. This can be ac... | Reads values of shock variables for the current period from history arrays. For each var-
iable X named in self.shock_vars, this attribute of self is set to self.X_hist[self.t_sim,:].
This method is only ever called if self.read_shocks is True. This can be achieved by using
the method makeSho... |
def getFingerprintForExpression(self, body, sparsity=1.0):
"""Resolve an expression
Args:
body, ExpressionOperation: The JSON encoded expression to be evaluated (required)
sparsity, float: Sparsify the resulting expression to this percentage (optional)
Returns:
... | Resolve an expression
Args:
body, ExpressionOperation: The JSON encoded expression to be evaluated (required)
sparsity, float: Sparsify the resulting expression to this percentage (optional)
Returns:
Fingerprint
Raises:
CorticalioException: if the ... |
def ray_triangle_id(triangles,
ray_origins,
ray_directions,
triangles_normal=None,
tree=None,
multiple_hits=True):
"""
Find the intersections between a group of triangles and rays
Parameters
------------... | Find the intersections between a group of triangles and rays
Parameters
-------------
triangles : (n, 3, 3) float
Triangles in space
ray_origins : (m, 3) float
Ray origin points
ray_directions : (m, 3) float
Ray direction vectors
triangles_normal : (n, 3) float
Normal ve... |
def register_service(cls, service):
"""Add a service to the thread's StackInABox instance.
:param service: StackInABoxService instance to add to the test
For return value and errors see StackInABox.register()
"""
logger.debug('Registering service {0}'.format(service.name))
... | Add a service to the thread's StackInABox instance.
:param service: StackInABoxService instance to add to the test
For return value and errors see StackInABox.register() |
def _import_astorb_to_database(
self,
astorbDictList):
"""*import the astorb orbital elements to database*
**Key Arguments:**
- ``astorbDictList`` -- the astorb database parsed as a list of dictionaries
**Return:**
- None
"""
self... | *import the astorb orbital elements to database*
**Key Arguments:**
- ``astorbDictList`` -- the astorb database parsed as a list of dictionaries
**Return:**
- None |
def persist(self):
"""
Banana banana
"""
os.makedirs(self.__symbol_folder, exist_ok=True)
os.makedirs(self.__aliases_folder, exist_ok=True)
os.makedirs(self.__comments_folder, exist_ok=True)
for name, sym in self.__symbols.items():
with open(self.__get... | Banana banana |
def thumbnail(self):
"""Path to the thumbnail of the album."""
if self._thumbnail:
# stop if it is already set
return self._thumbnail
# Test the thumbnail from the Markdown file.
thumbnail = self.meta.get('thumbnail', [''])[0]
if thumbnail and isfile(jo... | Path to the thumbnail of the album. |
def parse(self):
"""Parse a Supybot IRC stream.
Returns an iterator of dicts. Each dicts contains information
about the date, type, nick and body of a single log entry.
:returns: iterator of parsed lines
:raises ParseError: when an invalid line is found parsing the given
... | Parse a Supybot IRC stream.
Returns an iterator of dicts. Each dicts contains information
about the date, type, nick and body of a single log entry.
:returns: iterator of parsed lines
:raises ParseError: when an invalid line is found parsing the given
stream |
def compact_bucket(db, buck_key, limit):
"""
Perform the compaction operation. This reads in the bucket
information from the database, builds a compacted bucket record,
inserts that record in the appropriate place in the database, then
removes outdated updates.
:param db: A database handle for... | Perform the compaction operation. This reads in the bucket
information from the database, builds a compacted bucket record,
inserts that record in the appropriate place in the database, then
removes outdated updates.
:param db: A database handle for the Redis database.
:param buck_key: A turnstile... |
def fetch(self):
"""
Fetch this student's courses page. It's recommended to do that when
creating the object (this is the default) because the remote sessions
are short.
"""
soup = self.session.get_results_soup()
self.courses = CoursesList(soup) | Fetch this student's courses page. It's recommended to do that when
creating the object (this is the default) because the remote sessions
are short. |
def hdfFromKwargs(hdf=None, **kwargs):
"""If given an instance that has toHDF() method that method is invoked to get that object's HDF representation"""
if not hdf:
hdf = HDF()
for key, value in kwargs.iteritems():
if isinstance(value, dict):
#print "dict:",value
for ... | If given an instance that has toHDF() method that method is invoked to get that object's HDF representation |
def set_confound_pipeline(self, confound_pipeline):
"""
There may be times when the pipeline is updated (e.g. teneto) but you want the confounds from the preprocessing pipieline (e.g. fmriprep).
To do this, you set the confound_pipeline to be the preprocessing pipeline where the confound files a... | There may be times when the pipeline is updated (e.g. teneto) but you want the confounds from the preprocessing pipieline (e.g. fmriprep).
To do this, you set the confound_pipeline to be the preprocessing pipeline where the confound files are.
Parameters
----------
confound_pipeline : ... |
def rest(o) -> Optional[ISeq]:
"""If o is a ISeq, return the elements after the first in o. If o is None,
returns an empty seq. Otherwise, coerces o to a seq and returns the rest."""
if o is None:
return None
if isinstance(o, ISeq):
s = o.rest
if s is None:
return lse... | If o is a ISeq, return the elements after the first in o. If o is None,
returns an empty seq. Otherwise, coerces o to a seq and returns the rest. |
def get_coords(x, y, params):
"""
Transforms the given coordinates from plane-space to Mandelbrot-space (real and imaginary).
:param x: X coordinate on the plane.
:param y: Y coordinate on the plane.
:param params: Current application parameters.
:type params: params.Params
:return: Tuple c... | Transforms the given coordinates from plane-space to Mandelbrot-space (real and imaginary).
:param x: X coordinate on the plane.
:param y: Y coordinate on the plane.
:param params: Current application parameters.
:type params: params.Params
:return: Tuple containing the re-mapped coordinates in Man... |
def read_entity(self, entity_id, mount_point=DEFAULT_MOUNT_POINT):
"""Query an entity by its identifier.
Supported methods:
GET: /auth/{mount_point}/entity/id/{id}. Produces: 200 application/json
:param entity_id: Identifier of the entity.
:type entity_id: str
:para... | Query an entity by its identifier.
Supported methods:
GET: /auth/{mount_point}/entity/id/{id}. Produces: 200 application/json
:param entity_id: Identifier of the entity.
:type entity_id: str
:param mount_point: The "path" the secret engine was mounted on.
:type moun... |
def decompress(images, delete_png=False, delete_json=False, folder=None):
"""Reverse compression from tif to png and save them in original format
(ome.tif). TIFF-tags are gotten from json-files named the same as given
images.
Parameters
----------
images : list of filenames
Image to de... | Reverse compression from tif to png and save them in original format
(ome.tif). TIFF-tags are gotten from json-files named the same as given
images.
Parameters
----------
images : list of filenames
Image to decompress.
delete_png : bool
Wheter to delete PNG images.
delete_j... |
def add_line_to_file(self, line, filename, expect=None, shutit_pexpect_child=None, match_regexp=None, loglevel=logging.DEBUG):
"""Deprecated.
Use replace/insert_text instead.
Adds line to file if it doesn't exist (unless Force is set, which it is not by default).
Creates the file if it doesn't exist.
Must b... | Deprecated.
Use replace/insert_text instead.
Adds line to file if it doesn't exist (unless Force is set, which it is not by default).
Creates the file if it doesn't exist.
Must be exactly the line passed in to match.
Returns True if line(s) added OK, False if not.
If you have a lot of non-unique lines to ... |
def listfolder(p):
"""
generator of list folder in the path.
folders only
"""
for entry in scandir.scandir(p):
if entry.is_dir():
yield entry.name | generator of list folder in the path.
folders only |
def handler_view(self, request, resource_name, ids=None):
""" Handler for resources.
.. versionadded:: 0.5.7
Content-Type check
:return django.http.HttpResponse
"""
signal_request.send(sender=self, request=request)
time_start = time.time()
self.upda... | Handler for resources.
.. versionadded:: 0.5.7
Content-Type check
:return django.http.HttpResponse |
def psicomputations(variance, Z, variational_posterior, return_psi2_n=False):
"""
Compute psi-statistics for ss-linear kernel
"""
# here are the "statistics" for psi0, psi1 and psi2
# Produced intermediate results:
# psi0 N
# psi1 NxM
# psi2 MxM
mu = variational_posterior.me... | Compute psi-statistics for ss-linear kernel |
def subscribe(self, sr):
"""Login required. Send POST to subscribe to a subreddit. If ``sr`` is the name of the subreddit, a GET request is sent to retrieve the full id of the subreddit, which is necessary for this API call. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value ... | Login required. Send POST to subscribe to a subreddit. If ``sr`` is the name of the subreddit, a GET request is sent to retrieve the full id of the subreddit, which is necessary for this API call. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: `... |
def resource(self, api_path=None, base_path='/api/now', chunk_size=None):
"""Overrides :meth:`resource` provided by :class:`pysnow.Client` with extras for OAuth
:param api_path: Path to the API to operate on
:param base_path: (optional) Base path override
:param chunk_size: Response str... | Overrides :meth:`resource` provided by :class:`pysnow.Client` with extras for OAuth
:param api_path: Path to the API to operate on
:param base_path: (optional) Base path override
:param chunk_size: Response stream parser chunk size (in bytes)
:return:
- :class:`Resource` obj... |
def gen_etree(self):
"""convert an RST tree (DGParentedTree -> lxml etree)"""
relations_elem = self.gen_relations()
header = E('header')
header.append(relations_elem)
self.gen_body()
tree = E('rst')
tree.append(header)
# The <body> contains both <segmen... | convert an RST tree (DGParentedTree -> lxml etree) |
def repeat(col, n):
"""
Repeats a string column n times, and returns it as a new string column.
>>> df = spark.createDataFrame([('ab',)], ['s',])
>>> df.select(repeat(df.s, 3).alias('s')).collect()
[Row(s=u'ababab')]
"""
sc = SparkContext._active_spark_context
return Column(sc._jvm.func... | Repeats a string column n times, and returns it as a new string column.
>>> df = spark.createDataFrame([('ab',)], ['s',])
>>> df.select(repeat(df.s, 3).alias('s')).collect()
[Row(s=u'ababab')] |
def rename_pool(service, old_name, new_name):
"""
Rename a Ceph pool from old_name to new_name
:param service: six.string_types. The Ceph user name to run the command under
:param old_name: six.string_types
:param new_name: six.string_types
:return: None
"""
validator(value=old_name, val... | Rename a Ceph pool from old_name to new_name
:param service: six.string_types. The Ceph user name to run the command under
:param old_name: six.string_types
:param new_name: six.string_types
:return: None |
def register(cls, config={}):
"""
This function is basically a shortcut of boot for accessors
that have only the config dict argument.
Args
----
config (dict): the configuration dictionary
"""
if cls.accessor is not None:
if cls.instance is ... | This function is basically a shortcut of boot for accessors
that have only the config dict argument.
Args
----
config (dict): the configuration dictionary |
def service_running(service_name, **kwargs):
"""Determine whether a system service is running.
:param service_name: the name of the service
:param **kwargs: additional args to pass to the service command. This is
used to pass additional key=value arguments to the
s... | Determine whether a system service is running.
:param service_name: the name of the service
:param **kwargs: additional args to pass to the service command. This is
used to pass additional key=value arguments to the
service command line for managing specific instance
... |
def read(self):
"""Reads record from current position in reader.
Returns:
original bytes stored in a single record.
"""
data = None
while True:
last_offset = self.tell()
try:
(chunk, record_type) = self.__try_read_record()
if record_type == _RECORD_TYPE_NONE:
... | Reads record from current position in reader.
Returns:
original bytes stored in a single record. |
def get_subnets_for_net(self, net):
"""Returns the subnets in a network. """
try:
subnet_list = self.neutronclient.list_subnets(network_id=net)
subnet_dat = subnet_list.get('subnets')
return subnet_dat
except Exception as exc:
LOG.error("Failed to ... | Returns the subnets in a network. |
async def get_access_token(consumer_key, consumer_secret,
oauth_token, oauth_token_secret,
oauth_verifier, **kwargs):
"""
get the access token of the user
Parameters
----------
consumer_key : str
Your consumer key
consumer_secret... | get the access token of the user
Parameters
----------
consumer_key : str
Your consumer key
consumer_secret : str
Your consumer secret
oauth_token : str
OAuth token from :func:`get_oauth_token`
oauth_token_secret : str
OAuth token secret from :func:`get_oauth_tok... |
def create_pipeline(self, name, description, **kwargs):
'''Creates a pipeline with the provided attributes.
Args:
name required name string
kwargs {name, description, orgWide, aclEntries} user
specifiable ones only
return (status code, pipeline_dict) (as created)
'''
#req sanity check
if not (nam... | Creates a pipeline with the provided attributes.
Args:
name required name string
kwargs {name, description, orgWide, aclEntries} user
specifiable ones only
return (status code, pipeline_dict) (as created) |
def wait_for_and_switch_to_alert(driver, timeout=settings.LARGE_TIMEOUT):
"""
Wait for a browser alert to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.alert when the alert box
may not exist yet.
@Params
driver - the webdriver object (required)
... | Wait for a browser alert to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.alert when the alert box
may not exist yet.
@Params
driver - the webdriver object (required)
timeout - the time to wait for the alert in seconds |
def clearData(self):
"""Clears all histograms (keeps bins)"""
self._counts = np.zeros_like(self._bins)
self.histo.setOpts(height=self._counts) | Clears all histograms (keeps bins) |
def first_time_setup(self):
"""First time running Open Sesame?
Create keyring and an auto-unlock key in default keyring. Make sure
these things don't already exist.
"""
if not self._auto_unlock_key_position():
pw = password.create_passwords()[0]
... | First time running Open Sesame?
Create keyring and an auto-unlock key in default keyring. Make sure
these things don't already exist. |
def sample(self, fraction, seed=None, exact=False):
"""
Sample a fraction of the current SFrame's rows.
Parameters
----------
fraction : float
Fraction of the rows to fetch. Must be between 0 and 1.
if exact is False (default), the number of rows returned... | Sample a fraction of the current SFrame's rows.
Parameters
----------
fraction : float
Fraction of the rows to fetch. Must be between 0 and 1.
if exact is False (default), the number of rows returned is
approximately the fraction times the number of rows.
... |
def _str_to_datetime(self, str_value):
"""Parses a `YYYY-MM-DD` string into a datetime object."""
try:
ldt = [int(f) for f in str_value.split('-')]
dt = datetime.datetime(*ldt)
except (ValueError, TypeError):
return None
return dt | Parses a `YYYY-MM-DD` string into a datetime object. |
def render_to_response(self, context, **response_kwargs):
"""
Returns a JSON response, transforming 'context' to make the payload.
"""
response_kwargs['content_type'] = 'application/json'
return self.response_class(
self.convert_context_to_json(context),
... | Returns a JSON response, transforming 'context' to make the payload. |
def execute(self, query, args=None):
"""Execute a query.
query -- string, query to execute on server
args -- optional sequence or mapping, parameters to use with query.
Note: If args is a sequence, then %s must be used as the
parameter placeholder in the query. If a ma... | Execute a query.
query -- string, query to execute on server
args -- optional sequence or mapping, parameters to use with query.
Note: If args is a sequence, then %s must be used as the
parameter placeholder in the query. If a mapping is used,
%(key)s must be used as th... |
def x_runtime(f, *args, **kwargs):
"""X-Runtime Flask Response Decorator."""
_t0 = now()
r = f(*args, **kwargs)
_t1 = now()
r.headers['X-Runtime'] = '{0}s'.format(Decimal(str(_t1 - _t0)))
return r | X-Runtime Flask Response Decorator. |
def _update_resource_view(self, log=False):
# type: () -> bool
"""Check if resource view exists in HDX and if so, update resource view
Returns:
bool: True if updated and False if not
"""
update = False
if 'id' in self.data and self._load_from_hdx('resource vi... | Check if resource view exists in HDX and if so, update resource view
Returns:
bool: True if updated and False if not |
def pseudo_organization(organization, classification, default=None):
""" helper for setting an appropriate ID for organizations """
if organization and classification:
raise ScrapeValueError('cannot specify both classification and organization')
elif classification:
return _make_pseudo_id(cl... | helper for setting an appropriate ID for organizations |
def wait_pid(pid, timeout=None, callback=None):
"""Wait for process with pid 'pid' to terminate and return its
exit status code as an integer.
If pid is not a children of os.getpid() (current process) just
waits until the process disappears and return None.
If pid does not exist at all return None... | Wait for process with pid 'pid' to terminate and return its
exit status code as an integer.
If pid is not a children of os.getpid() (current process) just
waits until the process disappears and return None.
If pid does not exist at all return None immediately.
Raise TimeoutExpired on timeout expi... |
def call(self):
'''show a value dialog'''
from wx_loader import wx
dlg = wx.TextEntryDialog(None, self.title, self.title, defaultValue=str(self.default))
if dlg.ShowModal() != wx.ID_OK:
return None
return dlg.GetValue() | show a value dialog |
def _single_tree_paths(self, tree):
"""Get all traversal paths from a single tree."""
skel = tree.consolidate()
tree = defaultdict(list)
for edge in skel.edges:
svert = edge[0]
evert = edge[1]
tree[svert].append(evert)
tree[evert].append(svert)
def dfs(path, visited):
... | Get all traversal paths from a single tree. |
def get_module_name(package):
"""
package must have these attributes:
e.g.:
package.DISTRIBUTION_NAME = "DragonPyEmulator"
package.DIST_GROUP = "console_scripts"
package.ENTRY_POINT = "DragonPy"
:return: a string like: "dragonpy.core.cli"
"""
distribution = get_distribut... | package must have these attributes:
e.g.:
package.DISTRIBUTION_NAME = "DragonPyEmulator"
package.DIST_GROUP = "console_scripts"
package.ENTRY_POINT = "DragonPy"
:return: a string like: "dragonpy.core.cli" |
def template_subst(template, subs, delims=('<', '>')):
""" Perform substitution of content into tagged string.
For substitutions into template input files for external computational
packages, no checks for valid syntax are performed.
Each key in `subs` corresponds to a delimited
substitution tag t... | Perform substitution of content into tagged string.
For substitutions into template input files for external computational
packages, no checks for valid syntax are performed.
Each key in `subs` corresponds to a delimited
substitution tag to be replaced in `template` by the entire text of the
value... |
def emit(self, action, event, **kwargs):
"""
Send an event to all the client listening for notifications
:param action: Action name
:param event: Event to send
:param kwargs: Add this meta to the notification (project_id for example)
"""
for listener in self._lis... | Send an event to all the client listening for notifications
:param action: Action name
:param event: Event to send
:param kwargs: Add this meta to the notification (project_id for example) |
def find_document_type_by_name(self, entity_name, active='Y',
match_case=True):
"""
search document types by name and active(Y/N) status
:param entity_name: entity name
:return:
"""
all_types = self.get_dictionary('Document_Type_DE')
... | search document types by name and active(Y/N) status
:param entity_name: entity name
:return: |
def normalize_volume(volume):
'''convert volume metadata from es to archivant format
This function makes side effect on input volume
output example::
{
'id': 'AU0paPZOMZchuDv1iDv8',
'type': 'volume',
'metadata': {'_language': '... | convert volume metadata from es to archivant format
This function makes side effect on input volume
output example::
{
'id': 'AU0paPZOMZchuDv1iDv8',
'type': 'volume',
'metadata': {'_language': 'en',
'key1': ... |
def _set_zoning(self, v, load=False):
"""
Setter method for zoning, mapped from YANG variable /zoning (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_zoning is considered as a private
method. Backends looking to populate this variable should
do so via... | Setter method for zoning, mapped from YANG variable /zoning (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_zoning is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_zoning() directly. |
def dumps(self, contentType=None, version=None):
'''
[OPTIONAL] Identical to :meth:`dump`, except the serialized form
is returned as a string representation. As documented in
:meth:`dump`, the return value can optionally be a three-element
tuple of (contentType, version, data) if the provided conten... | [OPTIONAL] Identical to :meth:`dump`, except the serialized form
is returned as a string representation. As documented in
:meth:`dump`, the return value can optionally be a three-element
tuple of (contentType, version, data) if the provided content-type
should be overridden or enhanced. The default impl... |
def isin_start(elems, line):
"""Check if an element from a list starts a string.
:type elems: list
:type line: str
"""
found = False
elems = [elems] if type(elems) is not list else elems
for e in elems:
if line.lstrip().lower().startswith(e):
found = True
br... | Check if an element from a list starts a string.
:type elems: list
:type line: str |
def get_languages(self):
"""
:calls: `GET /repos/:owner/:repo/languages <http://developer.github.com/v3/repos>`_
:rtype: dict of string to integer
"""
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/languages"
)
ret... | :calls: `GET /repos/:owner/:repo/languages <http://developer.github.com/v3/repos>`_
:rtype: dict of string to integer |
def _get_cache_size(replace=False):
"""Get size of cache."""
if not replace:
size = _cached_search_compile.cache_info().currsize
else:
size = _cached_replace_compile.cache_info().currsize
return size | Get size of cache. |
def get_session_identifiers(cls, folder=None, inputfile=None):
""" Retrieve the list of session identifiers contained in the
data on the folder or the inputfile.
For this plugin, it returns the list of excel sheet available.
:kwarg folder: the path to the folder containing the files to
... | Retrieve the list of session identifiers contained in the
data on the folder or the inputfile.
For this plugin, it returns the list of excel sheet available.
:kwarg folder: the path to the folder containing the files to
check. This folder may contain sub-folders.
:kwarg inpu... |
def walk_revctrl(dirname='', ff=''):
"""Return files found by the file-finder 'ff'.
"""
file_finder = None
items = []
if not ff:
distutils.log.error('No file-finder passed to walk_revctrl')
sys.exit(1)
for ep in pkg_resources.iter_entry_points('setuptools.file_finders'):
... | Return files found by the file-finder 'ff'. |
def _check_env_vars_set(self, dir_env_var, file_env_var):
"""
Check to see if the default cert dir/file environment vars are present.
:return: bool
"""
return (
os.environ.get(file_env_var) is not None or
os.environ.get(dir_env_var) is not None
) | Check to see if the default cert dir/file environment vars are present.
:return: bool |
def _get_subject_uri(self, guid=None):
"""
Returns the full path that uniquely identifies
the subject endpoint.
"""
uri = self.uri + '/v1/subject'
if guid:
uri += '/' + urllib.quote_plus(guid)
return uri | Returns the full path that uniquely identifies
the subject endpoint. |
def _get_list(self, key, operation, create=False):
"""
Get (and maybe create) a list by name.
"""
return self._get_by_type(key, operation, create, b'list', []) | Get (and maybe create) a list by name. |
def _init_draw(self):
"""Initializes the drawing of the frames by setting the images to
random colors.
This function is called by TimedAnimation.
"""
if self.original is not None:
self.original.set_data(np.random.random((10, 10, 3)))
self.processed.set_data(n... | Initializes the drawing of the frames by setting the images to
random colors.
This function is called by TimedAnimation. |
def walkscan(x0, y0, xn=0.25, xp=0.25, yn=0.25, yp=0.25):
"""Scan pixels in a random walk pattern with given step probabilities. The
random walk will continue indefinitely unless a skip transformation is used
with the 'stop' parameter set or a clip transformation is used with the
'abort' parameter set t... | Scan pixels in a random walk pattern with given step probabilities. The
random walk will continue indefinitely unless a skip transformation is used
with the 'stop' parameter set or a clip transformation is used with the
'abort' parameter set to True. The probabilities are normalized to sum to 1.
:param... |
def add(i):
"""
Input: {
(repo_uoa) - repo UOA
module_uoa - normally should be 'module' already
data_uoa - UOA of the module to be created
(desc) - module description
(license) - module li... | Input: {
(repo_uoa) - repo UOA
module_uoa - normally should be 'module' already
data_uoa - UOA of the module to be created
(desc) - module description
(license) - module license
(cop... |
def df2arff(df, dataset_name, pods_data):
"""Write an arff file from a data set loaded in from pods"""
def java_simple_date(date_format):
date_format = date_format.replace('%Y', 'yyyy').replace('%m', 'MM').replace('%d', 'dd').replace('%H', 'HH')
return date_format.replace('%h', 'hh').replace('%M... | Write an arff file from a data set loaded in from pods |
def outliers(df,output_type = 'values',dtype = 'number',sensitivity = 1.5):# can output boolean array or values
""" Returns potential outliers as either a boolean array or a subset of the original.
Parameters:
df - array_like
Series or dataframe to check
output_type - string, default 'values'
... | Returns potential outliers as either a boolean array or a subset of the original.
Parameters:
df - array_like
Series or dataframe to check
output_type - string, default 'values'
if 'values' is specified, then will output the values in the series that are suspected
outliers. Else, a b... |
def Read(self, length):
"""Read from the file."""
if not self.IsFile():
raise IOError("%s is not a file." % self.pathspec.last.path)
available = min(self.size - self.offset, length)
if available > 0:
# This raises a RuntimeError in some situations.
try:
data = self.fd.read_ran... | Read from the file. |
def weight_layers(name, bilm_ops, l2_coef=None,
use_top_only=False, do_layer_norm=False, reuse=False):
"""
Weight the layers of a biLM with trainable scalar weights to
compute ELMo representations.
For each output layer, this returns two ops. The first computes
a layer specif... | Weight the layers of a biLM with trainable scalar weights to
compute ELMo representations.
For each output layer, this returns two ops. The first computes
a layer specific weighted average of the biLM layers, and
the second the l2 regularizer loss term.
The regularization terms are also ad... |
def prep_vrn_file(in_file, vcaller, work_dir, somatic_info, writer_class, seg_file=None, params=None):
"""Select heterozygous variants in the normal sample with sufficient depth.
writer_class implements write_header and write_row to write VCF outputs
from a record and extracted tumor/normal statistics.
... | Select heterozygous variants in the normal sample with sufficient depth.
writer_class implements write_header and write_row to write VCF outputs
from a record and extracted tumor/normal statistics. |
def _send(self, data):
"""Send data to statsd."""
if not self._sock:
self.connect()
self._do_send(data) | Send data to statsd. |
def to_feather(self, fname):
"""
Write out the binary feather-format for DataFrames.
.. versionadded:: 0.20.0
Parameters
----------
fname : str
string file path
"""
from pandas.io.feather_format import to_feather
to_feather(self, fnam... | Write out the binary feather-format for DataFrames.
.. versionadded:: 0.20.0
Parameters
----------
fname : str
string file path |
def _label_path_from_index(self, index):
"""
given image index, find out annotation path
Parameters:
----------
index: int
index of a specific image
Returns:
----------
full path of annotation file
"""
label_file = os.path.joi... | given image index, find out annotation path
Parameters:
----------
index: int
index of a specific image
Returns:
----------
full path of annotation file |
def main():
"""
1. Reads in a meraculous config file and outputs all of the associated config
files to $PWD/configs
2. The name of each run and the path to the directory is passed to a
multiprocessing core that controls which assemblies are executed and when.
"""
parser = CommandLine(... | 1. Reads in a meraculous config file and outputs all of the associated config
files to $PWD/configs
2. The name of each run and the path to the directory is passed to a
multiprocessing core that controls which assemblies are executed and when. |
def _get_resource_type_cls(self, name, resource):
"""Attempts to return troposphere class that represents Type of
provided resource. Attempts to find the troposphere class who's
`resource_type` field is the same as the provided resources `Type`
field.
:param resource: Resource t... | Attempts to return troposphere class that represents Type of
provided resource. Attempts to find the troposphere class who's
`resource_type` field is the same as the provided resources `Type`
field.
:param resource: Resource to find troposphere class for
:return: None: If no cla... |
def _cond_select_value_nonrecur(d,cond_match=None,**kwargs):
'''
d = {
"ActiveArea":"50829",
"Artist":"315",
"AsShotPreProfileMatrix":"50832",
"AnalogBalance":"50727",
"AsShotICCProfile":"50831",
"AsSh... | d = {
"ActiveArea":"50829",
"Artist":"315",
"AsShotPreProfileMatrix":"50832",
"AnalogBalance":"50727",
"AsShotICCProfile":"50831",
"AsShotProfileName":"50934",
"AntiAliasStrength":"50738",
... |
def get_issues(self, repo, keys):
""" Grab all the issues """
key1, key2 = keys
key3 = key1[:-1] # Just the singular form of key1
url = self.base_url + "/api/0/" + repo + "/" + key1
response = self.session.get(url, params=dict(status='Open'))
if not bool(response):
... | Grab all the issues |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.