text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def run(self, args):
"""Runs the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
args (Namespace): arguments to parse
Returns:
``None``
"""
jlink = self.create_jlink(args)
if args.downgrade:
if n... | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"jlink",
"=",
"self",
".",
"create_jlink",
"(",
"args",
")",
"if",
"args",
".",
"downgrade",
":",
"if",
"not",
"jlink",
".",
"firmware_newer",
"(",
")",
":",
"print",
"(",
"'DLL firmware is not older than... | 38.525 | 20.775 |
def runCPU():
"""Poll CPU usage, make predictions, and plot the results. Runs forever."""
# Create the model for predicting CPU usage.
model = ModelFactory.create(model_params.MODEL_PARAMS)
model.enableInference({'predictedField': 'cpu'})
# The shifter will align prediction and actual values.
shifter = Infe... | [
"def",
"runCPU",
"(",
")",
":",
"# Create the model for predicting CPU usage.",
"model",
"=",
"ModelFactory",
".",
"create",
"(",
"model_params",
".",
"MODEL_PARAMS",
")",
"model",
".",
"enableInference",
"(",
"{",
"'predictedField'",
":",
"'cpu'",
"}",
")",
"# Th... | 34.222222 | 18.911111 |
def _consume_queue(self):
"""
Continually blocks until data is on the internal queue, then calls
the session's registered callback and sends a PublishMessageReceived
if callback returned True.
"""
while True:
session, block_id, raw_data = self._queue.get()
... | [
"def",
"_consume_queue",
"(",
"self",
")",
":",
"while",
"True",
":",
"session",
",",
"block_id",
",",
"raw_data",
"=",
"self",
".",
"_queue",
".",
"get",
"(",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"raw_data",
".",
"decode",
"(",
"'utf-8'",
")... | 49.5 | 21.653846 |
def line(self, value):
"""The line property.
Args:
value (int). the property value.
"""
if value == self._defaults['line'] and 'line' in self._values:
del self._values['line']
else:
self._values['line'] = value | [
"def",
"line",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"self",
".",
"_defaults",
"[",
"'line'",
"]",
"and",
"'line'",
"in",
"self",
".",
"_values",
":",
"del",
"self",
".",
"_values",
"[",
"'line'",
"]",
"else",
":",
"self",
".",
... | 28.6 | 14.2 |
def get_all_completed_tasks(self, api_token, **kwargs):
"""Return a list of a user's completed tasks.
.. warning:: Requires Todoist premium.
:param api_token: The user's login api_token.
:type api_token: str
:param project_id: Filter the tasks by project.
:type project_... | [
"def",
"get_all_completed_tasks",
"(",
"self",
",",
"api_token",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'token'",
":",
"api_token",
"}",
"return",
"self",
".",
"_get",
"(",
"'get_all_completed_items'",
",",
"params",
",",
"*",
"*",
"kwargs... | 40.971429 | 16.971429 |
def page_load_time(self):
"""
The average total load time for all runs (not weighted).
"""
load_times = self.get_load_times('page')
return round(mean(load_times), self.decimal_precision) | [
"def",
"page_load_time",
"(",
"self",
")",
":",
"load_times",
"=",
"self",
".",
"get_load_times",
"(",
"'page'",
")",
"return",
"round",
"(",
"mean",
"(",
"load_times",
")",
",",
"self",
".",
"decimal_precision",
")"
] | 36.833333 | 11.5 |
def validate_business(form, field):
"""Valiates a PayPal business string.
It can either be an email address or a paypal business account ID.
"""
if not is_valid_mail(field.data, multi=False) and not re.match(r'^[a-zA-Z0-9]{13}$', field.data):
raise ValidationError(_('Invalid email address / pay... | [
"def",
"validate_business",
"(",
"form",
",",
"field",
")",
":",
"if",
"not",
"is_valid_mail",
"(",
"field",
".",
"data",
",",
"multi",
"=",
"False",
")",
"and",
"not",
"re",
".",
"match",
"(",
"r'^[a-zA-Z0-9]{13}$'",
",",
"field",
".",
"data",
")",
":... | 46.142857 | 23.571429 |
def from_url(cls, url):
"""
Given a resource uri, return an instance of that cache initialized with the given
parameters. An example usage:
>>> from aiocache import Cache
>>> Cache.from_url('memory://')
<aiocache.backends.memory.SimpleMemoryCache object at 0x1081dbb00>
... | [
"def",
"from_url",
"(",
"cls",
",",
"url",
")",
":",
"parsed_url",
"=",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
")",
"kwargs",
"=",
"dict",
"(",
"urllib",
".",
"parse",
".",
"parse_qsl",
"(",
"parsed_url",
".",
"query",
")",
")",
"cache_... | 32.25641 | 21.948718 |
def to_bytes(self, request=None):
'''Called to transform the collection of
``streams`` into the content string.
This method can be overwritten by derived classes.
:param streams: a collection (list or dictionary) containing
``strings/bytes`` used to build the final ``string/... | [
"def",
"to_bytes",
"(",
"self",
",",
"request",
"=",
"None",
")",
":",
"data",
"=",
"bytearray",
"(",
")",
"for",
"chunk",
"in",
"self",
".",
"stream",
"(",
"request",
")",
":",
"if",
"isinstance",
"(",
"chunk",
",",
"str",
")",
":",
"chunk",
"=",
... | 38.6 | 14.866667 |
def absolute_abundance(coverage, total_bases):
"""
absolute abundance = (number of bases mapped to genome / total number of bases in sample) * 100
"""
absolute = {}
for genome in coverage:
absolute[genome] = []
index = 0
for calc in coverage[genome]:
bases = calc[0]
total = total_bases[index]
absolu... | [
"def",
"absolute_abundance",
"(",
"coverage",
",",
"total_bases",
")",
":",
"absolute",
"=",
"{",
"}",
"for",
"genome",
"in",
"coverage",
":",
"absolute",
"[",
"genome",
"]",
"=",
"[",
"]",
"index",
"=",
"0",
"for",
"calc",
"in",
"coverage",
"[",
"geno... | 28.857143 | 18.095238 |
def application_path(path):
"""
Join application project_dir and path
"""
from uliweb import application
return os.path.join(application.project_dir, path) | [
"def",
"application_path",
"(",
"path",
")",
":",
"from",
"uliweb",
"import",
"application",
"return",
"os",
".",
"path",
".",
"join",
"(",
"application",
".",
"project_dir",
",",
"path",
")"
] | 28.333333 | 5.666667 |
def set_raw(self,text):
"""
Sets the text of the raw element (or creates the layer if does not exist)
@param text: text of the raw layer
@type text: string
"""
node_raw = self.root.find('raw')
if node_raw is None:
node_raw = etree.Element('raw')
... | [
"def",
"set_raw",
"(",
"self",
",",
"text",
")",
":",
"node_raw",
"=",
"self",
".",
"root",
".",
"find",
"(",
"'raw'",
")",
"if",
"node_raw",
"is",
"None",
":",
"node_raw",
"=",
"etree",
".",
"Element",
"(",
"'raw'",
")",
"self",
".",
"root",
".",
... | 35.090909 | 8.181818 |
def registerItem(self, regItem):
""" Adds a ClassRegItem object to the registry.
"""
super(RtiRegistry, self).registerItem(regItem)
for ext in regItem.extensions:
self._registerExtension(ext, regItem) | [
"def",
"registerItem",
"(",
"self",
",",
"regItem",
")",
":",
"super",
"(",
"RtiRegistry",
",",
"self",
")",
".",
"registerItem",
"(",
"regItem",
")",
"for",
"ext",
"in",
"regItem",
".",
"extensions",
":",
"self",
".",
"_registerExtension",
"(",
"ext",
"... | 34.142857 | 10.428571 |
def _strOrDate(st):
'''internal'''
if isinstance(st, string_types):
return st
elif isinstance(st, datetime):
return st.strftime('%Y%m%d')
raise PyEXception('Not a date: %s', str(st)) | [
"def",
"_strOrDate",
"(",
"st",
")",
":",
"if",
"isinstance",
"(",
"st",
",",
"string_types",
")",
":",
"return",
"st",
"elif",
"isinstance",
"(",
"st",
",",
"datetime",
")",
":",
"return",
"st",
".",
"strftime",
"(",
"'%Y%m%d'",
")",
"raise",
"PyEXcep... | 29.714286 | 12.571429 |
def _save_image(self, image_id, directory):
""" Saves the image as a tar archive under specified name """
for x in [0, 1, 2]:
self.log.info("Saving image %s to %s directory..." %
(image_id, directory))
self.log.debug("Try #%s..." % (x + 1))
... | [
"def",
"_save_image",
"(",
"self",
",",
"image_id",
",",
"directory",
")",
":",
"for",
"x",
"in",
"[",
"0",
",",
"1",
",",
"2",
"]",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Saving image %s to %s directory...\"",
"%",
"(",
"image_id",
",",
"direct... | 37.977273 | 21.454545 |
def pre_social_login(self, request, sociallogin):
"""Update user based on token information."""
user = sociallogin.user
# If the user hasn't been saved yet, it will be updated
# later on in the sign-up flow.
if not user.pk:
return
data = sociallogin.account.... | [
"def",
"pre_social_login",
"(",
"self",
",",
"request",
",",
"sociallogin",
")",
":",
"user",
"=",
"sociallogin",
".",
"user",
"# If the user hasn't been saved yet, it will be updated",
"# later on in the sign-up flow.",
"if",
"not",
"user",
".",
"pk",
":",
"return",
... | 35 | 15.916667 |
def smoothed(self, angle=.4):
"""
Return a version of the current mesh which will render
nicely, without changing source mesh.
Parameters
-------------
angle : float
Angle in radians, face pairs with angles smaller than
this value will appear smoothed... | [
"def",
"smoothed",
"(",
"self",
",",
"angle",
"=",
".4",
")",
":",
"# smooth should be recomputed if visuals change",
"self",
".",
"visual",
".",
"_verify_crc",
"(",
")",
"cached",
"=",
"self",
".",
"visual",
".",
"_cache",
"[",
"'smoothed'",
"]",
"if",
"cac... | 29.555556 | 16.444444 |
def _add_pret_words(self, pret_embeddings):
"""Read pre-trained embedding file for extending vocabulary
Parameters
----------
pret_embeddings : tuple
(embedding_name, source), used for gluonnlp.embedding.create(embedding_name, source)
"""
words_in_train_data ... | [
"def",
"_add_pret_words",
"(",
"self",
",",
"pret_embeddings",
")",
":",
"words_in_train_data",
"=",
"set",
"(",
"self",
".",
"_id2word",
")",
"pret_embeddings",
"=",
"gluonnlp",
".",
"embedding",
".",
"create",
"(",
"pret_embeddings",
"[",
"0",
"]",
",",
"s... | 41.928571 | 21.071429 |
def all(klass, account, tailored_audience_id, **kwargs):
"""Returns a Cursor instance for the given tailored audience permission resource."""
resource = klass.RESOURCE_COLLECTION.format(
account_id=account.id,
tailored_audience_id=tailored_audience_id)
request = Request(... | [
"def",
"all",
"(",
"klass",
",",
"account",
",",
"tailored_audience_id",
",",
"*",
"*",
"kwargs",
")",
":",
"resource",
"=",
"klass",
".",
"RESOURCE_COLLECTION",
".",
"format",
"(",
"account_id",
"=",
"account",
".",
"id",
",",
"tailored_audience_id",
"=",
... | 46.555556 | 19.888889 |
def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
changes = []
# Read current configuration and store default values
current_network_settings = _parse_current_networ... | [
"def",
"build_network_settings",
"(",
"*",
"*",
"settings",
")",
":",
"changes",
"=",
"[",
"]",
"# Read current configuration and store default values",
"current_network_settings",
"=",
"_parse_current_network_settings",
"(",
")",
"# Build settings",
"opts",
"=",
"_parse_ne... | 34.00813 | 17.796748 |
def parse(query_string, info={}):
"""
:returns: a normalized query_dict as in the following examples:
>>> parse('kind=stats', {'stats': {'mean': 0, 'max': 1}})
{'kind': ['mean', 'max'], 'k': [0, 1], 'rlzs': False}
>>> parse('kind=rlzs', {'stats': {}, 'num_rlzs': 3})
{'kind': ['rlz-000', 'rlz-00... | [
"def",
"parse",
"(",
"query_string",
",",
"info",
"=",
"{",
"}",
")",
":",
"qdic",
"=",
"parse_qs",
"(",
"query_string",
")",
"loss_types",
"=",
"info",
".",
"get",
"(",
"'loss_types'",
",",
"[",
"]",
")",
"for",
"key",
",",
"val",
"in",
"qdic",
".... | 44.043478 | 19.434783 |
def text_log_steps(self, request, project, pk=None):
"""
Gets a list of steps associated with this job
"""
try:
job = Job.objects.get(repository__name=project,
id=pk)
except ObjectDoesNotExist:
return Response("No job with... | [
"def",
"text_log_steps",
"(",
"self",
",",
"request",
",",
"project",
",",
"pk",
"=",
"None",
")",
":",
"try",
":",
"job",
"=",
"Job",
".",
"objects",
".",
"get",
"(",
"repository__name",
"=",
"project",
",",
"id",
"=",
"pk",
")",
"except",
"ObjectDo... | 47.266667 | 21 |
def terminating_sip_domains(self):
"""
Access the terminating_sip_domains
:returns: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainList
:rtype: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainList
"""
if self._terminatin... | [
"def",
"terminating_sip_domains",
"(",
"self",
")",
":",
"if",
"self",
".",
"_terminating_sip_domains",
"is",
"None",
":",
"self",
".",
"_terminating_sip_domains",
"=",
"TerminatingSipDomainList",
"(",
"self",
".",
"_version",
",",
"trunk_sid",
"=",
"self",
".",
... | 41.461538 | 18.692308 |
def dataset_document_iterator(self, file_path: str) -> Iterator[List[OntonotesSentence]]:
"""
An iterator over CONLL formatted files which yields documents, regardless
of the number of document annotations in a particular file. This is useful
for conll data which has been preprocessed, s... | [
"def",
"dataset_document_iterator",
"(",
"self",
",",
"file_path",
":",
"str",
")",
"->",
"Iterator",
"[",
"List",
"[",
"OntonotesSentence",
"]",
"]",
":",
"with",
"codecs",
".",
"open",
"(",
"file_path",
",",
"'r'",
",",
"encoding",
"=",
"'utf8'",
")",
... | 49.653846 | 18.730769 |
def dispatch(self, context, consumed, handler, is_endpoint):
"""Called as dispatch descends into a tier.
The base extension uses this to maintain the "current url".
"""
request = context.request
if __debug__:
log.debug("Handling dispatch event.", extra=dict(
request = id(context),
consum... | [
"def",
"dispatch",
"(",
"self",
",",
"context",
",",
"consumed",
",",
"handler",
",",
"is_endpoint",
")",
":",
"request",
"=",
"context",
".",
"request",
"if",
"__debug__",
":",
"log",
".",
"debug",
"(",
"\"Handling dispatch event.\"",
",",
"extra",
"=",
"... | 29.631579 | 22.473684 |
def create_git_action_for_new_collection(self, new_collection_id=None):
"""Checks out master branch as a side effect"""
ga = self.create_git_action()
assert new_collection_id is not None
# id should have been sorted out by the caller
self.register_doc_id(ga, new_collection_id)
... | [
"def",
"create_git_action_for_new_collection",
"(",
"self",
",",
"new_collection_id",
"=",
"None",
")",
":",
"ga",
"=",
"self",
".",
"create_git_action",
"(",
")",
"assert",
"new_collection_id",
"is",
"not",
"None",
"# id should have been sorted out by the caller",
"sel... | 49.714286 | 9.571429 |
def rmfile(path):
"""Ensure file deleted also on *Windows* where read-only files need special treatment."""
if osp.isfile(path):
if is_win:
os.chmod(path, 0o777)
os.remove(path) | [
"def",
"rmfile",
"(",
"path",
")",
":",
"if",
"osp",
".",
"isfile",
"(",
"path",
")",
":",
"if",
"is_win",
":",
"os",
".",
"chmod",
"(",
"path",
",",
"0o777",
")",
"os",
".",
"remove",
"(",
"path",
")"
] | 34.666667 | 14.166667 |
def _get_arch():
"""
Determines the current processor architecture.
@rtype: str
@return:
On error, returns:
- L{ARCH_UNKNOWN} (C{"unknown"}) meaning the architecture could not be detected or is not known to WinAppDbg.
On success, returns one of the following values:
... | [
"def",
"_get_arch",
"(",
")",
":",
"try",
":",
"si",
"=",
"GetNativeSystemInfo",
"(",
")",
"except",
"Exception",
":",
"si",
"=",
"GetSystemInfo",
"(",
")",
"try",
":",
"return",
"_arch_map",
"[",
"si",
".",
"id",
".",
"w",
".",
"wProcessorArchitecture",... | 42.595238 | 28.214286 |
def remote_space_available(self, search_pattern=r"(\d+) \w+ free"):
"""Return space available on remote device."""
remote_cmd = "dir {}".format(self.file_system)
remote_output = self.ssh_ctl_chan.send_command_expect(remote_cmd)
match = re.search(search_pattern, remote_output)
if ... | [
"def",
"remote_space_available",
"(",
"self",
",",
"search_pattern",
"=",
"r\"(\\d+) \\w+ free\"",
")",
":",
"remote_cmd",
"=",
"\"dir {}\"",
".",
"format",
"(",
"self",
".",
"file_system",
")",
"remote_output",
"=",
"self",
".",
"ssh_ctl_chan",
".",
"send_command... | 56.375 | 16.125 |
def iter_item_handles(self):
"""Return iterator over item handles."""
bucket = self.s3resource.Bucket(self.bucket)
for obj in bucket.objects.filter(Prefix=self.data_key_prefix).all():
relpath = obj.get()['Metadata']['handle']
yield relpath | [
"def",
"iter_item_handles",
"(",
"self",
")",
":",
"bucket",
"=",
"self",
".",
"s3resource",
".",
"Bucket",
"(",
"self",
".",
"bucket",
")",
"for",
"obj",
"in",
"bucket",
".",
"objects",
".",
"filter",
"(",
"Prefix",
"=",
"self",
".",
"data_key_prefix",
... | 31.333333 | 23.111111 |
def _build_pipeline_request(self, task_view):
"""Returns a Pipeline objects for the job."""
job_metadata = task_view.job_metadata
job_params = task_view.job_params
job_resources = task_view.job_resources
task_metadata = task_view.task_descriptors[0].task_metadata
task_params = task_view.task_des... | [
"def",
"_build_pipeline_request",
"(",
"self",
",",
"task_view",
")",
":",
"job_metadata",
"=",
"task_view",
".",
"job_metadata",
"job_params",
"=",
"task_view",
".",
"job_params",
"job_resources",
"=",
"task_view",
".",
"job_resources",
"task_metadata",
"=",
"task_... | 44.863636 | 17.204545 |
def list_backends():
"""List color backends."""
return [b.name.replace(".py", "") for b in
os.scandir(os.path.join(MODULE_DIR, "backends"))
if "__" not in b.name] | [
"def",
"list_backends",
"(",
")",
":",
"return",
"[",
"b",
".",
"name",
".",
"replace",
"(",
"\".py\"",
",",
"\"\"",
")",
"for",
"b",
"in",
"os",
".",
"scandir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"MODULE_DIR",
",",
"\"backends\"",
")",
")",... | 38 | 10.4 |
def shred(key_name: str,
value: t.Any,
field_names: t.Iterable[str] = SHRED_DATA_FIELD_NAMES) -> t.Union[t.Any, str]:
"""
Replaces sensitive data in ``value`` with ``*`` if ``key_name`` contains something that looks like a secret.
:param field_names: a list of key names that can possibl... | [
"def",
"shred",
"(",
"key_name",
":",
"str",
",",
"value",
":",
"t",
".",
"Any",
",",
"field_names",
":",
"t",
".",
"Iterable",
"[",
"str",
"]",
"=",
"SHRED_DATA_FIELD_NAMES",
")",
"->",
"t",
".",
"Union",
"[",
"t",
".",
"Any",
",",
"str",
"]",
"... | 34.363636 | 21.818182 |
def from_json(cls, json):
"""Create a Currency object from a JSON dump."""
obj = cls(name=json['name'],
code=json['code'],
numeric_code=json['numeric_code'],
symbol=json['symbol'],
exponent=json['exponent'],
entiti... | [
"def",
"from_json",
"(",
"cls",
",",
"json",
")",
":",
"obj",
"=",
"cls",
"(",
"name",
"=",
"json",
"[",
"'name'",
"]",
",",
"code",
"=",
"json",
"[",
"'code'",
"]",
",",
"numeric_code",
"=",
"json",
"[",
"'numeric_code'",
"]",
",",
"symbol",
"=",
... | 41.181818 | 7.909091 |
def roc_curve(self):
"""
Generate a ROC curve from the contingency table by calculating the probability of detection (TP/(TP+FN)) and the
probability of false detection (FP/(FP+TN)).
Returns:
A pandas.DataFrame containing the POD, POFD, and the corresponding probability thre... | [
"def",
"roc_curve",
"(",
"self",
")",
":",
"pod",
"=",
"self",
".",
"contingency_tables",
"[",
"\"TP\"",
"]",
".",
"astype",
"(",
"float",
")",
"/",
"(",
"self",
".",
"contingency_tables",
"[",
"\"TP\"",
"]",
"+",
"self",
".",
"contingency_tables",
"[",
... | 60.857143 | 37 |
def publish(ctx, test=False):
"""Publish to the cheeseshop."""
clean(ctx)
if test:
run('python setup.py register -r test sdist bdist_wheel', echo=True)
run('twine upload dist/* -r test', echo=True)
else:
run('python setup.py register sdist bdist_wheel', echo=True)
run('tw... | [
"def",
"publish",
"(",
"ctx",
",",
"test",
"=",
"False",
")",
":",
"clean",
"(",
"ctx",
")",
"if",
"test",
":",
"run",
"(",
"'python setup.py register -r test sdist bdist_wheel'",
",",
"echo",
"=",
"True",
")",
"run",
"(",
"'twine upload dist/* -r test'",
",",... | 38 | 19.777778 |
def find_near_matches_no_deletions_ngrams(subsequence, sequence, search_params):
"""search for near-matches of subsequence in sequence
This searches for near-matches, where the nearly-matching parts of the
sequence must meet the following limitations (relative to the subsequence):
* the maximum allowe... | [
"def",
"find_near_matches_no_deletions_ngrams",
"(",
"subsequence",
",",
"sequence",
",",
"search_params",
")",
":",
"if",
"not",
"subsequence",
":",
"raise",
"ValueError",
"(",
"'Given subsequence is empty!'",
")",
"max_substitutions",
",",
"max_insertions",
",",
"max_... | 44.117647 | 24.705882 |
def load_profile(self, profile_name):
"""Load user profiles from file."""
data = self.storage.get_user_profiles(profile_name)
for x in data.get_user_views():
self._graph.add_edge(int(x[0]), int(x[1]), {'weight': float(x[2])})
self.all_records[int(x[1])] += 1
ret... | [
"def",
"load_profile",
"(",
"self",
",",
"profile_name",
")",
":",
"data",
"=",
"self",
".",
"storage",
".",
"get_user_profiles",
"(",
"profile_name",
")",
"for",
"x",
"in",
"data",
".",
"get_user_views",
"(",
")",
":",
"self",
".",
"_graph",
".",
"add_e... | 36.333333 | 17.777778 |
def set_welcome_message(self):
"""Create and insert welcome message."""
string = html_header()
string += welcome_message().to_html()
string += html_footer()
self.welcome_message.setHtml(string) | [
"def",
"set_welcome_message",
"(",
"self",
")",
":",
"string",
"=",
"html_header",
"(",
")",
"string",
"+=",
"welcome_message",
"(",
")",
".",
"to_html",
"(",
")",
"string",
"+=",
"html_footer",
"(",
")",
"self",
".",
"welcome_message",
".",
"setHtml",
"("... | 38 | 6.333333 |
def cf_safe_name(name):
"""Converts a name to a safe string for a Cloudformation resource.
Given a string, returns a name that is safe for use as a CloudFormation
Resource. (ie: Only alphanumeric characters)
"""
alphanumeric = r"[a-zA-Z0-9]+"
parts = re.findall(alphanumeric, name)
return ""... | [
"def",
"cf_safe_name",
"(",
"name",
")",
":",
"alphanumeric",
"=",
"r\"[a-zA-Z0-9]+\"",
"parts",
"=",
"re",
".",
"findall",
"(",
"alphanumeric",
",",
"name",
")",
"return",
"\"\"",
".",
"join",
"(",
"[",
"uppercase_first_letter",
"(",
"part",
")",
"for",
"... | 40.777778 | 15.111111 |
def build(self, **kwargs):
"""
Builds a new record subject to the restrictions in the query.
Will build intermediate (join table) records as needed, and links them
to the returned record so that they are saved when the returned record
is.
"""
build_args = dict(sel... | [
"def",
"build",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"build_args",
"=",
"dict",
"(",
"self",
".",
"where_query",
")",
"build_args",
".",
"update",
"(",
"kwargs",
")",
"record",
"=",
"self",
".",
"model",
"(",
"*",
"*",
"record_args",
"(",
... | 54.37931 | 23.482759 |
def policy_set_definitions(self):
"""Instance depends on the API version:
* 2017-06-01-preview: :class:`PolicySetDefinitionsOperations<azure.mgmt.resource.policy.v2017_06_01_preview.operations.PolicySetDefinitionsOperations>`
* 2018-03-01: :class:`PolicySetDefinitionsOperations<azure.mgmt... | [
"def",
"policy_set_definitions",
"(",
"self",
")",
":",
"api_version",
"=",
"self",
".",
"_get_api_version",
"(",
"'policy_set_definitions'",
")",
"if",
"api_version",
"==",
"'2017-06-01-preview'",
":",
"from",
".",
"v2017_06_01_preview",
".",
"operations",
"import",
... | 75.823529 | 45.823529 |
def update_resource(self, resource_form):
"""Updates an existing resource.
arg: resource_form (osid.resource.ResourceForm): the form
containing the elements to be updated
raise: IllegalState - ``resource_form`` already used in an
update transaction
ra... | [
"def",
"update_resource",
"(",
"self",
",",
"resource_form",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.update_resource_template",
"collection",
"=",
"JSONClientValidated",
"(",
"'resource'",
",",
"collection",
"=",
"'Resource'",
",",
"... | 50.731707 | 22.902439 |
def _get_tag(self, url, tag, print_warn=True):
"""Check if url is available and returns given tag type
:param url: url to content relative to base url
:param anchor: anchor type to return
:param print_warn: if True print warn when url is unavailable
"""
# construct comple... | [
"def",
"_get_tag",
"(",
"self",
",",
"url",
",",
"tag",
",",
"print_warn",
"=",
"True",
")",
":",
"# construct complete url",
"complete_url",
"=",
"urljoin",
"(",
"self",
".",
"base_url",
",",
"url",
")",
"# check if exists",
"if",
"requests",
".",
"get",
... | 43.8 | 14.9 |
def get_param_arg(param, idx, klass, arg, attr='id'):
"""Return the correct value for a fabric from `arg`."""
if isinstance(arg, klass):
return getattr(arg, attr)
elif isinstance(arg, (int, str)):
return arg
else:
raise TypeError(
"%s[%d] must be int, str, or %s, not ... | [
"def",
"get_param_arg",
"(",
"param",
",",
"idx",
",",
"klass",
",",
"arg",
",",
"attr",
"=",
"'id'",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"klass",
")",
":",
"return",
"getattr",
"(",
"arg",
",",
"attr",
")",
"elif",
"isinstance",
"(",
"a... | 38.3 | 14.2 |
def _reverse_transform_column(self, table, metadata, table_name):
"""Reverses the transformtion on a column from table using the given parameters.
Args:
table (pandas.DataFrame): Dataframe containing column to transform.
metadata (dict): Metadata for given column.
ta... | [
"def",
"_reverse_transform_column",
"(",
"self",
",",
"table",
",",
"metadata",
",",
"table_name",
")",
":",
"column_name",
"=",
"metadata",
"[",
"'name'",
"]",
"if",
"column_name",
"not",
"in",
"table",
":",
"return",
"null_name",
"=",
"'?'",
"+",
"column_n... | 44.483871 | 28.387097 |
def div(a,b):
"""``div(a,b)`` is like ``a // b`` if ``b`` devides ``a``, otherwise
an `ValueError` is raised.
>>> div(10,2)
5
>>> div(10,3)
Traceback (most recent call last):
...
ValueError: 3 does not divide 10
"""
res, fail = divmod(a,b)
if fail:
raise ValueError("... | [
"def",
"div",
"(",
"a",
",",
"b",
")",
":",
"res",
",",
"fail",
"=",
"divmod",
"(",
"a",
",",
"b",
")",
"if",
"fail",
":",
"raise",
"ValueError",
"(",
"\"%r does not divide %r\"",
"%",
"(",
"b",
",",
"a",
")",
")",
"else",
":",
"return",
"res"
] | 22.8125 | 19.25 |
def get_range_start_line_number(self,rng):
"""
.. warning:: not implemented
"""
sys.stderr.write("error unimplemented get_range_start_line\n")
sys.exit()
for i in range(0,len(self._lines)):
if rng.cmp(self._lines[i]['rng'])==0: return i+1
return None | [
"def",
"get_range_start_line_number",
"(",
"self",
",",
"rng",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"error unimplemented get_range_start_line\\n\"",
")",
"sys",
".",
"exit",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"s... | 30.666667 | 11.333333 |
def data_manipulation_sh(network):
""" Adds missing components to run calculations with SH scenarios.
Parameters
----------
network : :class:`pypsa.Network
Overall container of PyPSA
"""
from shapely.geometry import Point, LineString, MultiLineString
from geoalchemy2.shap... | [
"def",
"data_manipulation_sh",
"(",
"network",
")",
":",
"from",
"shapely",
".",
"geometry",
"import",
"Point",
",",
"LineString",
",",
"MultiLineString",
"from",
"geoalchemy2",
".",
"shape",
"import",
"from_shape",
",",
"to_shape",
"# add connection from Luebeck to S... | 40.854167 | 22.5 |
def create_tag(self, tags):
"""Create tags for a Point in the language you specify. Tags can only contain alphanumeric (unicode) characters
and the underscore. Tags will be stored lower-cased.
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing t... | [
"def",
"create_tag",
"(",
"self",
",",
"tags",
")",
":",
"if",
"isinstance",
"(",
"tags",
",",
"str",
")",
":",
"tags",
"=",
"[",
"tags",
"]",
"evt",
"=",
"self",
".",
"_client",
".",
"_request_point_tag_update",
"(",
"self",
".",
"_type",
",",
"self... | 48.722222 | 29.166667 |
def obsoleteas(self, to='name_short'):
"""
Return obsolete countries in the specified classification
Parameters
----------
to : str, optional
Output classification (valid str for an index of
country_data file), default: name_short
Returns
... | [
"def",
"obsoleteas",
"(",
"self",
",",
"to",
"=",
"'name_short'",
")",
":",
"if",
"isinstance",
"(",
"to",
",",
"str",
")",
":",
"to",
"=",
"[",
"to",
"]",
"return",
"self",
".",
"data",
"[",
"self",
".",
"data",
".",
"obsolete",
">",
"0",
"]",
... | 25.333333 | 19 |
def tell(self, solutions, function_values, check_points=None,
copy=False):
"""pass objective function values to prepare for next
iteration. This core procedure of the CMA-ES algorithm updates
all state variables, in particular the two evolution paths, the
distribution mean, ... | [
"def",
"tell",
"(",
"self",
",",
"solutions",
",",
"function_values",
",",
"check_points",
"=",
"None",
",",
"copy",
"=",
"False",
")",
":",
"if",
"self",
".",
"_flgtelldone",
":",
"raise",
"_Error",
"(",
"'tell should only be called once per iteration'",
")",
... | 47.660194 | 25.964401 |
def checkBim(fileName, minNumber, chromosome):
"""Checks the BIM file for chrN markers.
:param fileName:
:param minNumber:
:param chromosome:
:type fileName: str
:type minNumber: int
:type chromosome: str
:returns: ``True`` if there are at least ``minNumber`` markers on
... | [
"def",
"checkBim",
"(",
"fileName",
",",
"minNumber",
",",
"chromosome",
")",
":",
"nbMarkers",
"=",
"0",
"with",
"open",
"(",
"fileName",
",",
"'r'",
")",
"as",
"inputFile",
":",
"for",
"line",
"in",
"inputFile",
":",
"row",
"=",
"line",
".",
"rstrip"... | 26.25 | 18.125 |
def check_get_revoked(self):
"""
Create a CRL object with 100 Revoked objects, then call the
get_revoked method repeatedly.
"""
crl = CRL()
for i in xrange(100):
crl.add_revoked(Revoked())
for i in xrange(self.iterations):
crl.get_revoked() | [
"def",
"check_get_revoked",
"(",
"self",
")",
":",
"crl",
"=",
"CRL",
"(",
")",
"for",
"i",
"in",
"xrange",
"(",
"100",
")",
":",
"crl",
".",
"add_revoked",
"(",
"Revoked",
"(",
")",
")",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"iterations",
... | 31.1 | 8.7 |
def _set_lang_settings(self, lang_settings):
""" Checks and sets the per language WPM, singular and plural values.
"""
is_int = isinstance(lang_settings, int)
is_dict = isinstance(lang_settings, dict)
if not is_int and not is_dict:
raise TypeError(("Settings 'READTIME... | [
"def",
"_set_lang_settings",
"(",
"self",
",",
"lang_settings",
")",
":",
"is_int",
"=",
"isinstance",
"(",
"lang_settings",
",",
"int",
")",
"is_dict",
"=",
"isinstance",
"(",
"lang_settings",
",",
"dict",
")",
"if",
"not",
"is_int",
"and",
"not",
"is_dict"... | 45.902439 | 22.682927 |
def conv3x3(in_channels, out_channels, stride=1):
"""
3x3 convolution with padding.
Original code has had bias turned off, because Batch Norm would remove the bias either way
"""
return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False) | [
"def",
"conv3x3",
"(",
"in_channels",
",",
"out_channels",
",",
"stride",
"=",
"1",
")",
":",
"return",
"nn",
".",
"Conv2d",
"(",
"in_channels",
",",
"out_channels",
",",
"kernel_size",
"=",
"3",
",",
"stride",
"=",
"stride",
",",
"padding",
"=",
"1",
... | 48.333333 | 21.666667 |
def import_class(classpath):
"""Import the class referred to by the fully qualified class path.
Args:
classpath: A full "foo.bar.MyClass" path to a class definition.
Returns:
The class referred to by the classpath.
Raises:
ImportError: If an error occurs while importing the mo... | [
"def",
"import_class",
"(",
"classpath",
")",
":",
"modname",
",",
"classname",
"=",
"classpath",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"modname",
")",
"klass",
"=",
"getattr",
"(",
"module",
"... | 32.117647 | 21.117647 |
def initialize(self):
'''List all datasets for a given ...'''
fmt = guess_format(self.source.url)
# if format can't be guessed from the url
# we fallback on the declared Content-Type
if not fmt:
response = requests.head(self.source.url)
mime_type = respons... | [
"def",
"initialize",
"(",
"self",
")",
":",
"fmt",
"=",
"guess_format",
"(",
"self",
".",
"source",
".",
"url",
")",
"# if format can't be guessed from the url",
"# we fallback on the declared Content-Type",
"if",
"not",
"fmt",
":",
"response",
"=",
"requests",
".",... | 47.588235 | 16.294118 |
def mkron(a, *args):
"""Kronecker product of all the arguments"""
if not isinstance(a, list):
a = [a]
a = list(a) # copy list
for i in args:
if isinstance(i, list):
a.extend(i)
else:
a.append(i)
c = _vector.vector()
c.d = 0
c.n = _np.array([]... | [
"def",
"mkron",
"(",
"a",
",",
"*",
"args",
")",
":",
"if",
"not",
"isinstance",
"(",
"a",
",",
"list",
")",
":",
"a",
"=",
"[",
"a",
"]",
"a",
"=",
"list",
"(",
"a",
")",
"# copy list",
"for",
"i",
"in",
"args",
":",
"if",
"isinstance",
"(",... | 25.846154 | 19.461538 |
def datetime(self):
"""
Returns a datetime object of the month, day, year, and time the game
was played.
"""
date_string = '%s %s' % (self._date, self._year)
date_string = re.sub(r' \(\d+\)', '', date_string)
return datetime.strptime(date_string, '%A, %b %d %Y') | [
"def",
"datetime",
"(",
"self",
")",
":",
"date_string",
"=",
"'%s %s'",
"%",
"(",
"self",
".",
"_date",
",",
"self",
".",
"_year",
")",
"date_string",
"=",
"re",
".",
"sub",
"(",
"r' \\(\\d+\\)'",
",",
"''",
",",
"date_string",
")",
"return",
"datetim... | 38.875 | 16.625 |
def status(name=None, user=None, conf_file=None, bin_env=None):
'''
List programs and its state
user
user to run supervisorctl as
conf_file
path to supervisord config file
bin_env
path to supervisorctl bin or path to virtualenv with supervisor
installed
CLI Exam... | [
"def",
"status",
"(",
"name",
"=",
"None",
",",
"user",
"=",
"None",
",",
"conf_file",
"=",
"None",
",",
"bin_env",
"=",
"None",
")",
":",
"all_process",
"=",
"{",
"}",
"for",
"line",
"in",
"status_raw",
"(",
"name",
",",
"user",
",",
"conf_file",
... | 27.5 | 23.5 |
def generate(self, project):
"""
Package name construction is based on provider, not on prefix.
Prefix does not have to equal provider_prefix.
"""
for assignment in self.s2n_mapping:
if assignment["ipprefix"] == project:
self._name = assignment["package"]
return self
#
# github.com -> github
... | [
"def",
"generate",
"(",
"self",
",",
"project",
")",
":",
"for",
"assignment",
"in",
"self",
".",
"s2n_mapping",
":",
"if",
"assignment",
"[",
"\"ipprefix\"",
"]",
"==",
"project",
":",
"self",
".",
"_name",
"=",
"assignment",
"[",
"\"package\"",
"]",
"r... | 25.745098 | 17.901961 |
def load_hpo_terms(adapter, hpo_lines=None, hpo_gene_lines=None, alias_genes=None):
"""Load the hpo terms into the database
Parse the hpo lines, build the objects and add them to the database
Args:
adapter(MongoAdapter)
hpo_lines(iterable(str))
hpo_gene_lines(iterable(str))... | [
"def",
"load_hpo_terms",
"(",
"adapter",
",",
"hpo_lines",
"=",
"None",
",",
"hpo_gene_lines",
"=",
"None",
",",
"alias_genes",
"=",
"None",
")",
":",
"# Store the hpo terms",
"hpo_terms",
"=",
"{",
"}",
"# Fetch the hpo terms if no file",
"if",
"not",
"hpo_lines"... | 29.068493 | 19.561644 |
def _get_mixed_actions(labeling_bits, equation_tup, trans_recips):
"""
From a labeling for player 0, a tuple of hyperplane equations of the
polar polytopes, and a tuple of the reciprocals of the translations,
return a tuple of the corresponding, normalized mixed actions.
Parameters
----------
... | [
"def",
"_get_mixed_actions",
"(",
"labeling_bits",
",",
"equation_tup",
",",
"trans_recips",
")",
":",
"m",
",",
"n",
"=",
"equation_tup",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
"-",
"1",
",",
"equation_tup",
"[",
"1",
"]",
".",
"shape",
"[",
"0... | 33.238095 | 21.380952 |
def cumulative_max(self):
"""
Return the cumulative maximum value of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
maximum value of all the elements preceding and including it. The
SArray is expected to be of numeric type (int,... | [
"def",
"cumulative_max",
"(",
"self",
")",
":",
"from",
".",
".",
"import",
"extensions",
"agg_op",
"=",
"\"__builtin__cum_max__\"",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"builtin_cumulative_aggregate",
"(",
"agg_op",
")",
")"
] | 29.821429 | 22.25 |
def get_zone_variable(self, zone_id, variable):
""" Retrieve the current value of a zone variable. If the variable is
not found in the local cache then the value is requested from the
controller. """
try:
return self._retrieve_cached_zone_variable(zone_id, variable)
... | [
"def",
"get_zone_variable",
"(",
"self",
",",
"zone_id",
",",
"variable",
")",
":",
"try",
":",
"return",
"self",
".",
"_retrieve_cached_zone_variable",
"(",
"zone_id",
",",
"variable",
")",
"except",
"UncachedVariable",
":",
"return",
"(",
"yield",
"from",
"s... | 44.9 | 17.9 |
def add_property(self, *args, **kwargs):
# type: (*Any, **Any) -> Property
"""Add a new property to this model.
See :class:`pykechain.Client.create_property` for available parameters.
:return: :class:`Property`
:raises APIError: in case an Error occurs
"""
if se... | [
"def",
"add_property",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (*Any, **Any) -> Property",
"if",
"self",
".",
"category",
"!=",
"Category",
".",
"MODEL",
":",
"raise",
"APIError",
"(",
"\"Part should be of category MODEL\"",
")... | 36.076923 | 17.384615 |
def logged(level=logging.DEBUG):
"""
Useful logging decorator. If a method is logged, the beginning and end of
the method call will be logged at a pre-specified level.
Args:
level: Level to log method at. Defaults to DEBUG.
"""
def wrap(f):
_logger = logging.getLogger("{}.{}".fo... | [
"def",
"logged",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"_logger",
"=",
"logging",
".",
"getLogger",
"(",
"\"{}.{}\"",
".",
"format",
"(",
"f",
".",
"__module__",
",",
"f",
".",
"__name__",
")",
")"... | 36.761905 | 23.238095 |
def _uniqualize(d):
'''
d = {1:'a',2:'b',3:'c',4:'b'}
_uniqualize(d)
'''
pt = copy.deepcopy(d)
seqs_for_del =[]
vset = set({})
for k in pt:
vset.add(pt[k])
tslen = vset.__len__()
freq = {}
for k in pt:
v = pt[k]
if(v in freq):
freq[... | [
"def",
"_uniqualize",
"(",
"d",
")",
":",
"pt",
"=",
"copy",
".",
"deepcopy",
"(",
"d",
")",
"seqs_for_del",
"=",
"[",
"]",
"vset",
"=",
"set",
"(",
"{",
"}",
")",
"for",
"k",
"in",
"pt",
":",
"vset",
".",
"add",
"(",
"pt",
"[",
"k",
"]",
"... | 19.666667 | 20.333333 |
def plot_figures():
"""Plot figures for tutorial."""
numpy.random.seed(1000)
def foo(coord, param):
return param[0] * numpy.e ** (-param[1] * coord)
coord = numpy.linspace(0, 10, 200)
distribution = cp.J(cp.Uniform(1, 2), cp.Uniform(0.1, 0.2))
samples = distribution.sample(50)
ev... | [
"def",
"plot_figures",
"(",
")",
":",
"numpy",
".",
"random",
".",
"seed",
"(",
"1000",
")",
"def",
"foo",
"(",
"coord",
",",
"param",
")",
":",
"return",
"param",
"[",
"0",
"]",
"*",
"numpy",
".",
"e",
"**",
"(",
"-",
"param",
"[",
"1",
"]",
... | 31.859155 | 19.239437 |
def sortable_title(portal, title):
"""Convert title to sortable title
"""
if not title:
return ''
def_charset = portal.plone_utils.getSiteEncoding()
sortabletitle = str(title.lower().strip())
# Replace numbers with zero filled numbers
sortabletitle = num_sort_regex.sub(zero_fill, so... | [
"def",
"sortable_title",
"(",
"portal",
",",
"title",
")",
":",
"if",
"not",
"title",
":",
"return",
"''",
"def_charset",
"=",
"portal",
".",
"plone_utils",
".",
"getSiteEncoding",
"(",
")",
"sortabletitle",
"=",
"str",
"(",
"title",
".",
"lower",
"(",
"... | 34.956522 | 17.521739 |
def _waitAny(*children):
"""Waits on any child Future created by the calling Future.
:param children: A tuple of children Future objects spawned by the calling
Future.
:return: A generator function that iterates on futures that are done.
The generator produces results of the children in a non... | [
"def",
"_waitAny",
"(",
"*",
"children",
")",
":",
"n",
"=",
"len",
"(",
"children",
")",
"# check for available results and index those unavailable",
"for",
"index",
",",
"future",
"in",
"enumerate",
"(",
"children",
")",
":",
"if",
"future",
".",
"exceptionVal... | 36.971429 | 17.571429 |
def mission_clear_all_send(self, target_system, target_component, force_mavlink1=False):
'''
Delete all mission items at once.
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
'''
... | [
"def",
"mission_clear_all_send",
"(",
"self",
",",
"target_system",
",",
"target_component",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"mission_clear_all_encode",
"(",
"target_system",
",",
"target_component",
... | 47.888889 | 35 |
def brightness(self, value=1.0):
"""Increases or decreases the brightness in the layer.
The given value is a percentage to increase
or decrease the image brightness,
for example 0.8 means brightness at 80%.
"""
b = ImageEnhance.Brightness(self.img)
... | [
"def",
"brightness",
"(",
"self",
",",
"value",
"=",
"1.0",
")",
":",
"b",
"=",
"ImageEnhance",
".",
"Brightness",
"(",
"self",
".",
"img",
")",
"self",
".",
"img",
"=",
"b",
".",
"enhance",
"(",
"value",
")"
] | 28.25 | 15.5 |
async def webhooks(self):
"""|coro|
Gets the list of webhooks from this channel.
Requires :attr:`~.Permissions.manage_webhooks` permissions.
Raises
-------
Forbidden
You don't have permissions to get the webhooks.
Returns
--------
L... | [
"async",
"def",
"webhooks",
"(",
"self",
")",
":",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"channel_webhooks",
"(",
"self",
".",
"id",
")",
"return",
"[",
"Webhook",
".",
"from_state",
"(",
"d",
",",
"state",
"=",
"self",
".",
... | 25.7 | 23.1 |
def get_bounding_box(
self, resource, resolution, _id, bb_type,
url_prefix, auth, session, send_opts):
"""Get bounding box containing object specified by id.
Currently only supports 'loose' bounding boxes. The bounding box
returned is cuboid aligned.
Args:
... | [
"def",
"get_bounding_box",
"(",
"self",
",",
"resource",
",",
"resolution",
",",
"_id",
",",
"bb_type",
",",
"url_prefix",
",",
"auth",
",",
"session",
",",
"send_opts",
")",
":",
"if",
"not",
"isinstance",
"(",
"resource",
",",
"ChannelResource",
")",
":"... | 42 | 23.386364 |
def requires_authentication(fn):
"""
Requires that the calling Subject be authenticated before allowing access.
"""
@functools.wraps(fn)
def wrap(*args, **kwargs):
subject = WebYosai.get_current_subject()
if not subject.authenticated:
msg... | [
"def",
"requires_authentication",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"subject",
"=",
"WebYosai",
".",
"get_current_subject",
"(",
")",
"if",
"not",
... | 33.933333 | 20.333333 |
def get_compound_ids(self):
"""Extract the current compound ids in the database. Updates the self.compound_ids list
"""
cursor = self.conn.cursor()
cursor.execute('SELECT inchikey_id FROM metab_compound')
self.conn.commit()
for row in cursor:
if not row[0] in ... | [
"def",
"get_compound_ids",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"'SELECT inchikey_id FROM metab_compound'",
")",
"self",
".",
"conn",
".",
"commit",
"(",
")",
"for",
"row",
"in",... | 42.111111 | 9.444444 |
def determine_file_type(self, z):
"""Determine file type."""
content = z.read('[Content_Types].xml')
with io.BytesIO(content) as b:
encoding = self._analyze_file(b)
if encoding is None:
encoding = 'utf-8'
b.seek(0)
text = b.read().... | [
"def",
"determine_file_type",
"(",
"self",
",",
"z",
")",
":",
"content",
"=",
"z",
".",
"read",
"(",
"'[Content_Types].xml'",
")",
"with",
"io",
".",
"BytesIO",
"(",
"content",
")",
"as",
"b",
":",
"encoding",
"=",
"self",
".",
"_analyze_file",
"(",
"... | 41.818182 | 13.181818 |
def _create_executor(self, handler, args, cpus_per_worker=1):
"""Return a new :class:`.Executor` instance."""
if self._args.parallel > 0:
workers = self._args.parallel
else:
try:
workers = mp.cpu_count() // cpus_per_worker
except NotImplemented... | [
"def",
"_create_executor",
"(",
"self",
",",
"handler",
",",
"args",
",",
"cpus_per_worker",
"=",
"1",
")",
":",
"if",
"self",
".",
"_args",
".",
"parallel",
">",
"0",
":",
"workers",
"=",
"self",
".",
"_args",
".",
"parallel",
"else",
":",
"try",
":... | 36.52381 | 17.238095 |
def execute(self, sources, sink, interval, alignment_stream=None):
"""
Execute the tool over the given time interval.
If an alignment stream is given, the output instances will be aligned to this stream
:param sources: The source streams (possibly None)
:param sink: The sink str... | [
"def",
"execute",
"(",
"self",
",",
"sources",
",",
"sink",
",",
"interval",
",",
"alignment_stream",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"interval",
",",
"TimeInterval",
")",
":",
"raise",
"TypeError",
"(",
"'Expected TimeInterval, got {}'"... | 42.387755 | 20.959184 |
def _get_attribute_tensors(onnx_model_proto): # type: (ModelProto) -> Iterable[TensorProto]
"""Create an iterator of tensors from node attributes of an ONNX model."""
for node in onnx_model_proto.graph.node:
for attribute in node.attribute:
if attribute.HasField("t"):
yield ... | [
"def",
"_get_attribute_tensors",
"(",
"onnx_model_proto",
")",
":",
"# type: (ModelProto) -> Iterable[TensorProto]",
"for",
"node",
"in",
"onnx_model_proto",
".",
"graph",
".",
"node",
":",
"for",
"attribute",
"in",
"node",
".",
"attribute",
":",
"if",
"attribute",
... | 49.75 | 10 |
def convert_video(fieldfile, force=False):
"""
Converts a given video file into all defined formats.
"""
instance = fieldfile.instance
field = fieldfile.field
filename = os.path.basename(fieldfile.path)
source_path = fieldfile.path
encoding_backend = get_backend()
for options in s... | [
"def",
"convert_video",
"(",
"fieldfile",
",",
"force",
"=",
"False",
")",
":",
"instance",
"=",
"fieldfile",
".",
"instance",
"field",
"=",
"fieldfile",
".",
"field",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"fieldfile",
".",
"path",
")... | 31.945455 | 17.036364 |
def merge(cls, components):
"""Merges components into a single component, applying their actions appropriately.
This operation is associative: M(M(a, b), c) == M(a, M(b, c)) == M(a, b, c).
:param list components: an iterable of instances of DictValueComponent.
:return: An instance representing the re... | [
"def",
"merge",
"(",
"cls",
",",
"components",
")",
":",
"# Note that action of the merged component is EXTEND until the first REPLACE is encountered.",
"# This guarantees associativity.",
"action",
"=",
"cls",
".",
"EXTEND",
"val",
"=",
"{",
"}",
"for",
"component",
"in",
... | 39.909091 | 20.363636 |
def dump_to_stream(self, cnf, stream, **opts):
"""
:param cnf: Configuration data to dump
:param stream: Config file or file like object write to
:param opts: optional keyword parameters
"""
tree = container_to_etree(cnf, **opts)
etree_write(tree, stream) | [
"def",
"dump_to_stream",
"(",
"self",
",",
"cnf",
",",
"stream",
",",
"*",
"*",
"opts",
")",
":",
"tree",
"=",
"container_to_etree",
"(",
"cnf",
",",
"*",
"*",
"opts",
")",
"etree_write",
"(",
"tree",
",",
"stream",
")"
] | 38 | 7 |
def _get_relationship_cell_val(self, obj, column):
"""
Return the value to insert in a relationship cell
Handle the case of complex related datas we want to handle
"""
val = SqlaExporter._get_relationship_cell_val(self, obj, column)
if val == "":
related_key =... | [
"def",
"_get_relationship_cell_val",
"(",
"self",
",",
"obj",
",",
"column",
")",
":",
"val",
"=",
"SqlaExporter",
".",
"_get_relationship_cell_val",
"(",
"self",
",",
"obj",
",",
"column",
")",
"if",
"val",
"==",
"\"\"",
":",
"related_key",
"=",
"column",
... | 36.346154 | 16.423077 |
def _load_version1(self, filename):
"""load a version 1 pest control file information
Parameters
----------
filename : str
pst filename
Raises
------
lots of exceptions for incorrect format
"""
f = open(filename, 'r')
f.... | [
"def",
"_load_version1",
"(",
"self",
",",
"filename",
")",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"f",
".",
"readline",
"(",
")",
"#control section",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"assert",
"\"* control data\"",
"in",
... | 40.829384 | 18.781991 |
def _in_deferred_types(self, cls):
"""
Check if the given class is specified in the deferred type registry.
Returns the printer from the registry if it exists, and None if the
class is not in the registry. Successful matches will be moved to the
regular type registry for future ... | [
"def",
"_in_deferred_types",
"(",
"self",
",",
"cls",
")",
":",
"mod",
"=",
"getattr",
"(",
"cls",
",",
"'__module__'",
",",
"None",
")",
"name",
"=",
"getattr",
"(",
"cls",
",",
"'__name__'",
",",
"None",
")",
"key",
"=",
"(",
"mod",
",",
"name",
... | 40.470588 | 15.294118 |
def format(args):
"""
%prog format gffile > formatted.gff
Read in the gff and print it out, changing seqid, etc.
"""
from jcvi.formats.obo import load_GODag, validate_term
valid_multiparent_ops = ["split", "merge"]
p = OptionParser(format.__doc__)
g1 = OptionGroup(p, "Parameter(s) us... | [
"def",
"format",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"obo",
"import",
"load_GODag",
",",
"validate_term",
"valid_multiparent_ops",
"=",
"[",
"\"split\"",
",",
"\"merge\"",
"]",
"p",
"=",
"OptionParser",
"(",
"format",
".",
"__doc__",
... | 43.049383 | 21.528395 |
def add_peak_demand(self):
"""Summarizes peak loads of underlying load_areas in kVA.
(peak load sum and peak load of satellites)
"""
peak_load = peak_load_satellites = 0
for lv_load_area in self.lv_load_areas():
peak_load += lv_load_area.peak_load
... | [
"def",
"add_peak_demand",
"(",
"self",
")",
":",
"peak_load",
"=",
"peak_load_satellites",
"=",
"0",
"for",
"lv_load_area",
"in",
"self",
".",
"lv_load_areas",
"(",
")",
":",
"peak_load",
"+=",
"lv_load_area",
".",
"peak_load",
"if",
"lv_load_area",
".",
"is_s... | 41.166667 | 10.166667 |
def compile_excludes(self):
"""Compile a set of regexps for files to be exlcuded from scans."""
self.compiled_exclude_files = []
for pattern in self.exclude_files:
try:
self.compiled_exclude_files.append(re.compile(pattern))
except re.error as e:
... | [
"def",
"compile_excludes",
"(",
"self",
")",
":",
"self",
".",
"compiled_exclude_files",
"=",
"[",
"]",
"for",
"pattern",
"in",
"self",
".",
"exclude_files",
":",
"try",
":",
"self",
".",
"compiled_exclude_files",
".",
"append",
"(",
"re",
".",
"compile",
... | 46.222222 | 13.666667 |
def generate(self):
"""
Generates a new token for this column based on its bit length. This method
will not ensure uniqueness in the model itself, that should be checked against
the model records in the database first.
:return: <str>
"""
try:
mode... | [
"def",
"generate",
"(",
"self",
")",
":",
"try",
":",
"model",
"=",
"self",
".",
"schema",
"(",
")",
".",
"model",
"(",
")",
"except",
"AttributeError",
":",
"return",
"os",
".",
"urandom",
"(",
"self",
".",
"__bits",
")",
".",
"encode",
"(",
"'hex... | 36.941176 | 19.882353 |
def get_languages(self, target_language=None):
"""Get list of supported languages for translation.
Response
See
https://cloud.google.com/translate/docs/discovering-supported-languages
:type target_language: str
:param target_language: (Optional) The language used to lo... | [
"def",
"get_languages",
"(",
"self",
",",
"target_language",
"=",
"None",
")",
":",
"query_params",
"=",
"{",
"}",
"if",
"target_language",
"is",
"None",
":",
"target_language",
"=",
"self",
".",
"target_language",
"if",
"target_language",
"is",
"not",
"None",... | 42.310345 | 22.724138 |
def Parse(self, stat, file_object, knowledge_base):
"""Parse the netgroup file and return User objects.
Lines are of the form:
group1 (-,user1,) (-,user2,) (-,user3,)
Groups are ignored, we return users in lines that match the filter regexes,
or all users in the file if no filters are specified.... | [
"def",
"Parse",
"(",
"self",
",",
"stat",
",",
"file_object",
",",
"knowledge_base",
")",
":",
"_",
",",
"_",
"=",
"stat",
",",
"knowledge_base",
"lines",
"=",
"[",
"l",
".",
"strip",
"(",
")",
"for",
"l",
"in",
"utils",
".",
"ReadFileBytesAsUnicode",
... | 28.846154 | 22 |
def _create_new_thread_loop(self):
"""
Create a daemonized thread that will run Tornado IOLoop.
:return: the IOLoop backed by the new thread.
"""
self._thread_loop = ThreadLoop()
if not self._thread_loop.is_ready():
self._thread_loop.start()
return sel... | [
"def",
"_create_new_thread_loop",
"(",
"self",
")",
":",
"self",
".",
"_thread_loop",
"=",
"ThreadLoop",
"(",
")",
"if",
"not",
"self",
".",
"_thread_loop",
".",
"is_ready",
"(",
")",
":",
"self",
".",
"_thread_loop",
".",
"start",
"(",
")",
"return",
"s... | 37.222222 | 5.666667 |
def convert_options(settings, defaults=None):
"""
Convert a settings object (or dictionary) to parameters which may be passed
to a new ``Client()`` instance.
"""
if defaults is None:
defaults = {}
if isinstance(settings, dict):
def getopt(key, default=None):
return s... | [
"def",
"convert_options",
"(",
"settings",
",",
"defaults",
"=",
"None",
")",
":",
"if",
"defaults",
"is",
"None",
":",
"defaults",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"settings",
",",
"dict",
")",
":",
"def",
"getopt",
"(",
"key",
",",
"default",
... | 38.781818 | 18.672727 |
def localize_datetime(datetime_obj, tz=pytz.utc):
"""Converts a naive or UTC-localized date into the provided timezone.
:param datetime_obj: The datetime object.
:type datetime_obj: datetime
:param tz: The timezone. If blank or None, UTC is used.
:type tz: datetime.tzinfo
:return: The localized... | [
"def",
"localize_datetime",
"(",
"datetime_obj",
",",
"tz",
"=",
"pytz",
".",
"utc",
")",
":",
"if",
"not",
"datetime_obj",
".",
"tzinfo",
":",
"return",
"tz",
".",
"localize",
"(",
"datetime_obj",
")",
"else",
":",
"try",
":",
"return",
"datetime_obj",
... | 35.631579 | 12.263158 |
def htmlize_paragraphs(text):
"""
Convert paragraphs delimited by blank lines into HTML text enclosed
in <p> tags.
"""
paragraphs = re.split('(\r?\n)\s*(\r?\n)', text)
return '\n'.join('<p>%s</p>' % paragraph for paragraph in paragraphs) | [
"def",
"htmlize_paragraphs",
"(",
"text",
")",
":",
"paragraphs",
"=",
"re",
".",
"split",
"(",
"'(\\r?\\n)\\s*(\\r?\\n)'",
",",
"text",
")",
"return",
"'\\n'",
".",
"join",
"(",
"'<p>%s</p>'",
"%",
"paragraph",
"for",
"paragraph",
"in",
"paragraphs",
")"
] | 36.428571 | 15.857143 |
def init_strate(self, global_setting, quant_frame, event_engine):
"""TinyQuantFrame 初始化策略的接口"""
if type(self._quant_frame) is not int:
return True
self._quant_frame = quant_frame
self._event_engine = event_engine
init_ret = self.__loadSetting(global_setting)
... | [
"def",
"init_strate",
"(",
"self",
",",
"global_setting",
",",
"quant_frame",
",",
"event_engine",
")",
":",
"if",
"type",
"(",
"self",
".",
"_quant_frame",
")",
"is",
"not",
"int",
":",
"return",
"True",
"self",
".",
"_quant_frame",
"=",
"quant_frame",
"s... | 36.090909 | 26.5 |
def create(input_shape):
""" Vel factory function """
if isinstance(input_shape, numbers.Number):
input_shape = (input_shape,)
elif not isinstance(input_shape, tuple):
input_shape = tuple(input_shape)
def instantiate(**_):
return NormalizeObservations(input_shape)
return Mo... | [
"def",
"create",
"(",
"input_shape",
")",
":",
"if",
"isinstance",
"(",
"input_shape",
",",
"numbers",
".",
"Number",
")",
":",
"input_shape",
"=",
"(",
"input_shape",
",",
")",
"elif",
"not",
"isinstance",
"(",
"input_shape",
",",
"tuple",
")",
":",
"in... | 31 | 12.636364 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.