text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def ensureKeysAreSetup(self):
"""
Check whether the keys are setup in the local STP keep.
Raises KeysNotFoundException if not found.
"""
if not areKeysSetup(self.name, self.keys_dir):
raise REx(REx.reason.format(self.name) + self.keygenScript) | [
"def",
"ensureKeysAreSetup",
"(",
"self",
")",
":",
"if",
"not",
"areKeysSetup",
"(",
"self",
".",
"name",
",",
"self",
".",
"keys_dir",
")",
":",
"raise",
"REx",
"(",
"REx",
".",
"reason",
".",
"format",
"(",
"self",
".",
"name",
")",
"+",
"self",
... | 41.285714 | 12.714286 |
def toggle_use_font_background_sensitivity(self, chk):
"""If the user chooses to use the gnome default font
configuration it means that he will not be able to use the
font selector.
"""
self.get_widget('palette_16').set_sensitive(chk.get_active())
self.get_widget('palette... | [
"def",
"toggle_use_font_background_sensitivity",
"(",
"self",
",",
"chk",
")",
":",
"self",
".",
"get_widget",
"(",
"'palette_16'",
")",
".",
"set_sensitive",
"(",
"chk",
".",
"get_active",
"(",
")",
")",
"self",
".",
"get_widget",
"(",
"'palette_17'",
")",
... | 50.142857 | 16.571429 |
def p_continue_statement_1(self, p):
"""continue_statement : CONTINUE SEMI
| CONTINUE AUTOSEMI
"""
p[0] = self.asttypes.Continue()
p[0].setpos(p) | [
"def",
"p_continue_statement_1",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Continue",
"(",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | 33.666667 | 5.333333 |
def setTopLevelItems( self, items ):
"""
Initializes the navigation system to start with the inputed root \
item.
:param item | <XNavigationItem>
"""
if ( not self._navigationModel ):
self.setNavigationModel(XNavigationModel(self))
... | [
"def",
"setTopLevelItems",
"(",
"self",
",",
"items",
")",
":",
"if",
"(",
"not",
"self",
".",
"_navigationModel",
")",
":",
"self",
".",
"setNavigationModel",
"(",
"XNavigationModel",
"(",
"self",
")",
")",
"self",
".",
"_navigationModel",
".",
"setTopLevel... | 32.545455 | 15.090909 |
def search_memories(self):
"""
Search and return list of 1-wire memories.
"""
if not self.connected:
raise NotConnected()
return self._cf.mem.get_mems(MemoryElement.TYPE_1W) | [
"def",
"search_memories",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"raise",
"NotConnected",
"(",
")",
"return",
"self",
".",
"_cf",
".",
"mem",
".",
"get_mems",
"(",
"MemoryElement",
".",
"TYPE_1W",
")"
] | 31.285714 | 8.714286 |
def invoke(
self,
cli,
args=None,
prog_name=None,
input=None,
terminate_input=False,
env=None,
_output_lines=None,
**extra
):
"""Like :meth:`CliRunner.invoke` but displays what the user
would enter in the terminal for env vars, ... | [
"def",
"invoke",
"(",
"self",
",",
"cli",
",",
"args",
"=",
"None",
",",
"prog_name",
"=",
"None",
",",
"input",
"=",
"None",
",",
"terminate_input",
"=",
"False",
",",
"env",
"=",
"None",
",",
"_output_lines",
"=",
"None",
",",
"*",
"*",
"extra",
... | 30.040816 | 22.489796 |
def source_channels(self):
""" Returns a set describing the source channels on which the gate is defined. """
source_channels = [v.coordinates.keys() for v in self.verts]
return set(itertools.chain(*source_channels)) | [
"def",
"source_channels",
"(",
"self",
")",
":",
"source_channels",
"=",
"[",
"v",
".",
"coordinates",
".",
"keys",
"(",
")",
"for",
"v",
"in",
"self",
".",
"verts",
"]",
"return",
"set",
"(",
"itertools",
".",
"chain",
"(",
"*",
"source_channels",
")"... | 59.25 | 13.75 |
def compute_duration_measures(self):
""" Helper function for computing measures derived from timing information.
These are only computed if the response is textgrid with timing information.
All times are in seconds.
"""
prefix = "TIMING_" + self.current_similarity_measure + "_... | [
"def",
"compute_duration_measures",
"(",
"self",
")",
":",
"prefix",
"=",
"\"TIMING_\"",
"+",
"self",
".",
"current_similarity_measure",
"+",
"\"_\"",
"+",
"self",
".",
"current_collection_type",
"+",
"\"_\"",
"if",
"self",
".",
"response_format",
"==",
"'TextGrid... | 52.909091 | 35.090909 |
def set_quantity(self, twig=None, value=None, **kwargs):
"""
TODO: add documentation
"""
# TODO: handle twig having parameter key (value@, default_unit@, adjust@, etc)
# TODO: does this return anything (update the docstring)?
return self.get_parameter(twig=twig, **kwargs)... | [
"def",
"set_quantity",
"(",
"self",
",",
"twig",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: handle twig having parameter key (value@, default_unit@, adjust@, etc)",
"# TODO: does this return anything (update the docstring)?",
"return",... | 50 | 20.857143 |
def assignrepr(self, prefix) -> str:
"""Return a string representation of the actual |anntools.ANN| object
that is prefixed with the given string."""
prefix = '%s%s(' % (prefix, self.name)
blanks = len(prefix)*' '
lines = [
objecttools.assignrepr_value(
... | [
"def",
"assignrepr",
"(",
"self",
",",
"prefix",
")",
"->",
"str",
":",
"prefix",
"=",
"'%s%s('",
"%",
"(",
"prefix",
",",
"self",
".",
"name",
")",
"blanks",
"=",
"len",
"(",
"prefix",
")",
"*",
"' '",
"lines",
"=",
"[",
"objecttools",
".",
"assig... | 51.375 | 13.833333 |
def get_postgres_encoding(python_encoding: str) -> str:
"""Python to postgres encoding map."""
encoding = normalize_encoding(python_encoding.lower())
encoding_ = aliases.aliases[encoding.replace('_', '', 1)].upper()
pg_encoding = PG_ENCODING_MAP[encoding_.replace('_', '')]
return pg_encoding | [
"def",
"get_postgres_encoding",
"(",
"python_encoding",
":",
"str",
")",
"->",
"str",
":",
"encoding",
"=",
"normalize_encoding",
"(",
"python_encoding",
".",
"lower",
"(",
")",
")",
"encoding_",
"=",
"aliases",
".",
"aliases",
"[",
"encoding",
".",
"replace",... | 38.375 | 22.625 |
def make_doc_id_range(doc_id):
'''Construct a tuple(begin, end) of one-tuple kvlayer keys from a
hexdigest doc_id.
'''
assert len(doc_id) == 32, 'expecting 32 hex string, not: %r' % doc_id
bin_docid = base64.b16decode(doc_id.upper())
doc_id_range = ((bin_docid,), (bin_docid,))
return doc_id... | [
"def",
"make_doc_id_range",
"(",
"doc_id",
")",
":",
"assert",
"len",
"(",
"doc_id",
")",
"==",
"32",
",",
"'expecting 32 hex string, not: %r'",
"%",
"doc_id",
"bin_docid",
"=",
"base64",
".",
"b16decode",
"(",
"doc_id",
".",
"upper",
"(",
")",
")",
"doc_id_... | 35.333333 | 21.777778 |
def returner(ret):
'''
Return data to an odbc server
'''
conn = _get_conn(ret)
cur = conn.cursor()
sql = '''INSERT INTO salt_returns
(fun, jid, retval, id, success, full_ret)
VALUES (?, ?, ?, ?, ?, ?)'''
cur.execute(
sql, (
ret['fun'],
... | [
"def",
"returner",
"(",
"ret",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"ret",
")",
"cur",
"=",
"conn",
".",
"cursor",
"(",
")",
"sql",
"=",
"'''INSERT INTO salt_returns\n (fun, jid, retval, id, success, full_ret)\n VALUES (?, ?, ?, ?, ?, ?)'''",
"cu... | 24.5 | 17.7 |
def encode(raw):
"""Encode SLIP message."""
return raw \
.replace(bytes([SLIP_ESC]), bytes([SLIP_ESC, SLIP_ESC_ESC])) \
.replace(bytes([SLIP_END]), bytes([SLIP_ESC, SLIP_ESC_END])) | [
"def",
"encode",
"(",
"raw",
")",
":",
"return",
"raw",
".",
"replace",
"(",
"bytes",
"(",
"[",
"SLIP_ESC",
"]",
")",
",",
"bytes",
"(",
"[",
"SLIP_ESC",
",",
"SLIP_ESC_ESC",
"]",
")",
")",
".",
"replace",
"(",
"bytes",
"(",
"[",
"SLIP_END",
"]",
... | 40 | 21.2 |
def run_sambamba_markdup(job, bam):
"""
Marks reads as PCR duplicates using Sambamba
:param JobFunctionWrappingJob job: passed automatically by Toil
:param str bam: FileStoreID for BAM file
:return: FileStoreID for sorted BAM file
:rtype: str
"""
work_dir = job.fileStore.getLocalTempDir... | [
"def",
"run_sambamba_markdup",
"(",
"job",
",",
"bam",
")",
":",
"work_dir",
"=",
"job",
".",
"fileStore",
".",
"getLocalTempDir",
"(",
")",
"job",
".",
"fileStore",
".",
"readGlobalFile",
"(",
"bam",
",",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",... | 37.125 | 14.041667 |
def html_overall_stat(
overall_stat,
digit=5,
overall_param=None,
recommended_list=()):
"""
Return HTML report file overall stat.
:param overall_stat: overall stat
:type overall_stat : dict
:param digit: scale (the number of digits to the right of the decimal point i... | [
"def",
"html_overall_stat",
"(",
"overall_stat",
",",
"digit",
"=",
"5",
",",
"overall_param",
"=",
"None",
",",
"recommended_list",
"=",
"(",
")",
")",
":",
"result",
"=",
"\"\"",
"result",
"+=",
"\"<h2>Overall Statistics : </h2>\\n\"",
"result",
"+=",
"'<table... | 43.227273 | 19.954545 |
def resample(self, inds):
"""Returns copy of constraint, with mask rearranged according to indices
"""
new = copy.deepcopy(self)
for arr in self.arrays:
x = getattr(new, arr)
setattr(new, arr, x[inds])
return new | [
"def",
"resample",
"(",
"self",
",",
"inds",
")",
":",
"new",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"for",
"arr",
"in",
"self",
".",
"arrays",
":",
"x",
"=",
"getattr",
"(",
"new",
",",
"arr",
")",
"setattr",
"(",
"new",
",",
"arr",
"... | 33.625 | 7.75 |
def RegisterArtifact(self,
artifact_rdfvalue,
source="datastore",
overwrite_if_exists=False,
overwrite_system_artifacts=False):
"""Registers a new artifact."""
artifact_name = artifact_rdfvalue.name
if artifact_name ... | [
"def",
"RegisterArtifact",
"(",
"self",
",",
"artifact_rdfvalue",
",",
"source",
"=",
"\"datastore\"",
",",
"overwrite_if_exists",
"=",
"False",
",",
"overwrite_system_artifacts",
"=",
"False",
")",
":",
"artifact_name",
"=",
"artifact_rdfvalue",
".",
"name",
"if",
... | 48.791667 | 15.166667 |
def permissions(cls, instance, db_session=None):
"""
returns all non-resource permissions based on what groups user
belongs and directly set ones for this user
:param instance:
:param db_session:
:return:
"""
db_session = get_db_session(db_session, in... | [
"def",
"permissions",
"(",
"cls",
",",
"instance",
",",
"db_session",
"=",
"None",
")",
":",
"db_session",
"=",
"get_db_session",
"(",
"db_session",
",",
"instance",
")",
"query",
"=",
"db_session",
".",
"query",
"(",
"cls",
".",
"models_proxy",
".",
"Grou... | 36.522727 | 20.568182 |
def find_by_id(cls, id):
"""
Finds a single document by its ID. Throws a
NotFoundException if the document does not exist (the
assumption being if you've got an id you should be
pretty certain the thing exists)
"""
obj = cls.find_one(cls._id_spec(id))
if n... | [
"def",
"find_by_id",
"(",
"cls",
",",
"id",
")",
":",
"obj",
"=",
"cls",
".",
"find_one",
"(",
"cls",
".",
"_id_spec",
"(",
"id",
")",
")",
"if",
"not",
"obj",
":",
"raise",
"NotFoundException",
"(",
"cls",
".",
"collection",
",",
"id",
")",
"retur... | 35.636364 | 11.636364 |
def save(self):
"""Saves all model instances in the batch as model.
"""
saved = 0
if not self.objects:
raise BatchError("Save failed. Batch is empty")
for deserialized_tx in self.objects:
try:
self.model.objects.get(pk=deserialized_tx.pk)
... | [
"def",
"save",
"(",
"self",
")",
":",
"saved",
"=",
"0",
"if",
"not",
"self",
".",
"objects",
":",
"raise",
"BatchError",
"(",
"\"Save failed. Batch is empty\"",
")",
"for",
"deserialized_tx",
"in",
"self",
".",
"objects",
":",
"try",
":",
"self",
".",
"... | 37.526316 | 15 |
def load_config(settings):
'''Load settings from configfile'''
config = ConfigParser()
section = 'pgdocgen'
try:
config.read(settings['configfile'])
except Exception as e:
sys.stderr.write('Failed to read config: ' + str(e))
sys.exit(1)
for option in config.options(sectio... | [
"def",
"load_config",
"(",
"settings",
")",
":",
"config",
"=",
"ConfigParser",
"(",
")",
"section",
"=",
"'pgdocgen'",
"try",
":",
"config",
".",
"read",
"(",
"settings",
"[",
"'configfile'",
"]",
")",
"except",
"Exception",
"as",
"e",
":",
"sys",
".",
... | 32.25 | 14.25 |
def remove(self, entity):
"""
Remove entity from the MatchBox.
:param object entity:
"""
empty_traits = set()
self.mismatch_unknown.discard(entity)
for trait, entities in self.index.items():
entities.discard(entity)
if not entities:
... | [
"def",
"remove",
"(",
"self",
",",
"entity",
")",
":",
"empty_traits",
"=",
"set",
"(",
")",
"self",
".",
"mismatch_unknown",
".",
"discard",
"(",
"entity",
")",
"for",
"trait",
",",
"entities",
"in",
"self",
".",
"index",
".",
"items",
"(",
")",
":"... | 28.066667 | 10.066667 |
def cformat(msg, reset=True, template=ColorTemplate):
"""
Transform msg so that colors e.g. #RED;, #BLUE;, etc are mapped to the
corresponding ANSI escape codes. e.g.
>>> cformat("This is #RED;a red string.")
'This is \\x1b[31ma red string.\\x1b[0m'
>>> cformat("This is #BLUE;a blue string.", ... | [
"def",
"cformat",
"(",
"msg",
",",
"reset",
"=",
"True",
",",
"template",
"=",
"ColorTemplate",
")",
":",
"ct",
"=",
"ColorTemplate",
"(",
"msg",
")",
"m",
"=",
"ct",
".",
"safe_substitute",
"(",
"ANSI_STRING_MAP",
")",
"if",
"reset",
":",
"m",
"+=",
... | 28.695652 | 18.782609 |
def _render_trajectories(self,
trajectories: Tuple[NonFluents, Fluents, Fluents, Fluents, np.array]) -> None:
'''Prints the first batch of simulated `trajectories`.
Args:
trajectories: NonFluents, states, actions, interms and rewards.
'''
if self._verbose:
... | [
"def",
"_render_trajectories",
"(",
"self",
",",
"trajectories",
":",
"Tuple",
"[",
"NonFluents",
",",
"Fluents",
",",
"Fluents",
",",
"Fluents",
",",
"np",
".",
"array",
"]",
")",
"->",
"None",
":",
"if",
"self",
".",
"_verbose",
":",
"non_fluents",
","... | 49.75 | 25.125 |
def nearest(self):
'''
Get the next state jump.
The next jump is calculated looking at :attr:`current` state
and its possible :attr:`jumps` to find the nearest and bigger
option in :attr:`pending` data.
If none is found, the returned next state label will be None.
... | [
"def",
"nearest",
"(",
"self",
")",
":",
"try",
":",
"options",
"=",
"self",
".",
"jumps",
"[",
"self",
".",
"current",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"'Current state %r not defined in %s.jumps.'",
"%",
"(",
"self",
".",
"current",... | 33.305556 | 17.305556 |
def _smooth(values: List[float], beta: float) -> List[float]:
""" Exponential smoothing of values """
avg_value = 0.
smoothed = []
for i, value in enumerate(values):
avg_value = beta * avg_value + (1 - beta) * value
smoothed.append(avg_value / (1 - beta ** (i + 1)))
return smoothed | [
"def",
"_smooth",
"(",
"values",
":",
"List",
"[",
"float",
"]",
",",
"beta",
":",
"float",
")",
"->",
"List",
"[",
"float",
"]",
":",
"avg_value",
"=",
"0.",
"smoothed",
"=",
"[",
"]",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"values",
... | 38.875 | 15.5 |
def is_spam(request, form, url):
"""
Main entry point for spam handling - called from the comment view and
page processor for ``yacms.forms``, to check if posted content is
spam. Spam filters are configured via the ``SPAM_FILTERS`` setting.
"""
for spam_filter_path in settings.SPAM_FILTERS:
... | [
"def",
"is_spam",
"(",
"request",
",",
"form",
",",
"url",
")",
":",
"for",
"spam_filter_path",
"in",
"settings",
".",
"SPAM_FILTERS",
":",
"spam_filter",
"=",
"import_dotted_path",
"(",
"spam_filter_path",
")",
"if",
"spam_filter",
"(",
"request",
",",
"form"... | 43.3 | 14.9 |
def srepr(expr, indented=False, cache=None):
"""Render the given expression into a string that can be evaluated in an
appropriate context to re-instantiate an identical expression. If
`indented` is False (default), the resulting string is a single line.
Otherwise, the result is a multiline string, and e... | [
"def",
"srepr",
"(",
"expr",
",",
"indented",
"=",
"False",
",",
"cache",
"=",
"None",
")",
":",
"if",
"indented",
":",
"printer",
"=",
"IndentedSReprPrinter",
"(",
"cache",
"=",
"cache",
")",
"else",
":",
"printer",
"=",
"QnetSReprPrinter",
"(",
"cache"... | 38.9 | 21.2 |
async def _write_ssl(self):
"""
Flush outgoing data which OpenSSL put in our BIO to the transport.
"""
pending = lib.BIO_ctrl_pending(self.write_bio)
if pending > 0:
result = lib.BIO_read(self.write_bio, self.write_cdata, len(self.write_cdata))
await self.... | [
"async",
"def",
"_write_ssl",
"(",
"self",
")",
":",
"pending",
"=",
"lib",
".",
"BIO_ctrl_pending",
"(",
"self",
".",
"write_bio",
")",
"if",
"pending",
">",
"0",
":",
"result",
"=",
"lib",
".",
"BIO_read",
"(",
"self",
".",
"write_bio",
",",
"self",
... | 43.9 | 17.5 |
def get_dead_hosting_devices_info(self):
"""
Get a list of hosting devices that have been marked dead
:return: List of dead hosting device ids
"""
res = []
for hd_id in self.hosting_devices_backlog:
hd = self.hosting_devices_backlog[hd_id]['hd']
if... | [
"def",
"get_dead_hosting_devices_info",
"(",
"self",
")",
":",
"res",
"=",
"[",
"]",
"for",
"hd_id",
"in",
"self",
".",
"hosting_devices_backlog",
":",
"hd",
"=",
"self",
".",
"hosting_devices_backlog",
"[",
"hd_id",
"]",
"[",
"'hd'",
"]",
"if",
"hd",
"[",... | 36 | 10.363636 |
def is_valid_pid_to_be_updated(did):
"""Assert that ``did`` is the PID of an object that can be updated (obsoleted) with
MNStorage.update()"""
if not d1_gmn.app.did.is_valid_pid_to_be_updated(did):
raise d1_common.types.exceptions.InvalidRequest(
0,
'Object cannot be updated ... | [
"def",
"is_valid_pid_to_be_updated",
"(",
"did",
")",
":",
"if",
"not",
"d1_gmn",
".",
"app",
".",
"did",
".",
"is_valid_pid_to_be_updated",
"(",
"did",
")",
":",
"raise",
"d1_common",
".",
"types",
".",
"exceptions",
".",
"InvalidRequest",
"(",
"0",
",",
... | 42.833333 | 16.833333 |
def check_valid(msg_type, attr, value, func, exec_info):
"""
Checker function all validate_* functions below will call.
Raises InvalidMessageInputError if input is not valid as per
given func.
"""
if value is not None:
if isinstance(value, MutableSequence):
for v in value:
... | [
"def",
"check_valid",
"(",
"msg_type",
",",
"attr",
",",
"value",
",",
"func",
",",
"exec_info",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"value",
",",
"MutableSequence",
")",
":",
"for",
"v",
"in",
"value",
":",
"i... | 39.142857 | 17.857143 |
def interval(coro, interval=1, times=None, loop=None):
"""
Schedules the execution of a coroutine function every `x` amount of
seconds.
The function returns an `asyncio.Task`, which implements also an
`asyncio.Future` interface, allowing the user to cancel the execution
cycle.
This functio... | [
"def",
"interval",
"(",
"coro",
",",
"interval",
"=",
"1",
",",
"times",
"=",
"None",
",",
"loop",
"=",
"None",
")",
":",
"assert_corofunction",
"(",
"coro",
"=",
"coro",
")",
"# Store maximum allowed number of calls",
"times",
"=",
"int",
"(",
"times",
"o... | 27.66129 | 22.016129 |
def timedeltaToString(delta):
"""
Convert timedelta to an ical DURATION.
"""
if delta.days == 0:
sign = 1
else:
sign = delta.days / abs(delta.days)
delta = abs(delta)
days = delta.days
hours = int(delta.seconds / 3600)
minutes = int((delta.seconds % 3600) / 60)
se... | [
"def",
"timedeltaToString",
"(",
"delta",
")",
":",
"if",
"delta",
".",
"days",
"==",
"0",
":",
"sign",
"=",
"1",
"else",
":",
"sign",
"=",
"delta",
".",
"days",
"/",
"abs",
"(",
"delta",
".",
"days",
")",
"delta",
"=",
"abs",
"(",
"delta",
")",
... | 24.419355 | 14.483871 |
def interpolate_exe(self, testString):
"""
Replace testString with a path to an executable based on the format.
If this looks like
${which:lalapps_tmpltbank}
it will return the equivalent of which(lalapps_tmpltbank)
Otherwise it will return an unchanged string.
... | [
"def",
"interpolate_exe",
"(",
"self",
",",
"testString",
")",
":",
"# First check if any interpolation is needed and abort if not",
"testString",
"=",
"testString",
".",
"strip",
"(",
")",
"if",
"not",
"(",
"testString",
".",
"startswith",
"(",
"'${'",
")",
"and",
... | 30.956522 | 21.608696 |
def build(self, filenames, cl_args=None, link_args=None,
x64=False, out_dir=''):
"""
Compile source files and link object files.
"""
if not cl_args:
cl_args = []
if not link_args:
link_args = []
msvc, lib = self.vc.get_bin_and_lib(x64... | [
"def",
"build",
"(",
"self",
",",
"filenames",
",",
"cl_args",
"=",
"None",
",",
"link_args",
"=",
"None",
",",
"x64",
"=",
"False",
",",
"out_dir",
"=",
"''",
")",
":",
"if",
"not",
"cl_args",
":",
"cl_args",
"=",
"[",
"]",
"if",
"not",
"link_args... | 37.724138 | 14 |
def set_annotation(self):
"""Appends the context's ``pending_symbol`` to its ``annotations`` sequence."""
assert self.pending_symbol is not None
assert not self.value
annotations = (_as_symbol(self.pending_symbol, is_symbol_value=False),) # pending_symbol becomes an annotation
s... | [
"def",
"set_annotation",
"(",
"self",
")",
":",
"assert",
"self",
".",
"pending_symbol",
"is",
"not",
"None",
"assert",
"not",
"self",
".",
"value",
"annotations",
"=",
"(",
"_as_symbol",
"(",
"self",
".",
"pending_symbol",
",",
"is_symbol_value",
"=",
"Fals... | 51.083333 | 19.666667 |
def get_run_as_identifiers_stack(self):
"""
:returns: an IdentifierCollection
"""
session = self.get_session(False)
try:
return session.get_internal_attribute(self.run_as_identifiers_session_key)
except AttributeError:
return None | [
"def",
"get_run_as_identifiers_stack",
"(",
"self",
")",
":",
"session",
"=",
"self",
".",
"get_session",
"(",
"False",
")",
"try",
":",
"return",
"session",
".",
"get_internal_attribute",
"(",
"self",
".",
"run_as_identifiers_session_key",
")",
"except",
"Attribu... | 29.4 | 14.4 |
def toint(number):
"""
Helper to return rounded int for a float or just the int it self.
"""
if isinstance(number, float):
if number > 1:
number = round(number, 0)
else:
# The following solves when image has small dimensions (like 1x54)
# then scale fa... | [
"def",
"toint",
"(",
"number",
")",
":",
"if",
"isinstance",
"(",
"number",
",",
"float",
")",
":",
"if",
"number",
">",
"1",
":",
"number",
"=",
"round",
"(",
"number",
",",
"0",
")",
"else",
":",
"# The following solves when image has small dimensions (lik... | 36.923077 | 16.615385 |
def get_nlp_base(self):
''' getter '''
if isinstance(self.__nlp_base, NlpBase) is False:
raise TypeError("The type of self.__nlp_base must be NlpBase.")
return self.__nlp_base | [
"def",
"get_nlp_base",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"__nlp_base",
",",
"NlpBase",
")",
"is",
"False",
":",
"raise",
"TypeError",
"(",
"\"The type of self.__nlp_base must be NlpBase.\"",
")",
"return",
"self",
".",
"__nlp_base"
] | 34.5 | 22.833333 |
def from_zenity_tuple_str(zenity_tuple_str: str):
"""
Parser for Zenity output, which outputs a named tuple-like string: "rgb(R, G, B)", where R, G, B are base10
integers.
@param zenity_tuple_str: tuple-like string: "rgb(r, g, b), where r, g, b are base10 integers.
@return: Colou... | [
"def",
"from_zenity_tuple_str",
"(",
"zenity_tuple_str",
":",
"str",
")",
":",
"components",
"=",
"zenity_tuple_str",
".",
"strip",
"(",
"\"rgb()\"",
")",
".",
"split",
"(",
"\",\"",
")",
"return",
"ColourData",
"(",
"*",
"map",
"(",
"int",
",",
"components"... | 47.7 | 21.7 |
def register_library_type(name, type_):
"""
Register a Arctic Library Type handler
"""
if name in LIBRARY_TYPES:
raise ArcticException("Library %s already registered as %s" % (name, LIBRARY_TYPES[name]))
LIBRARY_TYPES[name] = type_ | [
"def",
"register_library_type",
"(",
"name",
",",
"type_",
")",
":",
"if",
"name",
"in",
"LIBRARY_TYPES",
":",
"raise",
"ArcticException",
"(",
"\"Library %s already registered as %s\"",
"%",
"(",
"name",
",",
"LIBRARY_TYPES",
"[",
"name",
"]",
")",
")",
"LIBRAR... | 36.142857 | 11.571429 |
def option_changed(self, option, value):
"""Option has changed"""
setattr(self, to_text_string(option), value)
self.shellwidget.set_namespace_view_settings()
self.refresh_table() | [
"def",
"option_changed",
"(",
"self",
",",
"option",
",",
"value",
")",
":",
"setattr",
"(",
"self",
",",
"to_text_string",
"(",
"option",
")",
",",
"value",
")",
"self",
".",
"shellwidget",
".",
"set_namespace_view_settings",
"(",
")",
"self",
".",
"refre... | 42 | 8.2 |
def truncate(message, limit=500):
"""
Truncates the message to the given limit length. The beginning and the
end of the message are left untouched.
"""
if len(message) > limit:
trc_msg = ''.join([message[:limit // 2 - 2],
' .. ',
message[... | [
"def",
"truncate",
"(",
"message",
",",
"limit",
"=",
"500",
")",
":",
"if",
"len",
"(",
"message",
")",
">",
"limit",
":",
"trc_msg",
"=",
"''",
".",
"join",
"(",
"[",
"message",
"[",
":",
"limit",
"//",
"2",
"-",
"2",
"]",
",",
"' .. '",
",",... | 33.083333 | 14.083333 |
def fourier_fit_magseries(times, mags, errs, period,
fourierorder=None,
fourierparams=None,
sigclip=3.0,
magsarefluxes=False,
plotfit=False,
ignoreinitfail=True,
... | [
"def",
"fourier_fit_magseries",
"(",
"times",
",",
"mags",
",",
"errs",
",",
"period",
",",
"fourierorder",
"=",
"None",
",",
"fourierparams",
"=",
"None",
",",
"sigclip",
"=",
"3.0",
",",
"magsarefluxes",
"=",
"False",
",",
"plotfit",
"=",
"False",
",",
... | 38.410959 | 22.267123 |
def SetBackingStore(cls, backing):
"""Set the global backing type used by the ComponentRegistry from this point forward
This function must be called before any operations that use the registry are initiated
otherwise they will work from different registries that will likely contain different da... | [
"def",
"SetBackingStore",
"(",
"cls",
",",
"backing",
")",
":",
"if",
"backing",
"not",
"in",
"[",
"'json'",
",",
"'sqlite'",
",",
"'memory'",
"]",
":",
"raise",
"ArgumentError",
"(",
"\"Unknown backing store type that is not json or sqlite\"",
",",
"backing",
"="... | 44.578947 | 21.578947 |
def remove_organisation_from_all(cls, organisation_id):
"""Remove an organisation from all users"""
users = yield views.organisation_members.get(key=organisation_id,
include_docs=True)
users = [x['doc'] for x in users['rows']]
for user... | [
"def",
"remove_organisation_from_all",
"(",
"cls",
",",
"organisation_id",
")",
":",
"users",
"=",
"yield",
"views",
".",
"organisation_members",
".",
"get",
"(",
"key",
"=",
"organisation_id",
",",
"include_docs",
"=",
"True",
")",
"users",
"=",
"[",
"x",
"... | 47 | 20.5 |
def calc(path):
'''
Takes a path as an argument and returns the total size in bytes of the file
or directory. If the path is a directory the size will be calculated
recursively.
'''
total = 0
err = None
if os.path.isdir(path):
try:
for entry in os.scandir(path):
... | [
"def",
"calc",
"(",
"path",
")",
":",
"total",
"=",
"0",
"err",
"=",
"None",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"try",
":",
"for",
"entry",
"in",
"os",
".",
"scandir",
"(",
"path",
")",
":",
"try",
":",
"is_dir",
"=... | 33.911765 | 17.5 |
def load_model(self, name=None):
'''
Loads a saved version of the model.
'''
if self.clobber:
return False
if name is None:
name = self.name
file = os.path.join(self.dir, '%s.npz' % name)
if os.path.exists(file):
if not self.... | [
"def",
"load_model",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"self",
".",
"clobber",
":",
"return",
"False",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"name",
"file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self... | 34.655172 | 16.827586 |
def check_type(self, value, attr, data):
"""Customize check_type for handling containers."""
# Check the type in the standard way first, in order to fail quickly
# in case of invalid values.
root_value = super(InstructionParameter, self).check_type(
value, attr, data)
... | [
"def",
"check_type",
"(",
"self",
",",
"value",
",",
"attr",
",",
"data",
")",
":",
"# Check the type in the standard way first, in order to fail quickly",
"# in case of invalid values.",
"root_value",
"=",
"super",
"(",
"InstructionParameter",
",",
"self",
")",
".",
"c... | 39.833333 | 18.583333 |
def disablingBuidCache(self):
'''
Disable and invalidate the layer buid cache for migration
'''
self.buidcache = s_cache.LruDict(0)
yield
self.buidcache = s_cache.LruDict(BUID_CACHE_SIZE) | [
"def",
"disablingBuidCache",
"(",
"self",
")",
":",
"self",
".",
"buidcache",
"=",
"s_cache",
".",
"LruDict",
"(",
"0",
")",
"yield",
"self",
".",
"buidcache",
"=",
"s_cache",
".",
"LruDict",
"(",
"BUID_CACHE_SIZE",
")"
] | 32.714286 | 20.142857 |
def process_firehose_archive(bucket, key):
"""Download firehose archive, aggregate records in memory and write back."""
data = {}
with tempfile.NamedTemporaryFile(mode='w+b') as fh:
s3.download_file(bucket, key, fh.name)
log.warning("Downloaded Key Size:%s Key:%s",
sizeof... | [
"def",
"process_firehose_archive",
"(",
"bucket",
",",
"key",
")",
":",
"data",
"=",
"{",
"}",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'w+b'",
")",
"as",
"fh",
":",
"s3",
".",
"download_file",
"(",
"bucket",
",",
"key",
",",
"... | 39.1 | 14.566667 |
def types(self):
"""
List of the known event types
"""
r = requests.get(self.evaluator_url + 'types')
r.raise_for_status()
return r.json() | [
"def",
"types",
"(",
"self",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"evaluator_url",
"+",
"'types'",
")",
"r",
".",
"raise_for_status",
"(",
")",
"return",
"r",
".",
"json",
"(",
")"
] | 25.714286 | 10 |
def is_rate_matrix(K, tol):
"""
True if K is a rate matrix
Parameters
----------
K : scipy.sparse matrix
Matrix to check
tol : float
tolerance to check with
Returns
-------
Truth value : bool
True, if K negated diagonal is positive and row sums up to zero.
... | [
"def",
"is_rate_matrix",
"(",
"K",
",",
"tol",
")",
":",
"K",
"=",
"K",
".",
"tocsr",
"(",
")",
"# check rows sum up to zero.",
"row_sum",
"=",
"K",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"sum_eq_zero",
"=",
"np",
".",
"allclose",
"(",
"row_sum",
",... | 22.638889 | 20.972222 |
def load_plugin_modules(self, modnames):
"""take a list of module names which are pylint plugins and load
and register them
"""
for modname in modnames:
if modname in self._dynamic_plugins:
continue
self._dynamic_plugins.add(modname)
mo... | [
"def",
"load_plugin_modules",
"(",
"self",
",",
"modnames",
")",
":",
"for",
"modname",
"in",
"modnames",
":",
"if",
"modname",
"in",
"self",
".",
"_dynamic_plugins",
":",
"continue",
"self",
".",
"_dynamic_plugins",
".",
"add",
"(",
"modname",
")",
"module"... | 39.1 | 8 |
def get_column_names(self, virtual=True, strings=True, hidden=False, regex=None):
"""Return a list of column names
Example:
>>> import vaex
>>> df = vaex.from_scalars(x=1, x2=2, y=3, s='string')
>>> df['r'] = (df.x**2 + df.y**2)**2
>>> df.get_column_names()
['x'... | [
"def",
"get_column_names",
"(",
"self",
",",
"virtual",
"=",
"True",
",",
"strings",
"=",
"True",
",",
"hidden",
"=",
"False",
",",
"regex",
"=",
"None",
")",
":",
"def",
"column_filter",
"(",
"name",
")",
":",
"'''Return True if column with specified name sho... | 38.409091 | 18.068182 |
def process(self, items_block):
"""Process items to add file related information.
Eventize items creating one new item per each file found in the commit (excluding
files with no actions performed on them). For each event, file path, file name,
path parts, file type and file extension ar... | [
"def",
"process",
"(",
"self",
",",
"items_block",
")",
":",
"logger",
".",
"info",
"(",
"self",
".",
"__log_prefix",
"+",
"\" New commits: \"",
"+",
"str",
"(",
"len",
"(",
"items_block",
")",
")",
")",
"# Create events from commits",
"git_events",
"=",
"Gi... | 41.085106 | 29.170213 |
def resp_graph(dataframe, image_name, dir='./'):
"""Response time graph for bucketed data
:param pandas.DataFrame dataframe: dataframe containing all data
:param str image_name: the output file name
:param str dir: the output directory
:return: None
"""
fig = pygal.TimeLine(x_title='Elapsed... | [
"def",
"resp_graph",
"(",
"dataframe",
",",
"image_name",
",",
"dir",
"=",
"'./'",
")",
":",
"fig",
"=",
"pygal",
".",
"TimeLine",
"(",
"x_title",
"=",
"'Elapsed Time In Test (secs)'",
",",
"y_title",
"=",
"'Response Time (secs)'",
",",
"x_label_rotation",
"=",
... | 53.368421 | 21.526316 |
def devectorize_utterance(self, utterance):
"""
Take in a sequence of indices and transform it back into a tokenized utterance
"""
utterance = self.swap_pad_and_zero(utterance)
return self.ie.inverse_transform(utterance).tolist() | [
"def",
"devectorize_utterance",
"(",
"self",
",",
"utterance",
")",
":",
"utterance",
"=",
"self",
".",
"swap_pad_and_zero",
"(",
"utterance",
")",
"return",
"self",
".",
"ie",
".",
"inverse_transform",
"(",
"utterance",
")",
".",
"tolist",
"(",
")"
] | 44 | 13.666667 |
def makefile(identifier, dependencies, makepath, compileid,
precompile=False, inclfortpy=True, parser=None,
executable=True, extralinks=None, inclfpyaux=False,
makefpyaux=False, verbose=False):
"""Generates a makefile to create the unit testing executable
for the specified... | [
"def",
"makefile",
"(",
"identifier",
",",
"dependencies",
",",
"makepath",
",",
"compileid",
",",
"precompile",
"=",
"False",
",",
"inclfortpy",
"=",
"True",
",",
"parser",
"=",
"None",
",",
"executable",
"=",
"True",
",",
"extralinks",
"=",
"None",
",",
... | 43.292135 | 22.977528 |
def check_var(var, var_types:Union[type, List[type]] =None, var_name=None, enforce_not_none:bool = True,
allowed_values:Set = None, min_value = None, min_strict:bool = False,
max_value = None, max_strict:bool = False, min_len:int = None, min_len_strict:bool = False,
max_len:int... | [
"def",
"check_var",
"(",
"var",
",",
"var_types",
":",
"Union",
"[",
"type",
",",
"List",
"[",
"type",
"]",
"]",
"=",
"None",
",",
"var_name",
"=",
"None",
",",
"enforce_not_none",
":",
"bool",
"=",
"True",
",",
"allowed_values",
":",
"Set",
"=",
"No... | 45.408163 | 25.857143 |
def normalize(self, text, normalizations=None):
"""Normalize a given text applying all normalizations.
Normalizations to apply can be specified through a list of
parameters and will be executed in that order.
Args:
text: The text to be processed.
normalizations:... | [
"def",
"normalize",
"(",
"self",
",",
"text",
",",
"normalizations",
"=",
"None",
")",
":",
"for",
"normalization",
",",
"kwargs",
"in",
"self",
".",
"_parse_normalizations",
"(",
"normalizations",
"or",
"self",
".",
"_config",
".",
"normalizations",
")",
":... | 33.545455 | 21.590909 |
def handleNotification(self, handle, raw_data): # pylint: disable=unused-argument,invalid-name
""" gets called by the bluepy backend when using wait_for_notification
"""
if raw_data is None:
return
data = raw_data.decode("utf-8").strip(' \n\t')
self._cache = data
... | [
"def",
"handleNotification",
"(",
"self",
",",
"handle",
",",
"raw_data",
")",
":",
"# pylint: disable=unused-argument,invalid-name",
"if",
"raw_data",
"is",
"None",
":",
"return",
"data",
"=",
"raw_data",
".",
"decode",
"(",
"\"utf-8\"",
")",
".",
"strip",
"(",... | 43.214286 | 16.428571 |
def datapath(self):
""" Get an item's data path.
"""
path = self._fields['path']
if not path: # stopped item with no base_dir?
path = self.fetch('directory')
if path and not self._fields['is_multi_file']:
path = os.path.join(path, self._fields['na... | [
"def",
"datapath",
"(",
"self",
")",
":",
"path",
"=",
"self",
".",
"_fields",
"[",
"'path'",
"]",
"if",
"not",
"path",
":",
"# stopped item with no base_dir?",
"path",
"=",
"self",
".",
"fetch",
"(",
"'directory'",
")",
"if",
"path",
"and",
"not",
"self... | 41.444444 | 10.888889 |
def snmp_server_enable_trap_trap_flag(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp")
enable = ET.SubElement(snmp_server, "enable")
trap = ET.SubElement... | [
"def",
"snmp_server_enable_trap_trap_flag",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"snmp_server",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"snmp-server\"",
",",
"xmlns",
"=",
... | 42.727273 | 15.727273 |
def get_negative(self, cls=None, **kwargs):
"""Returns a generator that generates negative cases by
"each negative value in separate case" algorithm.
"""
for attr, set_of_values in kwargs.iteritems():
defaults = {key: kwargs[key][-1]["default"] for key in kwargs}
... | [
"def",
"get_negative",
"(",
"self",
",",
"cls",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"attr",
",",
"set_of_values",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"defaults",
"=",
"{",
"key",
":",
"kwargs",
"[",
"key",
"]",
"[",
... | 45.538462 | 10.307692 |
def pipelines(self):
"""
Property for accessing :class:`PipelineManager` instance, which is used to manage pipelines.
:rtype: yagocd.resources.pipeline.PipelineManager
"""
if self._pipeline_manager is None:
self._pipeline_manager = PipelineManager(session=self._sessi... | [
"def",
"pipelines",
"(",
"self",
")",
":",
"if",
"self",
".",
"_pipeline_manager",
"is",
"None",
":",
"self",
".",
"_pipeline_manager",
"=",
"PipelineManager",
"(",
"session",
"=",
"self",
".",
"_session",
")",
"return",
"self",
".",
"_pipeline_manager"
] | 39.222222 | 19.666667 |
def make_span(parented_tree):
"""create a 'span' or 'leaf' subtree for dis/lisp/RST-DT-formatted trees.
Examples:
span (a subtree that covers the leaves 1 to 7)
___|____
1 7
leaf (a subtree that only covers leaf 7)
|
7
"""
... | [
"def",
"make_span",
"(",
"parented_tree",
")",
":",
"all_leaves",
"=",
"all_leaf_positions",
"(",
"parented_tree",
")",
"if",
"is_root",
"(",
"parented_tree",
")",
":",
"return",
"t",
"(",
"'span'",
",",
"[",
"'1'",
",",
"str",
"(",
"len",
"(",
"all_leaves... | 35.269231 | 18.576923 |
def write_text(_command, txt_file):
"""Dump SQL command to a text file."""
command = _command.strip()
with open(txt_file, 'w') as txt:
txt.writelines(command) | [
"def",
"write_text",
"(",
"_command",
",",
"txt_file",
")",
":",
"command",
"=",
"_command",
".",
"strip",
"(",
")",
"with",
"open",
"(",
"txt_file",
",",
"'w'",
")",
"as",
"txt",
":",
"txt",
".",
"writelines",
"(",
"command",
")"
] | 34.8 | 5.6 |
def toroidal(target,
mode='max',
r_toroid=5e-6,
target_Pc=None,
num_points=1e2,
surface_tension='pore.surface_tension',
contact_angle='pore.contact_angle',
throat_diameter='throat.diameter',
touch_length='throat.touc... | [
"def",
"toroidal",
"(",
"target",
",",
"mode",
"=",
"'max'",
",",
"r_toroid",
"=",
"5e-6",
",",
"target_Pc",
"=",
"None",
",",
"num_points",
"=",
"1e2",
",",
"surface_tension",
"=",
"'pore.surface_tension'",
",",
"contact_angle",
"=",
"'pore.contact_angle'",
"... | 42.091954 | 19.95977 |
def get(dic, path, seps=PATH_SEPS, idx_reg=_JSNP_GET_ARRAY_IDX_REG):
"""getter for nested dicts.
:param dic: a dict[-like] object
:param path: Path expression to point object wanted
:param seps: Separator char candidates
:return: A tuple of (result_object, error_message)
>>> d = {'a': {'b': {'... | [
"def",
"get",
"(",
"dic",
",",
"path",
",",
"seps",
"=",
"PATH_SEPS",
",",
"idx_reg",
"=",
"_JSNP_GET_ARRAY_IDX_REG",
")",
":",
"items",
"=",
"[",
"_jsnp_unescape",
"(",
"p",
")",
"for",
"p",
"in",
"_split_path",
"(",
"path",
",",
"seps",
")",
"]",
"... | 37.514286 | 17.057143 |
def db_from_hass_config(path=None, **kwargs):
"""Initialize a database from HASS config."""
if path is None:
path = config.find_hass_config()
url = config.db_url_from_hass_config(path)
return HassDatabase(url, **kwargs) | [
"def",
"db_from_hass_config",
"(",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"config",
".",
"find_hass_config",
"(",
")",
"url",
"=",
"config",
".",
"db_url_from_hass_config",
"(",
"path",
")",
... | 34 | 10.428571 |
def process():
"""Get process overview."""
pmi = ProcessMemoryInfo()
threads = get_current_threads()
return dict(info=pmi, threads=threads) | [
"def",
"process",
"(",
")",
":",
"pmi",
"=",
"ProcessMemoryInfo",
"(",
")",
"threads",
"=",
"get_current_threads",
"(",
")",
"return",
"dict",
"(",
"info",
"=",
"pmi",
",",
"threads",
"=",
"threads",
")"
] | 30.2 | 8.8 |
def _set_system_monitor_mail(self, v, load=False):
"""
Setter method for system_monitor_mail, mapped from YANG variable /system_monitor_mail (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_system_monitor_mail is considered as a private
method. Backends lo... | [
"def",
"_set_system_monitor_mail",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",... | 82.227273 | 38.090909 |
def validate(self):
"""
Perform validation check on properties.
"""
if not self.api_token or not self.api_token_secret:
raise ImproperlyConfigured("'api_token' and 'api_token_secret' are required for authentication.")
if self.response_type not in ["json", "pson", "xm... | [
"def",
"validate",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"api_token",
"or",
"not",
"self",
".",
"api_token_secret",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"'api_token' and 'api_token_secret' are required for authentication.\"",
")",
"if",
"self",
".",... | 47.444444 | 27.444444 |
def search(self, CorpNum, MgtKeyType, DType, SDate, EDate, State, Type, TaxType, LateOnly, TaxRegIDYN, TaxRegIDType,
TaxRegID, Page, PerPage, Order, UserID=None, QString=None, InterOPYN=None, IssueType=None):
""" 목록 조회
args
CorpNum : 팝빌회원 사업자번호
MgtKeyTy... | [
"def",
"search",
"(",
"self",
",",
"CorpNum",
",",
"MgtKeyType",
",",
"DType",
",",
"SDate",
",",
"EDate",
",",
"State",
",",
"Type",
",",
"TaxType",
",",
"LateOnly",
",",
"TaxRegIDYN",
",",
"TaxRegIDType",
",",
"TaxRegID",
",",
"Page",
",",
"PerPage",
... | 39.38806 | 16.850746 |
def divConn (self, preCellsTags, postCellsTags, connParam):
from .. import sim
''' Generates connections between all pre and post-syn cells based on probability values'''
if sim.cfg.verbose: print('Generating set of divergent connections (rule: %s) ...' % (connParam['label']))
# get list of param... | [
"def",
"divConn",
"(",
"self",
",",
"preCellsTags",
",",
"postCellsTags",
",",
"connParam",
")",
":",
"from",
".",
".",
"import",
"sim",
"if",
"sim",
".",
"cfg",
".",
"verbose",
":",
"print",
"(",
"'Generating set of divergent connections (rule: %s) ...'",
"%",
... | 64.875 | 44.725 |
def enqueue(self, pipeline):
""" Start a pipeline.
:param pipeline: Start this pipeline.
"""
copied = Pipeline().append(pipeline)
copied.group = self
self._queue.put(copied) | [
"def",
"enqueue",
"(",
"self",
",",
"pipeline",
")",
":",
"copied",
"=",
"Pipeline",
"(",
")",
".",
"append",
"(",
"pipeline",
")",
"copied",
".",
"group",
"=",
"self",
"self",
".",
"_queue",
".",
"put",
"(",
"copied",
")"
] | 26.875 | 10.375 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'input') and self.input is not None:
_dict['input'] = self.input._to_dict()
if hasattr(self, 'intents') and self.intents is not None:
_dict['intents'] = [x._to_... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'input'",
")",
"and",
"self",
".",
"input",
"is",
"not",
"None",
":",
"_dict",
"[",
"'input'",
"]",
"=",
"self",
".",
"input",
".",
"_to_dict",
... | 49.9 | 20.2 |
def process_subprotocol(
self, headers: Headers, available_subprotocols: Optional[Sequence[Subprotocol]]
) -> Optional[Subprotocol]:
"""
Handle the Sec-WebSocket-Protocol HTTP request header.
Return Sec-WebSocket-Protocol HTTP response header, which is the same
as the select... | [
"def",
"process_subprotocol",
"(",
"self",
",",
"headers",
":",
"Headers",
",",
"available_subprotocols",
":",
"Optional",
"[",
"Sequence",
"[",
"Subprotocol",
"]",
"]",
")",
"->",
"Optional",
"[",
"Subprotocol",
"]",
":",
"subprotocol",
":",
"Optional",
"[",
... | 32.48 | 24.96 |
def skew(xi):
"""Return the skew-symmetric matrix that can be used to calculate
cross-products with vector xi.
Multiplying this matrix by a vector `v` gives the same result
as `xi x v`.
Parameters
----------
xi : :obj:`numpy.ndarray` of float
A 3-entry vector.
Returns
----... | [
"def",
"skew",
"(",
"xi",
")",
":",
"S",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"0",
",",
"-",
"xi",
"[",
"2",
"]",
",",
"xi",
"[",
"1",
"]",
"]",
",",
"[",
"xi",
"[",
"2",
"]",
",",
"0",
",",
"-",
"xi",
"[",
"0",
"]",
"]",
",",
... | 25.761905 | 19 |
def schemaNewParserCtxt(URL):
"""Create an XML Schemas parse context for that file/resource
expected to contain an XML Schemas file. """
ret = libxml2mod.xmlSchemaNewParserCtxt(URL)
if ret is None:raise parserError('xmlSchemaNewParserCtxt() failed')
return SchemaParserCtxt(_obj=ret) | [
"def",
"schemaNewParserCtxt",
"(",
"URL",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlSchemaNewParserCtxt",
"(",
"URL",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"parserError",
"(",
"'xmlSchemaNewParserCtxt() failed'",
")",
"return",
"SchemaParserCtxt",
"(",
... | 50.166667 | 8.833333 |
def screen(args):
"""
%prog screen scaffolds.fasta library.fasta
Screen sequences against FASTA library. Sequences that have 95% id and 50%
cov will be removed by default.
"""
from jcvi.apps.align import blast
from jcvi.formats.blast import covfilter
p = OptionParser(screen.__doc__)
... | [
"def",
"screen",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"apps",
".",
"align",
"import",
"blast",
"from",
"jcvi",
".",
"formats",
".",
"blast",
"import",
"covfilter",
"p",
"=",
"OptionParser",
"(",
"screen",
".",
"__doc__",
")",
"p",
".",
"set_alig... | 31.055556 | 18.888889 |
def onMessage(self, client, userdata, msg):
"""!
The callback for when a PUBLISH message is received from the server.
@param client
@param userdata
@param msg
"""
dataIdentifier = DataIdentifier(self.broker, msg.topic)
self.dataHandler.onNewData(dataIdent... | [
"def",
"onMessage",
"(",
"self",
",",
"client",
",",
"userdata",
",",
"msg",
")",
":",
"dataIdentifier",
"=",
"DataIdentifier",
"(",
"self",
".",
"broker",
",",
"msg",
".",
"topic",
")",
"self",
".",
"dataHandler",
".",
"onNewData",
"(",
"dataIdentifier",
... | 33 | 18.3 |
def safe_filename(filename, replacement="_"):
"""
Replace unsafe filename characters with underscores. Note that this does not
test for "legal" names accepted, but a more restricted set of:
Letters, numbers, spaces, hyphens, underscores and periods.
:param filename: name of a file as a string
:... | [
"def",
"safe_filename",
"(",
"filename",
",",
"replacement",
"=",
"\"_\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"filename",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"filename must be a string\"",
")",
"if",
"regex",
".",
"path",
".",
"linux",
... | 39.210526 | 17 |
def find_related_imports(self, fullname):
"""
Return a list of non-stdlib modules that are directly imported by
`fullname`, plus their parents.
The list is determined by retrieving the source code of
`fullname`, compiling it, and examining all IMPORT_NAME ops.
:param fu... | [
"def",
"find_related_imports",
"(",
"self",
",",
"fullname",
")",
":",
"related",
"=",
"self",
".",
"_related_cache",
".",
"get",
"(",
"fullname",
")",
"if",
"related",
"is",
"not",
"None",
":",
"return",
"related",
"modpath",
",",
"src",
",",
"_",
"=",
... | 34.12766 | 18.765957 |
def parse(self, tokens):
'''Parses a list of tokens into a JSON-serializable object.
The parsing proceeds from left to right and is greedy.
Precedence order:
1. Parameters with active context. For example, an Option with
nargs=-1 will gobble all the remaining tokens.
2. Subcommands.
3. Parame... | [
"def",
"parse",
"(",
"self",
",",
"tokens",
")",
":",
"self",
".",
"_ping_main",
"(",
")",
"# Pre-parsing:",
"# 1. Expand globbed options: -abc --> -a -b -c",
"def",
"is_globbed",
"(",
"s",
")",
":",
"return",
"len",
"(",
"s",
")",
">",
"2",
"and",
"s",
... | 38.576923 | 27.807692 |
def finalize(self, outcome=None):
"""Finalize state
This method is called when the run method finishes
:param rafcon.core.logical_port.Outcome outcome: final outcome of the state
:return: Nothing for the moment
"""
# Set the final outcome of the state
if outcom... | [
"def",
"finalize",
"(",
"self",
",",
"outcome",
"=",
"None",
")",
":",
"# Set the final outcome of the state",
"if",
"outcome",
"is",
"not",
"None",
":",
"self",
".",
"final_outcome",
"=",
"outcome",
"# If we are within a concurrency state, we have to notify it about our ... | 32.4 | 23 |
def encipher(self,string):
"""Encipher string using Enigma M3 cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Enigma(settings=('A','A','A'),rotors=(1,2,3),reflector='B',
ringstellung=('F','V'... | [
"def",
"encipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"ret",
"=",
"''",
"for",
"c",
"in",
"string",
".",
"upper",
"(",
")",
":",
"if",
"c",
".",
"isalpha",
"(",
")",
":",
"r... | 39.5 | 19.8 |
def get_resource_class_terminal_attribute_iterator(rc):
"""
Returns an iterator over all terminal attributes in the given registered
resource.
"""
for attr in itervalues_(rc.__everest_attributes__):
if attr.kind == RESOURCE_ATTRIBUTE_KINDS.TERMINAL:
yield attr | [
"def",
"get_resource_class_terminal_attribute_iterator",
"(",
"rc",
")",
":",
"for",
"attr",
"in",
"itervalues_",
"(",
"rc",
".",
"__everest_attributes__",
")",
":",
"if",
"attr",
".",
"kind",
"==",
"RESOURCE_ATTRIBUTE_KINDS",
".",
"TERMINAL",
":",
"yield",
"attr"... | 36.625 | 16.125 |
def _parse_spectra_annotation(self, line):
"""Parse and store the spectral annotation details
"""
if re.match('^PK\$NUM_PEAK(.*)', line, re.IGNORECASE):
self.start_spectra_annotation = False
return
saplist = line.split()
sarow = (
self.curren... | [
"def",
"_parse_spectra_annotation",
"(",
"self",
",",
"line",
")",
":",
"if",
"re",
".",
"match",
"(",
"'^PK\\$NUM_PEAK(.*)'",
",",
"line",
",",
"re",
".",
"IGNORECASE",
")",
":",
"self",
".",
"start_spectra_annotation",
"=",
"False",
"return",
"saplist",
"=... | 43 | 24.666667 |
def reference(self, reference):
"""
Sets the reference of this CreateCertificateIssuerConfig.
The certificate name, as created in the factory, to which the certificate issuer configuration applies. The following names are reserved and cannot be configured: LwM2M, BOOTSTRAP.
:param refe... | [
"def",
"reference",
"(",
"self",
",",
"reference",
")",
":",
"if",
"reference",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `reference`, must not be `None`\"",
")",
"if",
"reference",
"is",
"not",
"None",
"and",
"len",
"(",
"reference",
"... | 58.0625 | 37.5625 |
def get_dir(self, obj):
"""Return the dirattr of obj formatted with the dirfomat specified in the constructor.
If the attr is None then ``None`` is returned not the string ``\'None\'``.
:param obj: the fileinfo with information.
:type obj: :class:`FileInfo`
:returns: the directo... | [
"def",
"get_dir",
"(",
"self",
",",
"obj",
")",
":",
"if",
"self",
".",
"_dirattr",
"is",
"None",
":",
"return",
"a",
"=",
"attrgetter",
"(",
"self",
".",
"_dirattr",
")",
"(",
"obj",
")",
"if",
"a",
"is",
"None",
":",
"return",
"s",
"=",
"self",... | 32.882353 | 14.941176 |
def resource_copy(package_or_requirement, resource_name, destination):
'''
Copy file/dir resource to destination.
Parameters
----------
package_or_requirement : str
resource_name : str
destination : ~pathlib.Path
Path to copy to, it must not exist.
'''
args = package_or_requ... | [
"def",
"resource_copy",
"(",
"package_or_requirement",
",",
"resource_name",
",",
"destination",
")",
":",
"args",
"=",
"package_or_requirement",
",",
"resource_name",
"if",
"resource_isdir",
"(",
"*",
"args",
")",
":",
"destination",
".",
"mkdir",
"(",
")",
"fo... | 30.666667 | 15.25 |
def set_functions(self, functions):
"""Check functions passed as argument and set them to be used."""
for func in functions:
try:
self.append_function(func)
except (ValueError, AttributeError) as ex:
log.error("'%s' is not a callable function: %s",... | [
"def",
"set_functions",
"(",
"self",
",",
"functions",
")",
":",
"for",
"func",
"in",
"functions",
":",
"try",
":",
"self",
".",
"append_function",
"(",
"func",
")",
"except",
"(",
"ValueError",
",",
"AttributeError",
")",
"as",
"ex",
":",
"log",
".",
... | 43.125 | 13.5 |
def get_tunnel_info_output_tunnel_src_ip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_tunnel_info = ET.Element("get_tunnel_info")
config = get_tunnel_info
output = ET.SubElement(get_tunnel_info, "output")
tunnel = ET.SubElement(out... | [
"def",
"get_tunnel_info_output_tunnel_src_ip",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_tunnel_info",
"=",
"ET",
".",
"Element",
"(",
"\"get_tunnel_info\"",
")",
"config",
"=",
"get_tunne... | 38.846154 | 11.076923 |
def generate_string_to_sign(date, region, canonical_request):
"""
Generate string to sign.
:param date: Date is input from :meth:`datetime.datetime`
:param region: Region should be set to bucket region.
:param canonical_request: Canonical request generated previously.
"""
formatted_date_tim... | [
"def",
"generate_string_to_sign",
"(",
"date",
",",
"region",
",",
"canonical_request",
")",
":",
"formatted_date_time",
"=",
"date",
".",
"strftime",
"(",
"\"%Y%m%dT%H%M%SZ\"",
")",
"canonical_request_hasher",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"canonical_req... | 38.789474 | 17.421053 |
def moment(self, axis, channel=0, moment=1, *, resultant=None):
"""Take the nth moment the dataset along one axis, adding lower rank channels.
New channels have names ``<channel name>_<axis name>_moment_<moment num>``.
Moment 0 is the integral of the slice.
Moment 1 is the weighted ave... | [
"def",
"moment",
"(",
"self",
",",
"axis",
",",
"channel",
"=",
"0",
",",
"moment",
"=",
"1",
",",
"*",
",",
"resultant",
"=",
"None",
")",
":",
"# get axis index --------------------------------------------------------------------------",
"axis_index",
"=",
"None",... | 42.708333 | 22.395833 |
def generate_flare_lightcurve(
times,
mags=None,
errs=None,
paramdists={
# flare peak amplitude from 0.01 mag to 1.0 mag above median. this
# is tuned for redder bands, flares are much stronger in bluer
# bands, so tune appropriately for your situatio... | [
"def",
"generate_flare_lightcurve",
"(",
"times",
",",
"mags",
"=",
"None",
",",
"errs",
"=",
"None",
",",
"paramdists",
"=",
"{",
"# flare peak amplitude from 0.01 mag to 1.0 mag above median. this",
"# is tuned for redder bands, flares are much stronger in bluer",
"# bands, so... | 32.507042 | 23.591549 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.