Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
356,900 | def get_system_offset():
import time
if time.daylight and time.localtime().tm_isdst > 0:
return -time.altzone
else:
return -time.timezone | Get system's timezone offset using built-in library time.
For the Timezone constants (altzone, daylight, timezone, and tzname), the
value is determined by the timezone rules in effect at module load time or
the last time tzset() is called and may be incorrect for times in the past.
To keep compatibili... |
356,901 | def _get_initial_residual(self, x0):
if x0 is None:
Mlr = self.linear_system.Mlb
else:
r = self.linear_system.b - self.linear_system.A*x0
Mlr = self.linear_system.Ml*r
PMlr, self.UMlr = self.projection.apply_complement(Mlr, return_Ya=True)
MP... | Return the projected initial residual.
Returns :math:`MPM_l(b-Ax_0)`. |
356,902 | def remove_rule(self, rule):
if not issubclass(rule.__class__, (Rule, RuleLeaf)):
raise TypeError(
"Rule to remove ({}) is not subclass of {} or {}."
.format(rule.__class__, Rule, RuleLeaf))
try:
ind = self._R.index(rule)
del s... | Remove rule from :attr:`R` and its corresponding weight from
:attr:`W`.
:param rule: rule to remove
:type rule:
:class:`~creamas.rules.rule.Rule` or
:class:`~creamas.rules.rule.RuleLeaf`
:raises TypeError:
If rule is not derived from :class:`Rule` or ... |
356,903 | def get_recent_linkbacks(number=5,
template=):
entry_published_pks = map(smart_text,
Entry.published.values_list(, flat=True))
content_type = ContentType.objects.get_for_model(Entry)
linkbacks = get_comment_model().objects.filter(
content_... | Return the most recent linkbacks. |
356,904 | def load_data(path, dense=False):
catalog = {: load_csv, : load_svmlight_file, : load_hdf5}
ext = os.path.splitext(path)[1]
func = catalog[ext]
X, y = func(path)
if dense and sparse.issparse(X):
X = X.todense()
return X, y | Load data from a CSV, LibSVM or HDF5 file based on the file extension.
Args:
path (str): A path to the CSV, LibSVM or HDF5 format file containing data.
dense (boolean): An optional variable indicating if the return matrix
should be dense. By default, it is false.
Retu... |
356,905 | def check_description(package_info, *args):
reason = "Description missing"
result = False
if package_info.get() not in BAD_VALUES:
result = True
return result, reason, HAS_DESCRIPTION | Does the package have a description listed?
:param package_info: package_info dictionary
:return: Tuple (is the condition True or False?, reason if it is False else None) |
356,906 | def signingPayloadState(self, identifier=None):
if self.operation.get(TXN_TYPE) == ATTRIB:
d = deepcopy(super().signingPayloadState(identifier=identifier))
op = d[OPERATION]
keyName = {RAW, ENC, HASH}.intersection(set(op.keys())).pop()
op[keyName] = sha25... | Special signing state where the the data for an attribute is hashed
before signing
:return: state to be used when signing |
356,907 | def _read_motifs_from_filehandle(handle, fmt):
if fmt.lower() == "pwm":
motifs = _read_motifs_pwm(handle)
if fmt.lower() == "transfac":
motifs = _read_motifs_transfac(handle)
if fmt.lower() == "xxmotif":
motifs = _read_motifs_xxmotif(handle)
if fmt.lower() == "align":
... | Read motifs from a file-like object.
Parameters
----------
handle : file-like object
Motifs.
fmt : string, optional
Motif format, can be 'pwm', 'transfac', 'xxmotif', 'jaspar' or 'align'.
Returns
-------
motifs : list
List of Motif instances. |
356,908 | def ceil(cls, x: ) -> :
return cls._unary_op(x, tf.ceil, tf.float32) | Returns a TensorFluent for the ceil function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the ceil function. |
356,909 | def create(self, task_name, clone_task=None):
if not task_name or task_name.startswith():
raise ValueError()
try:
task_dir = self._get_task_dir(task_name)
if self.exists(task_dir):
raise errors.TaskExists(task_name)
task_cfg = ... | Creates a new task directory.
`task_name`
Task name.
`clone_task`
Existing task name to use as a template for new task.
Returns boolean.
* Raises ``Value`` if task name is invalid, ``TaskExists`` if task
already exists, or ... |
356,910 | async def request(self, method, path, json=None, auth=True):
url = .format(self.host)
if auth:
url += .format(self.username)
url += path
try:
async with self.websession.request(method, url, json=json) as res:
if res.content_type != :
... | Make a request to the API. |
356,911 | def isBool(self, type):
if type in (CKA_ALWAYS_SENSITIVE,
CKA_DECRYPT,
CKA_DERIVE,
CKA_ENCRYPT,
CKA_EXTRACTABLE,
CKA_HAS_RESET,
CKA_LOCAL,
CKA_MODIFIABLE,
... | is the type a boolean value?
:param type: PKCS#11 type like `CKA_ALWAYS_SENSITIVE`
:rtype: bool |
356,912 | def first(self, default=None, as_dict=False, as_ordereddict=False):
try:
record = self[0]
except IndexError:
if isexception(default):
raise default
return default
if as_dict:
return record.as_dict()
... | Returns a single record for the RecordCollection, or `default`. If
`default` is an instance or subclass of Exception, then raise it
instead of returning it. |
356,913 | def eccentricity(self):
l1, l2 = self.covariance_eigvals
if l1 == 0:
return 0.
return np.sqrt(1. - (l2 / l1)) | The eccentricity of the 2D Gaussian function that has the same
second-order moments as the source.
The eccentricity is the fraction of the distance along the
semimajor axis at which the focus lies.
.. math:: e = \\sqrt{1 - \\frac{b^2}{a^2}}
where :math:`a` and :math:`b` are th... |
356,914 | def get_data_iters(dataset, batch_size, opt):
if dataset == :
train_data, val_data = get_mnist_iterator(batch_size, (1, 28, 28),
num_parts=kv.num_workers, part_index=kv.rank)
elif dataset == :
train_data, val_data = get_cifar10_iterator(batc... | get dataset iterators |
356,915 | def settings(self):
if not self.__settings:
self.__settings = self.request(, ).json()
return self.__settings | Retrieve and cache settings from server |
356,916 | def _multiplexed_response_stream_helper(self, response):
socket = self._get_raw_response_socket(response)
self._disable_socket_timeout(socket)
while True:
header = response.raw.read(STREAM_HEADER_SIZE_BYTES)
if not header:
brea... | A generator of multiplexed data blocks coming from a response
stream. |
356,917 | def script_run(trun, script):
if trun["conf"]["VERBOSE"]:
cij.emph("rnr:script:run { script: %s }" % script)
cij.emph("rnr:script:run:evars: %s" % script["evars"])
launchers = {
".py": "python",
".sh": "source"
}
ext = os.path.splitext(script["fpath"])[-1]
if ... | Execute a script or testcase |
356,918 | def exposure_units(exposure):
units = definition(exposure)[]
return sorted(units, key=lambda k: k[]) | Helper to get unit of an exposure.
:param exposure: Exposure type.
:type exposure: str
:returns: List of exposure units.
:rtype: list |
356,919 | def get_properties_obj(self):
properties = c_uamqp.cProperties()
self._set_attr(, properties)
self._set_attr(, properties)
self._set_attr(, properties)
self._set_attr(, properties)
self._set_attr(, properties)
self._set_attr(, properties)
self._se... | Get the underlying C reference from this object.
:rtype: uamqp.c_uamqp.cProperties |
356,920 | def _elements(self):
ElementCls, element_dicts = self._element_makings
return tuple(
ElementCls(element_dict, idx, element_dicts)
for idx, element_dict in enumerate(element_dicts)
) | Composed tuple storing actual sequence of element objects. |
356,921 | def to_segmentlistdict(self):
d = segments.segmentlistdict()
for entry in self:
d |= entry.segmentlistdict
return d | Return a segmentlistdict object describing the instruments
and times spanned by the entries in this Cache. The return
value is coalesced. |
356,922 | def sum(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False):
return self._compute_agg(, expression, binby, limits, shape, selection, delay, edges, progress)
@delayed
def finish(*sums):
return vaex.utils.unli... | Calculate the sum for the given expression, possible on a grid defined by binby
Example:
>>> df.sum("L")
304054882.49378014
>>> df.sum("L", binby="E", shape=4)
array([ 8.83517994e+06, 5.92217598e+07, 9.55218726e+07,
1.40008776e+08])
:param... |
356,923 | def weekday_series(self, start, end, weekday, return_date=False):
start = self.parse_datetime(start)
end = self.parse_datetime(end)
if isinstance(weekday, integer_types):
weekday = [weekday, ]
series = list()
for i in self.time_series(
start... | Generate a datetime series with same weekday number.
ISO weekday number: Mon to Sun = 1 to 7
Usage::
>>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25"
>>> rolex.weekday_series(start, end, weekday=2) # All Tuesday
[
datetime(2014, 1, 7, 6... |
356,924 | def filter_repo_urls(candidates):
candidates = set(url for url in [validate_url(_url) for _url in candidates] if url)
logger.info("Got repo candidates {}".format(candidates))
repos = set(url for url in [validate_repo_url(_url) for _url in candidates] if url)
logger.info("Filtered initial candi... | Filters down a list of URL candidates
:param candidates: list, URL candidates
:return: set, Repo URLs |
356,925 | def merge_adjacent(dom, tag_name):
for node in dom.getElementsByTagName(tag_name):
prev_sib = node.previousSibling
if prev_sib and prev_sib.nodeName == node.tagName:
for child in list(node.childNodes):
prev_sib.appendChild(child)
remove_node(node) | Merge all adjacent tags with the specified tag name.
Return the number of merges performed. |
356,926 | def timethis(label, receiver_fn=None):
start = time.time()
try:
yield
finally:
end = time.time()
if receiver_fn:
receiver_fn(label, start, end)
else:
print(.format(label, start, end, end-start)) | Times a block of code
Inspired from David Beazley talk - Generators: The Final Frontier |
356,927 | def plot(self,
data,
chart_type,
chart_package=,
options=None,
w=800,
h=420):
return HTML(
self.iframe.format(
source=self.render(
data=data,
options=options... | Output an iframe containing the plot in the notebook without saving. |
356,928 | def _match_tag_regex(self, event_tag, search_tag):
return self.cache_regex.get(search_tag).search(event_tag) is not None | Check if the event_tag matches the search check.
Uses regular expression search to check.
Return True (matches) or False (no match) |
356,929 | def color_mask(self) -> Tuple[bool, bool, bool, bool]:
return self.mglo.color_mask | tuple: The color mask of the framebuffer. |
356,930 | def set_value(self, value):
self.validate_value(value)
self.value.set(value) | Set the current value of the property.
value -- the value to set |
356,931 | def get_by_id(self, id_interface):
if not is_valid_int_param(id_interface):
raise InvalidParameterError(
u)
url = + str(id_interface) +
code, map = self.submit(None, , url)
return self.response(code, map) | Get an interface by id.
:param id_interface: Interface identifier.
:return: Following dictionary:
::
{'interface': {'id': < id >,
'interface': < interface >,
'descricao': < descricao >,
'protegida': < protegida >,
'tipo_equip': < id... |
356,932 | def load_state(cls, fname):
log.info("Loading state from %s", fname)
with open(fname, ) as file:
data = pickle.load(file)
svr = Server(data[], data[], data[])
if data[]:
svr.bootstrap(data[])
return svr | Load the state of this node (the alpha/ksize/id/immediate neighbors)
from a cache file with the given fname. |
356,933 | def get_es_mappings(self):
es_mappings = json.loads(requests.get(self.mapping_url).text)
es_mappings = {"_".join(key.split("_")[:-1]): value[] \
for key, value in es_mappings.items()}
return es_mappings | Returns the mapping defitions presetn in elasticsearh |
356,934 | def _process_node(self,node):
ns=node.ns()
if ns:
ns_uri=node.ns().getContent()
if (not ns or ns_uri=="jabber:component:accept") and node.name=="handshake":
if self.initiator and not self.authenticated:
self.authenticated=1
self.st... | Process first level element of the stream.
Handle component handshake (authentication) element, and
treat elements in "jabber:component:accept", "jabber:client"
and "jabber:server" equally (pass to `self.process_stanza`).
All other elements are passed to `Stream._process_node`.
... |
356,935 | def value_to_python(self, value):
if not isinstance(value, bytes):
raise tldap.exceptions.ValidationError("should be a bytes")
try:
value = int(value)
except (TypeError, ValueError):
raise tldap.exceptions.ValidationError("is invalid integer")
... | Converts the input single value into the expected Python data type,
raising django.core.exceptions.ValidationError if the data can't be
converted. Returns the converted value. Subclasses should override
this. |
356,936 | def get_version_list(path=None, module=None):
major = 0
minor = 0
patch =
ver = get_version(path, module)
if ver is not None:
ver_segments = _sane_version_list(ver.split(".", 2))
major = ver_segments[0]
minor = ver_segments[1]
patch = ".".join(ver_segments[2:]... | Return the version information as a tuple.
This uses get_version and breaks the string up. Would make more sense if
the version was a tuple throughout katversion. |
356,937 | def _strategy(codes, context):
if not isinstance(codes, tuple):
strategies = []
i = 0
while i < len(codes):
if codes[i][0] == sre.LITERAL and not (context.flags & re.IGNORECASE):
j = i + 1
while j < ... | Convert SRE regex parse tree to strategy that generates strings matching that
regex represented by that parse tree.
`codes` is either a list of SRE regex elements representations or a particular
element representation. Each element is a tuple of element code (as string) and
parameters. E.g. regex 'ab[0... |
356,938 | def get_as_array(self, key):
value = self.get(key)
return AnyValueMap.from_value(value) | Converts map element into an AnyValueMap or returns empty AnyValueMap if conversion is not possible.
:param key: an index of element to get.
:return: AnyValueMap value of the element or empty AnyValueMap if conversion is not supported. |
356,939 | def read_binary_matrix(filename):
with tf.io.gfile.GFile(filename, "rb") as f:
s = f.read()
int32_dtype = np.dtype("int32").newbyteorder("<")
magic = int(np.frombuffer(s, dtype=int32_dtype, count=1))
if magic == 507333717:
data_dtype = np.dtype("uint8")
elif magic == 5073337... | Reads and returns binary formatted matrix stored in filename.
The file format is described on the data set page:
https://cs.nyu.edu/~ylclab/data/norb-v1.0-small/
Args:
filename: String with path to the file.
Returns:
Numpy array contained in the file. |
356,940 | def list_organizations(container_id=None, include_validation=True):
orgs = _paginate(.format(_base_url()),
"organizations",
method=,
decode=True,
decode_type=,
header_dict={
: _api... | List organizations that CertCentral knows about. You can filter by
container_id (also known as "Division") by passing a container_id.
This function returns validation information by default; pass
``include_validation=False`` to turn it off.
CLI Example:
.. code-block:: bash
salt-run digic... |
356,941 | def diffusive_heat_transport(self):
phi = np.deg2rad(self.lat)
phi_stag = np.deg2rad(self.lat_bounds)
D = self.param[]
T = np.squeeze(self.Ts)
dTdphi = np.diff(T) / np.diff(phi)
dTdphi = np.append(dTdphi, 0.)
dTdphi = np.insert(dTdphi, 0, 0.)
retu... | Compute instantaneous diffusive heat transport in unit :math:`\\textrm{PW}`
on the staggered grid (bounds) through calculating:
.. math::
H(\\varphi) = - 2 \pi R^2 cos(\\varphi) D \\frac{dT}{d\\varphi}
\\approx - 2 \pi R^2 cos(\\varphi) D \\frac{\Delta T}{\Delta \\v... |
356,942 | def list_group_users(self, group_id, **kwargs):
kwargs["group_id"] = group_id
kwargs = self._verify_sort_options(kwargs)
api = self._get_api(iam.AccountAdminApi)
return PaginatedResponse(api.get_users_of_group, lwrap_type=User, **kwargs) | List users of a group.
:param str group_id: The group ID (Required)
:param int limit: The number of users to retrieve
:param str order: The ordering direction, ascending (asc) or descending (desc)
:param str after: Get API keys after/starting at given user ID
:returns: a list of... |
356,943 | def box(b, line_width=2, color=, style=):
if not isinstance(b, Box):
raise ValueError()
min_i = b.min_pt[1]
min_j = b.min_pt[0]
max_i = b.max_pt[1]
max_j = b.max_pt[0]
top_left = np.array([min_i, min_j])
top_right = np.ar... | Draws a box on the current plot.
Parameters
----------
b : :obj:`autolab_core.Box`
box to draw
line_width : int
width of lines on side of box
color : :obj:`str`
color of box
style : :obj:`str`
style of lines to draw |
356,944 | def xview(self, *args):
self.after_idle(self.__updateWnds)
ttk.Treeview.xview(self, *args) | Update inplace widgets position when doing horizontal scroll |
356,945 | def CreateAndStartHunt(flow_name, flow_args, creator, **kwargs):
if "duration" in kwargs:
precondition.AssertType(kwargs["duration"], rdfvalue.Duration)
hunt_args = rdf_hunt_objects.HuntArguments(
hunt_type=rdf_hunt_objects.HuntArguments.HuntType.STANDARD,
standard=rdf_hunt_objects.... | Creates and starts a new hunt. |
356,946 | def debug_async(self, conn_id, cmd_name, cmd_args, progress_callback, callback):
def monitor_callback(_conn_string, _conn_id, _event_name, event):
if event.get() != :
return
progress_callback(event.get(), event.get())
async def _install_monitor():
... | Asynchronously complete a named debug command.
The command name and arguments are passed to the underlying device adapter
and interpreted there. If the command is long running, progress_callback
may be used to provide status updates. Callback is called when the command
has finished.
... |
356,947 | def send_ping(self, payload=None):
yield from asyncio.sleep(self._interval)
self._handler.send_ping(payload=payload)
self._start_timer(payload=payload) | Sends the ping after the interval specified when initializing |
356,948 | def directive_DCB(self, label, params):
self.labels[label] = self.space_pointer
if params in self.equates:
params = self.equates[params]
self.memory[self.space_pointer] = self.convert_to_integer(params) & 0xFF
self.space_pointer += 1 | label DCB value[, value ...]
Allocate a byte space in read only memory for the value or list of values |
356,949 | def _get_shard_names(self, args):
if in args and args[]:
if len(args[]) == 1:
try:
n_shards = int(args[][0])
shard_names = [
% (i + 1) for i in range(n_shard... | Get the shard names based on the self.args['sharded'] parameter.
If it's a number, create shard names of type shard##, where ## is a
2-digit number. Returns a list [None] if no shards are present. |
356,950 | def rp_module_level_in_stack():
from traceback import extract_stack
from rootpy import _ROOTPY_SOURCE_PATH
modlevel_files = [filename for filename, _, func, _ in extract_stack()
if func == "<module>"]
return any(path.startswith(_ROOTPY_SOURCE_PATH) for path in modlevel_files) | Returns true if we're during a rootpy import |
356,951 | def as_security_error(node, secid):
assert node.Name ==
src = XmlHelper.get_child_value(node, )
code = XmlHelper.get_child_value(node, )
cat = XmlHelper.get_child_value(node, )
msg = XmlHelper.get_child_value(node, )
subcat = XmlHelper.get_child_value(node, )
... | convert the securityError element to a SecurityError |
356,952 | def stopword_remove(self, items, threshold=False):
def remove(tokens):
return [t for t in tokens if t not in self.stopwords]
if items == :
self.tokens = list(map(remove, self.tokens))
elif items == :
self.stems = list(map(remove, self.stems))
... | Remove stopwords from either tokens (items = "tokens")
or stems (items = "stems") |
356,953 | def ensure_geo_reference(origin):
if isinstance(origin, Geo_reference):
geo_ref = origin
elif origin is None:
geo_ref = None
else:
geo_ref = apply(Geo_reference, origin)
return geo_ref | Given a list/tuple of zone, xllcorner and yllcorner of a geo-ref object,
return a geo ref object.
If the origin is None, return None, so calling this function doesn't
effect code logic |
356,954 | def _process_dbxref(self):
raw = .join((self.rawdir, ))
LOG.info("processing dbxrefs")
line_counter = 0
with open(raw, ) as f:
filereader = csv.reader(f, delimiter=, quotechar=)
f.readline()
for line in filereader:
(dbxref_... | We bring in the dbxref identifiers and store them in a hashmap for
lookup in other functions.
Note that some dbxrefs aren't mapped to identifiers.
For example, 5004018 is mapped to a string,
"endosome & imaginal disc epithelial cell | somatic clone..."
In those cases, there j... |
356,955 | def get_charset(response):
charset = DEFAULT_CHARSET
m = re.findall(r, response.get(, ))
if m:
charset = m[0]
return charset | Return charset from ``response`` or default charset.
:rtype: str |
356,956 | def extract_locals(trcback):
output = []
stack = extract_stack(get_inner_most_frame(trcback))
for frame, file_name, line_number, name, context, index in stack:
args_names, nameless, keyword = extract_arguments(frame)
arguments, nameless_args, keyword_args, locals = OrderedDict(), [], {... | Extracts the frames locals of given traceback.
:param trcback: Traceback.
:type trcback: Traceback
:return: Frames locals.
:rtype: list |
356,957 | def generate_nb_state_data(means, weights, R):
cells = weights.shape[1]
x_true = np.dot(means, weights)
R_ = np.tile(R, (cells, 1)).T
P_true = x_true/(R_ + x_true)
sample = np.random.negative_binomial(np.tile(R, (cells, 1)).T, P_true)
return sample.astype(float) | Generates data according to the Negative Binomial Convex Mixture Model.
Args:
means (array): Cell types- genes x clusters
weights (array): Cell cluster assignments- clusters x cells
R (array): dispersion parameter - 1 x genes
Returns:
data matrix - genes x cells |
356,958 | def usufyToXlsxExport(d, fPath):
from pyexcel_xlsx import get_data
try:
oldData = {"OSRFramework": get_data(fPath) }
except:
oldData = {"OSRFramework":[]}
tabularData = _generateTabularData(d, oldData)
from pyexcel_xlsx import save_data
... | Workaround to export to a .xlsx file.
Args:
-----
d: Data to export.
fPath: File path for the output file. |
356,959 | def _makedirs(self, path):
try:
oldmask = os.umask(0)
os.makedirs(path, self._conf[])
os.umask(oldmask)
except OSError as e:
if(e.errno == errno.EACCES):
raise Exception(.format(path))
elif(e.errno == errno.EEXIST):
... | Make folders recursively for the given path and
check read and write permission on the path
Args:
path -- path to the leaf folder |
356,960 | def draw_on(self, folium_map):
f = getattr(folium_map, self._map_method_name)
f(**self._folium_kwargs) | Add feature to Folium map object. |
356,961 | def read_raw_pressure(self):
self._device.write8(BMP085_CONTROL, BMP085_READPRESSURECMD + (self._mode << 6))
if self._mode == BMP085_ULTRALOWPOWER:
time.sleep(0.005)
elif self._mode == BMP085_HIGHRES:
time.sleep(0.014)
elif self._mode == BMP085_ULTRAHIGHR... | Reads the raw (uncompensated) pressure level from the sensor. |
356,962 | def reset(self):
self.skip_function = None
self.skip_during_range = None
self.enabled = True
self.splay = None
self.opts[] = {} | Reset the scheduler to defaults |
356,963 | def find_version(include_dev_version=True, version_file=,
version_module_paths=(),
git_args=(, , , ),
Popen=subprocess.Popen):
try:
proc = Popen(git_args, stdout=subprocess.PIPE)
except OSError:
raw_version = None
else:
... | Find an appropriate version number from version control.
It's much more convenient to be able to use your version control system's
tagging mechanism to derive a version number than to have to duplicate that
information all over the place. Currently, only git is supported.
The default behavior is to wr... |
356,964 | def set_temperature(self, target_temperature):
try:
target_temperature = float(target_temperature)
except Exception as err:
LOG.debug("Thermostat.set_temperature: Exception %s" % (err,))
return False
self.writeNodeData("SET_TEMPERATURE", target_temper... | Set the target temperature. |
356,965 | def showConfig( self ):
item = self.uiPluginTREE.currentItem()
if not isinstance(item, PluginItem):
return
plugin = item.plugin()
widget = self.findChild(QWidget, plugin.uniqueName())
if ( not widget ):
widget = plugin.createWidg... | Show the config widget for the currently selected plugin. |
356,966 | def init_manifest(
package_name: str, version: str, manifest_version: Optional[str] = "2"
) -> Dict[str, Any]:
return {
"package_name": package_name,
"version": version,
"manifest_version": manifest_version,
} | Returns an initial dict with the minimal requried fields for a valid manifest.
Should only be used as the first fn to be piped into a `build()` pipeline. |
356,967 | def save(self, filename, strip_prefix=):
arg_dict = {}
for param in self.values():
weight = param._reduce()
if not param.name.startswith(strip_prefix):
raise ValueError(
"Prefix is to be striped before saving, but Parameter%s%swith na... | Save parameters to file.
Parameters
----------
filename : str
Path to parameter file.
strip_prefix : str, default ''
Strip prefix from parameter names before saving. |
356,968 | def write_feedback(self, feedback, cr=True):
self.__previous_data += feedback
if cr is True:
self.__previous_data += | Store feedback. Keep specified feedback as previous output
:param feedback: data to store
:param cr: whether to write carriage return to the end or not
:return: None |
356,969 | def field_choices_attibute(function):
def _wrapper(field, **kwargs):
if hasattr(field.widget, ):
return random.choice(list(valid_choices(field.widget.choices)))
return function(field, **kwargs)
return _wrapper | Selection from field.choices |
356,970 | def _remove_node(self, node):
self.graph.remove_node(node)
if node.addr in self._nodes:
del self._nodes[node.addr]
if node.addr in self.kb.functions:
del self.kb.functions[node.addr]
if node.addr in self.kb.functions.callgraph:
sel... | Remove a CFGNode from self.graph as well as from the function manager (if it is the beginning of a function)
:param CFGNode node: The CFGNode to remove from the graph.
:return: None |
356,971 | def current_rev_reg_id(base_dir: str, cd_id: str) -> str:
LOGGER.debug(, base_dir, cd_id)
if not ok_cred_def_id(cd_id):
LOGGER.debug(, cd_id)
raise BadIdentifier(.format(cd_id))
tags = [int(rev_reg_id2tag(basename(f))) for f in Tails.links(base_dir)
... | Return the current revocation registry identifier for
input credential definition identifier, in input directory.
Raise AbsentTails if no corresponding tails file, signifying no such revocation registry defined.
:param base_dir: base directory for tails files, thereafter split by cred def id
... |
356,972 | def json(self):
attributes = {
: self.type,
: self.filename,
: self.lineno,
: self.secret_hash,
}
if self.is_secret is not None:
attributes[] = self.is_secret
return attributes | Custom JSON encoder |
356,973 | def segment_area(self):
theta = self.length_radians()
return self.radius**2 / 2 * (theta - np.sin(theta)) | Returns the area of the corresponding arc segment.
>>> Arc((0,0), 2, 0, 360, True).segment_area()
12.566...
>>> Arc((0,0), 2, 0, 180, True).segment_area()
6.283...
>>> Arc((0,0), 2, 0, 90, True).segment_area()
1.14159...
>>> Arc((0,0), 2, 0, 90, False).se... |
356,974 | def services(self):
services = []
if self._services is None:
self.__init()
for service in self._services:
url = "%s/%s/%s" % (self.root, service[], service[])
if service[] == "GPServer":
services.append(GPService(url=url,
... | gets the services in the current folder |
356,975 | def restrict_to_version(self, version):
cairo.cairo_pdf_surface_restrict_to_version(self._pointer, version)
self._check_status() | Restricts the generated PDF file to :obj:`version`.
See :meth:`get_versions` for a list of available version values
that can be used here.
This method should only be called
before any drawing operations have been performed on the given surface.
The simplest way to do this is to... |
356,976 | def replace_evict_func(self, func, only_read=False):
self.logger.info( % (
get_function_signature(self.evict_func), get_function_signature(func)))
self.evict_func = func
return True | >>> cache = Cache(log_level=logging.WARNING)
>>> def evict(dict, evict_number=10): pass
>>> cache.replace_evict_func(evict)
True
>>> def evict_b(dict): pass
>>> cache.replace_evict_func(evict_b)
False
>>> def evict_c(dict, a, b): pass
>>> cache.replace_evi... |
356,977 | def convert_coerce_type_and_add_to_where_block(coerce_type_block, where_block):
instanceof_filter = convert_coerce_type_to_instanceof_filter(coerce_type_block)
if where_block:
else:
return instanceof_filter | Create an "INSTANCEOF" Filter from a CoerceType, adding to an existing Filter if any. |
356,978 | def get_hypervisors(self):
json_scheme = self.gen_def_json_scheme()
json_obj = self.call_method_post(method=, json_scheme=json_scheme)
self.json_templates = json_obj
d = dict(json_obj)
for elem in d[]:
hv = self.hypervisors[elem[]]
for inner_elem ... | Initialize the internal list containing each template available for each
hypervisor.
:return: [bool] True in case of success, otherwise False |
356,979 | def get_keys(self, bucket, timeout=None):
bucket_type = self._get_bucket_type(bucket.bucket_type)
url = self.key_list_path(bucket.name, bucket_type=bucket_type,
timeout=timeout)
status, _, body = self._request(, url)
if status == 200:
... | Fetch a list of keys for the bucket |
356,980 | def parse_variant(variant, case, variant_type=,
rank_results_header=None, vep_header=None,
individual_positions=None, category=None):
rank_results_header = rank_results_header or []
vep_header = vep_header or []
parsed_variant = {}
case_id = case[]... | Return a parsed variant
Get all the necessary information to build a variant object
Args:
variant(cyvcf2.Variant)
case(dict)
variant_type(str): 'clinical' or 'research'
rank_results_header(list)
vep_header(list)
individual_positions(dict): Explain what posit... |
356,981 | def list_roles():
for role in lib.get_roles():
margin_left = lib.get_margin(len(role[]))
print("{0}{1}{2}".format(
role[], margin_left,
role.get(, ))) | Show a list of all available roles |
356,982 | def get_default(self):
definfo = functionutils.DefinitionInfo.read(self._function)
for arg, default in definfo.args_with_defaults:
if self.argname == arg:
return default
return None | Get a string representation of a param's default value.
Returns None if there is no default value for this param. |
356,983 | def update(self, labels, preds):
cls_prob = preds[0].asnumpy()
loc_loss = preds[1].asnumpy()
cls_label = preds[2].asnumpy()
valid_count = np.sum(cls_label >= 0)
label = cls_label.flatten()
mask = np.where(label >= 0)[0]
indices = np.int6... | Implementation of updating metrics |
356,984 | def GetNotifications(user=None, token=None):
if not user:
user = getpass.getuser()
user_obj = aff4.FACTORY.Open(
aff4.ROOT_URN.Add("users").Add(user), token=token)
return list(user_obj.Get(user_obj.Schema.PENDING_NOTIFICATIONS)) | Show pending notifications for a user. |
356,985 | def cleanup_temporary_directories(self):
while self.build_directories:
shutil.rmtree(self.build_directories.pop())
for requirement in self.reported_requirements:
requirement.remove_temporary_source()
while self.eggs_links:
symbolic_link = self.eggs_li... | Delete the build directories and any temporary directories created by pip. |
356,986 | def ranged_property(min=None, max=None):
min_value = -_INF if min is None else min
max_value = _INF if max is None else max
return lambda fget: RangedProperty(
fget, fmin=lambda obj: min_value, fmax=lambda obj: max_value) | Decorator for creating ranged property with fixed bounds. |
356,987 | def authorize_get(self, session, fields=[]):
sellerAuthorize = SellerAuthorize()
request = TOPRequest()
if not fields:
fields = sellerAuthorize.fields
request[] = .join(fields)
self.create(self.execute(request, session))
return self.seller_authorize | taobao.itemcats.authorize.get 查询B商家被授权品牌列表和类目列表 |
356,988 | def format(x, format):
sl = vaex.strings.format(x, format)
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl) | Uses http://www.cplusplus.com/reference/string/to_string/ for formatting |
356,989 | def get_address(self, address_id, **params):
return self.api_client.get_address(self.id, address_id, **params) | https://developers.coinbase.com/api/v2#show-addresss |
356,990 | def run(self):
logger.info("result_worker starting...")
while not self._quit:
try:
task, result = self.inqueue.get(timeout=1)
self.on_result(task, result)
except Queue.Empty as e:
continue
except KeyboardInterr... | Run loop |
356,991 | def check(self, url_data):
content = url_data.get_content()
filename = get_temp_filename(content)
try:
app = get_word_app()
try:
doc = open_wordfile(app, filename)
if doc is None:
raise Error("could not... | Parse Word data. |
356,992 | def strongly_connected_components(graph: Graph) -> List:
assert check_argument_types()
result = []
stack = []
low = {}
def visit(node: str):
if node in low: return
num = len(low)
low[node] = num
stack_pos = len(stack)
stack.append(node)
for successor in graph[node]:
visit(successor)
... | Find the strongly connected components in a graph using Tarjan's algorithm.
The `graph` argument should be a dictionary mapping node names to sequences of successor nodes. |
356,993 | def merge(cls, predictors):
assert len(predictors) > 0
if len(predictors) == 1:
return predictors[0]
allele_to_allele_specific_models = collections.defaultdict(list)
class1_pan_allele_models = []
allele_to_fixed_length_sequence = predictors[0].allele_to_fixe... | Merge the ensembles of two or more `Class1AffinityPredictor` instances.
Note: the resulting merged predictor will NOT have calibrated percentile
ranks. Call `calibrate_percentile_ranks` on it if these are needed.
Parameters
----------
predictors : sequence of `Class1AffinityPre... |
356,994 | def autojump():
currently_enabled = autojump_enabled()
toggle_autojump()
if not currently_enabled:
click.secho("Autojump enabled", fg=)
else:
click.secho("Autojump disabled", fg=) | Initializes a virtualenv |
356,995 | def _read_bytes_from_framed_body(self, b):
plaintext = b""
final_frame = False
_LOGGER.debug("collecting %d bytes", b)
while len(plaintext) < b and not final_frame:
_LOGGER.debug("Reading frame")
frame_data, final_frame = deserialize_frame(
... | Reads the requested number of bytes from a streaming framed message body.
:param int b: Number of bytes to read
:returns: Bytes read from source stream and decrypted
:rtype: bytes |
356,996 | def to_array(self):
array = super(ChatActionMessage, self).to_array()
array[] = u(self.action)
if self.receiver is not None:
if isinstance(self.receiver, None):
array[] = None(self.receiver)
array[] = u(self.receiver)
elif i... | Serializes this ChatActionMessage to a dictionary.
:return: dictionary representation of this object.
:rtype: dict |
356,997 | def cree_local_DB(scheme):
conn = LocalConnexion()
req = ""
for table, fields in scheme.items():
req += f"DROP TABLE IF EXISTS {table};"
req_fields = ", ".join(f for c_name, c_type in fields)
req += f
cur = conn.cursor()
cur.executescript(req)
conn.connexion.commit()... | Create emmpt DB according to the given scheme : dict { table : [ (column_name, column_type), .. ]}
Usefull at installation of application (and for developement) |
356,998 | def evaluate(self, simplify=False, empty_val=0):
if self.is_homogeneous:
if simplify:
x = self.base_value
else:
x = self.base_value * numpy.ones(self._shape, dtype=self.dtype)
elif isinstance(self.base_value, (int, long, numpy.int... | Return the lazy array as a real NumPy array.
If the array is homogeneous and ``simplify`` is ``True``, return a
single numerical value. |
356,999 | def OnDirectionChoice(self, event):
label = self.direction_choicectrl.GetItems()[event.GetSelection()]
param = self.choice_label2param[label]
self.attrs["direction"] = param
post_command_event(self, self.DrawChartMsg) | Direction choice event handler |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.