Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
340,000 | def discrimination_threshold(model, X, y, ax=None, n_trials=50, cv=0.1,
fbeta=1.0, argmax=, exclude=None,
quantiles=QUANTILES_MEDIAN_80, random_state=None,
**kwargs):
visualizer = DiscriminationThreshold(
model,... | Quick method for DiscriminationThreshold.
Visualizes how precision, recall, f1 score, and queue rate change as the
discrimination threshold increases. For probabilistic, binary classifiers,
the discrimination threshold is the probability at which you choose the
positive class over the negative. General... |
340,001 | def quotation(self, origin, target):
if not self._backend:
raise ExchangeBackendNotInstalled()
return self._backend.quotation(origin, target) | Return quotation between two currencies (origin, target) |
340,002 | def _set_interface_hello(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=interface_hello.interface_hello, is_container=, presence=False, yang_name="interface-hello", rest_name="hello", parent=self, path_helper=self._path_helper, extmethods=self._extme... | Setter method for interface_hello, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_hello (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_hello is considered as a private
method. Backends looking to populate this... |
340,003 | def readconf(conffile, section_name=None, log_name=None, defaults=None,
raw=False):
if defaults is None:
defaults = {}
if raw:
c = RawConfigParser(defaults)
else:
c = ConfigParser(defaults)
if hasattr(conffile, ):
c.readfp(conffile)
else:
if ... | Read config file and return config items as a dict
:param conffile: path to config file, or a file-like object (hasattr
readline)
:param section_name: config section to read (will return all sections if
not defined)
:param log_name: name to be used with logging (wi... |
340,004 | def get_cands_list_from_split(session, candidate_classes, doc, split):
cands = []
if split == ALL_SPLITS:
for candidate_class in candidate_classes:
cands.append(
session.query(candidate_class)
.filter(candidate_class.document_id == doc.id)
... | Return the list of list of candidates from this document based on the split. |
340,005 | def get_assign_annotation(node):
annotation = None
annotation_node = None
try:
annotation_node = node.annotation
except AttributeError:
annotation_node = getattr(node, "type_annotation", None)
if annotation_node:
if isinstance(annotation_node, astroid.nodes.Co... | Get the type annotation of the assignment of the given node.
:param node: The node to get the annotation for.
:type node: astroid.nodes.Assign or astroid.nodes.AnnAssign
:returns: The type annotation as a string, or None if one does not exist.
:type: str or None |
340,006 | def current_timestamp():
now = datetime.utcnow()
timestamp = now.isoformat()[0:19] +
debug("generated timestamp: {now}".format(now=timestamp))
return timestamp | Returns current time as ISO8601 formatted string in the Zulu TZ |
340,007 | def get_waiting_list(self, force=False):
code_lines = []
skip_autofield = self.options[]
for field in list(self.waiting_list):
try:
value = get_attribute_value(self.instance, field, self.context, force=force, skip_autofield=skip_au... | Add lines for any waiting fields that can be completed now. |
340,008 | def foreignkey(element, exceptions):
label = element.field.__dict__[]
try:
label = unicode(label)
except NameError:
pass
if (not label) or (label in exceptions):
return False
else:
return "_queryset" in element.field.__dict__ | function to determine if each select field needs a create button or not |
340,009 | def add_affect(self, name, src, dest, val, condition = None ):
self.affects.append(ParamAffects(name, src, dest, val, condition)) | adds how param 'src' affects param 'dest' to the list |
340,010 | def _is_version_range(req):
assert len(req.specifier) > 0
specs = list(req.specifier)
if len(specs) == 1:
return specs[0].operator !=
else:
return True | Returns true if requirements specify a version range. |
340,011 | def url_params(request, except_params=None, as_is=False):
if not request.GET:
return
params = []
for key, value in request.GET.items():
if except_params and key not in except_params:
for v in request.GET.getlist(key):
params.append( % (key, urlquote(v)))
... | create string with GET-params of request
usage example:
c['sort_url'] = url_params(request, except_params=('sort',))
...
<a href="{{ sort_url }}&sort=lab_number">Лабораторный номер</a> |
340,012 | def _seconds_to_HHMMSS(seconds):
less_than_second = seconds - floor(seconds)
minutes, seconds = divmod(floor(seconds), 60)
hours, minutes = divmod(minutes, 60)
return "{}H{}M{}S.{}".format(hours, minutes, seconds, less_than_second) | Retuns a string which is the hour, minute, second(milli) representation
of the intput `seconds`
Parameters
----------
seconds : float
Returns
-------
str
Has the form <int>H<int>M<int>S.<float> |
340,013 | def get_nth_bell_number(n):
import utool as ut
import scipy.special
@ut.memoize
def bell_(n):
if n < 2:
return 1
sum_ = 0
for k in range(1, n + 1):
sum_ = sum_ + scipy.special.binom(n - 1, k - 1) * bell_(k - 1)
return sum_
nth_bell = bell_... | Returns the (num_items - 1)-th Bell number using recursion.
The Bell numbers count the number of partitions of a set.
Args:
n (int): number of items in a set
Returns:
int:
References:
http://adorio-research.org/wordpress/?p=11460
CommandLine:
python -m utool.util_... |
340,014 | def drop_duplicates(self, keep="first", inplace=False, **kwargs):
inplace = validate_bool_kwarg(inplace, "inplace")
if kwargs.get("subset", None) is not None:
duplicates = self.duplicated(keep=keep, **kwargs)
else:
duplicates = self.duplicated(keep=keep, **... | Return DataFrame with duplicate rows removed, optionally only considering certain columns
Args:
subset : column label or sequence of labels, optional
Only consider certain columns for identifying duplicates, by
default use all of the columns
... |
340,015 | def psd(ts, nperseg=1500, noverlap=1200, plot=True):
ts = ts.squeeze()
if ts.ndim is 1:
ts = ts.reshape((-1, 1))
fs = (len(ts) - 1.0) / (ts.tspan[-1] - ts.tspan[0])
window = signal.hamming(nperseg, sym=False)
nfft = max(256, 2**np.int(np.log2(nperseg) + 1))
freqs, pxx = signal.welch... | plot Welch estimate of power spectral density, using nperseg samples per
segment, with noverlap samples overlap and Hamming window. |
340,016 | def delete(path, fatal=True, logger=LOG.debug):
islink = path and os.path.islink(path)
if not islink and (not path or not os.path.exists(path)):
return 0
if is_dryrun():
LOG.debug("Would delete %s", short(path))
return 1
if logger:
logger("Deleting %s", short(path)... | :param str|None path: Path to file or folder to delete
:param bool|None fatal: Abort execution on failure if True
:param callable|None logger: Logger to use
:return int: 1 if effectively done, 0 if no-op, -1 on failure |
340,017 | def get_conn(self):
db = self.get_connection(self.presto_conn_id)
reqkwargs = None
if db.password is not None:
reqkwargs = {: HTTPBasicAuth(db.login, db.password)}
return presto.connect(
host=db.host,
port=db.port,
username=db.logi... | Returns a connection object |
340,018 | def wait_for_package_sync(
ctx, opts, owner, repo, slug, wait_interval, skip_errors, attempts=3
):
attempts -= 1
click.echo()
label = "Synchronising %(package)s:" % {"package": click.style(slug, fg="green")}
status_str = "Waiting"
stage_str = None
def display_status(current):
... | Wait for a package to synchronise (or fail). |
340,019 | def find_netmiko_dir():
try:
netmiko_base_dir = os.environ["NETMIKO_DIR"]
except KeyError:
netmiko_base_dir = NETMIKO_BASE_DIR
netmiko_base_dir = os.path.expanduser(netmiko_base_dir)
if netmiko_base_dir == "/":
raise ValueError("/ cannot be netmiko_base_dir")
netmiko_ful... | Check environment first, then default dir |
340,020 | def activate(self, uid=None):
if uid is not None:
if not isinstance(uid, six.string_types):
raise TypeError("uid must be a string")
result = self.proxy.activate(uid)
status = result.result_status.value
if status == enums.ResultStat... | Activate a managed object stored by a KMIP appliance.
Args:
uid (string): The unique ID of the managed object to activate.
Optional, defaults to None.
Returns:
None
Raises:
ClientConnectionNotOpen: if the client connection is unusable
... |
340,021 | def start_node(self):
return db.cypher_query("MATCH (aNode) "
"WHERE id(aNode)={nodeid} "
"RETURN aNode".format(nodeid=self._start_node_id),
resolve_objects = True)[0][0][0] | Get start node
:return: StructuredNode |
340,022 | def tokenize(self, string):
if self.unit == UNIT_WORD:
return [token for token in string.replace("\n", " \n ").split(self.tokSep) if token != ""]
elif self.unit == UNIT_CHARACTER:
return string.decode(self.encoding)
else:
re... | Tokenizer utility.
When processing byte, outputs the string unaltered.
The character unit type is used for unicode data, the string is
decoded according to the encoding provided.
In the case of word unit, EOL characters are detached from the
preceding word, and outputs the list o... |
340,023 | def _AbortKill(self):
for pid, process in iter(self._processes_per_pid.items()):
if not process.is_alive():
continue
logger.warning(.format(
process.name, pid))
self._KillProcess(pid) | Aborts all registered processes by sending a SIGKILL or equivalent. |
340,024 | def get_driver(self, name, version):
user_credentials = self.get_user_credentials()
return discovery.build(
name, version,
http=self.authenticate(user_credentials)
) | Authenticates and creates new API driver to perform scope stuff
:param name: Name of driver
:param version: Version of driver
:return: driver |
340,025 | def aos_as_list(self):
return sorted(chain.from_iterable(
[self.aos[el] * int(self.composition[el]) for el in self.elements]
), key=lambda x: x[2]) | Returns a list of atomic orbitals, sorted from lowest to highest energy |
340,026 | def process_request_thread(self, mainthread):
life_time = time.time()
nb_requests = 0
while not mainthread.killed():
if self.max_life_time > 0:
if (time.time() - life_time) >= self.max_life_time:
mainthread.add_worker(1)
... | obtain request from queue instead of directly from server socket |
340,027 | def compact(self):
previous_value = object()
redundant = []
for time, value in self:
if value == previous_value:
redundant.append(time)
previous_value = value
for time in redundant:
del self[time] | Convert this instance to a compact version: the value will be the
same at all times, but repeated measurements are discarded. |
340,028 | def chunk_by(n, iterable, fillvalue=None):
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue) | Iterate over a given ``iterable`` by ``n`` elements at a time.
>>> for x, y in chunk_by(2, [1, 2, 3, 4, 5]):
... # iteration no 1: x=1, y=2
... # iteration no 2: x=3, y=4
... # iteration no 3: x=5, y=None
:param n: (int) a chunk size number
:param iterable: (iterator) an input ... |
340,029 | def add_hbar_widget(self, ref, x=1, y=1, length=10):
if ref not in self.widgets:
widget = widgets.HBarWidget(screen=self, ref=ref, x=x, y=y, length=length)
self.widgets[ref] = widget
return self.widgets[ref] | Add Horizontal Bar Widget |
340,030 | def open(self):
assert self.__context_refcount == 0
mayRaiseUSBError(libusb1.libusb_init(byref(self.__context_p)))
return self | Finish context initialisation, as is normally done in __enter__ .
This happens automatically on the first method call needing access to
the uninitialised properties, but with a warning.
Call this method ONLY if your usage pattern prevents you from using the
with USBContext() as cont... |
340,031 | def parse(self, data):
if self._initialized:
raise pycdlibexception.PyCdlibInternalError()
(self.unique_id, reserved_unused) = struct.unpack_from(self.FMT, data, 0)
self._initialized = True | Parse the passed in data into a UDF Logical Volume Header Descriptor.
Parameters:
data - The data to parse.
Returns:
Nothing. |
340,032 | def broadcast_signed_transaction(unsigned_tx, signatures, pubkeys, coin_symbol=, api_key=None):
assert not in unsigned_tx, unsigned_tx
assert api_key,
url = make_url(coin_symbol, **dict(txs=))
data = unsigned_tx.copy()
data[] = signatures
data[] = pubkeys
params = {: api_key}
... | Broadcasts the transaction from create_unsigned_tx |
340,033 | def _set_community(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=community.community, is_container=, presence=False, yang_name="community", rest_name="community", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_path... | Setter method for community, mapped from YANG variable /routing_system/route_map/content/set/community (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_community is considered as a private
method. Backends looking to populate this variable should
do so via cal... |
340,034 | def receive(xpub, callback, api_key):
params = {: xpub, : api_key, : callback}
resource = + util.urlencode(params)
resp = util.call_api(resource, base_url=)
json_resp = json.loads(resp)
payment_response = ReceiveResponse(json_resp[],
json_resp[],
... | Call the '/v2/receive' endpoint and create a forwarding address.
:param str xpub: extended public key to generate payment address
:param str callback: callback URI that will be called upon payment
:param str api_key: Blockchain.info API V2 key
:return: an instance of :class:`ReceiveResponse` class |
340,035 | def create_temp_user_avatar(self,
user,
filename,
size,
avatar_img,
contentType=None,
auto_confirm=False,
... | Register an image file as a user avatar.
The avatar created is temporary and must be confirmed before it can
be used.
Avatar images are specified by a filename, size, and file object. By default, the client will attempt to
autodetect the picture's content type: this mechanism relies on... |
340,036 | def attribute_checker(operator, attribute, value=):
return {
: lambda el: el.get(attribute) == value,
: lambda el: value in el.get(attribute, ).split(),
: lambda el: el.get(attribute, ).startswith(value),
: lambda el: el.get(attribute, ).endswith(value... | Takes an operator, attribute and optional value; returns a function that
will return True for elements that match that combination. |
340,037 | def get_vnetwork_hosts_output_instance_id(self, **kwargs):
config = ET.Element("config")
get_vnetwork_hosts = ET.Element("get_vnetwork_hosts")
config = get_vnetwork_hosts
output = ET.SubElement(get_vnetwork_hosts, "output")
instance_id = ET.SubElement(output, "instance-i... | Auto Generated Code |
340,038 | def import_model(self, source):
if not hasattr(source, ):
with open(self._resolve_source(source), ) as f:
return self._import(f)
else:
return self._import(source) | Import and return model instance. |
340,039 | def is_decorated_with_attrs(node, decorator_names=ATTRS_NAMES):
if not node.decorators:
return False
for decorator_attribute in node.decorators.nodes:
if isinstance(decorator_attribute, astroid.Call):
decorator_attribute = decorator_attribute.func
if decorator_attribut... | Return True if a decorated node has
an attr decorator applied. |
340,040 | def set_distributions(self):
distributions = etree.SubElement(self.bnmodel, )
cpds = self.model.get_cpds()
cpds.sort(key=lambda x: x.variable)
for cpd in cpds:
cpd_values = cpd.values.ravel()
var = cpd.variable
dist = etree.SubElement(distrib... | Set distributions in the network.
Examples
--------
>>> from pgmpy.readwrite.XMLBeliefNetwork import XBNWriter
>>> writer =XBNWriter()
>>> writer.set_distributions() |
340,041 | def is_constrained_reaction(model, rxn):
lower_bound, upper_bound = helpers.find_bounds(model)
if rxn.reversibility:
return rxn.lower_bound > lower_bound or rxn.upper_bound < upper_bound
else:
return rxn.lower_bound > 0 or rxn.upper_bound < upper_bound | Return whether a reaction has fixed constraints. |
340,042 | def calculate_size(name, replace_existing_values):
data_size = 0
data_size += calculate_size_str(name)
data_size += BOOLEAN_SIZE_IN_BYTES
return data_size | Calculates the request payload size |
340,043 | def _init_glyph(self, plot, mapping, properties, key):
properties.pop(, None)
if key == :
properties.pop()
arrow_end = mapping.pop()
arrow_start = mapping.pop()
start = arrow_start(**properties) if arrow_start else None
end = arrow_end... | Returns a Bokeh glyph object. |
340,044 | def bootstrap(self, path_or_uri):
_logger.debug("Bootstrapping new database: %s", path_or_uri)
self.database_uri = _urify_db(path_or_uri)
db = sa.create_engine(self.database_uri)
Base.metadata.create_all(db) | Initialize a database.
:param database_path: The absolute path to the database to initialize. |
340,045 | def group_join(
self,
inner_enumerable,
outer_key=lambda x: x,
inner_key=lambda x: x,
result_func=lambda x: x
):
if not isinstance(inner_enumerable, Enumerable):
raise TypeError(
u"inner enumerable parameter mus... | Return enumerable of group join between two enumerables
:param inner_enumerable: inner enumerable to join to self
:param outer_key: key selector of outer enumerable as lambda expression
:param inner_key: key selector of inner enumerable as lambda expression
:param result_func: lambda exp... |
340,046 | def OMList(self, l):
| Convert a list of OM objects into an OM object
EXAMPLES::
>>> from openmath import openmath as om
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
>>> o = converter.OMList([om.OMInteger(2), om.OMInteger(2)]); o
... |
340,047 | def getreference(self, validate=True):
if self.offset is None: return None
if self.ref:
ref = self.doc[self.ref]
else:
ref = self.finddefaultreference()
if not ref:
raise UnresolvableTextContent("Default reference for textcontent not found!... | Returns and validates the Text Content's reference. Raises UnresolvableTextContent when invalid |
340,048 | def recursively_compute_variable(self, var, start_date=None, end_date=None,
time_offset=None, model=None,
**DataAttrs):
if var.variables is None:
return self._load_or_get_from_model(
var, start_date, e... | Compute a variable recursively, loading data where needed.
An obvious requirement here is that the variable must eventually be
able to be expressed in terms of model-native quantities; otherwise the
recursion will never stop.
Parameters
----------
var : Var
... |
340,049 | def _update_globals(kids, xmlglobals):
for child in kids:
key = child.tag.lower()
if key != "defaults":
if key not in xmlglobals:
xmlglobals[key] = {}
if "identifier" in child.attrib:
xmlglobals[key][child.attrib["identifier"]] = child
... | Updates the specified 'xmlglobals' dictionary with the specific
*and* supported global tag definitions. |
340,050 | def env(*args, **kwargs):
for arg in args:
value = os.environ.get(arg, None)
if value:
return value
return kwargs.get("default", "") | Returns the first environment variable set
if none are non-empty, defaults to "" or keyword arg default |
340,051 | def copy_uri_options(hosts, mongodb_uri):
if "?" in mongodb_uri:
options = mongodb_uri.split("?", 1)[1]
else:
options = None
uri = "mongodb://" + hosts
if options:
uri += "/?" + options
return uri | Returns a MongoDB URI to hosts with the options from mongodb_uri. |
340,052 | def Clear(self):
headers = {: }
response, _ = self._http.request( % self._host, method=,
headers=headers)
if response.status == 200:
return True
else:
logging.warning(, response) | Clears all data from the emulator instance.
Returns:
True if the data was successfully cleared, False otherwise. |
340,053 | def parse_yes_no_str(bool_str):
lower_bool_str = bool_str.lower()
if lower_bool_str == :
return False
elif lower_bool_str == :
return True
else:
raise ValueError( % bool_str) | Parse a string serialization of boolean data as yes (Y) or no (N).
Prase a string serialization of boolean data where True is "Y" and False is
"N" case-insensitive.
@param bool_str: The string to parse.
@type bool_str: str
@return: The interpreted string.
@rtype: bool
@raise ValueError: Ra... |
340,054 | def process_request(self, request):
referer_url = request.META.get()
return_to_index_url = request.session.get()
try:
if all((
return_to_index_url,
referer_url,
request.method == ,
not request.is_ajax(),
... | Ignore unnecessary actions for static file requests, posts, or ajax
requests. We're only interested in redirecting following a 'natural'
request redirection to the `wagtailadmin_explore_root` or
`wagtailadmin_explore` views. |
340,055 | def load(self, data, context=None):
errors_builder = ValidationErrorBuilder()
for validator in self.validators:
try:
validator(data, context)
except ValidationError as ve:
errors_builder.add_errors(ve.messages)
errors_builder.raise... | Deserialize data from primitive types. Raises
:exc:`~lollipop.errors.ValidationError` if data is invalid.
:param data: Data to deserialize.
:param context: Context data.
:returns: Loaded data
:raises: :exc:`~lollipop.errors.ValidationError` |
340,056 | def _single_load(self, addr, offset, size, inspect=True, events=True):
try:
d = self._contents[addr]
except KeyError:
d = self._handle_uninitialized_read(addr, inspect=inspect, events=events)
self._contents[addr] = d
if offset == 0 and size == self.w... | Performs a single load. |
340,057 | def process_loop_funcs(self, comp_n, loop_node):
if isinstance(comp_n, ast.Call) and get_call_names_as_string(comp_n.func) in self.function_names:
last_node = self.visit(comp_n)
last_node.connect(loop_node) | If the loop test node contains function calls, it connects the loop node to the nodes of
those function calls.
:param comp_n: The test node of a loop that may contain functions.
:param loop_node: The loop node itself to connect to the new function nodes if any
:return: None |
340,058 | def generate_docs(app):
config = app.config
config_dir = app.env.srcdir
javascript_root = os.path.join(config_dir, config.jsdoc_source_root)
if javascript_root[-1] != os.path.sep:
javascript_root += os.path.sep
if not javascript_root:
return
output_root = os.path.join(c... | Generate the reST documentation files for the JavaScript code |
340,059 | def fastalite(handle):
Seq = namedtuple(, [, , ])
header, seq = , []
for line in handle:
if line.startswith():
if header:
yield Seq(header.split()[0], header, .join(seq))
header, seq = line[1:].strip(), []
else:
seq.append(line.strip... | Return a sequence of namedtuple objects from a fasta file with
attributes (id, description, seq) given open file-like object
``handle`` |
340,060 | def validation_tween_factory(handler, registry):
settings = load_settings(registry)
route_mapper = registry.queryUtility(IRoutesMapper)
validation_context = _get_validation_context(registry)
def validator_tween(request):
route_info = route_mapper(request)
... | Pyramid tween for performing validation.
Note this is very simple -- it validates requests, responses, and paths
while delegating to the relevant matching view. |
340,061 | def objLon(ID, chart):
if ID.startswith():
ID = ID[2:]
obj = chart.get(ID)
rulerID = essential.ruler(obj.sign)
ruler = chart.getObject(rulerID)
return ruler.lon
elif ID.startswith():
return partLon(ID, chart)
else:
obj =... | Returns the longitude of an object. |
340,062 | def im_detect(rois, scores, bbox_deltas, im_info,
bbox_stds, nms_thresh, conf_thresh):
rois = rois.asnumpy()
scores = scores.asnumpy()
bbox_deltas = bbox_deltas.asnumpy()
im_info = im_info.asnumpy()
height, width, scale = im_info
pred_boxes = bbox_pred(rois, bbox_deltas... | rois (nroi, 4), scores (nrois, nclasses), bbox_deltas (nrois, 4 * nclasses), im_info (3) |
340,063 | def k2a(a, x):
func, scale = None, 1
t = abs(x._t)
if 12 <= t <= 15:
unit = get_unit(a)
attr, shift, func, scale = _UNIT[unit]
a[:] = getattr(x, attr).data
a += shift
elif 16 <= t <= 19:
unit = get_unit(a)
func, scale = _SCALE[unit]
... | Rescale data from a K object x to array a. |
340,064 | def set_float(self, option, value):
if not isinstance(value, float):
raise TypeError("Value must be a float")
self.options[option] = value | Set a float option.
Args:
option (str): name of option.
value (float): value of the option.
Raises:
TypeError: Value must be a float. |
340,065 | def exists(self, client=None):
client = self._require_client(client)
try:
client.metrics_api.metric_get(self.project, self.name)
except NotFound:
return False
else:
return True | API call: test for the existence of the metric via a GET request
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/get
:type client: :class:`~google.cloud.logging.client.Client` or
``NoneType``
:param client: the client to use. If n... |
340,066 | def addSubsequenceOfFeature(self, parentid):
self.graph.addTriple(self.fid, self.globaltt[], parentid)
self.graph.addTriple(parentid, self.globaltt[], self.fid)
return | This will add reciprocal triples like:
feature <is subsequence of> parent
parent has_subsequence feature
:param graph:
:param parentid:
:return: |
340,067 | def createFromFile(self, sid, filename):
urls = []
with open(filename) as f:
for line in f:
for url in line.split():
urls.append(url)
return self.create(sid, tuple(urls)) | Create a new named (sid) Seed from a file containing URLs
It's assumed URLs are whitespace seperated.
:param sid: the name to assign to the new seed list
:param filename: the name of the file that contains URLs
:return: the created Seed object |
340,068 | def visit_evaluationsection(self, layout):
self.section += 1
self.format_children(layout)
self.section -= 1
self.writeln() | Display an evaluation section as a text. |
340,069 | def _execute(self, action, parameters, attempt, measurements):
future = concurrent.Future()
start = time.time()
def handle_response(request):
self._on_response(
action, parameters.get(, ), attempt,
start, request, future, measure... | Invoke a DynamoDB action
:param str action: DynamoDB action to invoke
:param dict parameters: parameters to send into the action
:param int attempt: Which attempt number this is
:param list measurements: A list for accumulating request measurements
:rtype: tornado.concurrent.Fut... |
340,070 | def generate_null_snvs(df, snvs, num_null_sets=5):
import numpy as np
import random
random.seed(20151007)
input_snvs = list(set(df.index) & set(snvs))
sig = df.ix[input_snvs]
not_sig = df.ix[set(df.index) - set(snvs)]
sig[] = sig.apply(lambda x: .join(x), axis=1)
not_sig[] = not_sig... | Generate a set of null SNVs based on an input list of SNVs and categorical
annotations.
Parameters
----------
df : pandas.DataFrame
Pandas dataframe where each column is a categorization of SNPs.
The index should be SNPs of the form chrom:pos.
snvs : list
List... |
340,071 | def safe_mkdir(path, uid=-1, gid=-1):
try:
os.mkdir(path)
except OSError as e:
if e.errno == errno.EEXIST:
pass
else:
raise
else:
os.chown(path, uid, gid) | create path if it doesn't exist |
340,072 | def infer_paths(output_dir, **subdirs):
directories = {}
for name, path in six.iteritems(subdirs):
directories[name] = path if path else os.path.join(output_dir, name)
directories["output_dir"] = output_dir
return directories | Infers standard paths to policy and model directories.
Example:
>>> infer_paths("/some/output/dir/", policy="", model="custom/path")
{"policy": "/some/output/dir/policy", "model": "custom/path",
"output_dir":"/some/output/dir/"}
Args:
output_dir: output directory.
**subdirs: sub-directories.
... |
340,073 | def openFiles(self, fileNames=None, rtiRegItem=None, caption=None, fileMode=None):
if fileNames is None:
dialog = QtWidgets.QFileDialog(self, caption=caption)
if rtiRegItem is None:
nameFilter =
nameFilter += self.argosApplication.rtiRegistry.g... | Lets the user select on or more files and opens it.
:param fileNames: If None an open-file dialog allows the user to select files,
otherwise the files are opened directly.
:param rtiRegItem: Open the files as this type of registered RTI. None=autodetect.
:param capti... |
340,074 | def _FlowProcessingRequestHandlerLoop(self, handler):
while not self.flow_processing_request_handler_stop:
try:
msgs = self._LeaseFlowProcessingReqests()
if msgs:
for m in msgs:
self.flow_processing_request_handler_pool.AddTask(
target=handler, args=(... | The main loop for the flow processing request queue. |
340,075 | def get(key, default=-1):
if isinstance(key, int):
return TOS_REL(key)
if key not in TOS_REL._member_map_:
extend_enum(TOS_REL, key, default)
return TOS_REL[key] | Backport support for original codes. |
340,076 | def fetchone(self):
self._check_executed()
if self._rows is None or self.rownumber >= len(self._rows):
return None
result = self._rows[self.rownumber]
self.rownumber += 1
return result | Fetch the next row |
340,077 | def read_version(group):
version = ( if not in group.attrs
else group.attrs[])
if isinstance(version, bytes):
version = version.decode()
if not is_supported_version(version):
raise IOError(.format(version))
return version | Return the h5features version of a given HDF5 `group`.
Look for a 'version' attribute in the `group` and return its
value. Return '0.1' if the version is not found. Raises an IOError
if it is not supported. |
340,078 | def binary(self):
creation_size = len(self.creation)
if creation_size == 1:
return (
b_chr(_TAG_PORT_EXT) +
self.node.binary() + self.id + self.creation
)
elif creation_size == 4:
return (
b_chr(_TAG_NEW... | return encoded representation |
340,079 | def get_class(class_string):
split_string = class_string.encode().split()
import_path = .join(split_string[:-1])
class_name = split_string[-1]
if class_name:
try:
if import_path:
mod = __import__(import_path, globals(), {}, [class_name])
cls = ge... | Get a class from a dotted string |
340,080 | def get_all_breakpoints(self):
bplist = list()
for (pid, bp) in self.get_all_code_breakpoints():
bplist.append( (pid, None, bp) )
for (pid, bp) in self.get_all_page_breakpoints():
bplist.append( (pid, None, bp) )
for (tid, bp... | Returns all breakpoint objects as a list of tuples.
Each tuple contains:
- Process global ID to which the breakpoint applies.
- Thread global ID to which the breakpoint applies, or C{None}.
- The L{Breakpoint} object itself.
@note: If you're only interested in a specific bre... |
340,081 | def get_safe_format(product_id=None, tile=None, entire_product=False, bands=None, data_source=DataSource.SENTINEL2_L1C):
entire_product = entire_product and product_id is None
if tile is not None:
safe_tile = SafeTile(tile_name=tile[0], time=tile[1], bands=bands, data_source=data_source)
if... | Returns .SAFE format structure in form of nested dictionaries. Either ``product_id`` or ``tile`` must be specified.
:param product_id: original ESA product identification string. Default is ``None``
:type product_id: str
:param tile: tuple containing tile name and sensing time/date. Default is ``None``
... |
340,082 | def accepts_manager_roles(func):
if inspect.isclass(func):
apply_function_to_members(func, accepts_manager_roles)
return func
else:
@functools.wraps(func)
def decorator(*args, **kwargs):
return accepts_roles(*ROLES_MANAGER)(func)(*args, **kwargs)
return ... | Decorator that accepts only manager roles
:param func:
:return: |
340,083 | def _get_comments_to_export(self, last_export_id=None):
qs = comments.get_model().objects.order_by()\
.filter(is_public=True, is_removed=False)
if last_export_id is not None:
print("Resuming after comment %s" % str(last_export_id))
qs = qs.filter(id__gt=l... | Return comments which should be exported. |
340,084 | def m2m_callback(sender, instance, action, reverse, model, pk_set, using, **kwargs):
if validate_instance(instance) and settings.AUTOMATED_LOGGING[]:
if action in ["post_add", ]:
modification = [model.objects.get(pk=x) for x in pk_set]
if in instance.__dict__.keys() and instan... | Many 2 Many relationship signall receivver.
Detect Many 2 Many relationship changes and append these to existing model or create if needed.
These get not recorded from the pre_save or post_save method and must therefor be received from
another method. This method to be precise. |
340,085 | def get_count(self, ngram, corpus=None):
r
if not corpus:
corpus = self.ngcorpus
if not ngram:
return corpus[None]
if isinstance(ngram, (text_type, str)):
ngram = text_type(ngram).split()
if ngram... | r"""Get the count of an n-gram in the corpus.
Parameters
----------
ngram : str
The n-gram to retrieve the count of from the n-gram corpus
corpus : Corpus
The corpus
Returns
-------
int
The n-gram count
Examples
... |
340,086 | def igetattr(self, name, context=None):
if not context:
context = contextmod.InferenceContext()
try:
if context.push((self._proxied, name)):
raise exceptions.InferenceError(
message="Cannot infer the same attribute again",... | inferred getattr |
340,087 | def getSRegNS(message):
for sreg_ns_uri in [ns_uri_1_1, ns_uri_1_0]:
alias = message.namespaces.getAlias(sreg_ns_uri)
if alias is not None:
break
else:
sreg_ns_uri = ns_uri_1_1
try:
message.namespaces.addAlias(ns_uri_1_1, )... | Extract the simple registration namespace URI from the given
OpenID message. Handles OpenID 1 and 2, as well as both sreg
namespace URIs found in the wild, as well as missing namespace
definitions (for OpenID 1)
@param message: The OpenID message from which to parse simple
registration fields. ... |
340,088 | def post(self, request, *args, **kwargs):
url = request.POST.get()
if not url:
return self.get(request, *args, **kwargs)
entry = self.get_object()
site = Site.objects.get_current()
if not entry.trackbacks_are_open:
return self.render_to_respons... | Check if an URL is provided and if trackbacks
are enabled on the Entry.
If so the URL is registered one time as a trackback. |
340,089 | def child_get(self, child, *prop_names):
return [self.child_get_property(child, name) for name in prop_names] | Returns a list of child property values for the given names. |
340,090 | def all_project_administrators(self):
for project in self.project_list():
log.info(.format(project.get(), project.get()))
yield {
: project.get(),
: project.get(),
: [{: x[], : x[]}
for x ... | Get the list of project administrators
:return: |
340,091 | def scan_used_functions(example_file, gallery_conf):
example_code_obj = identify_names(example_file)
if example_code_obj:
codeobj_fname = example_file[:-3] +
with open(codeobj_fname, ) as fid:
pickle.dump(example_code_obj, fid, pickle.HIGHEST_PROTOCOL)
_replace_md5(code... | save variables so we can later add links to the documentation |
340,092 | def geojson_to_dict_list(data):
if type(data) in (list, dict):
return data
try:
with open(data, ) as f:
features = json.load(f)[]
except IOError:
features = requests.get(data).json()[]
except:
raise SourceDataError()
return [fe... | Parse GeoJSON-formatted information in <data> to list of Python dicts |
340,093 | def set_default_locators_and_formatters(self, axis):
axis.set_major_locator(_LogicleLocator(self._transform))
axis.set_minor_locator(_LogicleLocator(self._transform,
subs=np.arange(2.0, 10.)))
axis.set_major_formatter(matplotlib.ticker.LogF... | Set up the locators and formatters for the scale.
Parameters
----------
axis: matplotlib.axis
Axis for which to set locators and formatters. |
340,094 | def _build(self, parent_cache):
for key, mice in parent_cache.cache.items():
if not mice.damaged_by_cut(self.subsystem):
self.cache[key] = mice | Build the initial cache from the parent.
Only include the |MICE| which are unaffected by the subsystem cut.
A |MICE| is affected if either the cut splits the mechanism
or splits the connections between the purview and mechanism |
340,095 | def apod(date=None, concept_tags=None):
base_url = "https://api.nasa.gov/planetary/apod?"
if date:
try:
vali_date(date)
base_url += "date=" + date + "&"
except:
raise ValueError("Incorrect date format, should be YYYY-MM-DD")
if concept_tags == True:
... | HTTP REQUEST
GET https://api.nasa.gov/planetary/apod
QUERY PARAMETERS
Parameter Type Default Description
date YYYY-MM-DD today The date of the APOD image to retrieve
concept_tags bool False Return an ordered dictionary of concepts from the APOD explanation
api_key string DEMO_KEY api.nasa.gov... |
340,096 | def chugid(runas, group=None):
uinfo = pwd.getpwnam(runas)
supgroups = []
supgroups_seen = set()
if group:
try:
target_pw_gid = grp.getgrnam(group).gr_gid
except KeyError as err:
raise CommandExecutionError(
.format(
group... | Change the current process to belong to the specified user (and the groups
to which it belongs) |
340,097 | def del_value(self, keys, complete=False, on_projects=False,
on_globals=False, projectname=None, base=, dtype=None,
**kwargs):
config = self.info(complete=complete, on_projects=on_projects,
on_globals=on_globals, projectname=projectname,
... | Delete a value in the configuration
Parameters
----------
keys: list of str
A list of keys to be deleted. %(get_value_note)s
%(ModelOrganizer.info.common_params)s
base: str
A base string that shall be put in front of each key in `values` to
av... |
340,098 | def __call(self, uri, params=None, method="get"):
try:
resp = self.__get_response(uri, params, method, False)
rjson = resp.json(**self.json_options)
assert resp.ok
except AssertionError:
msg = "OCode-{}: {}".format(resp.status_code, rjson["message... | Only returns the response, nor the status_code |
340,099 | def load_config(path=None, config=None, context=None):
given_config = config or {}
config = {}
config_sources = [
given_config,
can.rc,
lambda _context: load_environment_config(),
lambda _context: load_file_config(path, _context)
]
for cfg in ... | Returns a dict with configuration details which is loaded from (in this order):
- config
- can.rc
- Environment variables CAN_INTERFACE, CAN_CHANNEL, CAN_BITRATE
- Config files ``/etc/can.conf`` or ``~/.can`` or ``~/.canrc``
where the latter may add or replace values of the former.
Interface... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.