text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_certificate_issuers(self, **kwargs): # noqa: E501
"""Get certificate issuers list. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.get_certificate_issuers(asynchronous=Tr... | 0.002334 |
def sendCommands(comPort, commands):
"""Send X10 commands using the FireCracker on comPort
comPort should be the name of a serial port on the host platform. On
Windows, for example, 'com1'.
commands should be a string consisting of X10 commands separated by
commas. For example. 'A1 On, A Dim, A Di... | 0.000623 |
def plot_line(axes, fname, ltype):
"""plot the ecliptic plane line on the given axes."""
x = np.genfromtxt(fname, unpack=True)
axes.plot(x[0], x[1], ltype) | 0.005988 |
def _build_process_container_tree(self, pids):
"""
tops = [1,2,3]
childs = {1: [4,5], 2: [6,7], 3: [], 4: []}
"""
containers = []
procs = []
ppids = []
childs = {}
for pid in pids:
proc = process.Process(pid)
procs.append(pr... | 0.001453 |
def _invalid_frequency(self, frequency):
"""
Check to see that frequency was specified correctly
:param frequency (string): frequency string
:return (boolean):
"""
is_valid = self._is_eod_frequency(frequency) or re.match(self._frequency_pattern, frequency)
return ... | 0.009036 |
def get_class_alias(klass):
"""
Tries to find a suitable L{pyamf.ClassAlias} subclass for C{klass}.
"""
for k, v in pyamf.ALIAS_TYPES.iteritems():
for kl in v:
try:
if issubclass(klass, kl):
return k
except TypeError:
# ... | 0.002222 |
def watch(args):
" Watch directory for changes and auto pack sources "
assert op.isdir(args.source), "Watch mode allowed only for directories."
print 'Zeta-library v. %s watch mode' % VERSION
print '================================'
print 'Ctrl+C for exit\n'
observer = Observer()
handler = Z... | 0.001706 |
def get(self, flex_sched_rule_id):
"""Retrieve the information for a flexscheduleRule entity."""
path = '/'.join(['flexschedulerule', flex_sched_rule_id])
return self.rachio.get(path) | 0.009662 |
def _attach_params(self, params, **kwargs):
"""Attach a list of parameters (or ParameterSet) to this ParameterSet.
:parameter list params: list of parameters, or ParameterSet
:parameter **kwargs: attributes to set for each parameter (ie tags)
"""
lst = params.to_list() if isinst... | 0.002717 |
def _all_reads_from_contig(self, contig, fout):
'''Gets all reads from contig called "contig" and writes to fout'''
sam_reader = pysam.Samfile(self.bam, "rb")
for read in sam_reader.fetch(contig):
print(mapping.aligned_read_to_read(read, ignore_quality=not self.fastq_out), file=fout) | 0.009375 |
def parse_net_kwargs(kwargs):
"""Parse arguments for the estimator.
Resolves dotted names and instantiated classes.
Examples
--------
>>> kwargs = {'lr': 0.1, 'module__nonlin': 'torch.nn.Hardtanh(-2, max_val=3)'}
>>> parse_net_kwargs(kwargs)
{'lr': 0.1, 'module__nonlin': Hardtanh(min_val=-... | 0.003984 |
def electrum_pub(self, s):
"""
Parse an electrum public key from a text string in seed form ("E:xxx" where xxx
is a 128-character hex string).
Return a :class:`ElectrumWallet <pycoin.key.electrum.ElectrumWallet>` or None.
"""
blob = self._electrum_to_blob(s)
if bl... | 0.009501 |
def backport_makefile(self, mode="r", buffering=None, encoding=None,
errors=None, newline=None):
"""
Backport of ``socket.makefile`` from Python 3.5.
"""
if not set(mode) <= {"r", "w", "b"}:
raise ValueError(
"invalid mode %r (only r, w, b allowed)" % (mode,)
... | 0.000816 |
def setup(pin, mode, pullup=None, initial=False):
'''Setup pin with mode IN or OUT.
Args:
pin (int):
mode (str): use either gpio.OUT or gpio.IN
pullup (None): rpio compatibility. If anything but None, raises
value Error
pullup (bool, optional): Initial pin va... | 0.001379 |
def leader_for_partition(self, partition):
"""Return node_id of leader, -1 unavailable, None if unknown."""
if partition.topic not in self._partitions:
return None
elif partition.partition not in self._partitions[partition.topic]:
return None
return self._partitio... | 0.00545 |
def CPUID(cpu):
"""
CPUID instruction.
The ID flag (bit 21) in the EFLAGS register indicates support for the
CPUID instruction. If a software procedure can set and clear this
flag, the processor executing the procedure supports the CPUID
instruction. This instruction op... | 0.002137 |
def hpss_demo(input_file, output_harmonic, output_percussive):
'''HPSS demo function.
:parameters:
- input_file : str
path to input audio
- output_harmonic : str
path to save output harmonic (wav)
- output_percussive : str
path to save output harmonic (wav)
'... | 0.001155 |
def build(self):
"""Builds the index, creating an instance of `lunr.Index`.
This completes the indexing process and should only be called once all
documents have been added to the index.
"""
self._calculate_average_field_lengths()
self._create_field_vectors()
sel... | 0.003361 |
def consult_response_hook(self, item_session: ItemSession) -> Actions:
'''Return scripting action when a response ends.'''
try:
return self.hook_dispatcher.call(
PluginFunctions.handle_response, item_session
)
except HookDisconnected:
return Ac... | 0.006024 |
def get_content_commit_date(extensions, acceptance_callback=None,
root_dir='.'):
"""Get the datetime for the most recent commit to a project that
affected certain types of content.
Parameters
----------
extensions : sequence of 'str'
Extensions of files to consid... | 0.000316 |
def create_downloadjob(entry, domain, config):
"""Create download jobs for all file formats from a summary file entry."""
logging.info('Checking record %r', entry['assembly_accession'])
full_output_dir = create_dir(entry, config.section, domain, config.output)
symlink_path = None
if config.human_re... | 0.003915 |
def plot_blob(
sampler, blobidx=0, label=None, last_step=False, figure=None, **kwargs
):
"""
Plot a metadata blob as a fit to spectral data or value distribution
Additional ``kwargs`` are passed to `plot_fit`.
Parameters
----------
sampler : `emcee.EnsembleSampler`
Sampler with a s... | 0.000846 |
def predict_dims(self, q, dims_x, dims_y, dims_out, sigma=None, k=None):
"""Provide a prediction of q in the output space
@param xq an array of float of length dim_x
@param estimated_sigma if False (default), sigma_sq=self.sigma_sq, else it is estimated from the neighbor distances in self._we... | 0.015652 |
def camel_to_snake(camel):
"""Convert camelCase to snake_case."""
ret = []
last_lower = False
for char in camel:
current_upper = char.upper() == char
if current_upper and last_lower:
ret.append("_")
ret.append(char.lower())
else:
ret.append(cha... | 0.002545 |
def add_other_ldflags(self, flags, target_name=None, configuration_name=None):
"""
Adds flag values to the OTHER_LDFLAGS flag.
:param flags: A string or array of strings. If none, removes all values from the flag.
:param target_name: Target name or list of target names to add the flag to... | 0.010204 |
def _load_image_set_index(self, shuffle):
"""
find out which indexes correspond to given image set (train or val)
Parameters:
----------
shuffle : boolean
whether to shuffle the image list
Returns:
----------
entire list of images specified in... | 0.005215 |
def _write_script(path, lines, chmod=True):
'''write a script with some lines content to path in the image. This
is done by way of adding echo statements to the install section.
Parameters
==========
path: the path to the file to write
lines: the lines to ... | 0.007396 |
def compound(clr, flip=False):
"""
Roughly the complement and some far analogs.
"""
def _wrap(x, min, threshold, plus):
if x - min < threshold:
return x + plus
else:
return x - min
d = 1
if flip: d = -1
clr = color(clr)
colors = colorlist(clr)
... | 0.001815 |
def on_error(self, headers, body):
"""
Increment the error count. See :py:meth:`ConnectionListener.on_error`
:param dict headers: headers in the message
:param body: the message content
"""
if log.isEnabledFor(logging.DEBUG):
log.debug("received an error %s [... | 0.004651 |
def reduce(self, func):
"""Return a new DStream where each RDD was reduced with ``func``.
:rtype: DStream
"""
# avoid RDD.reduce() which does not return an RDD
return self.transform(
lambda rdd: (
rdd
.map(lambda i: (None, i))
... | 0.004785 |
def get_playlist(self, channel):
"""Return the playlist for the given channel
:param channel: the channel
:type channel: :class:`models.Channel` | :class:`str`
:returns: the playlist
:rtype: :class:`m3u8.M3U8`
:raises: :class:`requests.HTTPError` if channel is offline.
... | 0.002614 |
def version_cmd(argv):
"""Prints current pew version"""
import pkg_resources
try:
__version__ = pkg_resources.get_distribution('pew').version
except pkg_resources.DistributionNotFound:
__version__ = 'unknown'
print('Setuptools has some issues here, failed to get our own package.... | 0.00551 |
def logs_handle_experiment_job(experiment_name: str,
experiment_uuid: str,
log_lines: Optional[Union[str, Iterable[str]]],
temp: bool = True) -> None:
"""Task handling for sidecars logs."""
handle_experiment_job_log(exp... | 0.001984 |
def p_case_statement(self, p):
'case_statement : CASE LPAREN case_comp RPAREN casecontent_statements ENDCASE'
p[0] = CaseStatement(p[3], p[5], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | 0.013953 |
def has_datastore(self):
# type: () -> bool
"""Check if the resource has a datastore.
Returns:
bool: Whether the resource has a datastore or not
"""
success, result = self._read_from_hdx('datastore', self.data['id'], 'resource_id',
... | 0.009823 |
def get_model_and_form_class(model, form_class):
"""
Returns a model and form class based on the model and form_class
parameters that were passed to the generic view.
If ``form_class`` is given then its associated model will be returned along
with ``form_class`` itself. Otherwise, if ``model`` is ... | 0.000906 |
def _divide(self, x1, x2, out):
"""Compute the entry-wise quotient ``x1 / x2``.
This function is part of the subclassing API. Do not
call it directly.
Parameters
----------
x1, x2 : `NumpyTensor`
Dividend and divisor in the quotient.
out : `NumpyTens... | 0.002398 |
def search(self, query):
""" Perform request tracker search """
# Prepare the path
log.debug("Query: {0}".format(query))
path = self.url.path + '?Format=__id__+__Subject__'
path += "&Order=ASC&OrderBy=id&Query=" + urllib.quote(query)
# Get the tickets
lines = sel... | 0.004301 |
def handle_termination(cls, pid, is_cancel=True):
'''
Internal method to terminate a subprocess spawned by `pexpect` representing an invocation of runner.
:param pid: the process id of the running the job.
:param is_cancel: flag showing whether this termination is caused by
... | 0.003311 |
def read(morph_file, data_wrapper=DataWrapper):
'''return a 'raw_data' np.array with the full neuron, and the format of the file
suitable to be wrapped by DataWrapper
'''
msg = ('This is an experimental reader. '
'There are no guarantees regarding ability to parse '
'Neurolucida .... | 0.003257 |
def get_release(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
init_path = os.path.join(PROJECT_PATH, package, '__init__.py')
init_py = open(init_path).read()
return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1) | 0.00346 |
def get_function(self):
"""
Return function object for my function.
raise ProcessorConfigurationError when function could not be resolved.
"""
if not hasattr(self, '_function'):
try:
modname, funcname = self.function.rsplit('.', 1)
mod ... | 0.003617 |
def hist(self, var: str, title: str = '',
label: str = '') -> object:
"""
This method requires a numeric column (use the contents method to see column types) and generates a histogram.
:param var: the NUMERIC variable (column) you want to plot
:param title: an optional Titl... | 0.004288 |
def apply_transformation(self, structure, return_ranked_list=False):
"""
Apply the transformation.
Args:
structure: input structure
return_ranked_list (bool/int): Boolean stating whether or not
multiple structures are returned. If return_ranked_list is
... | 0.00133 |
def _set_vlag(self, v, load=False):
"""
Setter method for vlag, mapped from YANG variable /interface/port_channel/vlag (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vlag is considered as a private
method. Backends looking to populate this variable shoul... | 0.005938 |
def compile_file(fullpath, outfile_name, compiler_args):
"""Calls HamlPy compiler."""
if Options.VERBOSE:
print '%s %s -> %s' % (strftime("%H:%M:%S"), fullpath, outfile_name)
try:
if Options.DEBUG:
print "Compiling %s -> %s" % (fullpath, outfile_name)
haml_lines = codecs.... | 0.009749 |
def get(self, index, doc_type, id, fields=None, model=None, **query_params):
"""
Get a typed JSON document from an index based on its id.
"""
path = make_path(index, doc_type, id)
if fields is not None:
query_params["fields"] = ",".join(fields)
model = model o... | 0.007264 |
def iter_data(self):
"""Iterate over key-value pairs that are really meant to be displayed"""
for (k, v) in self.proxy.items():
if (
not (isinstance(k, str) and k[0] == '_') and
k not in (
'character',
'name',
... | 0.0075 |
def aggregation_postprocessors_extractor(impact_report, component_metadata):
"""Extracting aggregate result of demographic.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:para... | 0.000098 |
def pseudo_tempname(self):
"""Return a pseudo-tempname base in the install directory.
This code is intentionally naive; if a malicious party can write to
the target directory you're already in deep doodoo.
"""
try:
pid = os.getpid()
except:
pid = r... | 0.009456 |
def get_pending_withdrawals(self, currency=None):
"""
Used to view your pending withdrawals
Endpoint:
1.1 NO EQUIVALENT
2.0 /key/balance/getpendingwithdrawals
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:return: pending... | 0.003425 |
def purge_archives(base_dir: str, retain_latest: bool = False) -> None:
"""
Erase all (or nearly all) cache archives.
:param base_dir: archive base directory
:param retain_latest: retain latest archive if present, purge all others
"""
LOGGER.debug('purge_archives >>> ba... | 0.006002 |
def move_edges(self,n1,n2):
"""Move edges from node 1 to node 2
Not self edges though
Overwrites edges
"""
#Traverse edges to find incoming with n1
incoming = []
for e in self._edges.values():
if e.node2.id == n1.id: incoming.append(e)
#Traverse edges to... | 0.043435 |
def runExperiment():
"""
Experiment 1: Calculate error rate as a function of training sequence numbers
:return:
"""
trainSeqN = [5, 10, 20, 50, 100, 200]
rptPerCondition = 20
correctRateAll = np.zeros((len(trainSeqN), rptPerCondition))
missRateAll = np.zeros((len(trainSeqN), rptPerCondition))
fpRateAl... | 0.032695 |
def ffconvert(fname, limit_states, ff, min_iml=1E-10):
"""
Convert a fragility function into a numpy array plus a bunch
of attributes.
:param fname: path to the fragility model file
:param limit_states: expected limit states
:param ff: fragility function node
:returns: a pair (array, dictio... | 0.000349 |
def get_child_catalog_ids(self, catalog_id):
"""Gets the child ``Ids`` of the given catalog.
arg: catalog_id (osid.id.Id): the ``Id`` to query
return: (osid.id.IdList) - the children of the catalog
raise: NotFound - ``catalog_id`` is not found
raise: NullArgument - ``catalo... | 0.003576 |
def print_trip_table(document):
""" Print trip table """
headers = [
'Alt.',
'Name',
'Time',
'Track',
'Direction',
'Dest.',
'Track',
'Arrival']
table = []
altnr = 0
for alternative in document:
altnr += 1
first_trip_in_a... | 0.000923 |
def batch_size(self):
"""int: The number of results to fetch per batch. Clamped to
limit if limit is set and is smaller than the given batch
size.
"""
batch_size = self.get("batch_size", DEFAULT_BATCH_SIZE)
if self.limit is not None:
return min(self.limit, ba... | 0.005634 |
def warn_sf(messages, response, verbs=None, klass=SalesforceWarning):
"""Issue a warning SalesforceWarning, with message combined from message and data from SFDC response"""
warnings.warn(klass(messages, response, verbs), stacklevel=2) | 0.00823 |
def tenant_create(name, description=None, enabled=True, profile=None,
**connection_args):
'''
Create a keystone tenant
CLI Examples:
.. code-block:: bash
salt '*' keystone.tenant_create nova description='nova tenant'
salt '*' keystone.tenant_create test enabled=False... | 0.001934 |
def serializer_by_type_id(self, type_id):
"""
Find and return the serializer for the type-id
:param type_id: type-id the serializer
:return: the serializer
"""
if type_id <= 0:
indx = index_for_default_type(type_id)
serializer = self._constant_type... | 0.004348 |
def get_data(self, df):
"""Returns the chart data"""
chart_data = []
if len(self.groupby) > 0:
groups = df.groupby(self.groupby)
else:
groups = [((), df)]
for keys, data in groups:
chart_data.extend([{
'key': self.labelify(keys,... | 0.004454 |
def extract(pcmiter, samplerate, channels, duration = -1):
"""Given a PCM data stream, extract fingerprint data from the
audio. Returns a byte string of fingerprint data. Raises an
ExtractionError if fingerprinting fails.
"""
extractor = _fplib.Extractor(samplerate, channels, duration)
# Get fi... | 0.003852 |
def create_markdown_cell(block):
"""Create a markdown cell from a block."""
kwargs = {'cell_type': block['type'],
'source': block['content']}
markdown_cell = nbbase.new_markdown_cell(**kwargs)
return markdown_cell | 0.007605 |
def list_packages_in_eups_table(table_text):
"""List the names of packages that are required by an EUPS table file.
Parameters
----------
table_text : `str`
The text content of an EUPS table file.
Returns
-------
names : `list` [`str`]
List of package names that are require... | 0.001416 |
def ecdsa_public_key(pubkey_str, compressed=None):
"""
Make a public key object, but enforce the following rule:
* if compressed is True or False, make the key compressed/uncompressed.
* otherwise, return whatever the hex encoding is
"""
if compressed == True:
pubkey_str = keylib.key_for... | 0.006237 |
def mavlink_packet(self, m):
'''handle mavlink packets'''
if m.get_type() == 'SYSTEM_TIME':
if self.system_time_settings.verbose:
print("ST: Received from (%u/%u): %s" %
(m.get_srcSystem(), m.get_srcComponent(), m))
if m.get_type() == 'TIMESYNC':... | 0.001541 |
def get_links(self, text=None, *args, **kwargs):
"""Find anchors or buttons by containing text, as well as standard
BeautifulSoup arguments.
:param text: String or regex to be matched in link text
:return: List of BeautifulSoup tags
"""
return helpers.find_all(
... | 0.005208 |
def mixin_params(self, params):
"""
Merge in the MdsolAttribute for the passed parameter
:param dict params: dictionary of object parameters
"""
if not isinstance(params, (dict,)):
raise AttributeError("Cannot mixin to object of type {}".format(type(params)))
... | 0.007246 |
def open_application(self, remote_url, alias=None, **kwargs):
"""Opens a new application to given Appium server.
Capabilities of appium server, Android and iOS,
Please check https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/server-args.md
| *Option* ... | 0.00487 |
def add(self, interval):
"""
Returns self after adding the interval and balancing.
"""
if self.center_hit(interval):
self.s_center.add(interval)
return self
else:
direction = self.hit_branch(interval)
if not self[direction]:
... | 0.003565 |
def _quoted(value):
"""Return a single-quoted and escaped (percent-encoded) version of value
This function will also perform transforms of known data types to a representation
that will be handled by Device Cloud. For instance, datetime objects will be
converted to ISO8601.
"""
if isinstance(... | 0.006466 |
def load_inversion_results(self, sipdir):
"""Given an sEIT inversion directory, load inversion results and store
the corresponding parameter ids in self.assignments
Note that all previous data stored in this instance of the eitManager
will be overwritten, if required!
"""
... | 0.001129 |
def deconstruct(self):
"""
to support Django 1.7 migrations, see also the add_introspection_rules
section at bottom of this file for South + earlier Django versions
"""
name, path, args, kwargs = super(
ExclusiveBooleanField, self).deconstruct()
if self._on_fi... | 0.004902 |
def __internal_union(self, root_a, root_b):
"""Internal function to join two set trees specified by root_a and root_b.
Assumes root_a and root_b are distinct.
"""
# Merge the trees, smaller to larger
update_rank = False
# --Determine the larger tree
rank_a = self.... | 0.003641 |
def inv_std_norm_cdf(x):
"""
Inverse cumulative standard Gaussian distribution
Based on Winitzki, S. (2008)
"""
z = 2*x -1
ln1z2 = np.log(1-z**2)
a = 8*(np.pi -3)/(3*np.pi*(4-np.pi))
b = 2/(np.pi * a) + ln1z2/2
inv_erf = np.sign(z) * np.sqrt( np.sqrt(b**2 - ln1z2/a) - b )
return ... | 0.014706 |
def _rm_get_reference_coords_from_header(parts):
"""
extract the reference (genomic sequence match) coordinates of a repeat
occurrence from a repeatmakser header line. An example header line is::
239 29.42 1.92 0.97 chr1 11 17 (41) C XX#YY (74) 104 1 m_b1s502i1 4
the genomic start and end are always at po... | 0.007792 |
def __read_frame(self):
"""*Attempt* to read a frame. If we get an EAGAIN on the frame header,
it'll raise to our caller. If we get it *after* we already got the
header, wait-out the rest of the frame.
"""
if self.__frame_header_cache is None:
_logger.debug("Readin... | 0.004994 |
def set_definition_node(self, node, name):
"""Set definition by name."""
definition = self.get_definition(name)
if definition:
definition.node = node | 0.010811 |
async def traverse(self, func):
"""
Traverses an async function or generator, yielding each result.
This function is private. The class should be used as an iterator instead of using this method.
"""
# this allows the reference to be stolen
async_executor = self
... | 0.005859 |
def post(self, request):
"""
Save the user and profile, login and send the right signals.
"""
if request.user.is_authenticated():
return self.error_to_response(request, dict(
error=_("You are already logged in.")))
try:
user, profile, cli... | 0.010778 |
def rename(oldPath, newPath, **kwargs):
"""rename the file oldPath to newPath"""
import os
return os.rename(oldPath, newPath, **kwargs) | 0.006803 |
def read_request_from_str(data, **params):
"""
从字符串中读取请求头,并根据格式化字符串模板,进行字符串格式化
:param data:
:param params:
:return:
"""
method, uri = None, None
headers = {}
host = ''
try:
split_list = data.split('\n\n')
headers_text = split_list[0]
body = '\n\n'.join(sp... | 0.002492 |
def lstat(path):
'''
.. versionadded:: 2014.1.0
Returns the lstat attributes for the given file or dir. Does not support
symbolic links.
CLI Example:
.. code-block:: bash
salt '*' file.lstat /path/to/file
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
... | 0.004808 |
def gumbel_softmax_discrete_bottleneck(x,
bottleneck_bits,
beta=0.25,
decay=0.999,
epsilon=1e-5,
temperature_warmup_steps=150... | 0.008296 |
def construct_cfgs(**kargs):
"""construct_cfgs
Performs actions to construct either the setup.cfg (rpm) or stdeb.cfg (deb)
files as per the operating system specified. This construction is done as
per the setup_requirements.txt file from within the working directory
specified.
This is a very tempermental functio... | 0.000883 |
def can_undo(self):
"""
Are there actions to undo?
"""
return bool(self._undo) or bool(self._open and self._open[0]) | 0.013514 |
def images(cam):
"""Extract images from input stream to jpg files.
Args:
cam: Input stream of raw rosbag messages.
Returns:
File instances for images of input stream.
"""
# Set output stream title and pull first message
yield marv.set_header(title=cam.topic)
# Fetch and pr... | 0.001058 |
def get_requirements():
"""
Returns the content of 'requirements.txt' in a list.
:return: The content of 'requirements.txt'.
:rtype: list(str)
"""
requirements = []
with open(
os.path.join(BASE_DIRECTORY, 'requirements.txt'),
'r',
encoding='utf-8'
) as requireme... | 0.002119 |
def set_data(self, data):
"Use this method to set the data for this blob"
if data is None:
self.data_size = 0
self.data = None
return
self.data_size = len(data)
# create a string buffer so that null bytes aren't interpreted
# as the end of the string
self.data = ctypes.cast(ctypes.create_string_bu... | 0.031609 |
def buy_holding_pnl(self):
"""
[float] 买方向当日持仓盈亏
"""
return (self.last_price - self.buy_avg_holding_price) * self.buy_quantity * self.contract_multiplier | 0.016216 |
def close(self: Any) -> None:
"""Close any files linked to this object
"""
if self._file_obj is not None:
self._file_obj.close()
self._file_obj = None | 0.010309 |
def make_discord_blueprint(
client_id=None,
client_secret=None,
scope=None,
redirect_url=None,
redirect_to=None,
login_url=None,
authorized_url=None,
session_class=None,
storage=None,
):
"""
Make a blueprint for authenticating with Discord using OAuth 2. This requires
a c... | 0.001414 |
def create_api_v4_virtual_interface(self):
"""Get an instance of Api Virtual Interface services facade."""
return ApiV4VirtualInterface(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | 0.007605 |
def modified_environ(added=None, absent=()):
"""
Temporarily updates the os.environ dictionary in-place. Can be used as a
context manager or a decorator.
The os.environ dictionary is updated in-place so that the modification is
sure to work in all situations.
:param added: Dictionary of enviro... | 0.000788 |
def exec_helper(self, cmd, builddir):
''' Execute the given command, returning an error message if an error occured
or None if the command was succesful.'''
try:
child = subprocess.Popen(cmd, cwd=builddir)
child.wait()
except OSError as e:
if e.err... | 0.005384 |
def add_url(self, name: str, pattern: str, application: Callable) -> None:
""" add url pattern dispatching to application"""
self.urlmapper.add(name, self.prefix + pattern)
self.register_app(name, application) | 0.008584 |
def init(name, runtime):
"""Create a new Django app."""
runtime = click.unstyle(runtime)
stdout.write(
style.format_command(
'Initializing',
'%s %s %s' % (name, style.gray('@'), style.green(runtime))
)
)
config = Config(os.getcwd())
config.set('runtime',... | 0.002203 |
def get_request(self, request):
"""Get a list of DownloadRequests for all data that are under the given field in the table of a Geopedia layer.
:return: list of items which have to be downloaded
:rtype: list(DownloadRequest)
"""
request.layer = self._parse_layer(request.layer, r... | 0.007792 |
def xlink_href_target(self, node, group=None):
"""
Return either:
- a tuple (renderer, node) when the the xlink:href attribute targets
a vector file or node
- the path to an image file for any raster image targets
- None if any problem occurs
"""... | 0.002072 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.