text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def add_information_about_person(self, session_info):
"""If there already are information from this source in the cache
this function will overwrite that information"""
session_info = dict(session_info)
name_id = session_info["name_id"]
issuer = session_info.pop("issuer")
... | [
"def",
"add_information_about_person",
"(",
"self",
",",
"session_info",
")",
":",
"session_info",
"=",
"dict",
"(",
"session_info",
")",
"name_id",
"=",
"session_info",
"[",
"\"name_id\"",
"]",
"issuer",
"=",
"session_info",
".",
"pop",
"(",
"\"issuer\"",
")",
... | 43.7 | 10.4 |
def dummyvar(cis, return_sparse=False):
'''
This is an efficient implementation of matlab's "dummyvar" command
using sparse matrices.
input: partitions, NxM array-like containing M partitions of N nodes
into <=N distinct communities
output: dummyvar, an NxR matrix containing R column varia... | [
"def",
"dummyvar",
"(",
"cis",
",",
"return_sparse",
"=",
"False",
")",
":",
"# num_rows is not affected by partition indexes",
"n",
"=",
"np",
".",
"size",
"(",
"cis",
",",
"axis",
"=",
"0",
")",
"m",
"=",
"np",
".",
"size",
"(",
"cis",
",",
"axis",
"... | 35.757576 | 22.727273 |
def time(hour, minute=0, second=0, microsecond=0): # type: (int, int, int, int) -> Time
"""
Create a new Time instance.
"""
return Time(hour, minute, second, microsecond) | [
"def",
"time",
"(",
"hour",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0",
",",
"microsecond",
"=",
"0",
")",
":",
"# type: (int, int, int, int) -> Time",
"return",
"Time",
"(",
"hour",
",",
"minute",
",",
"second",
",",
"microsecond",
")"
] | 36.6 | 13.4 |
def get_screen_pointers(self):
"""
Returns the xcb_screen_t for every screen
useful for other bindings
"""
root_iter = lib.xcb_setup_roots_iterator(self._setup)
screens = [root_iter.data]
for i in range(self._setup.roots_len - 1):
lib.xcb_screen_next(... | [
"def",
"get_screen_pointers",
"(",
"self",
")",
":",
"root_iter",
"=",
"lib",
".",
"xcb_setup_roots_iterator",
"(",
"self",
".",
"_setup",
")",
"screens",
"=",
"[",
"root_iter",
".",
"data",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_setup",
"."... | 33.5 | 11.833333 |
def write(self, address, size, value):
"""Write arbitrary size content to memory.
"""
for i in range(0, size):
self.__write_byte(address + i, (value >> (i * 8)) & 0xff) | [
"def",
"write",
"(",
"self",
",",
"address",
",",
"size",
",",
"value",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"size",
")",
":",
"self",
".",
"__write_byte",
"(",
"address",
"+",
"i",
",",
"(",
"value",
">>",
"(",
"i",
"*",
"8",
... | 40 | 7.8 |
def save(self):
"""Convert to JSON.
Returns
-------
`dict`
JSON data.
"""
data = super().save()
data['end_chars'] = self.end_chars
data['default_end'] = self.default_end
return data | [
"def",
"save",
"(",
"self",
")",
":",
"data",
"=",
"super",
"(",
")",
".",
"save",
"(",
")",
"data",
"[",
"'end_chars'",
"]",
"=",
"self",
".",
"end_chars",
"data",
"[",
"'default_end'",
"]",
"=",
"self",
".",
"default_end",
"return",
"data"
] | 21.25 | 16.583333 |
def BHS(self, params):
"""
BHS label
Branch to the instruction at label if the C flag is set
"""
label = self.get_one_parameter(self.ONE_PARAMETER, params)
self.check_arguments(label_exists=(label,))
# BHS label
def BHS_func():
if self.is_C_... | [
"def",
"BHS",
"(",
"self",
",",
"params",
")",
":",
"label",
"=",
"self",
".",
"get_one_parameter",
"(",
"self",
".",
"ONE_PARAMETER",
",",
"params",
")",
"self",
".",
"check_arguments",
"(",
"label_exists",
"=",
"(",
"label",
",",
")",
")",
"# BHS label... | 24.5625 | 21.3125 |
def init_config(self):
"""Patch input.nml as a new or restart run."""
input_fpath = os.path.join(self.work_path, 'input.nml')
input_nml = f90nml.read(input_fpath)
if self.expt.counter == 0 or self.expt.repeat_run:
input_type = 'n'
else:
input_type = 'r'... | [
"def",
"init_config",
"(",
"self",
")",
":",
"input_fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"work_path",
",",
"'input.nml'",
")",
"input_nml",
"=",
"f90nml",
".",
"read",
"(",
"input_fpath",
")",
"if",
"self",
".",
"expt",
".",
... | 30.785714 | 22.5 |
def findChangelist(self, description=None):
"""Gets or creates a Changelist object with a description
:param description: The description to set or lookup
:type description: str
:returns: :class:`.Changelist`
"""
if description is None:
change = Default(self)... | [
"def",
"findChangelist",
"(",
"self",
",",
"description",
"=",
"None",
")",
":",
"if",
"description",
"is",
"None",
":",
"change",
"=",
"Default",
"(",
"self",
")",
"else",
":",
"if",
"isinstance",
"(",
"description",
",",
"six",
".",
"integer_types",
")... | 42.346154 | 19.346154 |
def run(self):
"""Run command."""
command = ['npm', 'install']
self.announce(
'Running command: %s' % str(command),
level=INFO)
subprocess.check_call(command) | [
"def",
"run",
"(",
"self",
")",
":",
"command",
"=",
"[",
"'npm'",
",",
"'install'",
"]",
"self",
".",
"announce",
"(",
"'Running command: %s'",
"%",
"str",
"(",
"command",
")",
",",
"level",
"=",
"INFO",
")",
"subprocess",
".",
"check_call",
"(",
"com... | 29.714286 | 10.857143 |
def symmetric_elliot_function( signal, derivative=False ):
""" A fast approximation of tanh """
s = 1.0 # steepness
abs_signal = (1 + np.abs(signal * s))
if derivative:
return s / abs_signal**2
else:
# Return the activation signal
return (signal * s) / abs_signal | [
"def",
"symmetric_elliot_function",
"(",
"signal",
",",
"derivative",
"=",
"False",
")",
":",
"s",
"=",
"1.0",
"# steepness",
"abs_signal",
"=",
"(",
"1",
"+",
"np",
".",
"abs",
"(",
"signal",
"*",
"s",
")",
")",
"if",
"derivative",
":",
"return",
"s",... | 30.3 | 13.5 |
def RemoveUser(self, user):
"""Remove a Linux user account.
Args:
user: string, the Linux user account to remove.
"""
self.logger.info('Removing user %s.', user)
if self.remove:
command = self.userdel_cmd.format(user=user)
try:
subprocess.check_call(command.split(' '))
... | [
"def",
"RemoveUser",
"(",
"self",
",",
"user",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Removing user %s.'",
",",
"user",
")",
"if",
"self",
".",
"remove",
":",
"command",
"=",
"self",
".",
"userdel_cmd",
".",
"format",
"(",
"user",
"=",
... | 33.823529 | 15.823529 |
def index_fields(self, index=Index(), **options):
""" Indexes the `Pointer` field and the :attr:`data` object referenced
by the `Pointer` field starting with the given *index* and returns the
:class:`Index` after the `Pointer` field.
:param Index index: :class:`Index` for the `Pointer` ... | [
"def",
"index_fields",
"(",
"self",
",",
"index",
"=",
"Index",
"(",
")",
",",
"*",
"*",
"options",
")",
":",
"index",
"=",
"self",
".",
"index_field",
"(",
"index",
")",
"# Container",
"if",
"is_container",
"(",
"self",
".",
"_data",
")",
":",
"self... | 46 | 17.709677 |
def min_med(images, weight_images, readnoise_list, exptime_list,
background_values, weight_masks=None, combine_grow=1,
combine_nsigma1=4, combine_nsigma2=3, fillval=False):
""" Create a median array, rejecting the highest pixel and
computing the lowest valid pixel after mask application.... | [
"def",
"min_med",
"(",
"images",
",",
"weight_images",
",",
"readnoise_list",
",",
"exptime_list",
",",
"background_values",
",",
"weight_masks",
"=",
"None",
",",
"combine_grow",
"=",
"1",
",",
"combine_nsigma1",
"=",
"4",
",",
"combine_nsigma2",
"=",
"3",
",... | 43.8 | 24.407018 |
def update_line(self, t, x, y, **kw):
"""overwrite data for trace t """
self.panel.update_line(t, x, y, **kw) | [
"def",
"update_line",
"(",
"self",
",",
"t",
",",
"x",
",",
"y",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"panel",
".",
"update_line",
"(",
"t",
",",
"x",
",",
"y",
",",
"*",
"*",
"kw",
")"
] | 41 | 2.666667 |
def _object_with_attr(self, name):
"""
Returns the first object that has the attribute `name`
:param name: the attribute to filter by
:type name: `str`
:raises AttributeError: when no object has the named attribute
"""
for obj in self._objects:
if has... | [
"def",
"_object_with_attr",
"(",
"self",
",",
"name",
")",
":",
"for",
"obj",
"in",
"self",
".",
"_objects",
":",
"if",
"hasattr",
"(",
"obj",
",",
"name",
")",
":",
"return",
"obj",
"raise",
"AttributeError",
"(",
"\"No object has attribute {!r}\"",
".",
... | 32.769231 | 16.923077 |
def get_time_axis(start_time, end_time, time_step, time_axis=None):
"""
Create a list of datetimes based on an start time, end time and
time step. If such a list is already passed in, then this is not
necessary.
Often either the start_time, end_time, time_step is passed into an
... | [
"def",
"get_time_axis",
"(",
"start_time",
",",
"end_time",
",",
"time_step",
",",
"time_axis",
"=",
"None",
")",
":",
"#Do this import here to avoid a circular dependency",
"from",
".",
".",
"lib",
"import",
"units",
"if",
"time_axis",
"is",
"not",
"None",
":",
... | 37.77551 | 20.428571 |
def AvgPool(a, k, strides, padding, data_format):
"""
Average pooling op.
"""
if data_format.decode("ascii") == "NCHW":
a = np.rollaxis(a, 1, -1),
patches = _pool_patches(a, k, strides, padding.decode("ascii"))
pool = np.average(patches, axis=tuple(range(-len(k), 0)))
if data_forma... | [
"def",
"AvgPool",
"(",
"a",
",",
"k",
",",
"strides",
",",
"padding",
",",
"data_format",
")",
":",
"if",
"data_format",
".",
"decode",
"(",
"\"ascii\"",
")",
"==",
"\"NCHW\"",
":",
"a",
"=",
"np",
".",
"rollaxis",
"(",
"a",
",",
"1",
",",
"-",
"... | 28.071429 | 16.785714 |
def ticket_metric_show(self, ticket_metric_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/ticket_metrics#show-ticket-metrics"
api_path = "/api/v2/ticket_metrics/{ticket_metric_id}.json"
api_path = api_path.format(ticket_metric_id=ticket_metric_id)
return self.call(api_p... | [
"def",
"ticket_metric_show",
"(",
"self",
",",
"ticket_metric_id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/ticket_metrics/{ticket_metric_id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"ticket_metric_id",
"=",
"ticket_metric_id",
"... | 66 | 26 |
def resetStats(self):
""" Reset the learning and inference stats. This will usually be called by
user code at the start of each inference run (for a particular data set).
"""
self._stats = dict()
self._internalStats = dict()
self._internalStats['nInfersSinceReset'] = 0
self._internalStats['... | [
"def",
"resetStats",
"(",
"self",
")",
":",
"self",
".",
"_stats",
"=",
"dict",
"(",
")",
"self",
".",
"_internalStats",
"=",
"dict",
"(",
")",
"self",
".",
"_internalStats",
"[",
"'nInfersSinceReset'",
"]",
"=",
"0",
"self",
".",
"_internalStats",
"[",
... | 40.290323 | 15.483871 |
def fetch_changes(repo_path, up_commit='master'):
"""
Fetch latest changes from stage and touch .timestamp
if any python sources have been modified.
"""
last_up_commit = None
prevcwd = os.getcwd()
try:
gitexe = 'git'
os.chdir(repo_path)
old_sources_timestamp = sources... | [
"def",
"fetch_changes",
"(",
"repo_path",
",",
"up_commit",
"=",
"'master'",
")",
":",
"last_up_commit",
"=",
"None",
"prevcwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"try",
":",
"gitexe",
"=",
"'git'",
"os",
".",
"chdir",
"(",
"repo_path",
")",
"old_sourc... | 39.681818 | 15.5 |
def kill(self, sig):
"""Send the given signal to the child application.
In keeping with UNIX tradition it has a misleading name. It does not
necessarily kill the child unless you send the right signal. See the
:mod:`signal` module for constants representing signal numbers.
"""
... | [
"def",
"kill",
"(",
"self",
",",
"sig",
")",
":",
"# Same as os.kill, but the pid is given for you.",
"if",
"self",
".",
"isalive",
"(",
")",
":",
"os",
".",
"kill",
"(",
"self",
".",
"pid",
",",
"sig",
")"
] | 38.909091 | 21.727273 |
def _set_filter(self, v, load=False):
"""
Setter method for filter, mapped from YANG variable /interface_vlan/interface/vlan/ip/arp/inspection/filter (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_filter is considered as a private
method. Backends lookin... | [
"def",
"_set_filter",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | 71.454545 | 33.772727 |
def play_audio(filename: str):
"""
Args:
filename: Audio filename
"""
import platform
from subprocess import Popen
player = 'play' if platform.system() == 'Darwin' else 'aplay'
Popen([player, '-q', filename]) | [
"def",
"play_audio",
"(",
"filename",
":",
"str",
")",
":",
"import",
"platform",
"from",
"subprocess",
"import",
"Popen",
"player",
"=",
"'play'",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Darwin'",
"else",
"'aplay'",
"Popen",
"(",
"[",
"player",... | 23.6 | 14.8 |
def play_move_msg(self, move_msg):
"""Another play move function for move message.
Parameters
----------
move_msg : string
a valid message should be in:
"[move type]: [X], [Y]"
"""
move_type, move_x, move_y = self.parse_move(move_msg)
self... | [
"def",
"play_move_msg",
"(",
"self",
",",
"move_msg",
")",
":",
"move_type",
",",
"move_x",
",",
"move_y",
"=",
"self",
".",
"parse_move",
"(",
"move_msg",
")",
"self",
".",
"play_move",
"(",
"move_type",
",",
"move_x",
",",
"move_y",
")"
] | 31.545455 | 12.818182 |
def split_source(source_code):
'''Split source code into lines
'''
eol_chars = get_eol_chars(source_code)
if eol_chars:
return source_code.split(eol_chars)
else:
return [source_code] | [
"def",
"split_source",
"(",
"source_code",
")",
":",
"eol_chars",
"=",
"get_eol_chars",
"(",
"source_code",
")",
"if",
"eol_chars",
":",
"return",
"source_code",
".",
"split",
"(",
"eol_chars",
")",
"else",
":",
"return",
"[",
"source_code",
"]"
] | 27.25 | 14.5 |
def setShowGridRows( self, state ):
"""
Sets whether or not the grid rows should be rendered when drawing the \
grid.
:param state | <bool>
"""
delegate = self.itemDelegate()
if ( isinstance(delegate, XTreeWidgetDelegate) ):
dele... | [
"def",
"setShowGridRows",
"(",
"self",
",",
"state",
")",
":",
"delegate",
"=",
"self",
".",
"itemDelegate",
"(",
")",
"if",
"(",
"isinstance",
"(",
"delegate",
",",
"XTreeWidgetDelegate",
")",
")",
":",
"delegate",
".",
"setShowGridRows",
"(",
"state",
")... | 33.8 | 12.8 |
def parse_load_fk(cls, data: Dict[str, List[Dict[str, object]]]) -> Dict[str, List[Dict[str, object]]]:
"""
:param data:{
<column>: role,
<column2>: role,
<column>: {
'role': role,
'loadfk': { ... },
},
:return: {
... | [
"def",
"parse_load_fk",
"(",
"cls",
",",
"data",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"Dict",
"[",
"str",
",",
"object",
"]",
"]",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"Dict",
"[",
"str",
",",
"object",
"]",
"]",
"]",
"... | 36.580645 | 17.290323 |
def add_packages(self, packages):
"""
Adds an automatic resolution of urls into tasks.
:param packages: The url will determine package/module and the class.
:return: self
"""
# type: (List[str])->TaskNamespace
assert isinstance(packages, list), "Packages must be l... | [
"def",
"add_packages",
"(",
"self",
",",
"packages",
")",
":",
"# type: (List[str])->TaskNamespace",
"assert",
"isinstance",
"(",
"packages",
",",
"list",
")",
",",
"\"Packages must be list of strings.\"",
"self",
".",
"_task_packages",
"+=",
"packages",
"return",
"se... | 38.7 | 14.1 |
def eqstr(a, b):
"""
Determine whether two strings are equivalent.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eqstr_c.html
:param a: Arbitrary character string.
:type a: str
:param b: Arbitrary character string.
:type b: str
:return: True if A and B are equivalent.
:rt... | [
"def",
"eqstr",
"(",
"a",
",",
"b",
")",
":",
"return",
"bool",
"(",
"libspice",
".",
"eqstr_c",
"(",
"stypes",
".",
"stringToCharP",
"(",
"a",
")",
",",
"stypes",
".",
"stringToCharP",
"(",
"b",
")",
")",
")"
] | 29.142857 | 19 |
def Yashar(x, rhol, rhog, mul, mug, m, D, g=g):
r'''Calculates void fraction in two-phase flow according to the model of
[1]_ also given in [2]_ and [3]_.
.. math::
\alpha = \left[1 + \frac{1}{Ft} + X_{tt}\right]^{-0.321}
.. math::
Ft = \left[\frac{G_{tp}^2 x^3}{(1-x)\rho_... | [
"def",
"Yashar",
"(",
"x",
",",
"rhol",
",",
"rhog",
",",
"mul",
",",
"mug",
",",
"m",
",",
"D",
",",
"g",
"=",
"g",
")",
":",
"G",
"=",
"m",
"/",
"(",
"pi",
"/",
"4",
"*",
"D",
"**",
"2",
")",
"Ft",
"=",
"(",
"G",
"**",
"2",
"*",
"... | 35.048387 | 24.080645 |
def index(self, value):
"""
Return index of *value* in self.
Raises ValueError if *value* is not found.
"""
# pylint: disable=arguments-differ
for idx, val in enumerate(self):
if value == val:
return idx
raise ValueError('{0!r} is not ... | [
"def",
"index",
"(",
"self",
",",
"value",
")",
":",
"# pylint: disable=arguments-differ",
"for",
"idx",
",",
"val",
"in",
"enumerate",
"(",
"self",
")",
":",
"if",
"value",
"==",
"val",
":",
"return",
"idx",
"raise",
"ValueError",
"(",
"'{0!r} is not in dic... | 30.272727 | 10.636364 |
def generate_uuid():
"""Generate a UUID."""
r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
return r_uuid.decode().replace('=', '') | [
"def",
"generate_uuid",
"(",
")",
":",
"r_uuid",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"uuid",
".",
"uuid4",
"(",
")",
".",
"bytes",
")",
"return",
"r_uuid",
".",
"decode",
"(",
")",
".",
"replace",
"(",
"'='",
",",
"''",
")"
] | 36.5 | 10 |
def sysidpath(ignore_options=False):
""" get a unique identifier for the machine running this function """
# in the event we have to make our own
# this should not be passed in a as a parameter
# since we need these definitions to be more or less static
failover = Path('/tmp/machine-id')
if not... | [
"def",
"sysidpath",
"(",
"ignore_options",
"=",
"False",
")",
":",
"# in the event we have to make our own",
"# this should not be passed in a as a parameter",
"# since we need these definitions to be more or less static",
"failover",
"=",
"Path",
"(",
"'/tmp/machine-id'",
")",
"if... | 32.956522 | 15.956522 |
def __decorate_axis(axis, ax_type):
'''Configure axis tickers, locators, and labels'''
if ax_type == 'tonnetz':
axis.set_major_formatter(TonnetzFormatter())
axis.set_major_locator(FixedLocator(0.5 + np.arange(6)))
axis.set_label_text('Tonnetz')
elif ax_type == 'chroma':
axi... | [
"def",
"__decorate_axis",
"(",
"axis",
",",
"ax_type",
")",
":",
"if",
"ax_type",
"==",
"'tonnetz'",
":",
"axis",
".",
"set_major_formatter",
"(",
"TonnetzFormatter",
"(",
")",
")",
"axis",
".",
"set_major_locator",
"(",
"FixedLocator",
"(",
"0.5",
"+",
"np"... | 40.183908 | 19.287356 |
def pypi_render(source):
"""
Copied (and slightly adapted) from pypi.description_tools
"""
ALLOWED_SCHEMES = '''file ftp gopher hdl http https imap mailto mms news
nntp prospero rsync rtsp rtspu sftp shttp sip sips snews svn svn+ssh
telnet wais irc'''.split()
settings_overrides = {
... | [
"def",
"pypi_render",
"(",
"source",
")",
":",
"ALLOWED_SCHEMES",
"=",
"'''file ftp gopher hdl http https imap mailto mms news\n nntp prospero rsync rtsp rtspu sftp shttp sip sips snews svn svn+ssh\n telnet wais irc'''",
".",
"split",
"(",
")",
"settings_overrides",
"=",
... | 32.896552 | 18.37931 |
def lies_under(self, prefix):
"""Indicates if the `prefix` is a parent of this path.
"""
orig_list = self.norm_case()._components()
pref_list = self.__class__(prefix).norm_case()._components()
return (len(orig_list) >= len(pref_list) and
orig_list[:len(pref_list)... | [
"def",
"lies_under",
"(",
"self",
",",
"prefix",
")",
":",
"orig_list",
"=",
"self",
".",
"norm_case",
"(",
")",
".",
"_components",
"(",
")",
"pref_list",
"=",
"self",
".",
"__class__",
"(",
"prefix",
")",
".",
"norm_case",
"(",
")",
".",
"_components... | 41 | 14.625 |
def _set_properties(self):
"""Setup title, size and tooltips"""
self.codetext_ctrl.SetToolTipString(_("Enter python code here."))
self.apply_button.SetToolTipString(_("Apply changes to current macro"))
self.splitter.SetBackgroundStyle(wx.BG_STYLE_COLOUR)
self.result_ctrl.SetMinS... | [
"def",
"_set_properties",
"(",
"self",
")",
":",
"self",
".",
"codetext_ctrl",
".",
"SetToolTipString",
"(",
"_",
"(",
"\"Enter python code here.\"",
")",
")",
"self",
".",
"apply_button",
".",
"SetToolTipString",
"(",
"_",
"(",
"\"Apply changes to current macro\"",... | 46.714286 | 21.571429 |
def _find_realname(self, post_input):
""" Returns the most appropriate name to identify the user """
# First, try the full name
if "lis_person_name_full" in post_input:
return post_input["lis_person_name_full"]
if "lis_person_name_given" in post_input and "lis_person_name_fa... | [
"def",
"_find_realname",
"(",
"self",
",",
"post_input",
")",
":",
"# First, try the full name",
"if",
"\"lis_person_name_full\"",
"in",
"post_input",
":",
"return",
"post_input",
"[",
"\"lis_person_name_full\"",
"]",
"if",
"\"lis_person_name_given\"",
"in",
"post_input",... | 43.05 | 20.45 |
def calculate(self, batch_info):
""" Calculate value of a metric """
value = self._value_function(batch_info['data'], batch_info['target'], batch_info['output'])
self.storage.append(value) | [
"def",
"calculate",
"(",
"self",
",",
"batch_info",
")",
":",
"value",
"=",
"self",
".",
"_value_function",
"(",
"batch_info",
"[",
"'data'",
"]",
",",
"batch_info",
"[",
"'target'",
"]",
",",
"batch_info",
"[",
"'output'",
"]",
")",
"self",
".",
"storag... | 52.25 | 18.5 |
def rcParams(self):
"""
Return rcParams dict for this theme.
Notes
-----
Subclasses should not need to override this method method as long as
self._rcParams is constructed properly.
rcParams are used during plotting. Sometimes the same theme can be
achie... | [
"def",
"rcParams",
"(",
"self",
")",
":",
"try",
":",
"rcParams",
"=",
"deepcopy",
"(",
"self",
".",
"_rcParams",
")",
"except",
"NotImplementedError",
":",
"# deepcopy raises an error for objects that are drived from or",
"# composed of matplotlib.transform.TransformNode.",
... | 37.90625 | 22.96875 |
def initialize_training(self, training_info: TrainingInfo, model_state=None, hidden_state=None):
""" Prepare models for training """
if model_state is not None:
self.model.load_state_dict(model_state)
else:
self.model.reset_weights()
self.algo.initialize(
... | [
"def",
"initialize_training",
"(",
"self",
",",
"training_info",
":",
"TrainingInfo",
",",
"model_state",
"=",
"None",
",",
"hidden_state",
"=",
"None",
")",
":",
"if",
"model_state",
"is",
"not",
"None",
":",
"self",
".",
"model",
".",
"load_state_dict",
"(... | 43.2 | 26.1 |
def ts(self, n):
"""
:param n: number of charge
:return: when to shoot nth charge, milliseconds
"""
try:
root1, root2 = solve_quadratic(self.slope / 2.0, self.minrps, -n)
except ZeroDivisionError:
root2 = float(n) / self.minrps
return int(r... | [
"def",
"ts",
"(",
"self",
",",
"n",
")",
":",
"try",
":",
"root1",
",",
"root2",
"=",
"solve_quadratic",
"(",
"self",
".",
"slope",
"/",
"2.0",
",",
"self",
".",
"minrps",
",",
"-",
"n",
")",
"except",
"ZeroDivisionError",
":",
"root2",
"=",
"float... | 32.3 | 12.7 |
def log_raise(log, err_str, err_type=RuntimeError):
"""Log an error message and raise an error.
Arguments
---------
log : `logging.Logger` object
err_str : str
Error message to be logged and raised.
err_type : `Exception` object
Type of error to raise.
"""
log.error(err... | [
"def",
"log_raise",
"(",
"log",
",",
"err_str",
",",
"err_type",
"=",
"RuntimeError",
")",
":",
"log",
".",
"error",
"(",
"err_str",
")",
"# Make sure output is flushed",
"# (happens automatically to `StreamHandlers`, but not `FileHandlers`)",
"for",
"handle",
"in",
"lo... | 27.473684 | 16.421053 |
def arg_spec(cls, mtd_name):
"""Cross-version argument signature inspection
Parameters
----------
cls : class
mtd_name : str
Name of the method to be inspected
Returns
-------
required_params : list of str
List of required, positional parameters
optional_params : li... | [
"def",
"arg_spec",
"(",
"cls",
",",
"mtd_name",
")",
":",
"mtd",
"=",
"getattr",
"(",
"cls",
",",
"mtd_name",
")",
"required_params",
"=",
"[",
"]",
"optional_params",
"=",
"[",
"]",
"if",
"hasattr",
"(",
"inspect",
",",
"'signature'",
")",
":",
"# Pyt... | 37.285714 | 20.938776 |
def _pypsa_generator_timeseries_aggregated_at_lv_station(network, timesteps):
"""
Aggregates generator time series per generator subtype and LV grid.
Parameters
----------
network : Network
The eDisGo grid topology model overall container
timesteps : array_like
Timesteps is an a... | [
"def",
"_pypsa_generator_timeseries_aggregated_at_lv_station",
"(",
"network",
",",
"timesteps",
")",
":",
"generation_p",
"=",
"[",
"]",
"generation_q",
"=",
"[",
"]",
"for",
"lv_grid",
"in",
"network",
".",
"mv_grid",
".",
"lv_grids",
":",
"# Determine aggregated ... | 40.766667 | 21.666667 |
def move_to_step(self, step):
"""
Use in cases when you need to move in given step depending on input
"""
if step not in self._scenario_steps.keys():
raise UndefinedState("step {} not defined in scenario".format(step))
try:
session_id = session.sessionId
... | [
"def",
"move_to_step",
"(",
"self",
",",
"step",
")",
":",
"if",
"step",
"not",
"in",
"self",
".",
"_scenario_steps",
".",
"keys",
"(",
")",
":",
"raise",
"UndefinedState",
"(",
"\"step {} not defined in scenario\"",
".",
"format",
"(",
"step",
")",
")",
"... | 41.083333 | 14.583333 |
def fix_header_comment(filename, timestamp):
"""Fixes the header-comment of the given file."""
# Fix input file.
name = os.path.basename( filename )
for line in fileinput.input( filename, inplace=1, mode="rU" ):
# If header-comment already contains anything for '$Id$', remove it.
line = ... | [
"def",
"fix_header_comment",
"(",
"filename",
",",
"timestamp",
")",
":",
"# Fix input file.",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"for",
"line",
"in",
"fileinput",
".",
"input",
"(",
"filename",
",",
"inplace",
"=",
"1",... | 57.4 | 24.3 |
def ektnam(n, lenout=_default_len_out):
"""
Return the name of a specified, loaded table.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ektnam_c.html
:param n: Index of table.
:type n: int
:param lenout: Maximum table name length.
:type lenout: int
:return: Name of table.
... | [
"def",
"ektnam",
"(",
"n",
",",
"lenout",
"=",
"_default_len_out",
")",
":",
"n",
"=",
"ctypes",
".",
"c_int",
"(",
"n",
")",
"lenout",
"=",
"ctypes",
".",
"c_int",
"(",
"lenout",
")",
"table",
"=",
"stypes",
".",
"stringToCharP",
"(",
"lenout",
")",... | 27.888889 | 13.666667 |
def _validate_request(endpoint, file_type='json', data=None, params=None):
"""
Validate request before calling API
:param endpoint: API endpoint
:param file_type: file type requested
:param data: payload
:param params: HTTP parameters
"""
if not isinstance... | [
"def",
"_validate_request",
"(",
"endpoint",
",",
"file_type",
"=",
"'json'",
",",
"data",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"endpoint",
",",
"string_types",
")",
"or",
"endpoint",
".",
"strip",
"(",
")",
... | 59.947368 | 27.105263 |
def graph_from_file(filename, bidirectional=False, simplify=True,
retain_all=False, name='unnamed'):
"""
Create a networkx graph from OSM data in an XML file.
Parameters
----------
filename : string
the name of a file containing OSM XML data
bidirectional : bool
... | [
"def",
"graph_from_file",
"(",
"filename",
",",
"bidirectional",
"=",
"False",
",",
"simplify",
"=",
"True",
",",
"retain_all",
"=",
"False",
",",
"name",
"=",
"'unnamed'",
")",
":",
"# transmogrify file of OSM XML data into JSON",
"response_jsons",
"=",
"[",
"ove... | 32.057143 | 22.342857 |
def validate(self, request):
""" Checks a request for proper authentication details.
Returns a tuple of ``(access_token, error_response_arguments)``, which are
designed to be passed to the :py:meth:`make_error_response` method.
For example, to restrict access to a given endpoint:
.. code-block:: ... | [
"def",
"validate",
"(",
"self",
",",
"request",
")",
":",
"# Ensure that all of the scopes that are being checked against exist.",
"# Otherwise, raise a ValueError.",
"for",
"name",
"in",
"self",
".",
"required_scope_names",
":",
"if",
"not",
"Scope",
".",
"objects",
".",... | 42.214286 | 27.214286 |
def calculate_connvectivity_radius(self, amount_clusters, maximum_iterations = 100):
"""!
@brief Calculates connectivity radius of allocation specified amount of clusters using ordering diagram and marks borders of clusters using indexes of values of ordering diagram.
@details Parameter 'maxi... | [
"def",
"calculate_connvectivity_radius",
"(",
"self",
",",
"amount_clusters",
",",
"maximum_iterations",
"=",
"100",
")",
":",
"maximum_distance",
"=",
"max",
"(",
"self",
".",
"__ordering",
")",
"upper_distance",
"=",
"maximum_distance",
"lower_distance",
"=",
"0.0... | 49.525 | 32.25 |
def Flush(self, state):
"""Finish writing JSON files, upload to cloudstorage and bigquery."""
self.bigquery = bigquery.GetBigQueryClient()
# BigQuery job ids must be alphanum plus dash and underscore.
urn_str = self.source_urn.RelativeName("aff4:/").replace("/", "_").replace(
":", "").replace(".... | [
"def",
"Flush",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"bigquery",
"=",
"bigquery",
".",
"GetBigQueryClient",
"(",
")",
"# BigQuery job ids must be alphanum plus dash and underscore.",
"urn_str",
"=",
"self",
".",
"source_urn",
".",
"RelativeName",
"(",
... | 43.954545 | 19.659091 |
def _arg_varname(self, wire):
"""
Input, Const, and Registers have special input values
"""
if isinstance(wire, (Input, Register)):
return 'd[' + repr(wire.name) + ']' # passed in
elif isinstance(wire, Const):
return str(wire.val) # hardcoded
els... | [
"def",
"_arg_varname",
"(",
"self",
",",
"wire",
")",
":",
"if",
"isinstance",
"(",
"wire",
",",
"(",
"Input",
",",
"Register",
")",
")",
":",
"return",
"'d['",
"+",
"repr",
"(",
"wire",
".",
"name",
")",
"+",
"']'",
"# passed in",
"elif",
"isinstanc... | 35.2 | 9.6 |
def com_google_fonts_check_fontv(ttFont):
""" Check for font-v versioning """
from fontv.libfv import FontVersion
fv = FontVersion(ttFont)
if fv.version and (fv.is_development or fv.is_release):
yield PASS, "Font version string looks GREAT!"
else:
yield INFO, ("Version string is: \"{}\"\n"
... | [
"def",
"com_google_fonts_check_fontv",
"(",
"ttFont",
")",
":",
"from",
"fontv",
".",
"libfv",
"import",
"FontVersion",
"fv",
"=",
"FontVersion",
"(",
"ttFont",
")",
"if",
"fv",
".",
"version",
"and",
"(",
"fv",
".",
"is_development",
"or",
"fv",
".",
"is_... | 43.142857 | 16.785714 |
def get_queryset(self, request):
"""Limit Pages to those that belong to the request's user."""
qs = super(VISADeviceAdmin, self).get_queryset(request)
return qs.filter(protocol_id=PROTOCOL_ID) | [
"def",
"get_queryset",
"(",
"self",
",",
"request",
")",
":",
"qs",
"=",
"super",
"(",
"VISADeviceAdmin",
",",
"self",
")",
".",
"get_queryset",
"(",
"request",
")",
"return",
"qs",
".",
"filter",
"(",
"protocol_id",
"=",
"PROTOCOL_ID",
")"
] | 53.25 | 10 |
def client_for_path(self, path):
"""
Returns a new client with the same root URL and authentication, but
a different specific URL. For instance, if you have a client pointed
at https://analytics.luminoso.com/api/v5/, and you want new ones for
Project A and Project B, you would c... | [
"def",
"client_for_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"url",
"=",
"self",
".",
"root_url",
"+",
"path",
"else",
":",
"url",
"=",
"self",
".",
"url",
"+",
"path",
"return",
"self",
".",
... | 40.8 | 20.9 |
def main():
"Main program"
generators = check_dependencies()
args = docopt(__doc__, version='md2ebook 0.0.1-dev')
commander = Commander(args, generators)
commander.handle() | [
"def",
"main",
"(",
")",
":",
"generators",
"=",
"check_dependencies",
"(",
")",
"args",
"=",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"'md2ebook 0.0.1-dev'",
")",
"commander",
"=",
"Commander",
"(",
"args",
",",
"generators",
")",
"commander",
".",
... | 31.166667 | 15.166667 |
def arg(*args, **kwargs):
"""
Dcorates a function or a class method to add to the argument parser
"""
def decorate(func):
"""
Decorate
"""
# we'll set the command name with the passed cmd_name argument, if
# exist, else the command name will be the function name
... | [
"def",
"arg",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorate",
"(",
"func",
")",
":",
"\"\"\"\n Decorate\n \"\"\"",
"# we'll set the command name with the passed cmd_name argument, if",
"# exist, else the command name will be the function na... | 44.727273 | 15.045455 |
def send(self, sender: PytgbotApiBot):
"""
Send the message via pytgbot.
:param sender: The bot instance to send with.
:type sender: pytgbot.bot.Bot
:rtype: PytgbotApiMessage
"""
return sender.send_chat_action(
# receiver, self.media, disable_notifi... | [
"def",
"send",
"(",
"self",
",",
"sender",
":",
"PytgbotApiBot",
")",
":",
"return",
"sender",
".",
"send_chat_action",
"(",
"# receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id",
"action",
"=",
"self",
".",
"action",
",",
... | 33.384615 | 17.230769 |
def list_work_units(self, work_spec_name, start=0, limit=None):
"""Get a dictionary of work units for some work spec.
The dictionary is from work unit name to work unit definiton.
Only work units that have not been completed ("available" or
"pending" work units) are included.
"... | [
"def",
"list_work_units",
"(",
"self",
",",
"work_spec_name",
",",
"start",
"=",
"0",
",",
"limit",
"=",
"None",
")",
":",
"return",
"self",
".",
"registry",
".",
"filter",
"(",
"WORK_UNITS_",
"+",
"work_spec_name",
",",
"start",
"=",
"start",
",",
"limi... | 44.1 | 20.9 |
def send_command_response(self,
source: list,
command: str,
*args,
**kwargs):
"""
Used in bot observer `on_next` method
"""
args = _json.dumps(args).encode('utf8')
... | [
"def",
"send_command_response",
"(",
"self",
",",
"source",
":",
"list",
",",
"command",
":",
"str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"_json",
".",
"dumps",
"(",
"args",
")",
".",
"encode",
"(",
"'utf8'",
")",
"kwar... | 39.666667 | 11.444444 |
def _make_continuation_prompt(self, prompt):
""" Given a plain text version of an In prompt, returns an HTML
continuation prompt.
"""
end_chars = '...: '
space_count = len(prompt.lstrip('\n')) - len(end_chars)
body = ' ' * space_count + end_chars
return '... | [
"def",
"_make_continuation_prompt",
"(",
"self",
",",
"prompt",
")",
":",
"end_chars",
"=",
"'...: '",
"space_count",
"=",
"len",
"(",
"prompt",
".",
"lstrip",
"(",
"'\\n'",
")",
")",
"-",
"len",
"(",
"end_chars",
")",
"body",
"=",
"' '",
"*",
"spac... | 44.25 | 9.25 |
def show_code_completion(self):
"""Display a completion list based on the current line"""
# Note: unicode conversion is needed only for ExternalShellBase
text = to_text_string(self.get_current_line_to_cursor())
last_obj = self.get_last_obj()
if not text:
return
... | [
"def",
"show_code_completion",
"(",
"self",
")",
":",
"# Note: unicode conversion is needed only for ExternalShellBase\r",
"text",
"=",
"to_text_string",
"(",
"self",
".",
"get_current_line_to_cursor",
"(",
")",
")",
"last_obj",
"=",
"self",
".",
"get_last_obj",
"(",
")... | 40.145833 | 16.270833 |
def port_profile_vlan_profile_switchport_trunk_trunk_vlan_classification_allowed_vlan_add_trunk_ctag_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile")
... | [
"def",
"port_profile_vlan_profile_switchport_trunk_trunk_vlan_classification_allowed_vlan_add_trunk_ctag_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"port_profile",
"=",
"ET",
".",
"SubElement",
"(",
... | 54.666667 | 21.47619 |
def summary(self) -> str:
"""
Condensed report summary created from translations
"""
if not self.translations:
self.update()
return summary.metar(self.translations) | [
"def",
"summary",
"(",
"self",
")",
"->",
"str",
":",
"if",
"not",
"self",
".",
"translations",
":",
"self",
".",
"update",
"(",
")",
"return",
"summary",
".",
"metar",
"(",
"self",
".",
"translations",
")"
] | 30 | 8.857143 |
def send(self):
""" Send all outstanding requests.
"""
from neobolt.exceptions import ConnectionExpired
if self._connection:
try:
self._connection.send()
except ConnectionExpired as error:
raise SessionExpired(*error.args) | [
"def",
"send",
"(",
"self",
")",
":",
"from",
"neobolt",
".",
"exceptions",
"import",
"ConnectionExpired",
"if",
"self",
".",
"_connection",
":",
"try",
":",
"self",
".",
"_connection",
".",
"send",
"(",
")",
"except",
"ConnectionExpired",
"as",
"error",
"... | 33.555556 | 10.333333 |
def nearpt(positn, a, b, c):
"""
locates the point on the surface of an ellipsoid that is nearest to a
specified position. It also returns the altitude of the
position above the ellipsoid.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/nearpt_c.html
:param positn: Position of a point ... | [
"def",
"nearpt",
"(",
"positn",
",",
"a",
",",
"b",
",",
"c",
")",
":",
"positn",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"positn",
")",
"a",
"=",
"ctypes",
".",
"c_double",
"(",
"a",
")",
"b",
"=",
"ctypes",
".",
"c_double",
"(",
"b",
")",
... | 35.551724 | 16.517241 |
def definition(self, name):
"""
Get the definition for the property I{name}.
@param name: The property I{name} to find the definition for.
@type name: str
@return: The property definition
@rtype: L{Definition}
@raise AttributeError: On not found.
"""
... | [
"def",
"definition",
"(",
"self",
",",
"name",
")",
":",
"d",
"=",
"self",
".",
"definitions",
".",
"get",
"(",
"name",
")",
"if",
"d",
"is",
"None",
":",
"raise",
"AttributeError",
"(",
"name",
")",
"return",
"d"
] | 32.230769 | 10.230769 |
def add_and_get(self, delta):
'''
Atomically adds `delta` to the current value.
:param delta: The delta to add.
'''
with self._lock.exclusive:
self._value += delta
return self._value | [
"def",
"add_and_get",
"(",
"self",
",",
"delta",
")",
":",
"with",
"self",
".",
"_lock",
".",
"exclusive",
":",
"self",
".",
"_value",
"+=",
"delta",
"return",
"self",
".",
"_value"
] | 26.555556 | 16.333333 |
def parse_locals_keylist(locals_, key_list, strlist_=None, prefix=''):
""" For each key in keylist, puts its value in locals into a stringlist
Args:
locals_ (?):
key_list (list):
strlist_ (list): (default = None)
prefix (unicode): (default = u'')
Returns:
list: strl... | [
"def",
"parse_locals_keylist",
"(",
"locals_",
",",
"key_list",
",",
"strlist_",
"=",
"None",
",",
"prefix",
"=",
"''",
")",
":",
"from",
"utool",
"import",
"util_str",
"if",
"strlist_",
"is",
"None",
":",
"strlist_",
"=",
"[",
"]",
"for",
"key",
"in",
... | 41.134328 | 22.597015 |
def post_content(url, headers={}, post_data={}, decoded=True, **kwargs):
"""Post the content of a URL via sending a HTTP POST request.
Args:
url: A URL.
headers: Request headers used by the client.
decoded: Whether decode the response body using UTF-8 or the charset specified in Content... | [
"def",
"post_content",
"(",
"url",
",",
"headers",
"=",
"{",
"}",
",",
"post_data",
"=",
"{",
"}",
",",
"decoded",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"'post_data_raw'",
")",
":",
"logging",
".",
"debug"... | 33.777778 | 21.288889 |
def fnmatches(fname, patterns, matchfun):
""""
matches?
:param fname: file name
:type fname: str
:param patterns: list of filename pattern. see fnmatch.fnamtch
:type patterns: [str]
:rtype: generator of bool
"""
import fnmatch
matchfun = matchfun or fnmatch.fnmatch
for p in p... | [
"def",
"fnmatches",
"(",
"fname",
",",
"patterns",
",",
"matchfun",
")",
":",
"import",
"fnmatch",
"matchfun",
"=",
"matchfun",
"or",
"fnmatch",
".",
"fnmatch",
"for",
"p",
"in",
"patterns",
":",
"yield",
"matchfun",
"(",
"fname",
",",
"p",
")"
] | 26.846154 | 12.615385 |
def add_root_bin(self, bin_id):
"""Adds a root bin.
arg: bin_id (osid.id.Id): the ``Id`` of a bin
raise: AlreadyExists - ``bin_id`` is already in hierarchy
raise: NotFound - ``bin_id`` not found
raise: NullArgument - ``bin_id`` is ``null``
raise: OperationFailed -... | [
"def",
"add_root_bin",
"(",
"self",
",",
"bin_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchyDesignSession.add_root_bin_template",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_session",
"... | 44.941176 | 18 |
def validate(**kwargs):
"""Defines a decorator to register a validator with a name for look-up.
If name is not provided we use function name as name of the validator.
"""
def decorator(func):
_VALIDATORS[kwargs.pop('name', func.__name__)] = func
return func
return decorator | [
"def",
"validate",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"_VALIDATORS",
"[",
"kwargs",
".",
"pop",
"(",
"'name'",
",",
"func",
".",
"__name__",
")",
"]",
"=",
"func",
"return",
"func",
"return",
"decorator"
] | 30.3 | 20.9 |
def _doRequest(self, request=None, is_file=False, file_xml_uri=''):
"""This function will perform the specified request on the FileMaker
server, and it will return the raw result from FileMaker."""
if request is None:
request = []
if is_file and file_xml_uri:
url = self._buildFileUrl(file_xml_uri)
else... | [
"def",
"_doRequest",
"(",
"self",
",",
"request",
"=",
"None",
",",
"is_file",
"=",
"False",
",",
"file_xml_uri",
"=",
"''",
")",
":",
"if",
"request",
"is",
"None",
":",
"request",
"=",
"[",
"]",
"if",
"is_file",
"and",
"file_xml_uri",
":",
"url",
"... | 25.681818 | 19.772727 |
def parse_content(self, content):
"""
All child classes inherit this function to parse XML file automatically.
It will call the function :func:`parse_dom` by default to
parser all necessary data to :attr:`data` and the :attr:`xmlns` (the
default namespace) is ready for this funct... | [
"def",
"parse_content",
"(",
"self",
",",
"content",
")",
":",
"self",
".",
"dom",
"=",
"self",
".",
"xmlns",
"=",
"None",
"self",
".",
"data",
"=",
"{",
"}",
"# ignore empty xml file",
"if",
"len",
"(",
"content",
")",
">",
"3",
":",
"self",
".",
... | 46 | 16.533333 |
def upsert(self, table: str, record: dict, create_cols: bool=False,
dtypes: list=None, pks=["id"], namefields=["id"]):
"""
Upsert a record in a table
"""
try:
self.db[table].upsert(record, pks, create_cols, dtypes)
except Exception as e:
sel... | [
"def",
"upsert",
"(",
"self",
",",
"table",
":",
"str",
",",
"record",
":",
"dict",
",",
"create_cols",
":",
"bool",
"=",
"False",
",",
"dtypes",
":",
"list",
"=",
"None",
",",
"pks",
"=",
"[",
"\"id\"",
"]",
",",
"namefields",
"=",
"[",
"\"id\"",
... | 34.642857 | 13.357143 |
def filter(self, *args, **kwargs):
"""
Returns a new TaskQuerySet with the given filters added.
"""
clone = self._clone()
for f in args:
clone.filter_obj.add_filter(f)
for key, value in kwargs.items():
clone.filter_obj.add_filter_param(key, value)
... | [
"def",
"filter",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"for",
"f",
"in",
"args",
":",
"clone",
".",
"filter_obj",
".",
"add_filter",
"(",
"f",
")",
"for",
"key",
",",
"v... | 33.1 | 9.9 |
def find_in_coord_list(coord_list, coord, atol=1e-8):
"""
Find the indices of matches of a particular coord in a coord_list.
Args:
coord_list: List of coords to test
coord: Specific coordinates
atol: Absolute tolerance. Defaults to 1e-8. Accepts both scalar and
array.
... | [
"def",
"find_in_coord_list",
"(",
"coord_list",
",",
"coord",
",",
"atol",
"=",
"1e-8",
")",
":",
"if",
"len",
"(",
"coord_list",
")",
"==",
"0",
":",
"return",
"[",
"]",
"diff",
"=",
"np",
".",
"array",
"(",
"coord_list",
")",
"-",
"np",
".",
"arr... | 33.058824 | 20.588235 |
def get_output_list_from_task(task, placeholder_dict):
"""
Purpose: Parse a Task object to extract the files to be staged as the output.
Details: The extracted data is then converted into the appropriate RP directive depending on whether the data
is to be copied/downloaded.
:arguments:
:ta... | [
"def",
"get_output_list_from_task",
"(",
"task",
",",
"placeholder_dict",
")",
":",
"try",
":",
"if",
"not",
"isinstance",
"(",
"task",
",",
"Task",
")",
":",
"raise",
"TypeError",
"(",
"expected_type",
"=",
"Task",
",",
"actual_type",
"=",
"type",
"(",
"t... | 30.922222 | 23.855556 |
def add_field(self, model, field):
"""Ran when a field is added to a model."""
for key in self._iterate_required_keys(field):
self._create_hstore_required(
model._meta.db_table,
field,
key
) | [
"def",
"add_field",
"(",
"self",
",",
"model",
",",
"field",
")",
":",
"for",
"key",
"in",
"self",
".",
"_iterate_required_keys",
"(",
"field",
")",
":",
"self",
".",
"_create_hstore_required",
"(",
"model",
".",
"_meta",
".",
"db_table",
",",
"field",
"... | 30.111111 | 14.444444 |
def construct(self, request, service=None, http_args=None, **kwargs):
"""
Constructs a client assertion and signs it with a key.
The request is modified as a side effect.
:param request: The request
:param service: A :py:class:`oidcservice.service.Service` instance
:para... | [
"def",
"construct",
"(",
"self",
",",
"request",
",",
"service",
"=",
"None",
",",
"http_args",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'client_assertion'",
"in",
"kwargs",
":",
"request",
"[",
"\"client_assertion\"",
"]",
"=",
"kwargs",
"... | 38.542169 | 19.795181 |
def columns(self, *args) -> List[List[Well]]:
"""
Accessor function used to navigate through a labware by column.
With indexing one can treat it as a typical python nested list.
To access row A for example,
simply write: labware.columns()[0]
This will output ['A1', 'B1',... | [
"def",
"columns",
"(",
"self",
",",
"*",
"args",
")",
"->",
"List",
"[",
"List",
"[",
"Well",
"]",
"]",
":",
"col_dict",
"=",
"self",
".",
"_create_indexed_dictionary",
"(",
"group",
"=",
"2",
")",
"keys",
"=",
"sorted",
"(",
"col_dict",
",",
"key",
... | 39.068966 | 18.37931 |
def transport_param(image):
""" Parse DockerImage info into skopeo parameter
:param image: DockerImage
:return: string. skopeo parameter specifying image
"""
transports = {SkopeoTransport.CONTAINERS_STORAGE: "containers-storage:",
SkopeoTransport.DIRECTORY: "dir:",
... | [
"def",
"transport_param",
"(",
"image",
")",
":",
"transports",
"=",
"{",
"SkopeoTransport",
".",
"CONTAINERS_STORAGE",
":",
"\"containers-storage:\"",
",",
"SkopeoTransport",
".",
"DIRECTORY",
":",
"\"dir:\"",
",",
"SkopeoTransport",
".",
"DOCKER",
":",
"\"docker:/... | 39.395349 | 19.418605 |
def partsphere(self, x):
"""Sphere (squared norm) test objective function"""
self.counter += 1
# return np.random.rand(1)[0]**0 * sum(x**2) + 1 * np.random.rand(1)[0]
dim = len(x)
x = array([x[i % dim] for i in xrange(2 * dim)])
N = 8
i = self.counter % dim
... | [
"def",
"partsphere",
"(",
"self",
",",
"x",
")",
":",
"self",
".",
"counter",
"+=",
"1",
"# return np.random.rand(1)[0]**0 * sum(x**2) + 1 * np.random.rand(1)[0]",
"dim",
"=",
"len",
"(",
"x",
")",
"x",
"=",
"array",
"(",
"[",
"x",
"[",
"i",
"%",
"dim",
"]... | 37 | 17.090909 |
def gen_gradient(self, skip=0, step=1, vskip=0, vstep=1):
"""Generate gradient measurements
Parameters
----------
skip: int
distance between current electrodes
step: int
steplength between subsequent current dipoles
vskip: int
distance... | [
"def",
"gen_gradient",
"(",
"self",
",",
"skip",
"=",
"0",
",",
"step",
"=",
"1",
",",
"vskip",
"=",
"0",
",",
"vstep",
"=",
"1",
")",
":",
"N",
"=",
"self",
".",
"nr_electrodes",
"quadpoles",
"=",
"[",
"]",
"for",
"a",
"in",
"range",
"(",
"1",... | 28.517241 | 16.655172 |
def refresh(self):
"""Refresh tabwidget."""
if self.tabwidget.count():
editor = self.tabwidget.currentWidget()
else:
editor = None
self.find_widget.set_editor(editor) | [
"def",
"refresh",
"(",
"self",
")",
":",
"if",
"self",
".",
"tabwidget",
".",
"count",
"(",
")",
":",
"editor",
"=",
"self",
".",
"tabwidget",
".",
"currentWidget",
"(",
")",
"else",
":",
"editor",
"=",
"None",
"self",
".",
"find_widget",
".",
"set_e... | 30.857143 | 12 |
def make_directory(self, directory_name, *args, **kwargs):
""" :meth:`.WNetworkClientProto.make_directory` method implementation
"""
self.dav_client().mkdir(self.join_path(self.session_path(), directory_name)) | [
"def",
"make_directory",
"(",
"self",
",",
"directory_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"dav_client",
"(",
")",
".",
"mkdir",
"(",
"self",
".",
"join_path",
"(",
"self",
".",
"session_path",
"(",
")",
",",
"dire... | 53 | 14 |
def process_existing_ids(self, entity: List[dict]) -> List[dict]:
""" Making sure key/value is in proper format for existing_ids in entity """
label = entity['label']
existing_ids = entity['existing_ids']
for existing_id in existing_ids:
if 'curie' not in existing_id or 'iri'... | [
"def",
"process_existing_ids",
"(",
"self",
",",
"entity",
":",
"List",
"[",
"dict",
"]",
")",
"->",
"List",
"[",
"dict",
"]",
":",
"label",
"=",
"entity",
"[",
"'label'",
"]",
"existing_ids",
"=",
"entity",
"[",
"'existing_ids'",
"]",
"for",
"existing_i... | 52.083333 | 15.75 |
def highest_expr_genes(
adata, n_top=30, show=None, save=None,
ax=None, gene_symbols=None, **kwds
):
"""\
Fraction of counts assigned to each gene over all cells.
Computes, for each gene, the fraction of counts assigned to that gene within
a cell. The `n_top` genes with the highest ... | [
"def",
"highest_expr_genes",
"(",
"adata",
",",
"n_top",
"=",
"30",
",",
"show",
"=",
"None",
",",
"save",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"gene_symbols",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"from",
"scipy",
".",
"sparse",
"impo... | 39.6875 | 23.515625 |
def from_timestamp(timestamp: TimestampPrimitive) -> ulid.ULID:
"""
Create a new :class:`~ulid.ulid.ULID` instance using a timestamp value of a supported type.
The following types are supported for timestamp values:
* :class:`~datetime.datetime`
* :class:`~int`
* :class:`~float`
* :class:`... | [
"def",
"from_timestamp",
"(",
"timestamp",
":",
"TimestampPrimitive",
")",
"->",
"ulid",
".",
"ULID",
":",
"if",
"isinstance",
"(",
"timestamp",
",",
"datetime",
".",
"datetime",
")",
":",
"timestamp",
"=",
"timestamp",
".",
"timestamp",
"(",
")",
"if",
"i... | 39.425532 | 19.042553 |
def CrearLiquidacion(self, nro_orden=None, cuit_comprador=None,
nro_act_comprador=None, nro_ing_bruto_comprador=None,
cod_tipo_operacion=None,
es_liquidacion_propia=None, es_canje=None,
cod_puerto=None, des_puerto_localidad=None, cod_grano=None,
... | [
"def",
"CrearLiquidacion",
"(",
"self",
",",
"nro_orden",
"=",
"None",
",",
"cuit_comprador",
"=",
"None",
",",
"nro_act_comprador",
"=",
"None",
",",
"nro_ing_bruto_comprador",
"=",
"None",
",",
"cod_tipo_operacion",
"=",
"None",
",",
"es_liquidacion_propia",
"="... | 51.682692 | 21.028846 |
def part(self, target, reason=None):
"""quit a channel"""
if reason:
target += ' :' + reason
self.send_line('PART %s' % target) | [
"def",
"part",
"(",
"self",
",",
"target",
",",
"reason",
"=",
"None",
")",
":",
"if",
"reason",
":",
"target",
"+=",
"' :'",
"+",
"reason",
"self",
".",
"send_line",
"(",
"'PART %s'",
"%",
"target",
")"
] | 31.8 | 6.6 |
def get_edge_string(self, i):
"""Return a string based on the bond order"""
order = self.orders[i]
if order == 0:
return Graph.get_edge_string(self, i)
else:
# pad with zeros to make sure that string sort is identical to number sort
return "%03i" % ord... | [
"def",
"get_edge_string",
"(",
"self",
",",
"i",
")",
":",
"order",
"=",
"self",
".",
"orders",
"[",
"i",
"]",
"if",
"order",
"==",
"0",
":",
"return",
"Graph",
".",
"get_edge_string",
"(",
"self",
",",
"i",
")",
"else",
":",
"# pad with zeros to make ... | 39.375 | 16 |
def chown(self, path, owner, group, recursive=False):
"""
Use snakebite.chown/chgrp, if available.
One of owner or group must be set. Just setting group calls chgrp.
:param path: update-able file(s)
:type path: either a string or sequence of strings
:param owner: new ow... | [
"def",
"chown",
"(",
"self",
",",
"path",
",",
"owner",
",",
"group",
",",
"recursive",
"=",
"False",
")",
":",
"bite",
"=",
"self",
".",
"get_bite",
"(",
")",
"if",
"owner",
":",
"if",
"group",
":",
"return",
"all",
"(",
"bite",
".",
"chown",
"(... | 42.565217 | 18.826087 |
def get_port_def(port_num, proto='tcp'):
'''
Given a port number and protocol, returns the port definition expected by
docker-py. For TCP ports this is simply an integer, for UDP ports this is
(port_num, 'udp').
port_num can also be a string in the format 'port_num/udp'. If so, the
"proto" argu... | [
"def",
"get_port_def",
"(",
"port_num",
",",
"proto",
"=",
"'tcp'",
")",
":",
"try",
":",
"port_num",
",",
"_",
",",
"port_num_proto",
"=",
"port_num",
".",
"partition",
"(",
"'/'",
")",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"if",
"port_n... | 43.235294 | 26.823529 |
def canonical_text(self, text):
"""Standardize an input TeX-file contents.
Currently:
* removes comments, unwrapping comment-wrapped lines.
"""
out = []
line_continues_a_comment = False
for line in text.splitlines():
line,comment = self.comment_re.f... | [
"def",
"canonical_text",
"(",
"self",
",",
"text",
")",
":",
"out",
"=",
"[",
"]",
"line_continues_a_comment",
"=",
"False",
"for",
"line",
"in",
"text",
".",
"splitlines",
"(",
")",
":",
"line",
",",
"comment",
"=",
"self",
".",
"comment_re",
".",
"fi... | 35.625 | 12.8125 |
def valid_hotp(
token,
secret,
last=1,
trials=1000,
digest_method=hashlib.sha1,
token_length=6,
):
"""Check if given token is valid for given secret. Return interval number
that was successful, or False if not found.
:param token: token being checked
:typ... | [
"def",
"valid_hotp",
"(",
"token",
",",
"secret",
",",
"last",
"=",
"1",
",",
"trials",
"=",
"1000",
",",
"digest_method",
"=",
"hashlib",
".",
"sha1",
",",
"token_length",
"=",
"6",
",",
")",
":",
"if",
"not",
"_is_possible_token",
"(",
"token",
",",
... | 31.826087 | 17.956522 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.