text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def set_image(self, **kwargs):
"""
set image of embed
:keyword url: source url of image (only supports http(s) and attachments)
:keyword proxy_url: a proxied url of the image
:keyword height: height of image
:keyword width: width of image
"""
self.image = ... | 0.005941 |
def get_identifier(self):
"""Return identifier which is either the machine file name or sha256 checksum of data."""
if self._path:
return os.path.basename(self._path)
else:
return hashlib.sha256(hashlib.sha256(repr(self._data).encode())).hexdigest() | 0.013468 |
def create_package(package, author, email, description, create_example):
"""Creates a Canari transform package skeleton."""
from canari.commands.create_package import create_package
create_package(package, author, email, description, create_example) | 0.003831 |
def matches(self, pattern):
"""Asserts that val is string and matches regex pattern."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if not isinstance(pattern, str_types):
raise TypeError('given pattern arg must be a string')
if l... | 0.005254 |
def validate(self):
"""
if schema exists we run shape file validation code of fiona by trying to save to in MemoryFile
"""
if self._schema is not None:
with MemoryFile() as memfile:
with memfile.open(driver="ESRI Shapefile", schema=self.schema) as target:
... | 0.008251 |
def add_l2_normalize(self, name, input_name, output_name, epsilon = 1e-5):
"""
Add L2 normalize layer. Normalizes the input by the L2 norm, i.e. divides by the
the square root of the sum of squares of all elements of the input along C, H and W dimensions.
Parameters
----------
... | 0.005958 |
def update_state_active(self):
"""Update the state of the model run to active.
Raises an exception if update fails or resource is unknown.
Returns
-------
ModelRunHandle
Refreshed run handle.
"""
# Update state to active
self.update_state(sel... | 0.008772 |
def eliminate_local_candidates(x, AggOp, A, T, Ca=1.0, **kwargs):
"""Eliminate canidates locally.
Helper function that determines where to eliminate candidates locally
on a per aggregate basis.
Parameters
---------
x : array
n x 1 vector of new candidate
AggOp : CSR or CSC sparse m... | 0.000366 |
def configureIAMCredentials(self, AWSAccessKeyID, AWSSecretAccessKey, AWSSessionToken=""):
"""
**Description**
Used to configure/update the custom IAM credentials for Websocket SigV4 connection to
AWS IoT. Should be called before connect.
**Syntax**
.. code:: python
... | 0.007758 |
def __update_info(self):
"""Updates "visualization options" and "file info" areas."""
from f311 import explorer as ex
import f311
t = self.tableWidget
z = self.listWidgetVis
z.clear()
classes = self.__vis_classes = []
propss = self.__lock_get_current_pro... | 0.002815 |
def main():
"""This program prints doubled values!"""
import numpy
X=arange(.1,10.1,.2) #make a list of numbers
Y=myfunc(X) # calls myfunc with argument X
for i in range(len(X)):
print(X[i],Y[i]) | 0.040359 |
def _get_calculated_status(self):
"""Get the calculated status of the page based on
:attr:`Page.publication_date`,
:attr:`Page.publication_end_date`,
and :attr:`Page.status`."""
if settings.PAGE_SHOW_START_DATE and self.publication_date:
if self.publication_date > get... | 0.003636 |
def probability_density(self, X):
"""Compute density function for given copula family.
Args:
X: `np.ndarray`
Returns:
np.array: probability density
"""
self.check_fit()
U, V = self.split_matrix(X)
if self.theta == 0:
return ... | 0.00519 |
def prob_imf(m1, m2, s1z, s2z, **kwargs):
''' Return probability density for power-law
Parameters
----------
m1: array
Component masses 1
m2: array
Component masses 2
s1z: array
Aligned spin 1(Not in use currently)
s2z:
... | 0.002239 |
def resolve_primary_keys_in_schema(sql_tokens: List[str],
schema: Dict[str, List[TableColumn]]) -> List[str]:
"""
Some examples in the text2sql datasets use ID as a column reference to the
column of a table which has a primary key. This causes problems if you are trying
... | 0.00611 |
def transform(self, Y):
"""Transform input data `Y` to reduced data space defined by `self.data`
Takes data in the same ambient space as `self.data` and transforms it
to be in the same reduced space as `self.data_nu`.
Parameters
----------
Y : array-like, shape=[n_sampl... | 0.002372 |
def load_smc_file(cls, filename):
"""Read an SMC formatted time series.
Format of the time series is provided by:
https://escweb.wr.usgs.gov/nsmp-data/smcfmt.html
Parameters
----------
filename: str
Filename to open.
"""
from .tools impo... | 0.001366 |
def close(self):
"""Closes the record writer."""
if self._writer is not None:
self.flush()
self._writer.close()
self._writer = None | 0.010929 |
def execute_async(self, operation, parameters=None, configuration=None):
"""Asynchronously execute a SQL query.
Immediately returns after query is sent to the HS2 server. Poll with
`is_executing`. A call to `fetch*` will block.
Parameters
----------
operation : str
... | 0.001437 |
def _translate(unistr, table):
'''Replace characters using a table.'''
if type(unistr) is str:
try:
unistr = unistr.decode('utf-8')
# Python 3 returns AttributeError when .decode() is called on a str
# This means it is already unicode.
except AttributeError:
... | 0.001524 |
def get_variant_by_id(cls, variant_id, **kwargs):
"""Find Variant
Return single instance of Variant by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_variant_by_id(variant_id, asy... | 0.00344 |
def init(self):
'''
Initialize the device.
Parameters of visa.ResourceManager().open_resource()
'''
super(Visa, self).init()
backend = self._init.get('backend', '') # Empty string means std. backend (NI VISA)
rm = visa.ResourceManager(backend)
try:
... | 0.008152 |
def unique(text):
"""
Return an unique text
@type text: str
@param text: Text written used spin syntax.
@return: An unique text
# Generate an unique sentence
>>> unique('The {quick|fast} {brown|gray|red} fox jumped over the lazy dog.')
'The quick red fox jumped over the lazy dog'
... | 0.003929 |
def get_cache_key(self, name, filename=None):
"""Returns the unique hash key for this template name."""
hash = sha1(name.encode('utf-8'))
if filename is not None:
filename = '|' + filename
if isinstance(filename, text_type):
filename = filename.encode('utf... | 0.005128 |
def trees(return_X_y=True):
"""cherry trees dataset
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes... | 0.001253 |
def reorder_brute(p_atoms, q_atoms, p_coord, q_coord):
"""
Re-orders the input atom list and xyz coordinates using all permutation of
rows (using optimized column results)
Parameters
----------
p_atoms : array
(N,1) matrix, where N is points holding the atoms' names
q_atoms : array
... | 0.000801 |
def _run_internal(self,
context,
pipeline_key,
root_pipeline_key,
caller_output):
"""Used by the Pipeline evaluator to execute this Pipeline."""
self._set_values_internal(
context, pipeline_key, root_pipeline_key, caller_out... | 0.008666 |
def isSelectionPositionValid(self, selPos: tuple):
"""
Return **True** if the start- and end position denote valid
positions within the document.
|Args|
* ``selPos`` (**tuple**): tuple with four integers.
|Returns|
**bool**: **True** if the positions are valid... | 0.002886 |
def arch_size(self):
"""Return the architecure size in bits."""
if not self._ptr:
raise BfdException("BFD not initialized")
try:
return _bfd.get_arch_size(self._ptr)
except Exception, err:
raise BfdException("Unable to determine architeure size.") | 0.006329 |
def _in_version(self, *versions):
"Returns true if this frame is in any of the specified versions of ID3."
for version in versions:
if (self._version == version
or (isinstance(self._version, collections.Container)
and version in self._version)):
... | 0.011142 |
def writeln (self, s=u"", **args):
"""
Write string to output descriptor plus a newline.
"""
self.write(u"%s%s" % (s, unicode(os.linesep)), **args) | 0.01676 |
def compare_basis_against_file(basis_name,
src_filepath,
file_type=None,
version=None,
uncontract_general=False,
data_dir=None):
'''Compare a basis set in the BS... | 0.00346 |
def deserialize_unicode(data):
"""Preserve unicode objects in Python 2, otherwise return data
as a string.
:param str data: response string to be deserialized.
:rtype: str or unicode
"""
# We might be here because we have an enum modeled as string,
# and we try t... | 0.003101 |
def _get_model_name(self, modeldata):
"""
Extract the model name from the ``modeldata`` that *django-admin-tools* provides.
"""
if 'change_url' in modeldata:
return modeldata['change_url'].strip('/').split('/')[-1] # /foo/admin/appname/modelname
elif 'add_url' in mo... | 0.011194 |
def select(self, filter_by=None):
"""
Parameters
----------
filter_by: callable, default None
Callable must take one argument (a record of queryset), and return True to keep record, or False to skip it.
Example : .select(lambda x: x.name == "my_name").
... | 0.006678 |
def z_axis_transform(compound, new_origin=None,
point_on_z_axis=None,
point_on_zx_plane=None):
"""Move a compound such that the z-axis lies on specified points.
Parameters
----------
compound : mb.Compound
The compound to move.
new_origin : mb.Compo... | 0.004334 |
def divide_work(list_of_indexes, batch_size):
"""
Given a sequential list of indexes split them into num_parts.
:param list_of_indexes: [int] list of indexes to be divided up
:param batch_size: number of items to put in batch(not exact obviously)
:return: [(int,int)] list of (ind... | 0.005505 |
def set_start_date(self, date):
"""Sets the start date.
arg: date (osid.calendaring.DateTime): the new date
raise: InvalidArgument - ``date`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``date`` is ``null``
*compliance: ... | 0.002861 |
def svs_description_metadata(description):
"""Return metatata from Aperio image description as dict.
The Aperio image description format is unspecified. Expect failures.
>>> svs_description_metadata('Aperio Image Library v1.0')
{'Aperio Image Library': 'v1.0'}
"""
if not description.startswit... | 0.001183 |
def plot_diff(self, graphing_library='matplotlib'):
"""
Generate CDF diff plots of the submetrics
"""
diff_datasource = sorted(set(self.reports[0].datasource) & set(self.reports[1].datasource))
graphed = False
for submetric in diff_datasource:
baseline_csv = naarad.utils.get_default_csv(se... | 0.011957 |
def _get_Berger_data(verbose=True):
'''Read in the Berger and Loutre orbital table as a pandas dataframe, convert to xarray
'''
# The first column of the data file is used as the row index, and represents kyr from present
orbit91_pd, path = load_data_source(local_path = local_path,
r... | 0.015106 |
def type_string(self):
'''
Returns the names of the flags that are set in the Type field
It can be used to format the counter.
'''
type = self.get_info()['type']
type_list = []
for member in dir(self):
if member.startswith("PERF_"):
bi... | 0.004367 |
def cli(ctx, config, quiet):
"""AWS ECS Docker Deployment Tool"""
ctx.obj = {}
ctx.obj['config'] = load_config(config.read()) # yaml.load(config.read())
ctx.obj['quiet'] = quiet
log(ctx, ' * ' + rnd_scotty_quote() + ' * ') | 0.004115 |
def GenerateNewFileName(self):
"""
Create new file name from show name, season number, episode number
and episode name in format ShowName.S<NUM>.E<NUM>.EpisodeName.
Returns
----------
string
New file name in format ShowName.S<NUM>.E<NUM>.EpisodeName.
"""
if self.showInfo.showN... | 0.013225 |
def ListTimeZones(self):
"""Lists the timezones."""
max_length = 0
for timezone_name in pytz.all_timezones:
if len(timezone_name) > max_length:
max_length = len(timezone_name)
utc_date_time = datetime.datetime.utcnow()
table_view = views.ViewsFactory.GetTableView(
self._views... | 0.006891 |
def get_commensurate_points(supercell_matrix): # wrt primitive cell
"""Commensurate q-points are returned.
Parameters
----------
supercell_matrix : array_like
Supercell matrix with respect to primitive cell basis vectors.
shape=(3, 3)
dtype=intc
"""
smat = np.array(su... | 0.001289 |
def distances(self, points):
"""
Computes the distances from the plane to each of the points. Positive distances are on the side of the
normal of the plane while negative distances are on the other side
:param points: Points for which distances are computed
:return: Distances fro... | 0.007407 |
def get_number_of_desktops(self):
"""
Get the current number of desktops.
Uses ``_NET_NUMBER_OF_DESKTOPS`` of the EWMH spec.
:param ndesktops:
pointer to long where the current number of desktops is stored
"""
ndesktops = ctypes.c_long(0)
_libxdo.xdo_... | 0.00489 |
def _headers(self, headers_dict):
"""
Convert dictionary of headers into twisted.web.client.Headers object.
"""
return Headers(dict((k,[v]) for (k,v) in headers_dict.items())) | 0.019324 |
def _acceptance_prob(self, position, position_bar, momentum, momentum_bar):
"""
Returns the acceptance probability for given new position(position) and momentum
"""
# Parameters to help in evaluating Joint distribution P(position, momentum)
_, logp = self.grad_log_pdf(position, ... | 0.010165 |
def replace_namespaced_horizontal_pod_autoscaler_status(self, name, namespace, body, **kwargs):
"""
replace status of the specified HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>... | 0.004792 |
def getRolesForUser(self, username, filter=None, maxCount=None):
"""
This operation returns a list of role names that have been
assigned to a particular user account.
Inputs:
username - name of the user for whom the returned roles
filter - filter to b... | 0.007239 |
def add_defaults_to_kwargs(defaults, **kwargs):
"""Updates `kwargs` with dict of `defaults`
Args:
defaults: A dictionary of keys and values
**kwargs: The kwargs to update.
Returns:
The updated kwargs.
"""
defaults = dict(defaults)
defaults.update(kwargs)
return defa... | 0.003086 |
def sparsity_pattern(self, reordered = True, symmetric = True):
"""
Returns a sparse matrix with the filled pattern. By default,
the routine uses the reordered pattern, and the inverse
permutation is applied if `reordered` is `False`.
:param reordered: boolean (default:... | 0.026804 |
def load(self):
"""
Load this step's result from its dump directory
"""
hdf_filename = os.path.join(self._dump_dirname, 'result.h5')
if os.path.isfile(hdf_filename):
store = pd.HDFStore(hdf_filename, mode='r')
keys = store.keys()
if keys == ['/... | 0.003672 |
def call_blink(*args, **kwargs):
'''
Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec.
CLI Example:
.. c... | 0.004684 |
def _fill_function(*args):
"""Fills in the rest of function data into the skeleton function object
The skeleton itself is create by _make_skel_func().
"""
if len(args) == 2:
func = args[0]
state = args[1]
elif len(args) == 5:
# Backwards compat for cloudpickle v0.4.0, after ... | 0.000922 |
def _updateColumnValues(self, index, hidden):
"""
Updates the column values for the inputed column.
:param column | <int>
state | <bool>
"""
if hidden or not self.isVisible():
return
column = self.columnOf(... | 0.011152 |
def _onerror(self, result):
""" To execute on execution failure
:param kser.result.Result result: Execution result
:return: Execution result
:rtype: kser.result.Result
"""
if KSER_METRICS_ENABLED == "yes":
KSER_TASKS_STATUS.labels(
__hostname_... | 0.002037 |
def find_executable(executable, path=None):
"""
As distutils.spawn.find_executable, but on Windows, look up
every extension declared in PATHEXT instead of just `.exe`
"""
if sys.platform != 'win32':
return distutils.spawn.find_executable(executable, path)
if path is None:
path =... | 0.001318 |
def p_typed_var_list(self, p):
'''typed_var_list : typed_var_list COMMA typed_var
| typed_var'''
if len(p) == 4:
p[1].append(p[3])
p[0] = p[1]
elif len(p) == 2:
p[0] = [p[1]] | 0.007692 |
def evaluate_vars(data, context=None):
"""
Evaluates variables in ``data``
:param data: data structure containing variables, may be
``str``, ``dict`` or ``list``
:param context: ``dict`` containing variables
:returns: modified data structure
"""
context = context or {}
... | 0.000743 |
def _add_person_to_group(person, group):
""" Call datastores after adding a person to a group. """
from karaage.datastores import add_accounts_to_group
from karaage.datastores import add_accounts_to_project
from karaage.datastores import add_accounts_to_institute
a_list = person.account_set
add... | 0.001828 |
def approximate_moment(
dist,
K,
retall=False,
control_var=None,
rule="F",
order=1000,
**kws
):
"""
Approximation method for estimation of raw statistical moments.
Args:
dist : Dist
Distribution domain with dim=len(dist)
K ... | 0.000702 |
def _get_node_column(cls, node, column_name):
"""Given a ParsedNode, add some fields that might be missing. Return a
reference to the dict that refers to the given column, creating it if
it doesn't yet exist.
"""
if not hasattr(node, 'columns'):
node.set('columns', {}... | 0.003604 |
def redraw(self, col=0):
"""redraw image, applying the following:
rotation, flips, log scale
max/min values from sliders or explicit intensity ranges
color map
interpolation
"""
conf = self.conf
# note: rotation re-calls display(), to reset the image
... | 0.00607 |
def validate(cls, job_config):
"""Inherit docs."""
super(ModelDatastoreInputReader, cls).validate(job_config)
params = job_config.input_reader_params
entity_kind = params[cls.ENTITY_KIND_PARAM]
# Fail fast if Model cannot be located.
try:
model_class = util.for_name(entity_kind)
except... | 0.009972 |
def sync_objects_in(self):
"""Synchronize from records to objects"""
self.dstate = self.STATES.BUILDING
self.build_source_files.record_to_objects() | 0.011696 |
def _handlePressure(self, d):
"""
Parse an altimeter-pressure group.
The following attributes are set:
press [int]
"""
press = d['press']
if press != '////':
press = float(press.replace('O', '0'))
if d['unit']:
if d[... | 0.001965 |
def write(self, handle):
'''Write metadata and point + analog frames to a file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle.
'''
if not self._frames... | 0.002194 |
def from_file(self, fname):
"""read in a file and compute digest"""
f = open(fname, "rb")
data = f.read()
self.update(data)
f.close() | 0.011561 |
def solveMDP():
"""Solve the problem as a finite horizon Markov decision process.
The optimal policy at each stage is found using backwards induction.
Possingham and Tuck report strategies for a 50 year time horizon, so the
number of stages for the finite horizon algorithm is set to 50. There is no... | 0.004994 |
def _SkipFieldContents(tokenizer):
"""Skips over contents (value or message) of a field.
Args:
tokenizer: A tokenizer to parse the field name and values.
"""
# Try to guess the type of this field.
# If this field is not a message, there should be a ":" between the
# field name and the field value and a... | 0.015193 |
def remove_product_version_from_build_configuration(id=None, name=None, product_version_id=None):
"""
Remove a ProductVersion from association with a BuildConfiguration
"""
data = remove_product_version_from_build_configuration_raw(id, name, product_version_id)
if data:
return utils.format_j... | 0.008982 |
def median_filter(data, size=3, cval = 0, res_g=None, sub_blocks=None):
"""
median filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
cval: scalar,
... | 0.008466 |
def handle_import_tags(userdata, import_root):
"""Handle @import(filepath)@ tags in a UserData script.
:param import_root: Location for imports.
:type import_root: str
:param userdata: UserData script content.
:type userdata: str
:return: UserData script with the content... | 0.006763 |
def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):
'''
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
o... | 0.000646 |
def handle_molecular_activity_default(_: str, __: int, tokens: ParseResults) -> ParseResults:
"""Handle a BEL 2.0 style molecular activity with BEL default names."""
upgraded = language.activity_labels[tokens[0]]
tokens[NAMESPACE] = BEL_DEFAULT_NAMESPACE
tokens[NAME] = upgraded
return tokens | 0.00641 |
def downsample(vector, factor):
"""
downsample(vector, factor):
Downsample (by averaging) a vector by an integer factor.
"""
if (len(vector) % factor):
print "Length of 'vector' is not divisible by 'factor'=%d!" % factor
return 0
vector.shape = (len(vector) / factor, factor)
... | 0.002801 |
def _set_interface_bfd(self, v, load=False):
"""
Setter method for interface_bfd, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_bfd (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_bfd is considered as a pr... | 0.005238 |
def combine_chunks(storage, args, prefix=None):
'''
Combine a chunked file into a whole file again.
Goes through each part, in order,
and appends that part's bytes to another destination file.
Chunks are stored in the chunks storage.
'''
uuid = args['uuid']
# Normalize filename including... | 0.001391 |
def nacm_rule_list_rule_rule_type_data_node_path(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
nacm = ET.SubElement(config, "nacm", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-acm")
rule_list = ET.SubElement(nacm, "rule-list")
name_key = ET... | 0.003659 |
def _add_column(self, column):
"""
Add a new column to the DataFrame
:param column: column name
:return: nothing
"""
self._columns.append(column)
if self._blist:
self._data.append(blist([None] * len(self._index)))
else:
self._data.... | 0.005666 |
def _send(self, *messages):
"""Send messages."""
if not self.transport:
return False
message = '\n'.join(messages) + '\n'
self.transport.write(message.encode('ascii')) | 0.009434 |
def attrib_to_dict(element, *args, **kwargs):
"""For an ElementTree ``element`` extract specified attributes. If an attribute does not exists, its value will be
``None``.
attrib_to_dict(element, 'attr_a', 'attr_b') -> {'attr_a': 'value', 'attr_a': 'value'}
Mapping between xml attributes and dictionary... | 0.00626 |
def zonearea(idf, zonename, debug=False):
"""zone area"""
zone = idf.getobject('ZONE', zonename)
surfs = idf.idfobjects['BuildingSurface:Detailed'.upper()]
zone_surfs = [s for s in surfs if s.Zone_Name == zone.Name]
floors = [s for s in zone_surfs if s.Surface_Type.upper() == 'FLOOR']
if debug:
... | 0.001701 |
def get_default_task(self):
"""
Returns the default task if there is only one
"""
default_tasks = list(filter(lambda task: task.default, self.values()))
if len(default_tasks) == 1:
return default_tasks[0] | 0.007813 |
def get_names_in_namespace_page(namespace_id, offset, count, proxy=None, hostport=None):
"""
Get a page of names in a namespace
Returns the list of names on success
Returns {'error': ...} on error
"""
assert proxy or hostport, 'Need proxy or hostport'
if proxy is None:
proxy = connec... | 0.004074 |
def set_source_nodes(self, source_nodes):
r"""
Set multiple source nodes and compute their t-weights.
Parameters
----------
source_nodes : sequence of integers
Declare the source nodes via their ids.
Raises
------
ValueError
... | 0.006902 |
def path_dispatch_kwarg(mname, path_default, returns_model):
"""
Parameterized decorator for methods that accept path as a second
argument.
"""
def _wrapper(self, path=path_default, **kwargs):
prefix, mgr, mgr_path = _resolve_path(path, self.managers)
result = getattr(mgr, mname)(pat... | 0.002053 |
def currentpath(self) -> str:
"""Absolute path of the current working directory.
>>> from hydpy.core.filetools import FileManager
>>> filemanager = FileManager()
>>> filemanager.BASEDIR = 'basename'
>>> filemanager.projectdir = 'projectname'
>>> from hydpy import repr_, ... | 0.003273 |
def end_of_month(val):
"""
Return a new datetime.datetime object with values that represent
a end of a month.
:param val: Date to ...
:type val: datetime.datetime | datetime.date
:rtype: datetime.datetime
"""
if type(val) == date:
val = datetime.fromordinal(val.toordinal())
i... | 0.001745 |
def CheckRepeatLogic(filename, linenumber, clean_lines, errors):
"""
Check for logic inside else, endif etc
"""
line = clean_lines.lines[linenumber]
for cmd in _logic_commands:
if re.search(r'\b%s\b'%cmd, line.lower()):
m = _RE_LOGIC_CHECK.search(line)
if m:
... | 0.007678 |
def create_replication_schedule(self,
start_time, end_time, interval_unit, interval, paused, arguments,
alert_on_start=False, alert_on_success=False, alert_on_fail=False,
alert_on_abort=False):
"""
Create a new replication schedule for this service.
The replication argument type varies pe... | 0.009502 |
def get_annotations(fname, prefix=None):
"Open a COCO style json in `fname` and returns the lists of filenames (with maybe `prefix`) and labelled bboxes."
annot_dict = json.load(open(fname))
id2images, id2bboxes, id2cats = {}, collections.defaultdict(list), collections.defaultdict(list)
classes = {}
... | 0.007034 |
async def play_tone(self, command):
"""
This method controls a piezo device to play a tone. It is a FirmataPlus feature.
Tone command is TONE_TONE to play, TONE_NO_TONE to stop playing.
:param command: {"method": "play_tone", "params": [PIN, TONE_COMMAND, FREQUENCY(Hz), DURATION(MS)]}
... | 0.005806 |
def emulate_users(self, request):
"""
The list view
"""
def display_as_link(self, obj):
try:
identifier = getattr(user_model_admin, list_display_link)(obj)
except AttributeError:
identifier = admin.utils.lookup_field(list_display_li... | 0.004617 |
def egg2dist(self, egginfo_path, distinfo_path):
"""Convert an .egg-info directory into a .dist-info directory"""
def adios(p):
"""Appropriately delete directory, file or link."""
if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p):
shutil.rmtree(p... | 0.001815 |
def populate(self, node_generator):
"""
Populate Merkle Tree with data from node_generator. This requires that node_generator yield byte[] elements.
Hashes, computes hex digest, and adds it to the Merkle Tree
:param node_generator:
:return:
"""
for data in node_ge... | 0.007317 |
def _update_items(self, items):
"""
Replace the 'items' list of this OrderedSet with a new one, updating
self.map accordingly.
"""
self.items = items
self.map = {item: idx for (idx, item) in enumerate(items)} | 0.007813 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.