code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def attach(domain, filename):
'''Attach existing dataset to their harvest remote id before harvesting.
The expected csv file format is the following:
- a column with header "local" and the local IDs or slugs
- a column with header "remote" and the remote IDs
The delimiter should be ";". columns o... | Attach existing dataset to their harvest remote id before harvesting.
The expected csv file format is the following:
- a column with header "local" and the local IDs or slugs
- a column with header "remote" and the remote IDs
The delimiter should be ";". columns order
and extras columns does not ... |
def Guo_Sun(dp, voidage, vs, rho, mu, Dt, L=1):
r'''Calculates pressure drop across a packed bed of spheres using a
correlation developed in [1]_. This is valid for highly-packed particles
at particle/tube diameter ratios between 2 and 3, where a ring packing
structure occurs. If a packing ratio is so... | r'''Calculates pressure drop across a packed bed of spheres using a
correlation developed in [1]_. This is valid for highly-packed particles
at particle/tube diameter ratios between 2 and 3, where a ring packing
structure occurs. If a packing ratio is so low, it is important to use this
model because ... |
def pop_context(self):
"""Pops the last set of keyword arguments provided to the processor."""
processor = getattr(self, 'processor', None)
if processor is not None:
pop_context = getattr(processor, 'pop_context', None)
if pop_context is None:
pop_context ... | Pops the last set of keyword arguments provided to the processor. |
def plot_dict(self, flags, label='key', known='x', **kwargs):
"""Plot a `~gwpy.segments.DataQualityDict` onto these axes
Parameters
----------
flags : `~gwpy.segments.DataQualityDict`
data-quality dict to display
label : `str`, optional
labelling system ... | Plot a `~gwpy.segments.DataQualityDict` onto these axes
Parameters
----------
flags : `~gwpy.segments.DataQualityDict`
data-quality dict to display
label : `str`, optional
labelling system to use, or fixed label for all `DataQualityFlags`.
Special va... |
def Recurrent(step_model):
"""Apply a stepwise model over a sequence, maintaining state. For RNNs"""
ops = step_model.ops
def recurrent_fwd(seqs, drop=0.0):
lengths = [len(X) for X in seqs]
X, size_at_t, unpad = ops.square_sequences(seqs)
Y = ops.allocate((X.shape[0], X.shape[1], st... | Apply a stepwise model over a sequence, maintaining state. For RNNs |
def from_client_config(cls, client_config, scopes, **kwargs):
"""Creates a :class:`requests_oauthlib.OAuth2Session` from client
configuration loaded from a Google-format client secrets file.
Args:
client_config (Mapping[str, Any]): The client
configuration in the Goo... | Creates a :class:`requests_oauthlib.OAuth2Session` from client
configuration loaded from a Google-format client secrets file.
Args:
client_config (Mapping[str, Any]): The client
configuration in the Google `client secrets`_ format.
scopes (Sequence[str]): The lis... |
def lesser(lhs, rhs):
"""Returns the result of element-wise **lesser than** (<) comparison operation
with broadcasting.
For each element in input arrays, return 1(true) if lhs elements are less than rhs,
otherwise return 0(false).
Equivalent to ``lhs < rhs`` and ``mx.nd.broadcast_lesser(lhs, rhs)`... | Returns the result of element-wise **lesser than** (<) comparison operation
with broadcasting.
For each element in input arrays, return 1(true) if lhs elements are less than rhs,
otherwise return 0(false).
Equivalent to ``lhs < rhs`` and ``mx.nd.broadcast_lesser(lhs, rhs)``.
.. note::
If ... |
def find_poor_default_arg(node):
"""Finds poor default args"""
poor_defaults = [
ast.Call,
ast.Dict,
ast.DictComp,
ast.GeneratorExp,
ast.List,
ast.ListComp,
ast.Set,
ast.SetComp,
]
# pylint: disable=unidiomatic-typecheck
return (
... | Finds poor default args |
def LSRS(self, params):
"""
LSRS [Ra,] Ra, Rc
LSRS [Ra,] Rb, #imm5_counting
Logical shift right Rb by Rc or imm5 and store the result in Ra
imm5 counting is [1, 32]
In the register shift, the first two operands must be the same register
Ra, Rb, and Rc must be low... | LSRS [Ra,] Ra, Rc
LSRS [Ra,] Rb, #imm5_counting
Logical shift right Rb by Rc or imm5 and store the result in Ra
imm5 counting is [1, 32]
In the register shift, the first two operands must be the same register
Ra, Rb, and Rc must be low registers
If Ra is omitted, then it... |
def get_external_logger(name=None, short_name=" ", log_to_file=True):
"""
Get a logger for external modules, whose logging should usually be on a less verbose level.
:param name: Name for logger
:param short_name: Shorthand name for logger
:param log_to_file: Boolean, True if logger should log to a... | Get a logger for external modules, whose logging should usually be on a less verbose level.
:param name: Name for logger
:param short_name: Shorthand name for logger
:param log_to_file: Boolean, True if logger should log to a file as well.
:return: Logger |
def LOS_PRMin(Ds, dus, kPOut=None, Eps=1.e-12, Test=True):
""" Compute the point on the LOS where the major radius is minimum """
if Test:
assert Ds.ndim in [1,2] and 3 in Ds.shape and Ds.shape==dus.shape
assert kPOut is None or (Ds.ndim==1 and not hasattr(kPOut,'__iter__')) or (Ds.ndim==2 and ... | Compute the point on the LOS where the major radius is minimum |
def _update_srcmap(self, name, src, **kwargs):
"""Update the source map for an existing source in memory."""
k = self._create_srcmap(name, src, **kwargs)
scale = self._src_expscale.get(name, 1.0)
k *= scale
# Force the source map to be cached
# FIXME: No longer necessar... | Update the source map for an existing source in memory. |
def events(self):
"""
Gets the Events API client.
Returns:
Events:
"""
if not self.__events:
self.__events = Events(self.__connection)
return self.__events | Gets the Events API client.
Returns:
Events: |
def is_transition(self):
"""Is this variant and pyrimidine to pyrimidine change or purine to purine change"""
return self.is_snv and is_purine(self.ref) == is_purine(self.alt) | Is this variant and pyrimidine to pyrimidine change or purine to purine change |
def malloc(self, sim_size):
"""
A somewhat faithful implementation of libc `malloc`.
:param sim_size: the amount of memory (in bytes) to be allocated
:returns: the address of the allocation, or a NULL pointer if the allocation failed
"""
raise NotImplementedError(... | A somewhat faithful implementation of libc `malloc`.
:param sim_size: the amount of memory (in bytes) to be allocated
:returns: the address of the allocation, or a NULL pointer if the allocation failed |
def simple(self):
'''A string representation with only one period delimiter.'''
if self._days:
return '%sD' % self.totaldays
elif self.months:
return '%sM' % self._months
elif self.years:
return '%sY' % self.years
else:
return '' | A string representation with only one period delimiter. |
def webui_data_stores_saved_query_key(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
webui = ET.SubElement(config, "webui", xmlns="http://tail-f.com/ns/webui")
data_stores = ET.SubElement(webui, "data-stores")
saved_query = ET.SubElement(data_st... | Auto Generated Code |
def indicator(self, indicator_type, summary, **kwargs):
"""Add Indicator data to Batch object.
Args:
indicator_type (str): The ThreatConnect define Indicator type.
summary (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this I... | Add Indicator data to Batch object.
Args:
indicator_type (str): The ThreatConnect define Indicator type.
summary (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp ... |
def alert_stream(self, reset_event, kill_event):
"""Open event stream."""
_LOGGING.debug('Stream Thread Started: %s, %s', self.name, self.cam_id)
start_event = False
parse_string = ""
fail_count = 0
url = '%s/ISAPI/Event/notification/alertStream' % self.root_url
... | Open event stream. |
def write_response(self, response):
"""
Writes response content synchronously to the transport.
"""
if self._response_timeout_handler:
self._response_timeout_handler.cancel()
self._response_timeout_handler = None
try:
keep_alive = self.keep_ali... | Writes response content synchronously to the transport. |
def RemoveBackground(EPIC, campaign=None):
'''
Returns :py:obj:`True` or :py:obj:`False`, indicating whether or not
to remove the background flux for the target. If ``campaign < 3``,
returns :py:obj:`True`, otherwise returns :py:obj:`False`.
'''
if campaign is None:
campaign = Campaign... | Returns :py:obj:`True` or :py:obj:`False`, indicating whether or not
to remove the background flux for the target. If ``campaign < 3``,
returns :py:obj:`True`, otherwise returns :py:obj:`False`. |
def area(x,y):
"""
Calculate the area of a polygon given as x(...),y(...)
Implementation of Shoelace formula
"""
# http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates
return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))) | Calculate the area of a polygon given as x(...),y(...)
Implementation of Shoelace formula |
def _post_clean(self):
"""
Rewrite the error dictionary, so that its keys correspond to the model fields.
"""
super(NgModelFormMixin, self)._post_clean()
if self._errors and self.prefix:
self._errors = ErrorDict((self.add_prefix(name), value) for name, value in self._... | Rewrite the error dictionary, so that its keys correspond to the model fields. |
def constant_time_compare(val1, val2):
"""Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match. Do
not use this function for anything else than comparision with known
length targets.
This is should be implemented in C in ... | Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match. Do
not use this function for anything else than comparision with known
length targets.
This is should be implemented in C in order to get it completely right. |
def createCellsFixedNum (self):
''' Create population cells based on fixed number of cells'''
from .. import sim
cells = []
self.rand.Random123(self.tags['numCells'], sim.net.lastGid, sim.cfg.seeds['loc'])
self.rand.uniform(0, 1)
vec = h.Vector(self.tags['numCells']*3)
... | Create population cells based on fixed number of cells |
def read_bit(self):
"""Read a single boolean value."""
if not self.bitcount:
self.bits = ord(self.input.read(1))
self.bitcount = 8
result = (self.bits & 1) == 1
self.bits >>= 1
self.bitcount -= 1
return result | Read a single boolean value. |
def pca_eig(x):
"""Calculate PCA using eigenvalue decomposition.
Parameters
----------
x : ndarray, shape (channels, samples)
Two-dimensional input data.
Returns
-------
w : ndarray, shape (channels, channels)
Eigenvectors (principal components) (in columns).
s : nd... | Calculate PCA using eigenvalue decomposition.
Parameters
----------
x : ndarray, shape (channels, samples)
Two-dimensional input data.
Returns
-------
w : ndarray, shape (channels, channels)
Eigenvectors (principal components) (in columns).
s : ndarray, shape (channels,... |
def organization_fields(self, organization):
"""
Retrieve the organization fields for this organization.
:param organization: Organization object or id
"""
return self._query_zendesk(self.endpoint.organization_fields, 'organization_field', id=organization) | Retrieve the organization fields for this organization.
:param organization: Organization object or id |
def iplot_state(quantum_state, method='city', figsize=None):
"""Plot the quantum state.
Args:
quantum_state (ndarray): statevector or density matrix
representation of a quantum state.
method (str): Plotting method to use.
figsize (tuple): Figure size in ... | Plot the quantum state.
Args:
quantum_state (ndarray): statevector or density matrix
representation of a quantum state.
method (str): Plotting method to use.
figsize (tuple): Figure size in pixels.
Raises:
VisualizationError: if the input is not... |
def anim(self, start=0, stop=None, fps=30):
"""
Method to return a matplotlib animation. The start and stop
frames may be specified as well as the fps.
"""
figure = self.state or self.initialize_plot()
anim = animation.FuncAnimation(figure, self.update_frame,
... | Method to return a matplotlib animation. The start and stop
frames may be specified as well as the fps. |
def _get_policies(self):
"""Returns all the policy names for a given user"""
username = self._get_username_for_key()
policies = self.client.list_user_policies(
UserName=username
)
return policies | Returns all the policy names for a given user |
def get_language_pairs(self, train_langs=None):
'''
Returns the language pairs available on unbabel
'''
if train_langs is None:
result = self.api_call('language_pair/')
else:
result = self.api_call(
'language_pair/?train_langs={}'.forma... | Returns the language pairs available on unbabel |
def get_overlay(self):
"""
Function make 3D data from dicom file slices. There are usualy
more overlays in the data.
"""
overlay = {}
dcmlist = self.files_in_serie
for i in range(len(dcmlist)):
onefile = dcmlist[i]
logger.info("reading '%s... | Function make 3D data from dicom file slices. There are usualy
more overlays in the data. |
def climate_stats(self, startclim, endclim, type, **kwargs):
r""" Returns a dictionary of aggregated yearly climate statistics (count, standard deviation,
average, median, maximum, minimum, min time, and max time depending on user specified type) of a time series
for a specified range of time at... | r""" Returns a dictionary of aggregated yearly climate statistics (count, standard deviation,
average, median, maximum, minimum, min time, and max time depending on user specified type) of a time series
for a specified range of time at user specified location. Users must specify at least one geographic... |
def _validate_positional_arguments(args):
"""
To validate the positional argument feature - https://github.com/Azure/azure-cli/pull/6055.
Assuming that unknown commands are positional arguments immediately
led by words that only appear at the end of the commands
Slight modification of
https://g... | To validate the positional argument feature - https://github.com/Azure/azure-cli/pull/6055.
Assuming that unknown commands are positional arguments immediately
led by words that only appear at the end of the commands
Slight modification of
https://github.com/Azure/azure-cli/blob/dev/src/azure-cli-core/... |
def _redefines_import(node):
""" Detect that the given node (AssignName) is inside an
exception handler and redefines an import from the tryexcept body.
Returns True if the node redefines an import, False otherwise.
"""
current = node
while current and not isinstance(current.parent, astroid.Exce... | Detect that the given node (AssignName) is inside an
exception handler and redefines an import from the tryexcept body.
Returns True if the node redefines an import, False otherwise. |
def get_computer_desc():
'''
Get PRETTY_HOSTNAME value stored in /etc/machine-info
If this file doesn't exist or the variable doesn't exist
return False.
:return: Value of PRETTY_HOSTNAME if this does not exist False.
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' sys... | Get PRETTY_HOSTNAME value stored in /etc/machine-info
If this file doesn't exist or the variable doesn't exist
return False.
:return: Value of PRETTY_HOSTNAME if this does not exist False.
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' system.get_computer_desc |
def shift(self, top=None, right=None, bottom=None, left=None):
"""
Shift the bounding box from one or more image sides, i.e. move it on the x/y-axis.
Parameters
----------
top : None or int, optional
Amount of pixels by which to shift the bounding box from the top.
... | Shift the bounding box from one or more image sides, i.e. move it on the x/y-axis.
Parameters
----------
top : None or int, optional
Amount of pixels by which to shift the bounding box from the top.
right : None or int, optional
Amount of pixels by which to shif... |
def add_remote(name, location):
'''
Adds a new location to install flatpak packages from.
Args:
name (str): The repository's name.
location (str): The location of the repository.
Returns:
dict: The ``result`` and ``output``.
CLI Example:
.. code-block:: bash
... | Adds a new location to install flatpak packages from.
Args:
name (str): The repository's name.
location (str): The location of the repository.
Returns:
dict: The ``result`` and ``output``.
CLI Example:
.. code-block:: bash
salt '*' flatpak.add_remote flathub https://... |
def apply_defaults(func):
"""
Function decorator that Looks for an argument named "default_args", and
fills the unspecified arguments from it.
Since python2.* isn't clear about which arguments are missing when
calling a function, and that this can be quite confusing with multi-level
inheritance... | Function decorator that Looks for an argument named "default_args", and
fills the unspecified arguments from it.
Since python2.* isn't clear about which arguments are missing when
calling a function, and that this can be quite confusing with multi-level
inheritance and argument defaults, this decorator... |
def _set_typeattr(typeattr, existing_ta = None):
"""
Add or updsate a type attribute.
If an existing type attribute is provided, then update.
Checks are performed to ensure that the dimension provided on the
type attr (not updateable) is the same as that on the referring attribute.
... | Add or updsate a type attribute.
If an existing type attribute is provided, then update.
Checks are performed to ensure that the dimension provided on the
type attr (not updateable) is the same as that on the referring attribute.
The unit provided (stored on tattr) must conform to the d... |
def load_data(handle, reader=None):
'''Unpack data into a raw data wrapper'''
if not reader:
reader = os.path.splitext(handle)[1][1:].lower()
if reader not in _READERS:
raise NeuroMError('Do not have a loader for "%s" extension' % reader)
filename = _get_file(handle)
try:
r... | Unpack data into a raw data wrapper |
def genome_info(genome, info):
"""
return genome info for choosing representative
if ggKbase table provided - choose rep based on SCGs and genome length
- priority for most SCGs - extra SCGs, then largest genome
otherwise, based on largest genome
"""
try:
scg = info['#SCG... | return genome info for choosing representative
if ggKbase table provided - choose rep based on SCGs and genome length
- priority for most SCGs - extra SCGs, then largest genome
otherwise, based on largest genome |
def get(self, sid):
"""
Constructs a ModelBuildContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildContext
:rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildContext
"""
... | Constructs a ModelBuildContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildContext
:rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildContext |
def cull_to_timestep(self, timestep=1):
"""Get a collection with only datetimes that fit a timestep."""
valid_s = self.header.analysis_period.VALIDTIMESTEPS.keys()
assert timestep in valid_s, \
'timestep {} is not valid. Choose from: {}'.format(timestep, valid_s)
new_ap, new... | Get a collection with only datetimes that fit a timestep. |
def max_dimension(cellmap, sheet = None):
"""
This function calculates the maximum dimension of the workbook or optionally the worksheet. It returns a tupple
of two integers, the first being the rows and the second being the columns.
:param cellmap: all the cells that should be used to calculate the ma... | This function calculates the maximum dimension of the workbook or optionally the worksheet. It returns a tupple
of two integers, the first being the rows and the second being the columns.
:param cellmap: all the cells that should be used to calculate the maximum.
:param sheet: (optionally) a string with t... |
def bootstrap_standby_leader(self):
""" If we found 'standby' key in the configuration, we need to bootstrap
not a real master, but a 'standby leader', that will take base backup
from a remote master and start follow it.
"""
clone_source = self.get_remote_master()
... | If we found 'standby' key in the configuration, we need to bootstrap
not a real master, but a 'standby leader', that will take base backup
from a remote master and start follow it. |
def bst(height=3, is_perfect=False):
"""Generate a random BST (binary search tree) and return its root node.
:param height: Height of the BST (default: 3, range: 0 - 9 inclusive).
:type height: int
:param is_perfect: If set to True (default: False), a perfect BST with all
levels filled is retur... | Generate a random BST (binary search tree) and return its root node.
:param height: Height of the BST (default: 3, range: 0 - 9 inclusive).
:type height: int
:param is_perfect: If set to True (default: False), a perfect BST with all
levels filled is returned. If set to False, a perfect BST may stil... |
def head(self):
"""
The token serving as the "head" of the mention
:getter: the token corresponding to the head
:type: corenlp_xml.document.Token
"""
if self._head is None:
self._head = self.sentence.tokens[self._head_id-1]
return self._head | The token serving as the "head" of the mention
:getter: the token corresponding to the head
:type: corenlp_xml.document.Token |
def _get(self, uri):
"""
Handles the communication with the API when getting
a specific resource managed by this class.
Because DNS returns a different format for the body,
the BaseManager method must be overridden here.
"""
uri = "%s?showRecords=false&showSubdom... | Handles the communication with the API when getting
a specific resource managed by this class.
Because DNS returns a different format for the body,
the BaseManager method must be overridden here. |
def evaluate_inline(self, groups):
"""Evaluate inline comments on their own lines."""
# Consecutive lines with only comments with same leading whitespace
# will be captured as a single block.
if self.lines:
if (
self.group_comments and
self.li... | Evaluate inline comments on their own lines. |
def pass_q_v1(self):
"""Update the outlet link sequence.
Required derived parameter:
|QFactor|
Required flux sequences:
|lland_fluxes.Q|
Calculated flux sequence:
|lland_outlets.Q|
Basic equation:
:math:`Q_{outlets} = QFactor \\cdot Q_{fluxes}`
"""
der = self.par... | Update the outlet link sequence.
Required derived parameter:
|QFactor|
Required flux sequences:
|lland_fluxes.Q|
Calculated flux sequence:
|lland_outlets.Q|
Basic equation:
:math:`Q_{outlets} = QFactor \\cdot Q_{fluxes}` |
def target_to_list(target):
""" Attempt to return a list of single hosts from a target string. """
# Is it an IPv4 address ?
new_list = target_to_ipv4(target)
# Is it an IPv6 address ?
if not new_list:
new_list = target_to_ipv6(target)
# Is it an IPv4 CIDR ?
if not new_list:
... | Attempt to return a list of single hosts from a target string. |
def migrate_flow_collection(apps, schema_editor):
"""Migrate 'flow_collection' field to 'entity_type'."""
Process = apps.get_model('flow', 'Process')
DescriptorSchema = apps.get_model('flow', 'DescriptorSchema')
for process in Process.objects.all():
process.entity_type = process.flow_collection... | Migrate 'flow_collection' field to 'entity_type'. |
def _init_polling(self):
"""
Bootstrap polling for throttler.
To avoid spiky traffic from throttler clients, we use a random delay
before the first poll.
"""
with self.lock:
if not self.running:
return
r = random.Random()
... | Bootstrap polling for throttler.
To avoid spiky traffic from throttler clients, we use a random delay
before the first poll. |
def sendFinalResponse(self):
"""
Send the final response and close the connection.
:return: <void>
"""
self.requestProtocol.requestResponse["code"] = (
self.responseCode
)
self.requestProtocol.requestResponse["content"] = (
self.responseCo... | Send the final response and close the connection.
:return: <void> |
def dumps(xs, model=None, properties=False, indent=True, **kwargs):
"""
Serialize Xmrs (or subclass) objects to PENMAN notation
Args:
xs: iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to
serialize
model: Xmrs subclass used to get triples
properties: if `True`, enco... | Serialize Xmrs (or subclass) objects to PENMAN notation
Args:
xs: iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to
serialize
model: Xmrs subclass used to get triples
properties: if `True`, encode variable properties
indent: if `True`, adaptively indent; if `False` ... |
def bump(self, bump_reqs=None, **kwargs):
"""
Bump dependencies using given requirements.
:param RequirementsManager bump_reqs: Bump requirements manager
:param dict kwargs: Additional args from argparse. Some bumpers accept user options, and some not.
:return: List of :... | Bump dependencies using given requirements.
:param RequirementsManager bump_reqs: Bump requirements manager
:param dict kwargs: Additional args from argparse. Some bumpers accept user options, and some not.
:return: List of :class:`Bump` changes made. |
def check_bounds(args, lowerLimit, upperLimit):
"""
checks whether the parameter vector has left its bound, if so, adds a big number
"""
penalty = 0
bound_hit = False
for i in range(0, len(args)):
if args[i] < lowerLimit[i] or args[i] > upperLimit[i]:
... | checks whether the parameter vector has left its bound, if so, adds a big number |
def getGDEFGlyphClasses(feaLib):
"""Return GDEF GlyphClassDef base/mark/ligature/component glyphs, or
None if no GDEF table is defined in the feature file.
"""
for st in feaLib.statements:
if isinstance(st, ast.TableBlock) and st.name == "GDEF":
for st in st.statements:
... | Return GDEF GlyphClassDef base/mark/ligature/component glyphs, or
None if no GDEF table is defined in the feature file. |
def error_lineno(self):
"""Get the line number with which to report violations."""
if isinstance(self.docstring, Docstring):
return self.docstring.start
return self.start | Get the line number with which to report violations. |
def _init_client():
"""Initialize connection and create table if needed
"""
if client is not None:
return
global _mysql_kwargs, _table_name
_mysql_kwargs = {
'host': __opts__.get('mysql.host', '127.0.0.1'),
'user': __opts__.get('mysql.user', None),
'passwd': __opts__... | Initialize connection and create table if needed |
def ic45(msg):
"""Icing.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Icing level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
"""
d = hex2bin(data(msg))
if d[9] == '0':
return None
ic = bin2int(d[10:12])
return ic | Icing.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Icing level. 0=NIL, 1=Light, 2=Moderate, 3=Severe |
def convert_1x_args(bucket, **kwargs):
"""
Converts arguments for 1.x constructors to their 2.x forms
"""
host = kwargs.pop('host', 'localhost')
port = kwargs.pop('port', None)
if not 'connstr' in kwargs and 'connection_string' not in kwargs:
kwargs['connection_string'] = _build_connstr(... | Converts arguments for 1.x constructors to their 2.x forms |
def run(self):
"""Redirects messages until a shutdown message is received."""
while True:
if not self.task_socket.poll(-1):
continue
msg = self.task_socket.recv_multipart()
msg_type = msg[1]
if self.debug:
self.stats.appen... | Redirects messages until a shutdown message is received. |
def _controller_name(self, objtype):
"""Determines the controller name for the object's type
Args:
objtype (str): The object type
Returns:
A string with the controller name
"""
# would be better to use inflect.pluralize here, but would add a dependency
... | Determines the controller name for the object's type
Args:
objtype (str): The object type
Returns:
A string with the controller name |
def get_context(self, filename):
"""Get context."""
if self.type == 'pptx':
context = '{}: '.format(RE_SLIDE.search(filename).group(1))
elif self.type == 'docx':
context = '{}: '.format(RE_DOCS.match(filename).group(1))
else:
context = ''
retu... | Get context. |
def get_auth_token(self):
"""Returns the user's authentication token."""
data = [str(self.id), hash_data(self.password)]
return _security.remember_token_serializer.dumps(data) | Returns the user's authentication token. |
def __get_precipfc_data(latitude, longitude):
"""Get buienradar forecasted precipitation."""
url = 'https://gpsgadget.buienradar.nl/data/raintext?lat={}&lon={}'
# rounding coordinates prevents unnecessary redirects/calls
url = url.format(
round(latitude, 2),
round(longitude, 2)
)
... | Get buienradar forecasted precipitation. |
async def send_pending_messages(self):
"""Wait until all pending messages have been sent.
:returns: A list of the send results of all the pending messages. Each
send result is a tuple with two values. The first is a boolean, indicating `True`
if the message sent, or `False` if it fail... | Wait until all pending messages have been sent.
:returns: A list of the send results of all the pending messages. Each
send result is a tuple with two values. The first is a boolean, indicating `True`
if the message sent, or `False` if it failed. The second is an error if the message
... |
def size(self, size):
"""
Set the query size of this QuerySet should execute its query against.
"""
clone = self._clone()
clone._size = size
return clone | Set the query size of this QuerySet should execute its query against. |
def get_function(self, name: str) -> AbiFunction or None:
"""
This interface is used to get an AbiFunction object from AbiInfo object by given function name.
:param name: the function name in abi file
:return: if succeed, an AbiFunction will constructed based on given function name
... | This interface is used to get an AbiFunction object from AbiInfo object by given function name.
:param name: the function name in abi file
:return: if succeed, an AbiFunction will constructed based on given function name |
def view(self, dtype=None):
"""
Create a new view of the Series.
This function will return a new Series with a view of the same
underlying values in memory, optionally reinterpreted with a new data
type. The new data type must preserve the same size in bytes as to not
ca... | Create a new view of the Series.
This function will return a new Series with a view of the same
underlying values in memory, optionally reinterpreted with a new data
type. The new data type must preserve the same size in bytes as to not
cause index misalignment.
Parameters
... |
def get_connection(hostname, username, logger, threads=5, use_sudo=None, detect_sudo=True):
"""
A very simple helper, meant to return a connection
that will know about the need to use sudo.
"""
if username:
hostname = "%s@%s" % (username, hostname)
try:
conn = remoto.Connection(
... | A very simple helper, meant to return a connection
that will know about the need to use sudo. |
def js_query(self, query: str) -> Awaitable:
"""Send query to related DOM on browser.
:param str query: single string which indicates query type.
"""
if self.connected:
self.js_exec(query, self.__reqid)
fut = Future() # type: Future[str]
self.__tasks... | Send query to related DOM on browser.
:param str query: single string which indicates query type. |
def handle_error(result):
"""
Extracts the last Windows error message into a python unicode string
:param result:
A function result, 0 or None indicates failure
:return:
A unicode string error message
"""
if result:
return
_, error_string = get_error()
if not... | Extracts the last Windows error message into a python unicode string
:param result:
A function result, 0 or None indicates failure
:return:
A unicode string error message |
def iter_result(self, timeout=30, pagesize=100, no_hscan=False):
'''
Iterate over the results of your query instead of getting them all with
`.all()`. Will only perform a single query. If you expect that your
processing will take more than 30 seconds to process 100 items, you
sho... | Iterate over the results of your query instead of getting them all with
`.all()`. Will only perform a single query. If you expect that your
processing will take more than 30 seconds to process 100 items, you
should pass `timeout` and `pagesize` to reflect an appropriate timeout
and page ... |
def create_dataset(group, name, data, units='', datatype=DataTypes.UNDEFINED,
chunks=True, maxshape=None, compression=None,
**attributes):
"""Create an ARF dataset under group, setting required attributes
Required arguments:
name -- the name of dataset in which to st... | Create an ARF dataset under group, setting required attributes
Required arguments:
name -- the name of dataset in which to store the data
data -- the data to store
Data can be of the following types:
* sampled data: an N-D numerical array of measurements
* "simple" event data: a 1-D array... |
def line(self, x0, y0, x1, y1, char):
"""Create a line on ASCII canvas.
Args:
x0 (int): x coordinate where the line should start.
y0 (int): y coordinate where the line should start.
x1 (int): x coordinate where the line should end.
y1 (int): y coordinate ... | Create a line on ASCII canvas.
Args:
x0 (int): x coordinate where the line should start.
y0 (int): y coordinate where the line should start.
x1 (int): x coordinate where the line should end.
y1 (int): y coordinate where the line should end.
char (str)... |
def draw(self, painter, option, rect):
"""
Draws the node for the graphics scene. this method can and should \
be overloaded to create custom nodes.
:param painter <QPainter>
:param option <QGraphicsItemSytleOption>
:param rect <QR... | Draws the node for the graphics scene. this method can and should \
be overloaded to create custom nodes.
:param painter <QPainter>
:param option <QGraphicsItemSytleOption>
:param rect <QRectF> |
def is_met(self, ti, session, dep_context=None):
"""
Returns whether or not this dependency is met for a given task instance. A
dependency is considered met if all of the dependency statuses it reports are
passing.
:param ti: the task instance to see if this dependency is met fo... | Returns whether or not this dependency is met for a given task instance. A
dependency is considered met if all of the dependency statuses it reports are
passing.
:param ti: the task instance to see if this dependency is met for
:type ti: airflow.models.TaskInstance
:param sessio... |
def add_object_file(self, obj_file):
"""
Add object file to the jit. object_file can be instance of
:class:ObjectFile or a string representing file system path
"""
if isinstance(obj_file, str):
obj_file = object_file.ObjectFileRef.from_path(obj_file)
ffi.lib.... | Add object file to the jit. object_file can be instance of
:class:ObjectFile or a string representing file system path |
def tempdir(cls, suffix='', prefix=None, dir=None):
"""Returns a new temporary directory.
Arguments are as for :meth:`~rpaths.Path.tempfile`, except that the
`text` argument is not accepted.
The directory is readable, writable, and searchable only by the
creating user.
... | Returns a new temporary directory.
Arguments are as for :meth:`~rpaths.Path.tempfile`, except that the
`text` argument is not accepted.
The directory is readable, writable, and searchable only by the
creating user.
The caller is responsible for deleting the directory when done... |
def nn(self, x, k = 1, radius = np.inf, eps = 0.0, p = 2):
"""Find the k nearest neighbors of x in the observed input data
:arg x: center
:arg k: the number of nearest neighbors to return (default: 1)
:arg eps: approximate nearest neighbors.
the k-th ret... | Find the k nearest neighbors of x in the observed input data
:arg x: center
:arg k: the number of nearest neighbors to return (default: 1)
:arg eps: approximate nearest neighbors.
the k-th returned value is guaranteed to be no further than
(... |
def fetch_userid(self, side):
"""Return the userid for the specified bed side."""
for user in self.users:
obj = self.users[user]
if obj.side == side:
return user | Return the userid for the specified bed side. |
def ICM(input_dim, num_outputs, kernel, W_rank=1,W=None,kappa=None,name='ICM'):
"""
Builds a kernel for an Intrinsic Coregionalization Model
:input_dim: Input dimensionality (does not include dimension of indices)
:num_outputs: Number of outputs
:param kernel: kernel that will be multiplied by the ... | Builds a kernel for an Intrinsic Coregionalization Model
:input_dim: Input dimensionality (does not include dimension of indices)
:num_outputs: Number of outputs
:param kernel: kernel that will be multiplied by the coregionalize kernel (matrix B).
:type kernel: a GPy kernel
:param W_rank: number tu... |
def _declare_namespace(self, package_name):
'''
Mock for #pkg_resources.declare_namespace() which calls
#pkgutil.extend_path() afterwards as the original implementation doesn't
seem to properly find all available namespace paths.
'''
self.state['declare_namespace'](package_name)
mod = sys.m... | Mock for #pkg_resources.declare_namespace() which calls
#pkgutil.extend_path() afterwards as the original implementation doesn't
seem to properly find all available namespace paths. |
def pad(cls, sequences, padding, pad_len=None):
"""
Pads a list of sequences such that they form a matrix.
:param sequences: a list of sequences of varying lengths.
:param padding: the value of padded cells.
:param pad_len: the length of the maximum padded sequence.
"""
... | Pads a list of sequences such that they form a matrix.
:param sequences: a list of sequences of varying lengths.
:param padding: the value of padded cells.
:param pad_len: the length of the maximum padded sequence. |
def sync(self, resync=False):
"""Sync the local Keep tree with the server. If resyncing, local changes will be detroyed. Otherwise, local changes to notes, labels and reminders will be detected and synced up.
Args:
resync (bool): Whether to resync data.
Raises:
SyncExce... | Sync the local Keep tree with the server. If resyncing, local changes will be detroyed. Otherwise, local changes to notes, labels and reminders will be detected and synced up.
Args:
resync (bool): Whether to resync data.
Raises:
SyncException: If there is a consistency issue. |
def get_subgraphs_as_molecules(self, use_weights=False):
"""
Retrieve subgraphs as molecules, useful for extracting
molecules from periodic crystals.
Will only return unique molecules, not any duplicates
present in the crystal (a duplicate defined as an
isomorphic subgra... | Retrieve subgraphs as molecules, useful for extracting
molecules from periodic crystals.
Will only return unique molecules, not any duplicates
present in the crystal (a duplicate defined as an
isomorphic subgraph).
:param use_weights (bool): If True, only treat subgraphs
... |
def get_extra_pids(self):
"""
Gets the list of process ids that should be marked as high priority.
:return: A list of process ids that are used by this bot in addition to the ones inside the python process.
"""
while not self.is_retired:
for proc in psutil.process_ite... | Gets the list of process ids that should be marked as high priority.
:return: A list of process ids that are used by this bot in addition to the ones inside the python process. |
def _group_by(data, criteria):
"""
Group objects in data using a function or a key
"""
if isinstance(criteria, str):
criteria_str = criteria
def criteria(x):
return x[criteria_str]
res = defaultdict(list)
for element in data:
key = criteria(element)
... | Group objects in data using a function or a key |
def mmi_to_raster(self, force_flag=False, algorithm=USE_ASCII):
"""Convert the grid.xml's mmi column to a raster using gdal_grid.
A geotiff file will be created.
Unfortunately no python bindings exist for doing this so we are
going to do it using a shell call.
.. see also:: ht... | Convert the grid.xml's mmi column to a raster using gdal_grid.
A geotiff file will be created.
Unfortunately no python bindings exist for doing this so we are
going to do it using a shell call.
.. see also:: http://www.gdal.org/gdal_grid.html
Example of the gdal_grid call we ... |
def lmx_h3k_f12k():
"""HParams for training languagemodel_lm1b32k_packed. 880M Params."""
hparams = lmx_base()
hparams.hidden_size = 3072
hparams.filter_size = 12288
hparams.batch_size = 2048
hparams.weight_dtype = "bfloat16"
return hparams | HParams for training languagemodel_lm1b32k_packed. 880M Params. |
def temporal_from_literal(text):
'''
Parse a temporal coverage from a literal ie. either:
- an ISO date range
- a single ISO date period (month,year)
'''
if text.count('/') == 1:
# This is an ISO date range as preconized by Gov.uk
# http://guidance.data.gov.uk/dcat_fields.html
... | Parse a temporal coverage from a literal ie. either:
- an ISO date range
- a single ISO date period (month,year) |
def TrimBeginningAndEndingSlashes(path):
"""Trims beginning and ending slashes
:param str path:
:return:
Path with beginning and ending slashes trimmed.
:rtype: str
"""
if path.startswith('/'):
# Returns substring starting from index 1 to end of the string
path = path[1... | Trims beginning and ending slashes
:param str path:
:return:
Path with beginning and ending slashes trimmed.
:rtype: str |
def overlay_gateway_enable_statistics_vlan_action(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway, "name")
... | Auto Generated Code |
def set_computer_policy(name,
setting,
cumulative_rights_assignments=True,
adml_language='en-US'):
'''
Set a single computer policy
Args:
name (str):
The name of the policy to configure
setting (str):
... | Set a single computer policy
Args:
name (str):
The name of the policy to configure
setting (str):
The setting to configure the named policy with
cumulative_rights_assignments (bool): Determine how user rights
assignment policies are configured. If True,... |
def get_dict_from_json_file(path, encoding='utf-8'):
"""Gets a dict of data form a json file.
:param path: the absolute path to the file
:param encoding: the encoding the file is in
"""
with open(path, encoding=encoding) as data_file:
return json.loads(data_file.read()) | Gets a dict of data form a json file.
:param path: the absolute path to the file
:param encoding: the encoding the file is in |
def user_loc_value_to_class(axis_tag, user_loc):
"""Return the OS/2 weight or width class that is closest to the provided
user location. For weight the user location is between 0 and 1000 and for
width it is a percentage.
>>> user_loc_value_to_class('wght', 310)
310
>>> user_loc_value_to_class(... | Return the OS/2 weight or width class that is closest to the provided
user location. For weight the user location is between 0 and 1000 and for
width it is a percentage.
>>> user_loc_value_to_class('wght', 310)
310
>>> user_loc_value_to_class('wdth', 62)
2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.