Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
3,600 | def labels(ctx):
config = ctx.obj[]
repos = config.get()
labels = config.get()
if not isinstance(repos, list):
raise CommandError(
)
if not isinstance(labels, dict):
raise CommandError(
)
git = GithubApi()
for repo in repos:
... | Crate or update labels in github |
3,601 | def run_lldptool(self, args):
full_args = [] + args
try:
return utils.execute(full_args, root_helper=self.root_helper)
except Exception as exc:
LOG.error("Unable to execute %(cmd)s. "
"Exception: %(exception)s",
{: full... | Function for invoking the lldptool utility. |
3,602 | def cfrom(self):
cfrom = -1
try:
if self.lnk.type == Lnk.CHARSPAN:
cfrom = self.lnk.data[0]
except AttributeError:
pass
return cfrom | The initial character position in the surface string.
Defaults to -1 if there is no valid cfrom value. |
3,603 | def name_suggest(q=None, datasetKey=None, rank=None, limit=100, offset=None, **kwargs):
Puma concolorPumaPumaPumaPumaPumaPuma
url = gbif_baseurl +
args = {:q, :rank, :offset, :limit}
return gbif_GET(url, args, **kwargs) | A quick and simple autocomplete service that returns up to 20 name usages by
doing prefix matching against the scientific name. Results are ordered by relevance.
:param q: [str] Simple search parameter. The value for this parameter can be a
simple word or a phrase. Wildcards can be added to the simple word pa... |
3,604 | def create_introspect_response(self, uri, http_method=, body=None,
headers=None):
resp_headers = {
: ,
: ,
: ,
}
request = Request(uri, http_method, body, headers)
try:
self.validate_introspect_re... | Create introspect valid or invalid response
If the authorization server is unable to determine the state
of the token without additional information, it SHOULD return
an introspection response indicating the token is not active
as described in Section 2.2. |
3,605 | def _instantiate_task(api, kwargs):
file_id = kwargs[]
kwargs[] = file_id if str(file_id).strip() else None
kwargs[] = kwargs[] or None
kwargs[] = kwargs[]
kwargs[] = kwargs[]
kwargs[] = get_utcdatetime(kwargs[])
kwargs[] = get_utcdatetime(kwargs[])
is_transferred = (kwargs[] == 2 a... | Create a Task object from raw kwargs |
3,606 | def pk_names(cls):
if cls._cache_pk_names is None:
cls._cache_pk_names = cls._get_primary_key_names()
return cls._cache_pk_names | Primary key column name list. |
3,607 | def _wait_for_process(self, pid, name):
try:
logging.debug("Waiting for process %s with pid %s", name, pid)
unused_pid, exitcode, ru_child = os.wait4(pid, 0)
return exitcode, ru_child
except OSError as e:
if self.PROCESS_KILLED and e.errno == errn... | Wait for the given process to terminate.
@return tuple of exit code and resource usage |
3,608 | def buy_close(id_or_ins, amount, price=None, style=None, close_today=False):
position_effect = POSITION_EFFECT.CLOSE_TODAY if close_today else POSITION_EFFECT.CLOSE
return order(id_or_ins, amount, SIDE.BUY, position_effect, cal_style(price, style)) | 平卖仓
:param id_or_ins: 下单标的物
:type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]
:param int amount: 下单手数
:param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。
:param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class... |
3,609 | def splitter(iterable, chunksize=60):
return (iterable[0+i:chunksize+i]
for i in range(0, len(iterable), chunksize)) | Split an iterable that supports indexing into chunks of 'chunksize'. |
3,610 | def log_posterior_transit_plus_line(theta, params, model, t, flux, err_flux,
priorbounds):
lp = _log_prior_transit_plus_line(theta, priorbounds)
if not np.isfinite(lp):
return -np.inf
else:
return (
lp + _log_likelihood_transit_plus_line(
... | Evaluate posterior probability given proposed model parameters and
the observed flux timeseries. |
3,611 | def get_cameras_signal_strength(self):
signal_strength = {}
if not self.camera_properties:
return None
for camera in self.camera_properties:
serialnum = camera.get()
cam_strength = camera.get()
signal_strength[serialnum] = cam_strength
... | Return a list of signal strength of all cameras. |
3,612 | def add(self, datapoint):
if not self.is_full:
self.set_datapoint(self.cur_index, datapoint)
self.cur_index += 1 | Adds the datapoint to the tensor if room is available. |
3,613 | def _add_chrome_arguments(self, options):
try:
for pref, pref_value in dict(self.config.items()).items():
pref_value = .format(pref_value) if pref_value else
self.logger.debug("Added chrome argument: %s%s", pref, pref_value)
options.add_argum... | Add Chrome arguments from properties file
:param options: chrome options object |
3,614 | def wait_func_accept_retry_state(wait_func):
if not six.callable(wait_func):
return wait_func
if func_takes_retry_state(wait_func):
return wait_func
if func_takes_last_result(wait_func):
@_utils.wraps(wait_func)
def wrapped_wait_func(retry_state):
warn_abou... | Wrap wait function to accept "retry_state" parameter. |
3,615 | def _get_log_level(level):
if level is None or level == "DEBUG":
return logging.DEBUG
level = level.upper()
if level == "INFO":
return logging.INFO
elif level == "WARNING":
return logging.WARNING
elif level == "CRITI... | small static method to get logging level
:param str level: string of the level e.g. "INFO"
:returns logging.<LEVEL>: appropriate debug level |
3,616 | def fetch(args: List[str], env: Dict[str, str] = None,
encoding: str = sys.getdefaultencoding()) -> str:
stdout, _ = run(args, env=env, capture_stdout=True,
echo_stdout=False, encoding=encoding)
log.debug(stdout)
return stdout | Run a command and returns its stdout.
Args:
args: the command-line arguments
env: the operating system environment to use
encoding: the encoding to use for ``stdout``
Returns:
the command's ``stdout`` output |
3,617 | def parse(s):
parts = s.replace(, ).split()
if not parts:
raise ValueError()
pieces = []
for part in parts:
m = PART_MATCH(part)
pieces.extend(m.groups() if m else [part])
if len(pieces) == 1:
pieces.append()
if len(pieces) % 2:
raise ValueError( ... | Parse a string representing a time interval or duration into seconds,
or raise an exception
:param str s: a string representation of a time interval
:raises ValueError: if ``s`` can't be interpreted as a duration |
3,618 | def _url_builder(url_root,api_key,path,params):
params[] = api_key
url_end = urlencode(params)
url = "%s%s%s" % (url_root,path,url_end)
return url | Helper funcation to build a parameterized url. |
3,619 | def event_handler(event_name):
def wrapper(func):
func._event_handler = True
func._handled_event = event_name
return func
return wrapper | Decorator for designating a handler for an event type. ``event_name`` must be a string
representing the name of the event type.
The decorated function must accept a parameter: the body of the received event,
which will be a Python object that can be encoded as a JSON (dict, list, str, int,
bool, float ... |
3,620 | def collect(self):
self.ignore_patterns = [
, , , , , , ,
]
page_themes = PageTheme.objects.all()
for finder in get_finders():
for path, storage in finder.list(self.ignore_patterns):
for t in page_themes:
static_p... | Load and save ``PageColorScheme`` for every ``PageTheme``
.. code-block:: bash
static/themes/bootswatch/united/variables.scss
static/themes/bootswatch/united/styles.scss |
3,621 | def set_wm_wallpaper(img):
if shutil.which("feh"):
util.disown(["feh", "--bg-fill", img])
elif shutil.which("nitrogen"):
util.disown(["nitrogen", "--set-zoom-fill", img])
elif shutil.which("bgs"):
util.disown(["bgs", "-z", img])
elif shutil.which("hsetroot"):
util... | Set the wallpaper for non desktop environments. |
3,622 | def sync_config_tasks(self):
tasks_by_hash = {_hash_task(t): t for t in self.config_tasks}
for task in self.all_tasks:
if tasks_by_hash.get(task["hash"]):
del tasks_by_hash[task["hash"]]
else:
self.collection.remove({"_id": task["_id"]})... | Performs the first sync of a list of tasks, often defined in the config file. |
3,623 | def complete_io(self, iocb, msg):
if _debug: IOQController._debug("complete_io %r %r", iocb, msg)
if iocb is not self.active_iocb:
raise RuntimeError("not the current iocb")
IOController.complete_io(self, iocb, msg)
self.active_iocb = No... | Called by a handler to return data to the client. |
3,624 | def set_prop(self, prop, value, ef=None):
if ef:
self.ef[prop] = value
else:
if prop == :
self.ensemble = value
elif prop == :
self.auc = value | set attributes values
:param prop:
:param value:
:param ef:
:return: |
3,625 | def load_file(file_path, credentials=None):
if file_path.startswith():
return _load_file_from_gcs(file_path, credentials)
else:
return open(file_path, ) | Load a file from either local or gcs.
Args:
file_path: The target file path, which should have the prefix 'gs://' if
to be loaded from gcs.
credentials: Optional credential to be used to load the file from gcs.
Returns:
A python File object if loading file from local or a StringIO objec... |
3,626 | def _compute_MFP_matrix(self):
self.MFP = np.zeros(self.Lp.shape)
for i in range(self.Lp.shape[0]):
for k in range(self.Lp.shape[1]):
for j in range(self.Lp.shape[1]):
self.MFP[i, k] += (self.Lp[i, j] - self.Lp[i, k]
... | See Fouss et al. (2006).
This is the mean-first passage time matrix. It's not a distance.
Mfp[i, k] := m(k|i) in the notation of Fouss et al. (2006). This
corresponds to the standard notation for transition matrices (left index
initial state, right index final state, i.e. a right-stoch... |
3,627 | def get_resources(cls):
plugin = directory.get_plugin()
controller = IPAvailabilityController(plugin)
return [extensions.ResourceExtension(Ip_availability.get_alias(),
controller)] | Returns Ext Resources. |
3,628 | def load(fp, **kwargs) -> BioCCollection:
obj = json.load(fp, **kwargs)
return parse_collection(obj) | Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to
a BioCCollection object
Args:
fp: a file containing a JSON document
**kwargs:
Returns:
BioCCollection: a collection |
3,629 | def list_present(name, acl_type, acl_names=None, perms=, recurse=False, force=False):
usergroup
if acl_names is None:
acl_names = []
ret = {: name,
: True,
: {},
: }
_octal = {: 4, : 2, : 1, : 0}
_octal_perms = sum([_octal.get(i, i) for i in perms])
if n... | Ensure a Linux ACL list is present
Takes a list of acl names and add them to the given path
name
The acl path
acl_type
The type of the acl is used for it can be 'user' or 'group'
acl_names
The list of users or groups
perms
Set the permissions eg.: rwx
recurs... |
3,630 | def _parse_title(dom, details):
title = details.find("h1")
if not title:
title = dom.find("title")
assert title, "Can't find <title> tag!"
return title[0].getContent().split("|")[0].strip()
return title[0].getContent().strip() | Parse title/name of the book.
Args:
dom (obj): HTMLElement containing whole HTML page.
details (obj): HTMLElement containing slice of the page with details.
Returns:
str: Book's title.
Raises:
AssertionError: If title not found. |
3,631 | def get_dimensions_units(names):
dimensions_uni = {}
for name in names:
key = get_key_from_dimensions(names[name].dimensions)
dimensions_uni[key] = names[name]
plain_dimensions = [{: name, : 1}]
key = get_key_from_dimensions(plain_dimensions)
dimensions_uni[key] = ... | Create dictionary of unit dimensions. |
3,632 | def use_comparative_activity_view(self):
self._object_views[] = COMPARATIVE
for session in self._get_provider_sessions():
try:
session.use_comparative_activity_view()
except AttributeError:
pass | Pass through to provider ActivityLookupSession.use_comparative_activity_view |
3,633 | def _urljoin(base, url):
parsed = urlparse(base)
scheme = parsed.scheme
return urlparse(
urljoin(parsed._replace(scheme=).geturl(), url)
)._replace(scheme=scheme).geturl() | Join relative URLs to base URLs like urllib.parse.urljoin but support
arbitrary URIs (esp. 'http+unix://'). |
3,634 | def VerifyMessageSignature(self, unused_response_comms, packed_message_list,
cipher, cipher_verified, api_version,
remote_public_key):
_ = api_version
result = rdf_flows.GrrMessage.AuthorizationState.UNAUTHENTICATED
if cipher_verified or c... | Verify the message list signature.
This is the way the messages are verified in the client.
In the client we also check that the nonce returned by the server is correct
(the timestamp doubles as a nonce). If the nonce fails we deem the response
unauthenticated since it might have resulted from a repla... |
3,635 | async def parse_target(self, runtime, target_str):
pipeline_parts = target_str.split(RULE_SEPARATOR)
module = await self.resolve_module(runtime, pipeline_parts[0],
target_str)
rules = []
for part in pipeline_parts[1:]:
rule ... | A target is a pipeline of a module into zero or more rules, and each
module and rule can itself be scoped with zero or more module names. |
3,636 | def main(argv):
source, target, tag = argv
if "a" in tag:
bump = "alpha"
if "b" in tag:
bump = "beta"
else:
bump = find_bump(target, tag)
filename = "{}.md".format(tag)
destination = copy(join(source, filename), target)
build_hugo_md(destination, tag, bump) | Identify the release type and create a new target file with TOML header.
Requires three arguments. |
3,637 | def transform_properties(properties, schema):
new_properties = properties.copy()
for prop_value, (prop_name, prop_type) in zip(new_properties.values(), schema["properties"].items()):
if prop_value is None:
continue
elif prop_type == "time":
new_properties[prop_name] ... | Transform properties types according to a schema.
Parameters
----------
properties : dict
Properties to transform.
schema : dict
Fiona schema containing the types. |
3,638 | def pointer_gate(num_qubits, U):
ptr_bits = int(floor(np.log2(num_qubits)))
data_bits = num_qubits - ptr_bits
ptr_state = 0
assert ptr_bits > 0
program = pq.Program()
program.defgate("CU", controlled(ptr_bits, U))
for _, target_qubit, changed in gray(ptr_bits):
if changed is ... | Make a pointer gate on `num_qubits`. The one-qubit gate U will act on the
qubit addressed by the pointer qubits interpreted as an unsigned binary
integer.
There are P = floor(lg(num_qubits)) pointer qubits, and qubits numbered
N - 1
N - 2
...
N - P
are those reserved t... |
3,639 | def configure(self, config):
credentials = CredentialParams.many_from_config(config)
for credential in credentials:
self._credentials.append(credential) | Configures component by passing configuration parameters.
:param config: configuration parameters to be set. |
3,640 | def sample_std(self, f, *args, **kwargs):
r
vals = self.sample_f(f, *args, **kwargs)
return _np.std(vals, axis=0) | r"""Sample standard deviation of numerical method f over all samples
Calls f(\*args, \*\*kwargs) on all samples and computes the standard deviation.
f must return a numerical value or an ndarray.
Parameters
----------
f : method reference or name (str)
Model method ... |
3,641 | def package(self, value):
if value is not None:
assert type(value) is unicode, " attribute: type is not !".format(
"package", value)
self.__package = value | Setter for **self.__package** attribute.
:param value: Attribute value.
:type value: unicode |
3,642 | def get_bitcoind_config(config_file=None, impl=None):
loaded = False
bitcoind_server = None
bitcoind_port = None
bitcoind_user = None
bitcoind_passwd = None
bitcoind_timeout = None
bitcoind_regtest = None
bitcoind_p2p_port = None
bitcoind_spv_path = None
regtest = None
... | Set bitcoind options globally.
Call this before trying to talk to bitcoind. |
3,643 | def compute_bgband (evtpath, srcreg, bkgreg, ebins, env=None):
import numpy as np
import pandas as pd
from scipy.special import erfcinv, gammaln
if env is None:
from . import CiaoEnvironment
env = CiaoEnvironment ()
srcarea = get_region_area (env, evtpath, srcreg)
bkgarea ... | Compute background information for a source in one or more energy bands.
evtpath
Path to a CIAO events file
srcreg
String specifying the source region to consider; use 'region(path.reg)' if you
have the region saved in a file.
bkgreg
String specifying the background region to consid... |
3,644 | def common_log(environ, response, response_time=None):
logger = logging.getLogger()
if response_time:
formatter = ApacheFormatter(with_response_time=True)
try:
log_entry = formatter(response.status_code, environ,
len(response.content), rt_us=r... | Given the WSGI environ and the response,
log this event in Common Log Format. |
3,645 | def to_repr(self: Variable, values, brackets1d: Optional[bool] = False) \
-> str:
prefix = f
if isinstance(values, str):
string = f
elif self.NDIM == 0:
string = f
elif self.NDIM == 1:
if brackets1d:
string = objecttools.assignrepr_list(values, prefix, 72... | Return a valid string representation for the given |Variable|
object.
Function |to_repr| it thought for internal purposes only, more
specifically for defining string representations of subclasses
of class |Variable| like the following:
>>> from hydpy.core.variabletools import to_repr, Variable
... |
3,646 | def profile(self, frame, event, arg):
if (self.events == None) or (event in self.events):
frame_info = inspect.getframeinfo(frame)
cp = (frame_info[0], frame_info[2], frame_info[1])
if self.codepoint_included(cp):
objects = muppy.get_objects()
... | Profiling method used to profile matching codepoints and events. |
3,647 | def expire_at(self, key, _time):
return self._client.expireat(self.get_key(key), round(_time)) | Sets the expiration time of @key to @_time
@_time: absolute Unix timestamp (seconds since January 1, 1970) |
3,648 | def parse_timespan(timedef):
if isinstance(timedef, int):
return timedef
converter_order = (, , , , )
converters = {
: 604800,
: 86400,
: 3600,
: 60,
: 1
}
timedef = timedef.lower()
if timedef.isdigit():
return int(timedef)
elif len(timedef) == 0:
return 0
seconds = -1
for spec in converter_o... | Convert a string timespan definition to seconds, for example converting
'1m30s' to 90. If *timedef* is already an int, the value will be returned
unmodified.
:param timedef: The timespan definition to convert to seconds.
:type timedef: int, str
:return: The converted value in seconds.
:rtype: int |
3,649 | def get(self, entry):
if self.apiVersion == 1:
path = self.secretsmount + + entry
else:
path = self.secretsmount + + entry
proj = yield self._http.get(.format(path))
code = yield proj.code
if code != 200:
... | get the value from vault secret backend |
3,650 | def get_database_data(file_name=):
if not os.path.exists(file_name):
raise IOError("File {} does not exist!".format(file_name))
df = pd.read_csv(file_name, header=1)
return df | return the energy (eV) and Sigma (barn) from the file_name
Parameters:
===========
file_name: string ('' by default) name of csv file
Returns:
========
pandas dataframe
Raises:
=======
IOError if file does not exist |
3,651 | def addcomment(self, order_increment_id,
status, comment=None, notify=False):
if comment is None:
comment = ""
return bool(self.call(
,
[order_increment_id, status, comment, notify]
)
) | Add comment to order or change its state
:param order_increment_id: Order ID
TODO: Identify possible values for status |
3,652 | def do_catch_fedora_errors(parser, token):
END_TAGS = (,
, )
blocks = {}
blocks[] = parser.parse(END_TAGS)
token = parser.next_token()
while token.contents != :
current_block = str(token.contents)
if current_block in blocks:
... | Catches fedora errors between ``{% fedora_access %}`` and
``{% end_fedora_access %}``. Template designers may specify
optional ``{% permission_denied %}`` and ``{% fedora_failed %}``
sections with fallback content in case of permission or other errors
while rendering the main block.
Note that when... |
3,653 | def _pre_run_checks(self, stream=sys.stdout, dry_run=False):
input_missing = self.check_input_files(return_found=False)
if input_missing:
if dry_run:
stream.write("Input files are missing: %s: %i\n" %
(self.linkname, len(i... | Do some checks before running this link
This checks if input and output files are present.
If input files are missing this will raise `OSError` if dry_run is False
If all output files are present this return False.
Parameters
-----------
stream : `file`
Str... |
3,654 | def generate_nucmer_commands(
filenames,
outdir=".",
nucmer_exe=pyani_config.NUCMER_DEFAULT,
filter_exe=pyani_config.FILTER_DEFAULT,
maxmatch=False,
):
nucmer_cmdlines, delta_filter_cmdlines = [], []
for idx, fname1 in enumerate(filenames[:-1]):
for fname2 in filenames[idx + 1 :... | Return a tuple of lists of NUCmer command-lines for ANIm
The first element is a list of NUCmer commands, the second a list
of delta_filter_wrapper.py commands. These are ordered such that
commands are paired. The NUCmer commands should be run before
the delta-filter commands.
- filenames - a list ... |
3,655 | def os_volumes(self):
if not self.__os_volumes:
self.__os_volumes = OsVolumes(self.__connection)
return self.__os_volumes | Gets the OS Volumes API client.
Returns:
OsVolumes: |
3,656 | def init(self, scope):
schemas = self.schemas().values()
for schema in schemas:
scope[schema.name()] = schema.model() | Loads the models from the orb system into the inputted scope.
:param scope | <dict>
autoGenerate | <bool>
schemas | [<orb.TableSchema>, ..] || None
database | <str> || None |
3,657 | def main():
parser = argparse.ArgumentParser(description=)
parser.add_argument(, "--add", nargs=3, action=parse_add_loopback(), help="add a Windows loopback adapter")
parser.add_argument("-r", "--remove", action="store", help="remove a Windows loopback adapter")
try:
args = parser.parse_ar... | Entry point for the Windows loopback tool. |
3,658 | def is_correct(self):
state = True
if self.command_name.startswith():
parameters = self.command_line.split()
if len(parameters) < 2:
self.command_name = "_internal_host_check;0;Host assumed to be UP"
self.ad... | Check if this object configuration is correct ::
* Check our own specific properties
* Call our parent class is_correct checker
:return: True if the configuration is correct, otherwise False
:rtype: bool |
3,659 | def convert_loguniform_categorical(self, challenger_dict):
converted_dict = {}
for key, value in challenger_dict.items():
if key in self.loguniform_key:
converted_dict[key] = np.exp(challenger_dict[key])
elif key in self.categori... | Convert the values of type `loguniform` back to their initial range
Also, we convert categorical:
categorical values in search space are changed to list of numbers before,
those original values will be changed back in this function
Parameters
----------
challenge... |
3,660 | def save_prov_to_files(self, showattributes=False):
self.doc.add_bundle(self.bundle)
ttl_file = os.path.join(self.export_dir, )
ttl_txt = self.doc.serialize(format=, rdf_format=)
ttl_txt, json_context = self.use_prefixes(ttl_txt)
... | Write-out provn serialisation to nidm.provn. |
3,661 | def sync_model(self, comment=, compact_central=False,
release_borrowed=True, release_workset=True,
save_local=False):
self._add_entry(templates.FILE_SYNC_START)
if compact_central:
self._add_entry(templates.FILE_SYNC_COMPACT)
if release... | Append a sync model entry to the journal.
This instructs Revit to sync the currently open workshared model.
Args:
comment (str): comment to be provided for the sync step
compact_central (bool): if True compacts the central file
release_borrowed (bool): if True relea... |
3,662 | def play_station(self, station):
for song in iterate_forever(station.get_playlist):
try:
self.play(song)
except StopIteration:
self.stop()
return | Play the station until something ends it
This function will run forever until termintated by calling
end_station. |
3,663 | def create_device(name,
role,
model,
manufacturer,
site):
try:
nb_role = get_(, , name=role)
if not nb_role:
return False
nb_type = get_(, , model=model)
if not nb_type:
return False... | .. versionadded:: 2019.2.0
Create a new device with a name, role, model, manufacturer and site.
All these components need to be already in Netbox.
name
The name of the device, e.g., ``edge_router``
role
String of device role, e.g., ``router``
model
String of device model, e... |
3,664 | def get_controller_state(self):
dpos = self.control[:3] * 0.005
roll, pitch, yaw = self.control[3:] * 0.005
self.grasp = self.control_gripper
drot1 = rotation_matrix(angle=-pitch, direction=[1., 0, 0], point=None)[:3, :3]
drot2 = rotation_matrix(angle=roll, dir... | Returns the current state of the 3d mouse, a dictionary of pos, orn, grasp, and reset. |
3,665 | def hideEvent(self, event):
super(CallTipWidget, self).hideEvent(event)
self._text_edit.cursorPositionChanged.disconnect(
self._cursor_position_changed)
self._text_edit.removeEventFilter(self) | Reimplemented to disconnect signal handlers and event filter. |
3,666 | def _init_params(self, inputs, overwrite=False):
inputs = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in inputs]
input_shapes = {item.name: item.shape for item in inputs}
arg_shapes, _, aux_shapes = self.symbol.infer_shape(**input_shapes)
assert arg_shapes is not None
... | Initialize weight parameters and auxiliary states. |
3,667 | def _forward_mode(self, *args):
X: np.ndarray
dX: np.ndarray
X, dX = self.f._forward_mode(*args)
p: float = self.p
val = X ** p
diff = p * X ** (p-1) * dX
return (val, diff) | Forward mode differentiation for a constant |
3,668 | def filter(self, filters):
new_elements = [
e for e in self.elements
if all(function(e) for function in filters)]
return Pileup(self.locus, new_elements) | Apply filters to the pileup elements, and return a new Pileup with the
filtered elements removed.
Parameters
----------
filters : list of PileupElement -> bool callables
A PileupUp element is retained if all filters return True when
called on it. |
3,669 | def load(self, model_file, save_dir, verbose=True):
if not os.path.exists(save_dir):
self.logger.error("Loading failed... Directory does not exist.")
try:
checkpoint = torch.load(f"{save_dir}/{model_file}")
except BaseException:
self.logger.error(
... | Load model from file and rebuild the model.
:param model_file: Saved model file name.
:type model_file: str
:param save_dir: Saved model directory.
:type save_dir: str
:param verbose: Print log or not
:type verbose: bool |
3,670 | def safe_call(self, kwargs, args=None):
raise
return str(exc) | Call the underlying function safely, given a set of keyword
arguments. If successful, the function return value (likely
None) will be returned. If the underlying function raises an
exception, the return value will be the exception message,
unless an argparse Namespace object defining a... |
3,671 | def _get_gecos(name):
gecos_field = pwd.getpwnam(name).pw_gecos.split(, 3)
if not gecos_field:
return {}
else:
while len(gecos_field) < 4:
gecos_field.append()
return {: six.text_type(gecos_field[0]),
: six.text_type(gecos_field[1]),
... | Retrieve GECOS field info and return it in dictionary form |
3,672 | def _merge_dicts(first, second):
new = deepcopy(first)
for k, v in second.items():
if isinstance(v, dict) and v:
ret = _merge_dicts(new.get(k, dict()), v)
new[k] = ret
else:
new[k] = second[k]
return new | Merge the 'second' multiple-dictionary into the 'first' one. |
3,673 | def random(cls, engine_or_session, limit=5):
ses, auto_close = ensure_session(engine_or_session)
result = ses.query(cls).order_by(func.random()).limit(limit).all()
if auto_close:
ses.close()
return result | Return random ORM instance.
:type engine_or_session: Union[Engine, Session]
:type limit: int
:rtype: List[ExtendedBase] |
3,674 | def swd_read8(self, offset):
value = self._dll.JLINK_SWD_GetU8(offset)
return ctypes.c_uint8(value).value | Gets a unit of ``8`` bits from the input buffer.
Args:
self (JLink): the ``JLink`` instance
offset (int): the offset (in bits) from which to start reading
Returns:
The integer read from the input buffer. |
3,675 | def scatter_plot(self, ax, topic_dims, t=None, ms_limits=True, **kwargs_plot):
plot_specs = {: , : }
plot_specs.update(kwargs_plot)
data = self.data_t(topic_dims, t)
ax.plot(*(data.T), **plot_specs)
... | 2D or 3D scatter plot.
:param axes ax: matplotlib axes (use Axes3D if 3D data)
:param tuple topic_dims: list of (topic, dims) tuples, where topic is a string and dims is a list of dimensions to be plotted for that topic.
:param int t: time indexes to be plotted
:param... |
3,676 | def humanize_time(secs):
if secs is None:
return
if secs < 1:
return "{:.2f}ms".format(secs*1000)
elif secs < 10:
return "{:.2f}s".format(secs)
else:
mins, secs = divmod(secs, 60)
hours, mins = divmod(mins, 60)
return .format(int(hours), int(mins), ... | convert second in to hh:mm:ss format |
3,677 | def send_message(self, message):
with self._instance_lock:
if message is None:
Global.LOGGER.error("cant deliver anonymous messages with body {message.body}")
return
if message.receiver is None:
Global.LOGGER.error(
... | Dispatch a message using 0mq |
3,678 | def get_names_owned_by_address(address, proxy=None, hostport=None):
assert proxy or hostport,
if proxy is None:
proxy = connect_hostport(hostport)
owned_schema = {
: ,
: {
: {
: ,
: {
: ,
: Tru... | Get the names owned by an address.
Returns the list of names on success
Returns {'error': ...} on error |
3,679 | def get_eval_func(obj, feature, slice=np.s_[...]):
if feature is not None:
if not isinstance(feature, InducingFeature) or not isinstance(obj, kernels.Kernel):
raise TypeError("If `feature` is supplied, `obj` must be a kernel.")
return lambda x: tf.transpose(Kuf(feature, obj... | Return the function of interest (kernel or mean) for the expectation
depending on the type of :obj: and whether any features are given |
3,680 | def frame_received_cb(self, frame):
PYVLXLOG.debug("REC: %s", frame)
for frame_received_cb in self.frame_received_cbs:
self.loop.create_task(frame_received_cb(frame)) | Received message. |
3,681 | def pop(self):
stack = getattr(self._local, "stack", None)
if stack is None:
return None
elif len(stack) == 1:
release_local(self._local)
return stack[-1]
else:
return stack.pop() | Removes the topmost item from the stack, will return the
old value or `None` if the stack was already empty. |
3,682 | def from_ymd_to_excel(year, month, day):
if not is_valid_ymd(year, month, day):
raise ValueError("Invalid date {0}.{1}.{2}".format(year, month, day))
days = _cum_month_days[month - 1] + day
days += 1 if (is_leap_year(year) and month > 2) else 0
years_distance = year - 1900
days += yea... | converts date as `(year, month, day)` tuple into Microsoft Excel representation style
:param tuple(int, int, int): int tuple `year, month, day`
:return int: |
3,683 | def warn(message, category=None, stacklevel=1, emitstacklevel=1):
if isinstance(message, Warning):
category = message.__class__
if category is None:
category = UserWarning
if not (isinstance(category, type) and issubclass(category, Warning)):
raise Type... | Issue a warning, or maybe ignore it or raise an exception.
Duplicate of the standard library warn function except it takes the
following argument:
`emitstacklevel` : default to 1, number of stackframe to consider when
matching the module that emits this warning. |
3,684 | def interpret(self, values={}, functions={}):
return self.expr.evaluate(Environment(values, functions)) | Like `substitute`, but forces the interpreter (rather than
the compiled version) to be used. The interpreter includes
exception-handling code for missing variables and buggy template
functions but is much slower. |
3,685 | def _group_paths_without_options(cls, line_parse_result):
active_pathspecs = set()
for group in line_parse_result:
active_pathspecs.add(group[])
has_options = (
in group or
in group or
in group
)
... | Given a parsed options specification as a list of groups, combine
groups without options with the first subsequent group which has
options.
A line of the form
'A B C [opts] D E [opts_2]'
results in
[({A, B, C}, [opts]), ({D, E}, [opts_2])] |
3,686 | def SetTimeZone(self, time_zone):
try:
self._time_zone = pytz.timezone(time_zone)
except (AttributeError, pytz.UnknownTimeZoneError):
raise ValueError(.format(time_zone)) | Sets the time zone.
Args:
time_zone (str): time zone.
Raises:
ValueError: if the timezone is not supported. |
3,687 | def follow(name: str) -> snug.Query[bool]:
request = snug.PUT(f)
response = yield request
return response.status_code == 204 | follow another user |
3,688 | def Parse(self, statentry, file_object, knowledge_base):
_ = knowledge_base
kwargs = {}
try:
kwargs["aff4path"] = file_object.urn
except AttributeError:
pass
direct_copy_items = [
"Label", "Disabled", "UserName", "GroupName", "Program",
"StandardInPath", "StandardOu... | Parse the Plist file. |
3,689 | def volume(self):
volume = abs(self.primitive.polygon.area *
self.primitive.height)
return volume | The volume of the primitive extrusion.
Calculated from polygon and height to avoid mesh creation.
Returns
----------
volume: float, volume of 3D extrusion |
3,690 | def printer(self, message, color_level=):
if self.job_args.get():
print(cloud_utils.return_colorized(msg=message, color=color_level))
else:
print(message) | Print Messages and Log it.
:param message: item to print to screen |
3,691 | def add_substitution(self, substitution):
if substitution.personalization:
try:
personalization = \
self._personalizations[substitution.personalization]
has_internal_personalization = True
except IndexError:
per... | Add a substitution to the email
:param value: Add a substitution to the email
:type value: Substitution |
3,692 | def _GetDatabaseConfig(self):
goodlogging.Log.Seperator()
goodlogging.Log.Info("CLEAR", "Getting configuration variables...")
goodlogging.Log.IncreaseIndent()
if self._sourceDir is None:
self._sourceDir = self._GetConfigValue(, )
if self._inPlaceRename is False and self._tvDir... | Get all configuration from database.
This includes values from the Config table as well as populating lists
for supported formats and ignored directories from their respective
database tables. |
3,693 | def _green_worker(self):
while not self.quit.is_set():
try:
task = self.green_queue.get(timeout=1)
timestamp, missile, marker = task
planned_time = self.start_time + (timestamp / 1000.0)
delay = planned_time - time.time()
... | A worker that does actual jobs |
3,694 | def display_molecule(mol, autozoom=True):
s = System([mol])
display_system(s, autozoom=True) | Display a `~chemlab.core.Molecule` instance in the viewer.
This function wraps the molecule in a system before displaying
it. |
3,695 | def parseGTF(inGTF):
desc=attributesGTF(inGTF)
ref=inGTF.copy()
ref.reset_index(inplace=True, drop=True)
df=ref.drop([],axis=1).copy()
for d in desc:
field=retrieve_GTF_field(d,ref)
df=pd.concat([df,field],axis=1)
return df | Reads an extracts all attributes in the attributes section of a GTF and constructs a new dataframe wiht one collumn per attribute instead of the attributes column
:param inGTF: GTF dataframe to be parsed
:returns: a dataframe of the orignal input GTF with attributes parsed. |
3,696 | def sql_fingerprint(query, hide_columns=True):
parsed_query = parse(query)[0]
sql_recursively_simplify(parsed_query, hide_columns=hide_columns)
return str(parsed_query) | Simplify a query, taking away exact values and fields selected.
Imperfect but better than super explicit, value-dependent queries. |
3,697 | def run(self, args):
email = args.email
username = args.username
force_send = args.resend
auth_role = args.auth_role
msg_file = args.msg_file
message = read_argument_file_contents(msg_file)
p... | Gives user permission based on auth_role arg and sends email to that user.
:param args Namespace arguments parsed from the command line |
3,698 | def from_string(contents):
lines = [l.strip() for l in contents.split("\n")]
link0_patt = re.compile(r"^(%.+)\s*=\s*(.+)")
link0_dict = {}
for i, l in enumerate(lines):
if link0_patt.match(l):
m = link0_patt.match(l)
link0_dict[m.grou... | Creates GaussianInput from a string.
Args:
contents: String representing an Gaussian input file.
Returns:
GaussianInput object |
3,699 | def access_token(self):
if self.cache_token:
return self.access_token_ or \
self._resolve_credential()
return self.access_token_ | Get access_token. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.