Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
384,000 | def t_ARTICLEHEADER(self, token):
ur
number = token.lexer.lexmatch.group("number").decode("utf8")
newtag = token.lexer.lexmatch.group("newtag").decode("utf8")
oldtag = token.lexer.lexmatch.group("oldtag").decode("utf8")
name = token.lexer.lexmatch.group("name").decode("u... | ur'\#\#\s+<article-(?P<number>[A-Z0-9]+)><(?P<newtag>[a-zA-Z0-9-]+)><(?P<oldtag>[a-zA-Z0-9-]+)>[ ]*(?P<name>[^\<]+?)(?P<sep>:\s|\xef\xbc\x9a)(?P<title>[^<\n]+)\n |
384,001 | def _dispatch(self, textgroup, directory):
self.dispatcher.dispatch(textgroup, path=directory) | Sparql dispatcher do not need to dispatch works, as the link is DB stored through Textgroup
:param textgroup: A Textgroup object
:param directory: The path in which we found the textgroup
:return: |
384,002 | def get_page(self, target_url):
response = self._version.domain.twilio.request(
,
target_url,
)
return SyncListPage(self._version, response, self._solution) | Retrieve a specific page of SyncListInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of SyncListInstance
:rtype: twilio.rest.sync.v1.service.sync_list.SyncListPage |
384,003 | def connections(self):
if not self.__connections:
self.__connections = Connections(
self.__connection)
return self.__connections | Gets the Connections API client.
Returns:
Connections: |
384,004 | def find_py_files(srctree, ignore=None):
if not os.path.isdir(srctree):
yield os.path.split(srctree)
for srcpath, _, fnames in os.walk(srctree):
if ignore is not None and ignore in srcpath:
continue
for fname in (x for x in fname... | Return all the python files in a source tree
Ignores any path that contains the ignore string
This is not used by other class methods, but is
designed to be used in code that uses this class. |
384,005 | def auto_newline(buffer):
r
insert_text = buffer.insert_text
if buffer.document.current_line_after_cursor:
insert_text()
else:
current_line = buffer.document.current_line_before_cursor.rstrip()
insert_text()
unindent = current_line.rstrip().en... | r"""
Insert \n at the cursor position. Also add necessary padding. |
384,006 | def save_weights_from_checkpoint(input_checkpoint, output_path, conv_var_names=None, conv_transpose_var_names=None):
check_input_checkpoint(input_checkpoint)
with tf.Session() as sess:
restore_from_checkpoint(sess, input_checkpoint)
save_weights(sess, output_path, conv_var_names=conv_var_n... | Save the weights of the trainable variables given a checkpoint, each one in a different file in output_path. |
384,007 | def compile(self, source, dest, is_two_file=True, post=None, lang=None):
makedirs(os.path.dirname(dest))
with io.open(dest, "w+", encoding="utf8") as out_file:
with io.open(source, "r", encoding="utf8") as in_file:
data = in_file.read()
data, shortcode_de... | Compile the docstring into HTML and save as dest. |
384,008 | def create_cookie(host, path, secure, expires, name, value):
return http.cookiejar.Cookie(0, name, value, None, False, host, host.startswith(), host.startswith(), path,
True, secure, expires, False, None, None, {}) | Shortcut function to create a cookie |
384,009 | def ellipticity(self):
eig = np.linalg.eig(self.field_hessian)
eig.sort()
return eig[0]/eig[1] - 1 | Most meaningful for bond critical points,
can be physically interpreted as e.g. degree
of pi-bonding in organic molecules. Consult
literature for more information.
:return: |
384,010 | def getParameters(self, emailAddress):
if emailAddress is not None:
address = emailAddress.address
else:
address = u
return [
liveform.Parameter(, liveform.TEXT_INPUT,
_normalizeWhitespace, ,
... | Return a C{list} of one L{LiveForm} parameter for editing an
L{EmailAddress}.
@type emailAddress: L{EmailAddress} or C{NoneType}
@param emailAddress: If not C{None}, an existing contact item from
which to get the email address default value.
@rtype: C{list}
@return:... |
384,011 | def remove_service(self, service):
uid = api.get_uid(service)
services = self.getAnalyses()
num_services = len(services)
services = [item for item in services
if item.get("service_uid", "") != uid]
removed = len(services) < num_services
... | Removes the service passed in from the services offered by the
current Template. If the Analysis Service passed in is not assigned to
this Analysis Template, returns False.
:param service: the service to be removed from this AR Template
:type service: AnalysisService
:return: Tru... |
384,012 | def _get_on_trixel_sources_from_database_query(
self):
self.log.debug(
)
tableName = self.tableName
raCol = self.raCol
decCol = self.decCol
radiusArc = self.radius
radius = self.radius / (60. * 60.)
trixelArray = self._g... | *generate the mysql query before executing it* |
384,013 | def purge_bucket(context, provider, **kwargs):
session = get_session(provider.region)
if kwargs.get():
bucket_name = kwargs[]
else:
if kwargs.get():
value = kwargs[]
handler = OutputLookup.handle
elif kwargs.get():
value = kwargs[]
... | Delete objects in bucket. |
384,014 | def code_to_session(self, js_code):
return self._get(
,
params={
: self.appid,
: self.secret,
: js_code,
:
}
) | 登录凭证校验。通过 wx.login() 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。更多使用方法详见 小程序登录
详情请参考
https://developers.weixin.qq.com/miniprogram/dev/api/code2Session.html
:param js_code:
:return: |
384,015 | def sample(self, bqm, chain_strength=1.0, chain_break_fraction=True, **parameters):
child = self.child
__, __, target_adjacency = child.structure
embedding = self.embedding
bqm_embedded = embed_bqm(bqm, embedding, target_adjacency,
... | Sample from the provided binary quadratic model.
Also set parameters for handling a chain, the set of vertices in a target graph that
represents a source-graph vertex; when a D-Wave system is the sampler, it is a set
of qubits that together represent a variable of the binary quadratic model bei... |
384,016 | def register(self, model, index_cls=AlgoliaIndex, auto_indexing=None):
if self.is_registered(model):
raise RegistrationError(
.format(model))
if not issubclass(index_cls, AlgoliaIndex):
raise RegistrationError(
.format(i... | Registers the given model with Algolia engine.
If the given model is already registered with Algolia engine, a
RegistrationError will be raised. |
384,017 | def get_homepath(self, ignore_session=False, force_cookieless=False):
if not ignore_session and self._session.get("session_id") is not None and self._session.get("cookieless", False):
return web.ctx.homepath + "/@" + self._session.get("session_id") + "@"
elif not ignore_session and ... | :param ignore_session: Ignore the cookieless session_id that should be put in the URL
:param force_cookieless: Force the cookieless session; the link will include the session_creator if needed. |
384,018 | def hilite(s, ok=True, bold=False):
if not term_supports_colors():
return s
attr = []
if ok is None:
pass
elif ok:
attr.append()
else:
attr.append()
if bold:
attr.append()
return % (.join(attr), s) | Return an highlighted version of 'string'. |
384,019 | def overwrite(self, bs, pos=None):
bs = Bits(bs)
if not bs.len:
return
if pos is None:
try:
pos = self._pos
except AttributeError:
raise TypeError("overwrite require a bit position for this type.")
if pos < 0:
... | Overwrite with bs at bit position pos.
bs -- The bitstring to overwrite with.
pos -- The bit position to begin overwriting from.
Raises ValueError if pos < 0 or pos + bs.len > self.len |
384,020 | def managed(name,
source=None,
source_hash=,
source_hash_name=None,
keep_source=True,
user=None,
group=None,
mode=None,
attrs=None,
template=None,
makedirs=False,
dir_mode=None,
... | r'''
Manage a given file, this function allows for a file to be downloaded from
the salt master and potentially run through a templating system.
name
The location of the file to manage, as an absolute path.
source
The source file to download to the minion, this source file can be
... |
384,021 | def size(default_chunk_size, response_time_max, response_time_actual):
if response_time_actual == 0:
response_time_actual = 1
scale = 1 / (response_time_actual / response_time_max)
size = int(default_chunk_size * scale)
return min(max(size, 1), default_chunk_size) | Determines the chunk size based on response times. |
384,022 | def name(random=random, *args, **kwargs):
if random.choice([True, True, True, False]):
return firstname(random=random) + " " + lastname(random=random)
elif random.choice([True, False]):
return title(random=random) + " " + firstname(random=random) + " " + lastname(random=random)
else:
... | Return someone's name
>>> mock_random.seed(0)
>>> name(random=mock_random)
'carl poopbritches'
>>> mock_random.seed(7)
>>> name(random=mock_random, capitalize=True)
'Duke Testy Wonderful' |
384,023 | def fit(self, validation_data=None, **kwargs):
callbacks = kwargs.pop(, [])
if validation_data is not None:
callbacks.insert(0, InferenceRunner(
validation_data, ScalarStats(self._stats_to_inference)))
self.trainer.train... | Args:
validation_data (DataFlow or InputSource): to be used for inference.
The inference callback is added as the first in the callback list.
If you need to use it in a different order, please write it in the callback list manually.
kwargs: same arguments as :meth... |
384,024 | def babel_extract(config, input, output, target, keywords):
click.echo(
click.style(
"Starting Extractions config:{0} input:{1} output:{2} keywords:{3}".format(
config, input, output, keywords
),
fg="green",
)
)
keywords = " -k ".join(... | Babel, Extracts and updates all messages marked for translation |
384,025 | def multiply(dists):
if not all([isinstance(k, Distribution) for k in dists]):
raise NotImplementedError("Can only multiply Distribution objects")
n_delta = np.sum([k.is_delta for k in dists])
min_width = np.max([k.min_width for k in dists])
if n_delta>1:
... | multiplies a list of Distribution objects |
384,026 | def elevations(self):
resources = self.get_resource()
elevations = namedtuple(, )
try:
return [elevations(resource[])
for resource in resources]
except KeyError:
return [elevations(resource[])
for resource in resour... | Retrieves elevations/offsets from the output response
Returns:
elevations/offsets (namedtuple): A named tuple of list of
elevations/offsets |
384,027 | def download_needed(self, response, outfile, quiet=True):
try:
remote_date = datetime.strptime(response.headers[],
)
if isfile(outfile):
local_date = datetime.fromtimestamp(os.path.getmtime(outfile))
if ... | determine if a download is needed based on timestamp. Return True
if needed (remote is newer) or False if local is newest.
Parameters
==========
response: the response from the API
outfile: the output file to write to
quiet: suppress verbose outpu... |
384,028 | def add_arguments(self, parser):
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(, , action=,
help=)
group.add_argument(, , action=,
help=)
return self.add_common_arguments(parser, False) | Adds the arguments for the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None`` |
384,029 | def stop_instance(self, instance_id):
self._restore_from_storage(instance_id)
if self._start_failed:
raise Exception(
% instance_id)
with self._resource_lock:
try:
v_m = self._qualified_name_to_vm(instance_id)
... | Stops the instance gracefully.
:param str instance_id: instance identifier
:return: None |
384,030 | def _update(self, rules: list):
self._rules = rules
to_store = .join(
rule.config_string
for rule in rules
)
sftp_connection = self._sftp_connection
with sftp_connection.open(self.RULE_PATH, mode=) as file_handle:
file_handle.write(to_... | Updates the given rules and stores
them on the router. |
384,031 | def convert(self, request, response, data):
qstr = request.query_string
return self.escape( % qstr) if qstr else | Performs the desired Conversion.
:param request: The webob Request object describing the
request.
:param response: The webob Response object describing the
response.
:param data: The data dictionary returned by the prepare()
... |
384,032 | def resize_thumbnail(image, size, resample=Image.LANCZOS):
img_format = image.format
img = image.copy()
img.thumbnail((size[0], size[1]), resample)
img.format = img_format
return img | Resize image according to size.
image: a Pillow image instance
size: a list of two integers [width, height] |
384,033 | def direct_horizontal_irradiance(self):
analysis_period = AnalysisPeriod(timestep=self.timestep,
is_leap_year=self.is_leap_year)
header_dhr = Header(data_type=DirectHorizontalIrradiance(),
unit=,
an... | Returns the direct irradiance on a horizontal surface at each timestep.
Note that this is different from the direct_normal_irradiance needed
to construct a Wea, which is NORMAL and not HORIZONTAL. |
384,034 | def get_variance(seq):
m = get_mean(seq)
return sum((v-m)**2 for v in seq)/float(len(seq)) | Batch variance calculation. |
384,035 | def roc_auc_xlim(x_bla, y_bla, xlim=0.1):
x = x_bla[:]
y = y_bla[:]
x.sort()
y.sort()
u = {}
for i in x + y:
u[i] = 1
vals = sorted(u.keys())
len_x = float(len(x))
len_y = float(len(y))
new_x = []
new_y = []
x_p = 0
y_p = 0
for val i... | Computes the ROC Area Under Curve until a certain FPR value.
Parameters
----------
fg_vals : array_like
list of values for positive set
bg_vals : array_like
list of values for negative set
xlim : float, optional
FPR value
Returns
-------
score : float
... |
384,036 | def bag(directory, mets_basename, dest, identifier, in_place, manifestation_depth, mets, base_version_checksum, tag_file, skip_zip, processes):
resolver = Resolver()
workspace = Workspace(resolver, directory=directory, mets_basename=mets_basename)
workspace_bagger = WorkspaceBagger(resolver)
worksp... | Bag workspace as OCRD-ZIP at DEST |
384,037 | def find_expectations(self,
expectation_type=None,
column=None,
expectation_kwargs=None,
discard_result_format_kwargs=True,
discard_include_configs_kwargs=True,
dis... | Find matching expectations within _expectation_config.
Args:
expectation_type=None : The name of the expectation type to be matched.
column=None : The name of the column to be matched.
expectation_kwargs=None : A dictionary... |
384,038 | def _reset_suffix_links(self):
self._suffix_links_set = False
for current, _parent in self.dfs():
current.suffix = None
current.dict_suffix = None
current.longest_prefix = None | Reset all suffix links in all nodes in this trie. |
384,039 | def load(self, profile_args):
for key, value in profile_args.items():
self.add(key, value) | Load provided CLI Args.
Args:
args (dict): Dictionary of args in key/value format. |
384,040 | def next_task(self, item, raise_exceptions=None, **kwargs):
filename = os.path.basename(item)
batch = self.get_batch(filename)
tx_deserializer = self.tx_deserializer_cls(
allow_self=self.allow_self, override_role=self.override_role
)
try:
tx_deser... | Deserializes all transactions for this batch and
archives the file. |
384,041 | def as_languages(self):
langs = []
for culture_code in self.select_related(, ).all():
lang = culture_code.language
lang.country = culture_code.country
lang.culturecode = culture_code.code
langs.append(lang)
return langs | Get the Language objects associated with this queryset of CultureCodes as a list.
The Language objects will have country and culturecode set.
:return: |
384,042 | def get_prev_step(self, step=None):
if step is None:
step = self.steps.current
form_list = self.get_form_list()
key = form_list.keyOrder.index(step) - 1
if key >= 0:
return form_list.keyOrder[key]
return None | Returns the previous step before the given `step`. If there are no
steps available, None will be returned. If the `step` argument is
None, the current step will be determined automatically. |
384,043 | def variablename(var):
s=[tpl[0] for tpl in itertools.ifilter(lambda x: var is x[1], globals().items())]
s=s[0].upper()
return s | Returns the string of a variable name. |
384,044 | def competition_download_leaderboard(self, id, **kwargs):
kwargs[] = True
if kwargs.get():
return self.competition_download_leaderboard_with_http_info(id, **kwargs)
else:
(data) = self.competition_download_leaderboard_with_http_info(id, **kwargs)
... | Download competition leaderboard # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.competition_download_leaderboard(id, async_req=True)
>>> result = thread.get()
:param async_... |
384,045 | def havdalah(self):
today = HDate(gdate=self.date, diaspora=self.location.diaspora)
tomorrow = HDate(gdate=self.date + dt.timedelta(days=1),
diaspora=self.location.diaspora)
if today.is_shabbat or today.is_yom_tov:
... | Return the time for havdalah, or None if not applicable.
If havdalah_offset is 0, uses the time for three_stars. Otherwise,
adds the offset to the time of sunset and uses that.
If it's currently a multi-day YomTov, and the end of the stretch is
after today, the havdalah value is defined... |
384,046 | def extend_substation(grid, critical_stations, grid_level):
load_factor_lv_trans_lc_normal = cfg_ding0.get(
,
)
load_factor_lv_trans_fc_normal = cfg_ding0.get(
,
)
trafo_params = grid.network._static_data[.format(
grid_level=grid_level)]
trafo_s_max_max = ma... | Reinforce MV or LV substation by exchanging the existing trafo and
installing a parallel one if necessary.
First, all available transformers in a `critical_stations` are extended to
maximum power. If this does not solve all present issues, additional
transformers are build.
Parameters
--------... |
384,047 | def add_macd(self,fast_period=12,slow_period=26,signal_period=9,column=None,
name=,str=None,**kwargs):
if not column:
column=self._d[]
study={:,
:name,
:{:fast_period,:slow_period,
:signal_period,:column,
:str},
:utils.merge_dict({:False,:[,]},kwargs)}
study[][]=.format(... | Add Moving Average Convergence Divergence (MACD) study to QuantFigure.studies
Parameters:
fast_period : int
MACD Fast Period
slow_period : int
MACD Slow Period
signal_period : int
MACD Signal Period
column :string
Defines the data column name that contains the
data over which the stu... |
384,048 | def _load_manifest_interpret_source(manifest, source, username=None, password=None, verify_certificate=True, do_inherit=True):
try:
if isinstance(source, string_types):
if source.startswith("http"):
_load_manifest_from_url(manifest, source,
... | Interpret the <source>, and load the results into <manifest> |
384,049 | def parse_signature_type_comment(type_comment):
try:
result = ast3.parse(type_comment, , )
except SyntaxError:
raise ValueError(f"invalid function signature type comment: {type_comment!r}")
assert isinstance(result, ast3.FunctionType)
if len(result.argtypes) == 1:
argtypes ... | Parse the fugly signature type comment into AST nodes.
Caveats: ASTifying **kwargs is impossible with the current grammar so we
hack it into unary subtraction (to differentiate from Starred in vararg).
For example from:
"(str, int, *int, **Any) -> 'SomeReturnType'"
To:
([ast3.Name, ast.Name, ... |
384,050 | def RegisterMessageHandler(self, handler, lease_time, limit=1000):
self.UnregisterMessageHandler()
self.handler_stop = False
self.handler_thread = threading.Thread(
name="message_handler",
target=self._MessageHandlerLoop,
args=(handler, lease_time, limit))
self.handler_thre... | Leases a number of message handler requests up to the indicated limit. |
384,051 | def _complete_statement(self, line: str) -> Statement:
while True:
try:
statement = self.statement_parser.parse(line)
if statement.multiline_command and statement.terminator:
break
if not statement.mult... | Keep accepting lines of input until the command is complete.
There is some pretty hacky code here to handle some quirks of
self.pseudo_raw_input(). It returns a literal 'eof' if the input
pipe runs out. We can't refactor it because we need to retain
backwards compatibility with the stan... |
384,052 | def aging_csv(request):
animal_list = Animal.objects.all()
response = HttpResponse(content_type=)
response[] =
writer = csv.writer(response)
writer.writerow(["Animal", "Strain", "Genotype", "Gender", "Age", "Death", "Alive"])
for animal in animal_list.iterator():
writer.writerow([
... | This view generates a csv output file of all animal data for use in aging analysis.
The view writes to a csv table the animal, strain, genotype, age (in days), and cause of death. |
384,053 | def create_graph_from_data(self, data, **kwargs):
self.arguments[] = str(self.verbose).upper()
results = self._run_ccdr(data, verbose=self.verbose)
return nx.relabel_nodes(nx.DiGraph(results),
{idx: i for idx, i in enumerate(data.columns)}) | Apply causal discovery on observational data using CCDr.
Args:
data (pandas.DataFrame): DataFrame containing the data
Returns:
networkx.DiGraph: Solution given by the CCDR algorithm. |
384,054 | def deploy_to(self, displays=None, exclude=[], lock=[]):
if displays is None:
signs = Sign.objects.all()
else:
signs = Sign.objects.filter(display__in=displays)
for sign in signs.exclude(display__in=exclude):
sign.pages.add(self)
sign.save... | Deploys page to listed display (specify with display). If display is None,
deploy to all display. Can specify exclude for which display to exclude.
This overwrites the first argument. |
384,055 | def standard_parser(cls, verbose=True,
interactive=False,
no_interactive=False,
simulate=False,
quiet=False,
overwrite=False):
parser = BoolOptionParser()
if verbose:
... | Create a standard ``OptionParser`` instance.
Typically used like::
class MyCommand(Command):
parser = Command.standard_parser()
Subclasses may redefine ``standard_parser``, so use the
nearest superclass's class method. |
384,056 | def main():
usage = "usage: %prog [-u USER] [-p PASSWORD] [-t TITLE] [-s selection] url"
parser = OptionParser(usage, version="%prog "+instapaperlib.__version__)
parser.add_option("-u", "--user", action="store", dest="user",
metavar="USER", help="instapaper username")
par... | main method |
384,057 | def open(self, user=None, repo=None):
s browser'
webbrowser.open(self.format_path(repo, namespace=user, rw=False)) | Open the URL of a repository in the user's browser |
384,058 | def parse(self, ioc_obj):
if ioc_obj is None:
return
iocid = ioc_obj.iocid
try:
sd = ioc_obj.metadata.xpath()[0]
except IndexError:
sd =
if iocid in self.iocs:
msg = .format(iocid,
... | parses an ioc to populate self.iocs and self.ioc_name
:param ioc_obj:
:return: |
384,059 | def default_cx(self):
px_width = self.image.px_width
horz_dpi = self.image.horz_dpi
width_in_inches = px_width / horz_dpi
return Inches(width_in_inches) | Native width of this image, calculated from its width in pixels and
horizontal dots per inch (dpi). |
384,060 | def options(self):
if self._options is None:
self._options = Option.View(self)
return self._options | Returns the options specified as argument to this command. |
384,061 | def addAttachment(self, filepath):
proj_id = self.contextId
fa = self.rtc_obj.getFiledAgainst(self.filedAgainst,
projectarea_id=proj_id)
fa_id = fa.url.split("/")[-1]
headers = copy.deepcopy(self.rtc_obj.headers)
if headers.__... | Upload attachment to a workitem
:param filepath: the attachment file path
:return: the :class:`rtcclient.models.Attachment` object
:rtype: rtcclient.models.Attachment |
384,062 | def onset_detect(y=None, sr=22050, onset_envelope=None, hop_length=512,
backtrack=False, energy=None,
units=, **kwargs):
return onsets | Basic onset detector. Locate note onset events by picking peaks in an
onset strength envelope.
The `peak_pick` parameters were chosen by large-scale hyper-parameter
optimization over the dataset provided by [1]_.
.. [1] https://github.com/CPJKU/onset_db
Parameters
----------
y ... |
384,063 | def download(self, url, destination_path):
self._pbar_url.update_total(1)
future = self._executor.submit(self._sync_download, url, destination_path)
return promise.Promise.resolve(future) | Download url to given path.
Returns Promise -> sha256 of downloaded file.
Args:
url: address of resource to download.
destination_path: `str`, path to directory where to download the resource.
Returns:
Promise obj -> (`str`, int): (downloaded object checksum, size in bytes). |
384,064 | def get_cli_static_event_returns(
self,
jid,
minions,
timeout=None,
tgt=,
tgt_type=,
verbose=False,
show_timeout=False,
show_jid=False):
log.trace()
minions = set(minions)
if verb... | Get the returns for the command line interface via the event system |
384,065 | def _handle_wrong_field(cls, field_name, field_type):
if field_type == ATTR_TYPE_READ:
field_type =
elif field_type == ATTR_TYPE_WRITE:
field_type =
elif field_type == ATTR_TYPE_URL:
field_type =
else:
raise AttributeError(.form... | Raise an exception whenever an invalid attribute with
the given name was attempted to be set to or retrieved from
this model class.
Assumes that the given field is invalid, without making any checks.
Also adds an entry to the logs. |
384,066 | def _apply_section(self, section, hosts):
if section[] is not None:
for hostname in self._group_get_hostnames(section[]):
hosts[hostname][].add(section[])
func_map = {
"hosts": self._apply_section_hosts,
"children": self._ap... | Recursively find all the hosts that belong in or under a section and
add the section's group name and variables to every host. |
384,067 | def _unsorted_set(df, label, **kwargs):
out = "*NSET, NSET={0}, UNSORTED\n".format(label)
labels = df.index.values
return out + argiope.utils.list_to_string(labels, **kwargs) | Returns a set as inp string with unsorted option. |
384,068 | def _get_delta(self, now, then):
if now.__class__ is not then.__class__:
now = datetime.date(now.year, now.month, now.day)
then = datetime.date(then.year, then.month, then.day)
if now < then:
raise ValueError("Cannot determine moderation rules because date fi... | Internal helper which will return a ``datetime.timedelta``
representing the time between ``now`` and ``then``. Assumes
``now`` is a ``datetime.date`` or ``datetime.datetime`` later
than ``then``.
If ``now`` and ``then`` are not of the same type due to one of
them being a ``datet... |
384,069 | def sff(args):
p = OptionParser(sff.__doc__)
p.add_option("--prefix", dest="prefix", default=None,
help="Output frg filename prefix")
p.add_option("--nodedup", default=False, action="store_true",
help="Do not remove duplicates [default: %default]")
p.set_size()
opts, arg... | %prog sff sffiles
Convert reads formatted as 454 SFF file, and convert to CA frg file.
Turn --nodedup on if another deduplication mechanism is used (e.g.
CD-HIT-454). See assembly.sff.deduplicate(). |
384,070 | def read_meminfo():
data = {}
with open("/proc/meminfo", "rb") as meminfo_file:
for row in meminfo_file:
fields = row.split()
data[fields[0].decode("ascii")[:-1]] = int(fields[1]) * 1024
return data | Returns system memory usage information.
:returns: The system memory usage.
:rtype: dict |
384,071 | def register(self, event_type: Union[Type, _ellipsis], callback: Callable[[], Any]):
if not isinstance(event_type, type) and event_type is not ...:
raise TypeError(f"{type(self)}.register requires event_type to be a type.")
if not callable(callback):
raise TypeError(f"{t... | Register a callback to be applied to an event at time of publishing.
Primarily to be used by subsystems.
The callback will receive the event. Your code should modify the event
in place. It does not need to return it.
:param event_type: The class of an event.
:param callback: A... |
384,072 | def print_invalid_chars(invalid_chars, vargs):
if len(invalid_chars) > 0:
if vargs["print_invalid"]:
print(u"".join(invalid_chars))
if vargs["unicode"]:
for u_char in sorted(set(invalid_chars)):
print(u"\t%s\t%s" % (u_char, hex(ord(u_char)), unicodedata.n... | Print Unicode characterss that are not IPA valid,
if requested by the user.
:param list invalid_chars: a list (possibly empty) of invalid Unicode characters
:param dict vargs: the command line parameters |
384,073 | def drain(iterable):
if getattr(iterable, "popleft", False):
def next_item(coll):
return coll.popleft()
elif getattr(iterable, "popitem", False):
def next_item(coll):
return coll.popitem()
else:
def next_item(coll):
return coll.pop()
whil... | Helper method that empties an iterable as it is iterated over.
Works for:
* ``dict``
* ``collections.deque``
* ``list``
* ``set`` |
384,074 | def submit_msql_object_query(object_query, client=None):
client = client or get_new_client()
if not client.session_id:
client.request_session()
result = client.execute_object_query(object_query)
execute_msql_result = result["body"]["ExecuteMSQLResult"]
membersuite_object_list = []
... | Submit `object_query` to MemberSuite, returning
.models.MemberSuiteObjects.
So this is a converter from MSQL to .models.MemberSuiteObjects.
Returns query results as a list of MemberSuiteObjects. |
384,075 | def push_intent(self, intent):
if intent.id:
print(.format(intent.name))
self.update(intent)
else:
print(.format(intent.name))
intent = self.register(intent)
return intent | Registers or updates an intent and returns the intent_json with an ID |
384,076 | def bookmark(ctx):
user, project_name, _build = get_build_or_local(ctx.obj.get(), ctx.obj.get())
try:
PolyaxonClient().build_job.bookmark(user, project_name, _build)
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.print_error(.format(_build))
... | Bookmark build job.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon build bookmark
```
\b
```bash
$ polyaxon build -b 2 bookmark
``` |
384,077 | def _parse_interfaces(interface_files=None):
if interface_files is None:
interface_files = []
if os.path.exists(_DEB_NETWORK_DIR):
interface_files += [.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)]
if os.path.isfile(_DEB_NETWORK_FILE):
... | Parse /etc/network/interfaces and return current configured interfaces |
384,078 | def blast_pdb(seq, outfile=, outdir=, evalue=0.0001, seq_ident_cutoff=0.0, link=False, force_rerun=False):
if len(seq) < 12:
raise ValueError()
if link:
page = .format(seq, evalue)
print(page)
parser = etree.XMLParser(ns_clean=True)
outfile = op.join(outdir, outfile)
... | Returns a list of BLAST hits of a sequence to available structures in the PDB.
Args:
seq (str): Your sequence, in string format
outfile (str): Name of output file
outdir (str, optional): Path to output directory. Default is the current directory.
evalue (float, optional): Cutoff for... |
384,079 | def where_before_entry(query, ref):
return orm.select(
e for e in query
if e.local_date < ref.local_date or
(e.local_date == ref.local_date and e.id < ref.id)
) | Generate a where clause for prior entries
ref -- The entry of reference |
384,080 | def has_friends(self, flt=FriendFilter.ALL):
return self._iface.get_has_friend(self.user_id, flt) | Indicated whether the user has friends, who meet the given criteria (filter).
:param int flt: Filter value from FriendFilter. Filters can be combined with `|`.
:rtype: bool |
384,081 | def run_step(context):
logger.debug("started")
CmdStep(name=__name__, context=context).run_step(is_shell=True)
logger.debug("done") | Run shell command without shell interpolation.
Context is a dictionary or dictionary-like.
Context must contain the following keys:
cmd: <<cmd string>> (command + args to execute.)
OR, as a dict
cmd:
run: str. mandatory. <<cmd string>> command + args to execute.
save: bool. defaul... |
384,082 | def put(self, deviceId, measurementId):
record = self.measurements.get(deviceId)
if record is not None:
measurement = record.get(measurementId)
if measurement is not None:
if len([x.name for x in measurement.statuses if x.name is or x.name is ]) > 0:
... | Schedules a new measurement at the specified time.
:param deviceId: the device to measure.
:param measurementId: the name of the measurement.
:return: 200 if it was scheduled, 400 if the device is busy, 500 if the device is bad. |
384,083 | def atlasdb_num_peers( con=None, path=None ):
with AtlasDBOpen(con=con, path=path) as dbcon:
sql = "SELECT MAX(peer_index) FROM peers;"
args = ()
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
ret = []
for row in res:
tmp = {}
... | How many peers are there in the db? |
384,084 | def object(self, infotype, key):
with self.pipe as pipe:
return pipe.object(infotype, self.redis_key(key)) | get the key's info stats
:param name: str the name of the redis key
:param subcommand: REFCOUNT | ENCODING | IDLETIME
:return: Future() |
384,085 | def compute_residuals(self):
r = self.rsdl()
adapt_tol = self.opt[]
if self.opt[, ]:
adapt_tol = self.tau0 / (1. + self.k)
return r, adapt_tol | Compute residuals and stopping thresholds. |
384,086 | def lane_stats_table(self):
headers = OrderedDict()
headers[] = {
: .format(config.base_count_prefix),
: .format(config.base_count_desc),
: ,
:
}
headers[] = {
: .format(config.read_count_prefix),
: .format... | Return a table with overview stats for each bcl2fastq lane for a single flow cell |
384,087 | def airwires(board, showgui=0):
board = Path(board).expand().abspath()
file_out = tempfile.NamedTemporaryFile(suffix=, delete=0)
file_out.close()
ulp = ulp_templ.replace(, file_out.name)
file_ulp = tempfile.NamedTemporaryFile(suffix=, delete=0)
file_ulp.write(ulp.encode())
file_ulp.c... | search for airwires in eagle board |
384,088 | def ARC4_encrypt(key, data, skip=0):
algorithm = algorithms.ARC4(key)
cipher = Cipher(algorithm, mode=None, backend=default_backend())
encryptor = cipher.encryptor()
if skip:
encryptor.update(b"\x00" * skip)
return encryptor.update(data) | Encrypt data @data with key @key, skipping @skip first bytes of the
keystream |
384,089 | def send_element(self, element):
with self.lock:
if self._eof or self._socket is None or not self._serializer:
logger.debug("Dropping element: {0}".format(
element_to_unicode(element)))
return
data =... | Send an element via the transport. |
384,090 | def cowsay_output(message):
command = % message
ret = subprocess.Popen(
command, shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
output, error = ret.communicate()
return output, error | Invoke a shell command to print cowsay output. Primary replacement for
os.system calls. |
384,091 | def update_from_dict(self, data_dict):
for k, v in data_dict.items():
setattr(self, k, v)
if "item_queue_id" in data_dict:
self.id = data_dict["item_queue_id"] | :param data_dict: Dictionary to be mapped into object attributes
:type data_dict: dict
:return: |
384,092 | def modify(self, max_time_out_of_sync=None, name=None,
hourly_snap_replication_policy=None,
daily_snap_replication_policy=None,
src_spa_interface=None, src_spb_interface=None,
dst_spa_interface=None, dst_spb_interface=None):
req_body = self._c... | Modifies properties of a replication session.
:param max_time_out_of_sync: same as the one in `create` method.
:param name: same as the one in `create` method.
:param hourly_snap_replication_policy: same as the one in `create`
method.
:param daily_snap_replication_policy: sa... |
384,093 | def path_expand(text):
result = os.path.expandvars(os.path.expanduser(text))
if result.startswith("."):
result = result.replace(".", os.getcwd(), 1)
return result | returns a string with expanded variable.
:param text: the path to be expanded, which can include ~ and environment $ variables
:param text: string |
384,094 | def predict(self, nSteps):
pristineTPDynamicState = self._getTPDynamicState()
assert (nSteps>0)
multiStepColumnPredictions = numpy.zeros((nSteps, self.numberOfCols),
dtype="float32")
step = 0
while True:
... | This function gives the future predictions for <nSteps> timesteps starting
from the current TM state. The TM is returned to its original state at the
end before returning.
1. We save the TM state.
2. Loop for nSteps
a. Turn-on with lateral support from the current active cells
b. Set the... |
384,095 | def et_node_to_string(et_node, default=):
return str(et_node.text).strip() if et_node is not None and et_node.text else default | Simple method to get stripped text from node or ``default`` string if None is given.
:param et_node: Element or None
:param default: string returned if None is given, default ``''``
:type et_node: xml.etree.ElementTree.Element, None
:type default: str
:return: text from node or default
:rtype: ... |
384,096 | def import_end_event_to_graph(diagram_graph, process_id, process_attributes, element):
end_event_definitions = {, , ,
, , }
BpmnDiagramGraphImport.import_flow_node_to_graph(diagram_graph, process_id, process_attributes, element)
BpmnDiagramGraphImport.im... | Adds to graph the new element that represents BPMN end event.
End event inherits sequence of eventDefinitionRef from Event type.
Separate methods for each event type are required since each of them has different variants
(Message, Error, Signal etc.).
:param diagram_graph: NetworkX grap... |
384,097 | def check(self):
status = _checkContainerStatus(self.sparkContainerID,
self.hdfsContainerID,
sparkNoun=,
hdfsNoun=)
return status | Checks to see if Spark worker and HDFS datanode are still running. |
384,098 | def create_fc_template(self, out_path, out_name):
fields = self.fields
objectIdField = self.objectIdField
geomType = self.geometryType
wkid = self.parentLayer.spatialReference[]
return create_feature_class(out_path,
out_name,
... | creates a featureclass template on local disk |
384,099 | def suggest(alias, max=3, cutoff=0.5):
aliases = matchers.keys()
similar = get_close_matches(alias, aliases, n=max, cutoff=cutoff)
return similar | Suggest a list of aliases which are similar enough |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.