Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
348,200 | def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
*echo foobar
lst = list_tab(user)
for cron in lst[]:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
... | Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar' |
348,201 | def gen_methods(self, *args, **kwargs):
token = args[0]
inst = self.inst
prefix = self._method_prefix
for method_key in self.gen_method_keys(*args, **kwargs):
method = getattr(inst, prefix + method_key, None)
if method is not None:
yield m... | Find all method names this input dispatches to. |
348,202 | def check_initial_web_request(self, item_session: ItemSession, request: HTTPRequest) -> Tuple[bool, str]:
verdict, reason, test_info = self.consult_filters(item_session.request.url_info, item_session.url_record)
if verdict and self._robots_txt_checker:
can_fetch = yield from self.c... | Check robots.txt, URL filters, and scripting hook.
Returns:
tuple: (bool, str)
Coroutine. |
348,203 | def stop_logging():
global __UTOOL_ROOT_LOGGER__
global __UTOOL_PRINT__
global __UTOOL_WRITE__
global __UTOOL_FLUSH__
if __UTOOL_ROOT_LOGGER__ is not None:
if VERBOSE or LOGGING_VERBOSE:
_utool_print()()()
_utool_flush()()
for h in __UTOOL_R... | Restores utool print functions to python defaults |
348,204 | def read_local_xlsx_catalog(xlsx_path, logger=None):
logger = logger or pydj_logger
wb = pyxl.load_workbook(open(xlsx_path, ), data_only=True,
read_only=True)
ws_catalog = helpers.get_ws_case_insensitive(wb, "catalog")
ws_dataset = helpers.get_ws_case_insensitive(... | Genera un diccionario de metadatos de catálogo a partir de un XLSX bien
formado.
Args:
xlsx_path (str): Path a un archivo XLSX "template" para describir la
metadata de un catálogo.
Returns:
dict: Diccionario con los metadatos de un catálogo. |
348,205 | def diff_sevice_by_changeset(service_name, service, environment, cf_client, repo_root):
global ret_code
logger.info(,
service[], service_name, environment)
delete_any_existing_changesets(cf_client, service_name, environment)
try:
changeset = generate_changeset(service_nam... | If an ef-cf call fails, the error will be logged, the retcode set to 2, but
the function will run to completion and return the list of non-error
results. |
348,206 | def _ensure_sparse_format(spmatrix, accept_sparse, dtype, order, copy,
force_all_finite):
if accept_sparse is None:
raise TypeError(
)
sparse_type = spmatrix.format
if dtype is None:
dtype = spmatrix.dtype
if... | Convert a sparse matrix to a given format.
Checks the sparse format of spmatrix and converts if necessary.
Parameters
----------
spmatrix : scipy sparse matrix
Input to validate and convert.
accept_sparse : string, list of string or None (default=None)
String[s] representing allow... |
348,207 | def assess_mhc_genes(job, isoform_expression, rna_haplotype, univ_options, mhc_genes_options):
job.fileStore.logToMaster( % univ_options[])
work_dir = job.fileStore.getLocalTempDir()
input_files = {
: isoform_expression,
: rna_haplotype,
: mhc_genes_options[]}
input_files = ... | This module will assess the prevalence of the various genes in the MHC pathway and return a
report in the tsv format
:param isoform_expression: Isoform expression from run_rsem
:param rna_haplotype: PHLAT output from running on rna
:param univ_options: Universal options for the pipeline
:param mhc_g... |
348,208 | def _parseCounters(self, data):
info_dict = util.NestedDict()
for line in data.splitlines():
mobj = re.match(, line)
if mobj:
(key, value) = mobj.groups()
klist = key.split()
info_dict.set_nested(klist, parse_value(value))
... | Parse simple stats list of key, value pairs.
@param data: Multiline data with one key-value pair in each line.
@return: Dictionary of stats. |
348,209 | def import_submodules(package_name):
import importlib, pkgutil
package = importlib.import_module(package_name)
return {
name: importlib.import_module(package_name + + name)
for _, name, _ in pkgutil.iter_modules(package.__path__)
} | Import all submodules of a module. |
348,210 | def set_config(**kwargs):
kk = kwargs.keys()
vv = kwargs.values()
check_call(_LIB.MXSetProcessProfilerConfig(len(kwargs),
c_str_array([key for key in kk]),
c_str_array([str(val) for val in vv]),
... | Set up the configure of profiler (only accepts keyword arguments).
Parameters
----------
filename : string,
output file for profile data
profile_all : boolean,
all profile types enabled
profile_symbolic : boolean,
whether to profile symbolic operators
profile_imperative ... |
348,211 | def find_instances(instance_id=None, name=None, tags=None, region=None,
key=None, keyid=None, profile=None, return_objs=False,
in_states=None, filters=None):
{"mytag": "value"}{"vpc-id": "vpc-12345678"}
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)... | Given instance properties, find and return matching instance ids
CLI Examples:
.. code-block:: bash
salt myminion boto_ec2.find_instances # Lists all instances
salt myminion boto_ec2.find_instances name=myinstance
salt myminion boto_ec2.find_instances tags='{"mytag": "value"}'
... |
348,212 | def nested_model(model, nested_fields):
if model is None:
return None
app_model = model.get_app_model()
is_dict = isinstance(nested_fields, dict)
for field in nested_fields:
field = get_nested_field_name(field)
nested_nested = nested_fields.get(
field) if... | Return :class:`zsl.db.model.app_model import AppModel` with the nested
models attached. ``nested_fields`` can be a simple list as model
fields, or it can be a tree definition in dict with leafs as keys with
``None`` value |
348,213 | def resubmit(self, req, keyspace, req_d, retries):
self.log( % (req.method,))
self.pushRequest_really(req, keyspace, req_d, retries)
try:
self.request_queue.pending.remove((req, keyspace, req_d, retries))
except ValueError:
pass
else:... | Push this request to the front of the line, just to be a jerk. |
348,214 | def emit(self, record):
if lvl > record.levelno:
return
self._recordQueue.insert(0, record)
self._recordQueue = self._recordQueue[:10]
super(XLogRecordHandler, self).emit(record) | Throws an error based on the information that the logger reported,
given the logging level.
:param record | <logging.LogRecord> |
348,215 | def _compute_anom_data_decay_all(self):
anom_scores = {}
values = self.time_series.values
ema = utils.compute_ema(self.smoothing_factor, values)
stdev = numpy.std(values)
for i, (timestamp, value) in enumerate(self.time_series_items):
anom_score = abs((value ... | Compute anomaly scores using a lagging window covering all the data points before. |
348,216 | def vectorize( self, docs ):
if type(docs) == dict:
docs = docs.items()
if self.model == None:
self.train(docs)
asset_id2vector = {}
unfound = []
for item in docs:
asset_id, _ = item
label = + str(asset_id... | Returns the feature vectors for a set of docs. If model is not already be trained,
then self.train() is called.
Args:
docs (dict or list of tuples): asset_id, body_text of documents
you wish to featurize. |
348,217 | def isqrt(n):
if n is None or type(n) is not int or n < 0:
raise ValueError("Input must be a non-negative integer.")
try:
root = int(sqrt(n))
if pow(root, 2) == n:
return root
except OverflowError:
pass
root = 0
rmdr = 0
for s in reversed(r... | Returns the largest root such that root**2 <= n (root + 1)**2 > n.
Credit goes to:
https://gist.github.com/castle-bravo/e841684d6bad8e0598e31862a7afcfc7
http://stackoverflow.com/a/23279113/2738025
>>> isqrt(4)
2
>>> isqrt(16)
4
>>> list(map(isqrt, range(16,26)))
[4, 4, 4, 4, 4,... |
348,218 | def check_origin(self, origin):
from ..util import check_whitelist
parsed_origin = urlparse(origin)
origin_host = parsed_origin.netloc.lower()
allowed_hosts = self.application.websocket_origins
if settings.allowed_ws_origin():
allowed_hosts = set(settings.al... | Implement a check_origin policy for Tornado to call.
The supplied origin will be compared to the Bokeh server whitelist. If the
origin is not allow, an error will be logged and ``False`` will be returned.
Args:
origin (str) :
The URL of the connection origin
... |
348,219 | def reboot(self, subid, params=None):
params = update_params(params, {: subid})
return self.request(, params, ) | /v1/server/reboot
POST - account
Reboot a virtual machine. This is a hard reboot
(basically, unplugging the machine).
Link: https://www.vultr.com/api/#server_reboot |
348,220 | def convert_dict_to_option_dict(input_dict):
ret_dict = {}
for key, value in input_dict.items():
ret_dict[key] = convert_value_to_option_tuple(value)
return ret_dict | Convert a simple key-value dictionary to a dictionary of options tuples |
348,221 | def fd_decompress(amp, phase, sample_frequencies, out=None, df=None,
f_lower=None, interpolation=):
precision = _precision_map[sample_frequencies.dtype.name]
if _precision_map[amp.dtype.name] != precision or \
_precision_map[phase.dtype.name] != precision:
raise ValueE... | Decompresses an FD waveform using the given amplitude, phase, and the
frequencies at which they are sampled at.
Parameters
----------
amp : array
The amplitude of the waveform at the sample frequencies.
phase : array
The phase of the waveform at the sample frequencies.
sample_fr... |
348,222 | def overlaps(self, other, permissive=False):
if not isinstance(other, AtomicInterval):
raise TypeError()
if self._lower > other.lower:
first, second = other, self
else:
first, second = self, other
if first._upper == second._lower:
... | Test if intervals have any overlapping value.
If 'permissive' is set to True (default is False), then [1, 2) and [2, 3] are considered as having
an overlap on value 2 (but not [1, 2) and (2, 3]).
:param other: an atomic interval.
:param permissive: set to True to consider contiguous in... |
348,223 | def _get_disks(dom):
disks = {}
doc = ElementTree.fromstring(dom.XMLDesc(0))
for elem in doc.findall():
source = elem.find()
if source is None:
continue
target = elem.find()
if target is None:
continue
if in target.attrib:
qem... | Get domain disks from a libvirt domain object. |
348,224 | def process_string(self,string):
item_list = self.parse_string(string)
for item in item_list:
if len(item)>0 and in dir(item[0]) and in dir(item[0].concept) and item[0].concept.action:
item[0].concept.action(item_list) | Searches the string (or list of strings) for an action word (a :class:`Concept` that has and ``action`` attached
to it), then calls the appropriate function with a dictionary of the identified words (according to ``vocab``).
For examples, see ``demo.py`` |
348,225 | def construct_operation_validators(api_path, path_definition, operation_definition, context):
validators = {}
assert not in operation_definition
assert not in operation_definition
assert not in operation_definition
for key in operation_definition.keys():
if key not in validato... | - consumes (did the request conform to the content types this api consumes)
- produces (did the response conform to the content types this endpoint produces)
- parameters (did the parameters of this request validate)
TODO: move path parameter validation to here, because each operation
can over... |
348,226 | def create_entry(self, **kwargs):
data = self._wrap_dict("time_entry", kwargs)
return self.post("/time_entries.json", data) | Creates a new time entry on Mite. Takes a data dictionary with the keys
`date_at` (a date string in `YYYY-MM-DD` format), `minutes` (an int),
`note` (the entry text), `user_id`, `project_id`, `service_id`, and
`locked`. All of them are optional. |
348,227 | def parse_docstring(docstring):
short_description = long_description = return_str = ""
args = []
if docstring:
docstring = trim(docstring.lstrip("\n"))
lines = docstring.split("\n", 1)
short_description = lines[0]
if len(lines) > 1:
long_description = lin... | Parse the docstring into its components.
:return: a dictionary of form
{
"short_description": ...,
"long_description": ...,
"params": [{"name": ..., "doc": ...}, ...],
"vals": [{"name": ..., "doc": ...}, ...],
"... |
348,228 | def from_cryptography(cls, crypto_req):
if not isinstance(crypto_req, x509.CertificateSigningRequest):
raise TypeError("Must be a certificate signing request")
req = cls()
req._req = crypto_req._x509_req
return req | Construct based on a ``cryptography`` *crypto_req*.
:param crypto_req: A ``cryptography`` X.509 certificate signing request
:type crypto_req: ``cryptography.x509.CertificateSigningRequest``
:rtype: X509Req
.. versionadded:: 17.1.0 |
348,229 | def _send_outgoing_route_refresh_msg(self, rr_msg):
assert rr_msg.type == BGP_MSG_ROUTE_REFRESH
self._protocol.send(rr_msg)
LOG.debug(,
self._neigh_conf.ip_address, rr_msg)
if rr_msg.demarcation == 0:
self.state.incr(PeerCounterNames.SENT_R... | Sends given message `rr_msg` to peer.
Parameters:
- rr_msg: (RouteRefresh) route refresh message to send to peer.
Update appropriate counters and set appropriate timers. |
348,230 | def print_state(state: State, file: TextIO = None) -> None:
state = state.vec.asarray()
for index, amplitude in np.ndenumerate(state):
ket = "".join([str(n) for n in index])
print(ket, ":", amplitude, file=file) | Print a state vector |
348,231 | def _is_type_compatible(a, b):
is_ts_compat = lambda x: isinstance(x, (Timestamp, DateOffset))
is_td_compat = lambda x: isinstance(x, (Timedelta, DateOffset))
return ((is_number(a) and is_number(b)) or
(is_ts_compat(a) and is_ts_compat(b)) or
(is_td_compat(a) and is_td_compat(b)... | helper for interval_range to check type compat of start/end/freq |
348,232 | def setup_logging(debug, logfile=None):
if debug:
level = logging.DEBUG
else:
level = logging.INFO
if logfile is not None:
logging.basicConfig(format="%(asctime)s %(levelname)8s %(message)s", datefmt="%H:%M:%S %Y/%m/%d", level=level, filename=logfile)
else:
logging.b... | Setup logging format and log level. |
348,233 | def full_path_str(self):
with self._mutex:
if self._parent:
if self._parent._name == :
return self._parent.full_path_str + self._name
else:
return self._parent.full_path_str + + self._name
else:
... | The full path of this node as a string. |
348,234 | def process_tags(self, tag=None):
if self.downloaded is False:
raise serror("Track not downloaded, can't process tags..")
filetype = magic.from_file(self.filepath, mime=True)
if filetype != "audio/mpeg":
raise serror("Cannot process tags for file type %s." % file... | Process ID3 Tags for mp3 files. |
348,235 | def cluster_replicate(self, node_id):
fut = self.execute(b, b, node_id)
return wait_ok(fut) | Reconfigure a node as a slave of the specified master node. |
348,236 | def add_global(self, globalvalue):
assert globalvalue.name not in self.globals
self.globals[globalvalue.name] = globalvalue | Add a new global value. |
348,237 | def get_stack(self, f, t):
stack = []
if t and t.tb_frame == f:
t = t.tb_next
while f is not None:
stack.append((f, f.f_lineno))
f = f.f_back
stack.reverse()
i = max(0, len(stack) - 1)
while t is not None:
stack.app... | Build the stack from frame and traceback |
348,238 | def _get_user_groups(self, user):
return [g.gr_name for g in grp.getgrall()
if user in g.gr_mem] + [grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name] | Get user groups.
:param user:
:return: |
348,239 | def detect_version_str(self):
help_text = run_matlab_cmd("help()".format(self.test_func))
if not help_text:
raise ArcanaRequirementNotFoundError(
"Did not find test function for {}"
.format(self.test_func, self))
return self.parse_help_text(h... | Try to detect version of package from command help text. Bit of a long
shot as they are typically included |
348,240 | def _on_axes_updated(self):
self.attrs["axes"] = [a.identity.encode() for a in self._axes]
while len(self._current_axis_identities_in_natural_namespace) > 0:
key = self._current_axis_identities_in_natural_namespace.pop(0)
try:
delattr(se... | Method to run when axes are changed in any way.
Propagates updated axes properly. |
348,241 | def to_html(self):
table = % self.html_attributes()
if self.caption is not None:
if isinstance(self.caption, MessageElement):
caption = self.caption.to_html()
else:
caption = self.caption
table += % caption
if self.he... | Render a Table MessageElement as html.
:returns: The html representation of the Table MessageElement
:rtype: basestring |
348,242 | def _readable_part_size(num_bytes):
"Returns the file size in readable form."
B = num_bytes
KB = float(1024)
MB = float(KB * 1024)
GB = float(MB * 1024)
TB = float(GB * 1024)
if B < KB:
return .format(B, if B != 1 else )
elif KB <= B < MB:
return .format(B/KB)
elif ... | Returns the file size in readable form. |
348,243 | def optional_args(proxy=None):
optional_args:port:1234
opt_args = _get_device_grain(, proxy=proxy) or {}
if opt_args and _FORBIDDEN_OPT_ARGS:
for arg in _FORBIDDEN_OPT_ARGS:
opt_args.pop(arg, None)
return {: opt_args} | Return the connection optional args.
.. note::
Sensible data will not be returned.
.. versionadded:: 2017.7.0
CLI Example - select all devices connecting via port 1234:
.. code-block:: bash
salt -G 'optional_args:port:1234' test.ping
Output:
.. code-block:: yaml
... |
348,244 | def write_double(self, value, little_endian=True):
if little_endian:
endian = "<"
else:
endian = ">"
return self.pack( % endian, value) | Pack the value as a double and write 8 bytes to the stream.
Args:
value (number): the value to write to the stream.
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: the number of bytes written. |
348,245 | def rewrap(el, t, ind, pref):
global term_columns
cols = term_columns - len(ind + pref)
if el.tag == or len(t) <= cols:
return t
puncs = , , , , ,
parts = []
origp = t.splitlines()
if len(origp) > 1:
pos = -1
while pos < len(origp) - 1:
... | Reasonably smart rewrapping checking punctuations |
348,246 | def _set_quality(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=quality.quality, is_container=, presence=False, yang_name="quality", rest_name="quality", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, ex... | Setter method for quality, mapped from YANG variable /ptp_state/clock/quality (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_quality is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_quality()... |
348,247 | def _bounds_from_array(arr, dim_name, bounds_name):
return bounds.T | Get the bounds of an array given its center values.
E.g. if lat-lon grid center lat/lon values are known, but not the
bounds of each grid box. The algorithm assumes that the bounds
are simply halfway between each pair of center values. |
348,248 | def t_t_eopen(self, t):
r"escapequotes\:
t.lexer.push_state()
return t | r'~"|~\ |
348,249 | def git_fetch(repo_dir, remote=None, refspec=None, verbose=False, tags=True):
command = [, ]
if not remote:
command.append()
else:
remote = pipes.quote(remote)
command.extend([])
if tags:
command.append()
if verbose:
command.append()
if remote:
co... | Do a git fetch of `refspec` in `repo_dir`.
If 'remote' is None, all remotes will be fetched. |
348,250 | def _resolve_ctx(rules):
if not rules:
raise ResolveError("Missing node definition.")
if len(rules) == 1 and rules[0][0] is None:
return rules[0][1]
if any(r[0] is None for r in rules):
raise ResolveError("Multiple definition, multiple ieml object provided for the same no... | Resolve the context of the rules (the type of this element), and building the ieml element.
:param rules:
:return: |
348,251 | def translate(ra, dec, r, theta):
factor = np.sin(np.radians(dec)) * np.cos(np.radians(r))
factor += np.cos(np.radians(dec)) * np.sin(np.radians(r)) * np.cos(np.radians(theta))
dec_out = np.degrees(np.arcsin(factor))
y = np.sin(np.radians(theta)) * np.sin(np.radians(r)) * np.cos(np.radians(dec))
... | Translate a given point a distance r in the (initial) direction theta, along a great circle.
Parameters
----------
ra, dec : float
The initial point of interest (degrees).
r, theta : float
The distance and initial direction to translate (degrees).
Returns
-------
ra, dec ... |
348,252 | def challenge_auth(username, password, challenge, lower, digest=):
def hdig(x):
return fdigest(x).hexdigest()
fdigest = get_digest(digest)
luser = lower(username)
tpass = password[:10].encode("ascii")
hvalue = hdig("{0}:{1}".format(luser, hdig(tpass)).encode("ascii"))
bhvalue = hva... | Calculates quakenet's challenge auth hash
.. code-block:: python
>>> challenge_auth("mooking", "0000000000",
... "12345678901234567890123456789012", str.lower, "md5")
'2ed1a1f1d2cd5487d2e18f27213286b9' |
348,253 | def missing_property_names(self):
propname = lambda x: self.__prop_names__[x]
missing = []
for x in self.__required__:
propinfo = self.propinfo(propname(x))
null_type = False
if in propinfo:
type_info = propinfo[]
... | Returns a list of properties which are required and missing.
Properties are excluded from this list if they are allowed to be null.
:return: list of missing properties. |
348,254 | def _get_filesystem_path(self, url_path, basedir=settings.MEDIA_ROOT):
if url_path.startswith(settings.MEDIA_URL):
url_path = url_path[len(settings.MEDIA_URL):]
return os.path.normpath(os.path.join(basedir, url2pathname(url_path))) | Makes a filesystem path from the specified URL path |
348,255 | def set_post_mortem():
def ipython_post_mortem_debug(shell, etype, evalue, tb,
tb_offset=None):
post_mortem_excepthook(etype, evalue, tb)
ipython_shell = get_ipython()
ipython_shell.set_custom_exc((Exception,), ipython_post_mortem_debug) | Enable the post mortem debugging excepthook. |
348,256 | def delete_session(self, client_id):
try:
session = self._sessions[client_id][0]
except KeyError:
session = None
if session is None:
self.logger.debug("Delete session : session %s doesn't exist" % client_id)
return
self.l... | Delete an existing session data, for example due to clean session set in CONNECT
:param client_id:
:return: |
348,257 | def clear_integer_value(self):
if (self.get_integer_value_metadata().is_read_only() or
self.get_integer_value_metadata().is_required()):
raise NoAccess()
self.my_osid_object_form._my_map[] = \
self.get_integer_value_metadata().get_default_integer_values()... | stub |
348,258 | async def _get_person_json(self, id_, url_params=None):
url = self.url_builder(
,
dict(person_id=id_),
url_params=url_params or OrderedDict(),
)
data = await self.get_data(url)
return data | Retrieve raw person JSON by ID.
Arguments:
id_ (:py:class:`int`): The person's TMDb ID.
url_params (:py:class:`dict`): Any additional URL parameters.
Returns:
:py:class:`dict`: The JSON data. |
348,259 | def determine_opening_indent(indent_texts):
num_lines = len(indent_texts)
if num_lines < 1:
return 0
assert num_lines >= 1
first_line_indent = indent_texts[0][0]
if num_lines == 1:
return first_line_indent
assert num_lines >= 2
second_line_indent = indent_texts[1]... | Determine the opening indent level for a docstring.
The opening indent level is the indent level is the first non-zero indent
level of a non-empty line in the docstring.
Args:
indent_texts: The lines of the docstring as an iterable over 2-tuples
each containing an integer indent level ... |
348,260 | def device_statistics(fritz, args):
stats = fritz.get_device_statistics(args.ain)
print(stats) | Command that prints the device statistics. |
348,261 | def reminder_pdf(self, reminder_id):
return self._create_get_request(resource=REMINDERS, billomat_id=reminder_id, command=PDF) | Opens a pdf of a reminder
:param reminder_id: the reminder id
:return: dict |
348,262 | def ordereddict_push_front(dct, key, value):
d = OrderedDict()
d[key] = value
d.update(dct)
return d | Set a value at the front of an OrderedDict
The original dict isn't modified, instead a copy is returned |
348,263 | def holiday_name(self, value=None):
if value is not None:
try:
value = str(value)
except ValueError:
raise ValueError(
.format(value))
if in value:
raise ValueError(
... | Corresponds to IDD Field `holiday_name`
Args:
value (str): value for IDD Field `holiday_name`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid v... |
348,264 | def profile_function(self):
prof = cProfile.Profile()
prof.enable()
result = self._run_object(*self._run_args, **self._run_kwargs)
prof.disable()
prof_stats = pstats.Stats(prof)
prof_stats.calc_callees()
return {
: self._object_name,
... | Runs cProfile on a function. |
348,265 | def ripesha(msg):
ripe = hashlib.new()
ripe.update(hashlib.sha256(msg).digest())
return ripe | RIPEMD160(SHA256(msg)) -> HASH object |
348,266 | def _generate_class_comment(self, data_type):
if is_struct_type(data_type):
class_type =
elif is_union_type(data_type):
class_type =
else:
raise TypeError(t handle type %rThe `{}` {}.This class implements the `DBSerializable` protocol (serialize and... | Emits a generic class comment for a union or struct. |
348,267 | def get_current(self):
where = slice(self._oldest_frame_idx(), self._pos)
major_axis = pd.DatetimeIndex(deepcopy(self.date_buf[where]), tz=)
return pd.Panel(self.buffer.values[:, where, :], self.items,
major_axis, self.minor_axis, dtype=self.dtype) | Get a Panel that is the current data in view. It is not safe to persist
these objects because internal data might change |
348,268 | def _set_peripheral_update(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=peripheral_update.peripheral_update, is_container=, presence=False, yang_name="peripheral-update", rest_name="peripheral-update", parent=self, path_helper=self._path_helper, ex... | Setter method for peripheral_update, mapped from YANG variable /firmware/peripheral_update (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_peripheral_update is considered as a private
method. Backends looking to populate this variable should
do so via calling... |
348,269 | def history_table_min(self):
if len(self.history_min) > 0:
lens = len(self.history_min[0])
else:
lens = len(self._history_headers)
return pd.DataFrame(
data=self.history_min,
columns=self._history_headers[:lens]
).sort_index() | 区间交易历史的table |
348,270 | def readTFAM(fileName):
tfam = None
with open(fileName, ) as inputFile:
tfam = [
tuple(i.rstrip("\r\n").split("\t")) for i in inputFile.readlines()
]
tfam = np.array(tfam)
return tfam | Reads the TFAM file.
:param fileName: the name of the ``tfam`` file.
:type fileName: str
:returns: a representation the ``tfam`` file (:py:class:`numpy.array`). |
348,271 | def dlogpdf_dlink(self, link_f, y, Y_metadata=None):
c = np.zeros_like(y)
if Y_metadata is not None and in Y_metadata.keys():
c = Y_metadata[]
uncensored = (1-c)*(-1/link_f + y**self.r/link_f**2)
censored = c*y**self.r/link_f**2
g... | Gradient of the log likelihood function at y, given link(f) w.r.t link(f)
.. math::
\\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)} = \\beta (\\log \\beta y_{i}) - \\Psi(\\alpha_{i})\\beta\\\\
\\alpha_{i} = \\beta y_{i}
:param link_f: latent variables (f)
:type li... |
348,272 | def is_bot_the_only_committer(self, pr):
committer = self.provider.get_pull_request_committer(
self.user_repo,
pr)
committer_set = set([c.login for c in committer])
if self.integration or getattr(self.provider, , ) == :
return len(c... | Checks if the bot is the only committer for the given pull request.
:param update: Update to check
:return: bool - True if conflict found |
348,273 | def wash_url_argument(var, new_type):
out = []
if new_type == :
if isinstance(var, list):
out = var
else:
out = [var]
elif new_type == :
if isinstance(var, list):
try:
out = "%s" % var[0]
except:
... | Wash argument into 'new_type', that can be 'list', 'str',
'int', 'tuple' or 'dict'.
If needed, the check 'type(var) is not None' should be done before
calling this function.
@param var: variable value
@param new_type: variable type, 'list', 'str', 'int', 't... |
348,274 | def primaryKeys(self, table, catalog=None, schema=None):
fut = self._run_operation(self._impl.primaryKeys, table,
catalog=catalog, schema=schema)
return fut | Creates a result set of column names that make up the primary key
for a table by executing the SQLPrimaryKeys function. |
348,275 | def deployment_groups(self):
if not self.__deployment_groups:
self.__deployment_groups = DeploymentGroups(self.__connection)
return self.__deployment_groups | Gets the Deployment Groups API client.
Returns:
DeploymentGroups: |
348,276 | def Value(self, p):
if p < 0 or p > 1:
raise ValueError()
if p == 0: return self.xs[0]
if p == 1: return self.xs[-1]
index = bisect.bisect(self.ps, p)
if p == self.ps[index - 1]:
return self.xs[index - 1]
else:
return self.xs[... | Returns InverseCDF(p), the value that corresponds to probability p.
Args:
p: number in the range [0, 1]
Returns:
number value |
348,277 | def import_mv_grid_districts(self, session, mv_grid_districts_no=None):
if not all(isinstance(_, int) for _ in mv_grid_districts_no):
raise TypeError()
try:
srid = str(int(cfg_ding0.get(, )))
except OSError:
logger.exception()
... | Imports MV Grid Districts, HV-MV stations, Load Areas, LV Grid Districts
and MV-LV stations, instantiates and initiates objects.
Parameters
----------
session : sqlalchemy.orm.session.Session
Database session
mv_grid_districts : List of MV grid_districts/stations... |
348,278 | def main(router):
argv = sys.argv[1:]
if not len(argv):
print()
sys.exit(1)
delay = 2.0
select = mitogen.select.Select(oneshot=False)
hosts = []
for hostname in argv:
print(, hostname)
host = Host()
host.name = hostname
if ho... | Main program entry point. @mitogen.main() is just a helper to handle
reliable setup/destruction of Broker, Router and the logging package. |
348,279 | def assert_instance_deleted(self, model_class, **kwargs):
return _InstanceContext(
self.assert_instance_exists,
self.assert_instance_does_not_exist,
model_class,
**kwargs
) | Checks if the model instance was deleted from the database.
For example::
>>> with self.assert_instance_deleted(Article, slug='lorem-ipsum'):
... Article.objects.get(slug='lorem-ipsum').delete() |
348,280 | def _cached_pages(self, target_page=-1):
try:
self._pages_iter = self._pages_iter or self.doc.get_pages()
except AttributeError:
self._pages_iter = self._pages_iter or \
PDFPage.create_pages(self.doc)
if target_p... | Get a page or all pages from page generator, caching results.
This is necessary because PDFMiner searches recursively for pages,
so we won't know how many there are until we parse the whole document,
which we don't want to do until we need to. |
348,281 | def email_message(self):
url = settings.SITE_URL
hello_text = __("Hi %s," % self.to_user.get_full_name())
action_text = __("\n\nMore details here: %s") % url
explain_text = __(
"This is an automatic notification sent from from %s.\n"
"If you want to stop ... | compose complete email message text |
348,282 | def _parse_resolution(res):
if isinstance(res, str):
return float(res.strip())
if isinstance(res, (int, float)):
return float(res)
raise TypeError(.format(type(res))) | Helper method for parsing given resolution. It will also try to parse a string into float
:return: A float value of resolution
:rtype: float |
348,283 | def get_geotiff_area_def(filename, crs):
from osgeo import gdal
from pyresample.geometry import AreaDefinition
from pyresample.utils import proj4_str_to_dict
fid = gdal.Open(filename)
geo_transform = fid.GetGeoTransform()
pcs_id = fid.GetProjection().split()[1]
min_x = geo_transform[0]
... | Read area definition from a geotiff. |
348,284 | def get_sparse_lineups(df):
if (set(ALL_LINEUP_COLS) - set(df.columns)):
lineup_df = get_dense_lineups(df)
else:
lineup_df = df[ALL_LINEUP_COLS]
hm_lineups = lineup_df[HM_LINEUP_COLS].values
aw_lineups = lineup_df[AW_LINEUP_COLS].values
hm_df = pd.DataFrame([
... | TODO: Docstring for get_sparse_lineups.
:param df: TODO
:returns: TODO |
348,285 | def compile_regex(self, pattern, flags=0):
pattern_re = regex.compile()
while 1:
matches = [md.groupdict() for md in pattern_re.finditer(pattern)]
if len(matches) == 0:
break
for md in matches:
if md[] in self.pattern_dict:
... | Compile regex from pattern and pattern_dict |
348,286 | def _add_new(self, host_object):
i = self._get_insertion_point(host_object)
for listed in self[i:]:
if not listed.is_subdomain(host_object):
break
self.hosts.pop(i)
self.hosts.insert(i, host_object.to_unicode()) | Add a new host to the collection.
Before a new hostname can be added, all its subdomains already
present in the collection must be removed. Since the collection
is sorted, we can limit our search for them to a slice of
the collection starting from insertion point and ending with
... |
348,287 | def predict(self, X):
check_is_fitted(self, )
X = check_array(X, dtype=DTYPE, order="C")
score = self._decision_function(X)
if score.shape[1] == 1:
score = score.ravel()
return score | Predict risk scores.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The input samples.
Returns
-------
y : ndarray, shape = (n_samples,)
The risk scores. |
348,288 | def importRemoteGenome(name, batchSize = 100) :
try :
dw = listRemoteDatawraps()["Flat"]["Reference genomes"][name]
except AttributeError :
raise AttributeError("There%s'" % name)
finalFile = _DW(name, dw["url"])
PG.importGenome(finalFile, batchSize) | Import a genome available from http://pygeno.iric.ca (might work). |
348,289 | def dafrda(handle, begin, end):
handle = ctypes.c_int(handle)
begin = ctypes.c_int(begin)
end = ctypes.c_int(end)
data = stypes.emptyDoubleVector(1 + end.value - begin.value)
libspice.dafrda_c(handle, begin, end, data)
return stypes.cVectorToPython(data) | Read the double precision data bounded by two addresses within a DAF.
Deprecated: This routine has been superseded by :func:`dafgda` and
:func:`dafgsr`. This routine is supported for purposes of backward
compatibility only.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafrda_c.html
:p... |
348,290 | def putcolslice(self, columnname, value, blc, trc, inc=[],
startrow=0, nrow=-1, rowincr=1):
self._putcolslice(columnname, value, blc, trc, inc,
startrow, nrow, rowincr) | Put into a slice in a table column holding arrays.
Its arguments are the same as for getcolslice and putcellslice. |
348,291 | def init_db(db_path):
logger.info("Creating database")
with closing(connect_database(db_path)) as db:
with open(SCHEMA, ) as f:
db.cursor().executescript(f.read())
db.commit()
return | Build the sqlite database |
348,292 | def sum(self, callback=None):
if callback is None:
return sum(self.items)
callback = self._value_retriever(callback)
return self.reduce(lambda result, item: (result or 0) + callback(item)) | Get the sum of the given values.
:param callback: The callback
:type callback: callable or string or None
:rtype: mixed |
348,293 | def load(cls, folder):
popset = PopulationSet.load_hdf(os.path.join(folder,))
sigfile = os.path.join(folder,)
with open(sigfile, ) as f:
trsig = pickle.load(f)
return cls(trsig, popset, folder=folder) | Loads PopulationSet from folder
``popset.h5`` and ``trsig.pkl`` must exist in folder.
:param folder:
Folder from which to load. |
348,294 | def _identity(self, *args, **kwargs):
localremoteallpasswd -S -a
LOCAL =
EXT =
data = dict()
data[LOCAL] = self._get_local_users(disabled=kwargs.get())
data[EXT] = self._get_external_accounts(data[LOCAL].keys()) or
data[] = self._get_local_groups()
re... | Local users and groups.
accounts
Can be either 'local', 'remote' or 'all' (equal to "local,remote").
Remote accounts cannot be resolved on all systems, but only
those, which supports 'passwd -S -a'.
disabled
True (or False, default) to return only disabl... |
348,295 | def new_histogram(name, reservoir=None):
if reservoir is None:
reservoir = histogram.UniformReservoir(histogram.DEFAULT_UNIFORM_RESERVOIR_SIZE)
return new_metric(name, histogram.Histogram, reservoir) | Build a new histogram metric with a given reservoir object
If the reservoir is not provided, a uniform reservoir with the default size is used |
348,296 | def ParseLocalEntryRow(
self, parser_mediator, query, row, cache=None, database=None,
**unused_kwargs):
query_hash = hash(query)
inode_number = self._GetRowValue(query_hash, row, )
local_path = self.GetLocalPath(inode_number, cache, database)
event_data = GoogleDriveSnapshotLocalEntry... | Parses a local entry row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row.
cache (Optional[SQLiteCache]): cache.
database (Optional[... |
348,297 | def _parse_hosts(self, hosts):
if hosts is None:
return
hosts = [(host[0], int(host[1])) for host in hosts]
return tuple(hosts) | Return hosts parsed into a tuple of tuples.
:param hosts: String or list of hosts |
348,298 | def stop(self, timeout=None):
self._lock.acquire()
try:
if self._thread:
self._queue.put_nowait(self._terminator)
self._thread.join(timeout=timeout)
self._thread = None
finally:
self._lock.release() | Stops the task thread. Synchronous! |
348,299 | def list_platforms(server_url):
config = _get_asam_configuration(server_url)
if not config:
return False
url = config[]
data = {
: ,
}
auth = (
config[],
config[]
)
try:
html_content = _make_post_request(url, data, auth, verify=False)
... | To list all ASAM platforms present on the Novell Fan-Out Driver
CLI Example:
.. code-block:: bash
salt-run asam.list_platforms prov1.domain.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.