text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _forwardImplementation(self, inbuf, outbuf):
""" Proportional probability method.
"""
assert self.module
propensities = self.module.getActionValues(0)
summedProps = sum(propensities)
probabilities = propensities / summedProps
action = eventGenerator(probabi... | [
"def",
"_forwardImplementation",
"(",
"self",
",",
"inbuf",
",",
"outbuf",
")",
":",
"assert",
"self",
".",
"module",
"propensities",
"=",
"self",
".",
"module",
".",
"getActionValues",
"(",
"0",
")",
"summedProps",
"=",
"sum",
"(",
"propensities",
")",
"p... | 28.571429 | 15.357143 |
def metadata(self):
"""Retrieves metadata about the bucket.
Returns:
A BucketMetadata instance with information about this bucket.
Raises:
Exception if there was an error requesting the bucket's metadata.
"""
if self._info is None:
try:
self._info = self._api.buckets_get(s... | [
"def",
"metadata",
"(",
"self",
")",
":",
"if",
"self",
".",
"_info",
"is",
"None",
":",
"try",
":",
"self",
".",
"_info",
"=",
"self",
".",
"_api",
".",
"buckets_get",
"(",
"self",
".",
"_name",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",... | 28.266667 | 22.133333 |
def get_election(self, row, race):
"""
Gets the Election object for the given row of election results.
Depends on knowing the Race object.
If this is the presidential election, this will determine the
Division attached to the election based on the row's statename.
This ... | [
"def",
"get_election",
"(",
"self",
",",
"row",
",",
"race",
")",
":",
"election_day",
"=",
"election",
".",
"ElectionDay",
".",
"objects",
".",
"get",
"(",
"date",
"=",
"row",
"[",
"\"electiondate\"",
"]",
")",
"if",
"row",
"[",
"\"racetypeid\"",
"]",
... | 34.06 | 18.38 |
def count_words(pattern):
"""
Count the number of words in a pattern as well as the total length of those words
:param pattern: The pattern to parse
:type pattern: str
:return: The word count first, then the total length of all words
:rtype : tuple of (int, int)
... | [
"def",
"count_words",
"(",
"pattern",
")",
":",
"word_pattern",
"=",
"re",
".",
"compile",
"(",
"r'(\\b(?<![\\(\\)\\[\\]\\|])\\w\\w*\\b(?![\\(\\)\\[\\]\\|]))'",
",",
"re",
".",
"IGNORECASE",
")",
"words",
"=",
"word_pattern",
".",
"findall",
"(",
"pattern",
")",
"... | 35.9375 | 20.3125 |
def set_col_min_width(self, x: int, min_width: int):
"""Sets a minimum width for blocks in the column with coordinate x."""
if x < 0:
raise IndexError('x < 0')
self._min_widths[x] = min_width | [
"def",
"set_col_min_width",
"(",
"self",
",",
"x",
":",
"int",
",",
"min_width",
":",
"int",
")",
":",
"if",
"x",
"<",
"0",
":",
"raise",
"IndexError",
"(",
"'x < 0'",
")",
"self",
".",
"_min_widths",
"[",
"x",
"]",
"=",
"min_width"
] | 44.6 | 7.8 |
def mappability(args):
"""
%prog mappability reference.fasta
Generate 50mer mappability for reference genome. Commands are based on gem
mapper. See instructions:
<https://github.com/xuefzhao/Reference.Mappability>
"""
p = OptionParser(mappability.__doc__)
p.add_option("--mer", default=5... | [
"def",
"mappability",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"mappability",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--mer\"",
",",
"default",
"=",
"50",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"User mer size\"",
")",
... | 26.833333 | 19.958333 |
def tpot_driver(args):
"""Perform a TPOT run."""
if args.VERBOSITY >= 2:
_print_args(args)
input_data = _read_data_file(args)
features = input_data.drop(args.TARGET_NAME, axis=1)
training_features, testing_features, training_target, testing_target = \
train_test_split(features, inp... | [
"def",
"tpot_driver",
"(",
"args",
")",
":",
"if",
"args",
".",
"VERBOSITY",
">=",
"2",
":",
"_print_args",
"(",
"args",
")",
"input_data",
"=",
"_read_data_file",
"(",
"args",
")",
"features",
"=",
"input_data",
".",
"drop",
"(",
"args",
".",
"TARGET_NA... | 39.135593 | 21.288136 |
def get_nodes(self, coord, coords):
"""Get the variables containing the definition of the nodes
Parameters
----------
coord: xarray.Coordinate
The mesh variable
coords: dict
The coordinates to use to get node coordinates"""
def get_coord(coord):
... | [
"def",
"get_nodes",
"(",
"self",
",",
"coord",
",",
"coords",
")",
":",
"def",
"get_coord",
"(",
"coord",
")",
":",
"return",
"coords",
".",
"get",
"(",
"coord",
",",
"self",
".",
"ds",
".",
"coords",
".",
"get",
"(",
"coord",
")",
")",
"return",
... | 37.153846 | 15.769231 |
def init(ctx):
"""Initialize the project for use with EasyCI. This installs the necessary
git hooks (pre-commit + pre-push) and add a config file if one does not
already exists.
"""
# install hooks
git = ctx.obj['vcs']
click.echo("Installing hooks...", nl=False)
for old in ['commit-msg']... | [
"def",
"init",
"(",
"ctx",
")",
":",
"# install hooks",
"git",
"=",
"ctx",
".",
"obj",
"[",
"'vcs'",
"]",
"click",
".",
"echo",
"(",
"\"Installing hooks...\"",
",",
"nl",
"=",
"False",
")",
"for",
"old",
"in",
"[",
"'commit-msg'",
"]",
":",
"path",
"... | 35.90625 | 16.75 |
def invalidate_cache(self):
"""
Invalidate httpBL cache
"""
if self._use_cache:
self._cache_version += 1
self._cache.increment('cached_httpbl_{0}_version'.format(self._api_key)) | [
"def",
"invalidate_cache",
"(",
"self",
")",
":",
"if",
"self",
".",
"_use_cache",
":",
"self",
".",
"_cache_version",
"+=",
"1",
"self",
".",
"_cache",
".",
"increment",
"(",
"'cached_httpbl_{0}_version'",
".",
"format",
"(",
"self",
".",
"_api_key",
")",
... | 28.375 | 15.375 |
def pages(request, path=None, instance=None):
"""
Представление для отображения текстовых страниц
:param request: запрос
:param path: адрес
:param instance: страница
:return:
"""
if instance and instance.active:
p = instance
else:
raise Http404()
return render(r... | [
"def",
"pages",
"(",
"request",
",",
"path",
"=",
"None",
",",
"instance",
"=",
"None",
")",
":",
"if",
"instance",
"and",
"instance",
".",
"active",
":",
"p",
"=",
"instance",
"else",
":",
"raise",
"Http404",
"(",
")",
"return",
"render",
"(",
"requ... | 23.333333 | 17.466667 |
async def _read(self, path, *,
raw=None,
recurse=None,
dc=None,
separator=None,
keys=None,
watch=None,
consistency=None):
"""Returns the specified key
Parameters:
... | [
"async",
"def",
"_read",
"(",
"self",
",",
"path",
",",
"*",
",",
"raw",
"=",
"None",
",",
"recurse",
"=",
"None",
",",
"dc",
"=",
"None",
",",
"separator",
"=",
"None",
",",
"keys",
"=",
"None",
",",
"watch",
"=",
"None",
",",
"consistency",
"="... | 31.571429 | 12.035714 |
def coreBurkAlpha(self, R, Rs, rho0, r_core, ax_x, ax_y):
"""
deflection angle
:param R:
:param Rs:
:param rho0:
:param r_core:
:param ax_x:
:param ax_y:
:return:
"""
x = R * Rs ** -1
p = Rs * r_core ** -1
gx = sel... | [
"def",
"coreBurkAlpha",
"(",
"self",
",",
"R",
",",
"Rs",
",",
"rho0",
",",
"r_core",
",",
"ax_x",
",",
"ax_y",
")",
":",
"x",
"=",
"R",
"*",
"Rs",
"**",
"-",
"1",
"p",
"=",
"Rs",
"*",
"r_core",
"**",
"-",
"1",
"gx",
"=",
"self",
".",
"_G",... | 19.75 | 19.15 |
async def lookup(client: Client, search: str) -> dict:
"""
GET UID/Public key data
:param client: Client to connect to the api
:param search: UID or public key
:return:
"""
return await client.get(MODULE + '/lookup/%s' % search, schema=LOOKUP_SCHEMA) | [
"async",
"def",
"lookup",
"(",
"client",
":",
"Client",
",",
"search",
":",
"str",
")",
"->",
"dict",
":",
"return",
"await",
"client",
".",
"get",
"(",
"MODULE",
"+",
"'/lookup/%s'",
"%",
"search",
",",
"schema",
"=",
"LOOKUP_SCHEMA",
")"
] | 30.111111 | 16.333333 |
def delete_course(self, courseid):
""" Erase all course data """
# Wipes the course (delete database)
self.wipe_course(courseid)
# Deletes the course from the factory (entire folder)
self.course_factory.delete_course(courseid)
# Removes backup
filepath = os.path... | [
"def",
"delete_course",
"(",
"self",
",",
"courseid",
")",
":",
"# Wipes the course (delete database)",
"self",
".",
"wipe_course",
"(",
"courseid",
")",
"# Deletes the course from the factory (entire folder)",
"self",
".",
"course_factory",
".",
"delete_course",
"(",
"co... | 37.333333 | 18.2 |
def parse_document(graph: BELGraph,
enumerated_lines: Iterable[Tuple[int, str]],
metadata_parser: MetadataParser,
) -> None:
"""Parse the lines in the document section of a BEL script."""
parse_document_start_time = time.time()
for line_number, line ... | [
"def",
"parse_document",
"(",
"graph",
":",
"BELGraph",
",",
"enumerated_lines",
":",
"Iterable",
"[",
"Tuple",
"[",
"int",
",",
"str",
"]",
"]",
",",
"metadata_parser",
":",
"MetadataParser",
",",
")",
"->",
"None",
":",
"parse_document_start_time",
"=",
"t... | 41.65625 | 19.21875 |
def preprovision_rbridge_id_wwn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
preprovision = ET.SubElement(config, "preprovision", xmlns="urn:brocade.com:mgmt:brocade-preprovision")
rbridge_id = ET.SubElement(preprovision, "rbridge-id")
rbridge... | [
"def",
"preprovision_rbridge_id_wwn",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"preprovision",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"preprovision\"",
",",
"xmlns",
"=",
"\"u... | 45.153846 | 16.769231 |
def mcmc(x1, x2, x1err=[], x2err=[], po=(1,1,0.5), logify=True,
nsteps=5000, nwalkers=100, nburn=500, output='full'):
"""
Use emcee to find the best-fit linear relation or power law
accounting for measurement uncertainties and intrinsic scatter
Parameters
----------
x1 : array... | [
"def",
"mcmc",
"(",
"x1",
",",
"x2",
",",
"x1err",
"=",
"[",
"]",
",",
"x2err",
"=",
"[",
"]",
",",
"po",
"=",
"(",
"1",
",",
"1",
",",
"0.5",
")",
",",
"logify",
"=",
"True",
",",
"nsteps",
"=",
"5000",
",",
"nwalkers",
"=",
"100",
",",
... | 38.574713 | 17.701149 |
def get_table_description(self, cursor, table_name):
"Returns a description of the table, with the DB-API cursor.description interface."
# pylint:disable=too-many-locals,unused-argument
result = []
for field in self.table_description_cache(table_name)['fields']:
params = Orde... | [
"def",
"get_table_description",
"(",
"self",
",",
"cursor",
",",
"table_name",
")",
":",
"# pylint:disable=too-many-locals,unused-argument",
"result",
"=",
"[",
"]",
"for",
"field",
"in",
"self",
".",
"table_description_cache",
"(",
"table_name",
")",
"[",
"'fields'... | 58.627907 | 23.139535 |
def fit2dArrayToFn(arr, fn, mask=None, down_scale_factor=None,
output_shape=None, guess=None,
outgrid=None):
"""Fit a 2d array to a 2d function
USE ONLY MASKED VALUES
* [down_scale_factor] map to speed up fitting procedure, set value smaller than 1
* [output_s... | [
"def",
"fit2dArrayToFn",
"(",
"arr",
",",
"fn",
",",
"mask",
"=",
"None",
",",
"down_scale_factor",
"=",
"None",
",",
"output_shape",
"=",
"None",
",",
"guess",
"=",
"None",
",",
"outgrid",
"=",
"None",
")",
":",
"if",
"mask",
"is",
"None",
":",
"#as... | 29.980769 | 18.615385 |
async def worker_start(self, worker, exc=None):
'''Start the worker by invoking the :meth:`create_server` method.
'''
if not exc and self.name not in worker.servers:
servers = await self.binds(worker, worker.sockets)
for server in servers.values():
server.... | [
"async",
"def",
"worker_start",
"(",
"self",
",",
"worker",
",",
"exc",
"=",
"None",
")",
":",
"if",
"not",
"exc",
"and",
"self",
".",
"name",
"not",
"in",
"worker",
".",
"servers",
":",
"servers",
"=",
"await",
"self",
".",
"binds",
"(",
"worker",
... | 51.857143 | 20.142857 |
def copy(self, dest, src):
"""Copy element from sequence, member from mapping.
:param dest: the destination
:type dest: Pointer
:param src: the source
:type src: Pointer
:return: resolved document
:rtype: Target
"""
doc = fragment = deepcopy(self.... | [
"def",
"copy",
"(",
"self",
",",
"dest",
",",
"src",
")",
":",
"doc",
"=",
"fragment",
"=",
"deepcopy",
"(",
"self",
".",
"document",
")",
"for",
"token",
"in",
"Pointer",
"(",
"src",
")",
":",
"fragment",
"=",
"token",
".",
"extract",
"(",
"fragme... | 30.8 | 13.466667 |
def get_notables(self, id_num):
"""Return the notables of the activity with the given id.
"""
url = self._build_url('my', 'activities', id_num, 'notables')
return self._json(url) | [
"def",
"get_notables",
"(",
"self",
",",
"id_num",
")",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"'my'",
",",
"'activities'",
",",
"id_num",
",",
"'notables'",
")",
"return",
"self",
".",
"_json",
"(",
"url",
")"
] | 41.2 | 9.6 |
def dispatch(self, block = False, timeout = None):
"""Get the next event from the queue and pass it to
the appropriate handlers.
:Parameters:
- `block`: wait for event if the queue is empty
- `timeout`: maximum time, in seconds, to wait if `block` is `True`
:Type... | [
"def",
"dispatch",
"(",
"self",
",",
"block",
"=",
"False",
",",
"timeout",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"\" dispatching...\"",
")",
"try",
":",
"event",
"=",
"self",
".",
"queue",
".",
"get",
"(",
"block",
",",
"timeout",
")",... | 38.1 | 14.45 |
def _upgradeTableOid(store, table, createTable, postCreate=lambda: None):
"""
Upgrade a table to have an explicit oid.
Must be called in a transaction to avoid corrupting the database.
"""
if _hasExplicitOid(store, table):
return
store.executeSchemaSQL(
'ALTER TABLE *DATABASE*.{... | [
"def",
"_upgradeTableOid",
"(",
"store",
",",
"table",
",",
"createTable",
",",
"postCreate",
"=",
"lambda",
":",
"None",
")",
":",
"if",
"_hasExplicitOid",
"(",
"store",
",",
"table",
")",
":",
"return",
"store",
".",
"executeSchemaSQL",
"(",
"'ALTER TABLE ... | 36.375 | 18.625 |
def chart(symbol, timeframe='1m', date=None, token='', version=''):
'''Historical price/volume data, daily and intraday
https://iexcloud.io/docs/api/#historical-prices
Data Schedule
1d: -9:30-4pm ET Mon-Fri on regular market trading days
-9:30-1pm ET on early close trading days
All others:
... | [
"def",
"chart",
"(",
"symbol",
",",
"timeframe",
"=",
"'1m'",
",",
"date",
"=",
"None",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"_raiseIfNotStr",
"(",
"symbol",
")",
"if",
"timeframe",
"is",
"not",
"None",
"and",
"timeframe",
"!... | 38.655172 | 21.965517 |
def _maketicks(self, ax, ylabel='Energy (eV)'):
"""Utility method to add tick marks to a band structure."""
# set y-ticks
ax.yaxis.set_major_locator(MaxNLocator(6))
ax.yaxis.set_minor_locator(AutoMinorLocator(2))
# set x-ticks; only plot the unique tick labels
ticks = se... | [
"def",
"_maketicks",
"(",
"self",
",",
"ax",
",",
"ylabel",
"=",
"'Energy (eV)'",
")",
":",
"# set y-ticks",
"ax",
".",
"yaxis",
".",
"set_major_locator",
"(",
"MaxNLocator",
"(",
"6",
")",
")",
"ax",
".",
"yaxis",
".",
"set_minor_locator",
"(",
"AutoMinor... | 43.615385 | 16.480769 |
def list_of_installed(self, repo, name):
"""Return installed packages
"""
all_installed_names = []
all_installed_packages = find_package("", self.meta.pkg_path)
for inst in all_installed_packages:
if repo == "sbo" and inst.endswith("_SBo"):
name = spli... | [
"def",
"list_of_installed",
"(",
"self",
",",
"repo",
",",
"name",
")",
":",
"all_installed_names",
"=",
"[",
"]",
"all_installed_packages",
"=",
"find_package",
"(",
"\"\"",
",",
"self",
".",
"meta",
".",
"pkg_path",
")",
"for",
"inst",
"in",
"all_installed... | 39.8 | 11.6 |
def download(url):
"""
Download `url` and return it as utf-8 encoded text.
Args:
url (str): What should be downloaded?
Returns:
str: Content of the page.
"""
headers = {"User-Agent": USER_AGENT}
resp = requests.get(
url,
timeout=REQUEST_TIMEOUT,
head... | [
"def",
"download",
"(",
"url",
")",
":",
"headers",
"=",
"{",
"\"User-Agent\"",
":",
"USER_AGENT",
"}",
"resp",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"timeout",
"=",
"REQUEST_TIMEOUT",
",",
"headers",
"=",
"headers",
",",
"allow_redirects",
"=",
... | 25.567568 | 19.351351 |
def add_time_event(self, time_event):
"""Add a TimeEvent.
:type time_event: :class: `~opencensus.trace.time_event.TimeEvent`
:param time_event: A TimeEvent object.
"""
if isinstance(time_event, time_event_module.TimeEvent):
self.time_events.append(time_event)
... | [
"def",
"add_time_event",
"(",
"self",
",",
"time_event",
")",
":",
"if",
"isinstance",
"(",
"time_event",
",",
"time_event_module",
".",
"TimeEvent",
")",
":",
"self",
".",
"time_events",
".",
"append",
"(",
"time_event",
")",
"else",
":",
"raise",
"TypeErro... | 41.727273 | 18.272727 |
def set(self, indexes=None, columns=None, values=None):
"""
Given indexes and columns will set a sub-set of the DataFrame to the values provided. This method will direct
to the below methods based on what types are passed in for the indexes and columns. If the indexes or columns
contains... | [
"def",
"set",
"(",
"self",
",",
"indexes",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"values",
"=",
"None",
")",
":",
"if",
"(",
"indexes",
"is",
"not",
"None",
")",
"and",
"(",
"columns",
"is",
"not",
"None",
")",
":",
"if",
"isinstance",
"... | 60.92 | 33.4 |
def get_version_name(version_id):
"""
Get the name of a protocol version by the internal version ID.
:param Integer version_id: Internal protocol version ID
:return: Name of the version
:rtype: String
"""
ver = registry.version_info.get(version_id)
if ver:
return ver.name
r... | [
"def",
"get_version_name",
"(",
"version_id",
")",
":",
"ver",
"=",
"registry",
".",
"version_info",
".",
"get",
"(",
"version_id",
")",
"if",
"ver",
":",
"return",
"ver",
".",
"name",
"return",
"'unknown'"
] | 24.846154 | 18.076923 |
def moran_cultural(network):
"""Generalized cultural Moran process.
At eachtime step, an individual is chosen to receive information from
another individual. Nobody dies, but perhaps their ideas do.
"""
if not network.transmissions(): # first step, replacer is a source
replacer = random.ch... | [
"def",
"moran_cultural",
"(",
"network",
")",
":",
"if",
"not",
"network",
".",
"transmissions",
"(",
")",
":",
"# first step, replacer is a source",
"replacer",
"=",
"random",
".",
"choice",
"(",
"network",
".",
"nodes",
"(",
"type",
"=",
"Source",
")",
")"... | 36.736842 | 20.368421 |
def get_status(self, hosts, services):
"""Get the status of this host
:return: "UP", "DOWN", "UNREACHABLE" or "n/a" based on host state_id or business_rule state
:rtype: str
"""
if self.got_business_rule:
mapping = {
0: "UP",
1: "DOWN"... | [
"def",
"get_status",
"(",
"self",
",",
"hosts",
",",
"services",
")",
":",
"if",
"self",
".",
"got_business_rule",
":",
"mapping",
"=",
"{",
"0",
":",
"\"UP\"",
",",
"1",
":",
"\"DOWN\"",
",",
"4",
":",
"\"UNREACHABLE\"",
",",
"}",
"return",
"mapping",... | 31.133333 | 20.533333 |
def respond(self):
"""Process the current request.
From :pep:`333`:
The start_response callable must not actually transmit
the response headers. Instead, it must store them for the
server or gateway to transmit only after the first
iteration of the appli... | [
"def",
"respond",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"req",
".",
"server",
".",
"wsgi_app",
"(",
"self",
".",
"env",
",",
"self",
".",
"start_response",
")",
"try",
":",
"for",
"chunk",
"in",
"filter",
"(",
"None",
",",
"response",
... | 40.913043 | 18.304348 |
def _scan_for_tokens(contents):
"""Scan a string for tokens and return immediate form tokens."""
# Regexes are in priority order. Changing the order may alter the
# behavior of the lexer
scanner = re.Scanner([
# Things inside quotes
(r"(?<![^\s\(])([\"\'])(?:(?=(\\?))\2.)*?\1(?![^\s\)])"... | [
"def",
"_scan_for_tokens",
"(",
"contents",
")",
":",
"# Regexes are in priority order. Changing the order may alter the",
"# behavior of the lexer",
"scanner",
"=",
"re",
".",
"Scanner",
"(",
"[",
"# Things inside quotes",
"(",
"r\"(?<![^\\s\\(])([\\\"\\'])(?:(?=(\\\\?))\\2.)*?\\1... | 41.616438 | 18.438356 |
def read_some(self):
"""Read at least one byte of cooked data unless EOF is hit.
Return '' if EOF is hit. Block if no data is immediately
available.
"""
self.process_rawq()
while self.cookedq.tell() == 0 and not self.eof:
self.fill_rawq()
self.p... | [
"def",
"read_some",
"(",
"self",
")",
":",
"self",
".",
"process_rawq",
"(",
")",
"while",
"self",
".",
"cookedq",
".",
"tell",
"(",
")",
"==",
"0",
"and",
"not",
"self",
".",
"eof",
":",
"self",
".",
"fill_rawq",
"(",
")",
"self",
".",
"process_ra... | 29.133333 | 16.2 |
def post(self, endpoint, json=None, params=None, **kwargs):
"""POST to DHIS2
:param endpoint: DHIS2 API endpoint
:param json: HTTP payload
:param params: HTTP parameters
:return: requests.Response object
"""
json = kwargs['data'] if 'data' in kwargs else json
... | [
"def",
"post",
"(",
"self",
",",
"endpoint",
",",
"json",
"=",
"None",
",",
"params",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"json",
"=",
"kwargs",
"[",
"'data'",
"]",
"if",
"'data'",
"in",
"kwargs",
"else",
"json",
"return",
"self",
".",
... | 42.777778 | 9.777778 |
def _bundle_models(custom_models):
""" Create a JavaScript bundle with selected `models`. """
exports = []
modules = []
def read_json(name):
with io.open(join(bokehjs_dir, "js", name + ".json"), encoding="utf-8") as f:
return json.loads(f.read())
bundles = ["bokeh", "bokeh-api"... | [
"def",
"_bundle_models",
"(",
"custom_models",
")",
":",
"exports",
"=",
"[",
"]",
"modules",
"=",
"[",
"]",
"def",
"read_json",
"(",
"name",
")",
":",
"with",
"io",
".",
"open",
"(",
"join",
"(",
"bokehjs_dir",
",",
"\"js\"",
",",
"name",
"+",
"\".j... | 38.835165 | 21.318681 |
def rollaxis(vari, axis, start=0):
"""
Roll the specified axis backwards, until it lies in a given position.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Input array or polynomial.
axis (int):
The axis to roll backwards. The positions of the other axes do not
... | [
"def",
"rollaxis",
"(",
"vari",
",",
"axis",
",",
"start",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"vari",
",",
"Poly",
")",
":",
"core_old",
"=",
"vari",
".",
"A",
".",
"copy",
"(",
")",
"core_new",
"=",
"{",
"}",
"for",
"key",
"in",
"var... | 34.47619 | 17.428571 |
def _return_metadata():
"""
Return JSON-formatted metadata for route attachment.
Requires flask.current_app to be set, which means
`with app.app_context()`
"""
app = current_app
retdict = {"auth": app.config["AUTH"]["type"]}
for fld in ["name", "repository", "version", "description",
... | [
"def",
"_return_metadata",
"(",
")",
":",
"app",
"=",
"current_app",
"retdict",
"=",
"{",
"\"auth\"",
":",
"app",
".",
"config",
"[",
"\"AUTH\"",
"]",
"[",
"\"type\"",
"]",
"}",
"for",
"fld",
"in",
"[",
"\"name\"",
",",
"\"repository\"",
",",
"\"version\... | 34.416667 | 11.416667 |
def lz (inlist, score):
"""
Returns the z-score for a given input score, given that score and the
list from which that score came. Not appropriate for population calculations.
Usage: lz(inlist, score)
"""
z = (score-mean(inlist))/samplestdev(inlist)
return z | [
"def",
"lz",
"(",
"inlist",
",",
"score",
")",
":",
"z",
"=",
"(",
"score",
"-",
"mean",
"(",
"inlist",
")",
")",
"/",
"samplestdev",
"(",
"inlist",
")",
"return",
"z"
] | 29.555556 | 19.333333 |
def fetch(self, remote='origin'):
"""fetch from a remote"""
git(self.gitdir, "fetch", remote, _env=self.env()) | [
"def",
"fetch",
"(",
"self",
",",
"remote",
"=",
"'origin'",
")",
":",
"git",
"(",
"self",
".",
"gitdir",
",",
"\"fetch\"",
",",
"remote",
",",
"_env",
"=",
"self",
".",
"env",
"(",
")",
")"
] | 41.333333 | 8.333333 |
def fitlin_clipped(xy,uv,verbose=False,mode='rscale',nclip=3,reject=3):
""" Perform a clipped fit based on the number of iterations and rejection limit
(in sigma) specified by the user. This will more closely replicate the results
obtained by 'geomap' using 'maxiter' and 'reject' parameters.
"""... | [
"def",
"fitlin_clipped",
"(",
"xy",
",",
"uv",
",",
"verbose",
"=",
"False",
",",
"mode",
"=",
"'rscale'",
",",
"nclip",
"=",
"3",
",",
"reject",
"=",
"3",
")",
":",
"fitting_funcs",
"=",
"{",
"'rscale'",
":",
"fitlin_rscale",
",",
"'general'",
":",
... | 37.552632 | 19.026316 |
def assoc(m, *kvs):
"""Associate keys to values in associative data structure m. If m is None,
returns a new Map with key-values kvs."""
if m is None:
return lmap.Map.empty().assoc(*kvs)
if isinstance(m, IAssociative):
return m.assoc(*kvs)
raise TypeError(
f"Object of type {t... | [
"def",
"assoc",
"(",
"m",
",",
"*",
"kvs",
")",
":",
"if",
"m",
"is",
"None",
":",
"return",
"lmap",
".",
"Map",
".",
"empty",
"(",
")",
".",
"assoc",
"(",
"*",
"kvs",
")",
"if",
"isinstance",
"(",
"m",
",",
"IAssociative",
")",
":",
"return",
... | 36.6 | 15.5 |
def do_capacity(self, line):
"capacity [tablename] {read_units} {write_units}"
table, line = self.get_table_params(line)
args = self.getargs(line)
read_units = int(args[0])
write_units = int(args[1])
desc = table.describe()
prov = desc['Table']['ProvisionedThrou... | [
"def",
"do_capacity",
"(",
"self",
",",
"line",
")",
":",
"table",
",",
"line",
"=",
"self",
".",
"get_table_params",
"(",
"line",
")",
"args",
"=",
"self",
".",
"getargs",
"(",
"line",
")",
"read_units",
"=",
"int",
"(",
"args",
"[",
"0",
"]",
")"... | 42.75 | 24.522727 |
def _do_scatter_var(v, parallel):
"""Logic for scattering a variable.
"""
# For batches, scatter records only at the top level (double nested)
if parallel.startswith("batch") and workflow.is_cwl_record(v):
return (tz.get_in(["type", "type"], v) == "array" and
tz.get_in(["type", "... | [
"def",
"_do_scatter_var",
"(",
"v",
",",
"parallel",
")",
":",
"# For batches, scatter records only at the top level (double nested)",
"if",
"parallel",
".",
"startswith",
"(",
"\"batch\"",
")",
"and",
"workflow",
".",
"is_cwl_record",
"(",
"v",
")",
":",
"return",
... | 44.2 | 17 |
def split(nodeShape, jobShape, wallTime):
"""
Partition a node allocation into two to fit the job, returning the
modified shape of the node and a new node reservation for
the extra time that the job didn't fill.
"""
return (Shape(wallTime,
nodeShape.memory - jobShape.memory,
... | [
"def",
"split",
"(",
"nodeShape",
",",
"jobShape",
",",
"wallTime",
")",
":",
"return",
"(",
"Shape",
"(",
"wallTime",
",",
"nodeShape",
".",
"memory",
"-",
"jobShape",
".",
"memory",
",",
"nodeShape",
".",
"cores",
"-",
"jobShape",
".",
"cores",
",",
... | 45.1875 | 10.9375 |
def get_relative_from_paths(self, filepath, paths):
"""
Find the relative filepath from the most relevant multiple paths.
This is somewhat like a ``os.path.relpath(path[, start])`` but where
``start`` is a list. The most relevant item from ``paths`` will be used
to apply the rel... | [
"def",
"get_relative_from_paths",
"(",
"self",
",",
"filepath",
",",
"paths",
")",
":",
"for",
"systempath",
"in",
"paths_by_depth",
"(",
"paths",
")",
":",
"if",
"filepath",
".",
"startswith",
"(",
"systempath",
")",
":",
"return",
"os",
".",
"path",
".",... | 41.413793 | 26.034483 |
def request(self, session_id):
"""Force the termination of a NETCONF session (not the current one!)
*session_id* is the session identifier of the NETCONF session to be terminated as a string
"""
node = new_ele("kill-session")
sub_ele(node, "session-id").text = session_id
... | [
"def",
"request",
"(",
"self",
",",
"session_id",
")",
":",
"node",
"=",
"new_ele",
"(",
"\"kill-session\"",
")",
"sub_ele",
"(",
"node",
",",
"\"session-id\"",
")",
".",
"text",
"=",
"session_id",
"return",
"self",
".",
"_request",
"(",
"node",
")"
] | 42.5 | 16.125 |
def add_to_deleted_models(sender, instance=None, *args, **kwargs):
"""
Whenever a model is deleted, we record its ID in a separate model for tracking purposes. During serialization, we will mark
the model as deleted in the store.
"""
if issubclass(sender, SyncableModel):
instance._update_del... | [
"def",
"add_to_deleted_models",
"(",
"sender",
",",
"instance",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"issubclass",
"(",
"sender",
",",
"SyncableModel",
")",
":",
"instance",
".",
"_update_deleted_models",
"(",
")"
] | 46.714286 | 16.714286 |
def file_attribs(location, mode=None, owner=None, group=None, sudo=False):
"""Updates the mode/owner/group for the remote file at the given
location."""
return dir_attribs(location, mode, owner, group, False, sudo) | [
"def",
"file_attribs",
"(",
"location",
",",
"mode",
"=",
"None",
",",
"owner",
"=",
"None",
",",
"group",
"=",
"None",
",",
"sudo",
"=",
"False",
")",
":",
"return",
"dir_attribs",
"(",
"location",
",",
"mode",
",",
"owner",
",",
"group",
",",
"Fals... | 55.75 | 14.75 |
def _get_children_as_string(node):
"""Iterate through all the children of a node.
Returns one string containing the values from all the text-nodes
recursively.
"""
out = []
if node:
for child in node:
if child.nodeType == child.TEXT_NODE:
out.append(child.dat... | [
"def",
"_get_children_as_string",
"(",
"node",
")",
":",
"out",
"=",
"[",
"]",
"if",
"node",
":",
"for",
"child",
"in",
"node",
":",
"if",
"child",
".",
"nodeType",
"==",
"child",
".",
"TEXT_NODE",
":",
"out",
".",
"append",
"(",
"child",
".",
"data"... | 30.071429 | 17.714286 |
def verify_ethinca_metric_options(opts, parser):
"""
Checks that the necessary options are given for the ethinca metric
calculation.
Parameters
----------
opts : argparse.Values instance
Result of parsing the input options with OptionParser
parser : object
The OptionParser i... | [
"def",
"verify_ethinca_metric_options",
"(",
"opts",
",",
"parser",
")",
":",
"if",
"opts",
".",
"filter_cutoff",
"is",
"not",
"None",
"and",
"not",
"(",
"opts",
".",
"filter_cutoff",
"in",
"pnutils",
".",
"named_frequency_cutoffs",
".",
"keys",
"(",
")",
")... | 46.68 | 21.8 |
def log(self, sequence, infoarray) -> None:
"""Log the given |IOSequence| object either for reading or writing
data.
The optional `array` argument allows for passing alternative data
in an |InfoArray| object replacing the series of the |IOSequence|
object, which is useful for wr... | [
"def",
"log",
"(",
"self",
",",
"sequence",
",",
"infoarray",
")",
"->",
"None",
":",
"descr_device",
"=",
"sequence",
".",
"descr_device",
"self",
".",
"sequences",
"[",
"descr_device",
"]",
"=",
"sequence",
"self",
".",
"arrays",
"[",
"descr_device",
"]"... | 41.571429 | 18.057143 |
def search_function(root1, q, s, f, l, o='g'):
"""
function to get links
"""
global links
links = search(q, o, s, f, l)
root1.destroy()
root1.quit() | [
"def",
"search_function",
"(",
"root1",
",",
"q",
",",
"s",
",",
"f",
",",
"l",
",",
"o",
"=",
"'g'",
")",
":",
"global",
"links",
"links",
"=",
"search",
"(",
"q",
",",
"o",
",",
"s",
",",
"f",
",",
"l",
")",
"root1",
".",
"destroy",
"(",
... | 18.5 | 14 |
def options_absent(name, sections=None, separator='='):
'''
.. code-block:: yaml
/home/saltminion/api-paste.ini:
ini.options_absent:
- separator: '='
- sections:
test:
- testkey
- secondoption
test1:
... | [
"def",
"options_absent",
"(",
"name",
",",
"sections",
"=",
"None",
",",
"separator",
"=",
"'='",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"'No anomaly detec... | 37.453333 | 17.906667 |
def vmomentdensity(self,*args,**kwargs):
"""
NAME:
vmomentdensity
PURPOSE:
calculate the an arbitrary moment of the velocity distribution
at R times the density
INPUT:
R - radius at which to calculate the moment(/ro)
n - vR^n
... | [
"def",
"vmomentdensity",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"use_physical",
"=",
"kwargs",
".",
"pop",
"(",
"'use_physical'",
",",
"True",
")",
"ro",
"=",
"kwargs",
".",
"pop",
"(",
"'ro'",
",",
"None",
")",
"if",
"ro... | 29.985714 | 26.3 |
def get_type(type_name):
"""Get a type given its importable name.
Parameters
----------
task_name : `str`
Name of the Python type, such as ``mypackage.MyClass``.
Returns
-------
object
The object.
"""
parts = type_name.split('.')
if len(parts) < 2:
raise... | [
"def",
"get_type",
"(",
"type_name",
")",
":",
"parts",
"=",
"type_name",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"parts",
")",
"<",
"2",
":",
"raise",
"SphinxError",
"(",
"'Type must be fully-qualified, '",
"'of the form ``module.MyClass``. Got: {}'",
... | 25.136364 | 19.909091 |
def check_precomputed_distance_matrix(X):
"""Perform check_array(X) after removing infinite values (numpy.inf) from the given distance matrix.
"""
tmp = X.copy()
tmp[np.isinf(tmp)] = 1
check_array(tmp) | [
"def",
"check_precomputed_distance_matrix",
"(",
"X",
")",
":",
"tmp",
"=",
"X",
".",
"copy",
"(",
")",
"tmp",
"[",
"np",
".",
"isinf",
"(",
"tmp",
")",
"]",
"=",
"1",
"check_array",
"(",
"tmp",
")"
] | 36 | 9.5 |
def add_child(self, child, logical_block_size, allow_duplicate=False):
# type: (DirectoryRecord, int, bool) -> bool
'''
A method to add a new child to this directory record.
Parameters:
child - The child directory record object to add.
logical_block_size - The size of ... | [
"def",
"add_child",
"(",
"self",
",",
"child",
",",
"logical_block_size",
",",
"allow_duplicate",
"=",
"False",
")",
":",
"# type: (DirectoryRecord, int, bool) -> bool",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalE... | 47.333333 | 29.222222 |
def find_instance_and_eni_by_ip(vpc_info, ip):
"""
Given a specific IP address, find the EC2 instance and ENI.
We need this information for setting the route.
Returns instance and emi in a tuple.
"""
for instance in vpc_info['instances']:
for eni in instance.interfaces:
fo... | [
"def",
"find_instance_and_eni_by_ip",
"(",
"vpc_info",
",",
"ip",
")",
":",
"for",
"instance",
"in",
"vpc_info",
"[",
"'instances'",
"]",
":",
"for",
"eni",
"in",
"instance",
".",
"interfaces",
":",
"for",
"pa",
"in",
"eni",
".",
"private_ip_addresses",
":",... | 35.25 | 14.5 |
def building(shape=None, gray=False):
"""Photo of the Centre for Mathematical Sciences in Cambridge.
Returns
-------
An image with the following properties:
image type: color (or gray scales if `gray=True`)
size: [442, 331] (if not specified by `size`)
scale: [0, 1]
type... | [
"def",
"building",
"(",
"shape",
"=",
"None",
",",
"gray",
"=",
"False",
")",
":",
"# TODO: Store data in some ODL controlled url",
"name",
"=",
"'cms.mat'",
"url",
"=",
"URL_CAM",
"+",
"name",
"dct",
"=",
"get_data",
"(",
"name",
",",
"subset",
"=",
"DATA_S... | 30.333333 | 15.388889 |
def get_next_step(self, step=None):
"""
Returns the next step after the given `step`. If no more steps are
available, None will be returned. If the `step` argument is None, the
current step will be determined automatically.
"""
if step is None:
step = self.ste... | [
"def",
"get_next_step",
"(",
"self",
",",
"step",
"=",
"None",
")",
":",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"self",
".",
"steps",
".",
"current",
"form_list",
"=",
"self",
".",
"get_form_list",
"(",
")",
"keys",
"=",
"list",
"(",
"form_lis... | 37.866667 | 10.533333 |
def bed(args):
"""
%prog bed frgscffile
Convert the frgscf posmap file to bed format.
"""
p = OptionParser(bed.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
frgscffile, = args
bedfile = frgscffile.rsplit(".", 1)[0] + ".bed"
fw... | [
"def",
"bed",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"bed",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
"not",
... | 21.125 | 19.375 |
def get_pages(parser, token):
"""Add to context the list of page links.
Usage:
.. code-block:: html+django
{% get_pages %}
This is mostly used for Digg-style pagination.
This call inserts in the template context a *pages* variable, as a sequence
of page links. You can use *pages* in ... | [
"def",
"get_pages",
"(",
"parser",
",",
"token",
")",
":",
"# Validate args.",
"try",
":",
"tag_name",
",",
"args",
"=",
"token",
".",
"contents",
".",
"split",
"(",
"None",
",",
"1",
")",
"except",
"ValueError",
":",
"var_name",
"=",
"'pages'",
"else",
... | 24.95122 | 22.170732 |
def is_complex(arg):
'''
is_complex(x) yields True if x is a complex numeric object and False otherwise. Note that this
includes anything representable as as a complex number such as an integer or a boolean value.
In effect, this makes this function an alias for is_number(arg).
'''
return (i... | [
"def",
"is_complex",
"(",
"arg",
")",
":",
"return",
"(",
"is_complex",
"(",
"mag",
"(",
"arg",
")",
")",
"if",
"is_quantity",
"(",
"arg",
")",
"else",
"True",
"if",
"isinstance",
"(",
"arg",
",",
"numbers",
".",
"Complex",
")",
"else",
"is_npscalar",
... | 57.444444 | 36.555556 |
def get_all_child_edges(self):
"""Return tuples for all child GO IDs, containing current GO ID and child GO ID."""
all_child_edges = set()
for parent in self.children:
all_child_edges.add((parent.item_id, self.item_id))
all_child_edges |= parent.get_all_child_edges()
... | [
"def",
"get_all_child_edges",
"(",
"self",
")",
":",
"all_child_edges",
"=",
"set",
"(",
")",
"for",
"parent",
"in",
"self",
".",
"children",
":",
"all_child_edges",
".",
"add",
"(",
"(",
"parent",
".",
"item_id",
",",
"self",
".",
"item_id",
")",
")",
... | 48.571429 | 10.714286 |
def select_candidates(config):
"""Select candidates to download.
Parameters
----------
config: NgdConfig
Runtime configuration object
Returns
-------
list of (<candidate entry>, <taxonomic group>)
"""
download_candidates = []
for group in config.group:
summary... | [
"def",
"select_candidates",
"(",
"config",
")",
":",
"download_candidates",
"=",
"[",
"]",
"for",
"group",
"in",
"config",
".",
"group",
":",
"summary_file",
"=",
"get_summary",
"(",
"config",
".",
"section",
",",
"group",
",",
"config",
".",
"uri",
",",
... | 24.26087 | 21.913043 |
def parse_filespec(fspec, sep=':', gpat='*'):
"""
Parse given filespec `fspec` and return [(filetype, filepath)].
Because anyconfig.load should find correct file's type to load by the file
extension, this function will not try guessing file's type if not file type
is specified explicitly.
:par... | [
"def",
"parse_filespec",
"(",
"fspec",
",",
"sep",
"=",
"':'",
",",
"gpat",
"=",
"'*'",
")",
":",
"if",
"sep",
"in",
"fspec",
":",
"tpl",
"=",
"(",
"ftype",
",",
"fpath",
")",
"=",
"tuple",
"(",
"fspec",
".",
"split",
"(",
"sep",
")",
")",
"els... | 34.375 | 17.8125 |
def run(self):
"""
Run the given command and yield each line(s) one by one.
.. note::
The difference between this method and :code:`self.execute()`
is that :code:`self.execute()` wait for the process to end
in order to return its output.
"""
... | [
"def",
"run",
"(",
"self",
")",
":",
"with",
"Popen",
"(",
"self",
".",
"command",
",",
"stdout",
"=",
"PIPE",
",",
"shell",
"=",
"True",
")",
"as",
"process",
":",
"# We initiate a process and parse the command to it.",
"while",
"True",
":",
"# We loop infini... | 34.78125 | 23.46875 |
def get_page_by_id_text(self, project, wiki_identifier, id, recursion_level=None, include_content=None, **kwargs):
"""GetPageByIdText.
[Preview API] Gets metadata or content of the wiki page for the provided page id. Content negotiation is done based on the `Accept` header sent in the request.
:... | [
"def",
"get_page_by_id_text",
"(",
"self",
",",
"project",
",",
"wiki_identifier",
",",
"id",
",",
"recursion_level",
"=",
"None",
",",
"include_content",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",... | 60.515152 | 29.181818 |
def start_drag(self, sprite, cursor_x = None, cursor_y = None):
"""start dragging given sprite"""
cursor_x, cursor_y = cursor_x or sprite.x, cursor_y or sprite.y
self._mouse_down_sprite = self._drag_sprite = sprite
sprite.drag_x, sprite.drag_y = self._drag_sprite.x, self._drag_sprite.y
... | [
"def",
"start_drag",
"(",
"self",
",",
"sprite",
",",
"cursor_x",
"=",
"None",
",",
"cursor_y",
"=",
"None",
")",
":",
"cursor_x",
",",
"cursor_y",
"=",
"cursor_x",
"or",
"sprite",
".",
"x",
",",
"cursor_y",
"or",
"sprite",
".",
"y",
"self",
".",
"_m... | 52.125 | 23.5 |
def _ensure_update_ha_compliant(self, router, current_router,
r_hd_binding_db):
"""To be called in update_router() BEFORE router has been
updated in DB.
"""
if r_hd_binding_db.role == ROUTER_ROLE_HA_REDUNDANCY:
return {ha.ENABLED: False}
... | [
"def",
"_ensure_update_ha_compliant",
"(",
"self",
",",
"router",
",",
"current_router",
",",
"r_hd_binding_db",
")",
":",
"if",
"r_hd_binding_db",
".",
"role",
"==",
"ROUTER_ROLE_HA_REDUNDANCY",
":",
"return",
"{",
"ha",
".",
"ENABLED",
":",
"False",
"}",
"auto... | 52.108108 | 17.945946 |
def _lastRecursiveChild(self):
"Finds the last element beneath this object to be parsed."
lastChild = self
while hasattr(lastChild, 'contents') and lastChild.contents:
lastChild = lastChild.contents[-1]
return lastChild | [
"def",
"_lastRecursiveChild",
"(",
"self",
")",
":",
"lastChild",
"=",
"self",
"while",
"hasattr",
"(",
"lastChild",
",",
"'contents'",
")",
"and",
"lastChild",
".",
"contents",
":",
"lastChild",
"=",
"lastChild",
".",
"contents",
"[",
"-",
"1",
"]",
"retu... | 43 | 17 |
def _decode(self):
"""
Convert the characters of character in value of component to standard
value (WFN value).
This function scans the value of component and returns a copy
with all percent-encoded characters decoded.
:exception: ValueError - invalid character in value ... | [
"def",
"_decode",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"idx",
"=",
"0",
"s",
"=",
"self",
".",
"_encoded_value",
"embedded",
"=",
"False",
"errmsg",
"=",
"[",
"]",
"errmsg",
".",
"append",
"(",
"\"Invalid value: \"",
")",
"while",
"(",
"id... | 37.085366 | 21.817073 |
def run(self, options, args):
"""Prints the completion code of the given shell"""
shells = COMPLETION_SCRIPTS.keys()
shell_options = ['--' + shell for shell in sorted(shells)]
if options.shell in shells:
script = COMPLETION_SCRIPTS.get(options.shell, '')
print(BAS... | [
"def",
"run",
"(",
"self",
",",
"options",
",",
"args",
")",
":",
"shells",
"=",
"COMPLETION_SCRIPTS",
".",
"keys",
"(",
")",
"shell_options",
"=",
"[",
"'--'",
"+",
"shell",
"for",
"shell",
"in",
"sorted",
"(",
"shells",
")",
"]",
"if",
"options",
"... | 45.363636 | 18.363636 |
def folderitems(self):
"""TODO: Refactor to non-classic mode
"""
items = super(AnalysisSpecificationView, self).folderitems()
self.categories.sort()
return items | [
"def",
"folderitems",
"(",
"self",
")",
":",
"items",
"=",
"super",
"(",
"AnalysisSpecificationView",
",",
"self",
")",
".",
"folderitems",
"(",
")",
"self",
".",
"categories",
".",
"sort",
"(",
")",
"return",
"items"
] | 32.666667 | 12.666667 |
def _make_2d_array(self, data):
"""
Convert a 1D array of mesh values to a masked 2D mesh array
given the 1D mesh indices ``mesh_idx``.
Parameters
----------
data : 1D `~numpy.ndarray`
A 1D array of mesh values.
Returns
-------
result... | [
"def",
"_make_2d_array",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
".",
"shape",
"!=",
"self",
".",
"mesh_idx",
".",
"shape",
":",
"raise",
"ValueError",
"(",
"'data and mesh_idx must have the same shape'",
")",
"if",
"np",
".",
"ma",
".",
"is_masked... | 31.314286 | 19.771429 |
def _join_paragraphs(cls, lines, use_indent=False, leading_blanks=False, trailing_blanks=False):
"""Join adjacent lines together into paragraphs using either a blank line or indent as separator."""
curr_para = []
paragraphs = []
for line in lines:
if use_indent:
... | [
"def",
"_join_paragraphs",
"(",
"cls",
",",
"lines",
",",
"use_indent",
"=",
"False",
",",
"leading_blanks",
"=",
"False",
",",
"trailing_blanks",
"=",
"False",
")",
":",
"curr_para",
"=",
"[",
"]",
"paragraphs",
"=",
"[",
"]",
"for",
"line",
"in",
"line... | 38.2 | 22.133333 |
def pre_encrypt_assertion(response):
"""
Move the assertion to within a encrypted_assertion
:param response: The response with one assertion
:return: The response but now with the assertion within an
encrypted_assertion.
"""
assertion = response.assertion
response.assertion = None
... | [
"def",
"pre_encrypt_assertion",
"(",
"response",
")",
":",
"assertion",
"=",
"response",
".",
"assertion",
"response",
".",
"assertion",
"=",
"None",
"response",
".",
"encrypted_assertion",
"=",
"EncryptedAssertion",
"(",
")",
"if",
"assertion",
"is",
"not",
"No... | 38.1875 | 13.9375 |
def resolve_variables(self, task):
"""
Resolve task variables based on input variables and the default
values.
Raises
------
LookupError
If a variable is missing.
"""
variables = {**task.variables, **self.project.variables}
values = ... | [
"def",
"resolve_variables",
"(",
"self",
",",
"task",
")",
":",
"variables",
"=",
"{",
"*",
"*",
"task",
".",
"variables",
",",
"*",
"*",
"self",
".",
"project",
".",
"variables",
"}",
"values",
"=",
"{",
"}",
"for",
"variable",
"in",
"variables",
".... | 25.409091 | 20.590909 |
def word_ngrams(s, n=3, token_fn=tokens.on_whitespace):
"""
Word-level n-grams in a string
By default, whitespace is assumed to be a word boundary.
>>> ng.word_ngrams('This is not a test!')
[('This', 'is', 'not'), ('is', 'not', 'a'), ('not', 'a', 'test!')]
If the sequence'... | [
"def",
"word_ngrams",
"(",
"s",
",",
"n",
"=",
"3",
",",
"token_fn",
"=",
"tokens",
".",
"on_whitespace",
")",
":",
"tokens",
"=",
"token_fn",
"(",
"s",
")",
"return",
"__ngrams",
"(",
"tokens",
",",
"n",
"=",
"min",
"(",
"len",
"(",
"tokens",
")",... | 27.434783 | 21.347826 |
def get_similar_users(self, users=None, k=10):
"""Get the k most similar users for each entry in `users`.
Each type of recommender has its own model for the similarity
between users. For example, the factorization_recommender will
return the nearest users based on the cosine similarity
... | [
"def",
"get_similar_users",
"(",
"self",
",",
"users",
"=",
"None",
",",
"k",
"=",
"10",
")",
":",
"if",
"users",
"is",
"None",
":",
"get_all_users",
"=",
"True",
"users",
"=",
"_SArray",
"(",
")",
"else",
":",
"get_all_users",
"=",
"False",
"if",
"i... | 38.359375 | 24.15625 |
def get_object_by_name(self, name):
"""Find an object
:param name: Name of object. Case-sensitive.
:rtype: Object if found, otherwise ValueError
"""
for obj in self.objects:
if obj.name == name:
return obj
raise ValueError | [
"def",
"get_object_by_name",
"(",
"self",
",",
"name",
")",
":",
"for",
"obj",
"in",
"self",
".",
"objects",
":",
"if",
"obj",
".",
"name",
"==",
"name",
":",
"return",
"obj",
"raise",
"ValueError"
] | 29.1 | 11.7 |
def logItems(self, level=logging.DEBUG):
""" rootItem
"""
rootItem = self.rootItem()
if rootItem is None:
logger.debug("No items in: {}".format(self))
else:
rootItem.logBranch(level=level) | [
"def",
"logItems",
"(",
"self",
",",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"rootItem",
"=",
"self",
".",
"rootItem",
"(",
")",
"if",
"rootItem",
"is",
"None",
":",
"logger",
".",
"debug",
"(",
"\"No items in: {}\"",
".",
"format",
"(",
"self... | 30.625 | 8 |
def backbone_bond_angles(self):
"""Dictionary containing backbone bond angles as lists of floats.
Returns
-------
bond_angles : dict
Keys are `n_ca_c`, `ca_c_o`, `ca_c_n` and `c_n_ca`, referring
to the N-CA-C, CA-C=O, CA-C-N and C-N-CA angles respectively.
... | [
"def",
"backbone_bond_angles",
"(",
"self",
")",
":",
"bond_angles",
"=",
"dict",
"(",
"n_ca_c",
"=",
"[",
"angle_between_vectors",
"(",
"r",
"[",
"'N'",
"]",
"-",
"r",
"[",
"'CA'",
"]",
",",
"r",
"[",
"'C'",
"]",
"-",
"r",
"[",
"'CA'",
"]",
")",
... | 54.115385 | 27.115385 |
def get_self_ip():
"""获取本机公网ip地址"""
TEST_IP = 'http://httpbin.org/ip'
html = requests.get(TEST_IP)
ip = json.loads(html.text)['origin']
return ip | [
"def",
"get_self_ip",
"(",
")",
":",
"TEST_IP",
"=",
"'http://httpbin.org/ip'",
"html",
"=",
"requests",
".",
"get",
"(",
"TEST_IP",
")",
"ip",
"=",
"json",
".",
"loads",
"(",
"html",
".",
"text",
")",
"[",
"'origin'",
"]",
"return",
"ip"
] | 26.666667 | 10 |
def char_beam_search(out):
"""
Description : apply beam search for prediction result
"""
out_conv = list()
for idx in range(out.shape[0]):
probs = out[idx]
prob = probs.softmax().asnumpy()
line_string_proposals = ctcBeamSearch(prob, ALPHABET, None, k=4, beamWidth=25)
... | [
"def",
"char_beam_search",
"(",
"out",
")",
":",
"out_conv",
"=",
"list",
"(",
")",
"for",
"idx",
"in",
"range",
"(",
"out",
".",
"shape",
"[",
"0",
"]",
")",
":",
"probs",
"=",
"out",
"[",
"idx",
"]",
"prob",
"=",
"probs",
".",
"softmax",
"(",
... | 33.727273 | 13.363636 |
def get_leapdays(init_date, final_date):
"""
Find the number of leap days between arbitrary dates. Returns a
timedelta object.
FIXME: calculate this instead of iterating.
"""
curr_date = init_date
leap_days = 0
while curr_date != final_date:
if curr_date.month == 2 and curr_d... | [
"def",
"get_leapdays",
"(",
"init_date",
",",
"final_date",
")",
":",
"curr_date",
"=",
"init_date",
"leap_days",
"=",
"0",
"while",
"curr_date",
"!=",
"final_date",
":",
"if",
"curr_date",
".",
"month",
"==",
"2",
"and",
"curr_date",
".",
"day",
"==",
"29... | 23.105263 | 19.947368 |
def output_to_terminal(sources):
"""Print statistics to the terminal"""
results = OrderedDict()
for source in sources:
if source.get_is_available():
source.update()
results.update(source.get_summary())
for key, value in results.items():
sys.stdout.write(str(key) +... | [
"def",
"output_to_terminal",
"(",
"sources",
")",
":",
"results",
"=",
"OrderedDict",
"(",
")",
"for",
"source",
"in",
"sources",
":",
"if",
"source",
".",
"get_is_available",
"(",
")",
":",
"source",
".",
"update",
"(",
")",
"results",
".",
"update",
"(... | 34.363636 | 11.090909 |
def like(self):
""" Like a clip.
"""
r = requests.post(
"https://kippt.com/api/clips/%s/likes" % (self.id),
headers=self.kippt.header
)
return (r.json()) | [
"def",
"like",
"(",
"self",
")",
":",
"r",
"=",
"requests",
".",
"post",
"(",
"\"https://kippt.com/api/clips/%s/likes\"",
"%",
"(",
"self",
".",
"id",
")",
",",
"headers",
"=",
"self",
".",
"kippt",
".",
"header",
")",
"return",
"(",
"r",
".",
"json",
... | 23.333333 | 16.777778 |
def get_species(taxdump_file, select_divisions=None,
exclude_divisions=None, nrows=None):
"""Get a dataframe with species information."""
if select_divisions and exclude_divisions:
raise ValueError('Cannot specify "select_divisions" and '
'"exclude_divisions... | [
"def",
"get_species",
"(",
"taxdump_file",
",",
"select_divisions",
"=",
"None",
",",
"exclude_divisions",
"=",
"None",
",",
"nrows",
"=",
"None",
")",
":",
"if",
"select_divisions",
"and",
"exclude_divisions",
":",
"raise",
"ValueError",
"(",
"'Cannot specify \"s... | 37.88 | 17.06 |
def load(self, name):
"""
If not yet in the cache, load the named template and compiles it,
placing it into the cache.
If in cache, return the cached template.
"""
if self.reload:
self._maybe_purge_cache()
template = self.cache.get(name)
if ... | [
"def",
"load",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"reload",
":",
"self",
".",
"_maybe_purge_cache",
"(",
")",
"template",
"=",
"self",
".",
"cache",
".",
"get",
"(",
"name",
")",
"if",
"template",
":",
"return",
"template",
"path"... | 26.896552 | 19.172414 |
def empty_platform(cls, arch):
"""
Create a platform without an ELF loaded.
:param str arch: The architecture of the new platform
:rtype: Linux
"""
platform = cls(None)
platform._init_cpu(arch)
platform._init_std_fds()
return platform | [
"def",
"empty_platform",
"(",
"cls",
",",
"arch",
")",
":",
"platform",
"=",
"cls",
"(",
"None",
")",
"platform",
".",
"_init_cpu",
"(",
"arch",
")",
"platform",
".",
"_init_std_fds",
"(",
")",
"return",
"platform"
] | 27 | 13 |
def user_feature_update(self, userid, payload):
''' update features by user id '''
response, status_code = self.__pod__.User.post_v1_admin_user_uid_features_update(
sessionToken=self.__session__,
uid=userid,
payload=payload
).result()
self.logger.debug... | [
"def",
"user_feature_update",
"(",
"self",
",",
"userid",
",",
"payload",
")",
":",
"response",
",",
"status_code",
"=",
"self",
".",
"__pod__",
".",
"User",
".",
"post_v1_admin_user_uid_features_update",
"(",
"sessionToken",
"=",
"self",
".",
"__session__",
","... | 42.777778 | 15.222222 |
def options(self, parser, env=os.environ):
"""Register commandline options."""
super(TimerPlugin, self).options(parser, env)
# timer top n
parser.add_option(
"--timer-top-n",
action="store",
default="-1",
dest="timer_top_n",
he... | [
"def",
"options",
"(",
"self",
",",
"parser",
",",
"env",
"=",
"os",
".",
"environ",
")",
":",
"super",
"(",
"TimerPlugin",
",",
"self",
")",
".",
"options",
"(",
"parser",
",",
"env",
")",
"# timer top n",
"parser",
".",
"add_option",
"(",
"\"--timer-... | 30.554217 | 20.951807 |
def parse_limits_list(path, limits):
"""Parse a structured list of flux limits as obtained from a YAML file
Yields tuples of reaction ID, lower and upper flux bounds. Path can be
given as a string or a context.
"""
context = FilePathContext(path)
for limit_def in limits:
if 'include' ... | [
"def",
"parse_limits_list",
"(",
"path",
",",
"limits",
")",
":",
"context",
"=",
"FilePathContext",
"(",
"path",
")",
"for",
"limit_def",
"in",
"limits",
":",
"if",
"'include'",
"in",
"limit_def",
":",
"include_context",
"=",
"context",
".",
"resolve",
"(",... | 33.125 | 17.0625 |
def dump(database, output, min_occurences=1, max_occurences=250, returncmd=False):
"""
Dumps output from kmc database into tab-delimited format.
:param database: Database generated by kmc.
:param output: Name for output.
:param min_occurences: Minimum number of times kmer must be in database to be d... | [
"def",
"dump",
"(",
"database",
",",
"output",
",",
"min_occurences",
"=",
"1",
",",
"max_occurences",
"=",
"250",
",",
"returncmd",
"=",
"False",
")",
":",
"cmd",
"=",
"'kmc_tools dump -ci{} -cx{} {} {}'",
".",
"format",
"(",
"min_occurences",
",",
"max_occur... | 49 | 24.125 |
def validate_authorization_request(self, uri, http_method='GET', body=None,
headers=None):
"""Extract response_type and route to the designated handler."""
request = Request(
uri, http_method=http_method, body=body, headers=headers)
request.sco... | [
"def",
"validate_authorization_request",
"(",
"self",
",",
"uri",
",",
"http_method",
"=",
"'GET'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"request",
"=",
"Request",
"(",
"uri",
",",
"http_method",
"=",
"http_method",
",",
"body",... | 50.545455 | 24.727273 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.