code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _ipsi(y, tol=1.48e-9, maxiter=10):
'''Inverse of psi (digamma) using Newton's method. For the purposes
of Dirichlet MLE, since the parameters a[i] must always
satisfy a > 0, we define ipsi :: R -> (0,inf).'''
y = asanyarray(y, dtype='float')
x0 = _piecewise(y, [y >= -2.22, y < -2.22],
... | Inverse of psi (digamma) using Newton's method. For the purposes
of Dirichlet MLE, since the parameters a[i] must always
satisfy a > 0, we define ipsi :: R -> (0,inf). |
def weather_history_at_place(self, name, start=None, end=None):
"""
Queries the OWM Weather API for weather history for the specified location
(eg: "London,uk"). A list of *Weather* objects is returned. It is
possible to query for weather history in a closed time period, whose
bo... | Queries the OWM Weather API for weather history for the specified location
(eg: "London,uk"). A list of *Weather* objects is returned. It is
possible to query for weather history in a closed time period, whose
boundaries can be passed as optional parameters.
:param name: the location's ... |
def get_last_branch_location(cls):
"""
Returns the source and destination addresses of the last taken branch.
@rtype: tuple( int, int )
@return: Source and destination addresses of the last taken branch.
@raise WindowsError:
Raises an exception on error.
@r... | Returns the source and destination addresses of the last taken branch.
@rtype: tuple( int, int )
@return: Source and destination addresses of the last taken branch.
@raise WindowsError:
Raises an exception on error.
@raise NotImplementedError:
Current architect... |
def first_line_indent(self):
"""
A |Length| value calculated from the values of `w:ind/@w:firstLine`
and `w:ind/@w:hanging`. Returns |None| if the `w:ind` child is not
present.
"""
ind = self.ind
if ind is None:
return None
hanging = ind.hangin... | A |Length| value calculated from the values of `w:ind/@w:firstLine`
and `w:ind/@w:hanging`. Returns |None| if the `w:ind` child is not
present. |
def commit(self):
"""
Commit MySQL Transaction to database.
MySQLDB: If the database and the tables support transactions,
this commits the current transaction; otherwise
this method successfully does nothing.
@author: Nick Verbeck
@since: 5/12/2008
"""
try:
if self.connection is not None:
... | Commit MySQL Transaction to database.
MySQLDB: If the database and the tables support transactions,
this commits the current transaction; otherwise
this method successfully does nothing.
@author: Nick Verbeck
@since: 5/12/2008 |
def check_virtualserver(self, name):
'''
Check to see if a virtual server exists
'''
vs = self.bigIP.LocalLB.VirtualServer
for v in vs.get_list():
if v.split('/')[-1] == name:
return True
return False | Check to see if a virtual server exists |
def wsgi_wrap(app):
'''
Wraps a standard wsgi application e.g.:
def app(environ, start_response)
It intercepts the start_response callback and grabs the results from it
so it can return the status, headers, and body as a tuple
'''
@wraps(app)
def wrapped(environ, start_response):
... | Wraps a standard wsgi application e.g.:
def app(environ, start_response)
It intercepts the start_response callback and grabs the results from it
so it can return the status, headers, and body as a tuple |
def edit(self, hardware_id, userdata=None, hostname=None, domain=None,
notes=None, tags=None):
"""Edit hostname, domain name, notes, user data of the hardware.
Parameters set to None will be ignored and not attempted to be updated.
:param integer hardware_id: the instance ID to ed... | Edit hostname, domain name, notes, user data of the hardware.
Parameters set to None will be ignored and not attempted to be updated.
:param integer hardware_id: the instance ID to edit
:param string userdata: user data on the hardware to edit.
If none exist it ... |
def get_dockercfg_credentials(self, docker_registry):
"""
Read the .dockercfg file and return an empty dict, or else a dict
with keys 'basic_auth_username' and 'basic_auth_password'.
"""
if not self.registry_secret_path:
return {}
dockercfg = Dockercfg(self.r... | Read the .dockercfg file and return an empty dict, or else a dict
with keys 'basic_auth_username' and 'basic_auth_password'. |
def handle_one_request(self):
"""Copy of WSGIRequestHandler.handle(), but with different ServerHandler"""
"""Copy of WSGIRequestHandler, but with different ServerHandler"""
self.raw_requestline = self.rfile.readline(65537)
if len(self.raw_requestline) > 65536:
self.requestli... | Copy of WSGIRequestHandler.handle(), but with different ServerHandler |
def get_ssh_key(host,
username,
password,
protocol=None,
port=None,
certificate_verify=False):
'''
Retrieve the authorized_keys entry for root.
This function only works for ESXi, not vCenter.
:param host: The location of th... | Retrieve the authorized_keys entry for root.
This function only works for ESXi, not vCenter.
:param host: The location of the ESXi Host
:param username: Username to connect as
:param password: Password for the ESXi web endpoint
:param protocol: defaults to https, can be http if ssl is disabled on E... |
def suites(self, request, pk=None):
"""
List of test suite names available in this project
"""
suites_names = self.get_object().suites.values_list('slug')
suites_metadata = SuiteMetadata.objects.filter(kind='suite', suite__in=suites_names)
page = self.paginate_queryset(su... | List of test suite names available in this project |
def fmpt(P):
"""
Calculates the matrix of first mean passage times for an ergodic transition
probability matrix.
Parameters
----------
P : array
(k, k), an ergodic Markov transition probability matrix.
Returns
-------
M : array
(k, k), elements are the e... | Calculates the matrix of first mean passage times for an ergodic transition
probability matrix.
Parameters
----------
P : array
(k, k), an ergodic Markov transition probability matrix.
Returns
-------
M : array
(k, k), elements are the expected value for the num... |
def x_build_targets_target( self, node ):
'''
Process the target dependency DAG into an ancestry tree so we can look up
which top-level library and test targets specific build actions correspond to.
'''
target_node = node
name = self.get_child_data(target_node,tag='name',... | Process the target dependency DAG into an ancestry tree so we can look up
which top-level library and test targets specific build actions correspond to. |
def createproject(self, name, **kwargs):
"""
Creates a new project owned by the authenticated user.
:param name: new project name
:param path: custom repository name for new project. By default generated based on name
:param namespace_id: namespace for the new project (defaults ... | Creates a new project owned by the authenticated user.
:param name: new project name
:param path: custom repository name for new project. By default generated based on name
:param namespace_id: namespace for the new project (defaults to user)
:param description: short project descriptio... |
def Shift(self, term):
"""Adds a term to the xs.
term: how much to add
"""
new = self.Copy()
new.xs = [x + term for x in self.xs]
return new | Adds a term to the xs.
term: how much to add |
def get_icon(name, aspix=False, asicon=False):
"""Return the real file path to the given icon name
If aspix is True return as QtGui.QPixmap, if asicon is True return as QtGui.QIcon.
:param name: the name of the icon
:type name: str
:param aspix: If True, return a QtGui.QPixmap.
:type aspix: boo... | Return the real file path to the given icon name
If aspix is True return as QtGui.QPixmap, if asicon is True return as QtGui.QIcon.
:param name: the name of the icon
:type name: str
:param aspix: If True, return a QtGui.QPixmap.
:type aspix: bool
:param asicon: If True, return a QtGui.QIcon.
... |
def keywords(s, top=10, **kwargs):
""" Returns a sorted list of keywords in the given string.
"""
return parser.find_keywords(s, top=top, frequency=parser.frequency) | Returns a sorted list of keywords in the given string. |
def _compute_count_availability(resource, status, previous_status):
'''Compute the `check:count-availability` extra value'''
count_availability = resource.extras.get('check:count-availability', 1)
return count_availability + 1 if status == previous_status else 1 | Compute the `check:count-availability` extra value |
def main():
"""
NAME
plotXY.py
DESCRIPTION
Makes simple X,Y plots
INPUT FORMAT
X,Y data in columns
SYNTAX
plotxy.py [command line options]
OPTIONS
-h prints this help message
-f FILE to set file name on command line
-c col1 col2 specify c... | NAME
plotXY.py
DESCRIPTION
Makes simple X,Y plots
INPUT FORMAT
X,Y data in columns
SYNTAX
plotxy.py [command line options]
OPTIONS
-h prints this help message
-f FILE to set file name on command line
-c col1 col2 specify columns to plot
-... |
def from_json(json_str, allow_pickle=False):
"""
Decodes a JSON object specified in the utool convention
Args:
json_str (str):
allow_pickle (bool): (default = False)
Returns:
object: val
CommandLine:
python -m utool.util_cache from_json --show
Example:
... | Decodes a JSON object specified in the utool convention
Args:
json_str (str):
allow_pickle (bool): (default = False)
Returns:
object: val
CommandLine:
python -m utool.util_cache from_json --show
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_cache i... |
def diffplot(self, f, delay=1, lfilter=None, **kargs):
"""diffplot(f, delay=1, lfilter=None)
Applies a function to couples (l[i],l[i+delay])
A list of matplotlib.lines.Line2D is returned.
"""
# Get the list of packets
if lfilter is None:
lst_pkts = [f(self.r... | diffplot(f, delay=1, lfilter=None)
Applies a function to couples (l[i],l[i+delay])
A list of matplotlib.lines.Line2D is returned. |
def count(start=0, step=1, *, interval=0):
"""Generate consecutive numbers indefinitely.
Optional starting point and increment can be defined,
respectively defaulting to ``0`` and ``1``.
An optional interval can be given to space the values out.
"""
agen = from_iterable.raw(itertools.count(sta... | Generate consecutive numbers indefinitely.
Optional starting point and increment can be defined,
respectively defaulting to ``0`` and ``1``.
An optional interval can be given to space the values out. |
def all_coplanar(triangles):
"""
Check to see if a list of triangles are all coplanar
Parameters
----------------
triangles: (n, 3, 3) float
Vertices of triangles
Returns
---------------
all_coplanar : bool
True if all triangles are coplanar
"""
triangles = np.asany... | Check to see if a list of triangles are all coplanar
Parameters
----------------
triangles: (n, 3, 3) float
Vertices of triangles
Returns
---------------
all_coplanar : bool
True if all triangles are coplanar |
def parse_query(query_str):
"""
Drives the whole logic, by parsing, restructuring and finally, generating an ElasticSearch query.
Args:
query_str (six.text_types): the given query to be translated to an ElasticSearch query
Returns:
six.text_types: Return an ElasticSearch query.
No... | Drives the whole logic, by parsing, restructuring and finally, generating an ElasticSearch query.
Args:
query_str (six.text_types): the given query to be translated to an ElasticSearch query
Returns:
six.text_types: Return an ElasticSearch query.
Notes:
In case there's an error, a... |
def find_longest_match(self, alo, ahi, blo, bhi):
"""Find longest matching block in a[alo:ahi] and b[blo:bhi].
Wrapper for the C implementation of this function.
"""
besti, bestj, bestsize = _cdifflib.find_longest_match(self, alo, ahi, blo, bhi)
return _Match(besti, bestj, bests... | Find longest matching block in a[alo:ahi] and b[blo:bhi].
Wrapper for the C implementation of this function. |
def bind_super(self, opr):
""" 为超级管理员授权所有权限
"""
for path in self.routes:
route = self.routes.get(path)
route['oprs'].append(opr) | 为超级管理员授权所有权限 |
def _get_resources_string(res_dict, pid):
""" Returns the nextflow resources string from a dictionary object
If the dictionary has at least on of the resource directives, these
will be compiled for each process in the dictionary and returned
as a string read for injection in the nextflo... | Returns the nextflow resources string from a dictionary object
If the dictionary has at least on of the resource directives, these
will be compiled for each process in the dictionary and returned
as a string read for injection in the nextflow config file template.
This dictionary shoul... |
def classifications(ctx, classifications, results, readlevel, readlevel_path):
"""Retrieve performed metagenomic classifications"""
# basic operation -- just print
if not readlevel and not results:
cli_resource_fetcher(ctx, "classifications", classifications)
# fetch the results
elif not r... | Retrieve performed metagenomic classifications |
def Run(self, unused_arg):
"""Run the kill."""
# Send a message back to the service to say that we are about to shutdown.
reply = rdf_flows.GrrStatus(status=rdf_flows.GrrStatus.ReturnedStatus.OK)
# Queue up the response message, jump the queue.
self.SendReply(reply, message_type=rdf_flows.GrrMessage... | Run the kill. |
def get(self, idx, default=''):
'''Returns the element at idx, or default if idx is beyond the length of the list'''
# if the index is beyond the length of the list, return ''
if isinstance(idx, int) and (idx >= len(self) or idx < -1 * len(self)):
return default
# else do the... | Returns the element at idx, or default if idx is beyond the length of the list |
def register_sub_command(self, sub_command, additional_ids=[]):
"""
Register a command as a subcommand.
It will have it's CommandDesc.command string used as id. Additional ids can be provided.
Args:
sub_command (CommandBase): Subcommand to register.
additional_id... | Register a command as a subcommand.
It will have it's CommandDesc.command string used as id. Additional ids can be provided.
Args:
sub_command (CommandBase): Subcommand to register.
additional_ids (List[str]): List of additional ids. Can be empty. |
def river_sources(world, water_flow, water_path):
"""Find places on map where sources of river can be found"""
river_source_list = []
# Using the wind and rainfall data, create river 'seeds' by
# flowing rainfall along paths until a 'flow' threshold is reached
# and we h... | Find places on map where sources of river can be found |
def precision(Ntp, Nsys, eps=numpy.spacing(1)):
"""Precision.
Wikipedia entry https://en.wikipedia.org/wiki/Precision_and_recall
Parameters
----------
Ntp : int >=0
Number of true positives.
Nsys : int >=0
Amount of system output.
eps : float
eps.
Default ... | Precision.
Wikipedia entry https://en.wikipedia.org/wiki/Precision_and_recall
Parameters
----------
Ntp : int >=0
Number of true positives.
Nsys : int >=0
Amount of system output.
eps : float
eps.
Default value numpy.spacing(1)
Returns
-------
pre... |
def get_class_alias(klass):
"""
Tries to find a suitable L{pyamf.ClassAlias} subclass for C{klass}.
"""
for k, v in pyamf.ALIAS_TYPES.iteritems():
for kl in v:
try:
if issubclass(klass, kl):
return k
except TypeError:
# ... | Tries to find a suitable L{pyamf.ClassAlias} subclass for C{klass}. |
def get_next_url(request, redirect_field_name):
"""Retrieves next url from request
Note: This verifies that the url is safe before returning it. If the url
is not safe, this returns None.
:arg HttpRequest request: the http request
:arg str redirect_field_name: the name of the field holding the nex... | Retrieves next url from request
Note: This verifies that the url is safe before returning it. If the url
is not safe, this returns None.
:arg HttpRequest request: the http request
:arg str redirect_field_name: the name of the field holding the next url
:returns: safe url or None |
def xyz_with_ports(self, arrnx3):
"""Set the positions of the particles in the Compound, including the Ports.
Parameters
----------
arrnx3 : np.ndarray, shape=(n,3), dtype=float
The new particle positions
"""
if not self.children:
if not arrnx3.s... | Set the positions of the particles in the Compound, including the Ports.
Parameters
----------
arrnx3 : np.ndarray, shape=(n,3), dtype=float
The new particle positions |
def post_grade2(self, grade, user=None, comment=''):
"""
Post grade to LTI consumer using REST/JSON
URL munging will is related to:
https://openedx.atlassian.net/browse/PLAT-281
:param: grade: 0 <= grade <= 1
:return: True if post successful and grade valid
:exce... | Post grade to LTI consumer using REST/JSON
URL munging will is related to:
https://openedx.atlassian.net/browse/PLAT-281
:param: grade: 0 <= grade <= 1
:return: True if post successful and grade valid
:exception: LTIPostMessageException if call failed |
def _configure_manager(self):
"""
Creates the Manager instance to handle networks.
"""
self._manager = CloudNetworkManager(self, resource_class=CloudNetwork,
response_key="network", uri_base="os-networksv2") | Creates the Manager instance to handle networks. |
def info_label(self, indicator):
"""Set info label by given settings.
Parameters
----------
indicator : int
A number where
0-8 is number of mines in srrounding.
12 is a mine field.
"""
if indicator in xrange(1, 9):
self.id ... | Set info label by given settings.
Parameters
----------
indicator : int
A number where
0-8 is number of mines in srrounding.
12 is a mine field. |
def to_digital(d, num):
"""
进制转换,从10进制转到指定机制
:param d:
:param num:
:return:
"""
if not isinstance(num, int) or not 1 < num < 10:
raise ValueError('digital num must between 1 and 10')
d = int(d)
result = []
x = d % num
d = d - x
result.append(str(x))
while d >... | 进制转换,从10进制转到指定机制
:param d:
:param num:
:return: |
def find_doc(self, name=None, ns_uri=None, first_only=False):
"""
Find :class:`Element` node descendants of the document containing
this node, with optional constraints to limit the results.
Delegates to :meth:`find` applied to this node's owning document.
"""
return sel... | Find :class:`Element` node descendants of the document containing
this node, with optional constraints to limit the results.
Delegates to :meth:`find` applied to this node's owning document. |
def is_first_root(self):
"""Return ``True`` if this page is the first root pages."""
if self.parent:
return False
if self._is_first_root is not None:
return self._is_first_root
first_root_id = cache.get('PAGE_FIRST_ROOT_ID')
if first_root_id is not None:
... | Return ``True`` if this page is the first root pages. |
def revoke_all(self, paths: Union[str, Iterable[str]], recursive: bool=False):
"""
See `AccessControlMapper.revoke_all`.
:param paths: see `AccessControlMapper.revoke_all`
:param access_controls: see `AccessControlMapper.revoke_all`
:param recursive: whether the access control li... | See `AccessControlMapper.revoke_all`.
:param paths: see `AccessControlMapper.revoke_all`
:param access_controls: see `AccessControlMapper.revoke_all`
:param recursive: whether the access control list should be changed recursively for all nested collections |
def append_note(self, player, text):
"""Append text to an already existing note."""
note = self._find_note(player)
note.text += text | Append text to an already existing note. |
def init_app(self, app):
"""
Register this extension with the flask app
:param app: A flask application
"""
# Save this so we can use it later in the extension
if not hasattr(app, 'extensions'): # pragma: no cover
app.extensions = {}
app.extensions[... | Register this extension with the flask app
:param app: A flask application |
def filter_any_above_threshold(
self,
multi_key_fn,
value_dict,
threshold,
default_value=0.0):
"""Like filter_above_threshold but `multi_key_fn` returns multiple
keys and the element is kept if any of them have a value above
the given t... | Like filter_above_threshold but `multi_key_fn` returns multiple
keys and the element is kept if any of them have a value above
the given threshold.
Parameters
----------
multi_key_fn : callable
Given an element of this collection, returns multiple keys
in... |
def get_randomized_guid_sample(self, item_count):
""" Fetch a subset of randomzied GUIDs from the whitelist """
dataset = self.get_whitelist()
random.shuffle(dataset)
return dataset[:item_count] | Fetch a subset of randomzied GUIDs from the whitelist |
def apex(self, axis):
'''
Find the most extreme vertex in the direction of the axis provided.
axis: A vector, which is an 3x1 np.array.
'''
from blmath.geometry.apex import apex
return apex(self.v, axis) | Find the most extreme vertex in the direction of the axis provided.
axis: A vector, which is an 3x1 np.array. |
def categorization(self, domains, labels=False):
'''Get the domain status and categorization of a domain or list of domains.
'domains' can be either a single domain, or a list of domains.
Setting 'labels' to True will give back categorizations in human-readable
form.
For more de... | Get the domain status and categorization of a domain or list of domains.
'domains' can be either a single domain, or a list of domains.
Setting 'labels' to True will give back categorizations in human-readable
form.
For more detail, see https://investigate.umbrella.com/docs/api#categori... |
def set_pid_params(self, *args, **kwargs):
'''Set PID parameters for all joints in the skeleton.
Parameters for this method are passed directly to the `pid` constructor.
'''
for joint in self.joints:
joint.target_angles = [None] * joint.ADOF
joint.controllers = [... | Set PID parameters for all joints in the skeleton.
Parameters for this method are passed directly to the `pid` constructor. |
def datetime(self, start: int = 2000, end: int = 2035,
timezone: Optional[str] = None) -> DateTime:
"""Generate random datetime.
:param start: Minimum value of year.
:param end: Maximum value of year.
:param timezone: Set custom timezone (pytz required).
:return... | Generate random datetime.
:param start: Minimum value of year.
:param end: Maximum value of year.
:param timezone: Set custom timezone (pytz required).
:return: Datetime |
def _default_buffer_pos_changed(self, _):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if self.app.current_buffer == self.default_buffer:
try:
line_no = self.default_buffer.docum... | When the cursor changes in the default buffer. Synchronize with
history buffer. |
def create_label(self, name, justify=Gtk.Justification.CENTER, wrap_mode=True, tooltip=None):
"""
The function is used for creating lable with HTML text
"""
label = Gtk.Label()
name = name.replace('|', '\n')
label.set_markup(name)
label.set_justify(justify)
... | The function is used for creating lable with HTML text |
def get_related_models(cls, model):
""" Get a dictionary with related structure models for given class or model:
>> SupportedServices.get_related_models(gitlab_models.Project)
{
'service': nodeconductor_gitlab.models.GitLabService,
'service_project_link':... | Get a dictionary with related structure models for given class or model:
>> SupportedServices.get_related_models(gitlab_models.Project)
{
'service': nodeconductor_gitlab.models.GitLabService,
'service_project_link': nodeconductor_gitlab.models.GitLabServiceProjec... |
def update(self, **kwargs):
"""Update `params` values using alias.
"""
for k in self.prior_params:
try:
self.params[k] = kwargs[self.alias[k]]
except(KeyError):
pass | Update `params` values using alias. |
def set_source_morphology(self, name, **kwargs):
"""Set the spatial model of a source.
Parameters
----------
name : str
Source name.
spatial_model : str
Spatial model name (PointSource, RadialGaussian, etc.).
spatial_pars : dict
Diction... | Set the spatial model of a source.
Parameters
----------
name : str
Source name.
spatial_model : str
Spatial model name (PointSource, RadialGaussian, etc.).
spatial_pars : dict
Dictionary of spatial parameters (optional).
use_cache : b... |
def disconnect(self, code):
"""Called when WebSocket connection is closed."""
Subscriber.objects.filter(session_id=self.session_id).delete() | Called when WebSocket connection is closed. |
def page_not_found(request, template_name='404.html'):
"""
Custom page not found (404) handler.
Don't raise a Http404 or anything like that in here otherwise
you will cause an infinite loop. That would be bad.
If no ResponsePage exists for with type ``RESPONSE_HTTP404`` then
the default templa... | Custom page not found (404) handler.
Don't raise a Http404 or anything like that in here otherwise
you will cause an infinite loop. That would be bad.
If no ResponsePage exists for with type ``RESPONSE_HTTP404`` then
the default template render view will be used.
Templates: :template:`404.html`
... |
def prepare_hooks(self, hooks):
"""Prepares the given hooks."""
# hooks can be passed as None to the prepare method and to this
# method. To prevent iterating over None, simply use an empty list
# if hooks is False-y
hooks = hooks or []
for event in hooks:
sel... | Prepares the given hooks. |
def _getInputValue(self, obj, fieldName):
"""
Gets the value of a given field from the input record
"""
if isinstance(obj, dict):
if not fieldName in obj:
knownFields = ", ".join(
key for key in obj.keys() if not key.startswith("_")
)
raise ValueError(
"... | Gets the value of a given field from the input record |
def getLogLevelNo(level):
"""Return numerical log level or raise ValueError.
A valid level is either an integer or a string such as WARNING etc."""
if isinstance(level,(int,long)):
return level
try:
return(int(logging.getLevelName(level.upper())))
except:
raise ValueError('i... | Return numerical log level or raise ValueError.
A valid level is either an integer or a string such as WARNING etc. |
def _write(self, request):
"""Actually serialize and write the request."""
with sw("serialize_request"):
request_str = request.SerializeToString()
with sw("write_request"):
with catch_websocket_connection_errors():
self._sock.send(request_str) | Actually serialize and write the request. |
def propagate_cols_up(self, cols, target_df_name, source_df_name):
"""
Take values from source table, compile them into a colon-delimited list,
and apply them to the target table.
This method won't overwrite values in the target table, it will only
supply values where they are mi... | Take values from source table, compile them into a colon-delimited list,
and apply them to the target table.
This method won't overwrite values in the target table, it will only
supply values where they are missing.
Parameters
----------
cols : list-like
list... |
def delete_project(self, owner, id, **kwargs):
"""
Delete a project
Permanently deletes a project and all data associated with it. This operation cannot be undone, although a new project may be created with the same id.
This method makes a synchronous HTTP request by default. To make an
... | Delete a project
Permanently deletes a project and all data associated with it. This operation cannot be undone, although a new project may be created with the same id.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` funct... |
def bulkMinuteBars(symbol, dates, token='', version=''):
'''fetch many dates worth of minute-bars for a given symbol'''
_raiseIfNotStr(symbol)
dates = [_strOrDate(date) for date in dates]
list_orig = dates.__class__
args = []
for date in dates:
args.append((symbol, '1d', date, token, ve... | fetch many dates worth of minute-bars for a given symbol |
def get_file(self, filename):
"""
Return the raw data of the specified filename
inside the APK
:rtype: bytes
"""
try:
return self.zip.read(filename)
except KeyError:
raise FileNotPresent(filename) | Return the raw data of the specified filename
inside the APK
:rtype: bytes |
def convert_uv(pinyin):
"""ü 转换,还原原始的韵母
ü行的韵跟声母j,q,x拼的时候,写成ju(居),qu(区),xu(虚),
ü上两点也省略;但是跟声母n,l拼的时候,仍然写成nü(女),lü(吕)。
"""
return UV_RE.sub(
lambda m: ''.join((m.group(1), UV_MAP[m.group(2)], m.group(3))),
pinyin) | ü 转换,还原原始的韵母
ü行的韵跟声母j,q,x拼的时候,写成ju(居),qu(区),xu(虚),
ü上两点也省略;但是跟声母n,l拼的时候,仍然写成nü(女),lü(吕)。 |
def has_own_property(self, attr):
"""
Returns if the property
"""
try:
object.__getattribute__(self, attr)
except AttributeError:
return False
else:
return True | Returns if the property |
def resolve_object_number(self, ref):
"""Resolve a variety of object numebrs to a dataset number"""
if not isinstance(ref, ObjectNumber):
on = ObjectNumber.parse(ref)
else:
on = ref
ds_on = on.as_dataset
return ds_on | Resolve a variety of object numebrs to a dataset number |
def count_missense_per_gene(lines):
""" count the number of missense variants in each gene.
"""
counts = {}
for x in lines:
x = x.split("\t")
gene = x[0]
consequence = x[3]
if gene not in counts:
counts[gene] = 0
if consequence !... | count the number of missense variants in each gene. |
def describe_constructor(self, s):
"""
Describe the input bytesequence (constructor arguments) s based on the loaded contract
abi definition
:param s: bytes constructor arguments
:return: AbiMethod instance
"""
method = self.signatures.get(b"__constructor__")
... | Describe the input bytesequence (constructor arguments) s based on the loaded contract
abi definition
:param s: bytes constructor arguments
:return: AbiMethod instance |
def head(self, n=5):
"""Get the first n rows of the DataFrame.
Args:
n (int): The number of rows to return.
Returns:
A new DataFrame with the first n rows of the DataFrame.
"""
if n >= len(self.index):
return self.copy()
re... | Get the first n rows of the DataFrame.
Args:
n (int): The number of rows to return.
Returns:
A new DataFrame with the first n rows of the DataFrame. |
def lineMatchingPattern(pattern, lines):
""" Searches through the specified list of strings and returns the regular expression
match for the first line that matches the specified pre-compiled regex pattern, or None if no match was found
Note: if you are using a regex pattern string (i.e. not already compi... | Searches through the specified list of strings and returns the regular expression
match for the first line that matches the specified pre-compiled regex pattern, or None if no match was found
Note: if you are using a regex pattern string (i.e. not already compiled), use lineMatching() instead
:type patte... |
def create_tables(self, tables):
"""Creates database tables in sqlite lookup db"""
cursor = self.get_cursor()
for table in tables:
columns = mslookup_tables[table]
try:
cursor.execute('CREATE TABLE {0}({1})'.format(
table, ', '.join(col... | Creates database tables in sqlite lookup db |
def invoke(*args, **kwargs):
"""Invokes a command callback in exactly the way it expects. There
are two ways to invoke this method:
1. the first argument can be a callback and all other arguments and
keyword arguments are forwarded directly to the function.
2. the first a... | Invokes a command callback in exactly the way it expects. There
are two ways to invoke this method:
1. the first argument can be a callback and all other arguments and
keyword arguments are forwarded directly to the function.
2. the first argument is a click command object. In t... |
def _command_line(): # pragma: no cover pylint: disable=too-many-branches,too-many-statements
"""
Provide the command line interface.
"""
if __name__ == "PyFunceble":
# We initiate the end of the coloration at the end of each line.
initiate(autoreset=True)
# We load the config... | Provide the command line interface. |
def present(name,
type,
url,
access='proxy',
user='',
password='',
database='',
basic_auth=False,
basic_auth_user='',
basic_auth_password='',
is_default=False,
json_data=None,
... | Ensure that a data source is present.
name
Name of the data source.
type
Which type of data source it is ('graphite', 'influxdb' etc.).
url
The URL to the data source API.
user
Optional - user to authenticate with the data source
password
Optional - passw... |
def mousePressEvent(self, event):
"""Marshalls behaviour depending on location of the mouse click"""
if event.x() < 50:
super(PlotMenuBar, self).mousePressEvent(event)
else:
# ignore to allow proper functioning of float
event.ignore() | Marshalls behaviour depending on location of the mouse click |
def mkopen(p, *args, **kwargs):
"""
A wrapper for the open() builtin which makes parent directories if needed.
"""
dir = os.path.dirname(p)
mkdir(dir)
return open(p, *args, **kwargs) | A wrapper for the open() builtin which makes parent directories if needed. |
def open(self, value, nt=None, wrap=None, unwrap=None):
"""Mark the PV as opened an provide its initial value.
This initial value is later updated with post().
:param value: A Value, or appropriate object (see nt= and wrap= of the constructor).
Any clients which have begun connecting ... | Mark the PV as opened an provide its initial value.
This initial value is later updated with post().
:param value: A Value, or appropriate object (see nt= and wrap= of the constructor).
Any clients which have begun connecting which began connecting while
this PV was in the close'd sta... |
def on_origin(self, *args):
"""Make sure to redraw whenever the origin moves."""
if self.origin is None:
Clock.schedule_once(self.on_origin, 0)
return
self.origin.bind(
pos=self._trigger_repoint,
size=self._trigger_repoint
) | Make sure to redraw whenever the origin moves. |
def insert_object_into_db_pk_known(self,
obj: Any,
table: str,
fieldlist: Sequence[str]) -> None:
"""Inserts object into database table, with PK (first field) already
known."""
pk... | Inserts object into database table, with PK (first field) already
known. |
def transform(self):
"""
Get the (4, 4) homogenous transformation from the
world frame to this camera object.
Returns
------------
transform : (4, 4) float
Transform from world to camera
"""
# no scene set
if self._scene is None:
... | Get the (4, 4) homogenous transformation from the
world frame to this camera object.
Returns
------------
transform : (4, 4) float
Transform from world to camera |
async def handle_action(self, action: str, request_id: str, **kwargs):
"""
run the action.
"""
try:
await self.check_permissions(action, **kwargs)
if action not in self.available_actions:
raise MethodNotAllowed(method=action)
method_n... | run the action. |
def wanted_labels(self, labels):
"""
Specify only WANTED labels to minimize get_labels() requests
Args:
- labels: <list> of wanted labels.
Example:
page.wanted_labels(['P18', 'P31'])
"""
if not isinstance(labels, list):
raise ValueError("In... | Specify only WANTED labels to minimize get_labels() requests
Args:
- labels: <list> of wanted labels.
Example:
page.wanted_labels(['P18', 'P31']) |
def encrypt_assertion(self, statement, enc_key, template, key_type='des-192', node_xpath=None, node_id=None):
"""
Will encrypt an assertion
:param statement: A XML document that contains the assertion to encrypt
:param enc_key: File name of a file containing the encryption key
:... | Will encrypt an assertion
:param statement: A XML document that contains the assertion to encrypt
:param enc_key: File name of a file containing the encryption key
:param template: A template for the encryption part to be added.
:param key_type: The type of session key to use.
:... |
def run(self, n_iterations=1, min_n_workers=1, iteration_kwargs = {},):
"""
run n_iterations of SuccessiveHalving
Parameters
----------
n_iterations: int
number of iterations to be performed in this run
min_n_workers: int
minimum number of workers before starting the run
"""
self.wait_for_worke... | run n_iterations of SuccessiveHalving
Parameters
----------
n_iterations: int
number of iterations to be performed in this run
min_n_workers: int
minimum number of workers before starting the run |
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and c... | Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab(). |
def user_auth_link(self, redirect_uri, scope='', state='', avoid_linking=False):
"""Generates a URL to send the user for OAuth 2.0
:param string redirect_uri: URL to redirect the user to after auth.
:param string scope: The scope of the privileges you want the eventual access_token to grant.
... | Generates a URL to send the user for OAuth 2.0
:param string redirect_uri: URL to redirect the user to after auth.
:param string scope: The scope of the privileges you want the eventual access_token to grant.
:param string state: A value that will be returned to you unaltered along with the use... |
def command(sock, dbname, spec, slave_ok, is_mongos,
read_preference, codec_options, session, client, check=True,
allowable_errors=None, address=None,
check_keys=False, listeners=None, max_bson_size=None,
read_concern=None,
parse_write_concern_error=False,
... | Execute a command over the socket, or raise socket.error.
:Parameters:
- `sock`: a raw socket instance
- `dbname`: name of the database on which to run the command
- `spec`: a command document as an ordered dict type, eg SON.
- `slave_ok`: whether to set the SlaveOkay wire protocol bit
... |
def convex_conj(self):
"""The convex conjugate functional.
Convex conjugate distributes over separable sums, so the result is
simply the separable sum of the convex conjugates.
"""
convex_conjs = [func.convex_conj for func in self.functionals]
return SeparableSum(*convex... | The convex conjugate functional.
Convex conjugate distributes over separable sums, so the result is
simply the separable sum of the convex conjugates. |
def remove_ectopy(tachogram_data, tachogram_time):
"""
-----
Brief
-----
Function for removing ectopic beats.
-----------
Description
-----------
Ectopic beats are beats that are originated in cells that do not correspond to the expected pacemaker cells. These
beats are identifi... | -----
Brief
-----
Function for removing ectopic beats.
-----------
Description
-----------
Ectopic beats are beats that are originated in cells that do not correspond to the expected pacemaker cells. These
beats are identifiable in ECG signals by abnormal rhythms.
This function all... |
def subtract_bg(samplename, bgname, factor=1, distance=None, disttolerance=2,
subname=None, qrange=(), graph_extension='png', graph_dpi=80):
"""Subtract background from measurements.
Inputs:
samplename: the name of the sample
bgname: the name of the background measurements. Alte... | Subtract background from measurements.
Inputs:
samplename: the name of the sample
bgname: the name of the background measurements. Alternatively, it can
be a numeric value (float or ErrorValue), which will be subtracted.
If None, this constant will be determined by integrati... |
def back_bfs(self, start, end=None):
"""
Returns a list of nodes in some backward BFS order.
Starting from the start node the breadth first search proceeds along
incoming edges.
"""
return [node for node, step in self._iterbfs(start, end, forward=False)] | Returns a list of nodes in some backward BFS order.
Starting from the start node the breadth first search proceeds along
incoming edges. |
def _apply_cell_filters(self, context):
"""
Applies the field restrictions based on the
return value of the context's "has_permission()" method.
Stores them on self._unpermitted_fields.
Returns:
List of unpermitted fields names.
"""
self.setattrs(_i... | Applies the field restrictions based on the
return value of the context's "has_permission()" method.
Stores them on self._unpermitted_fields.
Returns:
List of unpermitted fields names. |
def confidenceInterval(self, alpha=0.6827, steps=1.e5, plot=False):
"""
Compute two-sided confidence interval by taking x-values corresponding to the largest PDF-values first.
"""
x_dense, y_dense = self.densify()
y_dense -= np.max(y_dense) # Numeric stability
f = scipy.i... | Compute two-sided confidence interval by taking x-values corresponding to the largest PDF-values first. |
def _ParseDocstring(function):
"""Parses the functions docstring into a dictionary of type checks."""
if not function.__doc__:
return {}
type_check_dict = {}
for match in param_regexp.finditer(function.__doc__):
param_str = match.group(1).strip()
param_splitted = param_str.split(" ")
if len(par... | Parses the functions docstring into a dictionary of type checks. |
def get_table(self, dataset, table, project_id=None):
""" Retrieve a table if it exists, otherwise return an empty dict.
Parameters
----------
dataset : str
The dataset that the table is in
table : str
The name of the table
project_id: str, option... | Retrieve a table if it exists, otherwise return an empty dict.
Parameters
----------
dataset : str
The dataset that the table is in
table : str
The name of the table
project_id: str, optional
The project that the table is in
Returns
... |
def _compute_examples(self):
"""
Populates the ``_examples`` instance attribute by computing full
examples for each label in ``_raw_examples``.
The logic in this method is separate from :meth:`_add_example` because
this method requires that every type have ``_raw_examples`` assi... | Populates the ``_examples`` instance attribute by computing full
examples for each label in ``_raw_examples``.
The logic in this method is separate from :meth:`_add_example` because
this method requires that every type have ``_raw_examples`` assigned
for resolving example references. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.