Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
352,600 | def main():
p = OptionParser(main.__doc__)
supported_formats = tuple(x.strip() for x in \
"lav, lav+text, axt, axt+, maf, maf+, maf-, sam, softsam, "\
"sam-, softsam-, cigar, BLASTN, BLASTN-, differences, rdotplot, text".split())
p.add_option("--format", default="BLASTN-", choices=sup... | %prog database.fa query.fa [options]
Run LASTZ similar to the BLAST interface, and generates -m8 tabular format |
352,601 | def add_result(self, job):
self.cur.execute(
"INSERT INTO history VALUES(?,?,?,?)",
(job["id"], job["description"], job["last-run"], job["last-run-result"]))
return True | Adds a job run result to the history table.
:param dict job: The job dictionary
:returns: True |
352,602 | def intersect(self, other):
loc = self.locate_keys(other, strict=False)
return self.compress(loc, axis=0) | Intersect with `other` sorted index.
Parameters
----------
other : array_like, int
Array of values to intersect with.
Returns
-------
out : SortedIndex
Values in common.
Examples
--------
>>> import allel
>>> idx... |
352,603 | def sampleLocation(self):
areaRatio = self.radius / (self.radius + self.height)
if random.random() < areaRatio:
return self._sampleLocationOnDisc()
else:
return self._sampleLocationOnSide() | Simple method to sample uniformly from a cylinder. |
352,604 | def _nonzero_intersection(m, m_hat):
n_features, _ = m.shape
m_no_diag = m.copy()
m_no_diag[np.diag_indices(n_features)] = 0
m_hat_no_diag = m_hat.copy()
m_hat_no_diag[np.diag_indices(n_features)] = 0
m_hat_nnz = len(np.nonzero(m_hat_no_diag.flat)[0])
m_nnz = len(np.nonzero(m_no_diag.... | Count the number of nonzeros in and between m and m_hat.
Returns
----------
m_nnz : number of nonzeros in m (w/o diagonal)
m_hat_nnz : number of nonzeros in m_hat (w/o diagonal)
intersection_nnz : number of nonzeros in intersection of m/m_hat
(w/o diagonal) |
352,605 | def pl2nvp(plane):
assert (isinstance(plane, stypes.Plane))
normal = stypes.emptyDoubleVector(3)
point = stypes.emptyDoubleVector(3)
libspice.pl2nvp_c(ctypes.byref(plane), normal, point)
return stypes.cVectorToPython(normal), stypes.cVectorToPython(point) | Return a unit normal vector and point that define a specified plane.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pl2nvp_c.html
:param plane: A SPICE plane.
:type plane: supporttypes.Plane
:return: A unit normal vector and point that define plane.
:rtype: tuple |
352,606 | def Z_device(self, filter_order=None, window_size=None, tol=0.05):
ind = mlab.find(self.fb_resistor >= 0)
Z1 = np.empty(self.fb_resistor.shape)
Z1.fill(np.nan)
Z1 = np.ma.masked_invalid(Z1)
R2 = self.calibration.R_fb[self.fb_resistor[ind]]
C2 = self.cal... | Compute the impedance *(including resistive and capacitive load)* of
the DMF device *(i.e., dielectric and droplet)*.
See :func:`calibrate.compute_from_transfer_function`
for details. |
352,607 | def itermonthdates(cls, year, month):
curday = NepDate.from_bs_date(year, month, 1)
start_weekday = curday.weekday()
for i in range(start_weekday, 0, -1):
yield (curday - timedelta(days=i))
for i in range(0, values.NEPALI_MONTH_DAY_DATA[year][month - 1]):
... | Returns an iterator for the month in a year
This iterator will return all days (as NepDate objects) for the month
and all days before the start of the month or after the end of the month
that are required to get a complete week. |
352,608 | def get_pgs(self, pool_size, percent_data=DEFAULT_POOL_WEIGHT,
device_class=None):
validator(value=pool_size, valid_type=int)
if percent_data is None:
percent_data = DEFAULT_POOL_WEIGHT
osd_list = get_o... | Return the number of placement groups to use when creating the pool.
Returns the number of placement groups which should be specified when
creating the pool. This is based upon the calculation guidelines
provided by the Ceph Placement Group Calculator (located online at
http://ceph.com/... |
352,609 | def wrap_xml(self, xml, encoding =, standalone=):
header = %(encoding, standalone)
return header+xml | Method that provides a standard svg header string for a file |
352,610 | def write_default_config_file(self, output, comments=True):
if self.use_config_file:
log = logging.getLogger()
with open(output, ) as f:
if comments:
f.write("
f.write("
f.write("
... | This method write a sample file, with attributes, descriptions,
sample values, required flags, using the configuration object
properties. |
352,611 | def math_funcdef_handle(tokens):
internal_assert(len(tokens) == 2, "invalid assignment function definition tokens", tokens)
return tokens[0] + ("" if tokens[1].startswith("\n") else " ") + tokens[1] | Process assignment function definition. |
352,612 | def run(self):
try:
self.sftp.stat(self.remote_path)
except FileNotFoundError as e:
if self.create_remote_directory:
self.sftp.mkdir(self.remote_path)
self.logger.info(
"Created missing remote dir: ")
... | Run the sync.
Confront the local and the remote directories and perform the needed changes. |
352,613 | def _edges_to_adjacency_list(edges):
adj = {}
for i, j in edges:
if i in adj:
ni = adj[i]
else:
ni = adj[i] = set()
if j in adj:
nj = adj[j]
else:
nj = adj[j] = set()
ni.add(j)
nj.add(i)
return adj | Convert a list of edges into an adjacency list. |
352,614 | def build_temp_job_archive(cls):
try:
os.unlink()
os.unlink()
except OSError:
pass
cls._archive = cls(job_archive_table=,
file_archive_table=,
base_path=os.path.abspath() + )
return cls._a... | Build and return a `JobArchive` using defualt locations of
persistent files. |
352,615 | def main():
ofile=""
if in sys.argv:
print(main.__doc__)
sys.exit()
if in sys.argv:
ind=sys.argv.index()
ofile=sys.argv[ind+1]
out=open(ofile,)
if in sys.argv:
ind=sys.argv.index()
flt=float(sys.argv[ind+1])
else:
print(main._... | NAME
squish.py
DESCRIPTION
takes dec/inc data and "squishes" with specified flattening factor, flt
using formula tan(Io)=flt*tan(If)
INPUT
declination inclination
OUTPUT
"squished" declincation inclination
SYNTAX
squish.py [command line ... |
352,616 | def _set_l1_spf6_timer(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=l1_spf6_timer.l1_spf6_timer, is_container=, presence=False, yang_name="l1-spf6-timer", rest_name="l1-spf6-timer", parent=self, path_helper=self._path_helper, extmethods=self._extme... | Setter method for l1_spf6_timer, mapped from YANG variable /isis_state/router_isis_config/l1_spf6_timer (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_l1_spf6_timer is considered as a private
method. Backends looking to populate this variable should
do so vi... |
352,617 | def post_replace_result(self, score, outcome_opts=defaultdict(lambda:None), result_data=None):
texturl
return self.new_request(outcome_opts).post_replace_result(score, result_data) | POSTs the given score to the Tool Consumer with a replaceResult.
Returns OutcomeResponse object and stores it in self.outcome_request
OPTIONAL:
result_data must be a dictionary
Note: ONLY ONE of these values can be in the dict at a time,
due to the Canvas specificat... |
352,618 | def _add_node(self, idx, unique_idx, frac_coords):
self.nodes[idx] = {: unique_idx, : frac_coords} | Add information about a node describing a critical point.
:param idx: unique index
:param unique_idx: index of unique CriticalPoint,
used to look up more information of point (field etc.)
:param frac_coord: fractional co-ordinates of point
:return: |
352,619 | def make_qscan_plot(workflow, ifo, trig_time, out_dir, injection_file=None,
data_segments=None, time_window=100, tags=None):
tags = [] if tags is None else tags
makedir(out_dir)
name =
curr_exe = PlotQScanExecutable(workflow.cp, name, ifos=[ifo],
out_... | Generate a make_qscan node and add it to workflow.
This function generates a single node of the singles_timefreq executable
and adds it to the current workflow. Parent/child relationships are set by
the input/output files automatically.
Parameters
-----------
workflow: pycbc.workflow.core.Work... |
352,620 | def reader(self):
request_stream =
with self.connect() as request:
if request.msg != :
raise HTTPError
request_stream = request.read().decode()
return request_stream | Reads raw text from the connection stream.
Ensures proper exception handling.
:return bytes: request |
352,621 | def add_samples(self, samples, reverse=False):
self.log(u"Adding samples...")
samples_length = len(samples)
current_length = self.__samples_length
future_length = current_length + samples_length
if (self.__samples is None) or (self.__samples_capacity < future_length):
... | Concatenate the given new samples to the current audio data.
This function initializes the memory if no audio data
is present already.
If ``reverse`` is ``True``, the new samples
will be reversed and then concatenated.
:param samples: the new samples to be concatenated
... |
352,622 | def commit(self):
with self.native(writeAccess=True) as conn:
if not self._closed(conn):
return self._commit(conn) | Commits the changes to the current database connection.
:return <bool> success |
352,623 | def get_value(self, node):
if isinstance(node,tf.Tensor):
return self._cache.get(node.name,None)
elif isinstance(node,tf.Operation):
return None
else:
return self._cache.get(node,None) | retrieve a node value from the cache |
352,624 | def _format_segment(tokens, strict=True, gpstype=LIGOTimeGPS):
try:
start, end, dur = tokens
except ValueError:
return Segment(*map(gpstype, tokens))
seg = Segment(gpstype(start), gpstype(end))
if strict and not float(abs(seg)) == float(dur):
raise ValueError(
... | Format a list of tokens parsed from an ASCII file into a segment. |
352,625 | def batch(samples):
samples = [utils.to_single_data(x) for x in samples]
sample_order = [dd.get_sample_name(x) for x in samples]
batch_groups = collections.defaultdict(list)
for data in samples:
batch_samples = tuple(data.get("batch_samples", [dd.get_sample_name(data)]))
batch_group... | CWL: batch together per sample, joint and germline calls for ensemble combination.
Sets up groups of same sample/batch variant calls for ensemble calling, as
long as we have more than one caller per group. |
352,626 | def new_symlink(self, vd, name, parent, rr_target, seqnum, rock_ridge,
rr_name, xa):
if self._initialized:
raise pycdlibexception.PyCdlibInternalError()
self._new(vd, name, parent, seqnum, False, 0, xa)
if rock_ridge:
self._rr_new(ro... | Create a new symlink Directory Record. This implies that the new
record will be Rock Ridge.
Parameters:
vd - The Volume Descriptor this record is part of.
name - The name for this directory record.
parent - The parent of this directory record.
rr_target - The symlin... |
352,627 | def add(self, vector, InterventionAnophelesParams=None):
assert isinstance(vector, six.string_types)
et = ElementTree.fromstring(vector)
mosquito = Vector(et)
assert isinstance(mosquito.mosquito, str)
... | Add a vector to entomology section.
vector is either ElementTree or xml snippet
InterventionAnophelesParams is an anophelesParams section for every GVI, ITN and IRS intervention
already defined in the scenario.xml |
352,628 | def util_pattern_space(time_series, lag, dim):
n = len(time_series)
if lag * dim > n:
raise Exception()
elif lag < 1:
raise Exception()
pattern_space = np.empty((n - lag * (dim - 1), dim))
for i in range(n - lag * (dim - 1)):
for j in range(dim):
pattern_sp... | Create a set of sequences with given lag and dimension
Args:
time_series: Vector or string of the sample data
lag: Lag between beginning of sequences
dim: Dimension (number of patterns)
Returns:
2D array of vectors |
352,629 | def transform_entries(self, entries, terminal_compositions):
new_entries = []
if self.normalize_terminals:
fractional_comp = [c.fractional_composition
for c in terminal_compositions]
else:
fractional_comp = terminal_compositions
... | Method to transform all entries to the composition coordinate in the
terminal compositions. If the entry does not fall within the space
defined by the terminal compositions, they are excluded. For example,
Li3PO4 is mapped into a Li2O:1.5, P2O5:0.5 composition. The terminal
compositions ... |
352,630 | def upload_backup_bundle_from_file(self, file_path, deployment_groups_id_or_uri):
deployment_groups_uri = deployment_groups_id_or_uri
if self.DEPLOYMENT_GROUPS_URI not in deployment_groups_id_or_uri:
deployment_groups_uri = self.DEPLOYMENT_GROUPS_URI + deployment_groups_id_or_uri
... | Restore an Artifact Bundle from a backup file.
Args:
file_path (str): The File Path to restore the Artifact Bundle.
deployment_groups_id_or_uri: ID or URI of the Deployment Groups.
Returns:
dict: Deployment group. |
352,631 | def argmax(self, C):
ind = np.absolute(C).argmax()
return np.unravel_index(ind, C.shape) | Returns the ArgMax from C by returning the
(x_pos, y_pos, theta, scale) tuple
>>> C = np.random.randn(10, 10, 5, 4)
>>> x_pos, y_pos, theta, scale = mp.argmax(C)
>>> C[x_pos][y_pos][theta][scale] = C.max() |
352,632 | def write(self, message, autoerase=True):
super(Animation, self).write(message)
self.last_message = message
if autoerase:
time.sleep(self.interval)
self.erase(message) | Send something for stdout and erased after delay |
352,633 | def dynamic_content_item_variant_show(self, item_id, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/dynamic_content
api_path = "/api/v2/dynamic_content/items/{item_id}/variants/{id}.json"
api_path = api_path.format(item_id=item_id, id=id)
return self.call(api_path, **kw... | https://developer.zendesk.com/rest_api/docs/core/dynamic_content#show-variant |
352,634 | def set_ttl(self, key, ttl):
return self._client.expire(self.get_key(key), ttl) | Sets time to live for @key to @ttl seconds
-> #bool True if the timeout was set |
352,635 | def namer(cls, imageUrl, pageUrl):
parts, year, month, stripname = pageUrl.rsplit(, 3)
stripname = stripname.rsplit(, 1)[0]
parts, imagename = imageUrl.rsplit(, 1)
return % (year, month, stripname, imagename) | Use page URL to construct meaningful image name. |
352,636 | def page_menus(root_menu):
for page in Page.objects.filter(include_in_menu=True):
path = page.get_path()
menu = path[0] if len(path) > 1 else None
try:
root_menu.add_item(page.name, page.get_absolute_url(), menu=menu)
except MenuError as e:
logger.error("... | Add page menus. |
352,637 | def _load_significant_pathways_file(path_to_file):
feature_pathway_df = pd.read_table(
path_to_file, header=0,
usecols=["feature", "side", "pathway"])
feature_pathway_df = feature_pathway_df.sort_values(
by=["feature", "side"])
return feature_pathway_df | Read in the significant pathways file as a
pandas.DataFrame. |
352,638 | def query_gene(self, gene, color=None, invert=False):
qi = self.columns[0].index(gene)
ndata = len(self.data)
for col in self.columns[1:]:
upstream_dist = downstream_dist = 1000
for i in range(qi - 1, -1, -1):
if col[i] not in (".", "... | Used in mcscanq() for query |
352,639 | def changes_since(self, domain, date_or_datetime):
domain_id = utils.get_id(domain)
dt = utils.iso_time_string(date_or_datetime, show_tzinfo=True)
uri = "/domains/%s/changes?since=%s" % (domain_id, dt)
resp, body = self._retry_get(uri)
return body.get("changes", []) | Gets the changes for a domain since the specified date/datetime.
The date can be one of:
- a Python datetime object
- a Python date object
- a string in the format 'YYYY-MM-YY HH:MM:SS'
- a string in the format 'YYYY-MM-YY'
It returns a list of dicts, who... |
352,640 | def next_frame_glow_bair_qual():
hparams = next_frame_glow_bair_quant()
hparams.coupling = "additive"
hparams.temperature = 0.5
hparams.coupling_width = 392
return hparams | Hparams for qualitative video generation results. |
352,641 | def generate_handler_sourcepath(
self, toolchain, spec, loaderplugin_sourcepath):
npm_pkg_name = (
self.node_module_pkg_name
if self.node_module_pkg_name else
self.find_node_module_pkg_name(toolchain, spec)
)
if not npm_pkg_name... | Attempt to locate the plugin source; returns a mapping of
modnames to the absolute path of the located sources. |
352,642 | def query_nvidia_smi(device_ids: List[int], result_queue: multiprocessing.Queue) -> None:
device_id_strs = [str(device_id) for device_id in device_ids]
query = "--query-gpu=index,memory.used,memory.total"
format_arg = "--format=csv,noheader,nounits"
try:
sp = subprocess.Popen([, query, form... | Runs nvidia-smi to determine the memory usage.
:param device_ids: A list of devices for which the the memory usage will be queried.
:param result_queue: The queue to which the result dictionary of device id mapping to a tuple of
(memory used, memory total) is added. |
352,643 | def _extract_ajax_endpoints(self):
url = .join([DOC_ROOT, ELITE_PAGE])
response = requests.get(url)
raw_html = response.text
soup = BeautifulSoup(raw_html, )
for url in soup.select():
if in url.text:
yield %... | make a GET request to freeproxylists.com/elite.html |
352,644 | def run(self):
try:
while True:
aFunction, arguments = self.manager.taskQueue.get()
if aFunction is None:
break
aFunction(arguments)
except KeyboardInterrupt:
import thread
print >>sys.stderr, "%s caught KeyboardInterrupt" % threading.currentThread().getN... | The main routine for a thread's work.
The thread pulls tasks from the manager's task queue and executes
them until it encounters a task with a function that is None. |
352,645 | def run(self, duration, obs):
from ecell4_base.core import TimeoutObserver
timeout = TimeoutObserver(self.__timeout)
if isinstance(obs, collections.Iterable):
obs = tuple(obs) + (timeout, )
else:
obs = (obs, timeout)
p = ProgressBar(**self.__kwar... | Run the simulation.
Parameters
----------
duration : Real
a duration for running a simulation.
A simulation is expected to be stopped at t() + duration.
observers : list of Obeservers, optional
observers |
352,646 | def get_mentions(self, docs=None, sort=False):
result = []
if docs:
docs = docs if isinstance(docs, (list, tuple)) else [docs]
for mention_class in self.mention_classes:
mentions = (
self.session.query(mention_class)
... | Return a list of lists of the mentions associated with this extractor.
Each list of the return will contain the Mentions for one of the
mention classes associated with the MentionExtractor.
:param docs: If provided, return Mentions from these documents. Else,
return all Mentions.
... |
352,647 | def _positive_int(integer_string, strict=False, cutoff=None):
ret = int(integer_string)
if ret < 0 or (ret == 0 and strict):
raise ValueError()
if cutoff:
ret = min(ret, cutoff)
return ret | Cast a string to a strictly positive integer. |
352,648 | def _many_to_one(input_dict):
return dict((key, val)
for keys, val in input_dict.items()
for key in keys) | Convert a many-to-one mapping to a one-to-one mapping |
352,649 | def get_load(jid):
log.debug(, jid)
conn = _get_conn(ret=None)
cur = conn.cursor()
sql =
cur.execute(sql,
{: jid})
data = cur.fetchone()
if data:
return salt.utils.json.loads(data[0].encode())
_close_conn(conn)
return {} | Return the load from a specified jid |
352,650 | def pagedump(self):
self.fh.seek(self.pagesize)
pn = 1
while True:
try:
pagedata = self.fh.read(self.pagesize)
if len(pagedata) == 0:
break
elif len(pagedata) != self.pagesize:
... | dump the contents of all pages, ignoring links between pages,
this will enable you to view contents of pages which have become
lost due to datacorruption. |
352,651 | def printSegment(self):
print "ID:%-5d" % (self.segID),
if self.isSequenceSeg:
print "True",
else:
print "False",
print "%9.7f" % (self.dutyCycle(readOnly=True)),
print "(%4d/%-4d)" % (self.positiveActivations,
self.totalActivations),... | Print segment information for verbose messaging and debugging.
This uses the following format:
ID:54413 True 0.64801 (24/36) 101 [9,1]0.75 [10,1]0.75 [11,1]0.75
where:
54413 - is the unique segment id
True - is sequence segment
0.64801 - moving average duty cycle
(24/36) - (numPos... |
352,652 | def memoize_single(func):
class memodict_single(dict):
def __missing__(self, key):
ret = self[key] = func(key)
return ret
return memodict_single().__getitem__ | Memoization decorator for a function taking a single argument
References:
http://code.activestate.com/recipes/578231-fastest-memoization-decorator |
352,653 | def Js(val, Clamped=False):
if isinstance(val, PyJs):
return val
elif val is None:
return undefined
elif isinstance(val, basestring):
return PyJsString(val, StringPrototype)
elif isinstance(val, bool):
return true if val else false
elif isinstance(val, float) or ... | Converts Py type to PyJs type |
352,654 | def _bulk_cache_lookup(self, api_name, keys):
if self._cache:
responses = self._cache.bulk_lookup(api_name, keys)
missing_keys = [key for key in keys if key not in responses.keys()]
return (responses, missing_keys)
return ({}, keys) | Performes a bulk cache lookup and returns a tuple with the results
found and the keys missing in the cache. If cached is not configured
it will return an empty dictionary of found results and the initial
list of keys.
Args:
api_name: a string name of the API.
key... |
352,655 | def _stringify_path(path_or_buffer):
try:
import pathlib
_PATHLIB_INSTALLED = True
except ImportError:
_PATHLIB_INSTALLED = False
if hasattr(path_or_buffer, ):
return path_or_buffer.__fspath__()
if _PATHLIB_INSTALLED and isinstance(path_or_buffer, pathlib.Path):
... | Convert path like object to string
Args:
path_or_buffer: object to be converted
Returns:
string_path_or_buffer: maybe string version of path_or_buffer |
352,656 | def uninstall(self):
log_filename = "agent_{host}.log".format(host=self.host)
data_filename = "agent_{host}.rawdata".format(host=self.host)
try:
if self.session:
self.session.send("stop\n")
self.session.close()
self.session = ... | Remove agent's files from remote host |
352,657 | def create_blobstore(self, **kwargs):
blobstore = predix.admin.blobstore.BlobStore(**kwargs)
blobstore.create()
blobstore.add_to_manifest(self)
return blobstore | Creates an instance of the BlobStore Service. |
352,658 | def p_expression_lor(self, p):
p[0] = Lor(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | expression : expression LOR expression |
352,659 | def sky2pix(self, skypos):
skybox = [skypos, skypos]
pixbox = self.wcs.all_world2pix(skybox, 1)
return [float(pixbox[0][0]), float(pixbox[0][1])] | Get the pixel coordinates for a given sky position (degrees).
Parameters
----------
skypos : (float,float)
ra,dec position in degrees.
Returns
-------
x,y : float
Pixel coordinates. |
352,660 | def create_lab_meeting(self, event_type, presenters, foodie = None, locked = False):
e = self.initialize_tagged_copy()
summary_texts = {
: ,
:
}
assert(summary_texts.get(event_type))
e[][][] = event_type
e[][][] = presenters
e[]... | Presenters can be a comma-separated list of presenters. |
352,661 | def _write_vdr(self, f, cdataType, numElems, numDims, dimSizes, name,
dimVary, recVary, sparse, blockingfactor, compression,
pad, zVar):
if zVar:
block_size = CDF.zVDR_BASE_SIZE64
section_type = CDF.zVDR_
else:
block_siz... | Writes a VDR block to the end of the file.
Parameters:
f : file
The open CDF file
cdataType : int
The CDF data type
numElems : int
The number of elements in the variable
numDims : int
The number of d... |
352,662 | def optimize(loss, learning_rate, hparams, use_tpu=False, variables=None):
loss = weight_decay_and_noise(loss, hparams, learning_rate)
loss = tf.identity(loss, name="total_loss")
if variables is None:
variables = tf.trainable_variables()
log_variable_sizes(variables, verbose=hparams.summarize_vars)
... | Minimize loss. |
352,663 | def writeLogToFile(self):
if not os.path.exists(self.logFolder):
os.mkdir(self.logFolder)
with open(self.logFile, mode=) as f:
f.write( + self.log) | writes the log to a |
352,664 | def extract_table(
self,
source,
destination_uris,
job_id=None,
job_id_prefix=None,
location=None,
project=None,
job_config=None,
retry=DEFAULT_RETRY,
):
job_id = _make_job_id(job_id, job_id_prefix)
if project is None:... | Start a job to extract a table into Cloud Storage files.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.extract
Arguments:
source (Union[ \
:class:`google.cloud.bigquery.table.Table`, \
:class:`google.cloud.bigquery.t... |
352,665 | def add(self, rule_name, session, **kwargs):
request = TOPRequest()
request[] = rule_name
for k, v in kwargs.iteritems():
if k not in (, , , , , , , , , , , , , , , ) and v==None: continue
request[k] = v
self.create(self.execute(request, session))
... | taobao.crm.rule.add 分组规则添加
添加分组规则,规则可用于筛选一定条件的会员。过滤条件可以选择客户来源、会员级别 、交易笔数、交易额、上次交易时间、平均客单价、宝贝件数、省份、关闭交易数等,新建规则时必须至少选择一个以上筛选条件。如果输入的规则的筛选条件不正确则不会进行处理,可以将某些分组挂在这个规则下,对被挂在该规则下的分组,系统对现有满足规则的客户都划分到这个分组(异步任务),若某些会员分组数或规则数超最大限额,则该会员不被操作,同时不影响其余会员操作,接口调用依然返回成功。每个规则可以应用到多个分组,一个用户的规则上限为5个。 |
352,666 | def _check_result(method_name, result):
if result.status_code != 200:
msg = \
.format(result.status_code, result.reason, result.text.encode())
raise ApiException(msg, method_name, result)
try:
result_json = result.json()
except:
msg = \
.format... | Checks whether `result` is a valid API response.
A result is considered invalid if:
- The server returned an HTTP response code other than 200
- The content of the result is invalid JSON.
- The method call was unsuccessful (The JSON 'ok' field equals False)
:raises ApiException: if one ... |
352,667 | def dict2tlist(this_dict,**kwargs):
abcd
if( in kwargs):
check = kwargs[]
else:
check = 1
if(check):
if(isinstance(this_dict,dict)):
pass
else:
return(None)
else:
pass
if( in kwargs):
deepcopy = kwargs[]
else:
de... | #sequence will be losted
d = {'a':'b','c':'d'}
dict2tlist(d) |
352,668 | def _server_url(server):
if not _HTTP_PAT.match(server):
server = % server
parsed = urlparse(server)
url = % (parsed.scheme, parsed.netloc)
return url | Normalizes a given server string to an url
>>> print(_server_url('a'))
http://a
>>> print(_server_url('a:9345'))
http://a:9345
>>> print(_server_url('https://a:9345'))
https://a:9345
>>> print(_server_url('https://a'))
https://a
>>> print(_server_url('demo.crate.io'))
http://dem... |
352,669 | def handle_channel_disconnected(self):
for namespace in self.app_namespaces:
if namespace in self._handlers:
self._handlers[namespace].channel_disconnected()
self.app_namespaces = []
self.destination_id = None
self.session_id = None | Handles a channel being disconnected. |
352,670 | def reset(self):
if self.seq is not None and self.shuffle:
random.shuffle(self.seq)
if self.last_batch_handle != or \
self._cache_data is None:
if self.imgrec is not None:
self.imgrec.reset()
self.cur = 0
if self._allo... | Resets the iterator to the beginning of the data. |
352,671 | def _merge_multi_context(outputs, major_axis):
rets = []
for tensors, axis in zip(outputs, major_axis):
if axis >= 0:
if len(tensors) == 1:
rets.append(tensors[0])
else:
rets.append(nd.concat(*[tensor.as_in_contex... | Merge outputs that lives on multiple context into one, so that they look
like living on one context. |
352,672 | def get_tmpdir():
global __tmpdir
if __tmpdir is not None:
return __tmpdir
__tmpdir = tempfile.mkdtemp(prefix=, dir=".")
atexit.register(__clean_tmpdir)
return __tmpdir | On first invocation, creates a temporary directory and returns its
path. Subsequent invocations uses the same directory.
:returns: A temporary directory created for this run of glerbl.
:rtype: :class:`str` |
352,673 | def get_suitable_date_for_daily_extract(self, date=None, ut=False):
daily_trips = self.get_trip_counts_per_day()
max_daily_trips = daily_trips[u].max(axis=0)
if date in daily_trips[u]:
start_index = daily_trips[daily_trips[u] == date].index.tolist()[0]
daily_trip... | Parameters
----------
date : str
ut : bool
Whether to return the date as a string or as a an int (seconds after epoch).
Returns
-------
Selects suitable date for daily extract
Iterates trough the available dates forward and backward from the download ... |
352,674 | def get_pull_requests(app, repo_config):
response = get_api_response(app, repo_config, "/repos/{repo_name}/pulls")
if not response.ok:
raise Exception("Unable to get pull requests: status code {}".format(response.status_code))
return (item for item in response.json) | Last 30 pull requests from a repository.
:param app: Flask app
:param repo_config: dict with ``github_repo`` key
:returns: id for a pull request |
352,675 | def add_predicate(self, key, value, predicate_type=):
if predicate_type not in operators:
predicate_type = operator_lkup.get(predicate_type)
if predicate_type:
self.predicates.append({: predicate_type,
: key,
... | add key, value, type combination of a predicate
:param key: query KEY parameter
:param value: the value used in the predicate
:param predicate_type: the type of predicate (e.g. ``equals``) |
352,676 | def json_request(endpoint, verb=, session_options=None, **options):
req = functools.partial(_request, endpoint, verb, session_options,
json=True, **options)
return _run_in_fresh_loop(req) | Like :func:`molotov.request` but extracts json from the response. |
352,677 | def exec_route_callback(self) -> Response or object:
if self.__method.lower() in self.__end_points:
for bound in self.__end_points[self.__method.lower()]:
route = list(bound)[0]
expected_params = self.get_url_params(route)
actual_params = sel... | Executes the resolved end-point callback, or its fallback
:rtype: Response or object |
352,678 | def fmt_chi2(f):
if hasattr(f, ):
fmt = "chi2/dof = %.2g [%d] Q = %.2g log(GBF) = %.5g"
chi2_dof = f.chi2 / f.dof if f.dof != 0 else 0
return fmt % (chi2_dof, f.dof, f.Q, f.logGBF)
else:
fmt = "chi2/dof = %.2g [%d] Q = %.2g"
chi2_dof = f.chi2 / f.dof if f.do... | Return string containing ``chi**2/dof``, ``dof`` and ``Q`` from ``f``.
Assumes ``f`` has attributes ``chi2``, ``dof`` and ``Q``. The
logarithm of the Bayes factor will also be printed if ``f`` has
attribute ``logGBF``. |
352,679 | def update(self, virtual_interfaces):
data = {: virtual_interfaces}
virtual_interfaces_ids = [str(env.get()) for env in virtual_interfaces]
return super(ApiV4VirtualInterface, self).put\
( % .join(virtual_interfaces_ids), data) | Method to update Virtual Interfaces
:param Virtual Interfaces: List containing Virtual Interfaces desired to updated
:return: None |
352,680 | def split_add_ops(text):
n = 0
text = text.replace(, ).replace(
, )
spotted = False
last = 0
while n < len(text):
e = text[n]
if e == or e == :
if spotted:
yield text[last:n].replace(, ).replace(, )
yield e
... | Specialized function splitting text at add/sub operators.
Operands are *not* translated. Example result ['op1', '+', 'op2', '-', 'op3'] |
352,681 | def DOM_getSearchResults(self, searchId, fromIndex, toIndex):
assert isinstance(searchId, (str,)
), "Argument must be of type str. Received type: " % type(
searchId)
assert isinstance(fromIndex, (int,)
), "Argument must be of type int. Received type: " % type(
fromIndex)
assert isinst... | Function path: DOM.getSearchResults
Domain: DOM
Method name: getSearchResults
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'searchId' (type: string) -> Unique search session identifier.
'fromIndex' (type: integer) -> Start index of the search result to... |
352,682 | def params(self):
params = FormsDict()
for key, value in self.query.allitems():
params[key] = value
for key, value in self.forms.allitems():
params[key] = value
return params | A :class:`FormsDict` with the combined values of :attr:`query` and
:attr:`forms`. File uploads are stored in :attr:`files`. |
352,683 | def addValuesToField(self, i, numValues):
assert(len(self.fields)>i)
values = [self.addValueToField(i) for n in range(numValues)]
return values | Add values to the field i. |
352,684 | def _path_to_value(cls, path, parent_dict):
keys = cls._path_to_keys(path)
child_dict = parent_dict
for key in keys[:-1]:
child_dict = child_dict.get(key)
if child_dict is None:
return
return child_dict.get(keys[-1]) | Return a value from a dictionary at the given path |
352,685 | def contains_value(self, value):
check_not_none(value, "value can't be None")
value_data = self._to_data(value)
return self._encode_invoke(map_contains_value_codec, value=value_data) | Determines whether this map contains one or more keys for the specified value.
:param value: (object), the specified value.
:return: (bool), ``true`` if this map contains an entry for the specified value. |
352,686 | def _search_for_export_symbols(self, matches):
pattern = .join(re.escape(match) for match in matches)
exp = re.compile(pattern)
symbol_list = []
try:
for symbol in self.pefile_handle.DIRECTORY_ENTRY_EXPORT.symbols:
if symbol.name:
... | Just encapsulating a search that takes place fairly often |
352,687 | def shape(self) -> tuple:
try:
assert self._shape is not None
except (AssertionError, AttributeError):
self._shape = wt_kit.joint_shape(*self.variables)
finally:
return self._shape | Shape. |
352,688 | def build_response(self, request, response, from_cache=False):
if not from_cache and request.method == :
if response.status == 304:
cached_response = self.controller.update_cached_response(
... | Build a response by making a request or using the cache.
This will end up calling send and returning a potentially
cached response |
352,689 | def validate(self, other):
if other is None:
return
if other.table_type != self.table_type:
raise TypeError(
"incompatible table_type with existing "
"[{other} - {self}]".format(
other=other.table_type, self=self.table... | validate against an existing table |
352,690 | def allow_ip(*ips: typing.Union[str, ipaddress.IPv4Network, ipaddress.IPv4Address]):
for ip in ips:
if isinstance(ip, ipaddress.IPv4Address):
allowed_ips.add(ip)
elif isinstance(ip, str):
allowed_ips.add(ipaddress.IPv4Address(ip))
elif isinstance(ip, ipaddress.IP... | Allow ip address.
:param ips:
:return: |
352,691 | def createFilter(
self, *,
argument_filters=None,
fromBlock=None,
toBlock="latest",
address=None,
topics=None):
if fromBlock is None:
raise TypeError("Missing mandatory keyword argument to createFilter: fromBlock")
... | Create filter object that tracks logs emitted by this contract event.
:param filter_params: other parameters to limit the events |
352,692 | def set_attr(self, key: str, value):
self.attr_setter(self, key, value) | Sets node attribute. Can be customized by attr_setter property |
352,693 | def _populate_solver(self, reaction_list, metabolite_list=None):
constraint_terms = AutoVivification()
to_add = []
if metabolite_list is not None:
for met in metabolite_list:
to_add += [self.problem.Constraint(
Zero, name=met.id, lb=0, ub=... | Populate attached solver with constraints and variables that
model the provided reactions. |
352,694 | def Ω(self, k, n, τ, σ):
d = self._dichalcogenide
at, Δ, λ = d.at, d.Δ, d.λ
x = Δ - λ * τ * σ
y = (2 * at * k)**2 + x**2
return -2 * (n * τ * at**2) * x * y**(-3/2) | Berry curvature.
:param k: Momentum :math:`k`.
:type k: float
:param n: Band index :math:`n = ±1`.
:type n: int
:param τ: Valley index :math:`τ = ±1`.
:type τ: int
:param σ: Spin index :math:`σ = ±1`.
:type σ: int
:return: :math:`Ω^n_{τ σ} (k)`... |
352,695 | def get_bboxes_pathcollection(sc, ax):
transform = sc.get_transform()
transOffset = sc.get_offset_transform()
offsets = sc._offsets
paths = sc.get_paths()
transforms = sc.get_transforms()
if not transform.is_affine:
paths = [transform.transform_path_non_affine(p) for p in paths]
... | Function to return a list of bounding boxes in data coordinates
for a scatter plot
Thank you to ImportanceOfBeingErnest
https://stackoverflow.com/a/55007838/1304161 |
352,696 | def competition_submissions(self, competition):
submissions_result = self.process_response(
self.competitions_submissions_list_with_http_info(id=competition))
return [Submission(s) for s in submissions_result] | get the list of Submission for a particular competition
Parameters
==========
competition: the name of the competition |
352,697 | def is_stone_backend(cls, path):
path_without_ext, _ = os.path.splitext(path)
_, second_ext = os.path.splitext(path_without_ext)
return second_ext == cls.backend_extension | Returns True if the file name matches the format of a stone backend,
ie. its inner extension of "stoneg". For example: xyz.stoneg.py |
352,698 | def defaultExtension(self):
result = self.EXTERNAL_TYPES[self.typ]
if not self.fileExtensions:
return result
if result in self.fileExtensions:
return result
return self.fileExtensions[0] | Return default extension for this parameter type, checked
against supported fileExtensions. If the default extension is
not within `fileExtensions`, return the first supported
extension. |
352,699 | def latsph(radius, lon, lat):
radius = ctypes.c_double(radius)
lon = ctypes.c_double(lon)
lat = ctypes.c_double(lat)
rho = ctypes.c_double()
colat = ctypes.c_double()
lons = ctypes.c_double()
libspice.latsph_c(radius, lon, lat, ctypes.byref(rho), ctypes.byref(colat),
... | Convert from latitudinal coordinates to spherical coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latsph_c.html
:param radius: Distance of a point from the origin.
:param lon: Angle of the point from the XZ plane in radians.
:param lat: Angle of the point from the XY plane in radi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.