text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def htmlNodeDumpOutput(self, buf, cur, encoding):
"""Dump an HTML node, recursive behaviour,children are printed
too, and formatting returns/spaces are added. """
if buf is None: buf__o = None
else: buf__o = buf._o
if cur is None: cur__o = None
else: cur__o = cur._o
... | [
"def",
"htmlNodeDumpOutput",
"(",
"self",
",",
"buf",
",",
"cur",
",",
"encoding",
")",
":",
"if",
"buf",
"is",
"None",
":",
"buf__o",
"=",
"None",
"else",
":",
"buf__o",
"=",
"buf",
".",
"_o",
"if",
"cur",
"is",
"None",
":",
"cur__o",
"=",
"None",... | 47.875 | 8.625 |
def plot(args):
"""
%prog plot workdir sample chr1,chr2
Plot some chromosomes for visual proof. Separate multiple chromosomes with
comma. Must contain folder workdir/sample-cn/.
"""
from jcvi.graphics.base import savefig
p = OptionParser(plot.__doc__)
opts, args, iopts = p.set_image_op... | [
"def",
"plot",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"graphics",
".",
"base",
"import",
"savefig",
"p",
"=",
"OptionParser",
"(",
"plot",
".",
"__doc__",
")",
"opts",
",",
"args",
",",
"iopts",
"=",
"p",
".",
"set_image_options",
"(",
"args",
"... | 29.409091 | 17.590909 |
def update_reminder(self, reminder_id, reminder_dict):
"""
Updates a reminder
:param reminder_id: the reminder id
:param reminder_dict: dict
:return: dict
"""
return self._create_put_request(
resource=REMINDERS,
billomat_id=reminder_id,
... | [
"def",
"update_reminder",
"(",
"self",
",",
"reminder_id",
",",
"reminder_dict",
")",
":",
"return",
"self",
".",
"_create_put_request",
"(",
"resource",
"=",
"REMINDERS",
",",
"billomat_id",
"=",
"reminder_id",
",",
"send_data",
"=",
"reminder_dict",
")"
] | 27 | 11.153846 |
def votes(ctx, account, type):
""" List accounts vesting balances
"""
if not isinstance(type, (list, tuple)):
type = [type]
account = Account(account, full=True)
ret = {key: list() for key in Vote.types()}
for vote in account["votes"]:
t = Vote.vote_type_from_id(vote["id"])
... | [
"def",
"votes",
"(",
"ctx",
",",
"account",
",",
"type",
")",
":",
"if",
"not",
"isinstance",
"(",
"type",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"type",
"=",
"[",
"type",
"]",
"account",
"=",
"Account",
"(",
"account",
",",
"full",
"=",
... | 32.824324 | 18.648649 |
def count(self, model_class, conditions=None):
'''
Counts the number of records in the model's table.
- `model_class`: the model to count.
- `conditions`: optional SQL conditions (contents of the WHERE clause).
'''
query = 'SELECT count() FROM $table'
if conditio... | [
"def",
"count",
"(",
"self",
",",
"model_class",
",",
"conditions",
"=",
"None",
")",
":",
"query",
"=",
"'SELECT count() FROM $table'",
"if",
"conditions",
":",
"query",
"+=",
"' WHERE '",
"+",
"conditions",
"query",
"=",
"self",
".",
"_substitute",
"(",
"q... | 37.076923 | 16.615385 |
def get_session(self, redirect_url):
"""Create Session to store credentials.
Parameters
redirect_url (str)
The full URL that the Uber server redirected to after
the user authorized your app.
Returns
(Session)
A Session obj... | [
"def",
"get_session",
"(",
"self",
",",
"redirect_url",
")",
":",
"query_params",
"=",
"self",
".",
"_extract_query",
"(",
"redirect_url",
")",
"error",
"=",
"query_params",
".",
"get",
"(",
"'error'",
")",
"if",
"error",
":",
"raise",
"UberIllegalState",
"(... | 31.805556 | 17.638889 |
def long2ip(l, rfc1924=False):
"""Convert a network byte order 128-bit integer to a canonical IPv6
address.
>>> long2ip(2130706433)
'::7f00:1'
>>> long2ip(42540766411282592856904266426630537217)
'2001:db8::1:0:0:1'
>>> long2ip(MIN_IP)
'::'
>>> long2ip(MAX_IP)
'ffff:ffff:ffff:ff... | [
"def",
"long2ip",
"(",
"l",
",",
"rfc1924",
"=",
"False",
")",
":",
"if",
"MAX_IP",
"<",
"l",
"or",
"l",
"<",
"MIN_IP",
":",
"raise",
"TypeError",
"(",
"\"expected int between %d and %d inclusive\"",
"%",
"(",
"MIN_IP",
",",
"MAX_IP",
")",
")",
"if",
"rf... | 31.178082 | 17.972603 |
def buglist(self, from_date=DEFAULT_DATETIME):
"""Get a summary of bugs in CSV format.
:param from_date: retrieve bugs that where updated from that date
"""
if not self.version:
self.version = self.__fetch_version()
if self.version in self.OLD_STYLE_VERSIONS:
... | [
"def",
"buglist",
"(",
"self",
",",
"from_date",
"=",
"DEFAULT_DATETIME",
")",
":",
"if",
"not",
"self",
".",
"version",
":",
"self",
".",
"version",
"=",
"self",
".",
"__fetch_version",
"(",
")",
"if",
"self",
".",
"version",
"in",
"self",
".",
"OLD_S... | 27.72 | 18.6 |
def ensure_ceph_keyring(service, user=None, group=None,
relation='ceph', key=None):
"""Ensures a ceph keyring is created for a named service and optionally
ensures user and group ownership.
@returns boolean: Flag to indicate whether a key was successfully written
... | [
"def",
"ensure_ceph_keyring",
"(",
"service",
",",
"user",
"=",
"None",
",",
"group",
"=",
"None",
",",
"relation",
"=",
"'ceph'",
",",
"key",
"=",
"None",
")",
":",
"if",
"not",
"key",
":",
"for",
"rid",
"in",
"relation_ids",
"(",
"relation",
")",
"... | 33.166667 | 19.333333 |
def set_triggered_by_event(self, value):
"""
Setter for 'triggered_by_event' field.
:param value - a new value of 'triggered_by_event' field. Must be a boolean type. Does not accept None value.
"""
if value is None or not isinstance(value, bool):
raise TypeError("Trig... | [
"def",
"set_triggered_by_event",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"TriggeredByEvent must be set to a bool\"",
")",
"else",
":",
"self"... | 45.333333 | 17.777778 |
def modification_time(self):
"""dfdatetime.DateTimeValues: modification time or None if not available."""
timestamp = self._fsntfs_file_entry.get_modification_time_as_integer()
return dfdatetime_filetime.Filetime(timestamp=timestamp) | [
"def",
"modification_time",
"(",
"self",
")",
":",
"timestamp",
"=",
"self",
".",
"_fsntfs_file_entry",
".",
"get_modification_time_as_integer",
"(",
")",
"return",
"dfdatetime_filetime",
".",
"Filetime",
"(",
"timestamp",
"=",
"timestamp",
")"
] | 60.5 | 16.5 |
def ci(python="python", codecov="codecov", coverage_file="coverage.xml", wheel=True):
"""
Run the most common CI tasks
"""
# Import pip
from pip import __version__ as pip_version
if Version(pip_version) >= Version("10.0.0"):
import pip._internal as pip
else:
import pip
... | [
"def",
"ci",
"(",
"python",
"=",
"\"python\"",
",",
"codecov",
"=",
"\"codecov\"",
",",
"coverage_file",
"=",
"\"coverage.xml\"",
",",
"wheel",
"=",
"True",
")",
":",
"# Import pip",
"from",
"pip",
"import",
"__version__",
"as",
"pip_version",
"if",
"Version",... | 32.69697 | 17.060606 |
def _find_indices(self, x):
"""Find indices and distances of the given nodes.
Can be overridden by subclasses to improve efficiency.
"""
# find relevant edges between which xi are situated
index_vecs = []
# compute distance to lower edge in unity units
norm_dista... | [
"def",
"_find_indices",
"(",
"self",
",",
"x",
")",
":",
"# find relevant edges between which xi are situated",
"index_vecs",
"=",
"[",
"]",
"# compute distance to lower edge in unity units",
"norm_distances",
"=",
"[",
"]",
"# iterate through dimensions",
"for",
"xi",
",",... | 33.181818 | 17.545455 |
def scoped(cls, optionable, removal_version=None, removal_hint=None):
"""Returns a dependency on this subsystem, scoped to `optionable`.
:param removal_version: An optional deprecation version for this scoped Subsystem dependency.
:param removal_hint: An optional hint to accompany a deprecation removal_ver... | [
"def",
"scoped",
"(",
"cls",
",",
"optionable",
",",
"removal_version",
"=",
"None",
",",
"removal_hint",
"=",
"None",
")",
":",
"return",
"SubsystemDependency",
"(",
"cls",
",",
"optionable",
".",
"options_scope",
",",
"removal_version",
",",
"removal_hint",
... | 56.222222 | 34.333333 |
def norm(field, vmin=0, vmax=255):
"""Truncates field to 0,1; then normalizes to a uin8 on [0,255]"""
field = 255*np.clip(field, 0, 1)
field = field.astype('uint8')
return field | [
"def",
"norm",
"(",
"field",
",",
"vmin",
"=",
"0",
",",
"vmax",
"=",
"255",
")",
":",
"field",
"=",
"255",
"*",
"np",
".",
"clip",
"(",
"field",
",",
"0",
",",
"1",
")",
"field",
"=",
"field",
".",
"astype",
"(",
"'uint8'",
")",
"return",
"f... | 37.8 | 8.2 |
async def series(self):
'''list of series in the collection
|force|
|coro|
Returns
-------
list
of type :class:`embypy.objects.Series`
'''
items = []
for i in await self.items:
if i.type == 'Series':
items.append(i)
elif hasattr(i, 'series'):
item... | [
"async",
"def",
"series",
"(",
"self",
")",
":",
"items",
"=",
"[",
"]",
"for",
"i",
"in",
"await",
"self",
".",
"items",
":",
"if",
"i",
".",
"type",
"==",
"'Series'",
":",
"items",
".",
"append",
"(",
"i",
")",
"elif",
"hasattr",
"(",
"i",
",... | 18.052632 | 22.368421 |
def _safe_output(line):
'''
Looks for rabbitmqctl warning, or general formatting, strings that aren't
intended to be parsed as output.
Returns a boolean whether the line can be parsed as rabbitmqctl output.
'''
return not any([
line.startswith('Listing') and line.endswith('...'),
... | [
"def",
"_safe_output",
"(",
"line",
")",
":",
"return",
"not",
"any",
"(",
"[",
"line",
".",
"startswith",
"(",
"'Listing'",
")",
"and",
"line",
".",
"endswith",
"(",
"'...'",
")",
",",
"line",
".",
"startswith",
"(",
"'Listing'",
")",
"and",
"'\\t'",
... | 35.666667 | 22.333333 |
def _backup_pb_gui(self, dirs):
"""Create a zip backup with a GUI progress bar."""
import PySimpleGUI as sg
# Legacy support
with ZipFile(self.zip_filename, 'w') as backup_zip:
for count, path in enumerate(dirs):
backup_zip.write(path, path[len(self.source):le... | [
"def",
"_backup_pb_gui",
"(",
"self",
",",
"dirs",
")",
":",
"import",
"PySimpleGUI",
"as",
"sg",
"# Legacy support",
"with",
"ZipFile",
"(",
"self",
".",
"zip_filename",
",",
"'w'",
")",
"as",
"backup_zip",
":",
"for",
"count",
",",
"path",
"in",
"enumera... | 50.111111 | 18.777778 |
def _shellcomplete(cli, prog_name, complete_var=None):
"""Internal handler for the bash completion support.
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
complete_var : str
The environ... | [
"def",
"_shellcomplete",
"(",
"cli",
",",
"prog_name",
",",
"complete_var",
"=",
"None",
")",
":",
"if",
"complete_var",
"is",
"None",
":",
"complete_var",
"=",
"'_%s_COMPLETE'",
"%",
"(",
"prog_name",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
")",
".... | 46.943396 | 17.679245 |
def confusion_matrix(links_true, links_pred, total=None):
"""Compute the confusion matrix.
The confusion matrix is of the following form:
+----------------------+-----------------------+----------------------+
| | Predicted Positives | Predicted Negatives |
+===============... | [
"def",
"confusion_matrix",
"(",
"links_true",
",",
"links_pred",
",",
"total",
"=",
"None",
")",
":",
"links_true",
"=",
"_get_multiindex",
"(",
"links_true",
")",
"links_pred",
"=",
"_get_multiindex",
"(",
"links_pred",
")",
"tp",
"=",
"true_positives",
"(",
... | 37.745455 | 25.690909 |
def style_from_dict(style_dict, include_defaults=True):
"""
Create a ``Style`` instance from a dictionary or other mapping.
The dictionary is equivalent to the ``Style.styles`` dictionary from
pygments, with a few additions: it supports 'reverse' and 'blink'.
Usage::
style_from_dict({
... | [
"def",
"style_from_dict",
"(",
"style_dict",
",",
"include_defaults",
"=",
"True",
")",
":",
"assert",
"isinstance",
"(",
"style_dict",
",",
"Mapping",
")",
"if",
"include_defaults",
":",
"s2",
"=",
"{",
"}",
"s2",
".",
"update",
"(",
"DEFAULT_STYLE_EXTENSIONS... | 32.724138 | 17.229885 |
def on_open_output_tool_clicked(self):
"""Autoconnect slot activated when open output tool button is clicked.
"""
output_path = self.output_path.text()
if not output_path:
output_path = os.path.expanduser('~')
# noinspection PyCallByClass,PyTypeChecker
filenam... | [
"def",
"on_open_output_tool_clicked",
"(",
"self",
")",
":",
"output_path",
"=",
"self",
".",
"output_path",
".",
"text",
"(",
")",
"if",
"not",
"output_path",
":",
"output_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"# noinspection Py... | 44.636364 | 10.181818 |
def OnRemoveCards(self, removedcards):
"""Called when a card is removed.
Removes the card from the tree."""
self.mutex.acquire()
try:
parentnode = self.root
for cardtoremove in removedcards:
(childReader, cookie) = self.GetFirstChild(parentnode)
... | [
"def",
"OnRemoveCards",
"(",
"self",
",",
"removedcards",
")",
":",
"self",
".",
"mutex",
".",
"acquire",
"(",
")",
"try",
":",
"parentnode",
"=",
"self",
".",
"root",
"for",
"cardtoremove",
"in",
"removedcards",
":",
"(",
"childReader",
",",
"cookie",
"... | 42.130435 | 13.913043 |
def child_added(self, child):
""" Overwrite the content view """
view = child.widget
if view is not None:
self.dialog.setContentView(view) | [
"def",
"child_added",
"(",
"self",
",",
"child",
")",
":",
"view",
"=",
"child",
".",
"widget",
"if",
"view",
"is",
"not",
"None",
":",
"self",
".",
"dialog",
".",
"setContentView",
"(",
"view",
")"
] | 34 | 8 |
def main(bot):
"""
Entry point for the command line launcher.
:param bot: the IRC bot to run
:type bot: :class:`fatbotslim.irc.bot.IRC`
"""
greenlet = spawn(bot.run)
try:
greenlet.join()
except KeyboardInterrupt:
print '' # cosmetics matters
log.info("Killed by ... | [
"def",
"main",
"(",
"bot",
")",
":",
"greenlet",
"=",
"spawn",
"(",
"bot",
".",
"run",
")",
"try",
":",
"greenlet",
".",
"join",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"print",
"''",
"# cosmetics matters",
"log",
".",
"info",
"(",
"\"Killed by use... | 24.4375 | 14.4375 |
def select_entry(self, core_element_id, by_cursor=True):
"""Selects the row entry belonging to the given core_element_id by cursor or tree selection"""
for row_num, element_row in enumerate(self.list_store):
# Compare data port ids
if element_row[self.ID_STORAGE_ID] == core_eleme... | [
"def",
"select_entry",
"(",
"self",
",",
"core_element_id",
",",
"by_cursor",
"=",
"True",
")",
":",
"for",
"row_num",
",",
"element_row",
"in",
"enumerate",
"(",
"self",
".",
"list_store",
")",
":",
"# Compare data port ids",
"if",
"element_row",
"[",
"self",... | 52.2 | 16.8 |
def create_tfs_core_client(url, token=None):
"""
Create a core_client.py client for a Team Foundation Server Enterprise connection instance
If token is not provided, will attempt to use the TFS_API_TOKEN
environment variable if present.
"""
if token is None:
token = os.environ.get('TFS_... | [
"def",
"create_tfs_core_client",
"(",
"url",
",",
"token",
"=",
"None",
")",
":",
"if",
"token",
"is",
"None",
":",
"token",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'TFS_API_TOKEN'",
",",
"None",
")",
"tfs_connection",
"=",
"create_tfs_connection",
"(... | 34.777778 | 22.888889 |
def get(self, *keys: str, default: Any = NOT_SET) -> Any:
""" Returns values from the settings in the order of keys, the first value encountered is used.
Example:
>>> settings = Settings({"ARCA_ONE": 1, "ARCA_TWO": 2})
>>> settings.get("one")
1
>>> settings.get("one", "... | [
"def",
"get",
"(",
"self",
",",
"*",
"keys",
":",
"str",
",",
"default",
":",
"Any",
"=",
"NOT_SET",
")",
"->",
"Any",
":",
"if",
"not",
"len",
"(",
"keys",
")",
":",
"raise",
"ValueError",
"(",
"\"At least one key must be provided.\"",
")",
"for",
"op... | 33.295455 | 23.022727 |
def _check_logged_user(self):
"""Check if a user is logged. Otherwise, an error is raised."""
if not self._env or not self._password or not self._login:
raise error.InternalError("Login required") | [
"def",
"_check_logged_user",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_env",
"or",
"not",
"self",
".",
"_password",
"or",
"not",
"self",
".",
"_login",
":",
"raise",
"error",
".",
"InternalError",
"(",
"\"Login required\"",
")"
] | 55.25 | 13 |
def _force(self,obj,objtype=None):
"""Force a new value to be generated, and return it."""
gen=super(Dynamic,self).__get__(obj,objtype)
if hasattr(gen,'_Dynamic_last'):
return self._produce_value(gen,force=True)
else:
return gen | [
"def",
"_force",
"(",
"self",
",",
"obj",
",",
"objtype",
"=",
"None",
")",
":",
"gen",
"=",
"super",
"(",
"Dynamic",
",",
"self",
")",
".",
"__get__",
"(",
"obj",
",",
"objtype",
")",
"if",
"hasattr",
"(",
"gen",
",",
"'_Dynamic_last'",
")",
":",
... | 34.75 | 14.625 |
def deinit(ctx):
"""
Detach from the current cloud server
"""
utils.check_for_cloud_server()
if config["local_server"]["url"]:
utils.cancel_global_db_replication()
if config["cloud_server"]["username"]:
ctx.invoke(logout_user)
config["cloud_server"]["url"] = None | [
"def",
"deinit",
"(",
"ctx",
")",
":",
"utils",
".",
"check_for_cloud_server",
"(",
")",
"if",
"config",
"[",
"\"local_server\"",
"]",
"[",
"\"url\"",
"]",
":",
"utils",
".",
"cancel_global_db_replication",
"(",
")",
"if",
"config",
"[",
"\"cloud_server\"",
... | 29.8 | 4.8 |
def _hexvalue_to_rgb(hexvalue):
"""
Converts the hexvalue used by tuya for colour representation into
an RGB value.
Args:
hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue()
"""
r = int(hexvalue[0:2], 16)
g = in... | [
"def",
"_hexvalue_to_rgb",
"(",
"hexvalue",
")",
":",
"r",
"=",
"int",
"(",
"hexvalue",
"[",
"0",
":",
"2",
"]",
",",
"16",
")",
"g",
"=",
"int",
"(",
"hexvalue",
"[",
"2",
":",
"4",
"]",
",",
"16",
")",
"b",
"=",
"int",
"(",
"hexvalue",
"[",... | 29.923077 | 19.153846 |
def top3_reduced(votes):
"""
Description:
Top 3 alternatives 16 moment conditions values calculation
Parameters:
votes: ordinal preference data (numpy ndarray of integers)
"""
res = np.zeros(16)
for vote in votes:
# the top ranked alternative is in vote[0][0], second in v... | [
"def",
"top3_reduced",
"(",
"votes",
")",
":",
"res",
"=",
"np",
".",
"zeros",
"(",
"16",
")",
"for",
"vote",
"in",
"votes",
":",
"# the top ranked alternative is in vote[0][0], second in vote[1][0]",
"if",
"vote",
"[",
"0",
"]",
"[",
"0",
"]",
"==",
"0",
... | 31.727273 | 14.181818 |
def do_display(self, arg):
"""
display expression
Add expression to the display list; expressions in this list
are evaluated at each step, and printed every time its value
changes.
WARNING: since the expressions is evaluated multiple time, pay
attention not to p... | [
"def",
"do_display",
"(",
"self",
",",
"arg",
")",
":",
"try",
":",
"value",
"=",
"self",
".",
"_getval_or_undefined",
"(",
"arg",
")",
"except",
":",
"return",
"self",
".",
"_get_display_list",
"(",
")",
"[",
"arg",
"]",
"=",
"value"
] | 30.705882 | 20.705882 |
def real_main():
"""The main program."""
global RTS
global DTR
try:
default_baud = int(os.getenv('RSHELL_BAUD'))
except:
default_baud = 115200
default_port = os.getenv('RSHELL_PORT')
default_rts = os.getenv('RSHELL_RTS') or RTS
default_dtr = os.getenv('RSHELL_DTR') or DTR... | [
"def",
"real_main",
"(",
")",
":",
"global",
"RTS",
"global",
"DTR",
"try",
":",
"default_baud",
"=",
"int",
"(",
"os",
".",
"getenv",
"(",
"'RSHELL_BAUD'",
")",
")",
"except",
":",
"default_baud",
"=",
"115200",
"default_port",
"=",
"os",
".",
"getenv",... | 27.987124 | 19.012876 |
def substitution_set(string, indexes):
"""
for a string, return a set of all possible substitutions
"""
strlen = len(string)
return {mutate_string(string, x) for x in indexes if valid_substitution(strlen, x)} | [
"def",
"substitution_set",
"(",
"string",
",",
"indexes",
")",
":",
"strlen",
"=",
"len",
"(",
"string",
")",
"return",
"{",
"mutate_string",
"(",
"string",
",",
"x",
")",
"for",
"x",
"in",
"indexes",
"if",
"valid_substitution",
"(",
"strlen",
",",
"x",
... | 37.166667 | 14.166667 |
def is_valid_int_param(param):
"""Verifica se o parâmetro é um valor inteiro válido.
:param param: Valor para ser validado.
:return: True se o parâmetro tem um valor inteiro válido, ou False, caso contrário.
"""
if param is None:
return False
try:
param = int(param)
if ... | [
"def",
"is_valid_int_param",
"(",
"param",
")",
":",
"if",
"param",
"is",
"None",
":",
"return",
"False",
"try",
":",
"param",
"=",
"int",
"(",
"param",
")",
"if",
"param",
"<",
"0",
":",
"return",
"False",
"except",
"(",
"TypeError",
",",
"ValueError"... | 25.8125 | 19.3125 |
def is_closing(self) -> bool:
"""Return ``True`` if this connection is closing.
The connection is considered closing if either side has
initiated its closing handshake or if the stream has been
shut down uncleanly.
"""
return self.stream.closed() or self.client_terminate... | [
"def",
"is_closing",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"stream",
".",
"closed",
"(",
")",
"or",
"self",
".",
"client_terminated",
"or",
"self",
".",
"server_terminated"
] | 42.5 | 19.75 |
def _inv_key(list_keys, valid_keys):
"""
-----
Brief
-----
A sub-function of _filter_keywords function.
-----------
Description
-----------
Function used for identification when a list of keywords contains invalid keywords not present
in the valid list.
----------
Param... | [
"def",
"_inv_key",
"(",
"list_keys",
",",
"valid_keys",
")",
":",
"inv_keys",
"=",
"[",
"]",
"bool_out",
"=",
"True",
"for",
"i",
"in",
"list_keys",
":",
"if",
"i",
"not",
"in",
"valid_keys",
":",
"bool_out",
"=",
"False",
"inv_keys",
".",
"append",
"(... | 23.657895 | 24.342105 |
def destandardize_variables(self, tv, blin, bvar, errBeta, nonmissing):
"""Destandardize betas and other components."""
return self.test_variables.destandardize(tv, blin, bvar, errBeta, nonmissing) | [
"def",
"destandardize_variables",
"(",
"self",
",",
"tv",
",",
"blin",
",",
"bvar",
",",
"errBeta",
",",
"nonmissing",
")",
":",
"return",
"self",
".",
"test_variables",
".",
"destandardize",
"(",
"tv",
",",
"blin",
",",
"bvar",
",",
"errBeta",
",",
"non... | 70.333333 | 25.333333 |
def get_token_func():
"""
This function makes a call to AAD to fetch an OAuth token
:return: the OAuth token and the interval to wait before refreshing it
"""
print("{}: token updater was triggered".format(datetime.datetime.now()))
# in this example, the OAuth token is o... | [
"def",
"get_token_func",
"(",
")",
":",
"print",
"(",
"\"{}: token updater was triggered\"",
".",
"format",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
")",
"# in this example, the OAuth token is obtained using the ADAL library",
"# however, the user can us... | 56.565217 | 31.173913 |
def rot_consts(geom, masses, units=_EURC.INV_INERTIA, on_tol=_DEF.ORTHONORM_TOL):
"""Rotational constants for a given molecular system.
Calculates the rotational constants for the provided system with numerical
value given in the units provided in `units`. The orthnormality tolerance
`on_tol` is requi... | [
"def",
"rot_consts",
"(",
"geom",
",",
"masses",
",",
"units",
"=",
"_EURC",
".",
"INV_INERTIA",
",",
"on_tol",
"=",
"_DEF",
".",
"ORTHONORM_TOL",
")",
":",
"# Imports",
"import",
"numpy",
"as",
"np",
"from",
".",
".",
"const",
"import",
"EnumTopType",
"... | 40.14 | 24 |
def __get_event(self, block=True, timeout=1):
"""
Retrieves an event. If self._exceeding_event is not None, it'll be
returned. Otherwise, an event is dequeued from the event buffer. If
The event which was retrieved is bigger than the permitted batch size,
it'll be omitted, and th... | [
"def",
"__get_event",
"(",
"self",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"1",
")",
":",
"while",
"True",
":",
"if",
"self",
".",
"_exceeding_event",
":",
"# An event was omitted from last batch",
"event",
"=",
"self",
".",
"_exceeding_event",
"self",... | 48.25 | 20.5 |
def isvalid(path, access=None, extensions=None, filetype=None, minsize=None):
"""Check whether file meets access, extension, size, and type criteria."""
return ((access is None or os.access(path, access)) and
(extensions is None or checkext(path, extensions)) and
(((filetype == 'all' and... | [
"def",
"isvalid",
"(",
"path",
",",
"access",
"=",
"None",
",",
"extensions",
"=",
"None",
",",
"filetype",
"=",
"None",
",",
"minsize",
"=",
"None",
")",
":",
"return",
"(",
"(",
"access",
"is",
"None",
"or",
"os",
".",
"access",
"(",
"path",
",",... | 62.5 | 19.9 |
def unix_time(dt=None, as_int=False):
"""Generate a unix style timestamp (in seconds)"""
if dt is None:
dt = datetime.datetime.utcnow()
if type(dt) is datetime.date:
dt = date_to_datetime(dt)
epoch = datetime.datetime.utcfromtimestamp(0)
delta = dt - epoch
if as_int:
... | [
"def",
"unix_time",
"(",
"dt",
"=",
"None",
",",
"as_int",
"=",
"False",
")",
":",
"if",
"dt",
"is",
"None",
":",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"type",
"(",
"dt",
")",
"is",
"datetime",
".",
"date",
":",
... | 25.066667 | 17.2 |
def gp_size(self, _gp_size):
"""Store the new start address attribute of the BFD file being
processed.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.set_gp_size(self._ptr, _gp_size) | [
"def",
"gp_size",
"(",
"self",
",",
"_gp_size",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"set_gp_size",
"(",
"self",
".",
"_ptr",
",",
"_gp_size",
")"
] | 29.444444 | 16.222222 |
def _get_bottom_line_coordinates(self):
"""Returns start and stop coordinates of bottom line"""
rect_x, rect_y, rect_width, rect_height = self.rect
start_point = rect_x, rect_y + rect_height
end_point = rect_x + rect_width, rect_y + rect_height
return start_point, end_point | [
"def",
"_get_bottom_line_coordinates",
"(",
"self",
")",
":",
"rect_x",
",",
"rect_y",
",",
"rect_width",
",",
"rect_height",
"=",
"self",
".",
"rect",
"start_point",
"=",
"rect_x",
",",
"rect_y",
"+",
"rect_height",
"end_point",
"=",
"rect_x",
"+",
"rect_widt... | 34.333333 | 19.333333 |
def calc_qdgz_v1(self):
"""Aggregate the amount of total direct flow released by all HRUs.
Required control parameters:
|Lnk|
|NHRU|
|FHRU|
Required flux sequence:
|QDB|
|NKor|
|EvI|
Calculated flux sequence:
|QDGZ|
Basic equation:
:math:`QDGZ = \... | [
"def",
"calc_qdgz_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fastaccess",
"flu",
".",
"qdgz",
"=",
"0.",
"for",
"k",
"in",
"range",
... | 30.125 | 20.642857 |
def _factory(importname, base_class_type, path=None, *args, **kargs):
''' Load a module of a given base class type
Parameter
--------
importname: string
Name of the module, etc. converter
base_class_type: class type
E.g converter
path: Absoulte path o... | [
"def",
"_factory",
"(",
"importname",
",",
"base_class_type",
",",
"path",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"def",
"is_base_class",
"(",
"item",
")",
":",
"return",
"isclass",
"(",
"item",
")",
"and",
"item",
".",
"__m... | 32.475 | 20.925 |
def deserialize(self, value, **kwargs):
"""Deserialize instance from JSON value
If a deserializer is registered, that is used. Otherwise, if the
instance_class is a HasProperties subclass, an instance can be
deserialized from a dictionary.
"""
kwargs.update({'trusted': k... | [
"def",
"deserialize",
"(",
"self",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'trusted'",
":",
"kwargs",
".",
"get",
"(",
"'trusted'",
",",
"False",
")",
"}",
")",
"if",
"self",
".",
"deserializer",
"is",
"... | 42.764706 | 14.647059 |
def set_secure_boot_mode(self, secure_boot_enable):
"""Enable/Disable secure boot on the server.
Resetting the server post updating this settings is needed
from the caller side to make this into effect.
:param secure_boot_enable: True, if secure boot needs to be
enabled f... | [
"def",
"set_secure_boot_mode",
"(",
"self",
",",
"secure_boot_enable",
")",
":",
"if",
"self",
".",
"_is_boot_mode_uefi",
"(",
")",
":",
"sushy_system",
"=",
"self",
".",
"_get_sushy_system",
"(",
"PROLIANT_SYSTEM_ID",
")",
"try",
":",
"sushy_system",
".",
"secu... | 49.433333 | 18.2 |
def plot_rolling_returns(returns,
factor_returns=None,
live_start_date=None,
logy=False,
cone_std=None,
legend_loc='best',
volatility_match=False,
... | [
"def",
"plot_rolling_returns",
"(",
"returns",
",",
"factor_returns",
"=",
"None",
",",
"live_start_date",
"=",
"None",
",",
"logy",
"=",
"False",
",",
"cone_std",
"=",
"None",
",",
"legend_loc",
"=",
"'best'",
",",
"volatility_match",
"=",
"False",
",",
"co... | 39.016 | 17.992 |
def p_id_expr(p):
""" bexpr : ID
| ARRAY_ID
"""
entry = SYMBOL_TABLE.access_id(p[1], p.lineno(1), default_class=CLASS.var)
if entry is None:
p[0] = None
return
entry.accessed = True
if entry.type_ == TYPE.auto:
entry.type_ = _TYPE(gl.DEFAULT_TYPE)
ap... | [
"def",
"p_id_expr",
"(",
"p",
")",
":",
"entry",
"=",
"SYMBOL_TABLE",
".",
"access_id",
"(",
"p",
"[",
"1",
"]",
",",
"p",
".",
"lineno",
"(",
"1",
")",
",",
"default_class",
"=",
"CLASS",
".",
"var",
")",
"if",
"entry",
"is",
"None",
":",
"p",
... | 34.903226 | 20.548387 |
def contracts_data_path(version: Optional[str] = None):
"""Returns the deployment data directory for a version."""
if version is None:
return _BASE.joinpath('data')
return _BASE.joinpath(f'data_{version}') | [
"def",
"contracts_data_path",
"(",
"version",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"return",
"_BASE",
".",
"joinpath",
"(",
"'data'",
")",
"return",
"_BASE",
".",
"joinpath",
"(",
"f'data_{version}'",... | 44.2 | 7.8 |
def follow_double_underscores(obj, field_name=None, excel_dialect=True, eval_python=False, index_error_value=None):
'''Like getattr(obj, field_name) only follows model relationships through "__" or "." as link separators
>>> from django.contrib.auth.models import Permission
>>> import math
>>> p = Perm... | [
"def",
"follow_double_underscores",
"(",
"obj",
",",
"field_name",
"=",
"None",
",",
"excel_dialect",
"=",
"True",
",",
"eval_python",
"=",
"False",
",",
"index_error_value",
"=",
"None",
")",
":",
"if",
"not",
"obj",
":",
"return",
"obj",
"if",
"isinstance"... | 47.333333 | 29.52381 |
def sanitize(self):
'''
Check if the current settings conform to the LISP specifications and
fix them where possible.
'''
super(EncapsulatedControlMessage, self).sanitize()
# S: This is the Security bit. When set to 1 the following
# authentication information w... | [
"def",
"sanitize",
"(",
"self",
")",
":",
"super",
"(",
"EncapsulatedControlMessage",
",",
"self",
")",
".",
"sanitize",
"(",
")",
"# S: This is the Security bit. When set to 1 the following",
"# authentication information will be appended to the end of the Map-",
"# Reply. The... | 46.611111 | 24.777778 |
def setconfig(lookup, key, value=None):
'''setconfig will update a lookup to give priority based on the following:
1. If both values are None, we set the value to None
2. If the currently set (the config.json) is set but not runtime, use config
3. If the runtime is set but not config.json, we... | [
"def",
"setconfig",
"(",
"lookup",
",",
"key",
",",
"value",
"=",
"None",
")",
":",
"lookup",
"[",
"key",
"]",
"=",
"value",
"or",
"lookup",
".",
"get",
"(",
"key",
")",
"return",
"lookup"
] | 39.454545 | 24.181818 |
def _uncythonized_mb_model(self, beta, mini_batch):
""" Creates the structure of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
mini_batch : int
Size of each mini batch of data
Returns... | [
"def",
"_uncythonized_mb_model",
"(",
"self",
",",
"beta",
",",
"mini_batch",
")",
":",
"rand_int",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"low",
"=",
"0",
",",
"high",
"=",
"self",
".",
"data",
".",
"shape",
"[",
"0",
"]",
"-",
"mini_batch",... | 35.631579 | 27.710526 |
def on_plot_select(self,event):
"""
Select data point if cursor is in range of a data point
@param: event -> the wx Mouseevent for that click
"""
if not self.xdata or not self.ydata: return
pos=event.GetPosition()
width, height = self.canvas.get_width_height()
... | [
"def",
"on_plot_select",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"self",
".",
"xdata",
"or",
"not",
"self",
".",
"ydata",
":",
"return",
"pos",
"=",
"event",
".",
"GetPosition",
"(",
")",
"width",
",",
"height",
"=",
"self",
".",
"canvas",
... | 36.846154 | 16.076923 |
def get_queryset(self, queryset=None):
"""
Returns a queryset for this request.
Arguments:
queryset: Optional root-level queryset.
"""
serializer = self.get_serializer()
return getattr(self, 'queryset', serializer.Meta.model.objects.all()) | [
"def",
"get_queryset",
"(",
"self",
",",
"queryset",
"=",
"None",
")",
":",
"serializer",
"=",
"self",
".",
"get_serializer",
"(",
")",
"return",
"getattr",
"(",
"self",
",",
"'queryset'",
",",
"serializer",
".",
"Meta",
".",
"model",
".",
"objects",
"."... | 32.222222 | 12.888889 |
def bar(x, y, **kwargs):
"""Draws a bar chart in the current context figure.
Parameters
----------
x: numpy.ndarray, 1d
The x-coordinates of the data points.
y: numpy.ndarray, 1d
The y-coordinates of the data pints.
options: dict (default: {})
Options for the scales to ... | [
"def",
"bar",
"(",
"x",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'x'",
"]",
"=",
"x",
"kwargs",
"[",
"'y'",
"]",
"=",
"y",
"return",
"_draw_mark",
"(",
"Bars",
",",
"*",
"*",
"kwargs",
")"
] | 37.136364 | 19.590909 |
def _integrate_plugins():
"""Integrate plugins to the context"""
import sys
from airflow.plugins_manager import sensors_modules
for sensors_module in sensors_modules:
sys.modules[sensors_module.__name__] = sensors_module
globals()[sensors_module._name] = sensors_module | [
"def",
"_integrate_plugins",
"(",
")",
":",
"import",
"sys",
"from",
"airflow",
".",
"plugins_manager",
"import",
"sensors_modules",
"for",
"sensors_module",
"in",
"sensors_modules",
":",
"sys",
".",
"modules",
"[",
"sensors_module",
".",
"__name__",
"]",
"=",
"... | 42.142857 | 13.571429 |
def _makeflags(self):
"""Set variable MAKEFLAGS with the numbers of
processors
"""
if self.meta.makeflags in ["on", "ON"]:
cpus = multiprocessing.cpu_count()
os.environ["MAKEFLAGS"] = "-j{0}".format(cpus) | [
"def",
"_makeflags",
"(",
"self",
")",
":",
"if",
"self",
".",
"meta",
".",
"makeflags",
"in",
"[",
"\"on\"",
",",
"\"ON\"",
"]",
":",
"cpus",
"=",
"multiprocessing",
".",
"cpu_count",
"(",
")",
"os",
".",
"environ",
"[",
"\"MAKEFLAGS\"",
"]",
"=",
"... | 36.285714 | 10.285714 |
def get_infix_items(tokens, callback=infix_error):
"""Perform infix token processing.
Takes a callback that (takes infix tokens and returns a string) to handle inner infix calls.
"""
internal_assert(len(tokens) >= 3, "invalid infix tokens", tokens)
(arg1, func, arg2), tokens = tokens[:3], tokens[3:... | [
"def",
"get_infix_items",
"(",
"tokens",
",",
"callback",
"=",
"infix_error",
")",
":",
"internal_assert",
"(",
"len",
"(",
"tokens",
")",
">=",
"3",
",",
"\"invalid infix tokens\"",
",",
"tokens",
")",
"(",
"arg1",
",",
"func",
",",
"arg2",
")",
",",
"t... | 39.461538 | 17.538462 |
def iter_nearest_neighbours(umis, substr_idx):
'''
Added by Matt 06/05/17
use substring dict to get (approximately) all the nearest neighbours to
each in a set of umis.
'''
for i, u in enumerate(umis, 1):
neighbours = set()
for idx, substr_map in substr_idx.items():
u... | [
"def",
"iter_nearest_neighbours",
"(",
"umis",
",",
"substr_idx",
")",
":",
"for",
"i",
",",
"u",
"in",
"enumerate",
"(",
"umis",
",",
"1",
")",
":",
"neighbours",
"=",
"set",
"(",
")",
"for",
"idx",
",",
"substr_map",
"in",
"substr_idx",
".",
"items",... | 35.142857 | 15.857143 |
def make_energy_bounds_hdu(self, extname="EBOUNDS"):
""" Builds and returns a FITs HDU with the energy bin boundries
extname : The HDU extension name
"""
if self._ebins is None:
return None
cols = [fits.Column("CHANNEL", "I", array=np.arange(1, len(self... | [
"def",
"make_energy_bounds_hdu",
"(",
"self",
",",
"extname",
"=",
"\"EBOUNDS\"",
")",
":",
"if",
"self",
".",
"_ebins",
"is",
"None",
":",
"return",
"None",
"cols",
"=",
"[",
"fits",
".",
"Column",
"(",
"\"CHANNEL\"",
",",
"\"I\"",
",",
"array",
"=",
... | 45.714286 | 18.142857 |
def get_html_source_with_base_href(driver, page_source):
''' Combines the domain base href with the html source.
This is needed for the page html to render correctly. '''
last_page = get_last_page(driver)
if '://' in last_page:
base_href_html = get_base_href_html(last_page)
return '%... | [
"def",
"get_html_source_with_base_href",
"(",
"driver",
",",
"page_source",
")",
":",
"last_page",
"=",
"get_last_page",
"(",
"driver",
")",
"if",
"'://'",
"in",
"last_page",
":",
"base_href_html",
"=",
"get_base_href_html",
"(",
"last_page",
")",
"return",
"'%s\\... | 45.625 | 16.625 |
def set(self, attr_dict):
"""Sets attributes of this user object.
:type attr_dict: dict
:param attr_dict: Parameters to set, with attribute keys.
:rtype: :class:`.Base`
:return: The current object.
"""
for key in attr_dict:
if key == self._id_attribute:
setattr(self, self._i... | [
"def",
"set",
"(",
"self",
",",
"attr_dict",
")",
":",
"for",
"key",
"in",
"attr_dict",
":",
"if",
"key",
"==",
"self",
".",
"_id_attribute",
":",
"setattr",
"(",
"self",
",",
"self",
".",
"_id_attribute",
",",
"attr_dict",
"[",
"key",
"]",
")",
"els... | 25.6875 | 18.3125 |
def _create_gitlab_runner_prometheus_instance(self, instance, init_config):
"""
Set up the gitlab_runner instance so it can be used in OpenMetricsBaseCheck
"""
# Mapping from Prometheus metrics names to Datadog ones
# For now it's a 1:1 mapping
allowed_metrics = init_conf... | [
"def",
"_create_gitlab_runner_prometheus_instance",
"(",
"self",
",",
"instance",
",",
"init_config",
")",
":",
"# Mapping from Prometheus metrics names to Datadog ones",
"# For now it's a 1:1 mapping",
"allowed_metrics",
"=",
"init_config",
".",
"get",
"(",
"'allowed_metrics'",
... | 45.269231 | 27.423077 |
def next_request(self):
""" Provides a request to be scheduled.
:return: Request object or None
"""
method_frame, header_frame, url = self.server.basic_get(queue=self.rabbitmq_key)
# TODO(royce): Remove print
print url
if url:
return self.make_reque... | [
"def",
"next_request",
"(",
"self",
")",
":",
"method_frame",
",",
"header_frame",
",",
"url",
"=",
"self",
".",
"server",
".",
"basic_get",
"(",
"queue",
"=",
"self",
".",
"rabbitmq_key",
")",
"# TODO(royce): Remove print",
"print",
"url",
"if",
"url",
":",... | 27.166667 | 20.833333 |
def logpdf_link(self, inv_link_f, y, Y_metadata=None):
"""
Log Likelihood function given inverse link of f.
.. math::
\\ln p(y_{i}|\\lambda(f_{i})) = y_{i}\\log\\lambda(f_{i}) + (1-y_{i})\\log (1-f_{i})
:param inv_link_f: latent variables inverse link of f.
:type in... | [
"def",
"logpdf_link",
"(",
"self",
",",
"inv_link_f",
",",
"y",
",",
"Y_metadata",
"=",
"None",
")",
":",
"N",
"=",
"Y_metadata",
"[",
"'trials'",
"]",
"np",
".",
"testing",
".",
"assert_array_equal",
"(",
"N",
".",
"shape",
",",
"y",
".",
"shape",
"... | 34.925926 | 20.925926 |
def missing(self, *args, **kwds):
"""Return whether an output is considered missing or not."""
from functools import reduce
indexer = kwds['indexer']
freq = kwds['freq'] or generic.default_freq(**indexer)
miss = (checks.missing_any(generic.select_time(da, **indexer), freq) for ... | [
"def",
"missing",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"from",
"functools",
"import",
"reduce",
"indexer",
"=",
"kwds",
"[",
"'indexer'",
"]",
"freq",
"=",
"kwds",
"[",
"'freq'",
"]",
"or",
"generic",
".",
"default_freq",
"... | 40.666667 | 19.333333 |
def get_absolute_path(some_path):
"""
This function will return an appropriate absolute path for the path it is
given. If the input is absolute, it will return unmodified; if the input is
relative, it will be rendered as relative to the current working directory.
"""
if os.path.isabs(some_path):... | [
"def",
"get_absolute_path",
"(",
"some_path",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"some_path",
")",
":",
"return",
"some_path",
"else",
":",
"return",
"evaluate_relative_path",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"some_path",
")"
] | 40.8 | 19.8 |
def is_installed(self, bug: Bug) -> bool:
"""
Determines whether the Docker image for a given bug has been installed
on the server.
"""
r = self.__api.get('bugs/{}/installed'.format(bug.name))
if r.status_code == 200:
answer = r.json()
assert isin... | [
"def",
"is_installed",
"(",
"self",
",",
"bug",
":",
"Bug",
")",
"->",
"bool",
":",
"r",
"=",
"self",
".",
"__api",
".",
"get",
"(",
"'bugs/{}/installed'",
".",
"format",
"(",
"bug",
".",
"name",
")",
")",
"if",
"r",
".",
"status_code",
"==",
"200"... | 32.764706 | 17.352941 |
def binsearch(reader, key, compare_func=cmp, block_size=8192):
"""
Perform a binary search for a specified key to within a 'block_size'
(default 8192) granularity, and return first full line found.
"""
min_ = binsearch_offset(reader, key, compare_func, block_size)
reader.seek(min_)
if min... | [
"def",
"binsearch",
"(",
"reader",
",",
"key",
",",
"compare_func",
"=",
"cmp",
",",
"block_size",
"=",
"8192",
")",
":",
"min_",
"=",
"binsearch_offset",
"(",
"reader",
",",
"key",
",",
"compare_func",
",",
"block_size",
")",
"reader",
".",
"seek",
"(",... | 26.789474 | 21.421053 |
def send(self, sender, to, subject, plain=None, html=None, cc=None, bcc=None,
replyto=None, attach=None):
"""
Send the message.
If we have PLAIN and HTML versions, send a multipart alternative
MIME message, else send whichever we do have.
If we have neither, raise ... | [
"def",
"send",
"(",
"self",
",",
"sender",
",",
"to",
",",
"subject",
",",
"plain",
"=",
"None",
",",
"html",
"=",
"None",
",",
"cc",
"=",
"None",
",",
"bcc",
"=",
"None",
",",
"replyto",
"=",
"None",
",",
"attach",
"=",
"None",
")",
":",
"self... | 30.576923 | 18.692308 |
def join_list(values, delimiter=', ', transform=None):
"""
Concatenates the upper-cased values using the given delimiter if
the given values variable is a list. Otherwise it is just returned.
:param values: List of strings or string .
:param delimiter: The delimiter used to join the values.
:ret... | [
"def",
"join_list",
"(",
"values",
",",
"delimiter",
"=",
"', '",
",",
"transform",
"=",
"None",
")",
":",
"# type: (Union[List[str], str], str)->str",
"if",
"transform",
"is",
"None",
":",
"transform",
"=",
"_identity",
"if",
"values",
"is",
"not",
"None",
"a... | 40 | 16.266667 |
def jsonrpc_map(self):
""" Map of json-rpc available calls.
:return str:
"""
result = "<h1>JSON-RPC map</h1><pre>{0}</pre>".format("\n\n".join([
"{0}: {1}".format(fname, f.__doc__)
for fname, f in self.dispatcher.items()
]))
return Response(resul... | [
"def",
"jsonrpc_map",
"(",
"self",
")",
":",
"result",
"=",
"\"<h1>JSON-RPC map</h1><pre>{0}</pre>\"",
".",
"format",
"(",
"\"\\n\\n\"",
".",
"join",
"(",
"[",
"\"{0}: {1}\"",
".",
"format",
"(",
"fname",
",",
"f",
".",
"__doc__",
")",
"for",
"fname",
",",
... | 28.363636 | 19 |
def list_rds(region, filter_by_kwargs):
"""List all RDS thingys."""
conn = boto.rds.connect_to_region(region)
instances = conn.get_all_dbinstances()
return lookup(instances, filter_by=filter_by_kwargs) | [
"def",
"list_rds",
"(",
"region",
",",
"filter_by_kwargs",
")",
":",
"conn",
"=",
"boto",
".",
"rds",
".",
"connect_to_region",
"(",
"region",
")",
"instances",
"=",
"conn",
".",
"get_all_dbinstances",
"(",
")",
"return",
"lookup",
"(",
"instances",
",",
"... | 42.6 | 4.8 |
def verify_and_fill_address_paths_from_bip32key(address_paths, master_key, network):
'''
Take address paths and verifies their accuracy client-side.
Also fills in all the available metadata (WIF, public key, etc)
'''
assert network, network
wallet_obj = Wallet.deserialize(master_key, network=... | [
"def",
"verify_and_fill_address_paths_from_bip32key",
"(",
"address_paths",
",",
"master_key",
",",
"network",
")",
":",
"assert",
"network",
",",
"network",
"wallet_obj",
"=",
"Wallet",
".",
"deserialize",
"(",
"master_key",
",",
"network",
"=",
"network",
")",
"... | 33.826923 | 21.365385 |
def reset(self):
"""Re-initialize the sampler."""
# live points
self.live_u = self.rstate.rand(self.nlive, self.npdim)
if self.use_pool_ptform:
# Use the pool to compute the prior transform.
self.live_v = np.array(list(self.M(self.prior_transform,
... | [
"def",
"reset",
"(",
"self",
")",
":",
"# live points",
"self",
".",
"live_u",
"=",
"self",
".",
"rstate",
".",
"rand",
"(",
"self",
".",
"nlive",
",",
"self",
".",
"npdim",
")",
"if",
"self",
".",
"use_pool_ptform",
":",
"# Use the pool to compute the pri... | 35.245283 | 19.509434 |
def report(self, item_id, report_format="json"):
"""Retrieves the specified report for the analyzed item, referenced by item_id.
For available report formats, see online Joe Sandbox documentation.
:type item_id: str
:param item_id: File ID number
:type report_form... | [
"def",
"report",
"(",
"self",
",",
"item_id",
",",
"report_format",
"=",
"\"json\"",
")",
":",
"if",
"report_format",
"==",
"\"json\"",
":",
"report_format",
"=",
"\"jsonfixed\"",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"self",
".",
"jbx",
".",
... | 40.380952 | 21.142857 |
def _dir_out(self):
"""Create string of the data directory to save individual .nc files."""
return os.path.join(self.proj.direc_out, self.proj.name,
self.model.name, self.run.name, self.name) | [
"def",
"_dir_out",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"proj",
".",
"direc_out",
",",
"self",
".",
"proj",
".",
"name",
",",
"self",
".",
"model",
".",
"name",
",",
"self",
".",
"run",
".",
"name",
... | 58 | 18.75 |
def write_base (self, url_data):
"""Write url_data.base_ref."""
self.write(self.part("base") + self.spaces("base"))
self.writeln(url_data.base_ref, color=self.colorbase) | [
"def",
"write_base",
"(",
"self",
",",
"url_data",
")",
":",
"self",
".",
"write",
"(",
"self",
".",
"part",
"(",
"\"base\"",
")",
"+",
"self",
".",
"spaces",
"(",
"\"base\"",
")",
")",
"self",
".",
"writeln",
"(",
"url_data",
".",
"base_ref",
",",
... | 47.5 | 12 |
def check_frequencies(pfeed, *, as_df=False, include_warnings=False):
"""
Check that ``pfeed.frequency`` follows the ProtoFeed spec.
Return a list of problems of the form described in
:func:`gt.check_table`;
the list will be empty if no problems are found.
"""
table = 'frequencies'
probl... | [
"def",
"check_frequencies",
"(",
"pfeed",
",",
"*",
",",
"as_df",
"=",
"False",
",",
"include_warnings",
"=",
"False",
")",
":",
"table",
"=",
"'frequencies'",
"problems",
"=",
"[",
"]",
"# Preliminary checks",
"if",
"pfeed",
".",
"frequencies",
"is",
"None"... | 33.767857 | 22.160714 |
def comparison(self, t):
"""
<PropertyIsEqualTo>
<PropertyName>NAME</PropertyName>
<Literal>Sydney</Literal>
</PropertyIsEqualTo>
"""
assert(len(t) == 3)
d = {"PropertyIsEqualTo": [
t[0], t[1], t[2]
]}
#parts = [str(p.value) for p in t]
... | [
"def",
"comparison",
"(",
"self",
",",
"t",
")",
":",
"assert",
"(",
"len",
"(",
"t",
")",
"==",
"3",
")",
"d",
"=",
"{",
"\"PropertyIsEqualTo\"",
":",
"[",
"t",
"[",
"0",
"]",
",",
"t",
"[",
"1",
"]",
",",
"t",
"[",
"2",
"]",
"]",
"}",
"... | 21.15 | 16.15 |
def get_temp_directory():
"""Return an absolute path to an existing temporary directory"""
# Supports all platforms supported by tempfile
directory = os.path.join(gettempdir(), "ttkthemes")
if not os.path.exists(directory):
os.makedirs(directory)
return directory | [
"def",
"get_temp_directory",
"(",
")",
":",
"# Supports all platforms supported by tempfile",
"directory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"gettempdir",
"(",
")",
",",
"\"ttkthemes\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directo... | 40.714286 | 10.428571 |
def notify(title,
message,
jid,
password,
recipient,
hostname=None,
port=5222,
path_to_certs=None,
mtype=None,
retcode=None):
"""
Optional parameters
* ``hostname`` (if not from jid)
* ``port``
... | [
"def",
"notify",
"(",
"title",
",",
"message",
",",
"jid",
",",
"password",
",",
"recipient",
",",
"hostname",
"=",
"None",
",",
"port",
"=",
"5222",
",",
"path_to_certs",
"=",
"None",
",",
"mtype",
"=",
"None",
",",
"retcode",
"=",
"None",
")",
":",... | 32 | 20.444444 |
def set_attributes(
name,
attributes,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Set attributes on an SQS queue.
CLI Example:
.. code-block:: bash
salt myminion boto_sqs.set_attributes myqueue '{ReceiveMessageWaitTimeSeconds: 20}' region=us-east-1
'''
... | [
"def",
"set_attributes",
"(",
"name",
",",
"attributes",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
... | 25.851852 | 28.074074 |
def format_log(ret):
'''
Format the state into a log message
'''
msg = ''
if isinstance(ret, dict):
# Looks like the ret may be a valid state return
if 'changes' in ret:
# Yep, looks like a valid state return
chg = ret['changes']
if not chg:
... | [
"def",
"format_log",
"(",
"ret",
")",
":",
"msg",
"=",
"''",
"if",
"isinstance",
"(",
"ret",
",",
"dict",
")",
":",
"# Looks like the ret may be a valid state return",
"if",
"'changes'",
"in",
"ret",
":",
"# Yep, looks like a valid state return",
"chg",
"=",
"ret"... | 44.5 | 18.928571 |
def extern_get_type_for(self, context_handle, val):
"""Return a representation of the object's type."""
c = self._ffi.from_handle(context_handle)
obj = self._ffi.from_handle(val[0])
type_id = c.to_id(type(obj))
return TypeId(type_id) | [
"def",
"extern_get_type_for",
"(",
"self",
",",
"context_handle",
",",
"val",
")",
":",
"c",
"=",
"self",
".",
"_ffi",
".",
"from_handle",
"(",
"context_handle",
")",
"obj",
"=",
"self",
".",
"_ffi",
".",
"from_handle",
"(",
"val",
"[",
"0",
"]",
")",
... | 41.333333 | 6.5 |
def callback_liveIn_button_press(red_clicks, blue_clicks, green_clicks,
rc_timestamp, bc_timestamp, gc_timestamp, **kwargs): # pylint: disable=unused-argument
'Input app button pressed, so do something interesting'
if not rc_timestamp:
rc_timestamp = 0
if not bc_tim... | [
"def",
"callback_liveIn_button_press",
"(",
"red_clicks",
",",
"blue_clicks",
",",
"green_clicks",
",",
"rc_timestamp",
",",
"bc_timestamp",
",",
"gc_timestamp",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"if",
"not",
"rc_timestamp",
":",
... | 41.75 | 23.35 |
def generate_key_value_sequences(entry, default_value):
"""Parse a key value config entry (used in duplicate foreach)
If we have a key that look like [X-Y] we will expand it into Y-X+1 keys
:param str entry: The config line to be parsed.
:param str default_value: The default value to be used when none... | [
"def",
"generate_key_value_sequences",
"(",
"entry",
",",
"default_value",
")",
":",
"no_one_yielded",
"=",
"True",
"for",
"value",
"in",
"entry",
".",
"split",
"(",
"','",
")",
":",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"if",
"not",
"value",
":... | 43.1 | 18.85 |
def _get_filtered_stmts(self, _, node, _stmts, mystmt):
"""method used in _filter_stmts to get statements and trigger break"""
if self.statement() is mystmt:
# original node's statement is the assignment, only keep
# current node (gen exp, list comp)
return [node], Tr... | [
"def",
"_get_filtered_stmts",
"(",
"self",
",",
"_",
",",
"node",
",",
"_stmts",
",",
"mystmt",
")",
":",
"if",
"self",
".",
"statement",
"(",
")",
"is",
"mystmt",
":",
"# original node's statement is the assignment, only keep",
"# current node (gen exp, list comp)",
... | 49.285714 | 10.428571 |
def _SanitizeField(self, field):
"""Sanitizes a field for output.
This method removes the field delimiter from the field string.
Args:
field (str): field value.
Returns:
str: formatted field value.
"""
if self._FIELD_DELIMITER and isinstance(field, py2to3.STRING_TYPES):
re... | [
"def",
"_SanitizeField",
"(",
"self",
",",
"field",
")",
":",
"if",
"self",
".",
"_FIELD_DELIMITER",
"and",
"isinstance",
"(",
"field",
",",
"py2to3",
".",
"STRING_TYPES",
")",
":",
"return",
"field",
".",
"replace",
"(",
"self",
".",
"_FIELD_DELIMITER",
"... | 26.428571 | 21.214286 |
def randomize_es(es_queryset):
"""Randomize an elasticsearch queryset."""
return es_queryset.query(
query.FunctionScore(
functions=[function.RandomScore()]
)
).sort("-_score") | [
"def",
"randomize_es",
"(",
"es_queryset",
")",
":",
"return",
"es_queryset",
".",
"query",
"(",
"query",
".",
"FunctionScore",
"(",
"functions",
"=",
"[",
"function",
".",
"RandomScore",
"(",
")",
"]",
")",
")",
".",
"sort",
"(",
"\"-_score\"",
")"
] | 29.857143 | 12.714286 |
def create_experiment(args):
'''start a new experiment'''
config_file_name = ''.join(random.sample(string.ascii_letters + string.digits, 8))
nni_config = Config(config_file_name)
config_path = os.path.abspath(args.config)
if not os.path.exists(config_path):
print_error('Please set correct co... | [
"def",
"create_experiment",
"(",
"args",
")",
":",
"config_file_name",
"=",
"''",
".",
"join",
"(",
"random",
".",
"sample",
"(",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
",",
"8",
")",
")",
"nni_config",
"=",
"Config",
"(",
"config_... | 45.571429 | 17.857143 |
def GetVectorAsNumpy(self, flags, off):
"""
GetVectorAsNumpy returns the vector that starts at `Vector(off)`
as a numpy array with the type specified by `flags`. The array is
a `view` into Bytes, so modifying the returned array will
modify Bytes in place.
"""
offs... | [
"def",
"GetVectorAsNumpy",
"(",
"self",
",",
"flags",
",",
"off",
")",
":",
"offset",
"=",
"self",
".",
"Vector",
"(",
"off",
")",
"length",
"=",
"self",
".",
"VectorLen",
"(",
"off",
")",
"# TODO: length accounts for bytewidth, right?",
"numpy_dtype",
"=",
... | 49 | 17.545455 |
def showMessageOverlay(self, pchText, pchCaption, pchButton0Text, pchButton1Text, pchButton2Text, pchButton3Text):
"""Show the message overlay. This will block and return you a result."""
fn = self.function_table.showMessageOverlay
result = fn(pchText, pchCaption, pchButton0Text, pchButton1Text... | [
"def",
"showMessageOverlay",
"(",
"self",
",",
"pchText",
",",
"pchCaption",
",",
"pchButton0Text",
",",
"pchButton1Text",
",",
"pchButton2Text",
",",
"pchButton3Text",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"showMessageOverlay",
"result",
"=",
... | 61.666667 | 34.666667 |
def get_dates_in_period(start=None, top=None, step=1, step_dict={}):
"""Return a list of dates from the `start` to `top`."""
delta = relativedelta(**step_dict) if step_dict else timedelta(days=step)
start = start or datetime.today()
top = top or start + delta
dates = []
current = start
whi... | [
"def",
"get_dates_in_period",
"(",
"start",
"=",
"None",
",",
"top",
"=",
"None",
",",
"step",
"=",
"1",
",",
"step_dict",
"=",
"{",
"}",
")",
":",
"delta",
"=",
"relativedelta",
"(",
"*",
"*",
"step_dict",
")",
"if",
"step_dict",
"else",
"timedelta",
... | 30.615385 | 20.846154 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.