text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def next(self):
""" Returns the next row in the CSV, for iteration """
if self._cur_row >= len(self._table):
raise StopIteration
data = self._table[self._cur_row].copy()
self._cur_row += 1
return data | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cur_row",
">=",
"len",
"(",
"self",
".",
"_table",
")",
":",
"raise",
"StopIteration",
"data",
"=",
"self",
".",
"_table",
"[",
"self",
".",
"_cur_row",
"]",
".",
"copy",
"(",
")",
"self",
... | 35.142857 | 11.714286 |
def write_point(self, **kw):
"""
Write a task point to the file::
with writer.write_point(type=PointType.TURN):
writer.write_waypoint(...)
writer.write_observation_zone(...)
# <Point type="Turn"> ... </Point>
Inside the with clause the
... | [
"def",
"write_point",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"assert",
"'type'",
"in",
"kw",
"self",
".",
"convert_bool",
"(",
"kw",
",",
"'score_exit'",
")",
"return",
"self",
".",
"write_tag_with_content",
"(",
"'Point'",
",",
"*",
"*",
"kw",
")... | 31.791667 | 20.125 |
def __find_sentence_initial_proper_names(self, docs):
""" Moodustame lausealguliste pärisnimede loendi: vaatame sõnu, millel nii
pärisnimeanalüüs(id) kui ka mittepärisnimeanalüüs(id) ning mis esinevad
lause või nummerdatud loendi alguses - jäädvustame selliste sõnade
unikaa... | [
"def",
"__find_sentence_initial_proper_names",
"(",
"self",
",",
"docs",
")",
":",
"sentInitialNames",
"=",
"set",
"(",
")",
"for",
"doc",
"in",
"docs",
":",
"for",
"sentence",
"in",
"doc",
".",
"divide",
"(",
"layer",
"=",
"WORDS",
",",
"by",
"=",
"SENT... | 59.657895 | 22.842105 |
def device_to_user(self, x, y):
"""Transform a coordinate from device space to user space
by multiplying the given point
by the inverse of the current transformation matrix (CTM).
:param x: X position.
:param y: Y position.
:type x: float
:type y: float
:... | [
"def",
"device_to_user",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"xy",
"=",
"ffi",
".",
"new",
"(",
"'double[2]'",
",",
"[",
"x",
",",
"y",
"]",
")",
"cairo",
".",
"cairo_device_to_user",
"(",
"self",
".",
"_pointer",
",",
"xy",
"+",
"0",
",",... | 33 | 15.375 |
def infer_from_frame_stack(self, ob_stack):
"""Infer policy from stack of observations.
Args:
ob_stack: array of shape (1, frame_stack_size, height, width, channels)
Returns:
logits and vf.
"""
logits, vf = self.sess.run([self.logits_t, self.value_function_t],
... | [
"def",
"infer_from_frame_stack",
"(",
"self",
",",
"ob_stack",
")",
":",
"logits",
",",
"vf",
"=",
"self",
".",
"sess",
".",
"run",
"(",
"[",
"self",
".",
"logits_t",
",",
"self",
".",
"value_function_t",
"]",
",",
"feed_dict",
"=",
"{",
"self",
".",
... | 30.833333 | 22.666667 |
def AddRow(self, values):
"""Adds a row of values.
Args:
values (list[object]): values.
Raises:
ValueError: if the number of values is out of bounds.
"""
if self._number_of_columns and len(values) != self._number_of_columns:
raise ValueError('Number of values is out of bounds.')
... | [
"def",
"AddRow",
"(",
"self",
",",
"values",
")",
":",
"if",
"self",
".",
"_number_of_columns",
"and",
"len",
"(",
"values",
")",
"!=",
"self",
".",
"_number_of_columns",
":",
"raise",
"ValueError",
"(",
"'Number of values is out of bounds.'",
")",
"self",
"."... | 26 | 20.6875 |
def file_exists(original_file):
"""
Validate the original file is in the S3 bucket
"""
s3 = boto3.resource('s3')
bucket_name, object_key = _parse_s3_file(original_file)
bucket = s3.Bucket(bucket_name)
bucket_iterator = bucket.objects.filter(Prefix=object_key)
bucket_list = [x for x in bu... | [
"def",
"file_exists",
"(",
"original_file",
")",
":",
"s3",
"=",
"boto3",
".",
"resource",
"(",
"'s3'",
")",
"bucket_name",
",",
"object_key",
"=",
"_parse_s3_file",
"(",
"original_file",
")",
"bucket",
"=",
"s3",
".",
"Bucket",
"(",
"bucket_name",
")",
"b... | 42.5 | 13.5 |
def heightmap_rain_erosion(
hm: np.ndarray,
nbDrops: int,
erosionCoef: float,
sedimentationCoef: float,
rnd: Optional[tcod.random.Random] = None,
) -> None:
"""Simulate the effect of rain drops on the terrain, resulting in erosion.
``nbDrops`` should be at least hm.size.
Args:
... | [
"def",
"heightmap_rain_erosion",
"(",
"hm",
":",
"np",
".",
"ndarray",
",",
"nbDrops",
":",
"int",
",",
"erosionCoef",
":",
"float",
",",
"sedimentationCoef",
":",
"float",
",",
"rnd",
":",
"Optional",
"[",
"tcod",
".",
"random",
".",
"Random",
"]",
"=",... | 33.692308 | 19.192308 |
def extract_archive(archive_path, dest):
"""Extract a local or GCS archive file to a folder.
Args:
archive_path: local or gcs path to a *.tar.gz or *.tar file
dest: local folder the archive will be extracted to
"""
# Make the dest folder if it does not exist
if not os.path.isdir(dest):
os.makedir... | [
"def",
"extract_archive",
"(",
"archive_path",
",",
"dest",
")",
":",
"# Make the dest folder if it does not exist",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dest",
")",
":",
"os",
".",
"makedirs",
"(",
"dest",
")",
"try",
":",
"tmpfolder",
"=",
... | 32.861111 | 21.027778 |
def set_mode_broodlord_params(
self, zerg_count=None,
vassal_overload_sos_interval=None, vassal_queue_items_sos=None):
"""This mode is a way for a vassal to ask for reinforcements to the Emperor.
Reinforcements are new vassals spawned on demand generally bound on the same socket... | [
"def",
"set_mode_broodlord_params",
"(",
"self",
",",
"zerg_count",
"=",
"None",
",",
"vassal_overload_sos_interval",
"=",
"None",
",",
"vassal_queue_items_sos",
"=",
"None",
")",
":",
"self",
".",
"_set",
"(",
"'emperor-broodlord'",
",",
"zerg_count",
")",
"self"... | 44.807692 | 31 |
def filter(self, track=None, follow=None, locations=None, event=None,
record_keepalive=False):
"""
Returns an iterator for tweets that match a given filter track from
the livestream of tweets happening right now.
If a threading.Event is provided for event and the event is... | [
"def",
"filter",
"(",
"self",
",",
"track",
"=",
"None",
",",
"follow",
"=",
"None",
",",
"locations",
"=",
"None",
",",
"event",
"=",
"None",
",",
"record_keepalive",
"=",
"False",
")",
":",
"if",
"locations",
"is",
"not",
"None",
":",
"if",
"type",... | 40.985915 | 15.070423 |
def ends_to_curve(start_node, end_node):
"""Convert a "pair" of intersection nodes to a curve segment.
.. note::
This is a helper used only by :func:`basic_interior_combine`, which in
turn is only used by :func:`combine_intersections`.
.. note::
This function could specialize to the... | [
"def",
"ends_to_curve",
"(",
"start_node",
",",
"end_node",
")",
":",
"if",
"is_first",
"(",
"start_node",
".",
"interior_curve",
")",
":",
"if",
"end_node",
".",
"index_first",
"!=",
"start_node",
".",
"index_first",
":",
"raise",
"ValueError",
"(",
"_WRONG_C... | 38.891892 | 24.945946 |
def get_share_url_with_dirname(uk, shareid, dirname):
'''得到共享目录的链接'''
return ''.join([
const.PAN_URL, 'wap/link',
'?shareid=', shareid,
'&uk=', uk,
'&dir=', encoder.encode_uri_component(dirname),
'&third=0',
]) | [
"def",
"get_share_url_with_dirname",
"(",
"uk",
",",
"shareid",
",",
"dirname",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"const",
".",
"PAN_URL",
",",
"'wap/link'",
",",
"'?shareid='",
",",
"shareid",
",",
"'&uk='",
",",
"uk",
",",
"'&dir='",
","... | 30.333333 | 16.555556 |
def checkAndRaise(pageNum, itemsPerPage):
"""Check and Raise an Exception if needed
Args:
pageNum (int): Page number
itemsPerPage (int): Number of items per Page
Raises:
ErrPaginationLimits: If we are out of limits
"""
... | [
"def",
"checkAndRaise",
"(",
"pageNum",
",",
"itemsPerPage",
")",
":",
"if",
"pageNum",
"<",
"1",
":",
"raise",
"ErrPaginationLimits",
"(",
"ErrPaginationLimits",
".",
"ERR_PAGE_NUM",
")",
"if",
"itemsPerPage",
"<",
"Settings",
".",
"itemsPerPageMin",
"or",
"ite... | 36.25 | 21.875 |
def listdir(self, folder_id='0', offset=None, limit=None, fields=None):
'Get Box object, representing list of objects in a folder.'
if fields is not None\
and not isinstance(fields, types.StringTypes): fields = ','.join(fields)
return self(
join('folders', folder_id, 'items'),
dict(offset=offset, limit=l... | [
"def",
"listdir",
"(",
"self",
",",
"folder_id",
"=",
"'0'",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"fields",
"=",
"None",
")",
":",
"if",
"fields",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"fields",
",",
"types",
... | 48 | 20.285714 |
def _GetSanitizedEventValues(self, event):
"""Sanitizes the event for use in 4n6time.
Args:
event (EventObject): event.
Returns:
dict[str, object]: dictionary containing the sanitized event values.
Raises:
NoFormatterFound: If no event formatter can be found to match the data
... | [
"def",
"_GetSanitizedEventValues",
"(",
"self",
",",
"event",
")",
":",
"data_type",
"=",
"getattr",
"(",
"event",
",",
"'data_type'",
",",
"'UNKNOWN'",
")",
"event_formatter",
"=",
"self",
".",
"_output_mediator",
".",
"GetEventFormatter",
"(",
"event",
")",
... | 34.385417 | 20.270833 |
def append_from_dict(self, the_dict):
"""
Creates a ``measurement.Measurement`` object from the supplied dict
and then appends it to the buffer
:param the_dict: dict
"""
m = Measurement.from_dict(the_dict)
self.append(m) | [
"def",
"append_from_dict",
"(",
"self",
",",
"the_dict",
")",
":",
"m",
"=",
"Measurement",
".",
"from_dict",
"(",
"the_dict",
")",
"self",
".",
"append",
"(",
"m",
")"
] | 29.888889 | 12.333333 |
def get_category_metrics(self, category):
"""Get metrics belonging to the given category"""
slug_list = self._category_slugs(category)
return self.get_metrics(slug_list) | [
"def",
"get_category_metrics",
"(",
"self",
",",
"category",
")",
":",
"slug_list",
"=",
"self",
".",
"_category_slugs",
"(",
"category",
")",
"return",
"self",
".",
"get_metrics",
"(",
"slug_list",
")"
] | 47.5 | 3.25 |
def defvalkey(js, key, default=None, take_none=True):
"""
Returns js[key] if set, otherwise default. Note js[key] can be None.
:param js:
:param key:
:param default:
:param take_none:
:return:
"""
if js is None:
return default
if key not in js:
return default
... | [
"def",
"defvalkey",
"(",
"js",
",",
"key",
",",
"default",
"=",
"None",
",",
"take_none",
"=",
"True",
")",
":",
"if",
"js",
"is",
"None",
":",
"return",
"default",
"if",
"key",
"not",
"in",
"js",
":",
"return",
"default",
"if",
"js",
"[",
"key",
... | 24 | 17.625 |
def choose_template(self, template):
'''Choose a template
Args:
template: String, choose which template you would like.
Returns:
None
Raises:
None
'''
n1 = int(template)/10
n2 = int(template)%10
self.send('^TS'+... | [
"def",
"choose_template",
"(",
"self",
",",
"template",
")",
":",
"n1",
"=",
"int",
"(",
"template",
")",
"/",
"10",
"n2",
"=",
"int",
"(",
"template",
")",
"%",
"10",
"self",
".",
"send",
"(",
"'^TS'",
"+",
"'0'",
"+",
"str",
"(",
"n1",
")",
"... | 25.230769 | 19.538462 |
def env_present(name,
value=None,
user='root'):
'''
Verifies that the specified environment variable is present in the crontab
for the specified user.
name
The name of the environment variable to set in the user crontab
user
The name of the user whos... | [
"def",
"env_present",
"(",
"name",
",",
"value",
"=",
"None",
",",
"user",
"=",
"'root'",
")",
":",
"ret",
"=",
"{",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
",",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
"}",
"if",
"__... | 32.647059 | 23.27451 |
def describe_jobflow(self, jobflow_id):
"""
Describes a single Elastic MapReduce job flow
:type jobflow_id: str
:param jobflow_id: The job flow id of interest
"""
jobflows = self.describe_jobflows(jobflow_ids=[jobflow_id])
if jobflows:
return jobflows... | [
"def",
"describe_jobflow",
"(",
"self",
",",
"jobflow_id",
")",
":",
"jobflows",
"=",
"self",
".",
"describe_jobflows",
"(",
"jobflow_ids",
"=",
"[",
"jobflow_id",
"]",
")",
"if",
"jobflows",
":",
"return",
"jobflows",
"[",
"0",
"]"
] | 31.4 | 13.6 |
def _update_flip(context, flip_id, ip_type, requested_ports):
"""Update a flip based IPAddress
:param context: neutron api request context.
:param flip_id: id of the flip or scip
:param ip_type: ip_types.FLOATING | ip_types.SCALING
:param requested_ports: dictionary of the structure:
{"port_id"... | [
"def",
"_update_flip",
"(",
"context",
",",
"flip_id",
",",
"ip_type",
",",
"requested_ports",
")",
":",
"# This list will hold flips that require notifications.",
"# Using sets to avoid dups, if any.",
"notifications",
"=",
"{",
"billing",
".",
"IP_ASSOC",
":",
"set",
"(... | 47.105263 | 20.150376 |
def seek(self, offset, whence=0):
"""Seek to the specified position.
:param int offset: The offset in bytes.
:param int whence: Where the offset is from.
Returns the position after seeking."""
logger.debug('seeking to offset: %r whence: %r', offset, whence)
if whence no... | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"whence",
"=",
"0",
")",
":",
"logger",
".",
"debug",
"(",
"'seeking to offset: %r whence: %r'",
",",
"offset",
",",
"whence",
")",
"if",
"whence",
"not",
"in",
"s3",
".",
"WHENCE_CHOICES",
":",
"raise",
"V... | 32.931818 | 18.659091 |
def _read_moment_tensor_from_ndk_string(ndk_string, system='USE'):
"""
Reads the moment tensor from the ndk_string representation
ndk_string = [Mrr, sigMrr, Mtt, sigMtt, Mpp, sigMpp, Mrt, sigMrt, Mrp,
sigMrp, Mtp, sigMtp]
Output tensors should be of format:
expected = [[Mtt, Mt... | [
"def",
"_read_moment_tensor_from_ndk_string",
"(",
"ndk_string",
",",
"system",
"=",
"'USE'",
")",
":",
"exponent",
"=",
"float",
"(",
"ndk_string",
"[",
"0",
":",
"2",
"]",
")",
"-",
"7.",
"mkr",
"=",
"np",
".",
"array",
"(",
"[",
"2",
",",
"9",
","... | 36.902439 | 15.243902 |
def select_column(self, column_name):
"""
Get a reference to the :class:`~turicreate.SArray` that corresponds with
the given column_name. Throws an exception if the column_name is
something other than a string or if the column name is not found.
Parameters
----------
... | [
"def",
"select_column",
"(",
"self",
",",
"column_name",
")",
":",
"if",
"not",
"isinstance",
"(",
"column_name",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid column_nametype: must be str\"",
")",
"with",
"cython_context",
"(",
")",
":",
"return",... | 31.828571 | 22.457143 |
def get_account_details(self, account):
""" Get the account details. """
result = {}
try:
luser = self._get_account(account.username)
luser = preload(luser, database=self._database)
except ObjectDoesNotExist:
return result
for i, j in luser.it... | [
"def",
"get_account_details",
"(",
"self",
",",
"account",
")",
":",
"result",
"=",
"{",
"}",
"try",
":",
"luser",
"=",
"self",
".",
"_get_account",
"(",
"account",
".",
"username",
")",
"luser",
"=",
"preload",
"(",
"luser",
",",
"database",
"=",
"sel... | 30 | 16.714286 |
def re_rect(FlowRate, Width, DistCenter, Nu, openchannel):
"""Return the Reynolds Number for a rectangular channel."""
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([FlowRate, ">0", "Flow rate"], [Nu, ">0", "Nu"])
return (4 * FlowRat... | [
"def",
"re_rect",
"(",
"FlowRate",
",",
"Width",
",",
"DistCenter",
",",
"Nu",
",",
"openchannel",
")",
":",
"#Checking input validity - inputs not checked here are checked by",
"#functions this function calls.",
"ut",
".",
"check_range",
"(",
"[",
"FlowRate",
",",
"\">... | 53.5 | 15.875 |
def rlmb_tiny_recurrent():
"""Tiny setting with a recurrent next-frame model."""
hparams = rlmb_ppo_tiny()
hparams.epochs = 1 # Too slow with 2 for regular runs.
hparams.generative_model = "next_frame_basic_recurrent"
hparams.generative_model_params = "next_frame_basic_recurrent"
return hparams | [
"def",
"rlmb_tiny_recurrent",
"(",
")",
":",
"hparams",
"=",
"rlmb_ppo_tiny",
"(",
")",
"hparams",
".",
"epochs",
"=",
"1",
"# Too slow with 2 for regular runs.",
"hparams",
".",
"generative_model",
"=",
"\"next_frame_basic_recurrent\"",
"hparams",
".",
"generative_mode... | 43.142857 | 15.571429 |
def _GetFileSystemCacheIdentifier(self, path_spec):
"""Determines the file system cache identifier for the path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
str: identifier of the VFS object.
"""
string_parts = []
string_parts.append(getattr(path_spec.pa... | [
"def",
"_GetFileSystemCacheIdentifier",
"(",
"self",
",",
"path_spec",
")",
":",
"string_parts",
"=",
"[",
"]",
"string_parts",
".",
"append",
"(",
"getattr",
"(",
"path_spec",
".",
"parent",
",",
"'comparable'",
",",
"''",
")",
")",
"string_parts",
".",
"ap... | 29.066667 | 21.533333 |
def generate_identifier(sender, instance, **kwargs):
"""
Generate and set identifier of concept before saving object to DB
Args:
sender (class): should be Concept
instance (Concept): saving concept
"""
identifier = Concept.create_identifier(instance.query)
qs = Concept.objects.f... | [
"def",
"generate_identifier",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"identifier",
"=",
"Concept",
".",
"create_identifier",
"(",
"instance",
".",
"query",
")",
"qs",
"=",
"Concept",
".",
"objects",
".",
"filter",
"(",
"identifi... | 35.333333 | 15.066667 |
def getReturnPage(context, prior=False):
'''
This tag makes it easy to get return links from within a template without
requiring custom logic inside the view. Just include
{% getReturnPage as returnPage %} and then reference {{ returnPage.url }}
and {{ returnPage.title }} as needed.
'''
... | [
"def",
"getReturnPage",
"(",
"context",
",",
"prior",
"=",
"False",
")",
":",
"siteHistory",
"=",
"getattr",
"(",
"context",
".",
"get",
"(",
"'request'",
",",
"None",
")",
",",
"'session'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'SITE_HISTORY'",
",",
... | 50.666667 | 24.888889 |
def init(config, workdir=None, logfile=None, loglevel=logging.INFO, **kwargs):
"""
Initialize the Lago environment
Args:
config(str): Path to LagoInitFile
workdir(str): Path to initalize the workdir, defaults to "$PWD/.lago"
**kwargs(dict): Pass arguments to :func:`~lago.cmd.do_init... | [
"def",
"init",
"(",
"config",
",",
"workdir",
"=",
"None",
",",
"logfile",
"=",
"None",
",",
"loglevel",
"=",
"logging",
".",
"INFO",
",",
"*",
"*",
"kwargs",
")",
":",
"setup_sdk_logging",
"(",
"logfile",
",",
"loglevel",
")",
"defaults",
"=",
"lago_c... | 32.925926 | 17.814815 |
def calculate_priority(ratios=None, **kwargs):
"Calculates a priority score based on a number of attributes."
if not ratios:
ratios = PRIORITY_FEATURE_WEIGHTS
scores = [DEFAULT_PRIORITY_SCORE]
for key, value in kwargs.items():
if key not in PRIORITY_FEATURE_WEIGHTS:
raise Key... | [
"def",
"calculate_priority",
"(",
"ratios",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"ratios",
":",
"ratios",
"=",
"PRIORITY_FEATURE_WEIGHTS",
"scores",
"=",
"[",
"DEFAULT_PRIORITY_SCORE",
"]",
"for",
"key",
",",
"value",
"in",
"kwargs",
... | 46.583333 | 13.75 |
def needs_repo_fabsetup_custom(func):
'''Decorator, ensures that fabsetup-custom exists and it is a git repo.'''
from fabric.api import local
@wraps(func)
def wrapper(*args, **kwargs):
if not os.path.exists(FABSETUP_CUSTOM_DIR):
msg = '''\
Git repository ~/.fabsetup-custom with conf... | [
"def",
"needs_repo_fabsetup_custom",
"(",
"func",
")",
":",
"from",
"fabric",
".",
"api",
"import",
"local",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
... | 44.887097 | 19.5 |
def get_auth_info(self, **params):
"""https://developers.coinbase.com/api/v2#show-authorization-information"""
response = self._get('v2', 'user', 'auth', params=params)
return self._make_api_object(response, APIObject) | [
"def",
"get_auth_info",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"response",
"=",
"self",
".",
"_get",
"(",
"'v2'",
",",
"'user'",
",",
"'auth'",
",",
"params",
"=",
"params",
")",
"return",
"self",
".",
"_make_api_object",
"(",
"response",
",",... | 59.75 | 12 |
def RemoveKeywordsForName(self, name, keywords):
"""Removes keywords for a name.
Args:
name: A name which should not be associated with some keywords anymore.
keywords: A collection of keywords.
"""
data_store.DB.IndexRemoveKeywordsForName(self.urn, name, keywords) | [
"def",
"RemoveKeywordsForName",
"(",
"self",
",",
"name",
",",
"keywords",
")",
":",
"data_store",
".",
"DB",
".",
"IndexRemoveKeywordsForName",
"(",
"self",
".",
"urn",
",",
"name",
",",
"keywords",
")"
] | 35.875 | 18.375 |
def write_hier_all(self, out=sys.stdout,
len_dash=1, max_depth=None, num_child=None, short_prt=False):
"""Write hierarchy for all GO Terms in obo file."""
# Print: [biological_process, molecular_function, and cellular_component]
for go_id in ['GO:0008150', 'GO:0003674', 'GO... | [
"def",
"write_hier_all",
"(",
"self",
",",
"out",
"=",
"sys",
".",
"stdout",
",",
"len_dash",
"=",
"1",
",",
"max_depth",
"=",
"None",
",",
"num_child",
"=",
"None",
",",
"short_prt",
"=",
"False",
")",
":",
"# Print: [biological_process, molecular_function, a... | 68.833333 | 25.666667 |
def deps_used(self, pkg, used):
"""Create dependencies dictionary
"""
if find_package(pkg + self.meta.sp, self.meta.pkg_path):
if pkg not in self.deps_dict.values():
self.deps_dict[pkg] = used
else:
self.deps_dict[pkg] += used | [
"def",
"deps_used",
"(",
"self",
",",
"pkg",
",",
"used",
")",
":",
"if",
"find_package",
"(",
"pkg",
"+",
"self",
".",
"meta",
".",
"sp",
",",
"self",
".",
"meta",
".",
"pkg_path",
")",
":",
"if",
"pkg",
"not",
"in",
"self",
".",
"deps_dict",
".... | 37.375 | 8.875 |
def install(self, **kwargs):
"""
Installs the app in the current user's account.
"""
if self._dxid is not None:
return dxpy.api.app_install(self._dxid, **kwargs)
else:
return dxpy.api.app_install('app-' + self._name, alias=self._alias, **kwargs) | [
"def",
"install",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_dxid",
"is",
"not",
"None",
":",
"return",
"dxpy",
".",
"api",
".",
"app_install",
"(",
"self",
".",
"_dxid",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"retur... | 37.75 | 16.25 |
def get_texts(self):
""" Parse documents from a .txt file assuming 1 document per line, yielding lists of filtered tokens """
with self.getstream() as text_stream:
for i, line in enumerate(text_stream):
line = to_unicode(line)
line = (TweetCorpus.case_normaliz... | [
"def",
"get_texts",
"(",
"self",
")",
":",
"with",
"self",
".",
"getstream",
"(",
")",
"as",
"text_stream",
":",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"text_stream",
")",
":",
"line",
"=",
"to_unicode",
"(",
"line",
")",
"line",
"=",
"(",
... | 47.111111 | 13.555556 |
def fll(self, value):
"""
Returns loglike of value
"""
self.stochastic.value = value
try:
ll = self.loglike
except ZeroProbability:
ll = -np.infty
self.stochastic.revert()
return ll | [
"def",
"fll",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"stochastic",
".",
"value",
"=",
"value",
"try",
":",
"ll",
"=",
"self",
".",
"loglike",
"except",
"ZeroProbability",
":",
"ll",
"=",
"-",
"np",
".",
"infty",
"self",
".",
"stochastic",
... | 23.545455 | 11.181818 |
def p_array_literal_2(self, p):
"""array_literal : LBRACKET element_list RBRACKET
| LBRACKET element_list COMMA elision_opt RBRACKET
"""
items = p[2]
if len(p) == 6:
items.extend(p[4])
p[0] = self.asttypes.Array(items=items)
p[0].setpo... | [
"def",
"p_array_literal_2",
"(",
"self",
",",
"p",
")",
":",
"items",
"=",
"p",
"[",
"2",
"]",
"if",
"len",
"(",
"p",
")",
"==",
"6",
":",
"items",
".",
"extend",
"(",
"p",
"[",
"4",
"]",
")",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes... | 35.111111 | 12.888889 |
def overlapping_bins(start, stop=None):
"""
Given an interval `start:stop`, return bins for intervals *overlapping*
`start:stop` by at least one position. The order is according to the bin
level (starting with the smallest bins), and within a level according to
the bin number (ascending).
:arg ... | [
"def",
"overlapping_bins",
"(",
"start",
",",
"stop",
"=",
"None",
")",
":",
"if",
"stop",
"is",
"None",
":",
"stop",
"=",
"start",
"+",
"1",
"return",
"[",
"bin",
"for",
"first",
",",
"last",
"in",
"range_per_level",
"(",
"start",
",",
"stop",
")",
... | 37.44 | 24 |
def calculate_rsq(self):
"""calculate_rsq calculates coefficient of determination, or r-squared, defined here as 1.0 - SS_res / SS_tot. rsq is only calculated for those timepoints in the data for which the design matrix is non-zero.
"""
assert hasattr(self, 'betas'), 'no betas found, please run ... | [
"def",
"calculate_rsq",
"(",
"self",
")",
":",
"assert",
"hasattr",
"(",
"self",
",",
"'betas'",
")",
",",
"'no betas found, please run regression before rsq'",
"explained_times",
"=",
"self",
".",
"design_matrix",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
"!=",
... | 76.181818 | 41.272727 |
def multi_split(text, regexes):
"""
Split the text by the given regexes, in priority order.
Make sure that the regex is parenthesized so that matches are returned in
re.split().
Splitting on a single regex works like normal split.
>>> '|'.join(multi_split('one two three', [r'\w+']))
'one| ... | [
"def",
"multi_split",
"(",
"text",
",",
"regexes",
")",
":",
"def",
"make_regex",
"(",
"s",
")",
":",
"return",
"re",
".",
"compile",
"(",
"s",
")",
"if",
"isinstance",
"(",
"s",
",",
"basestring",
")",
"else",
"s",
"regexes",
"=",
"[",
"make_regex",... | 35.045455 | 19.363636 |
def add_entity_meta(self, datastream, options, data):
"""
To add entity meta data to a datastream
:param datastream: string
:param options: dict
:param data: list
"""
url = '/datastream/' + str(datastream) + '/entityMeta'
response = self.http.post(url, dat... | [
"def",
"add_entity_meta",
"(",
"self",
",",
"datastream",
",",
"options",
",",
"data",
")",
":",
"url",
"=",
"'/datastream/'",
"+",
"str",
"(",
"datastream",
")",
"+",
"'/entityMeta'",
"response",
"=",
"self",
".",
"http",
".",
"post",
"(",
"url",
",",
... | 37 | 11.153846 |
def uniform_random_global_points(n=100):
"""
Returns an array of `n` uniformally distributed `shapely.geometry.Point` objects. Points are coordinates
distributed equivalently across the Earth's surface.
"""
xs = np.random.uniform(-180, 180, n)
ys = np.random.uniform(-90, 90, n)
return [shape... | [
"def",
"uniform_random_global_points",
"(",
"n",
"=",
"100",
")",
":",
"xs",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"180",
",",
"180",
",",
"n",
")",
"ys",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"90",
",",
"90",
",",
"... | 45.125 | 13.875 |
def get_cv_pattern(self, word, pprint=False):
"""
input = iparras
pattern = [('V', 1, 'i'), ('C', 1, 'p'), ('V', 2, 'a'), ('C', 2, 'r'),
('C', 2, 'r'), ('V', 2, 'a'), ('C', 3, 's')]
pprint = V₁C₁V₂C₂C₂V₂C₃
"""
subscripts = {
1: '₁',
... | [
"def",
"get_cv_pattern",
"(",
"self",
",",
"word",
",",
"pprint",
"=",
"False",
")",
":",
"subscripts",
"=",
"{",
"1",
":",
"'₁',",
"",
"2",
":",
"'₂',",
"",
"3",
":",
"'₃',",
"",
"4",
":",
"'₄',",
"",
"5",
":",
"'₅',",
"",
"6",
":",
"'₆',",
... | 33.918367 | 18.571429 |
def bytenet_internal(inputs, targets, hparams):
"""ByteNet, main step used for training."""
with tf.variable_scope("bytenet"):
# Flatten inputs and extend length by 50%.
inputs = tf.expand_dims(common_layers.flatten4d3d(inputs), axis=2)
extend_length = tf.to_int32(0.5 * tf.to_float(tf.shape(inputs)[1]))... | [
"def",
"bytenet_internal",
"(",
"inputs",
",",
"targets",
",",
"hparams",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"bytenet\"",
")",
":",
"# Flatten inputs and extend length by 50%.",
"inputs",
"=",
"tf",
".",
"expand_dims",
"(",
"common_layers",
".",... | 51.12 | 20.12 |
def send(self, to, from_, body, dm=False):
"""
Send BODY as an @message from FROM to TO
If we don't have the access tokens for FROM, raise AccountNotFoundError.
If the tweet resulting from '@{0} {1}'.format(TO, BODY) is > 140 chars
raise TweetTooLongError.
If we want to... | [
"def",
"send",
"(",
"self",
",",
"to",
",",
"from_",
",",
"body",
",",
"dm",
"=",
"False",
")",
":",
"tweet",
"=",
"'@{0} {1}'",
".",
"format",
"(",
"to",
",",
"body",
")",
"if",
"from_",
"not",
"in",
"self",
".",
"accounts",
":",
"raise",
"Accou... | 29 | 18.058824 |
def write(self, session, data):
"""Writes data to device or interface synchronously.
Corresponds to viWrite function of the VISA library.
:param session: Unique logical identifier to a session.
:param data: data to be written.
:type data: str
:return: Number of bytes ac... | [
"def",
"write",
"(",
"self",
",",
"session",
",",
"data",
")",
":",
"try",
":",
"sess",
"=",
"self",
".",
"sessions",
"[",
"session",
"]",
"except",
"KeyError",
":",
"return",
"constants",
".",
"StatusCode",
".",
"error_invalid_object",
"try",
":",
"retu... | 34.047619 | 20.47619 |
def process_orders(self, orderbook):
''' Default and costant orders processor. Overwrite it for more
sophisticated strategies '''
for stock, alloc in orderbook.iteritems():
self.logger.info('{}: Ordered {} {} stocks'.format(
self.datetime, stock, alloc))
i... | [
"def",
"process_orders",
"(",
"self",
",",
"orderbook",
")",
":",
"for",
"stock",
",",
"alloc",
"in",
"orderbook",
".",
"iteritems",
"(",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'{}: Ordered {} {} stocks'",
".",
"format",
"(",
"self",
".",
"d... | 45.466667 | 10.4 |
def previous_unwrittable_on_col(view, coords):
"""Return position of the previous (in column) letter that is unwrittable"""
x, y = coords
miny = -1
for offset in range(y - 1, miny, -1):
letter = view[x, offset]
if letter not in REWRITABLE_LETTERS:
return offset
return Non... | [
"def",
"previous_unwrittable_on_col",
"(",
"view",
",",
"coords",
")",
":",
"x",
",",
"y",
"=",
"coords",
"miny",
"=",
"-",
"1",
"for",
"offset",
"in",
"range",
"(",
"y",
"-",
"1",
",",
"miny",
",",
"-",
"1",
")",
":",
"letter",
"=",
"view",
"[",... | 34.777778 | 12.111111 |
def get_clusters_interfaces(clusters, extra_cond=lambda nic: True):
""" Returns for each cluster the available cluster interfaces
Args:
clusters (str): list of the clusters
extra_cond (lambda): extra predicate to filter network card retrieved
from the API. E.g lambda nic: not nic['mounted']... | [
"def",
"get_clusters_interfaces",
"(",
"clusters",
",",
"extra_cond",
"=",
"lambda",
"nic",
":",
"True",
")",
":",
"interfaces",
"=",
"{",
"}",
"for",
"cluster",
"in",
"clusters",
":",
"nics",
"=",
"get_cluster_interfaces",
"(",
"cluster",
",",
"extra_cond",
... | 32.407407 | 22.555556 |
def azimuth(self, point):
"""
Compute the azimuth (in decimal degrees) between this point
and the given point.
:param point:
Destination point.
:type point:
Instance of :class:`Point`
:returns:
The azimuth, value in a range ``[0, 360)`... | [
"def",
"azimuth",
"(",
"self",
",",
"point",
")",
":",
"return",
"geodetic",
".",
"azimuth",
"(",
"self",
".",
"longitude",
",",
"self",
".",
"latitude",
",",
"point",
".",
"longitude",
",",
"point",
".",
"latitude",
")"
] | 30.0625 | 17.3125 |
def write(self, stream):
'''
Write PLY data to a writeable file-like object or filename.
'''
(must_close, stream) = _open_stream(stream, 'write')
try:
stream.write(self.header.encode('ascii'))
stream.write(b'\n')
for elt in self:
... | [
"def",
"write",
"(",
"self",
",",
"stream",
")",
":",
"(",
"must_close",
",",
"stream",
")",
"=",
"_open_stream",
"(",
"stream",
",",
"'write'",
")",
"try",
":",
"stream",
".",
"write",
"(",
"self",
".",
"header",
".",
"encode",
"(",
"'ascii'",
")",
... | 30.785714 | 20.928571 |
def drawBezier(page, p1, p2, p3, p4, color=None, fill=None,
dashes=None, width=1, morph=None,
closePath=False, roundCap=False, overlay=True):
"""Draw a general cubic Bezier curve from p1 to p4 using control points p2 and p3.
"""
img = page.newShape()
Q = img.drawBezier(Poin... | [
"def",
"drawBezier",
"(",
"page",
",",
"p1",
",",
"p2",
",",
"p3",
",",
"p4",
",",
"color",
"=",
"None",
",",
"fill",
"=",
"None",
",",
"dashes",
"=",
"None",
",",
"width",
"=",
"1",
",",
"morph",
"=",
"None",
",",
"closePath",
"=",
"False",
",... | 43.75 | 18.666667 |
def _setup_argparse(self):
"""Create `argparse` instance, and setup with appropriate parameters.
"""
parser = argparse.ArgumentParser(
prog='catalog', description='Parent Catalog class for astrocats.')
subparsers = parser.add_subparsers(
description='valid subcom... | [
"def",
"_setup_argparse",
"(",
"self",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"'catalog'",
",",
"description",
"=",
"'Parent Catalog class for astrocats.'",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
"descr... | 32.333333 | 19.416667 |
def create_image_stream(self, name, docker_image_repository,
insecure_registry=False):
"""
Create an ImageStream object
Raises exception on error
:param name: str, name of ImageStream
:param docker_image_repository: str, pull spec for docker image
... | [
"def",
"create_image_stream",
"(",
"self",
",",
"name",
",",
"docker_image_repository",
",",
"insecure_registry",
"=",
"False",
")",
":",
"img_stream_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"os_conf",
".",
"get_build_json_store",
"(",
")"... | 42.217391 | 20.304348 |
def name(self):
"""Returns the name of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Device name.
"""
return ctypes.cast(self.sName, ctypes.c_char_p).value.decode() | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"ctypes",
".",
"cast",
"(",
"self",
".",
"sName",
",",
"ctypes",
".",
"c_char_p",
")",
".",
"value",
".",
"decode",
"(",
")"
] | 25.5 | 23 |
def unaccentuate(s):
""" Replace accentuated chars in string by their non accentuated equivalent. """
return "".join(c for c in unicodedata.normalize("NFKD", s) if not unicodedata.combining(c)) | [
"def",
"unaccentuate",
"(",
"s",
")",
":",
"return",
"\"\"",
".",
"join",
"(",
"c",
"for",
"c",
"in",
"unicodedata",
".",
"normalize",
"(",
"\"NFKD\"",
",",
"s",
")",
"if",
"not",
"unicodedata",
".",
"combining",
"(",
"c",
")",
")"
] | 66.333333 | 25 |
def add_output_file(self, filename):
"""
Add filename as a output file for this DAG node.
@param filename: output filename to add
"""
if filename not in self.__output_files:
self.__output_files.append(filename)
if not isinstance(self.job(), CondorDAGManJob):
if self.job().get_un... | [
"def",
"add_output_file",
"(",
"self",
",",
"filename",
")",
":",
"if",
"filename",
"not",
"in",
"self",
".",
"__output_files",
":",
"self",
".",
"__output_files",
".",
"append",
"(",
"filename",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"job",
"... | 33.727273 | 7.727273 |
def readTuple(self, line, n=3):
""" Reads a tuple of numbers. e.g. vertices, normals or teture coords.
"""
numbers = [num for num in line.split(' ') if num]
return [float(num) for num in numbers[1:n + 1]] | [
"def",
"readTuple",
"(",
"self",
",",
"line",
",",
"n",
"=",
"3",
")",
":",
"numbers",
"=",
"[",
"num",
"for",
"num",
"in",
"line",
".",
"split",
"(",
"' '",
")",
"if",
"num",
"]",
"return",
"[",
"float",
"(",
"num",
")",
"for",
"num",
"in",
... | 46.4 | 8.2 |
def compose_MDAL_dic(self, site, point_type,
start, end, var, agg, window, aligned, points=None, return_names=False):
""" Create dictionary for MDAL request.
Parameters
----------
site : str
Building name.
start : str
... | [
"def",
"compose_MDAL_dic",
"(",
"self",
",",
"site",
",",
"point_type",
",",
"start",
",",
"end",
",",
"var",
",",
"agg",
",",
"window",
",",
"aligned",
",",
"points",
"=",
"None",
",",
"return_names",
"=",
"False",
")",
":",
"# Convert time to UTC",
"st... | 37.41791 | 22.58209 |
def _PartitionChunks(chunks):
"""Groups chunks into partitions of size safe for a single INSERT."""
partitions = [[]]
partition_size = 0
for chunk in chunks:
cursize = len(chunk["blob_chunk"])
if (cursize + partition_size > BLOB_CHUNK_SIZE or
len(partitions[-1]) >= CHUNKS_PER_INSERT):
par... | [
"def",
"_PartitionChunks",
"(",
"chunks",
")",
":",
"partitions",
"=",
"[",
"[",
"]",
"]",
"partition_size",
"=",
"0",
"for",
"chunk",
"in",
"chunks",
":",
"cursize",
"=",
"len",
"(",
"chunk",
"[",
"\"blob_chunk\"",
"]",
")",
"if",
"(",
"cursize",
"+",... | 28.866667 | 16.266667 |
def find_valid_random_signature(s: int) -> Tuple[int, int]:
"""
Find v and r valid values for a given s
:param s: random value
:return: v, r
"""
for _ in range(10000):
r = int(os.urandom(31).hex(), 16)
v = (r % 2) + 27
if r < secpk1n:
... | [
"def",
"find_valid_random_signature",
"(",
"s",
":",
"int",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
"]",
":",
"for",
"_",
"in",
"range",
"(",
"10000",
")",
":",
"r",
"=",
"int",
"(",
"os",
".",
"urandom",
"(",
"31",
")",
".",
"hex",
"(",
")... | 37.222222 | 16.444444 |
def force_text(s, encoding='utf-8', errors='strict'):
"""
Similar to smart_text, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if isinstance(s, text_type):
return s
tr... | [
"def",
"force_text",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"text_type",
")",
":",
"return",
"s",
"try",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"string_types",
"... | 32.933333 | 15.333333 |
def has_been(s, since, dt=None):
'''
A parser to check whether a (cron-like) string has been true during a certain time period.
Useful for applications which cannot check every minute or need to catch up during a restart.
@input:
s = cron-like string (minute, hour, day of month, month, day of we... | [
"def",
"has_been",
"(",
"s",
",",
"since",
",",
"dt",
"=",
"None",
")",
":",
"if",
"dt",
"is",
"None",
":",
"dt",
"=",
"datetime",
".",
"now",
"(",
"tz",
"=",
"since",
".",
"tzinfo",
")",
"if",
"dt",
"<",
"since",
":",
"raise",
"ValueError",
"(... | 36 | 27.909091 |
def val(self, piece, ref_color):
"""
Finds value of ``Piece``
:type: piece: Piece
:type: ref_color: Color
:rtype: int
"""
if piece is None:
return 0
if ref_color == piece.color:
const = 1
else:
const = -1
... | [
"def",
"val",
"(",
"self",
",",
"piece",
",",
"ref_color",
")",
":",
"if",
"piece",
"is",
"None",
":",
"return",
"0",
"if",
"ref_color",
"==",
"piece",
".",
"color",
":",
"const",
"=",
"1",
"else",
":",
"const",
"=",
"-",
"1",
"if",
"isinstance",
... | 27.517241 | 11.655172 |
def bin(self):
"""Full-length binary representation of the IP address.
>>> ip = IP("127.0.0.1")
>>> print(ip.bin())
01111111000000000000000000000001
"""
bits = self.v == 4 and 32 or 128
return bin(self.ip).split('b')[1].rjust(bits, '0') | [
"def",
"bin",
"(",
"self",
")",
":",
"bits",
"=",
"self",
".",
"v",
"==",
"4",
"and",
"32",
"or",
"128",
"return",
"bin",
"(",
"self",
".",
"ip",
")",
".",
"split",
"(",
"'b'",
")",
"[",
"1",
"]",
".",
"rjust",
"(",
"bits",
",",
"'0'",
")"
... | 31.666667 | 11.666667 |
def trace_memory_stop(self):
""" Stops measuring memory consumption """
self.trace_memory_clean_caches()
objgraph.show_growth(limit=30)
trace_type = context.get_current_config()["trace_memory_type"]
if trace_type:
filename = '%s/%s-%s.png' % (
cont... | [
"def",
"trace_memory_stop",
"(",
"self",
")",
":",
"self",
".",
"trace_memory_clean_caches",
"(",
")",
"objgraph",
".",
"show_growth",
"(",
"limit",
"=",
"30",
")",
"trace_type",
"=",
"context",
".",
"get_current_config",
"(",
")",
"[",
"\"trace_memory_type\"",
... | 28.585366 | 21.560976 |
def revert(self, strip=0, root=None):
""" apply patch in reverse order """
reverted = copy.deepcopy(self)
reverted._reverse()
return reverted.apply(strip, root) | [
"def",
"revert",
"(",
"self",
",",
"strip",
"=",
"0",
",",
"root",
"=",
"None",
")",
":",
"reverted",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"reverted",
".",
"_reverse",
"(",
")",
"return",
"reverted",
".",
"apply",
"(",
"strip",
",",
"roo... | 34.4 | 5.6 |
def get_ip_address(ifname):
""" Hack to get IP address from the interface """
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24]) | [
"def",
"get_ip_address",
"(",
"ifname",
")",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"return",
"socket",
".",
"inet_ntoa",
"(",
"fcntl",
".",
"ioctl",
"(",
"s",
".",
"fileno",
"(",
... | 30.888889 | 14.111111 |
def load_file(self, dfile, incremental=False):
"""
Loads the specified file and returns the Instances object.
In case of incremental loading, only the structure.
:param dfile: the file to load
:type dfile: str
:param incremental: whether to load the dataset incrementally... | [
"def",
"load_file",
"(",
"self",
",",
"dfile",
",",
"incremental",
"=",
"False",
")",
":",
"self",
".",
"enforce_type",
"(",
"self",
".",
"jobject",
",",
"\"weka.core.converters.FileSourcedConverter\"",
")",
"self",
".",
"incremental",
"=",
"incremental",
"if",
... | 51.172414 | 22.689655 |
def answer(self) -> str:
"""Get a random answer in current language.
:return: An answer.
:Example:
No
"""
answers = self._data['answers']
return self.random.choice(answers) | [
"def",
"answer",
"(",
"self",
")",
"->",
"str",
":",
"answers",
"=",
"self",
".",
"_data",
"[",
"'answers'",
"]",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"answers",
")"
] | 22.5 | 16.1 |
def _merge_csv_column(table, csvs):
"""
Add csv data to each column in a list of columns
:param dict table: Table metadata
:param str crumbs: Hierarchy crumbs
:param str pc: Paleo or Chron table type
:return dict: Table metadata with csv "values" entry
:return bool ensemble: Ensemble data o... | [
"def",
"_merge_csv_column",
"(",
"table",
",",
"csvs",
")",
":",
"# Start putting CSV data into corresponding column \"values\" key",
"try",
":",
"ensemble",
"=",
"is_ensemble",
"(",
"table",
"[",
"\"columns\"",
"]",
")",
"if",
"ensemble",
":",
"# realization columns",
... | 46.836735 | 21.734694 |
def convert_outlook_msg(msg_bytes):
"""
Uses the ``msgconvert`` Perl utility to convert an Outlook MS file to
standard RFC 822 format
Args:
msg_bytes (bytes): the content of the .msg file
Returns:
A RFC 822 string
"""
if not is_outlook_msg(msg_bytes):
raise ValueErr... | [
"def",
"convert_outlook_msg",
"(",
"msg_bytes",
")",
":",
"if",
"not",
"is_outlook_msg",
"(",
"msg_bytes",
")",
":",
"raise",
"ValueError",
"(",
"\"The supplied bytes are not an Outlook MSG file\"",
")",
"orig_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"tmp_dir",
"... | 30.6875 | 18 |
def serialize(self):
"""Return the string representation of the receiver."""
res = '<?xml version="1.0" encoding="UTF-8"?>'
for ns in self.namespaces:
self.top_grammar.attr["xmlns:" + self.namespaces[ns]] = ns
res += self.top_grammar.start_tag()
for ch in self.top_gra... | [
"def",
"serialize",
"(",
"self",
")",
":",
"res",
"=",
"'<?xml version=\"1.0\" encoding=\"UTF-8\"?>'",
"for",
"ns",
"in",
"self",
".",
"namespaces",
":",
"self",
".",
"top_grammar",
".",
"attr",
"[",
"\"xmlns:\"",
"+",
"self",
".",
"namespaces",
"[",
"ns",
"... | 43.571429 | 9.071429 |
def __boost(self, grad, hess):
"""Boost Booster for one iteration with customized gradient statistics.
Note
----
For multi-class task, the score is group by class_id first, then group by row_id.
If you want to get i-th row score in j-th class, the access way is score[j * num_dat... | [
"def",
"__boost",
"(",
"self",
",",
"grad",
",",
"hess",
")",
":",
"grad",
"=",
"list_to_1d_numpy",
"(",
"grad",
",",
"name",
"=",
"'gradient'",
")",
"hess",
"=",
"list_to_1d_numpy",
"(",
"hess",
",",
"name",
"=",
"'hessian'",
")",
"assert",
"grad",
".... | 41.305556 | 19.194444 |
def verify_order(self, hostname, domain, location, hourly, flavor, router=None):
"""Verifies an order for a dedicated host.
See :func:`place_order` for a list of available options.
"""
create_options = self._generate_create_dict(hostname=hostname,
... | [
"def",
"verify_order",
"(",
"self",
",",
"hostname",
",",
"domain",
",",
"location",
",",
"hourly",
",",
"flavor",
",",
"router",
"=",
"None",
")",
":",
"create_options",
"=",
"self",
".",
"_generate_create_dict",
"(",
"hostname",
"=",
"hostname",
",",
"ro... | 48.714286 | 27.214286 |
def unblock_events(self):
"""
Allows the widget to send signals.
"""
self._widget.blockSignals(False)
self._widget.setUpdatesEnabled(True) | [
"def",
"unblock_events",
"(",
"self",
")",
":",
"self",
".",
"_widget",
".",
"blockSignals",
"(",
"False",
")",
"self",
".",
"_widget",
".",
"setUpdatesEnabled",
"(",
"True",
")"
] | 28.833333 | 3.5 |
def wiki_create(self, title, body, other_names=None):
"""Action to lets you create a wiki page (Requires login) (UNTESTED).
Parameters:
title (str): Page title.
body (str): Page content.
other_names (str): Other names.
"""
params = {
'wiki... | [
"def",
"wiki_create",
"(",
"self",
",",
"title",
",",
"body",
",",
"other_names",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'wiki_page[title]'",
":",
"title",
",",
"'wiki_page[body]'",
":",
"body",
",",
"'wiki_page[other_names]'",
":",
"other_names",
"}",
... | 36.214286 | 13.214286 |
def get_webhook(self, scaling_group, policy, webhook):
"""
Gets the detail for the specified webhook.
"""
return self._manager.get_webhook(scaling_group, policy, webhook) | [
"def",
"get_webhook",
"(",
"self",
",",
"scaling_group",
",",
"policy",
",",
"webhook",
")",
":",
"return",
"self",
".",
"_manager",
".",
"get_webhook",
"(",
"scaling_group",
",",
"policy",
",",
"webhook",
")"
] | 39.6 | 11.2 |
def apply_same_chip_constraints(vertices_resources, nets, constraints):
"""Modify a set of vertices_resources, nets and constraints to account for
all SameChipConstraints.
To allow placement algorithms to handle SameChipConstraints without any
special cases, Vertices identified in a SameChipConstraint ... | [
"def",
"apply_same_chip_constraints",
"(",
"vertices_resources",
",",
"nets",
",",
"constraints",
")",
":",
"# Make a copy of the basic structures to be modified by this function",
"vertices_resources",
"=",
"vertices_resources",
".",
"copy",
"(",
")",
"nets",
"=",
"nets",
... | 43.081301 | 23.463415 |
def _load_script(self, filename: str) -> Script:
"""Load a Lua script.
Read the Lua script file to generate its Script object. If the script
starts with a magic string, add it to the list of scripts requiring an
idempotency token to execute.
"""
with open(path.join(here,... | [
"def",
"_load_script",
"(",
"self",
",",
"filename",
":",
"str",
")",
"->",
"Script",
":",
"with",
"open",
"(",
"path",
".",
"join",
"(",
"here",
",",
"'redis_scripts'",
",",
"filename",
")",
",",
"mode",
"=",
"'rb'",
")",
"as",
"f",
":",
"script_dat... | 45.076923 | 19.230769 |
def _outputs(self):
"""List of layers containing outputs from the IF.
:returns: A list of vector layers.
:rtype: list
"""
layers = OrderedDict()
layers[layer_purpose_exposure_summary['key']] = (
self._exposure_summary)
layers[layer_purpose_aggregate_h... | [
"def",
"_outputs",
"(",
"self",
")",
":",
"layers",
"=",
"OrderedDict",
"(",
")",
"layers",
"[",
"layer_purpose_exposure_summary",
"[",
"'key'",
"]",
"]",
"=",
"(",
"self",
".",
"_exposure_summary",
")",
"layers",
"[",
"layer_purpose_aggregate_hazard_impacted",
... | 41.486486 | 17.540541 |
def smart_email_send(self, smart_email_id, to, consent_to_track, cc=None, bcc=None, attachments=None, data=None, add_recipients_to_list=None):
"""Sends the smart email."""
validate_consent_to_track(consent_to_track)
body = {
"To": to,
"CC": cc,
"BCC": bcc,
... | [
"def",
"smart_email_send",
"(",
"self",
",",
"smart_email_id",
",",
"to",
",",
"consent_to_track",
",",
"cc",
"=",
"None",
",",
"bcc",
"=",
"None",
",",
"attachments",
"=",
"None",
",",
"data",
"=",
"None",
",",
"add_recipients_to_list",
"=",
"None",
")",
... | 43.533333 | 21.266667 |
def NewFromJSON(data):
"""
Create a new Comment instance from a JSON dict.
Args:
data (dict): JSON dictionary representing a Comment.
Returns:
A Comment instance.
"""
return Comment(
body=data.get('body', None),
posted_at=... | [
"def",
"NewFromJSON",
"(",
"data",
")",
":",
"return",
"Comment",
"(",
"body",
"=",
"data",
".",
"get",
"(",
"'body'",
",",
"None",
")",
",",
"posted_at",
"=",
"data",
".",
"get",
"(",
"'posted_at'",
",",
"None",
")",
",",
"user",
"=",
"User",
".",... | 26.8 | 18.133333 |
def CheckBlobsExist(self, blob_ids):
"""Checks if given blobs exit."""
result = {}
for blob_id in blob_ids:
result[blob_id] = blob_id in self.blobs
return result | [
"def",
"CheckBlobsExist",
"(",
"self",
",",
"blob_ids",
")",
":",
"result",
"=",
"{",
"}",
"for",
"blob_id",
"in",
"blob_ids",
":",
"result",
"[",
"blob_id",
"]",
"=",
"blob_id",
"in",
"self",
".",
"blobs",
"return",
"result"
] | 22.25 | 18.625 |
def parent(self):
"""A new URL with last part of path removed and cleaned up query and
fragment.
"""
path = self.raw_path
if not path or path == "/":
if self.raw_fragment or self.raw_query_string:
return URL(self._val._replace(query="", fragment=""), ... | [
"def",
"parent",
"(",
"self",
")",
":",
"path",
"=",
"self",
".",
"raw_path",
"if",
"not",
"path",
"or",
"path",
"==",
"\"/\"",
":",
"if",
"self",
".",
"raw_fragment",
"or",
"self",
".",
"raw_query_string",
":",
"return",
"URL",
"(",
"self",
".",
"_v... | 38.307692 | 18.076923 |
def wikilinks(self) -> List['WikiLink']:
"""Return a list of wikilink objects."""
_lststr = self._lststr
_type_to_spans = self._type_to_spans
return [
WikiLink(_lststr, _type_to_spans, span, 'WikiLink')
for span in self._subspans('WikiLink')] | [
"def",
"wikilinks",
"(",
"self",
")",
"->",
"List",
"[",
"'WikiLink'",
"]",
":",
"_lststr",
"=",
"self",
".",
"_lststr",
"_type_to_spans",
"=",
"self",
".",
"_type_to_spans",
"return",
"[",
"WikiLink",
"(",
"_lststr",
",",
"_type_to_spans",
",",
"span",
",... | 41.714286 | 10.285714 |
def negative_sharpe(
weights, expected_returns, cov_matrix, gamma=0, risk_free_rate=0.02
):
"""
Calculate the negative Sharpe ratio of a portfolio
:param weights: asset weights of the portfolio
:type weights: np.ndarray
:param expected_returns: expected return of each asset
:type expected_r... | [
"def",
"negative_sharpe",
"(",
"weights",
",",
"expected_returns",
",",
"cov_matrix",
",",
"gamma",
"=",
"0",
",",
"risk_free_rate",
"=",
"0.02",
")",
":",
"mu",
"=",
"weights",
".",
"dot",
"(",
"expected_returns",
")",
"sigma",
"=",
"np",
".",
"sqrt",
"... | 39.958333 | 15.791667 |
def extract_files(files):
"""Expand list of paths to include all text files matching the pattern."""
expanded_files = []
legal_extensions = [".md", ".txt", ".rtf", ".html", ".tex", ".markdown"]
for f in files:
# If it's a directory, recursively walk through it and find the files.
if os.... | [
"def",
"extract_files",
"(",
"files",
")",
":",
"expanded_files",
"=",
"[",
"]",
"legal_extensions",
"=",
"[",
"\".md\"",
",",
"\".txt\"",
",",
"\".rtf\"",
",",
"\".html\"",
",",
"\".tex\"",
",",
"\".markdown\"",
"]",
"for",
"f",
"in",
"files",
":",
"# If ... | 39.15 | 20.35 |
def _find_relation_factory(module):
"""
Attempt to find a RelationFactory subclass in the module.
Note: RelationFactory and RelationBase are ignored so they may
be imported to be used as base classes without fear.
"""
if not module:
return None
# All the RelationFactory subclasses
... | [
"def",
"_find_relation_factory",
"(",
"module",
")",
":",
"if",
"not",
"module",
":",
"return",
"None",
"# All the RelationFactory subclasses",
"candidates",
"=",
"[",
"o",
"for",
"o",
"in",
"(",
"getattr",
"(",
"module",
",",
"attr",
")",
"for",
"attr",
"in... | 37.117647 | 20.470588 |
def simple_mult(A, B, start):
""" Builds a slow, small multiplier using the simple shift-and-add algorithm.
Requires very small area (it uses only a single adder), but has long delay
(worst case is len(A) cycles). start is a one-bit input to indicate inputs are ready.
done is a one-bit output signal rai... | [
"def",
"simple_mult",
"(",
"A",
",",
"B",
",",
"start",
")",
":",
"triv_result",
"=",
"_trivial_mult",
"(",
"A",
",",
"B",
")",
"if",
"triv_result",
"is",
"not",
"None",
":",
"return",
"triv_result",
",",
"pyrtl",
".",
"Const",
"(",
"1",
",",
"1",
... | 39.138889 | 20.305556 |
def get_undeclared_type(self, item):
"""
Checks if a typed has already been declared in the python output
or is a builtin python type.
"""
if item in self.done:
return None
if isinstance(item, typedesc.FundamentalType):
return None
if isins... | [
"def",
"get_undeclared_type",
"(",
"self",
",",
"item",
")",
":",
"if",
"item",
"in",
"self",
".",
"done",
":",
"return",
"None",
"if",
"isinstance",
"(",
"item",
",",
"typedesc",
".",
"FundamentalType",
")",
":",
"return",
"None",
"if",
"isinstance",
"(... | 37.4 | 11.133333 |
def connected_ids(self, subset=None, show_ip=False, show_ipv4=None, include_localhost=None):
'''
Return a set of all connected minion ids, optionally within a subset
'''
if include_localhost is not None:
salt.utils.versions.warn_until(
'Sodium',
... | [
"def",
"connected_ids",
"(",
"self",
",",
"subset",
"=",
"None",
",",
"show_ip",
"=",
"False",
",",
"show_ipv4",
"=",
"None",
",",
"include_localhost",
"=",
"None",
")",
":",
"if",
"include_localhost",
"is",
"not",
"None",
":",
"salt",
".",
"utils",
".",... | 45.966667 | 18.833333 |
def _buildItem(self, elem, cls=None, initpath=None):
""" Factory function to build objects based on registered PLEXOBJECTS. """
# cls is specified, build the object and return
initpath = initpath or self._initpath
if cls is not None:
return cls(self._server, elem, initpath)
... | [
"def",
"_buildItem",
"(",
"self",
",",
"elem",
",",
"cls",
"=",
"None",
",",
"initpath",
"=",
"None",
")",
":",
"# cls is specified, build the object and return",
"initpath",
"=",
"initpath",
"or",
"self",
".",
"_initpath",
"if",
"cls",
"is",
"not",
"None",
... | 58.714286 | 19.285714 |
def getScreenRGB(self,screen_data=None):
"""This function fills screen_data with the data
screen_data MUST be a numpy array of uint32/int32. This can be initialized like so:
screen_data = np.array(w*h,dtype=np.uint32)
Notice, it must be width*height in size also
If it is None, th... | [
"def",
"getScreenRGB",
"(",
"self",
",",
"screen_data",
"=",
"None",
")",
":",
"if",
"(",
"screen_data",
"is",
"None",
")",
":",
"width",
"=",
"ale_lib",
".",
"getScreenWidth",
"(",
"self",
".",
"obj",
")",
"height",
"=",
"ale_lib",
".",
"getScreenWidth"... | 49.923077 | 14.307692 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.