Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
376,000 | def heat_wave_frequency(tasmin, tasmax, thresh_tasmin=, thresh_tasmax=,
window=3, freq=):
r
thresh_tasmax = utils.convert_units_to(thresh_tasmax, tasmax)
thresh_tasmin = utils.convert_units_to(thresh_tasmin, tasmin)
cond = (tasmin > thresh_tasmin) & (tasmax > thresh_tasmax)... | r"""Heat wave frequency
Number of heat waves over a given period. A heat wave is defined as an event
where the minimum and maximum daily temperature both exceeds specific thresholds
over a minimum number of days.
Parameters
----------
tasmin : xarrray.DataArray
Minimum daily temperature... |
376,001 | def _adjust_penalty(self, observ, old_policy_params, length):
old_policy = self._policy_type(**old_policy_params)
with tf.name_scope():
network = self._network(observ, length)
print_penalty = tf.Print(0, [self._penalty], )
with tf.control_dependencies([print_penalty]):
kl_change =... | Adjust the KL policy between the behavioral and current policy.
Compute how much the policy actually changed during the multiple
update steps. Adjust the penalty strength for the next training phase if we
overshot or undershot the target divergence too much.
Args:
observ: Sequences of observatio... |
376,002 | def post(self, url, data, headers={}):
response = self._run_method(, url, data=data, headers=headers)
return self._handle_response(url, response) | POST request for creating new objects.
data should be a dictionary. |
376,003 | def confusion_matrix(model, X, y, ax=None, classes=None, sample_weight=None,
percent=False, label_encoder=None, cmap=,
fontsize=None, random_state=None, **kwargs):
visualizer = ConfusionMatrix(
model, ax, classes, sample_weight, percent,
label_enco... | Quick method:
Creates a heatmap visualization of the sklearn.metrics.confusion_matrix().
A confusion matrix shows each combination of the true and predicted
classes for a test data set.
The default color map uses a yellow/orange/red color scale. The user can
choose between displaying values as the... |
376,004 | def closed(self, code, reason=None):
if code != 1000:
self._error = errors.SignalFlowException(code, reason)
_logger.info(,
self, code, reason)
for c in self._channels.values():
c.offer(WebSocketComputationChannel.END_SENTINEL... | Handler called when the WebSocket is closed. Status code 1000
denotes a normal close; all others are errors. |
376,005 | def getecho (self):
attr = termios.tcgetattr(self.child_fd)
if attr[3] & termios.ECHO:
return True
return False | This returns the terminal echo mode. This returns True if echo is
on or False if echo is off. Child applications that are expecting you
to enter a password often set ECHO False. See waitnoecho(). |
376,006 | def is_dataset(ds):
import tensorflow as tf
from tensorflow_datasets.core.utils import py_utils
dataset_types = [tf.data.Dataset]
v1_ds = py_utils.rgetattr(tf, "compat.v1.data.Dataset", None)
v2_ds = py_utils.rgetattr(tf, "compat.v2.data.Dataset", None)
if v1_ds is not None:
dataset_types.append(v1_d... | Whether ds is a Dataset. Compatible across TF versions. |
376,007 | def append_row(table, label, data):
count = table.rowCount()
table.insertRow(table.rowCount())
items = QTableWidgetItem(label)
variant = (data,)
items.setData(Qt.UserRole, variant)
table.setItem(count, 0, items)
table.setItem(coun... | Append new row to table widget.
:param table: The table that shall have the row added to it.
:type table: QTableWidget
:param label: Label for the row.
:type label: str
:param data: custom data associated with label value.
:type data: str |
376,008 | def get_object(self, pid, type=None):
if type is None:
type = self.__class__
return type(self.api, pid) | Initialize and return a new
:class:`~eulfedora.models.DigitalObject` instance from the same
repository, passing along the connection credentials in use by
the current object. If type is not specified, the current
DigitalObject class will be used.
:param pid: pid of the object t... |
376,009 | def lande_g_factors(element, isotope, L=None, J=None, F=None):
r
atom = Atom(element, isotope)
gL = atom.gL
gS = atom.gS
gI = atom.gI
res = [gL, gS, gI]
if J is not None:
if L is None:
raise ValueError("A value of L must be specified.")
S = 1/Integer(2... | r"""Return the Lande g-factors for a given atom or level.
>>> element = "Rb"
>>> isotope = 87
>>> print(lande_g_factors(element, isotope))
[ 9.9999e-01 2.0023e+00 -9.9514e-04]
The spin-orbit g-factor for a certain J
>>> print(lande_g_factors(element, isotope, L=0, J=1/Integer(2)))
... |
376,010 | def rpc_request(method_name: str, *args, **kwargs) -> rpcq.messages.RPCRequest:
if args:
kwargs[] = args
return rpcq.messages.RPCRequest(
jsonrpc=,
id=str(uuid.uuid4()),
method=method_name,
params=kwargs
) | Create RPC request
:param method_name: Method name
:param args: Positional arguments
:param kwargs: Keyword arguments
:return: JSON RPC formatted dict |
376,011 | def get_locs(self, seq):
from .numeric import Int64Index
true_slices = [i for (i, s) in enumerate(com.is_true_slices(seq)) if s]
if true_slices and true_slices[-1] >= self.lexsort_depth:
raise UnsortedIndexError(
... | Get location for a given label/slice/list/mask or a sequence of such as
an array of integers.
Parameters
----------
seq : label/slice/list/mask or a sequence of such
You should use one of the above for each level.
If a level should not be used, set it to ``slice(No... |
376,012 | def _setup_notification_listener(self, topic_name, url):
self.notify_listener = rpc.DfaNotifcationListener(
topic_name, url, rpc.DfaNotificationEndpoints(self)) | Setup notification listener for a service. |
376,013 | def step(self, vector_action=None, memory=None, text_action=None, value=None, custom_action=None) -> AllBrainInfo:
vector_action = {} if vector_action is None else vector_action
memory = {} if memory is None else memory
text_action = {} if text_action is None else text_action
va... | Provides the environment with an action, moves the environment dynamics forward accordingly,
and returns observation, state, and reward information to the agent.
:param value: Value estimates provided by agents.
:param vector_action: Agent's vector action. Can be a scalar or vector of int/floats... |
376,014 | def plot2d(self, c_poly=, alpha=1, cmap=, ret=False,
title=, colorbar=False, cbar_label=):
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.cm as cm
paths = [polygon.get_path() for polygon in self]
do... | Generates a 2D plot for the z=0 Surface projection.
:param c_poly: Polygons color.
:type c_poly: matplotlib color
:param alpha: Opacity.
:type alpha: float
:param cmap: colormap
:type cmap: matplotlib.cm
:param ret: If True, returns the figure. It... |
376,015 | def yesterday(symbol, token=, version=):
_raiseIfNotStr(symbol)
return _getJson( + symbol + , token, version) | This returns previous day adjusted price data for one or more stocks
https://iexcloud.io/docs/api/#previous-day-prices
Available after 4am ET Tue-Sat
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: resu... |
376,016 | def plot(self, figsize="GROW", parameters=None, chains=None, extents=None, filename=None,
display=False, truth=None, legend=None, blind=None, watermark=None):
chains, parameters, truth, extents, blind = self._sanitise(chains, parameters, truth,
... | Plot the chain!
Parameters
----------
figsize : str|tuple(float)|float, optional
The figure size to generate. Accepts a regular two tuple of size in inches,
or one of several key words. The default value of ``COLUMN`` creates a figure
of appropriate size of i... |
376,017 | def append(self, species, coords, coords_are_cartesian=False,
validate_proximity=False, properties=None):
return self.insert(len(self), species, coords,
coords_are_cartesian=coords_are_cartesian,
validate_proximity=validate_proximity,... | Append a site to the structure.
Args:
species: Species of inserted site
coords (3x1 array): Coordinates of inserted site
coords_are_cartesian (bool): Whether coordinates are cartesian.
Defaults to False.
validate_proximity (bool): Whether to check... |
376,018 | def crescent_data(num_data=200, seed=default_seed):
np.random.seed(seed=seed)
sqrt2 = np.sqrt(2)
R = np.array([[sqrt2 / 2, -sqrt2 / 2], [sqrt2 / 2, sqrt2 / 2]])
scales = []
scales.append(np.array([[3, 0], [0, 1]]))
scales.append(np.array([[3, 0], [0, 1]]))
scales.append([[1, 0... | Data set formed from a mixture of four Gaussians. In each class two of the Gaussians are elongated at right angles to each other and offset to form an approximation to the crescent data that is popular in semi-supervised learning as a toy problem.
:param num_data_part: number of data to be sampled (default is 200)... |
376,019 | def _color_name_to_rgb(self, color):
" Turn , into (0xff, 0xff, 0xff). "
try:
rgb = int(color, 16)
except ValueError:
raise
else:
r = (rgb >> 16) & 0xff
g = (rgb >> 8) & 0xff
b = rgb & 0xff
return r, g, b | Turn 'ffffff', into (0xff, 0xff, 0xff). |
376,020 | def get(self, key, default=None):
if key in self._hparam_types:
if default is not None:
param_type, is_param_list = self._hparam_types[key]
type_str = % param_type if is_param_list else str(param_type)
fail_msg = ("Hparam of type is incompatible with "
... | Returns the value of `key` if it exists, else `default`. |
376,021 | def libvlc_media_player_set_time(p_mi, i_time):
f = _Cfunctions.get(, None) or \
_Cfunction(, ((1,), (1,),), None,
None, MediaPlayer, ctypes.c_longlong)
return f(p_mi, i_time) | Set the movie time (in ms). This has no effect if no media is being played.
Not all formats and protocols support this.
@param p_mi: the Media Player.
@param i_time: the movie time (in ms). |
376,022 | def _append_slash_if_dir_path(self, relpath):
if self._isdir_raw(relpath):
return self._append_trailing_slash(relpath)
return relpath | For a dir path return a path that has a trailing slash. |
376,023 | def Disks(self):
if not self.disks: self.disks = clc.v2.Disks(server=self,disks_lst=self.data[][],session=self.session)
return(self.disks) | Return disks object associated with server.
>>> clc.v2.Server("WA1BTDIX01").Disks()
<clc.APIv2.disk.Disks object at 0x10feea190> |
376,024 | def build_struct_type(s_sdt):
s_dt = nav_one(s_sdt).S_DT[17]()
struct = ET.Element(, name=s_dt.name)
first_filter = lambda selected: not nav_one(selected).S_MBR[46, ]()
s_mbr = nav_any(s_sdt).S_MBR[44](first_filter)
while s_mbr:
s_dt = nav_one(s_mbr).S_DT[45]()
type_na... | Build an xsd complexType out of a S_SDT. |
376,025 | async def get_tracks(self, query) -> Tuple[Track, ...]:
if not self._warned:
log.warn("get_tracks() is now deprecated. Please switch to using load_tracks().")
self._warned = True
result = await self.load_tracks(query)
return result.tracks | Gets tracks from lavalink.
Parameters
----------
query : str
Returns
-------
Tuple[Track, ...] |
376,026 | def check_valid_solution(solution, graph):
expected = Counter(
i for (i, _) in graph.iter_starts_with_index()
if i < graph.get_disjoint(i)
)
actual = Counter(
min(i, graph.get_disjoint(i))
for i in solution
)
difference = Counter(expected)
difference.subtrac... | Check that the solution is valid: every path is visited exactly once. |
376,027 | def search(self, **kwargs):
point = kwargs.pop(, False)
if point:
kwargs[] = % (point[0], point[1])
bound = kwargs.pop(, False)
if bound:
kwargs[] = bound[0]
kwargs[] = bound[1]
filters = kwargs.pop(, False)
if filters:
... | Firms search
http://api.2gis.ru/doc/firms/searches/search/ |
376,028 | def command(self, command, value=1, check=True, allowable_errors=None,
codec_options=DEFAULT_CODEC_OPTIONS, _deadline=None, **kwargs):
if isinstance(command, (bytes, unicode)):
command = SON([(command, value)])
options = kwargs.copy()
command.update(options)
... | command(command, value=1, check=True, allowable_errors=None, codec_options=DEFAULT_CODEC_OPTIONS) |
376,029 | def get_create_table_sql(self, table, create_flags=CREATE_INDEXES):
table_name = table.get_quoted_name(self)
options = dict((k, v) for k, v in table.get_options().items())
options["unique_constraints"] = OrderedDict()
options["indexes"] = OrderedDict()
options["primary"... | Returns the SQL statement(s) to create a table
with the specified name, columns and constraints
on this platform.
:param table: The table
:type table: Table
:type create_flags: int
:rtype: str |
376,030 | def delim(arguments):
if bool(arguments.control_files) == bool(arguments.directory):
raise ValueError(
)
if arguments.directory:
arguments.control_files.extend(control_iter(arguments.directory))
with arguments.output as fp:
results = _delim_accum(arguments.con... | Execute delim action.
:param arguments: Parsed command line arguments from :func:`main` |
376,031 | def render(self, *args, **kwargs):
env = {}; stdout = []
for dictarg in args: env.update(dictarg)
env.update(kwargs)
self.execute(stdout, env)
return .join(stdout) | Render the template using keyword arguments as local variables. |
376,032 | def parse_locator(locator):
if isinstance(locator, loc.Locator):
locator = .format(by=locator.by, locator=locator.locator)
locator_tuple = namedtuple(, )
if locator.count() > 0 and locator.count() < 1:
by = locator[:locator.find()].replace(, )
... | Parses a valid selenium By and value from a locator;
returns as a named tuple with properties 'By' and 'value'
locator -- a valid element locator or css string |
376,033 | def add_rpt(self, sequence, mod, pt):
modstr = self.value(mod)
if modstr == :
self._stream.restore_context()
self.diagnostic.notify(
error.Severity.ERROR,
"Cannot repeat a lookahead rule",
error.LocationInfo.from_stream(self._stream, is_... | Add a repeater to the previous sequence |
376,034 | def pull(remote=, branch=):
print(cyan("Pulling changes from repo ( %s / %s)..." % (remote, branch)))
local("git pull %s %s" % (remote, branch)) | git pull commit |
376,035 | def _generate_url_root(protocol, host, port):
return URL_ROOT_PATTERN.format(protocol=protocol, host=host, port=port) | Generate API root URL without resources
:param protocol: Web protocol [HTTP | HTTPS] (string)
:param host: Hostname or IP (string)
:param port: Service port (string)
:return: ROOT url |
376,036 | def get_coauthors(self):
res = download(url=self.coauthor_link, accept=)
data = loads(res.text)[]
N = int(data.get(, 0))
fields =
coauth = namedtuple(, fields)
coauthors = []
count = 0
while count < N:
param... | Retrieves basic information about co-authors as a list of
namedtuples in the form
(surname, given_name, id, areas, affiliation_id, name, city, country),
where areas is a list of subject area codes joined by "; ".
Note: These information will not be cached and are slow for large
c... |
376,037 | def save_load(jid, clear_load, minion=None):
cb_ = _get_connection()
try:
jid_doc = cb_.get(six.text_type(jid))
except couchbase.exceptions.NotFoundError:
cb_.add(six.text_type(jid), {}, ttl=_get_ttl())
jid_doc = cb_.get(six.text_type(jid))
jid_doc.value[] = clear_load
... | Save the load to the specified jid |
376,038 | def stats_for(self, dt):
if not isinstance(dt, datetime):
raise TypeError()
return self._client.get(.format(dt.strftime())) | Returns stats for the month containing the given datetime |
376,039 | def status(self):
rd = self.repo_dir
logger.debug("pkg path %s", rd)
if not rd:
print(
"unable to find pkg . %s" % (self.name, did_u_mean(self.name))
)
cwd = os.getcwd()
os.chdir(self.repo_dir)
logger.debug("cwd: %s, get... | Get status on the repo.
:return:
:rtype: |
376,040 | def age(self, as_at_date=None):
if self.date_of_death != None or self.is_deceased == True:
return None
as_at_date = date.today() if as_at_date == None else as_at_date
if self.date_of_birth != None:
if (as_at_date.month >= self.date_of_birth.month) and (... | Compute the person's age |
376,041 | def enhancer(self):
if self._enhancer is None:
self._enhancer = Enhancer(ppp_config_dir=self.ppp_config_dir)
return self._enhancer | Lazy loading of enhancements only if needed. |
376,042 | def files_rm(self, path, recursive=False, **kwargs):
kwargs.setdefault("opts", {"recursive": recursive})
args = (path,)
return self._client.request(, args, **kwargs) | Removes a file from the MFS.
.. code-block:: python
>>> c.files_rm("/bla/file")
b''
Parameters
----------
path : str
Filepath within the MFS
recursive : bool
Recursively remove directories? |
376,043 | def moveCursor(self, cursorAction, modifiers):
if cursorAction not in (self.MoveNext,
self.MoveRight,
self.MovePrevious,
self.MoveLeft,
self.MoveHome,
... | Returns a QModelIndex object pointing to the next object in the
view, based on the given cursorAction and keyboard modifiers
specified by modifiers.
:param modifiers | <QtCore.Qt.KeyboardModifiers> |
376,044 | def empty(self, duration):
ann = super(DynamicLabelTransformer, self).empty(duration)
ann.append(time=0, duration=duration, value=None)
return ann | Empty label annotations.
Constructs a single observation with an empty value (None).
Parameters
----------
duration : number > 0
The duration of the annotation |
376,045 | def edit_section(self, id, course_section_end_at=None, course_section_name=None, course_section_restrict_enrollments_to_section_dates=None, course_section_sis_section_id=None, course_section_start_at=None):
path = {}
data = {}
params = {}
path["id"] = i... | Edit a section.
Modify an existing section. |
376,046 | def str_variants(institute_id, case_name):
page = int(request.args.get(, 1))
variant_type = request.args.get(, )
form = StrFiltersForm(request.args)
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
query = form.data
query[] = variant_type
variants_query =... | Display a list of STR variants. |
376,047 | def run_outdated(cls, options):
latest_versions = sorted(
cls.find_packages_latest_versions(cls.options),
key=lambda p: p[0].project_name.lower())
for dist, latest_version, typ in latest_versions:
if latest_version > dist.parsed_version:
if o... | Print outdated user packages. |
376,048 | def getRastersAsPngs(self, session, tableName, rasterIds, postGisRampString, rasterField=, rasterIdField=, cellSize=None, resampleMethod=):
VALID_RESAMPLE_METHODS = (, , , , )
if resampleMethod not in VALID_RESAMPLE_METHODS:
print(
.format(resam... | Return the raster in a PNG format |
376,049 | def _dataflash_dir(self, mpstate):
if mpstate.settings.state_basedir is None:
ret =
else:
ret = os.path.join(mpstate.settings.state_basedir,)
try:
os.makedirs(ret)
except OSError as e:
if e.errno != errno.EEXIST:
... | returns directory path to store DF logs in. May be relative |
376,050 | def plot_isotherm(self, T, Pmin=None, Pmax=None, methods_P=[], pts=50,
only_valid=True):
r
if not has_matplotlib:
raise Exception()
if Pmin is None:
if self.Pmin is not None:
Pmin = self.Pmin
else:
... | r'''Method to create a plot of the property vs pressure at a specified
temperature according to either a specified list of methods, or the
user methods (if set), or all methods. User-selectable number of
points, and pressure range. If only_valid is set,
`test_method_validity_P` will be... |
376,051 | def expect(self, *args):
integer64t match, raise a ConfigParseError.
'
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,)) | Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError. |
376,052 | def page(self, attr=None, fill=u):
u
if attr is None:
attr = self.attr
if len(fill) != 1:
raise ValueError
info = CONSOLE_SCREEN_BUFFER_INFO()
self.GetConsoleScreenBufferInfo(self.hout, byref(info))
if info.dwCursorPosition.X != 0 or info.d... | u'''Fill the entire screen. |
376,053 | def _scheduleMePlease(self):
sched = IScheduler(self.store)
if len(list(sched.scheduledTimes(self))) == 0:
sched.schedule(self, sched.now()) | This queue needs to have its run() method invoked at some point in the
future. Tell the dependent scheduler to schedule it if it isn't
already pending execution. |
376,054 | def lock_file(path):
with _paths_lock:
lock = _paths_to_locks.get(path)
if lock is None:
_paths_to_locks[path] = lock = _FileLock(path)
return lock | File based lock on ``path``.
Creates a file based lock. When acquired, other processes or threads are
prevented from acquiring the same lock until it is released. |
376,055 | def interface_by_ipaddr(self, ipaddr):
owns
ipaddr = IPAddr(ipaddr)
for devname,iface in self._devinfo.items():
if iface.ipaddr == ipaddr:
return iface
raise KeyError("No device has IP address {}".format(ipaddr)) | Given an IP address, return the interface that 'owns' this address |
376,056 | def kwargs_to_variable_assignment(kwargs: dict, value_representation=repr,
assignment_operator: str = ,
statement_separator: str = ,
statement_per_line: bool = False) -> str:
code = []
join_str = if state... | Convert a dictionary into a string with assignments
Each assignment is constructed based on:
key assignment_operator value_representation(value) statement_separator,
where key and value are the key and value of the dictionary.
Moreover one can seprate the assignment statements by new lines.
Parame... |
376,057 | def params_size(m: Union[nn.Module,Learner], size: tuple = (3, 64, 64))->Tuple[Sizes, Tensor, Hooks]:
"Pass a dummy input through the model to get the various sizes. Returns (res,x,hooks) if `full`"
if isinstance(m, Learner):
if m.data.is_empty:
raise Exception("This is an empty `Learner` an... | Pass a dummy input through the model to get the various sizes. Returns (res,x,hooks) if `full` |
376,058 | def set_inbound_cipher(
self, block_engine, block_size, mac_engine, mac_size, mac_key
):
self.__block_engine_in = block_engine
self.__block_size_in = block_size
self.__mac_engine_in = mac_engine
self.__mac_size_in = mac_size
self.__mac_key_in = mac_key
... | Switch inbound data cipher. |
376,059 | def comments(self):
if self.cache[]: return self.cache[]
comments = []
for message in self.messages[0:3]:
comment_xml = self.bc.comments(message.id)
for comment_node in ET.fromstring(comment_xml).findall("comment"):
comments.append(Comment(comment... | Looks through the last 3 messages and returns those comments. |
376,060 | def get_children(self):
def visitor(child, parent, children):
assert child != conf.lib.clang_getNullCursor()
child._tu = self._tu
children.append(child)
return 1
children = []
conf.lib.cla... | Return an iterator for accessing the children of this cursor. |
376,061 | async def service_messages(self, msg, _context):
msgs = self.service_manager.service_messages(msg.get())
return [x.to_dict() for x in msgs] | Get all messages for a service. |
376,062 | def astype(array, y):
if isinstance(y, autograd.core.Node):
return array.astype(numpy.array(y.value).dtype)
return array.astype(numpy.array(y).dtype) | A functional form of the `astype` method.
Args:
array: The array or number to cast.
y: An array or number, as the input, whose type should be that of array.
Returns:
An array or number with the same dtype as `y`. |
376,063 | def ar_periodogram(x, window=, window_len=7):
x_lag = x[:-1]
X = np.array([np.ones(len(x_lag)), x_lag]).T
y = np.array(x[1:])
beta_hat = np.linalg.solve(X.T @ X, X.T @ y)
e_hat = y - X @ beta_hat
phi = beta_hat[1]
w, I_w = periodogram(e_hat, window=window, windo... | Compute periodogram from data x, using prewhitening, smoothing and
recoloring. The data is fitted to an AR(1) model for prewhitening,
and the residuals are used to compute a first-pass periodogram with
smoothing. The fitted coefficients are then used for recoloring.
Parameters
----------
x : ... |
376,064 | def validate(self, config):
if not isinstance(config, ConfigObject):
raise Exception("Config object expected")
if config["output"]["componants"] not in ("local", "remote", "embedded", "without"):
raise ValueError("Unknown componant \"%s\"." % config["output"]["componant... | Validate that the source file is ok |
376,065 | def handle_data(self, data):
self.days += 1
signals = {}
self.orderbook = {}
if self.initialized and self.manager:
self.manager.update(
self.portfolio,
self.datetime,
self.perf_tracker.cumulative_... | Method called for each event by zipline. In intuition this is the
place to factorize algorithms and then call event() |
376,066 | def set_os_environ(variables_mapping):
for variable in variables_mapping:
os.environ[variable] = variables_mapping[variable]
logger.log_debug("Set OS environment variable: {}".format(variable)) | set variables mapping to os.environ |
376,067 | def bcesp(y1,y1err,y2,y2err,cerr,nsim=10000):
import time
import multiprocessing
print "BCES,", nsim,"trials... ",
tic=time.time()
ncores=multiprocessing.cpu_count()
n=2*ncores
pargs=[]
for i in range(n):
pargs.append([y1,y1err,y2,y2err,cerr,nsim/n])
pool = multiprocessing.Pool(processes... | Parallel implementation of the BCES with bootstrapping.
Divide the bootstraps equally among the threads (cores) of
the machine. It will automatically detect the number of
cores available.
Usage:
>>> a,b,aerr,berr,covab=bcesp(x,xerr,y,yerr,cov,nsim)
:param x,y: data
:param xerr,yerr: measurement errors affecting x an... |
376,068 | def ready_to_draw(mol):
copied = molutil.clone(mol)
equalize_terminal_double_bond(copied)
scale_and_center(copied)
format_ring_double_bond(copied)
return copied | Shortcut function to prepare molecule to draw.
Overwrite this function for customized appearance.
It is recommended to clone the molecule before draw
because all the methods above are destructive. |
376,069 | def instance(cls, size):
if not getattr(cls, "_instance", None):
cls._instance = {}
if size not in cls._instance:
cls._instance[size] = ThreadPool(size)
return cls._instance[size] | Cache threadpool since context is
recreated for each request |
376,070 | def mkIntDate(s):
n = s.__len__()
d = int(s[-(n - 1):n])
return d | Convert the webserver formatted dates
to an integer format by stripping the
leading char and casting |
376,071 | async def set_agent_neighbors(self):
for addr in self.addrs:
r_manager = await self.env.connect(addr)
await r_manager.set_agent_neighbors() | Set neighbors for all the agents in all the slave environments.
Assumes that all the slave environments have their neighbors set. |
376,072 | def compile_config(path,
source=None,
config_name=None,
config_data=None,
config_data_source=None,
script_parameters=None,
salt_env=):
rbase**
if source:
log.info(, source)
cached_fi... | r'''
Compile a config from a PowerShell script (``.ps1``)
Args:
path (str): Path (local) to the script that will create the ``.mof``
configuration file. If no source is passed, the file must exist
locally. Required.
source (str): Path to the script on ``file_roots`` to... |
376,073 | def getMeanInpCurrents(params, numunits=100,
filepattern=os.path.join(,
)):
x = np.arange(100) * params.dt
kernel = np.exp(-x / params.model_params[])
K_bg = np.array(sum(params.K_bg, []))
}
... | return a dict with the per population mean and std synaptic current,
averaging over numcells recorded units from each population in the
network
Returned currents are in unit of nA. |
376,074 | def make_path(*args):
paths = unpack_args(*args)
return os.path.abspath(os.path.join(*[p for p in paths if p is not None])) | >>> _hack_make_path_doctest_output(make_path("/a", "b"))
'/a/b'
>>> _hack_make_path_doctest_output(make_path(["/a", "b"]))
'/a/b'
>>> _hack_make_path_doctest_output(make_path(*["/a", "b"]))
'/a/b'
>>> _hack_make_path_doctest_output(make_path("/a"))
'/a'
>>> _hack_make_path_doctest_output... |
376,075 | def flatten(value):
if isinstance(value, np.ndarray):
def unflatten(vector):
return np.reshape(vector, value.shape)
return np.ravel(value), unflatten
elif isinstance(value, float):
return np.array([value]), lambda x: x[0]
elif isinstance(value, tuple):
if n... | value can be any nesting of tuples, arrays, dicts.
returns 1D numpy array and an unflatten function. |
376,076 | def parse_table_data(lines):
data = "\n".join([i.rstrip() for i in lines
if not i.startswith(("^", "!", "
if data:
return read_csv(StringIO(data), index_col=None, sep="\t")
else:
return DataFrame() | Parse list of lines from SOFT file into DataFrame.
Args:
lines (:obj:`Iterable`): Iterator over the lines.
Returns:
:obj:`pandas.DataFrame`: Table data. |
376,077 | def parse(self, text, *, metadata=None, filename="input"):
metadata = metadata or {}
body = []
in_metadata = True
line_number = None
def throw(s):
raise BlurbError(f("Error in {filename}:{line_number}:\n{s}"))
def finish_entry():
nonlo... | Parses a string. Appends a list of blurb ENTRIES to self, as tuples:
(metadata, body)
metadata is a dict. body is a string. |
376,078 | def _compute_bounds(self, axis, view):
is_vertical = self._is_vertical
pos = self._pos
if axis == 0 and is_vertical:
return (pos[0, 0], pos[0, 0])
elif axis == 1 and not is_vertical:
return (self._pos[0, 1], self._pos[0, 1])
return None | Return the (min, max) bounding values of this visual along *axis*
in the local coordinate system. |
376,079 | def parseFloat(self, words):
def pointFloat(words):
m = re.search(r, words)
if m:
whole = m.group(1)
frac = m.group(2)
total = 0.0
coeff = 0.10
for digit in frac.split():
total +=... | Convert a floating-point number described in words to a double.
Supports two kinds of descriptions: those with a 'point' (e.g.,
"one point two five") and those with a fraction (e.g., "one and
a quarter").
Args:
words (str): Description of the floating-point number.
... |
376,080 | def density_und(CIJ):
n = len(CIJ)
k = np.size(np.where(np.triu(CIJ).flatten()))
kden = k / ((n * n - n) / 2)
return kden, n, k | Density is the fraction of present connections to possible connections.
Parameters
----------
CIJ : NxN np.ndarray
undirected (weighted/binary) connection matrix
Returns
-------
kden : float
density
N : int
number of vertices
k : int
number of edges
... |
376,081 | def dutyCycle(self, active=False, readOnly=False):
if self.tm.lrnIterationIdx <= self.dutyCycleTiers[1]:
dutyCycle = float(self.positiveActivations) \
/ self.tm.lrnIterationIdx
if not readOnly:
self._lastPosDutyCycleIteration = self.tm.lrnIterationId... | Compute/update and return the positive activations duty cycle of
this segment. This is a measure of how often this segment is
providing good predictions.
:param active True if segment just provided a good prediction
:param readOnly If True, compute the updated duty cycle, but don't change
... |
376,082 | def from_http(cls, headers: Mapping[str, str]) -> Optional["RateLimit"]:
try:
limit = int(headers["x-ratelimit-limit"])
remaining = int(headers["x-ratelimit-remaining"])
reset_epoch = float(headers["x-ratelimit-reset"])
except KeyError:
return Non... | Gather rate limit information from HTTP headers.
The mapping providing the headers is expected to support lowercase
keys. Returns ``None`` if ratelimit info is not found in the headers. |
376,083 | def set_file_paths(self, new_file_paths):
self._file_paths = new_file_paths
self._file_path_queue = [x for x in self._file_path_queue
if x in new_file_paths]
filtered_processors = {}
for file_path, processor in self._processors.items():
... | Update this with a new set of paths to DAG definition files.
:param new_file_paths: list of paths to DAG definition files
:type new_file_paths: list[unicode]
:return: None |
376,084 | def send_result(self, return_code, output, service_description=, time_stamp=0, specific_servers=None):
if time_stamp == 0:
time_stamp = int(time.time())
if specific_servers == None:
specific_servers = self.servers
else:
specific_servers = set(self.se... | Send result to the Skinken WS |
376,085 | def joint_sfs_scaled(dac1, dac2, n1=None, n2=None):
s = joint_sfs(dac1, dac2, n1=n1, n2=n2)
s = scale_joint_sfs(s)
return s | Compute the joint site frequency spectrum between two populations,
scaled such that a constant value is expected across the spectrum for
neutral variation, constant population size and unrelated populations.
Parameters
----------
dac1 : array_like, int, shape (n_variants,)
Derived allele co... |
376,086 | def get_resources_strings(self):
resources_strings = list()
if hasattr(self, ):
for resource_type in self.DIRECTORY_ENTRY_RESOURCE.entries:
if hasattr(resource_type, ):
for resource_id in resource_type.directory.entr... | Returns a list of all the strings found withing the resources (if any).
This method will scan all entries in the resources directory of the PE, if
there is one, and will return a list() with the strings.
An empty list will be returned otherwise. |
376,087 | def get_last_live_chat(self):
now = datetime.now()
lcqs = self.get_query_set()
lcqs = lcqs.filter(
chat_ends_at__lte=now,
).order_by()
for itm in lcqs:
if itm.chat_ends_at + timedelta(days=3) > now:
return itm
return N... | Check if there is a live chat that ended in the last 3 days, and
return it. We will display a link to it on the articles page. |
376,088 | def _xr_to_keyset(line):
tkns = [elm for elm in line.strip().split(":", 1) if elm]
if len(tkns) == 1:
return ": ".format(tkns[0])
else:
key, val = tkns
return ": ,".format(key.strip(), val.strip()) | Parse xfsrestore output keyset elements. |
376,089 | def yum_install(self, packages, ignore_error=False):
return self.run( + .join(packages), ignore_error=ignore_error, retry=5) | Install some packages on the remote host.
:param packages: ist of packages to install. |
376,090 | def get_publish_path(self, obj):
return os.path.join(
obj.chat_type.publish_path, obj.publish_path.lstrip("/")
) | publish_path joins the publish_paths for the chat type and the channel. |
376,091 | def _CCompiler_spawn_silent(cmd, dry_run=None):
proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
if proc.returncode:
raise DistutilsExecError(err) | Spawn a process, and eat the stdio. |
376,092 | def get_multi_generation(self, tables, db=):
generations = []
for table in tables:
generations.append(self.get_single_generation(table, db))
key = self.keygen.gen_multi_key(generations, db)
val = self.cache_backend.get(key, None, db)
if val is None:
... | Takes a list of table names and returns an aggregate
value for the generation |
376,093 | def create_chapter_from_string(self, html_string, url=None, title=None):
clean_html_string = self.clean_function(html_string)
clean_xhtml_string = clean.html_to_xhtml(clean_html_string)
if title:
pass
else:
try:
root = BeautifulSoup(html_s... | Creates a Chapter object from a string. Sanitizes the
string using the clean_function method, and saves
it as the content of the created chapter.
Args:
html_string (string): The html or xhtml content of the created
Chapter
url (Option[string]): A url to i... |
376,094 | def prepare(cls):
if cls._ask_openapi():
napp_path = Path()
tpl_path = SKEL_PATH /
OpenAPI(napp_path, tpl_path).render_template()
print()
sys.exit() | Prepare NApp to be uploaded by creating openAPI skeleton. |
376,095 | def _set_default_configs(user_settings, default):
for key in default:
if key not in user_settings:
user_settings[key] = default[key]
return user_settings | Set the default value to user settings if user not specified
the value. |
376,096 | def remove(self, document_id, namespace, timestamp):
index, doc_type = self._index_and_mapping(namespace)
action = {
: ,
: index,
: doc_type,
: u(document_id)
}
meta_action = {
: ,
: self.meta_index_name,
... | Remove a document from Elasticsearch. |
376,097 | def run_actions(self, actions):
policy = self._policy
for action in actions:
config_id = action.config_id
config_type = config_id.config_type
client_config = policy.clients[action.client_name]
client = client_config.get_client()
c_map ... | Runs the given lists of attached actions and instance actions on the client.
:param actions: Actions to apply.
:type actions: list[dockermap.map.action.ItemAction]
:return: Where the result is not ``None``, returns the output from the client. Note that this is a generator
and needs to... |
376,098 | def perspective(fovy, aspect, znear, zfar):
assert(znear != zfar)
h = math.tan(fovy / 360.0 * math.pi) * znear
w = h * aspect
return frustum(-w, w, -h, h, znear, zfar) | Create perspective projection matrix
Parameters
----------
fovy : float
The field of view along the y axis.
aspect : float
Aspect ratio of the view.
znear : float
Near coordinate of the field of view.
zfar : float
Far coordinate of the field of view.
Returns... |
376,099 | def tri_area(self, lons, lats):
lons, lats = self._check_integrity(lons, lats)
x, y, z = _stripack.trans(lats, lons)
area = _stripack.areas(x, y, z)
return area | Calculate the area enclosed by 3 points on the unit sphere.
Parameters
----------
lons : array of floats, shape (3)
longitudinal coordinates in radians
lats : array of floats, shape (3)
latitudinal coordinates in radians
Returns
-------
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.