Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
350,000 | def utctimetuple(self):
"Return UTC time tuple compatible with time.gmtime()."
offset = self.utcoffset()
if offset:
self -= offset
y, m, d = self.year, self.month, self.day
hh, mm, ss = self.hour, self.minute, self.second
return _build_struct_time(y, m, d, hh,... | Return UTC time tuple compatible with time.gmtime(). |
350,001 | def generate_hotel_price(location, nights, room_type):
room_types = [, , ]
cost_of_living = 0
for i in range(len(location)):
cost_of_living += ord(location.lower()[i]) - 97
return nights * (100 + cost_of_living + (100 + room_types.index(room_type.lower()))) | Generates a number within a reasonable range that might be expected for a hotel.
The price is fixed for a pair of location and roomType. |
350,002 | def groupcountdistinctvalues(table, key, value):
s1 = cut(table, key, value)
s2 = distinct(s1)
s3 = aggregate(s2, key, len)
return s3 | Group by the `key` field then count the number of distinct values in the
`value` field. |
350,003 | def drop_schema(client, table_name):
query =
return client.execute(query.format(cf=table_name),
{}, ConsistencyLevel.QUORUM) | Delete the table/columnfamily.
:param client: A Cassandra CQL client
:type client: silverberg.client.CQLClient
:param lock_table: A table/columnfamily table name for holding locks.
:type lock_table: str |
350,004 | def update(self, *args, **kwargs):
self._write_op(self._update_nosync, *args, **kwargs) | Update the values of several attributes in a single operation. |
350,005 | def load(cls, fp, **kwargs):
json_obj = json.load(fp, **kwargs)
return parse(cls, json_obj) | wrapper for :py:func:`json.load` |
350,006 | def check_need_install():
md5_root, md5_dst = list(), list()
need_install_flag = False
for root, _, basename_list in os.walk(_ROOT):
if os.path.basename(root) != "__pycache__":
for basename in basename_list:
src = os.path.join(root, basename)
dst = os... | Check if installed package are exactly the same to this one. |
350,007 | def optional_product(self, product_type):
self._optional_dependencies.add(product_type)
self.require(product_type) | Schedules tasks, if any, that produce product_type to be executed before the requesting task.
There need not be any tasks that produce the required product type. All this method
guarantees is that if there are any then they will be executed before the requesting task.
:API: public |
350,008 | def plot_survival_function(self, **kwargs):
return _plot_estimate(
self,
estimate=self.survival_function_,
confidence_intervals=self.confidence_interval_survival_function_,
**kwargs
) | Alias of ``plot`` |
350,009 | def cred_init(
self,
*,
secrets_dir: str,
log: Logger,
bot_name: str,
) -> None:
super().__init__(secrets_dir=secrets_dir, log=log, bot_name=bot_name)
self.ldebug("Retrieving CONSUMER_KEY...")
with open(path.join(self.secr... | Initialize what requires credentials/secret files.
:param secrets_dir: dir to expect credentials in and store logs/history in.
:param log: logger to use for log output.
:param bot_name: name of this bot,
used for various kinds of labelling.
:returns: none. |
350,010 | def _get_all_secret_versions(self, secure_data_path, limit=None):
for secret in self._get_all_secret_version_ids(secure_data_path, limit):
yield {: self.get_secrets_data(secure_data_path, version=secret[]),
: secret} | Convenience function that returns a generator yielding the contents of secrets and their version info
secure_data_path -- full path to the key in the safety deposit box
limit -- Default(100), limits how many records to be returned from the api at once. |
350,011 | def atan_mgl(x, n=10):
acc = 1 / (1 - z ** -1)
return acc(mgl_seq(x)).skip(n-1).take() | Finds the arctan using the Madhava-Gregory-Leibniz series. |
350,012 | def replace(self, new_value, args, kwargs):
if self.arg_pos is not None and len(args) > self.arg_pos:
old_value = args[self.arg_pos]
args = list(args)
args[self.arg_pos] = new_value
else:
old_value = kwargs.get... | Replace the named argument in ``args, kwargs`` with ``new_value``.
Returns ``(old_value, args, kwargs)``. The returned ``args`` and
``kwargs`` objects may not be the same as the input objects, or
the input objects may be mutated.
If the named argument was not found, ``new_value`` will... |
350,013 | def q_scan(data, mismatch=DEFAULT_MISMATCH, qrange=DEFAULT_QRANGE,
frange=DEFAULT_FRANGE, duration=None, sampling=None,
**kwargs):
from gwpy.timeseries import TimeSeries
if isinstance(data, TimeSeries):
duration = abs(data.span)
sampling = data.sample_rate.to().va... | Transform data by scanning over a `QTiling`
This utility is provided mainly to allow direct manipulation of the
`QTiling.transform` output. Most users probably just want to use
:meth:`~gwpy.timeseries.TimeSeries.q_transform`, which wraps around this.
Parameters
----------
data : `~gwpy.timeser... |
350,014 | def make_disk_kernel(radius, npix=501, cdelt=0.01, xpix=None, ypix=None):
radius /= cdelt
def fn(t, s): return 0.5 * (np.sign(s - t) + 1.0)
dxy = make_pixel_distance(npix, xpix, ypix)
k = fn(dxy, radius)
k /= (np.sum(k) * np.radians(cdelt) ** 2)
return k | Make kernel for a 2D disk.
Parameters
----------
radius : float
Disk radius in deg. |
350,015 | def check_deps(self):
shutit_global.shutit_global_object.yield_to_draw()
cfg = self.cfg
self.log(, level=logging.DEBUG)
self.pause_point(, print_input=False, level=3)
return [] | Dependency checking phase is performed in this method. |
350,016 | def name_to_hex(name, spec=u):
if spec not in SUPPORTED_SPECIFICATIONS:
raise ValueError(SPECIFICATION_ERROR_TEMPLATE.format(spec=spec))
normalized = name.lower()
hex_value = {u: CSS2_NAMES_TO_HEX,
u: CSS21_NAMES_TO_HEX,
u: CSS3_NAMES_TO_HEX,
u... | Convert a color name to a normalized hexadecimal color value.
The optional keyword argument ``spec`` determines which
specification's list of color names will be used; valid values are
``html4``, ``css2``, ``css21`` and ``css3``, and the default is
``css3``.
When no color of that name exists in th... |
350,017 | def finder_for_path(path):
result = None
pkgutil.get_importer(path)
loader = sys.path_importer_cache.get(path)
finder = _finder_registry.get(type(loader))
if finder:
module = _dummy_module
module.__file__ = os.path.join(path, )
module.__loader__ = loader
res... | Return a resource finder for a path, which should represent a container.
:param path: The path.
:return: A :class:`ResourceFinder` instance for the path. |
350,018 | def starting(self):
ident = self.ident()
print(.format(ident, self.to_consume))
if self.max_tasks:
print(.format(ident, self.max_tasks))
else:
print(.format(ident)) | Prints a startup message to stdout. |
350,019 | def analyze(self, M_c, T, X_L, X_D, seed, kernel_list=(), n_steps=1, c=(),
r=(),
max_iterations=-1, max_time=-1, do_diagnostics=False,
diagnostics_every_N=1,
ROW_CRP_ALPHA_GRID=(),
COLUMN_CRP_ALPHA_GRID=(),
S_GRID=(), MU_GRI... | Evolve the latent state by running MCMC transition kernels.
:param seed: The random seed
:type seed: int
:param M_c: The column metadata
:type M_c: dict
:param T: The data table in mapped representation (all floats, generated
by data_utils.read_data_objects)
... |
350,020 | def appendDatastore(self, store):
if not isinstance(store, Datastore):
raise TypeError("stores must be of type %s" % Datastore)
self._stores.append(store) | Appends datastore `store` to this collection. |
350,021 | def create_rsa_encrypted_pem(private_key, passphrase):
securesystemslib.formats.PEMRSA_SCHEMA.check_match(private_key)
securesystemslib.formats.PASSWORD_SCHEMA.check_match(passphrase)
encrypted_pem = None
encrypted_pem = securesystemslib.pyca_crypto_keys.create_rsa_encrypted_pem(
... | <Purpose>
Return a string in PEM format (TraditionalOpenSSL), where the private part
of the RSA key is encrypted using the best available encryption for a given
key's backend. This is a curated (by cryptography.io) encryption choice and
the algorithm may change over time.
c.f. cryptography.io/en/la... |
350,022 | def at_rank(self, rank):
s = self
while s:
if s.rank == rank:
return s
s = s.parent
raise ValueError("No node at rank {0} for {1}".format(
rank, self.tax_id)) | Find the node above this node at rank ``rank`` |
350,023 | def _read_json_db(self):
try:
metadata_str = self.db_io.read_metadata_from_uri(
self.layer_uri, )
except HashNotFoundError:
return {}
try:
metadata = json.loads(metadata_str)
return metadata
except ValueError:
... | read metadata from a json string stored in a DB.
:return: the parsed json dict
:rtype: dict |
350,024 | def debug_string(self, max_debug=MAX_DEBUG_TRIALS):
messages = self._debug_messages()
states = collections.defaultdict(set)
limit_per_state = collections.Counter()
for t in self._trials:
states[t.status].add(t)
while max_debug > 0:
start... | Returns a human readable message for printing to the console. |
350,025 | def plot_recurrence_models(
configs, area, slip, msr, rake,
shear_modulus=30.0, disp_length_ratio=1.25E-5, msr_sigma=0.,
figure_size=(8, 6), filename=None, filetype=, dpi=300, ax=None):
if ax is None:
fig, ax = plt.subplots(figsize=figure_size)
else:
fig = ax.get_fig... | Plots a set of recurrence models
:param list configs:
List of configuration dictionaries |
350,026 | def get_client(self, region):
ep = self._ep_for_region(region)
if not ep:
raise exc.NoEndpointForRegion("There is no endpoint defined for the "
"region for the service." % (region,
self.service_type))
return ep.client | Returns an instance of the appropriate client class for the given
region. If there is no endpoint for that region, a NoEndpointForRegion
exception is raised. |
350,027 | async def msetnx(self, *args, **kwargs):
if args:
if len(args) != 1 or not isinstance(args[0], dict):
raise RedisError()
kwargs.update(args[0])
for k, _ in kwargs.items():
if await self.get(k):
return False
r... | Sets key/values based on a mapping if none of the keys are already set.
Mapping can be supplied as a single dictionary argument or as kwargs.
Returns a boolean indicating if the operation was successful.
Clutser impl:
Itterate over all items and do GET to determine if all keys do no... |
350,028 | def sample(self, n_samples, divs=1, visual=False, safe=False):
if visual:
print("Sampling: 0%")
for i in xrange(divs):
self._sample(int(n_samples/divs))
if visual:
sys.stdout.write("\033[F")
print("Sampling: "+str(int(i*100.... | Sample
Sampling
Inputs :
n_samples :
number of samples to generate
Optional Inputs :
divs : (1)
number of divisions
visual :
show progress
safe :
save the chain at every division |
350,029 | def main(params=None):
if params == None:
parser = getParser()
args = parser.parse_args(params)
else:
args = params
results = []
if not args.quiet:
print(general.title(banner.text))
sayingHello = .format(general.LICENSE_URL)
print(general.info(sayingHello))... | Main function to launch phonefy.
The function is created in this way so as to let other applications make
use of the full configuration capabilities of the application. The
parameters received are used as parsed by this modules `getParser()`.
Args:
-----
params: A list with the parameters ... |
350,030 | def validate(self):
try:
assert self.question == "", "Assumption Failed: Perseus question should not have a question"
assert self.question_type == exercises.PERSEUS_QUESTION, "Assumption Failed: Question should be perseus type"
assert self.answers == [], "Assumption ... | validate: Makes sure perseus question is valid
Args: None
Returns: boolean indicating if perseus question is valid |
350,031 | def get(self, parent_cid=None, cids=[], fields=[]):
request = TOPRequest()
if not fields:
itemCat = ItemCat()
fields = itemCat.fields
request[] = fields
if parent_cid!=None:
request[] = parent_cid
if cids:
request[] = .join... | taobao.itemcats.get 获取后台供卖家发布商品的标准商品类目 |
350,032 | def edit(self, billing_email=github.GithubObject.NotSet, blog=github.GithubObject.NotSet, company=github.GithubObject.NotSet, description=github.GithubObject.NotSet, email=github.GithubObject.NotSet, location=github.GithubObject.NotSet, name=github.GithubObject.NotSet):
assert billing_email is github.G... | :calls: `PATCH /orgs/:org <http://developer.github.com/v3/orgs>`_
:param billing_email: string
:param blog: string
:param company: string
:param description: string
:param email: string
:param location: string
:param name: string
:rtype: None |
350,033 | def add_arguments(parser):
default_log_path = os.path.realpath()
parser.add_argument(, metavar=, type=str,
dest=, default=default_log_path,
help=)
q_choices = (
, ,
, ,
, ,
, ,
, ,
, ,
, ,
, ,
, ,
)
parser.add_argument(, metavar=, ty... | Adds stock arguments to argparse parsers from scripts that submit grid
jobs. |
350,034 | def vals2bins(vals,res=100):
if any(isinstance(el, list) for el in vals):
vals = list(itertools.chain(*vals))
return list(np.digitize(vals, np.linspace(np.min(vals), np.max(vals)+1, res+1)) - 1) | Maps values to bins
Args:
values (list or list of lists) - list of values to map to colors
res (int) - resolution of the color map (default: 100)
Returns:
list of numbers representing bins |
350,035 | def attach_to_log(level=logging.DEBUG,
handler=None,
loggers=None,
colors=True,
capture_warnings=True,
blacklist=None):
if blacklist is None:
blacklist = [,
,
,
... | Attach a stream handler to all loggers.
Parameters
------------
level: logging level
handler: log handler object
loggers: list of loggers to attach to
if None, will try to attach to all available
colors: bool, if True try to use colorlog formatter
blacklist: list... |
350,036 | def _Close(self):
super(RawFile, self)._Close()
for file_object in self._file_objects:
file_object.close()
self._file_objects = [] | Closes the file-like object. |
350,037 | def from_networkx_graph(cls, G, vartype=None, node_attribute_name=,
edge_attribute_name=):
if vartype is None:
if not hasattr(G, ):
msg = ("either argument must be provided or "
"the given graph should have a vartype attrib... | Create a binary quadratic model from a NetworkX graph.
Args:
G (:obj:`networkx.Graph`):
A NetworkX graph with biases stored as node/edge attributes.
vartype (:class:`.Vartype`/str/set, optional):
Variable type for the binary quadratic model. Accepted inp... |
350,038 | def process_params(self, params):
custom_ext_
for key, val in params.items():
if key in LAUNCH_DATA_PARAMETERS and val != :
if key == :
if isinstance(val, list):
self.roles = val.split()
else... | Populates the launch data from a dictionary. Only cares about keys in
the LAUNCH_DATA_PARAMETERS list, or that start with 'custom_' or
'ext_'. |
350,039 | def write_min_config(self, filename,
header="
with self._open(filename, "w") as f:
f.write(header)
for sym in self.unique_defined_syms:
if sym.choice and \
not sym.cho... | Writes out a "minimal" configuration file, omitting symbols whose value
matches their default value. The format matches the one produced by
'make savedefconfig'.
The resulting configuration file is incomplete, but a complete
configuration can be derived from it by loading it. Minimal
... |
350,040 | def tasks_file_to_task_descriptors(tasks, retries, input_file_param_util,
output_file_param_util):
task_descriptors = []
path = tasks[]
task_min = tasks.get()
task_max = tasks.get()
param_file = dsub_util.load_file(path)
reader = csv.reader(param_file, delimiter=)
... | Parses task parameters from a TSV.
Args:
tasks: Dict containing the path to a TSV file and task numbers to run
variables, input, and output parameters as column headings. Subsequent
lines specify parameter values, one row per job.
retries: Number of retries allowed.
input_file_param_util: Utility... |
350,041 | def get_schema_dir(db_version=1):
v = str(db_version)
return os.path.join(_top_dir, , , , v) | Get path to directory with schemata.
:param db_version: Version of the database
:type db_version: int
:return: Path
:rtype: str |
350,042 | def subscribe(self, event, callback):
if not callable(callback):
raise QiskitError("Callback is not a callable!")
if event not in self._subscribers:
self._subscribers[event] = []
new_subscription = self._Subscription(event, callback)
if new_subscription... | Subscribes to an event, so when it's emitted all the callbacks subscribed,
will be executed. We are not allowing double registration.
Args
event (string): The event to subscribed in the form of:
"terra.<component>.<method>.<action>"
callback (callable... |
350,043 | def _apply_skips(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
for skip in self._skips:
try:
result = skip(r)
if result is True:
yield True
... | Apply skip functions on `r`. |
350,044 | def writeRaw8(self, value):
value = value & 0xFF
self._idle()
self._transaction_start()
self._i2c_start()
self._i2c_write_bytes([self._address_byte(False), value])
self._i2c_stop()
response = self._transaction_end()
self._verify_acks(response) | Write an 8-bit value on the bus (without register). |
350,045 | def get_span_ids(self):
node_span = self.node.find()
if node_span is not None:
mySpan = Cspan(node_span)
span_ids = mySpan.get_span_ids()
return span_ids
else:
return [] | Returns the span object of the term
@rtype: List
@return: the term span as list of wf ids |
350,046 | def generate(self, func_src):
logger.warning(
)
with open(, ) as fh:
fh.write(func_src)
logger.debug()
logger.warning(
)
self._write_zip(func_src, )
logger.debug()
logger... | Generate TF config and write to ./webhook2lambda2sqs.tf.json;
write the lambda function to ./webhook2lambda2sqs_func.py
:param func_src: lambda function source
:type func_src: str |
350,047 | def __modify(self, mfa_id, **kwargs):
params = {
: mfa_id
}
return self.make_call(self.__modify, params, kwargs) | Call documentation: `/user/mfa/modify
<https://www.wepay.com/developer/reference/user-mfa#modify>`_,
plus extra keyword parameter:
:keyword bool batch_mode: turn on/off the batch_mode, see
:class:`wepay.api.WePay`
:keyword str batch_reference_id: `reference_id` para... |
350,048 | def connect(cls, region, session=None, access_key=None, secret_key=None,
host=None, port=80, is_secure=True, **kwargs):
if session is None:
session = botocore.session.get_session()
if access_key is not None:
session.set_credentials(access_key, sec... | Connect to an AWS region.
Parameters
----------
region : str
Name of an AWS region
session : :class:`~botocore.session.Session`, optional
The Session object to use for the connection
access_key : str, optional
If session is None, set this acce... |
350,049 | def get_assets(self):
if not bool(self._my_map[]):
raise errors.IllegalState()
mgr = self._get_provider_manager()
if not mgr.supports_asset_lookup():
raise errors.OperationFailed()
lookup_session = mgr.get_asset_lookup_session(proxy=get... | Gets any assets associated with this activity.
return: (osid.repository.AssetList) - list of assets
raise: IllegalState - ``is_asset_based_activity()`` is
``false``
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implem... |
350,050 | def _rest_dispatch(self, request, response):
http_verb = request.get_command()
sub_path = request.get_sub_path()
max_valid_args = -1
best_method = None
best_args = None
best_match = None
for route, method in self.__ro... | Dispatches the request
:param request: Request bean
:param response: Response bean |
350,051 | def has_var_groups(self):
ids = set()
for d in self.data:
if self._has_known_variant(d) != and d[] != :
ids.add(d[])
return ids | Returns a set of the variant group ids that this cluster has |
350,052 | def _multi(fun, lons, lats, chunk_size, cores=1):
pool = Pool(processes=cores)
splits = get_scene_splits(lons.shape[0], chunk_size, cores)
lons_parts = np.vsplit(lons, splits)
lats_parts = np.vsplit(lats, splits)
results = [pool.apply_async(fun,
(lons_parts[i]... | Work on multiple cores. |
350,053 | def add_origin(self, account_id, media_type, origin_url, cname=None,
secure=False):
config = {: media_type,
: origin_url,
: secure}
if cname:
config[] = cname
return self.account.createOriginPullMapping(config, id=acc... | Adds an original pull mapping to an origin-pull.
:param int account_id: the numeric ID associated with the CDN account.
:param string media_type: the media type/protocol associated with this
origin pull mapping; valid values are HTTP,
... |
350,054 | def smoothed_hazards_(self, bandwidth=1):
timeline = self._index.values
return pd.DataFrame(
np.dot(epanechnikov_kernel(timeline[:, None], timeline, bandwidth), self.hazards_.values),
columns=self.hazards_.columns,
index=timeline,
) | Using the epanechnikov kernel to smooth the hazard function, with sigma/bandwidth |
350,055 | def gender(word, pos=NOUN):
w = word.lower()
if pos == NOUN:
if w.endswith(gender_masculine):
return MASCULINE
if w.endswith(gender_feminine):
return FEMININE
if w.endswith(gender_neuter):
return NEUTER
for g in gender_ma... | Returns the gender (MALE, FEMALE or NEUTRAL) for nouns (majority vote).
Returns None for words that are not nouns. |
350,056 | def clean(self, *args, **kwargs):
if not self.pk:
if self.node.participation_settings.voting_allowed is not True:
raise ValidationError("Voting not allowed for this node")
if in settings.INSTALLED_APPS:
layer = self.node.layer
... | Check if votes can be inserted for parent node or parent layer |
350,057 | def _dfs_preorder(node, visited):
if node not in visited:
visited.add(node)
yield node
if node.lo is not None:
yield from _dfs_preorder(node.lo, visited)
if node.hi is not None:
yield from _dfs_preorder(node.hi, visited) | Iterate through nodes in DFS pre-order. |
350,058 | def _FindKeys(self, key, names, matches):
for name, subkey in iter(key.items()):
if name in names:
matches.append((name, subkey))
if isinstance(subkey, dict):
self._FindKeys(subkey, names, matches) | Searches the plist key hierarchy for keys with matching names.
If a match is found a tuple of the key name and value is added to
the matches list.
Args:
key (dict[str, object]): plist key.
names (list[str]): names of the keys to match.
matches (list[str]): keys with matching names. |
350,059 | def init_relation(self, models, relation):
for model in models:
model.set_relation(relation, Result(None, self, model))
return models | Initialize the relation on a set of models.
:type models: list
:type relation: str |
350,060 | def _binaryconfig(path, conf, dtype=None, shape=None, credentials=None):
import json
from thunder.readers import get_file_reader, FileNotFoundError
reader = get_file_reader(path)(credentials=credentials)
try:
buf = reader.read(path, filename=conf)
params = json.loads(str(buf.decode... | Collects parameters to use for binary series loading. |
350,061 | def remove_state(self, state_id, recursive=True, force=False, destroy=True):
if state_id not in self.states:
raise AttributeError("State_id %s does not exist" % state_id)
if state_id == self.start_state_id:
self.set_start_state(None)
keys_to_delete = [... | Remove a state from the container state.
:param state_id: the id of the state to remove
:param recursive: a flag to indicate a recursive disassembling of all substates
:param force: a flag to indicate forcefully deletion of all states (important for the decider state in the
barr... |
350,062 | def relations(cls):
return [c.key for c in cls.__mapper__.iterate_properties
if isinstance(c, RelationshipProperty)] | Return a `list` of relationship names or the given model |
350,063 | def ext_pillar(minion_id,
pillar,
conf):
vs = varstack.Varstack(config_filename=conf)
return vs.evaluate(__grains__) | Parse varstack data and return the result |
350,064 | def wantFile(self, file, package=None):
if self.coverInclusive:
if file.endswith(".py"):
if package and self.coverPackages:
for want in self.coverPackages:
if package.startswith(want):
return True
... | If inclusive coverage enabled, return true for all source files
in wanted packages. |
350,065 | def write(self, b):
self._checkClosed()
self._checkWritable()
try:
return self._sock.send(b)
except error as e:
if e.args[0] in _blocking_errnos:
return None
raise | Write the given bytes or bytearray object *b* to the socket
and return the number of bytes written. This can be less than
len(b) if not all data could be written. If the socket is
non-blocking and no bytes could be written None is returned. |
350,066 | def commit_file(self, message, path, content):
if self.git_batch_commit:
self.add_file(path, content)
self.git_batch_commit_messages.append(message)
else:
with self.lock_write():
if self.job_id:
self.read_tree(self.ref_head... | Add a new file as blob in the storage, add its tree entry into the index and commit the index.
:param message: str
:param path: str
:param content: str
:return: |
350,067 | def _setup_chrome(self, capabilities):
chrome_driver = self.config.get(, )
self.logger.debug("Chrome driver path given in properties: %s", chrome_driver)
return webdriver.Chrome(chrome_driver, chrome_options=self._create_chrome_options(),
desired_capabili... | Setup Chrome webdriver
:param capabilities: capabilities object
:returns: a new local Chrome driver |
350,068 | def response_headers():
headers = MultiDict(request.args.items(multi=True))
response = jsonify(list(headers.lists()))
while True:
original_data = response.data
d = {}
for key in response.headers.keys():
value = response.headers.get_all(key)
if ... | Returns a set of response headers from the query string.
---
tags:
- Response inspection
parameters:
- in: query
name: freeform
explode: true
allowEmptyValue: true
schema:
type: object
additionalProperties:
type: string
styl... |
350,069 | def bulk_launch(self, jobs=None, filter=None, all=False):
json = None
if jobs is not None:
schema = JobSchema(exclude=(, , , , , , , , , ))
jobs_json = self.service.encode(schema, jobs, many=True)
json = {self.RESOURCE: jobs_json}
schema = JobSchema... | Bulk launch a set of jobs.
:param jobs: :class:`jobs.Job <jobs.Job>` list
:param filter: (optional) Filters to apply as a string list.
:param all: (optional) Apply to all if bool `True`. |
350,070 | def freqz_cas(sos,w):
Ns,Mcol = sos.shape
w,Hcas = signal.freqz(sos[0,:3],sos[0,3:],w)
for k in range(1,Ns):
w,Htemp = signal.freqz(sos[k,:3],sos[k,3:],w)
Hcas *= Htemp
return w, Hcas | Cascade frequency response
Mark Wickert October 2016 |
350,071 | def ensure_built(self, headers=None):
if not self.params:
return
else:
for child in self.params:
child.ensure_built(headers=headers)
if headers is None:
headers = self.guess_headers
generate(str(self), headers,
... | Make sure that a dictionary exists for this type. |
350,072 | def pingback_ping(source, target):
try:
if source == target:
return UNDEFINED_ERROR
site = Site.objects.get_current()
try:
document = .join(map(
lambda byte_line: byte_line.decode(),
urlopen(source).readlines()))
except (H... | pingback.ping(sourceURI, targetURI) => 'Pingback message'
Notifies the server that a link has been added to sourceURI,
pointing to targetURI.
See: http://hixie.ch/specs/pingback/pingback-1.0 |
350,073 | def retrieve_dataset_handles_or_version_numbers_of_all_versions(self, drs_id, prefix):
self.__reset_error_messages()
response_json = self.__ask_solr_for_handles_or_version_numbers_of_all_versions(drs_id)
result_dict = self.__parse_result_handles_or_version_numbers_of_all_versions(respon... | :return: Dict. Should never return None.
:raise: SolrSwitchedOff
:raise SolrError: If ... |
350,074 | def from_fits_renormalized(cls, file_path, hdu, pixel_scale):
psf = PSF.from_fits_with_scale(file_path, hdu, pixel_scale)
psf[:, :] = np.divide(psf, np.sum(psf))
return psf | Loads a PSF from fits and renormalizes it
Parameters
----------
pixel_scale
file_path: String
The path to the file containing the PSF
hdu : int
The HDU the PSF is stored in the .fits file.
Returns
-------
psf: PSF
A re... |
350,075 | def bitop_not(self, dest, key):
return self.execute(b, b, dest, key) | Perform bitwise NOT operations between strings. |
350,076 | def emit_to_room(self, room, event, *args):
pkt = dict(type="event",
name=event,
args=args,
endpoint=self.ns_name)
room_name = self._get_room_name(room)
for sessid, socket in six.iteritems(self.socket.server.sockets):
... | This is sent to all in the room (in this particular Namespace) |
350,077 | def showBeamlines(self):
cnt = 0
blidlist = []
for k in self.all_elements:
try:
if in self.all_elements.get(k):
cnt += 1
blidlist.append(k)
except:
pass
retstr = .format(total=cnt,
... | show all defined beamlines |
350,078 | def _handle_sighup(self, signum: int, frame: Any) -> None:
logger.warning("Catched SIGHUP")
exc_info = self._heartbeat_exc_info
self._heartbeat_exc_info = None
formatted_exception = .join(traceback.format_exception(*exc_info))
raise HeartbeatError(exc_info) | Used internally to fail the task when connection to RabbitMQ is
lost during the execution of the task. |
350,079 | def speak(self):
if self.quiet is False:
bot.info( %(self.name))
self._speak() | a function for the helper to announce him or herself, depending
on the level specified. If you want your client to have additional
announced things here, then implement the class `_speak` for your
client. |
350,080 | def _overlapOK(self, i, j, overlap=None):
if overlap is None:
overlap = self._countOverlapIndices(i, j)
if abs(i-j) < self.w:
if overlap == (self.w - abs(i-j)):
return True
else:
return False
else:
if overlap <= self._maxOverlap:
return True
else:
... | Return True if the given overlap between bucket indices i and j are
acceptable. If overlap is not specified, calculate it from the bucketMap |
350,081 | def duty_cycle_sp(self):
self._duty_cycle_sp, value = self.get_attr_int(self._duty_cycle_sp, )
return value | Writing sets the duty cycle setpoint. Reading returns the current value.
Units are in percent. Valid values are -100 to 100. A negative value causes
the motor to rotate in reverse. |
350,082 | def _parse_line(self, file):
line = self._strip_comments(file.readline())
if not line:
return False
if line.strip() == :
return True
reg = re.search("^\*(?P<key>[^:
if reg:
key = reg.group().strip()
... | Parse single line (or more if particular keyword actually demands it)
:param file:
:type file: file |
350,083 | def _compute_orientation(self):
cyl_mat = self.sim.data.body_xmat[self.cyl_body_id]
cyl_mat.shape = (3, 3)
cyl_pos = self.sim.data.body_xpos[self.cyl_body_id]
hole_pos = self.sim.data.body_xpos[self.hole_body_id]
hole_mat = self.sim.data.body_xmat[self.hole_body_id]
... | Helper function to return the relative positions between the hole and the peg.
In particular, the intersection of the line defined by the peg and the plane
defined by the hole is computed; the parallel distance, perpendicular distance,
and angle are returned. |
350,084 | def subst(self, string, raw=0, target=None, source=None, conv=None, executor=None):
gvars = self.gvars()
lvars = self.lvars()
lvars[] = self
if executor:
lvars.update(executor.get_lvars())
return SCons.Subst.scons_subst(string, self, raw, target, source, gvar... | Recursively interpolates construction variables from the
Environment into the specified string, returning the expanded
result. Construction variables are specified by a $ prefix
in the string and begin with an initial underscore or
alphabetic character followed by any number of undersco... |
350,085 | def subsample(self, rate, random=False):
if type(rate) != int and rate < 1:
raise ValueError()
indices = np.arange(self.num_points)
if random:
np.random.shuffle(indices)
subsample_inds = indices[::rate]
subsampled_data = self._data[:,subsample_ind... | Returns a subsampled version of the PointCloud.
Parameters
----------
rate : int
Only every rate-th element of the PointCloud is returned.
Returns
-------
:obj:`PointCloud`
A subsampled point cloud with N / rate total samples.
Raises
... |
350,086 | def match(self, subsetLines, offsetOfSubset, fileName):
for (offset,l) in enumerate(subsetLines):
column = l.find(self.literal)
if column != -1:
truePosition = offset + offsetOfSubset
_logger.debug(.format(str(truePosition+ 1), column))
... | Search through lines for match.
Raise an Exception if fail to match
If match is succesful return the position the match was found |
350,087 | def delete_enrollment(db, uuid, organization, from_date=None, to_date=None):
if uuid is None:
raise InvalidValueError()
if uuid == :
raise InvalidValueError()
if organization is None:
raise InvalidValueError()
if organization == :
raise InvalidValueError()
if no... | Withdraw a unique identity from an organization.
This function removes all the enrollments between the unique identity
identified by 'uuid' and the given 'organization'. Both 'uuid' and
organization must exists before deleting. Otherwise, it will raise a
'NotFoundError' exception.
When a period of... |
350,088 | def fsliceafter(astr, sub):
findex = astr.find(sub)
return astr[findex + len(sub):] | Return the slice after at sub in string astr |
350,089 | def to_json(self, model):
obj = super(DefaultModelRegistry, self).to_json(model)
obj[] = [
para.to_json() for para in model.parameters
]
obj[] = model.outputs.to_json()
return obj | Create a Json-like object for a model.
Parameters
----------
model : ModelHandle
Returns
-------
dict
Json-like object representation |
350,090 | def get_or_create_bottleneck(sess, image_lists, label_name, index, image_dir,
category, bottleneck_dir, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor, module_name):
label_lists = image_lists[lab... | Retrieves or calculates bottleneck values for an image.
If a cached version of the bottleneck data exists on-disk, return that,
otherwise calculate the data and save it to disk for future use.
Args:
sess: The current active TensorFlow Session.
image_lists: OrderedDict of training images for each label.
... |
350,091 | def init_logging(verbose=False, format=):
def sig_handler(signum, frame):
logger = logging.getLogger()
log_level = logger.level
if log_level == logging.DEBUG:
log_level = logging.WARN
else:
log_level = logging.DEBUG
logging.warn(,
... | Common utility for setting up logging in PyCBC.
Installs a signal handler such that verbosity can be activated at
run-time by sending a SIGUSR1 to the process. |
350,092 | def start(io_loop=None, check_time=2):
io_loop = io_loop or asyncio.get_event_loop()
if io_loop in _io_loops:
return
_io_loops[io_loop] = True
if len(_io_loops) > 1:
logger.warning("aiohttp_autoreload started more than once in the same process")
modify_times = {}
... | Begins watching source files for changes.
.. versionchanged:: 4.1
The ``io_loop`` argument is deprecated. |
350,093 | def process_action(self, request, queryset):
count = 0
for obj in queryset:
count += 1
obj.unpublish()
object_url = self.get_object_url(obj)
self.log_action(obj, CMSLog.UNPUBLISH, url=object_url)
url = self.get_done_url()
msg = sel... | Unpublishes the selected objects by calling the object's \
unpublish method. The action is logged and the user is \
notified with a message.
Returns a 'render redirect' to the result of the \
`get_done_url` method. |
350,094 | def get_metadata_new(self, series_number):
files, files_with_info = self.get_sorted_series_files(series_number=series_number, return_files_with_info=True)
metadata = {
... | Return series metadata.
Output condatin information about voxelsize_mm, series_number and modality.
If it is possible, the ImageComment, AcquisitionDate and few other dicom tags are also in output dict.
:param series_number:
:return: metadata dict with voxelsize_mm, SeriesNumber and othe... |
350,095 | def prev(self, n=1):
i = abs(self.tell - n)
return self.get(i, n) | Get the previous n data from file.
Keyword argument:
n -- number of structs to be retrieved (default 1)
Must be greater than 0.
Return:
A data in the format of obj_fmt, if n = 1. A list of
structs, otherwise. |
350,096 | def GetBigQueryClient(service_account_json=None,
project_id=None,
dataset_id=None):
service_account_data = (
service_account_json or config.CONFIG["BigQuery.service_acct_json"])
project_id = project_id or config.CONFIG["BigQuery.project_id"]
dataset_id = datase... | Create a BigQueryClient. |
350,097 | def getMaxWidth(self, rows):
w = 0
if len(rows) > 0:
w = max(max(len(self.getDisplayValue(r)) for r in rows), len(self.name))+2
return max(w, len(self.name)) | Return the maximum length of any cell in column or its header. |
350,098 | def getObjectsInHouse(self, house):
res = [obj for obj in self if house.hasObject(obj)]
return ObjectList(res) | Returns a list with all objects in a house. |
350,099 | def get_vertices_per_edge(mesh_v, mesh_f):
vc = sp.coo_matrix(get_vert_connectivity(mesh_v, mesh_f))
result = np.hstack((col(vc.row), col(vc.col)))
result = result[result[:,0] < result[:,1]]
return result | Returns an Ex2 array of adjacencies between vertices, where
each element in the array is a vertex index. Each edge is included
only once. If output of get_faces_per_edge is provided, this is used to
avoid call to get_vert_connectivity() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.