code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _rebuild_mod_path(orig_path, package_name, module):
"""
Rebuild module.__path__ ensuring that all entries are ordered
corresponding to their sys.path order
"""
sys_path = [_normalize_cached(p) for p in sys.path]
def safe_sys_path_index(entry):
"""
Workaround for #520 and #51... | Rebuild module.__path__ ensuring that all entries are ordered
corresponding to their sys.path order |
def topological_sort(bpmn_graph, nodes_with_classification):
"""
:return:
"""
node_param_name = "node"
classification_param_name = "classification"
tmp_nodes_with_classification = copy.deepcopy(nodes_with_classification)
sorted_nodes_with_classification = []
no_incoming_flow_nodes = []
... | :return: |
def add_vcenter(self, **kwargs):
"""
Add vCenter on the switch
Args:
id(str) : Name of an established vCenter
url (bool) : vCenter URL
username (str): Username of the vCenter
password (str): Password of the vCenter
callback (function):... | Add vCenter on the switch
Args:
id(str) : Name of an established vCenter
url (bool) : vCenter URL
username (str): Username of the vCenter
password (str): Password of the vCenter
callback (function): A function executed upon completion of the
... |
def configuration_from_uri(cls, persistence_uri):
"""
Return a configuration object.
"""
db_uri, persistence_state_id = cls.parse_persistence_uri(persistence_uri)
engine = create_engine(db_uri)
Base.metadata.create_all(engine)
Base.metadata.bind = engine
D... | Return a configuration object. |
def explode(self):
"""Explode realms with each realm_members and higher_realms to get all the
realms sub realms.
:return: None
"""
# Manage higher realms where defined
for realm in [tmp_realm for tmp_realm in self if tmp_realm.higher_realms]:
for parent in re... | Explode realms with each realm_members and higher_realms to get all the
realms sub realms.
:return: None |
def robust_init(stochclass, tries, *args, **kwds):
"""Robust initialization of a Stochastic.
If the evaluation of the log-probability returns a ZeroProbability
error, due for example to a parent being outside of the support for
this Stochastic, the values of parents are randomly sampled until
a val... | Robust initialization of a Stochastic.
If the evaluation of the log-probability returns a ZeroProbability
error, due for example to a parent being outside of the support for
this Stochastic, the values of parents are randomly sampled until
a valid log-probability is obtained.
If the log-probabilit... |
def download(url, dest):
"""
Platform-agnostic downloader.
"""
u = urllib.FancyURLopener()
logger.info("Downloading %s..." % url)
u.retrieve(url, dest)
logger.info('Done, see %s' % dest)
return dest | Platform-agnostic downloader. |
def is_valid(self):
""" Checks recursively if the tree is valid
It is valid if each node splits correctly """
if not self:
return True
if self.left and self.data[self.axis] < self.left.data[self.axis]:
return False
if self.right and self.data[self.axis... | Checks recursively if the tree is valid
It is valid if each node splits correctly |
def s2m(self):
'''
Imports settings to meta
'''
m = '%s settings' % (IDENT)
self.meta.load(m, 'import %s' % (m), mdict=self.settings.get) | Imports settings to meta |
def _get_prepped_model_field(model_obj, field):
"""
Gets the value of a field of a model obj that is prepared for the db.
"""
# Get the field
field = model_obj._meta.get_field(field)
# Get the value
value = field.get_db_prep_save(getattr(model_obj, field.attname), connection)
# Return... | Gets the value of a field of a model obj that is prepared for the db. |
def _repr_latex_(self):
"""
This is used in IPython notebook it allows us to render the ODEProblem object in LaTeX.
How Cool is this?
"""
# TODO: we're mixing HTML with latex here. That is not necessarily a good idea, but works
# with IPython 1.2.0. Once IPython 2.0 is re... | This is used in IPython notebook it allows us to render the ODEProblem object in LaTeX.
How Cool is this? |
def show_dependencies(self, stream=sys.stdout):
"""Writes to the given stream the ASCII representation of the dependency tree."""
def child_iter(node):
return [d.node for d in node.deps]
def text_str(node):
return colored(str(node), color=node.status.color_opts["color"])... | Writes to the given stream the ASCII representation of the dependency tree. |
def create(cls, name, gateway, network, input_speed=None,
output_speed=None, domain_server_address=None,
provider_name=None, probe_address=None,
standby_mode_period=3600, standby_mode_timeout=30,
active_mode_period=5, active_mode_timeout=1, comment=None):
... | Create a new StaticNetlink to be used as a traffic handler.
:param str name: name of netlink Element
:param gateway_ref: gateway to map this netlink to. This can be an element
or str href.
:type gateway_ref: Router,Engine
:param list ref: network/s associated with this netli... |
def previous(self):
''' Returns previous image for same content_object and None if image
is the first. '''
try:
return self.__class__.objects.for_model(self.content_object,
self.content_type).\
filter(ord... | Returns previous image for same content_object and None if image
is the first. |
def _read_sections(ifile):
"""Read sections_in.txt file, if it exists."""
if os.path.exists(ifile):
return read_sections(ifile, exclude_ungrouped=True, prt=None) | Read sections_in.txt file, if it exists. |
def get_current_live_chat(self):
""" Check if there is a live chat on the go, so that we should take
over the AskMAMA page with the live chat.
"""
now = datetime.now()
chat = self.upcoming_live_chat()
if chat and chat.is_in_progress():
return chat
... | Check if there is a live chat on the go, so that we should take
over the AskMAMA page with the live chat. |
def _get_pos_name(code, name='parent', english=True, delimiter=':',
pos_tags=pos_map.POS_MAP):
"""Gets the part of speech name for *code*.
Joins the names together with *delimiter* if *name* is ``'all'``.
See :func:``pynlpir.pos_map.get_pos_name`` for more information.
"""
pos_n... | Gets the part of speech name for *code*.
Joins the names together with *delimiter* if *name* is ``'all'``.
See :func:``pynlpir.pos_map.get_pos_name`` for more information. |
def parse(s):
r"""
Returns a list of strings or format dictionaries to describe the strings.
May raise a ValueError if it can't be parsed.
>>> parse(">>> []")
['>>> []']
>>> #parse("\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\... | r"""
Returns a list of strings or format dictionaries to describe the strings.
May raise a ValueError if it can't be parsed.
>>> parse(">>> []")
['>>> []']
>>> #parse("\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m") |
def set_path(self, file_path):
"""
Set the path of the database.
Create the file if it does not exist.
"""
if not file_path:
self.read_data = self.memory_read
self.write_data = self.memory_write
elif not is_valid(file_path):
self.write_... | Set the path of the database.
Create the file if it does not exist. |
def dump_graph(self):
"""Dump a key-only representation of the schema to a dictionary. Every
known relation is a key with a value of a list of keys it is referenced
by.
"""
# we have to hold the lock for the entire dump, if other threads modify
# self.relations or any cac... | Dump a key-only representation of the schema to a dictionary. Every
known relation is a key with a value of a list of keys it is referenced
by. |
def update_slidepos(self):
"""
Periodically update the slide position.
Also farmed out to a thread to avoid hanging GUI main thread
"""
g = get_root(self).globals
if not g.cpars['focal_plane_slide_on']:
self.after(20000, self.update_slidepos)
retu... | Periodically update the slide position.
Also farmed out to a thread to avoid hanging GUI main thread |
def call_audit(func):
"""Print a detailed audit of all calls to this function."""
def audited_func(*args, **kwargs):
import traceback
stack = traceback.extract_stack()
r = func(*args, **kwargs)
func_name = func.__name__
print("@depth %d, trace %s -> %s(*%r, **%r) => %r" ... | Print a detailed audit of all calls to this function. |
def as_format(item, format_str='.2f'):
"""
Map a format string over a pandas object.
"""
if isinstance(item, pd.Series):
return item.map(lambda x: format(x, format_str))
elif isinstance(item, pd.DataFrame):
return item.applymap(lambda x: format(x, format_str)) | Map a format string over a pandas object. |
def _get_graph(graph, filename):
"""Retrieve or render a graph."""
try:
rendered = graph.rendered_file
except AttributeError:
try:
graph.render(os.path.join(server.tmpdir, filename), format='png')
rendered = filename
except OSError:
rendered = None... | Retrieve or render a graph. |
def mean_subtraction(x, mean, t, base_axis=1, update_running_mean=True):
r"""
It subtracts the mean of the elements of the input array,
and normalizes it to :math:`0`. Preprocessing arrays with this function has the effect of improving accuracy
in various tasks such as image classification.
At trai... | r"""
It subtracts the mean of the elements of the input array,
and normalizes it to :math:`0`. Preprocessing arrays with this function has the effect of improving accuracy
in various tasks such as image classification.
At training time, this function is defined as
.. math::
\begin{eqnarray... |
def _folder_item_assigned_worksheet(self, analysis_brain, item):
"""Adds an icon to the item dict if the analysis is assigned to a
worksheet and if the icon is suitable for the current context
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary cou... | Adds an icon to the item dict if the analysis is assigned to a
worksheet and if the icon is suitable for the current context
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row |
def raw_snapshot_data(self, name):
"""
::
GET /:login/machines/:id/snapshots/:name
:param name: identifier for snapshot
:type name: :py:class:`basestring`
:rtype: :py:class:`dict`
Used internally to get a raw dict of a singl... | ::
GET /:login/machines/:id/snapshots/:name
:param name: identifier for snapshot
:type name: :py:class:`basestring`
:rtype: :py:class:`dict`
Used internally to get a raw dict of a single machine snapshot. |
def for_account_hash(parent, account_hash):
"""
Returns a new AccountProxy that acquires the account with the
given hash, if such an account is known to the account manager.
It is an error if the account manager does not have such an
account.
"""
account = Account... | Returns a new AccountProxy that acquires the account with the
given hash, if such an account is known to the account manager.
It is an error if the account manager does not have such an
account. |
def launch_ipython_legacy_shell(args): # pylint: disable=unused-argument
"""Open the SolveBio shell (IPython wrapper) for older IPython versions"""
try:
from IPython.config.loader import Config
except ImportError:
_print("The SolveBio Python shell requires IPython.\n"
"To ins... | Open the SolveBio shell (IPython wrapper) for older IPython versions |
def create_secgroup_rule(self, protocol, from_port, to_port,
source, target):
"""
Creates a new server security group rule.
:param str protocol: E.g. ``tcp``, ``icmp``, etc...
:param int from_port: E.g. ``1``
:param int to_port: E.g. ``65535``
:param str s... | Creates a new server security group rule.
:param str protocol: E.g. ``tcp``, ``icmp``, etc...
:param int from_port: E.g. ``1``
:param int to_port: E.g. ``65535``
:param str source:
:param str target: |
def update(self, configuration, debug=None):
"""Update the internal configuration values, removing debug_only
handlers if debug is False. Returns True if the configuration has
changed from previous configuration values.
:param dict configuration: The logging configuration
:param... | Update the internal configuration values, removing debug_only
handlers if debug is False. Returns True if the configuration has
changed from previous configuration values.
:param dict configuration: The logging configuration
:param bool debug: Toggles use of debug_only loggers
:... |
def touch(args):
"""
%prog touch timestamp.info
Recover timestamps for files in the current folder.
CAUTION: you must execute this in the same directory as timestamp().
"""
from time import ctime
p = OptionParser(touch.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
... | %prog touch timestamp.info
Recover timestamps for files in the current folder.
CAUTION: you must execute this in the same directory as timestamp(). |
def corr_dw_v1(self):
"""Adjust the water stage drop to the highest value allowed and correct
the associated fluxes.
Note that method |corr_dw_v1| calls the method `interp_v` of the
respective application model. Hence the requirements of the actual
`interp_v` need to be considered additionally.
... | Adjust the water stage drop to the highest value allowed and correct
the associated fluxes.
Note that method |corr_dw_v1| calls the method `interp_v` of the
respective application model. Hence the requirements of the actual
`interp_v` need to be considered additionally.
Required control parameter... |
def delete(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Delete a security group.
CLI example::
salt myminion boto_secgroup.delete mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
... | Delete a security group.
CLI example::
salt myminion boto_secgroup.delete mysecgroup |
def get_assessment_notification_session_for_bank(self, assessment_receiver, bank_id):
"""Gets the ``OsidSession`` associated with the assessment notification service for the given bank.
arg: assessment_receiver
(osid.assessment.AssessmentReceiver): the assessment
rece... | Gets the ``OsidSession`` associated with the assessment notification service for the given bank.
arg: assessment_receiver
(osid.assessment.AssessmentReceiver): the assessment
receiver interface
arg: bank_id (osid.id.Id): the ``Id`` of the bank
return: (osid... |
def do_bugin(self, args):
"""bugin [ <logger> ] - add a console logging handler to a logger"""
args = args.split()
if _debug: ConsoleCmd._debug("do_bugin %r", args)
# get the logger name and logger
if args:
loggerName = args[0]
if loggerName in logging.L... | bugin [ <logger> ] - add a console logging handler to a logger |
def SA_tank(D, L, sideA=None, sideB=None, sideA_a=0,
sideB_a=0, sideA_f=None, sideA_k=None, sideB_f=None, sideB_k=None,
full_output=False):
r'''Calculates the surface are of a cylindrical tank with optional heads.
In the degenerate case of being provided with only `D` and `L`, provides... | r'''Calculates the surface are of a cylindrical tank with optional heads.
In the degenerate case of being provided with only `D` and `L`, provides
the surface area of a cylinder.
Parameters
----------
D : float
Diameter of the cylindrical section of the tank, [m]
L : float
Lengt... |
def rank_members_in(self, leaderboard_name, members_and_scores):
'''
Rank an array of members in the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param members_and_scores [Array] Variable list of members and scores.
'''
for member, score ... | Rank an array of members in the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param members_and_scores [Array] Variable list of members and scores. |
def update_context(self, ctx):
""" updates the query context with this clauses values """
assert isinstance(ctx, dict)
ctx[str(self.context_id)] = self.value | updates the query context with this clauses values |
def list_nodes_min(call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names and
their state is returned. This is the minimum amount of information needed to
check for existing VMs.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt... | Return a list of the VMs that are on the provider. Only a list of VM names and
their state is returned. This is the minimum amount of information needed to
check for existing VMs.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-cloud -f list_nodes_min packet-provider
... |
def remove_all_trips_fully_outside_buffer(db_conn, center_lat, center_lon, buffer_km, update_secondary_data=True):
"""
Not used in the regular filter process for the time being.
Parameters
----------
db_conn: sqlite3.Connection
connection to the GTFS object
center_lat: float
center_... | Not used in the regular filter process for the time being.
Parameters
----------
db_conn: sqlite3.Connection
connection to the GTFS object
center_lat: float
center_lon: float
buffer_km: float |
def load_checkpoints(self, checkpointDirs):
"""Load checkpoints from the checkpoint files into a dictionary.
The results are used to pre-populate the memoizer's lookup_table
Kwargs:
- checkpointDirs (list) : List of run folder to use as checkpoints
Eg. ['runinfo/001... | Load checkpoints from the checkpoint files into a dictionary.
The results are used to pre-populate the memoizer's lookup_table
Kwargs:
- checkpointDirs (list) : List of run folder to use as checkpoints
Eg. ['runinfo/001', 'runinfo/002']
Returns:
- dict... |
def require(*args, **kwargs):
'''
Install a set of packages using pip
This is designed to be an interface for IPython notebooks that
replicates the requirements.txt pip format. This lets notebooks
specify which versions of packages they need inside the notebook
itself.
This function is... | Install a set of packages using pip
This is designed to be an interface for IPython notebooks that
replicates the requirements.txt pip format. This lets notebooks
specify which versions of packages they need inside the notebook
itself.
This function is the general-purpose interface that lets
... |
def processResponse(self, arg, replytype, **kw):
"""
Parameters:
arg -- deferred
replytype -- typecode
"""
if self.debug:
log.msg('--->PROCESS REQUEST\n%s' %arg, debug=1)
for h in self.handlers:
arg.addCallback(h.processResponse, ... | Parameters:
arg -- deferred
replytype -- typecode |
def lit_count(self):
"""
The number of LEDs on the bar graph actually lit up. Note that just
like :attr:`value`, this can be negative if the LEDs are lit from last
to first.
"""
lit_value = self.value * len(self)
if not isinstance(self[0], PWMLED):
lit... | The number of LEDs on the bar graph actually lit up. Note that just
like :attr:`value`, this can be negative if the LEDs are lit from last
to first. |
def rename(name):
# type: (str) -> None
""" Give the currently developed hotfix a new name. """
from peltak.extra.gitflow import logic
if name is None:
name = click.prompt('Hotfix name')
logic.hotfix.rename(name) | Give the currently developed hotfix a new name. |
def decode_ay(ay):
"""Convert binary blob from DBus queries to strings."""
if ay is None:
return ''
elif isinstance(ay, str):
return ay
elif isinstance(ay, bytes):
return ay.decode('utf-8')
else:
# dbus.Array([dbus.Byte]) or any similar sequence type:
return b... | Convert binary blob from DBus queries to strings. |
def decode(self, inputs, context, inference=False):
"""
Applies the decoder to inputs, given the context from the encoder.
:param inputs: tensor with inputs (batch, seq_len) if 'batch_first'
else (seq_len, batch)
:param context: context from the encoder
:param infere... | Applies the decoder to inputs, given the context from the encoder.
:param inputs: tensor with inputs (batch, seq_len) if 'batch_first'
else (seq_len, batch)
:param context: context from the encoder
:param inference: if True inference mode, if False training mode |
def fromstring(cls, s, *args, **kwargs):
""" Returns a new Pattern from the given string.
Constraints are separated by a space.
If a constraint contains a space, it must be wrapped in [].
"""
s = s.replace("\(", "&lparen;")
s = s.replace("\)", "&rparen;")
... | Returns a new Pattern from the given string.
Constraints are separated by a space.
If a constraint contains a space, it must be wrapped in []. |
def subscribe(self, clock_name: str=None, clock_slots: Iterable[str]=None, subscriptions: Dict[str, Any]={}):
"""Subscribes this Area to the given Areas and optionally given Slots. Must be called before the Area is run.
Args:
clock_name: The name of the Area that is used as synchronizing Clock.
clock_slots: ... | Subscribes this Area to the given Areas and optionally given Slots. Must be called before the Area is run.
Args:
clock_name: The name of the Area that is used as synchronizing Clock.
clock_slots: The slots of the Clock relevant to this Area.
subscriptions: A dictionary containing the relevant Areas names as... |
def flush(self, preserve=None):
"""
Delete the cache for this dataset. Optionally preserve
a region. Helpful when working with overlaping volumes.
Warning: the preserve option is not multi-process safe.
You're liable to end up deleting the entire cache.
Optional:
preserve (Bbox: None): P... | Delete the cache for this dataset. Optionally preserve
a region. Helpful when working with overlaping volumes.
Warning: the preserve option is not multi-process safe.
You're liable to end up deleting the entire cache.
Optional:
preserve (Bbox: None): Preserve chunks located partially
or ... |
def immediate(self, name, value):
"""
Load something immediately
"""
setattr(self, name, value)
self._all.add(name) | Load something immediately |
def setconf(self, conf, rscpath, logger=None):
"""Set input conf in input path.
:param Configuration conf: conf to write to path.
:param str rscpath: specific resource path to use.
:param Logger logger: used to log info/errors.
:param bool error: raise catched errors.
:r... | Set input conf in input path.
:param Configuration conf: conf to write to path.
:param str rscpath: specific resource path to use.
:param Logger logger: used to log info/errors.
:param bool error: raise catched errors.
:raises: ConfDriver.Error in case of error and input error. |
def queue_it(queue=g_queue, **put_args):
"""
Wrapper. Instead of returning the result of the function, add it to a queue.
.. code: python
import reusables
import queue
my_queue = queue.Queue()
@reusables.queue_it(my_queue)
def func(a):
return a
... | Wrapper. Instead of returning the result of the function, add it to a queue.
.. code: python
import reusables
import queue
my_queue = queue.Queue()
@reusables.queue_it(my_queue)
def func(a):
return a
func(10)
print(my_queue.get())
# 1... |
def in_resource(cls, session_type):
"""Returns True if the attribute is part of a given session type.
The session_type is a tuple with the interface type and resource_class
:type session_type: (constants.InterfaceType, str)
:rtype: bool
"""
if cls.resources is AllSessio... | Returns True if the attribute is part of a given session type.
The session_type is a tuple with the interface type and resource_class
:type session_type: (constants.InterfaceType, str)
:rtype: bool |
def switch(self, idx, control):
"""Switch a single control of <idx>"""
old = None
new = None
if control == 'Q':
if self.PQ[idx] == 1:
old = 'PQ'
new = 'PV'
elif self.vQ[idx] == 1:
old = 'vQ'
new = 'vV... | Switch a single control of <idx> |
def RunStateMethod(self, method_name, request=None, responses=None):
"""Completes the request by calling the state method.
Args:
method_name: The name of the state method to call.
request: A RequestState protobuf.
responses: A list of FlowMessages responding to the request.
"""
if sel... | Completes the request by calling the state method.
Args:
method_name: The name of the state method to call.
request: A RequestState protobuf.
responses: A list of FlowMessages responding to the request. |
def enterprise_login_required(view):
"""
View decorator for allowing authenticated user with valid enterprise UUID.
This decorator requires enterprise identifier as a parameter
`enterprise_uuid`.
This decorator will throw 404 if no kwarg `enterprise_uuid` is provided to
the decorated view .
... | View decorator for allowing authenticated user with valid enterprise UUID.
This decorator requires enterprise identifier as a parameter
`enterprise_uuid`.
This decorator will throw 404 if no kwarg `enterprise_uuid` is provided to
the decorated view .
If there is no enterprise in database against ... |
def load_terminfo(terminal_name=None, fallback='vt100'):
"""
If the environment variable TERM is unset try with `fallback` if not empty.
vt100 is a popular terminal supporting ANSI X3.64.
"""
terminal_name = os.getenv('TERM')
if not terminal_name:
if not fallback:
raise Term... | If the environment variable TERM is unset try with `fallback` if not empty.
vt100 is a popular terminal supporting ANSI X3.64. |
def get_children(self, node):
"""Get children."""
# if node in self.nodes:
try:
index = self.nodes.index(node) + 1
return [self.nodes[index]]
except IndexError:
return [] | Get children. |
def create_pipeline(url, auth, json_payload, verify_ssl):
"""Create a new pipeline.
Args:
url (str): the host url in the form 'http://host:port/'.
auth (tuple): a tuple of username, and password.
json_payload (dict): the exported json paylod as a dictionary.
ver... | Create a new pipeline.
Args:
url (str): the host url in the form 'http://host:port/'.
auth (tuple): a tuple of username, and password.
json_payload (dict): the exported json paylod as a dictionary.
verify_ssl (bool): whether to verify ssl certificates
Returns... |
def preload(python_data: LdapObject, database: Optional[Database] = None) -> LdapObject:
""" Preload all NotLoaded fields in LdapObject. """
changes = {}
# Load objects within lists.
def preload_item(value: Any) -> Any:
if isinstance(value, NotLoaded):
return value.load(database)
... | Preload all NotLoaded fields in LdapObject. |
def profileUpperLimit(self, delta = 2.71):
"""
Compute one-sided upperlimit via profile method.
"""
a = self.p_2
b = self.p_1
if self.vertex_x < 0:
c = self.p_0 + delta
else:
c = self.p_0 - self.vertex_y + delta
if b**2 - 4. * a * ... | Compute one-sided upperlimit via profile method. |
def get(no_create=False, server=None, port=None, force_uuid=None):
"""Get the thread local singleton"""
pid = os.getpid()
thread = threading.current_thread()
wdb = Wdb._instances.get((pid, thread))
if not wdb and not no_create:
wdb = object.__new__(Wdb)
Wd... | Get the thread local singleton |
def display(self, filename=None):
"""Displays/opens the doc using the OS's default application."""
if filename is None:
filename = 'display_temp.svg'
self.save(filename)
open_in_browser(filename) | Displays/opens the doc using the OS's default application. |
def validate(self, table: pd.DataFrame, failed_only=False) -> pd.DataFrame:
"""Return a dataframe of validation results for the appropriate series vs the vector of validators.
Args:
table (pd.DataFrame): A dataframe on which to apply validation logic.
failed_only (bool): If ``Tr... | Return a dataframe of validation results for the appropriate series vs the vector of validators.
Args:
table (pd.DataFrame): A dataframe on which to apply validation logic.
failed_only (bool): If ``True``: return only the indexes that failed to validate. |
def assert_gt(left, right, message=None, extra=None):
"""Raises an AssertionError if left_hand <= right_hand."""
assert left > right, _assert_fail_message(message, left, right, "<=", extra) | Raises an AssertionError if left_hand <= right_hand. |
def enqueue_job(self, job):
"""
Move a scheduled job to a queue. In addition, it also does puts the job
back into the scheduler if needed.
"""
self.log.debug('Pushing {0} to {1}'.format(job.id, job.origin))
interval = job.meta.get('interval', None)
repeat = job.m... | Move a scheduled job to a queue. In addition, it also does puts the job
back into the scheduler if needed. |
def count(self, model_class, conditions=None):
'''
Counts the number of records in the model's table.
- `model_class`: the model to count.
- `conditions`: optional SQL conditions (contents of the WHERE clause).
'''
query = 'SELECT count() FROM $table'
if conditio... | Counts the number of records in the model's table.
- `model_class`: the model to count.
- `conditions`: optional SQL conditions (contents of the WHERE clause). |
def delete(ctx, opts, owner_repo_identifier, yes):
"""
Delete an entitlement from a repository.
- OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org),
and the REPO name that has an entitlement identified by IDENTIFIER. All
separated by a slash.
Example: 'your-org/your... | Delete an entitlement from a repository.
- OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org),
and the REPO name that has an entitlement identified by IDENTIFIER. All
separated by a slash.
Example: 'your-org/your-repo/abcdef123456'
Full CLI example:
$ cloudsmith ... |
def array(
item_processor, # type: Processor
alias=None, # type: Optional[Text]
nested=None, # type: Optional[Text]
omit_empty=False, # type: bool
hooks=None # type: Optional[Hooks]
):
# type: (...) -> RootProcessor
"""
Create an array processor that can be used ... | Create an array processor that can be used to parse and serialize array data.
XML arrays may be nested within an array element, or they may be embedded
within their parent. A nested array would look like:
.. sourcecode:: xml
<root-element>
<some-element>ABC</some-element>
... |
def get_or_create_evidence(self, citation: Citation, text: str) -> Evidence:
"""Create an entry and object for given evidence if it does not exist."""
sha512 = hash_evidence(text=text, type=str(citation.type), reference=str(citation.reference))
if sha512 in self.object_cache_evidence:
... | Create an entry and object for given evidence if it does not exist. |
def from_str(cls, timestr, shaked=False):
"""Use `dateutil` module to parse the give string
:param basestring timestr: string representing a date to parse
:param bool shaked: whether the input parameter been already
cleaned or not.
"""
orig = timestr
if not shake... | Use `dateutil` module to parse the give string
:param basestring timestr: string representing a date to parse
:param bool shaked: whether the input parameter been already
cleaned or not. |
def npz_to_W_pdf(path=None, regx='w1pre_[0-9]+\.(npz)'):
r"""Convert the first weight matrix of `.npz` file to `.pdf` by using `tl.visualize.W()`.
Parameters
----------
path : str
A folder path to `npz` files.
regx : str
Regx for the file name.
Examples
---------
Conver... | r"""Convert the first weight matrix of `.npz` file to `.pdf` by using `tl.visualize.W()`.
Parameters
----------
path : str
A folder path to `npz` files.
regx : str
Regx for the file name.
Examples
---------
Convert the first weight matrix of w1_pre...npz file to w1_pre...pd... |
def set_backlight(self, backlight):
"""Enable or disable the backlight. If PWM is not enabled (default), a
non-zero backlight value will turn on the backlight and a zero value will
turn it off. If PWM is enabled, backlight can be any value from 0.0 to
1.0, with 1.0 being full intensity... | Enable or disable the backlight. If PWM is not enabled (default), a
non-zero backlight value will turn on the backlight and a zero value will
turn it off. If PWM is enabled, backlight can be any value from 0.0 to
1.0, with 1.0 being full intensity backlight. |
def define_standalone_options(parser, extra_options=None):
'''
Adds the options specific to the database connection.
Parses the agency configuration files and uses its configuration as the
default values.
'''
c = config.parse_service_config()
parser.add_option('--dbhost', '-H', action='stor... | Adds the options specific to the database connection.
Parses the agency configuration files and uses its configuration as the
default values. |
def is_citeable(publication_info):
"""Check some fields in order to define if the article is citeable.
:param publication_info: publication_info field
already populated
:type publication_info: list
"""
def _item_has_pub_info(item):
return all(
key in item for key in (
... | Check some fields in order to define if the article is citeable.
:param publication_info: publication_info field
already populated
:type publication_info: list |
def add_permission(FunctionName, StatementId, Action, Principal, SourceArn=None,
SourceAccount=None, Qualifier=None,
region=None, key=None, keyid=None, profile=None):
'''
Add a permission to a lambda function.
Returns {added: true} if the permission was added and retur... | Add a permission to a lambda function.
Returns {added: true} if the permission was added and returns
{added: False} if the permission was not added.
CLI Example:
.. code-block:: bash
salt myminion boto_lamba.add_permission my_function my_id "lambda:*" \\
s3.amazona... |
def move(self, dest, src):
"""Move element from sequence, member from mapping.
:param dest: the destination
:type dest: Pointer
:param src: the source
:type src: Pointer
:return: resolved document
:rtype: Target
.. note::
This operation is f... | Move element from sequence, member from mapping.
:param dest: the destination
:type dest: Pointer
:param src: the source
:type src: Pointer
:return: resolved document
:rtype: Target
.. note::
This operation is functionally identical to a "remove" op... |
def order_by(self, key_selector=identity):
'''Sorts by a key in ascending order.
Introduces a primary sorting order to the sequence. Additional sort
criteria should be specified by subsequent calls to then_by() and
then_by_descending(). Calling order_by() or order_by_descending() on
... | Sorts by a key in ascending order.
Introduces a primary sorting order to the sequence. Additional sort
criteria should be specified by subsequent calls to then_by() and
then_by_descending(). Calling order_by() or order_by_descending() on
the results of a call to order_by() will introdu... |
def stop(self):
"""Stop the process."""
logger.info("stopping process")
self.watcher.stop()
os.kill(self.child_pid, signal.SIGTERM) | Stop the process. |
def _raiseImageMissing(self, pattern):
""" Builds an ImageMissing event and triggers the default handler (or the custom handler,
if one has been specified). Returns True if throwing method should retry, False if it
should skip, and throws an exception if it should abort. """
event = Imag... | Builds an ImageMissing event and triggers the default handler (or the custom handler,
if one has been specified). Returns True if throwing method should retry, False if it
should skip, and throws an exception if it should abort. |
def get_labels(self, plt, label_fontsize=10):
"""
Handles the optional labelling of the plot with relevant quantities
Args:
plt (plt): Plot of the locpot vs c axis
label_fontsize (float): Fontsize of labels
Returns Labelled plt
"""
# center of vac... | Handles the optional labelling of the plot with relevant quantities
Args:
plt (plt): Plot of the locpot vs c axis
label_fontsize (float): Fontsize of labels
Returns Labelled plt |
def _update_settings(self, dialect):
"""Sets the widget settings to those of the chosen dialect"""
# the first parameter is the dialect itself --> ignore
for parameter in self.csv_params[2:]:
pname, ptype, plabel, phelp = parameter
widget = self._widget_from_p(pname, pt... | Sets the widget settings to those of the chosen dialect |
def upload(self, login, package_name, release, basename, fd, distribution_type,
description='', md5=None, size=None, dependencies=None, attrs=None, channels=('main',), callback=None):
'''
Upload a new distribution to a package release.
:param login: the login of the package owner... | Upload a new distribution to a package release.
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param basename: the basename of the distribution to download
:param fd: a file like object... |
def make_simple(self):
"""
Return a cylinder with the thread's average radius & length.
:math:`radius = (inner_radius + outer_radius) / 2`
"""
(inner_radius, outer_radius) = self.get_radii()
radius = (inner_radius + outer_radius) / 2
return cadquery.Workplane('XY... | Return a cylinder with the thread's average radius & length.
:math:`radius = (inner_radius + outer_radius) / 2` |
def safe_either(method, dictionary, key1, key2, default_value=None):
"""A helper-wrapper for the safe_value_2() family."""
value = method(dictionary, key1)
return value if value is not None else method(dictionary, key2, default_value) | A helper-wrapper for the safe_value_2() family. |
def clear_alarms(alarm):
'''
Clear (acknowledge) an alarm event. The arguments are “all” for all current
alarms, a specific alarm number (e.g. ‘‘1’‘), or an alarm string identifier
(e.g. ‘’MGMT_ALARM_PROXY_CONFIG_ERROR’‘).
.. code-block:: bash
salt '*' trafficserver.clear_alarms [all | #ev... | Clear (acknowledge) an alarm event. The arguments are “all” for all current
alarms, a specific alarm number (e.g. ‘‘1’‘), or an alarm string identifier
(e.g. ‘’MGMT_ALARM_PROXY_CONFIG_ERROR’‘).
.. code-block:: bash
salt '*' trafficserver.clear_alarms [all | #event | name] |
def open(self):
'''Opens the stream for reading.'''
options = copy(self.__options)
# Get scheme and format if not already given
compression = None
if self.__scheme is None or self.__format is None:
detected_scheme, detected_format = helpers.detect_scheme_and_format(s... | Opens the stream for reading. |
def FindByIndex(node, index):
'''
Method which finds child according to index. Applies only to nodes whose children are sorted into a dict,
so if the current node's children are in a list it will recursively search - similarly if the index is not found
in the current node's dictionary indexes.
:para... | Method which finds child according to index. Applies only to nodes whose children are sorted into a dict,
so if the current node's children are in a list it will recursively search - similarly if the index is not found
in the current node's dictionary indexes.
:param node: current node to search for
:pa... |
def _get_field(self, field):
"""
Queries the api for a single field for the record by `id`.
This method should only be called indirectly by cached properties.
:param field: name of the record field to load
"""
if not hasattr(self, "id") or self.id is None:
rai... | Queries the api for a single field for the record by `id`.
This method should only be called indirectly by cached properties.
:param field: name of the record field to load |
def get_user_permissions(self, username):
"""
:returns: list of dicts, or an empty list if there are no permissions.
:param string username: User to set permissions for.
"""
path = Client.urls['user_permissions'] % (username,)
conns = self._call(path, 'GET')
ret... | :returns: list of dicts, or an empty list if there are no permissions.
:param string username: User to set permissions for. |
def delete_many(self, mongo_collection, filter_doc, mongo_db=None, **kwargs):
"""
Deletes one or more documents in a mongo collection.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.delete_many
:param mongo_collection: The name of the co... | Deletes one or more documents in a mongo collection.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.delete_many
:param mongo_collection: The name of the collection to delete from.
:type mongo_collection: str
:param filter_doc: A query th... |
def _get_argspec(func):
"""Helper function to support both Python versions"""
if inspect.isclass(func):
func = func.__init__
if not inspect.isfunction(func):
# Init function not existing
return [], False
parameters = inspect.signature(func).parameters
args = []
uses_stars... | Helper function to support both Python versions |
def _headline(self, error, i: int) -> str:
"""
Format the error message's headline
"""
msgs = Msg()
# get the error title
if error.errclass == "fatal":
msg = msgs.fatal(i)
elif error.errclass == "warning":
msg = msgs.warning(i)
elif... | Format the error message's headline |
def dataset(self, **kwargs):
""" Return a key that specifies the data selection
"""
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
self._replace_none(kwargs_copy)
try:
return NameFactory.dataset_format.format(**kwargs_copy)
except Key... | Return a key that specifies the data selection |
def subsample(self):
"""
Subsample 1000 reads from the baited files
"""
# Create the threads for the analysis
logging.info('Subsampling FASTQ reads')
for _ in range(self.cpus):
threads = Thread(target=self.subsamplethreads, args=())
threads.setDaem... | Subsample 1000 reads from the baited files |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: UsageContext for this UsageInstance
:rtype: twilio.rest.preview.wireless.sim.usage.UsageContext
... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: UsageContext for this UsageInstance
:rtype: twilio.rest.preview.wireless.sim.usage.UsageContext |
def _handleBulletWidth(bulletText, style, maxWidths):
"""
work out bullet width and adjust maxWidths[0] if neccessary
"""
if bulletText:
if isinstance(bulletText, basestring):
bulletWidth = stringWidth(bulletText, style.bulletFontName, style.bulletFontSize)
else:
... | work out bullet width and adjust maxWidths[0] if neccessary |
def _poor_convergence(z, r, f, bn, mvec):
"""
Test for poor convergence based on three function evaluations.
This test evaluates the function at the three points and returns false if
the relative error is greater than 1e-3.
"""
check_points = (-0.4 + 0.3j, 0.7 + 0.2j, 0.02 - 0.06j)
diffs = ... | Test for poor convergence based on three function evaluations.
This test evaluates the function at the three points and returns false if
the relative error is greater than 1e-3. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.