Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
348,400 | def result(self, timeout=None):
if self._done_event.wait(timeout) or self._done_event.is_set():
if self._exception is not None:
raise self._exception
return self._result
raise OSError("Timeout raised") | Waits up to timeout for the result the threaded job.
Returns immediately the result if the job has already been done.
:param timeout: The maximum time to wait for a result (in seconds)
:raise OSError: The timeout raised before the job finished
:raise Exception: Raises the exception that... |
348,401 | def CirrusIamUserReady(iam_aws_id, iam_aws_secret):
is_ready = False
try:
s3 = core.CreateTestedS3Connection(iam_aws_id, iam_aws_secret)
if s3:
if core.CirrusAccessIdMetadata(s3, iam_aws_id).IsInitialized():
is_ready = True
except boto.exception.BotoServerError as e:
print... | Returns true if provided IAM credentials are ready to use. |
348,402 | def data_frame_to_astropy_table (dataframe):
from astropy.utils import OrderedDict
from astropy.table import Table, Column, MaskedColumn
from astropy.extern import six
out = OrderedDict()
for name in dataframe.columns:
column = dataframe[name]
mask = np.array (column.isnull ()... | This is a backport of the Astropy method
:meth:`astropy.table.table.Table.from_pandas`. It converts a Pandas
:class:`pandas.DataFrame` object to an Astropy
:class:`astropy.table.Table`. |
348,403 | def save_metadata_json(self, filename: str, structure: JsonExportable) -> None:
if self.compress_json:
filename +=
else:
filename +=
save_structure_to_file(structure, filename)
if isinstance(structure, (Post, StoryItem)):
self.c... | Saves metadata JSON file of a structure. |
348,404 | def rows_for_firmwares(self, firmwares):
rows = []
i = 0
for firmware in firmwares:
frame = self.frame_from_firmware(firmware)
row = {
"seq": i,
"platform": firmware["platform"],
"frame": frame,
"re... | provide user-readable text for a firmware entry |
348,405 | def _selection_for_character(self, position):
selection = QtGui.QTextEdit.ExtraSelection()
cursor = self._text_edit.textCursor()
cursor.setPosition(position)
cursor.movePosition(QtGui.QTextCursor.NextCharacter,
QtGui.QTextCursor.KeepAnchor)
se... | Convenience method for selecting a character. |
348,406 | def list_all_coupons(cls, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._list_all_coupons_with_http_info(**kwargs)
else:
(data) = cls._list_all_coupons_with_http_info(**kwargs)
return data | List Coupons
Return a list of Coupons
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_coupons(async=True)
>>> result = thread.get()
:param async bool
:param int page:... |
348,407 | def followers(self, blogname, **kwargs):
url = "/v2/blog/{}/followers".format(blogname)
return self.send_api_request("get", url, kwargs, [, ]) | Gets the followers of the given blog
:param limit: an int, the number of followers you want returned
:param offset: an int, the follower to start at, for pagination.
# Start at the 20th blog and get 20 more blogs.
client.followers({'offset': 20, 'limit': 20})
:returns: ... |
348,408 | def _wrap_decorator(decorator, targets, is_valid_target):
@functools.wraps(decorator)
def wrapper(*args, **kwargs):
one_arg = len(args) == 1 and not kwargs
if one_arg and is_valid_target(args[0]):
actual_decorator = decorator()
return actual_decorat... | Wraps given decorator in order to provide additional functionality:
optional arguments and verification of decorator's target type.
:param decorator: Decorator callable
:param targets: Name of the decorator targets, as plural
(used in error messages)
:param is_valid_target: Callable... |
348,409 | def load_csv(self, url, **kwargs):
self.start("Loading csv...")
try:
if self.datapath is not None and url.startswith("/") is False:
url = self.datapath + "/" + url
df = pd.read_csv(url, **kwargs)
self.df = df
except FileNotFoundError:
... | Loads csv data in the main dataframe
:param url: url of the csv file to load:
can be absolute if it starts with ``/``
or relative if it starts with ``./``
:type url: str
:param kwargs: keyword arguments to pass to Pandas
... |
348,410 | def main():
args = getArguments()
try:
if args.action == :
while True:
print % args.basePath,
text = raw_input()
if text.lower() == :
print
return 1
elif text.lower() =... | The main entry |
348,411 | def as_json_dict(self):
data = {}
for key, value in self.__dict__.items():
camel_key = utils.to_camel_case(key)
if isinstance(value, (list, tuple, set)):
data[camel_key] = list()
for item in value:
if hasattr(item, ):
... | Return dictionary from this object.
:return: dict |
348,412 | def _dataframe_to_vertex_list(df):
cols = df.columns
if len(cols):
assert _VID_COLUMN in cols, "Vertex DataFrame must contain column %s" % _VID_COLUMN
df = df[cols].T
ret = [Vertex(None, _series=df[col]) for col in df]
return ret
else:
return [] | Convert dataframe into list of vertices, assuming that vertex ids are stored in _VID_COLUMN. |
348,413 | def inject(self, contents=None, **kwargs):
if contents and not isinstance(contents, dict):
raise WrongContentError(self, contents, "contents should be a dict")
self._stable = False
if not contents:
contents = {}
if kwargs:
contents.update(kwar... | Adds content data in this element. This will be used in the rendering of this element's childs.
Multiple injections on the same key will override the content (dict.update behavior). |
348,414 | def validate_args(fname, args, max_fname_arg_count, compat_args):
_check_arg_length(fname, args, max_fname_arg_count, compat_args)
kwargs = dict(zip(compat_args, args))
_check_for_default_values(fname, kwargs, compat_args) | Checks whether the length of the `*args` argument passed into a function
has at most `len(compat_args)` arguments and whether or not all of these
elements in `args` are set to their default values.
fname: str
The name of the function being passed the `*args` parameter
args: tuple
The `... |
348,415 | def printUnusedImports(self):
for module in self.listModules():
names = [(unused.lineno, unused.name)
for unused in module.unused_names]
names.sort()
for lineno, name in names:
if not self.all_unused:
line = li... | Produce a report of unused imports. |
348,416 | def rm(self, line):
self.log(.format(line))
if line is False:
return False
if isinstance(line, str):
line = line.split()
if not isinstance(line, list):
raise TypeError("Parameter not a or , is {0}".format(type(line)))
local_changes =... | Remove all occurrences of 'line' from contents
where 'line' is an entire line or a list of lines.
Return true if the file was changed by rm(), False otherwise.
Multi-line strings are converted to a list delimited by new lines.
:param line: String, or List of Strings; each string r... |
348,417 | def register_class(self, instance, name=None):
prefix_name = name or instance.__class__.__name__
for e in dir(instance):
if e[0][0] != "_":
self.register_function(
getattr(instance, e),
name="%s.%s" % (prefix_name, e)
... | Add all functions of a class-instance to the RPC-services.
All entries of the instance which do not begin with '_' are added.
:Parameters:
- myinst: class-instance containing the functions
- name: | hierarchical prefix.
| If omitted, the functions are ad... |
348,418 | def element(self, inp=None):
if inp is None:
return self.elements[0]
elif inp in self.elements:
return inp
else:
raise ValueError(
.format(inp, self)) | Create a new element.
For more specific control, use set[i].element() to pick which subset to
use. |
348,419 | def convert_args(args, kwargs):
found = False
for arg in args:
if isinstance(arg, Cells):
found = True
break
if found:
args = tuple(
arg.value if isinstance(arg, Cells) else arg for arg in args
)
if kwargs is not None:
for key, ... | If args and kwargs contains Cells, Convert them to their values. |
348,420 | def reformat_pattern(pattern, compile=False):
rex_pattern = re.sub(r, , pattern)
rex_pattern = re.sub(r, , rex_pattern)
rex_pattern = re.sub(r, , rex_pattern)
rex_pattern = re.sub(r, , rex_pattern)
rex_pattern = re.sub(r,
,
... | Apply the filters on user pattern to generate a new regular expression
pattern.
A user provided variable, should start with an alphabet, can be
alphanumeric and can have _. |
348,421 | def create_pool(
database,
minsize=1,
maxsize=10,
echo=False,
loop=None,
**kwargs
):
coro = _create_pool(
database=database,
minsize=minsize,
maxsize=maxsize,
echo=echo,
loop=loop,
**kwargs
)
return _PoolCon... | 创建支持上下文管理的pool |
348,422 | def _CheckIsLink(self, file_entry):
if definitions.FILE_ENTRY_TYPE_LINK not in self._file_entry_types:
return False
return file_entry.IsLink() | Checks the is_link find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not. |
348,423 | def stagger(iterable, offsets=(-1, 0, 1), longest=False, fillvalue=None):
children = tee(iterable, len(offsets))
return zip_offset(
*children, offsets=offsets, longest=longest, fillvalue=fillvalue
) | Yield tuples whose elements are offset from *iterable*.
The amount by which the `i`-th item in each tuple is offset is given by
the `i`-th item in *offsets*.
>>> list(stagger([0, 1, 2, 3]))
[(None, 0, 1), (0, 1, 2), (1, 2, 3)]
>>> list(stagger(range(8), offsets=(0, 2, 4)))
[(0, ... |
348,424 | def register_listener(self, member_uuid, listener):
member_uuid = str(member_uuid)
if member_uuid not in self._casts:
self._casts[member_uuid] = {: [],
: set()}
self._casts[member_uuid][].append(listener) | Register a listener for audio group changes of cast uuid.
On update will call:
listener.added_to_multizone(group_uuid)
The cast has been added to group uuid
listener.removed_from_multizone(group_uuid)
The cast has been removed from group uuid
... |
348,425 | def iterconfig(config, scan_type):
if scan_type in config:
for modality,scans in iter(config[scan_type].items()):
for scan in scans:
scan.update({
: scan_type,
: modality
})
yield scan | Iterate over BIDS configuration file |
348,426 | def is_http_running_on(port):
try:
conn = httplib.HTTPConnection( + str(port))
conn.connect()
conn.close()
return True
except Exception:
return False | Check if an http server runs on a given port.
Args:
The port to check.
Returns:
True if it is used by an http server. False otherwise. |
348,427 | def _github_create_twofactor_authorization(cls, ui):
try:
try:
auth = cls._user.create_authorization()
except cls._gh_exceptions.GithubException:
onetime_pw = DialogHelper.ask_for_password(ui, prompt=)
auth = cls._user.create_auth... | Create an authorization for a GitHub user using two-factor
authentication. Unlike its non-two-factor counterpart, this method
does not traverse the available authentications as they are not
visible until the user logs in.
Please note: cls._user's attributes are not accessibl... |
348,428 | def enable_aliases_autocomplete(_, **kwargs):
external_completions = kwargs.get(, [])
prefix = kwargs.get(, [])
cur_commands = kwargs.get(, [])
alias_table = get_alias_table()
_transform_cur_commands(cur_commands, alias_table=alias_table)
for alias, alias_command in filter_aliase... | Enable aliases autocomplete by injecting aliases into Azure CLI tab completion list. |
348,429 | def group_members_remove(self, device_group_id, body, **kwargs):
kwargs[] = True
if kwargs.get():
return self.group_members_remove_with_http_info(device_group_id, body, **kwargs)
else:
(data) = self.group_members_remove_with_http_info(device_group_id, body, *... | Remove a device from a group # noqa: E501
Remove one device from a group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.group_members_remove(device_group_id, body, asynchronous=... |
348,430 | def xpathCmpNodes(self, node2):
if node2 is None: node2__o = None
else: node2__o = node2._o
ret = libxml2mod.xmlXPathCmpNodes(self._o, node2__o)
return ret | Compare two nodes w.r.t document order |
348,431 | def class_balance(y_train, y_test=None, ax=None, labels=None, **kwargs):
visualizer = ClassBalance(ax=ax, labels=labels, **kwargs)
visualizer.fit(y_train, y_test)
visualizer.finalize()
return visualizer.ax | Quick method:
One of the biggest challenges for classification models is an imbalance of
classes in the training data. This function vizualizes the relationship of
the support for each class in both the training and test data by
displaying how frequently each class occurs as a bar graph.
The figur... |
348,432 | def match_in_args_kwargs(self, match_args, args, kwargs, allow_star_args=False):
req_len = 0
arg_checks = {}
to_match = []
for i, arg in enumerate(match_args):
if isinstance(arg, tuple):
(match, default) = arg
else:
match... | Matches against args or kwargs. |
348,433 | def load_noise_map(noise_map_path, noise_map_hdu, pixel_scale, image, background_noise_map, exposure_time_map,
convert_noise_map_from_weight_map, convert_noise_map_from_inverse_noise_map,
noise_map_from_image_and_background_noise_map, convert_from_electrons, gain, convert_from_adus... | Factory for loading the noise-map from a .fits file.
This factory also includes a number of routines for converting the noise-map from from other units (e.g. \
a weight map) or computing the noise-map from other unblurred_image_1d (e.g. the ccd image and background noise-map).
Parameters
----------
... |
348,434 | def frame(y, frame_length=2048, hop_length=512):
if not isinstance(y, np.ndarray):
raise ParameterError(
.format(type(y)))
if y.ndim != 1:
raise ParameterError(
.format(y.ndim))
if len(y) < frame_length:
raise Paramete... | Slice a time series into overlapping frames.
This implementation uses low-level stride manipulation to avoid
redundant copies of the time series data.
Parameters
----------
y : np.ndarray [shape=(n,)]
Time series to frame. Must be one-dimensional and contiguous
in memory.
fram... |
348,435 | async def destroy_async(self):
for _, link in self._mgmt_links.items():
await link.destroy_async()
self._session.destroy() | Asynchronously close any open management Links and close the Session.
Cleans up and C objects for both mgmt Links and Session. |
348,436 | def end(self):
pids_to_kill = self.get_all_pids()
if len(pids_to_kill) > 0:
this_process = psutil.Process(os.getpid())
except psutil.TimeoutExpired:
self.log.debug("Ran out of time while waiting for processes to exit")
... | Kill all child processes on exit since we don't want to leave
them as orphaned. |
348,437 | def assortativity_indicators(user):
matrix = matrix_undirected_unweighted(user)
count_indicator = defaultdict(int)
total_indicator = defaultdict(int)
ego_indics = all(user, flatten=True)
ego_indics = {a: value for a, value in ego_indics.items()
if a != "name" and a[:11... | Computes the assortativity of indicators.
This indicator measures the similarity of the current user with his
correspondants, for all bandicoot indicators. For each one, it calculates
the variance of the current user's value with the values for all his
correspondants:
.. math::
\\text{ass... |
348,438 | def dafrs(insum):
insum = stypes.toDoubleVector(insum)
libspice.dafrs_c(ctypes.byref(insum)) | Change the summary for the current array in the current DAF.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafrs_c.html
:param insum: New summary for current array.
:type insum: Array of floats |
348,439 | def requester(self):
if self.api and self.requester_id:
return self.api._get_user(self.requester_id) | | Comment: The id of the requester |
348,440 | def get_multiplicon_properties(self, value):
sql =
cur = self._dbconn.cursor()
cur.execute(sql, {: str(value)})
result = cur.fetchone()
cur.close()
return {: int(result[0]),
: int(result[1]) if len(result[1]) else None,
: int(resu... | Return a dictionary describing multiplicon data:
id, parent, level, number_of_anchorpoints, profile_length,
is_redundant and the contributing genome segments |
348,441 | def var(self, bias=False, *args, **kwargs):
nv.validate_window_func(, args, kwargs)
def f(arg):
return libwindow.ewmcov(arg, arg, self.com, int(self.adjust),
int(self.ignore_na), int(self.min_periods),
int(bias... | Exponential weighted moving variance. |
348,442 | def TeXLaTeXStrFunction(target = None, source= None, env=None):
if env.GetOption("no_exec"):
basedir = os.path.split(str(source[0]))[0]
abspath = os.path.abspath(basedir)
if is_LaTeX(source,env,abspath):
result = env.subst(,0,target,source)+" ..."
else:
... | A strfunction for TeX and LaTeX that scans the source file to
decide the "flavor" of the source and then returns the appropriate
command string. |
348,443 | def set_xlim_cb(self, redraw=True):
try:
xmin = float(self.w.x_lo.get_text())
except Exception:
set_min = True
else:
set_min = False
try:
xmax = float(self.w.x_hi.get_text())
except Exception:
set_max = True
... | Set plot limit based on user values. |
348,444 | def _close(self):
try:
self._file.flush()
except AttributeError:
pass
if self._own_file:
self._file.close() | Close the file if it was created by the writer.
If a buffer or file-like object was passed in, for example a GzipFile,
then leave this file open for the caller to close. In either case,
attempt to flush the file contents to ensure they are written to disk
(if supported) |
348,445 | def get_meta_references(self, datas):
rule = datas.get(RULE_META_REFERENCES, {})
if not rule:
msg = "Manifest lacks of or is empty"
raise SerializerError(msg.format(RULE_META_REFERENCES))
else:
if rule.get(, None):
names = rule.get()... | Get manifest enabled references declaration
This required declaration is readed from
``styleguide-metas-references`` rule that require either a ``--names``
or ``--auto`` variable, each one define the mode to enable reference:
Manually
Using ``--names`` which define a list o... |
348,446 | def t_END_FOR(self, t):
r"(?i)end[\s]+for"
t.endlexpos = t.lexpos + len(t.value)
return t | r"(?i)end[\s]+for |
348,447 | def get_as_type_with_default(self, key, value_type, default_value):
value = self.get(key)
return TypeConverter.to_type_with_default(value_type, value, default_value) | Converts map element into a value defined by specied typecode.
If conversion is not possible it returns default value.
:param key: an index of element to get.
:param value_type: the TypeCode that defined the type of the result
:param default_value: the default value
:return: ... |
348,448 | def set(self, key, value):
if not self.subsystem.is_cut:
super().set(key, value) | Only need to set if the subsystem is uncut.
Caches are only inherited from uncut subsystems. |
348,449 | def _check_y_exog(y, exog):
if y is not None:
y = column_or_1d(
check_array(y, ensure_2d=False, dtype=DTYPE, copy=True,
force_all_finite=False))
if exog is not None:
exog = check_array(exog, ensure_2d=True, dtype=DTYPE... | Validate input |
348,450 | def read_bin_particle_density(self):
config = []
self.cnxn.xfer([0x33])
sleep(10e-3)
for i in range(4):
resp = self.cnxn.xfer([0x00])[0]
config.append(resp)
bpd = self._calculate_float(config)
return bpd | Read the bin particle density
:returns: float |
348,451 | def oper(self, name, password):
with self.lock:
self.send( % (name, password))
snomasks =
new_umodes =
if self.readable():
msg = self._recv(expected_replies=( \
, , ))
... | Opers up.
Required arguments:
* name - Oper name.
* password - Oper password. |
348,452 | def createValidationDataSampler(dataset, ratio):
indices = np.random.permutation(len(dataset))
training_count = int(len(indices) * ratio)
train = torch.utils.data.SubsetRandomSampler(indices=indices[:training_count])
validate = torch.utils.data.SubsetRandomSampler(indices=indices[training_count:])
return (... | Create `torch.utils.data.Sampler`s used to split the dataset into 2 ramdom
sampled subsets. The first should used for training and the second for
validation.
:param dataset: A valid torch.utils.data.Dataset (i.e. torchvision.datasets.MNIST)
:param ratio: The percentage of the dataset to be used for training. T... |
348,453 | def VERSION(self):
return int(re.match(r, self.__class__.__name__).group(2)) | TAN mechanism version |
348,454 | def has_provider_support(provider, media_type):
if provider.lower() not in API_ALL:
return False
provider_const = "API_" + media_type.upper()
return provider in globals().get(provider_const, {}) | Verifies if API provider has support for requested media type |
348,455 | def build(self) -> Application:
pipelines = self._build_pipelines()
self._factory.new(, pipelines)
return self._factory[] | Put the application together. |
348,456 | def _construct_pillar(top_dir,
follow_dir_links,
keep_newline=False,
render_default=None,
renderer_blacklist=None,
renderer_whitelist=None,
template=False):
pillar = {}
render... | Construct pillar from file tree. |
348,457 | def move_parent_up(self):
cursor = self.nav.absolute_index
if cursor > 0:
level = max(self.content.get(cursor)[], 1)
while self.content.get(cursor - 1)[] >= level:
self._move_cursor(-1)
cursor -= 1
self._move_cursor(-1)
... | Move the cursor up to the comment's parent. If the comment is
top-level, jump to the previous top-level comment. |
348,458 | def resizeEvent(self, event):
value = self.config.value
self.idx_fig.fitInView(value[],
value[],
value[] - value[],
value[] - value[]) | Fit the whole scene in view.
Parameters
----------
event : instance of Qt.Event
not important |
348,459 | def summary(self, varnames=None, ranefs=False, transformed=False, hpd=.95,
quantiles=None, diagnostics=[, ]):
gelman_rubineffective_n
samples = self.to_df(varnames, ranefs, transformed)
df = pd.DataFrame({: samples.mean(0), : samples.std(0)})
if quant... | Returns a DataFrame of summary/diagnostic statistics for the parameters.
Args:
varnames (list): List of variable names to include; if None
(default), all eligible variables are included.
ranefs (bool): Whether or not to include random effects in the
summa... |
348,460 | def create_turtle(self, id, shape, model_init, color_init):
assert id not in self.id_to_shape
data = self._create_turtle(id, shape, model_init, color_init)
self.id_to_shape[id] = shape
return data | Create a slice of memory for turtle data storage |
348,461 | def comments(self):
return self.discussions.filter(Q(flags=None) | Q(
flags__flag=CommentFlag.MODERATOR_APPROVAL)) | Returns a queryset of the published comments. |
348,462 | def load_balancer_absent(name, resource_group, connection_auth=None):
ret = {
: name,
: False,
: ,
: {}
}
if not isinstance(connection_auth, dict):
ret[] =
return ret
load_bal = __salt__[](
name,
resource_group,
azurearm_log... | .. versionadded:: 2019.2.0
Ensure a load balancer does not exist in the resource group.
:param name:
Name of the load balancer.
:param resource_group:
The resource group assigned to the load balancer.
:param connection_auth:
A dict with subscription and authentication paramet... |
348,463 | def extract_dms (archive, compression, cmd, verbosity, interactive, outdir):
check_archive_ext(archive)
cmdlist = [cmd, , outdir]
if verbosity > 1:
cmdlist.append()
cmdlist.extend([, archive])
return cmdlist | Extract a DMS archive. |
348,464 | def sitesMatching(self, targets, matchCase, any_):
if not matchCase:
targets = set(map(str.lower, targets))
result = set() if any_ else None
for read in self:
sequence = read.sequence if matchCase else read.sequence.lower()
matches ... | Find sites (i.e., sequence indices) that match a given set of target
sequence bases.
@param targets: A C{set} of sequence bases to look for.
@param matchCase: If C{True}, case will be considered in matching.
@param any_: If C{True}, return sites that match in any read. Else
... |
348,465 | def _craft_s3_keys(self):
now = time.gmtime()
stub = "templates/{stack_name}/{version}".format(
stack_name=self._config.get(, {}).get(, None),
version=self._config.get()
)
stub = stub + "/" + str(now.tm_year)
stub = stub + "/" + str( % now.tm_mon... | We are putting stuff into S3, were supplied the bucket. Here we
craft the key of the elements we are putting up there in the
internet clouds.
Args:
None
Returns:
a tuple of teplate file key and property file key |
348,466 | def get_k8s_upgrades_completion_list(cmd, prefix, namespace, **kwargs):
resource_group = getattr(namespace, , None)
name = getattr(namespace, , None)
return get_k8s_upgrades(cmd.cli_ctx, resource_group, name) if resource_group and name else None | Return Kubernetes versions available for upgrading an existing cluster. |
348,467 | def select_scheme(self, name):
scheme = INSTALL_SCHEMES[name]
for key in SCHEME_KEYS:
attrname = + key
if getattr(self, attrname) is None:
setattr(self, attrname, scheme[key]) | Sets the install directories by applying the install schemes. |
348,468 | def check_xsrf_cookie(self) -> None:
token = (
self.get_argument("_xsrf", None)
or self.request.headers.get("X-Xsrftoken")
or self.request.headers.get("X-Csrftoken")
)
if not token:
rai... | Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.
To prevent cross-site request forgery, we set an ``_xsrf``
cookie and include the same value as a non-cookie
field with all ``POST`` requests. If the two do not match, we
reject the form submission as a potential forgery... |
348,469 | def get_driver(self, namespace, parsed_args, **kwargs):
option, dest = self._namespace_to_option(namespace)
dest_prefix = .format(dest)
driver_name = getattr(parsed_args, dest, )
driver_extension = self.driver_managers[namespace][driver_name]
return driver_extension.plug... | Get mutually-exlusive plugin for plugin namespace. |
348,470 | def build_connection(url):
username = os.environ.get()
password = os.environ.get()
if username and password:
return Elasticsearch(url, http_auth=(username, password))
return Elasticsearch(url) | Build an Elasticsearch connection with the given url
Elastic.co's Heroku addon doesn't create credientials with access to the
cluster by default so they aren't exposed in the URL they provide either.
This function works around the situation by grabbing our credentials from
the environment via Django se... |
348,471 | def on_okButton(self, event):
os.chdir(self.WD)
options_dict = {}
wd = self.WD
options_dict[] = wd
full_file = self.bSizer0.return_value()
if not full_file:
pw.simple_warning()
return False
input_directory, Utrecht_file = os.path.s... | Complies information input in GUI into a kwargs dictionary which can
be passed into the utrecht_magic script and run to output magic files |
348,472 | def get_locale_dict(self, text=None):
text = text or self.cat_locale()
return dict(re.findall(r\"]*([0-8a-zA-Z_\.\:\-]+)[\, text, re.MULTILINE)) | Reads /etc/default/locale and returns a dictionary representing its key pairs. |
348,473 | def skydir_to_pixel(self, skydir):
if self.coordsys in [, ]:
skydir = skydir.transform_to()
lon = skydir.ra.deg
lat = skydir.dec.deg
else:
skydir = skydir.transform_to()
lon = skydir.l.deg
lat = skydir.b.deg
return... | Return the pixel index of a SkyCoord object. |
348,474 | def method(dispatch_fn, dispatch_key=None):
def apply_decorator(fn):
if dispatch_key is None:
dispatch_fn.__multi_default__ = fn
else:
dispatch_fn.__multi__[dispatch_key] = fn
return fn
return apply_decorator | A decorator for a function implementing dispatch_fn for dispatch_key.
If no dispatch_key is specified, the function is used as the
default dispacth function. |
348,475 | def jac(x,a):
return (x-a) / np.sqrt(((x-a)**2).sum(1))[:,np.newaxis] | Jacobian matrix given Christophe's suggestion of f |
348,476 | def get_asset_form(self, *args, **kwargs):
if isinstance(args[-1], list) or in kwargs:
return self.get_asset_form_for_create(*args, **kwargs)
else:
return self.get_asset_form_for_update(*args, **kwargs) | Pass through to provider AssetAdminSession.get_asset_form_for_update |
348,477 | def feature_types(self, feature_types):
if not feature_types is None:
if self.feature_names is None:
msg =
raise ValueError(msg)
if isinstance(feature_types, STRING_TYPES):
feature_types = [feature_types] * self... | Set feature types (column types).
This is for displaying the results and unrelated
to the learning process.
Parameters
----------
feature_types : list or None
Labels for features. None will reset existing feature names |
348,478 | def get_pwm_list(pwm_id_list, pseudocountProb=0.0001):
l = load_motif_db(HOCOMOCO_PWM)
l = {k.split()[0]: v for k, v in l.items()}
pwm_list = [PWM(_normalize_pwm(l[m]) + pseudocountProb, name=m) for m in pwm_id_list]
return pwm_list | Get a list of HOCOMOCO PWM's.
# Arguments
pwm_id_list: List of id's from the `PWM_id` column in `get_metadata()` table
pseudocountProb: Added pseudocount probabilities to the PWM
# Returns
List of `concise.utils.pwm.PWM` instances. |
348,479 | def get_spectra_id(self, fn_id, retention_time=None, scan_nr=None):
cursor = self.get_cursor()
sql =
values = [fn_id]
if retention_time is not None:
sql = .format(sql)
values.append(retention_time)
if scan_nr is not None:
sql = .forma... | Returns spectra id for spectra filename and retention time |
348,480 | def getAnalysesUIDs(self):
analyses = self.getAnalyses()
if isinstance(analyses, list):
return [an.UID() for an in analyses]
return [] | Returns the analyses UIDs from the analyses assigned to this worksheet
:returns: a list of UIDs
:rtype: a list of strings |
348,481 | def add_document(self, document):
is passed to `requests.post
documents_url = urljoin(self.base_url, self.DOCUMENTS_PAGE)
data = {"corpus": self.url}
files = {"blob": document}
result = self.session.post(documents_url, data=data, files=files)
if result.status_code == 20... | Add a document to this corpus
`document' is passed to `requests.post', so it can be a file-like
object, a string (that will be sent as the file content) or a tuple
containing a filename followed by any of these two options. |
348,482 | def sanitize(self):
super(MapReferralMessage, self).sanitize()
if len(bytes(self.nonce)) != 8:
raise ValueError()
for record in s... | Check if the current settings conform to the LISP specifications and
fix them where possible. |
348,483 | def to_dataframe(network,
interaction=,
default_interaction=,
edges_attr_cols=[]):
edges = network[][]
if edges_attr_cols is None:
edges_attr_cols = []
edges_attr_cols = sorted(edges_attr_cols)
network_array = []
valid_extra_cols... | Utility to convert a Cytoscape dictionary into a Pandas Dataframe.
:param network: Dictionary to convert.
:param interaction: Name of interaction column.
:param default_interaction: Default value for missing interactions.
:param edges_attr_cols: List containing other edges' attributes to include
... |
348,484 | def transcript_to_gene(gtf):
gene_lookup = {}
for feature in complete_features(get_gtf_db(gtf)):
gene_id = feature.attributes.get(, [None])[0]
transcript_id = feature.attributes.get(, [None])[0]
gene_lookup[transcript_id] = gene_id
return gene_lookup | return a dictionary keyed by transcript_id of the associated gene_id |
348,485 | def callsign(msg):
if common.typecode(msg) < 1 or common.typecode(msg) > 4:
raise RuntimeError("%s: Not a identification message" % msg)
chars =
msgbin = common.hex2bin(msg)
csbin = msgbin[40:96]
cs =
cs += chars[common.bin2int(csbin[0:6])]
cs += chars[common.bin2int(csbin[... | Aircraft callsign
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
string: callsign |
348,486 | def update_webhook(self, id, **kwargs):
kwargs[] = True
if kwargs.get():
return self.update_webhook_with_http_info(id, **kwargs)
else:
(data) = self.update_webhook_with_http_info(id, **kwargs)
return data | Update a specific webhook # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_webhook(id, async_req=True)
>>> result = thread.get()
:param async_re... |
348,487 | def get_nac_eigendisplacements_along_dir(self, direction):
versor = [i / np.linalg.norm(direction) for i in direction]
for d, e in self.nac_eigendisplacements:
if np.allclose(versor, d):
return e
return None | Returns the nac_eigendisplacements for the given direction (not necessarily a versor).
None if the direction is not present or nac_eigendisplacements has not been calculated.
Args:
direction: the direction as a list of 3 elements
Returns:
the eigendisplacements as a nump... |
348,488 | def current(self):
if not self.started:
return None
return count_group(self.group, cached=self.cached) | get the index of the currently executing chain element
:return int: current chain index |
348,489 | def endian(self):
if self._endian is None:
value = self._DEFAULT_ENDIAN[self.arch]
if value is None:
raise NotImplementedError( % self.arch)
return value
else:
return self._endian | The target architecture byte order. One of :class:`Target.Endian`. |
348,490 | def register_wcs(name, wrapper_class, coord_types):
global custom_wcs
custom_wcs[name] = Bunch.Bunch(name=name,
wrapper_class=wrapper_class,
coord_types=coord_types) | Register a custom WCS wrapper.
Parameters
----------
name : str
The name of the custom WCS wrapper
wrapper_class : subclass of `~ginga.util.wcsmod.BaseWCS`
The class implementing the WCS wrapper
coord_types : list of str
List of names of coordinate types supported by the W... |
348,491 | def pause(self, length=None, **kwargs):
return self.nest(Pause(length=length, **kwargs)) | Create a <Pause> element
:param length: Length in seconds to pause
:param kwargs: additional attributes
:returns: <Pause> element |
348,492 | def group_theta(self, group):
for i, g in enumerate(self.nodes.keys()):
if g == group:
break
return i * self.major_angle | Computes the theta along which a group's nodes are aligned. |
348,493 | def execute_rolling_restart(
brokers,
jolokia_port,
jolokia_prefix,
check_interval,
check_count,
unhealthy_time_limit,
skip,
verbose,
pre_stop_task,
post_stop_task,
start_command,
stop_command,
ssh_password=None
):
all_hosts = [b[1] for b in brokers]
for ... | Execute the rolling restart on the specified brokers. It checks the
number of under replicated partitions on each broker, using Jolokia.
The check is performed at constant intervals, and a broker will be restarted
when all the brokers are answering and are reporting zero under replicated
partitions.
... |
348,494 | def offset(polygons,
distance,
join=,
tolerance=2,
precision=0.001,
join_first=False,
max_points=199,
layer=0,
datatype=0):
poly = []
if isinstance(polygons, PolygonSet):
poly.extend(polygons.polygons)
elif ... | Shrink or expand a polygon or polygon set.
Parameters
----------
polygons : polygon or array-like
Polygons to be offset. Must be a ``PolygonSet``,
``CellReference``, ``CellArray``, or an array. The array may
contain any of the previous objects or an array-like[N][2] of
ver... |
348,495 | def get_or_add_image(self, image_descriptor):
image_part = self._package.get_or_add_image_part(image_descriptor)
rId = self.relate_to(image_part, RT.IMAGE)
return rId, image_part.image | Return (rId, image) pair for image identified by *image_descriptor*.
*rId* is the str key (often like "rId7") for the relationship between this story
part and the image part, reused if already present, newly created if not.
*image* is an |Image| instance providing access to the properties of th... |
348,496 | def getattr(self, obj, attribute):
try:
value = getattr(obj, attribute)
except AttributeError:
try:
return obj[attribute]
except (TypeError, LookupError):
pass
else:
if self.is_safe_attribute(obj, attribute,... | Subscribe an object from sandboxed code and prefer the
attribute. The attribute passed *must* be a bytestring. |
348,497 | def delete_dir_rec(path: Path):
if not path.exists() or not path.is_dir():
return
for sub in path.iterdir():
if sub.is_dir():
delete_dir_rec(sub)
else:
sub.unlink()
path.rmdir() | Delete a folder recursive.
:param path: folder to deleted
:type path: ~pathlib.Path |
348,498 | def tool_classpath(self, key, scope=None):
return self.tool_classpath_from_products(self.context.products, key, scope=self._scope(scope)) | Get a classpath for the tool previously registered under key in the given scope.
:API: public
:param string key: The key the tool configuration was registered under.
:param string scope: The scope the tool configuration was registered under; the task scope by
default.
:returns... |
348,499 | def get_quoted_string(value):
quoted_string = QuotedString()
if value and value[0] in CFWS_LEADER:
token, value = get_cfws(value)
quoted_string.append(token)
token, value = get_bare_quoted_string(value)
quoted_string.append(token)
if value and value[0] in CFWS_LEADER:
to... | quoted-string = [CFWS] <bare-quoted-string> [CFWS]
'bare-quoted-string' is an intermediate class defined by this
parser and not by the RFC grammar. It is the quoted string
without any attached CFWS. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.