text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def style_classpath(self, products, scheduler):
"""Returns classpath as paths for scalastyle."""
classpath_entries = self._tool_classpath('scalastyle', products, scheduler)
return [classpath_entry.path for classpath_entry in classpath_entries] | [
"def",
"style_classpath",
"(",
"self",
",",
"products",
",",
"scheduler",
")",
":",
"classpath_entries",
"=",
"self",
".",
"_tool_classpath",
"(",
"'scalastyle'",
",",
"products",
",",
"scheduler",
")",
"return",
"[",
"classpath_entry",
".",
"path",
"for",
"cl... | 63 | 20 |
def is_canonical_address(address: Any) -> bool:
"""
Returns `True` if the `value` is an address in its canonical form.
"""
if not is_bytes(address) or len(address) != 20:
return False
return address == to_canonical_address(address) | [
"def",
"is_canonical_address",
"(",
"address",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"not",
"is_bytes",
"(",
"address",
")",
"or",
"len",
"(",
"address",
")",
"!=",
"20",
":",
"return",
"False",
"return",
"address",
"==",
"to_canonical_address",
"(",
... | 36.142857 | 11.285714 |
def build_columns(self, X, verbose=False):
"""construct the model matrix columns for the term
Parameters
----------
X : array-like
Input dataset with n rows
verbose : bool
whether to show warnings
Returns
-------
scipy sparse arr... | [
"def",
"build_columns",
"(",
"self",
",",
"X",
",",
"verbose",
"=",
"False",
")",
":",
"return",
"sp",
".",
"sparse",
".",
"csc_matrix",
"(",
"X",
"[",
":",
",",
"self",
".",
"feature",
"]",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
")"
] | 25.125 | 18.1875 |
def cancel(self, job_ids):
"""Cancel the jobs specified by a list of job ids.
Parameters
----------
job_ids : list of str
List of of job identifiers
Returns
-------
list of bool
Each entry in the list will contain False if the operation f... | [
"def",
"cancel",
"(",
"self",
",",
"job_ids",
")",
":",
"if",
"self",
".",
"linger",
"is",
"True",
":",
"logger",
".",
"debug",
"(",
"\"Ignoring cancel requests due to linger mode\"",
")",
"return",
"[",
"False",
"for",
"x",
"in",
"job_ids",
"]",
"try",
":... | 30.727273 | 23.666667 |
def get_link_mappings(link_id, link_2_id=None, **kwargs):
"""
Get all the resource attribute mappings in a network. If another network
is specified, only return the mappings between the two networks.
"""
qry = db.DBSession.query(ResourceAttrMap).filter(
or_(
and_(
... | [
"def",
"get_link_mappings",
"(",
"link_id",
",",
"link_2_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"qry",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"ResourceAttrMap",
")",
".",
"filter",
"(",
"or_",
"(",
"and_",
"(",
"ResourceAttrMap",
... | 38.48 | 20.48 |
def strip_prompt(self, a_string):
"""Strip the trailing router prompt from the output."""
expect_string = r"^(OK|ERROR|Command not recognized\.)$"
response_list = a_string.split(self.RESPONSE_RETURN)
last_line = response_list[-1]
if re.search(expect_string, last_line):
... | [
"def",
"strip_prompt",
"(",
"self",
",",
"a_string",
")",
":",
"expect_string",
"=",
"r\"^(OK|ERROR|Command not recognized\\.)$\"",
"response_list",
"=",
"a_string",
".",
"split",
"(",
"self",
".",
"RESPONSE_RETURN",
")",
"last_line",
"=",
"response_list",
"[",
"-",... | 45.333333 | 13.888889 |
def learn(self, *args, **kwargs):
"""[DEPRECATED] Use 'fit_predict'.
"""
warnings.warn("learn is deprecated, {}.fit_predict "
"instead".format(self.__class__.__name__))
return self.fit_predict(*args, **kwargs) | [
"def",
"learn",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"learn is deprecated, {}.fit_predict \"",
"\"instead\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"return",
"s... | 36.857143 | 14.142857 |
def optimal_t(self, seq_p, seq_ch, pattern_multiplicity=None, ignore_gaps=False):
'''
Find the optimal distance between the two sequences
Parameters
----------
seq_p : character array
Parent sequence
seq_c : character array
Child sequence
... | [
"def",
"optimal_t",
"(",
"self",
",",
"seq_p",
",",
"seq_ch",
",",
"pattern_multiplicity",
"=",
"None",
",",
"ignore_gaps",
"=",
"False",
")",
":",
"seq_pair",
",",
"multiplicity",
"=",
"self",
".",
"compress_sequence_pair",
"(",
"seq_p",
",",
"seq_ch",
",",... | 38.407407 | 28.555556 |
def create_server_rackspace(connection,
distribution,
disk_name,
disk_size,
ami,
region,
key_pair,
instance_type,
... | [
"def",
"create_server_rackspace",
"(",
"connection",
",",
"distribution",
",",
"disk_name",
",",
"disk_size",
",",
"ami",
",",
"region",
",",
"key_pair",
",",
"instance_type",
",",
"instance_name",
",",
"tags",
"=",
"{",
"}",
",",
"security_groups",
"=",
"None... | 33.723404 | 16.574468 |
def set_property_filter(filter_proto, name, op, value):
"""Set property filter contraint in the given datastore.Filter proto message.
Args:
filter_proto: datastore.Filter proto message
name: property name
op: datastore.PropertyFilter.Operation
value: property value
Returns:
the same datastor... | [
"def",
"set_property_filter",
"(",
"filter_proto",
",",
"name",
",",
"op",
",",
"value",
")",
":",
"filter_proto",
".",
"Clear",
"(",
")",
"pf",
"=",
"filter_proto",
".",
"property_filter",
"pf",
".",
"property",
".",
"name",
"=",
"name",
"pf",
".",
"op"... | 26.818182 | 18.818182 |
def start(self, positionals=None):
'''start the helper flow. We check helper system configurations to
determine components that should be collected for the submission.
This is where the client can also pass on any extra (positional)
arguments in a list from the user.
'''... | [
"def",
"start",
"(",
"self",
",",
"positionals",
"=",
"None",
")",
":",
"bot",
".",
"info",
"(",
"'[helpme|%s]'",
"%",
"(",
"self",
".",
"name",
")",
")",
"self",
".",
"speak",
"(",
")",
"self",
".",
"_start",
"(",
"positionals",
")"
] | 45.666667 | 19.666667 |
def clear_scroll(self, scroll_id=None, body=None, **query_params):
"""
Clear the scroll request created by specifying the scroll parameter to
search.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html>`_
:param scroll_id: A comma-separated... | [
"def",
"clear_scroll",
"(",
"self",
",",
"scroll_id",
"=",
"None",
",",
"body",
"=",
"None",
",",
"*",
"*",
"query_params",
")",
":",
"if",
"scroll_id",
"in",
"NULL_VALUES",
"and",
"body",
"in",
"NULL_VALUES",
":",
"raise",
"ValueError",
"(",
"\"You need t... | 50.052632 | 24.789474 |
def unfollow(user, obj):
""" Make a user unfollow an object """
try:
follow = Follow.objects.get_follows(obj).get(user=user)
follow.delete()
return follow
except Follow.DoesNotExist:
pass | [
"def",
"unfollow",
"(",
"user",
",",
"obj",
")",
":",
"try",
":",
"follow",
"=",
"Follow",
".",
"objects",
".",
"get_follows",
"(",
"obj",
")",
".",
"get",
"(",
"user",
"=",
"user",
")",
"follow",
".",
"delete",
"(",
")",
"return",
"follow",
"excep... | 28.125 | 17.875 |
def cfgGetBool(theObj, name, dflt):
""" Get a stringified val from a ConfigObj obj and return it as bool """
strval = theObj.get(name, None)
if strval is None:
return dflt
return strval.lower().strip() == 'true' | [
"def",
"cfgGetBool",
"(",
"theObj",
",",
"name",
",",
"dflt",
")",
":",
"strval",
"=",
"theObj",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
"strval",
"is",
"None",
":",
"return",
"dflt",
"return",
"strval",
".",
"lower",
"(",
")",
".",
"strip... | 38.333333 | 8.666667 |
def strip_between(self, string, start, end):
"""Deletes everything between regexes start and end from string"""
regex = start + r'.*?' + end + r'\s*'
res = re.sub(regex, '', string,
flags=re.DOTALL|re.IGNORECASE|re.MULTILINE)
return res | [
"def",
"strip_between",
"(",
"self",
",",
"string",
",",
"start",
",",
"end",
")",
":",
"regex",
"=",
"start",
"+",
"r'.*?'",
"+",
"end",
"+",
"r'\\s*'",
"res",
"=",
"re",
".",
"sub",
"(",
"regex",
",",
"''",
",",
"string",
",",
"flags",
"=",
"re... | 47.333333 | 9.333333 |
def get_template_folder():
"""Get path to the folder where th HTML templates are."""
cfg = get_project_configuration()
if 'templates' not in cfg:
home = os.path.expanduser("~")
rcfile = os.path.join(home, ".hwrtrc")
cfg['templates'] = pkg_resources.resource_filename('hwrt',
... | [
"def",
"get_template_folder",
"(",
")",
":",
"cfg",
"=",
"get_project_configuration",
"(",
")",
"if",
"'templates'",
"not",
"in",
"cfg",
":",
"home",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
"rcfile",
"=",
"os",
".",
"path",
".",
"... | 44.909091 | 11.363636 |
def source_expand(self, source):
'''Expand the wildcards for an S3 path. This emulates the shall expansion
for wildcards if the input is local path.
'''
result = []
if not isinstance(source, list):
source = [source]
for src in source:
# XXX Hacky: We need to disable recursive wh... | [
"def",
"source_expand",
"(",
"self",
",",
"source",
")",
":",
"result",
"=",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"source",
",",
"list",
")",
":",
"source",
"=",
"[",
"source",
"]",
"for",
"src",
"in",
"source",
":",
"# XXX Hacky: We need to disable... | 32.818182 | 22.636364 |
def tokenize(self, sentence,
normalize=True,
is_feature=False,
is_surface=False,
return_list=False,
func_normalizer=text_preprocess.normalize_text):
# type: (text_type, bool, bool, bool, bool, Callable[[str],str]) -> Union[List... | [
"def",
"tokenize",
"(",
"self",
",",
"sentence",
",",
"normalize",
"=",
"True",
",",
"is_feature",
"=",
"False",
",",
"is_surface",
"=",
"False",
",",
"return_list",
"=",
"False",
",",
"func_normalizer",
"=",
"text_preprocess",
".",
"normalize_text",
")",
":... | 39.947368 | 19.078947 |
def validate(self, collection: BioCCollection):
"""Validate a single collection."""
for document in collection.documents:
self.validate_doc(document) | [
"def",
"validate",
"(",
"self",
",",
"collection",
":",
"BioCCollection",
")",
":",
"for",
"document",
"in",
"collection",
".",
"documents",
":",
"self",
".",
"validate_doc",
"(",
"document",
")"
] | 43.5 | 3.25 |
async def download_cot_artifacts(chain):
"""Call ``download_cot_artifact`` in parallel for each "upstreamArtifacts".
Optional artifacts are allowed to not be downloaded.
Args:
chain (ChainOfTrust): the chain of trust object
Returns:
list: list of full paths to downloaded artifacts. Fa... | [
"async",
"def",
"download_cot_artifacts",
"(",
"chain",
")",
":",
"upstream_artifacts",
"=",
"chain",
".",
"task",
"[",
"'payload'",
"]",
".",
"get",
"(",
"'upstreamArtifacts'",
",",
"[",
"]",
")",
"all_artifacts_per_task_id",
"=",
"get_all_artifacts_per_task_id",
... | 40.410256 | 29.179487 |
def time_plots(df, path, title=None, color="#4CB391", figformat="png",
log_length=False, plot_settings=None):
"""Making plots of time vs read length, time vs quality and cumulative yield."""
dfs = check_valid_time_and_sort(df, "start_time")
logging.info("Nanoplotter: Creating timeplots using ... | [
"def",
"time_plots",
"(",
"df",
",",
"path",
",",
"title",
"=",
"None",
",",
"color",
"=",
"\"#4CB391\"",
",",
"figformat",
"=",
"\"png\"",
",",
"log_length",
"=",
"False",
",",
"plot_settings",
"=",
"None",
")",
":",
"dfs",
"=",
"check_valid_time_and_sort... | 57.818182 | 15.818182 |
def stop_broadcast(self, broadcast_id):
"""
Use this method to stop a live broadcast of an OpenTok session
:param String broadcast_id: The ID of the broadcast you want to stop
:rtype A Broadcast object, which contains information of the broadcast: id, sessionId
projectId, creat... | [
"def",
"stop_broadcast",
"(",
"self",
",",
"broadcast_id",
")",
":",
"endpoint",
"=",
"self",
".",
"endpoints",
".",
"broadcast_url",
"(",
"broadcast_id",
",",
"stop",
"=",
"True",
")",
"response",
"=",
"requests",
".",
"post",
"(",
"endpoint",
",",
"heade... | 40.387097 | 18.258065 |
def download_patric_genomes(self, ids, force_rerun=False):
"""Download genome files from PATRIC given a list of PATRIC genome IDs and load them as strains.
Args:
ids (str, list): PATRIC ID or list of PATRIC IDs
force_rerun (bool): If genome files should be downloaded again even ... | [
"def",
"download_patric_genomes",
"(",
"self",
",",
"ids",
",",
"force_rerun",
"=",
"False",
")",
":",
"ids",
"=",
"ssbio",
".",
"utils",
".",
"force_list",
"(",
"ids",
")",
"counter",
"=",
"0",
"log",
".",
"info",
"(",
"'Downloading sequences from PATRIC...... | 47.708333 | 28.833333 |
def check_access_token(self, request_token):
"""Checks that the token contains only safe characters
and is no shorter than lower and no longer than upper.
"""
lower, upper = self.access_token_length
return (set(request_token) <= self.safe_characters and
lower <= l... | [
"def",
"check_access_token",
"(",
"self",
",",
"request_token",
")",
":",
"lower",
",",
"upper",
"=",
"self",
".",
"access_token_length",
"return",
"(",
"set",
"(",
"request_token",
")",
"<=",
"self",
".",
"safe_characters",
"and",
"lower",
"<=",
"len",
"(",... | 48.714286 | 9.714286 |
def demo(nums=[]):
"Print a few usage examples on stdout."
nums = nums or [3, 1, 4, 1, 5, 9, 2, 6]
fmt = lambda num: '{0:g}'.format(num) if isinstance(num, (float, int)) else 'None'
nums1 = list(map(fmt, nums))
if __name__ == '__main__':
prog = sys.argv[0]
else:
prog = 'sparkli... | [
"def",
"demo",
"(",
"nums",
"=",
"[",
"]",
")",
":",
"nums",
"=",
"nums",
"or",
"[",
"3",
",",
"1",
",",
"4",
",",
"1",
",",
"5",
",",
"9",
",",
"2",
",",
"6",
"]",
"fmt",
"=",
"lambda",
"num",
":",
"'{0:g}'",
".",
"format",
"(",
"num",
... | 37.431818 | 24.431818 |
def retry(self, f, *args, **kwargs):
"""
Retries the given function self.tries times on NetworkErros
"""
backoff = random.random() / 100 # 5ms on average
for _ in range(self.tries - 1):
try:
return f(*args, **kwargs)
except NetworkError:
... | [
"def",
"retry",
"(",
"self",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"backoff",
"=",
"random",
".",
"random",
"(",
")",
"/",
"100",
"# 5ms on average",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"tries",
"-",
"1",
")",
... | 33.833333 | 8.833333 |
def get_coinc_def_id(self, search, search_coinc_type, create_new = True, description = None):
"""
Return the coinc_def_id for the row in the table whose
search string and search_coinc_type integer have the values
given. If a matching row is not found, the default
behaviour is to create a new row and return t... | [
"def",
"get_coinc_def_id",
"(",
"self",
",",
"search",
",",
"search_coinc_type",
",",
"create_new",
"=",
"True",
",",
"description",
"=",
"None",
")",
":",
"# look for the ID",
"rows",
"=",
"[",
"row",
"for",
"row",
"in",
"self",
"if",
"(",
"row",
".",
"... | 39.806452 | 20.580645 |
def doDirectPayment(self, params):
"""Call PayPal DoDirectPayment method."""
defaults = {"method": "DoDirectPayment", "paymentaction": "Sale"}
required = ["creditcardtype",
"acct",
"expdate",
"cvv2",
"ipaddress",
... | [
"def",
"doDirectPayment",
"(",
"self",
",",
"params",
")",
":",
"defaults",
"=",
"{",
"\"method\"",
":",
"\"DoDirectPayment\"",
",",
"\"paymentaction\"",
":",
"\"Sale\"",
"}",
"required",
"=",
"[",
"\"creditcardtype\"",
",",
"\"acct\"",
",",
"\"expdate\"",
",",
... | 40.444444 | 14.407407 |
def doc_dir(self):
"""The absolute directory of the document"""
from os.path import abspath
if not self.ref:
return None
u = parse_app_url(self.ref)
return abspath(dirname(u.path)) | [
"def",
"doc_dir",
"(",
"self",
")",
":",
"from",
"os",
".",
"path",
"import",
"abspath",
"if",
"not",
"self",
".",
"ref",
":",
"return",
"None",
"u",
"=",
"parse_app_url",
"(",
"self",
".",
"ref",
")",
"return",
"abspath",
"(",
"dirname",
"(",
"u",
... | 25.111111 | 16.222222 |
def delete_as(access_token, subscription_id, resource_group, as_name):
'''Delete availability set.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
as_name (str): Name of ... | [
"def",
"delete_as",
"(",
"access_token",
",",
"subscription_id",
",",
"resource_group",
",",
"as_name",
")",
":",
"endpoint",
"=",
"''",
".",
"join",
"(",
"[",
"get_rm_endpoint",
"(",
")",
",",
"'/subscriptions/'",
",",
"subscription_id",
",",
"'/resourceGroups/... | 39.555556 | 21.666667 |
def retrofitted(self):
"""
:returns: the asset retrofitted value
"""
return self.calc('structural', {'structural': self._retrofitted},
self.area, self.number) | [
"def",
"retrofitted",
"(",
"self",
")",
":",
"return",
"self",
".",
"calc",
"(",
"'structural'",
",",
"{",
"'structural'",
":",
"self",
".",
"_retrofitted",
"}",
",",
"self",
".",
"area",
",",
"self",
".",
"number",
")"
] | 35 | 10.666667 |
def horizontal(y, xmin=0, xmax=1, color=None, width=None, dash=None, opacity=None):
"""Draws a horizontal line from `xmin` to `xmax`.
Parameters
----------
xmin : int, optional
xmax : int, optional
color : str, optional
width : number, optional
Returns
-------
Chart
"""
... | [
"def",
"horizontal",
"(",
"y",
",",
"xmin",
"=",
"0",
",",
"xmax",
"=",
"1",
",",
"color",
"=",
"None",
",",
"width",
"=",
"None",
",",
"dash",
"=",
"None",
",",
"opacity",
"=",
"None",
")",
":",
"lineattr",
"=",
"{",
"}",
"if",
"color",
":",
... | 22.407407 | 24.185185 |
def calc_ethsw_port(self, port_num, port_def):
"""
Split and create the port entry for an Ethernet Switch
:param port_num: port number
:type port_num: str or int
:param str port_def: port definition
"""
# Port String - access 1 SW2 1
# 0: type 1: vlan 2: ... | [
"def",
"calc_ethsw_port",
"(",
"self",
",",
"port_num",
",",
"port_def",
")",
":",
"# Port String - access 1 SW2 1",
"# 0: type 1: vlan 2: destination device 3: destination port",
"port_def",
"=",
"port_def",
".",
"split",
"(",
"' '",
")",
"if",
"len",
"(",
"port_def",
... | 36.925926 | 9.666667 |
def get_one(cls,
execution_date,
key=None,
task_id=None,
dag_id=None,
include_prior_dates=False,
session=None):
"""
Retrieve an XCom value, optionally meeting certain criteria.
TODO: "pickling" has be... | [
"def",
"get_one",
"(",
"cls",
",",
"execution_date",
",",
"key",
"=",
"None",
",",
"task_id",
"=",
"None",
",",
"dag_id",
"=",
"None",
",",
"include_prior_dates",
"=",
"False",
",",
"session",
"=",
"None",
")",
":",
"filters",
"=",
"[",
"]",
"if",
"k... | 37.622222 | 19.622222 |
def dictfetchall(cursor):
"""Returns all rows from a cursor as a dict (rather than a headerless table)
From Django Documentation: https://docs.djangoproject.com/en/dev/topics/db/sql/
"""
desc = cursor.description
return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] | [
"def",
"dictfetchall",
"(",
"cursor",
")",
":",
"desc",
"=",
"cursor",
".",
"description",
"return",
"[",
"dict",
"(",
"zip",
"(",
"[",
"col",
"[",
"0",
"]",
"for",
"col",
"in",
"desc",
"]",
",",
"row",
")",
")",
"for",
"row",
"in",
"cursor",
"."... | 43.714286 | 21.571429 |
def GetFileSystemTypeIndicators(cls, path_spec, resolver_context=None):
"""Determines if a file contains a supported file system types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which ... | [
"def",
"GetFileSystemTypeIndicators",
"(",
"cls",
",",
"path_spec",
",",
"resolver_context",
"=",
"None",
")",
":",
"if",
"(",
"cls",
".",
"_file_system_remainder_list",
"is",
"None",
"or",
"cls",
".",
"_file_system_store",
"is",
"None",
")",
":",
"specification... | 39.961538 | 18.038462 |
def flag_forgotten_entries(session, today=None):
"""Flag any entries from previous days where users forgot to sign
out.
:param session: SQLAlchemy session through which to access the database.
:param today: (optional) The current date as a `datetime.date` object. Used for testing.
""" # noqa
to... | [
"def",
"flag_forgotten_entries",
"(",
"session",
",",
"today",
"=",
"None",
")",
":",
"# noqa",
"today",
"=",
"date",
".",
"today",
"(",
")",
"if",
"today",
"is",
"None",
"else",
"today",
"forgotten",
"=",
"(",
"session",
".",
"query",
"(",
"Entry",
")... | 31.130435 | 21.434783 |
def generate_action(args):
"""Generate action."""
controller = args.get('<controller>')
action = args.get('<action>')
with_template = args.get('-t')
current_path = os.getcwd()
logger.info('Start generating action.')
controller_file_path = os.path.join(current_path, 'application/controllers... | [
"def",
"generate_action",
"(",
"args",
")",
":",
"controller",
"=",
"args",
".",
"get",
"(",
"'<controller>'",
")",
"action",
"=",
"args",
".",
"get",
"(",
"'<action>'",
")",
"with_template",
"=",
"args",
".",
"get",
"(",
"'-t'",
")",
"current_path",
"="... | 46.344828 | 27.62069 |
def texture_from_image(renderer, image_name):
"""Create an SDL2 Texture from an image file"""
soft_surface = ext.load_image(image_name)
texture = SDL_CreateTextureFromSurface(renderer.renderer, soft_surface)
SDL_FreeSurface(soft_surface)
return texture | [
"def",
"texture_from_image",
"(",
"renderer",
",",
"image_name",
")",
":",
"soft_surface",
"=",
"ext",
".",
"load_image",
"(",
"image_name",
")",
"texture",
"=",
"SDL_CreateTextureFromSurface",
"(",
"renderer",
".",
"renderer",
",",
"soft_surface",
")",
"SDL_FreeS... | 44.5 | 12.333333 |
def add_virtual_columns_proper_motion_gal2eq(self, long_in="ra", lat_in="dec", pm_long="pm_l", pm_lat="pm_b", pm_long_out="pm_ra", pm_lat_out="pm_dec",
name_prefix="__proper_motion_gal2eq",
right_ascension_galactic_pole=192.85,
... | [
"def",
"add_virtual_columns_proper_motion_gal2eq",
"(",
"self",
",",
"long_in",
"=",
"\"ra\"",
",",
"lat_in",
"=",
"\"dec\"",
",",
"pm_long",
"=",
"\"pm_l\"",
",",
"pm_lat",
"=",
"\"pm_b\"",
",",
"pm_long_out",
"=",
"\"pm_ra\"",
",",
"pm_lat_out",
"=",
"\"pm_dec... | 57.642857 | 28.785714 |
def integer_based_slice(self, ts):
"""
Transform a :class:`TimeSlice` into integer indices that numpy can work
with
Args:
ts (slice, TimeSlice): the time slice to translate into integer
indices
"""
if isinstance(ts, slice):
try:
... | [
"def",
"integer_based_slice",
"(",
"self",
",",
"ts",
")",
":",
"if",
"isinstance",
"(",
"ts",
",",
"slice",
")",
":",
"try",
":",
"start",
"=",
"Seconds",
"(",
"0",
")",
"if",
"ts",
".",
"start",
"is",
"None",
"else",
"ts",
".",
"start",
"if",
"... | 36.047619 | 21.047619 |
def popUpItem(self, *args):
"""Return the specified item in a pop up menu."""
self.Press()
time.sleep(.5)
return self._menuItem(self, *args) | [
"def",
"popUpItem",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"Press",
"(",
")",
"time",
".",
"sleep",
"(",
".5",
")",
"return",
"self",
".",
"_menuItem",
"(",
"self",
",",
"*",
"args",
")"
] | 33.6 | 10.6 |
def get_run(session, dag_id, execution_date):
"""
:param dag_id: DAG ID
:type dag_id: unicode
:param execution_date: execution date
:type execution_date: datetime
:return: DagRun corresponding to the given dag_id and execution date
if one exists. None otherwis... | [
"def",
"get_run",
"(",
"session",
",",
"dag_id",
",",
"execution_date",
")",
":",
"qry",
"=",
"session",
".",
"query",
"(",
"DagRun",
")",
".",
"filter",
"(",
"DagRun",
".",
"dag_id",
"==",
"dag_id",
",",
"DagRun",
".",
"external_trigger",
"==",
"False",... | 36.3125 | 9.4375 |
def nacm_rule_list_cmdrule_context(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
nacm = ET.SubElement(config, "nacm", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-acm")
rule_list = ET.SubElement(nacm, "rule-list")
name_key = ET.SubElement(ru... | [
"def",
"nacm_rule_list_cmdrule_context",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"nacm",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"nacm\"",
",",
"xmlns",
"=",
"\"urn:ietf:param... | 45.9375 | 14.875 |
def parse_exac_genes(lines):
"""Parse lines with exac formated genes
This is designed to take a dump with genes from exac.
This is downloaded from:
ftp.broadinstitute.org/pub/ExAC_release//release0.3/functional_gene_constraint/
fordist_cleaned_exac_r03_march16_z_pli... | [
"def",
"parse_exac_genes",
"(",
"lines",
")",
":",
"header",
"=",
"[",
"]",
"logger",
".",
"info",
"(",
"\"Parsing exac genes...\"",
")",
"for",
"index",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if",
"index",
"==",
"0",
":",
"header",
"... | 36.090909 | 18.909091 |
def _(c: Concept, cutoff: float = 0.7) -> bool:
"""Check if a concept has a high grounding score. """
return is_grounded(c) and (top_grounding_score(c) >= cutoff) | [
"def",
"_",
"(",
"c",
":",
"Concept",
",",
"cutoff",
":",
"float",
"=",
"0.7",
")",
"->",
"bool",
":",
"return",
"is_grounded",
"(",
"c",
")",
"and",
"(",
"top_grounding_score",
"(",
"c",
")",
">=",
"cutoff",
")"
] | 42 | 17.75 |
def get_default_value(self, check):
"""
Given a check, return the default value for the check
(converted to the right type).
If the check doesn't specify a default value then a
``KeyError`` will be raised.
"""
fun_name, fun_args, fun_kwargs, default = self._parse... | [
"def",
"get_default_value",
"(",
"self",
",",
"check",
")",
":",
"fun_name",
",",
"fun_args",
",",
"fun_kwargs",
",",
"default",
"=",
"self",
".",
"_parse_with_caching",
"(",
"check",
")",
"if",
"default",
"is",
"None",
":",
"raise",
"KeyError",
"(",
"'Che... | 39.4 | 15.933333 |
def remove_column(conn, table, column_name, schema=None):
"""
Removes given `activity` jsonb data column key. This function is useful
when you are doing schema changes that require removing a column.
Let's say you've been using PostgreSQL-Audit for a while for a table called
article. Now you want t... | [
"def",
"remove_column",
"(",
"conn",
",",
"table",
",",
"column_name",
",",
"schema",
"=",
"None",
")",
":",
"activity_table",
"=",
"get_activity_table",
"(",
"schema",
"=",
"schema",
")",
"remove",
"=",
"sa",
".",
"cast",
"(",
"column_name",
",",
"sa",
... | 30.833333 | 22.214286 |
def check_lazy_load_wegsegment(f):
'''
Decorator function to lazy load a :class:`Wegsegment`.
'''
def wrapper(*args):
wegsegment = args[0]
if (
wegsegment._methode_id is None or
wegsegment._geometrie is None or
wegsegment._metadata is None
):
... | [
"def",
"check_lazy_load_wegsegment",
"(",
"f",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
")",
":",
"wegsegment",
"=",
"args",
"[",
"0",
"]",
"if",
"(",
"wegsegment",
".",
"_methode_id",
"is",
"None",
"or",
"wegsegment",
".",
"_geometrie",
"is",
"None... | 35.105263 | 16.157895 |
def new_character(self, name, data=None, **kwargs):
"""Create and return a new :class:`Character`."""
self.add_character(name, data, **kwargs)
return self.character[name] | [
"def",
"new_character",
"(",
"self",
",",
"name",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"add_character",
"(",
"name",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"character",
"[",
"name",
"]... | 47.75 | 6 |
def convert(self, to_mag, from_mag=None):
""" Converts magnitudes using UBVRIJHKLMNQ photometry in Taurus-Auriga (Kenyon+ 1995)
ReadMe+ftp1995ApJS..101..117K Colors for main-sequence stars
If from_mag isn't specified the program will cycle through provided magnitudes and choose one. Note that... | [
"def",
"convert",
"(",
"self",
",",
"to_mag",
",",
"from_mag",
"=",
"None",
")",
":",
"allowed_mags",
"=",
"\"UBVJIHKLMN\"",
"if",
"from_mag",
":",
"if",
"to_mag",
"==",
"'V'",
":",
"# If V mag is requested (1/3) - from mag specified",
"return",
"self",
".",
"_c... | 48.488889 | 26.266667 |
def _build_date_header_string(self, date_value):
"""Gets the date_value (may be None, basestring, float or
datetime.datetime instance) and returns a valid date string as per
RFC 2822."""
if isinstance(date_value, datetime):
date_value = time.mktime(date_value.timetuple())
if not isinstance(date_value, base... | [
"def",
"_build_date_header_string",
"(",
"self",
",",
"date_value",
")",
":",
"if",
"isinstance",
"(",
"date_value",
",",
"datetime",
")",
":",
"date_value",
"=",
"time",
".",
"mktime",
"(",
"date_value",
".",
"timetuple",
"(",
")",
")",
"if",
"not",
"isin... | 45 | 9.636364 |
def generate_delete_view(self):
"""Generate class based view for DeleteView"""
name = model_class_form(self.model + 'DeleteView')
delete_args = dict(
model=self.get_model_class,
template_name=self.get_template('delete'),
permissions=self.view_permission('dele... | [
"def",
"generate_delete_view",
"(",
"self",
")",
":",
"name",
"=",
"model_class_form",
"(",
"self",
".",
"model",
"+",
"'DeleteView'",
")",
"delete_args",
"=",
"dict",
"(",
"model",
"=",
"self",
".",
"get_model_class",
",",
"template_name",
"=",
"self",
".",... | 43.294118 | 19.764706 |
def _messageFromSender(self, sender, messageID):
"""
Locate a previously queued message by a given sender and messageID.
"""
return self.store.findUnique(
_QueuedMessage,
AND(_QueuedMessage.senderUsername == sender.localpart,
_QueuedMessage.senderD... | [
"def",
"_messageFromSender",
"(",
"self",
",",
"sender",
",",
"messageID",
")",
":",
"return",
"self",
".",
"store",
".",
"findUnique",
"(",
"_QueuedMessage",
",",
"AND",
"(",
"_QueuedMessage",
".",
"senderUsername",
"==",
"sender",
".",
"localpart",
",",
"_... | 41.6 | 13.6 |
def flush(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Flush current iptables state
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {... | [
"def",
"flush",
"(",
"name",
",",
"table",
"=",
"'filter'",
",",
"family",
"=",
"'ipv4'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
... | 26.697674 | 22.930233 |
def months_per_hour(self):
"""A list of tuples representing months per hour in this analysis period."""
month_hour = []
hour_range = xrange(self.st_hour, self.end_hour + 1)
for month in self.months_int:
month_hour.extend([(month, hr) for hr in hour_range])
return mont... | [
"def",
"months_per_hour",
"(",
"self",
")",
":",
"month_hour",
"=",
"[",
"]",
"hour_range",
"=",
"xrange",
"(",
"self",
".",
"st_hour",
",",
"self",
".",
"end_hour",
"+",
"1",
")",
"for",
"month",
"in",
"self",
".",
"months_int",
":",
"month_hour",
"."... | 45.714286 | 13.428571 |
def populateFromRow(self, featureSetRecord):
"""
Populates the instance variables of this FeatureSet from the specified
DB row.
"""
self._dbFilePath = featureSetRecord.dataurl
self.setAttributesJson(featureSetRecord.attributes)
self.populateFromFile(self._dbFilePa... | [
"def",
"populateFromRow",
"(",
"self",
",",
"featureSetRecord",
")",
":",
"self",
".",
"_dbFilePath",
"=",
"featureSetRecord",
".",
"dataurl",
"self",
".",
"setAttributesJson",
"(",
"featureSetRecord",
".",
"attributes",
")",
"self",
".",
"populateFromFile",
"(",
... | 39.5 | 13 |
def to_timedelta(value, strict=True):
"""
converts duration string to timedelta
strict=True (by default) raises StrictnessError if either hours,
minutes or seconds in duration string exceed allowed values
"""
if isinstance(value, int):
return timedelta(seconds=value) # assuming it's se... | [
"def",
"to_timedelta",
"(",
"value",
",",
"strict",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"return",
"timedelta",
"(",
"seconds",
"=",
"value",
")",
"# assuming it's seconds",
"elif",
"isinstance",
"(",
"value",
",",... | 34.086957 | 14.434783 |
def toLily(self):
'''
Method which converts the object instance, its attributes and children to a string of lilypond code
:return: str of lilypond code
'''
lilystring = ""
if self.duration > 0:
lilystring += "r" + str(self.duration)
return lilystring | [
"def",
"toLily",
"(",
"self",
")",
":",
"lilystring",
"=",
"\"\"",
"if",
"self",
".",
"duration",
">",
"0",
":",
"lilystring",
"+=",
"\"r\"",
"+",
"str",
"(",
"self",
".",
"duration",
")",
"return",
"lilystring"
] | 31 | 24.4 |
def fromkeys (cls, iterable, value=None):
"""Construct new caseless dict from given data."""
d = cls()
for k in iterable:
dict.__setitem__(d, k.lower(), value)
return d | [
"def",
"fromkeys",
"(",
"cls",
",",
"iterable",
",",
"value",
"=",
"None",
")",
":",
"d",
"=",
"cls",
"(",
")",
"for",
"k",
"in",
"iterable",
":",
"dict",
".",
"__setitem__",
"(",
"d",
",",
"k",
".",
"lower",
"(",
")",
",",
"value",
")",
"retur... | 34.5 | 11.833333 |
def _do_code_blocks(self, text):
"""Process Markdown `<pre><code>` blocks."""
code_block_re = re.compile(r'''
(?:\n\n|\A\n?)
( # $1 = the code block -- one or more lines, starting with a space/tab
(?:
(?:[ ]{%d} | \t) # Lines must star... | [
"def",
"_do_code_blocks",
"(",
"self",
",",
"text",
")",
":",
"code_block_re",
"=",
"re",
".",
"compile",
"(",
"r'''\n (?:\\n\\n|\\A\\n?)\n ( # $1 = the code block -- one or more lines, starting with a space/tab\n (?:\n (?:[... | 44.714286 | 22.714286 |
def get_undefined_namespace_names(graph: BELGraph, namespace: str) -> Set[str]:
"""Get the names from a namespace that wasn't actually defined.
:return: The set of all names from the undefined namespace
"""
return {
exc.name
for _, exc, _ in graph.warnings
if isinstance(exc, Und... | [
"def",
"get_undefined_namespace_names",
"(",
"graph",
":",
"BELGraph",
",",
"namespace",
":",
"str",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"return",
"{",
"exc",
".",
"name",
"for",
"_",
",",
"exc",
",",
"_",
"in",
"graph",
".",
"warnings",
"if",
"i... | 37.1 | 23.3 |
def __looks_like_html(response):
"""Guesses entity type when Content-Type header is missing.
Since Content-Type is not strictly required, some servers leave it out.
"""
text = response.text.lstrip().lower()
return text.startswith('<html') or text.startswith('<!doctype') | [
"def",
"__looks_like_html",
"(",
"response",
")",
":",
"text",
"=",
"response",
".",
"text",
".",
"lstrip",
"(",
")",
".",
"lower",
"(",
")",
"return",
"text",
".",
"startswith",
"(",
"'<html'",
")",
"or",
"text",
".",
"startswith",
"(",
"'<!doctype'",
... | 50.833333 | 13.833333 |
def request(self, method, apikey, *args, **kwargs):
""" Make a xml-rpc call to remote API. """
dry_run = kwargs.get('dry_run', False)
return_dry_run = kwargs.get('return_dry_run', False)
if return_dry_run:
args[-1]['--dry-run'] = True
try:
func = getattr(... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"apikey",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"dry_run",
"=",
"kwargs",
".",
"get",
"(",
"'dry_run'",
",",
"False",
")",
"return_dry_run",
"=",
"kwargs",
".",
"get",
"(",
"'return_dr... | 42.347826 | 12.26087 |
def energy_prof(step):
"""Energy flux.
This computation takes sphericity into account if necessary.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the energy flux and the radial position
at wh... | [
"def",
"energy_prof",
"(",
"step",
")",
":",
"diff",
",",
"rad",
"=",
"diffs_prof",
"(",
"step",
")",
"adv",
",",
"_",
"=",
"advts_prof",
"(",
"step",
")",
"return",
"(",
"diff",
"+",
"np",
".",
"append",
"(",
"adv",
",",
"0",
")",
")",
",",
"r... | 29.333333 | 19.866667 |
def serialize(self):
"""
Converts the credentials to a percent encoded string to be stored for
later use.
:returns:
:class:`string`
"""
if self.provider_id is None:
raise ConfigError(
'To serialize credentials you need to specify... | [
"def",
"serialize",
"(",
"self",
")",
":",
"if",
"self",
".",
"provider_id",
"is",
"None",
":",
"raise",
"ConfigError",
"(",
"'To serialize credentials you need to specify a '",
"'unique integer under the \"id\" key in the config '",
"'for each provider!'",
")",
"# Get the pr... | 29.9 | 20.966667 |
def batch_flatten(x):
"""
Flatten the tensor except the first dimension.
"""
shape = x.get_shape().as_list()[1:]
if None not in shape:
return tf.reshape(x, [-1, int(np.prod(shape))])
return tf.reshape(x, tf.stack([tf.shape(x)[0], -1])) | [
"def",
"batch_flatten",
"(",
"x",
")",
":",
"shape",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"1",
":",
"]",
"if",
"None",
"not",
"in",
"shape",
":",
"return",
"tf",
".",
"reshape",
"(",
"x",
",",
"[",
"-",
"1",
",... | 32.5 | 9.5 |
def is_thin_archieve(self):
"""
Return the is thin archieve attribute of the BFD file being processed.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(
self._ptr, BfdAttributes.IS_THIN_ARCHIEVE) | [
"def",
"is_thin_archieve",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"get_bfd_attribute",
"(",
"self",
".",
"_ptr",
",",
"BfdAttributes",
".",
"IS_THIN_ARC... | 33 | 15 |
def power(self, n):
"""Return the compose of a QuantumChannel with itself n times.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
SuperOp: the n-times composition channel as a SuperOp object.
Raises:
QiskitError: if th... | [
"def",
"power",
"(",
"self",
",",
"n",
")",
":",
"if",
"not",
"isinstance",
"(",
"n",
",",
"(",
"int",
",",
"np",
".",
"integer",
")",
")",
":",
"raise",
"QiskitError",
"(",
"\"Can only power with integer powers.\"",
")",
"if",
"self",
".",
"_input_dim",... | 40.818182 | 23.409091 |
def _scheduled_check_for_summaries(self):
"""Present the results if they have become available or timed out."""
if self._analysis_process is None:
return
# handle time out
timed_out = time.time() - self._analyze_start_time > self.time_limit
if timed_out:
s... | [
"def",
"_scheduled_check_for_summaries",
"(",
"self",
")",
":",
"if",
"self",
".",
"_analysis_process",
"is",
"None",
":",
"return",
"# handle time out",
"timed_out",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"_analyze_start_time",
">",
"self",
"."... | 47.217391 | 17.956522 |
def _template(node_id, value=None):
"Check if a template is assigned to it and render that with the value"
result = []
select_template_from_node = fetch_query_string('select_template_from_node.sql')
try:
result = db.execute(text(select_template_from_node), node_id=node_id)
template_resul... | [
"def",
"_template",
"(",
"node_id",
",",
"value",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"select_template_from_node",
"=",
"fetch_query_string",
"(",
"'select_template_from_node.sql'",
")",
"try",
":",
"result",
"=",
"db",
".",
"execute",
"(",
"text",... | 40.1 | 21.7 |
def validate_character_instance_valid_for_arc(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Evaluate attempts to assign a character instance to ensure it is from same
outline.
'''
if action == 'pre_add':
if reverse:
# Fetch arc definition through link.
... | [
"def",
"validate_character_instance_valid_for_arc",
"(",
"sender",
",",
"instance",
",",
"action",
",",
"reverse",
",",
"pk_set",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"action",
"==",
"'pre_add'",
":",
"if",
"reverse",
":",
"# Fetch arc ... | 50.470588 | 31.058824 |
def delete(path, regex=None, recurse=False, test=False):
"""Deletes the file or directory at `path`. If `path` is a directory and
`regex` is provided, matching files will be deleted; `recurse` controls
whether subdirectories are recursed. A list of deleted items is returned.
If `test` is true, nothing w... | [
"def",
"delete",
"(",
"path",
",",
"regex",
"=",
"None",
",",
"recurse",
"=",
"False",
",",
"test",
"=",
"False",
")",
":",
"deleted",
"=",
"[",
"]",
"if",
"op",
".",
"isfile",
"(",
"path",
")",
":",
"if",
"not",
"test",
":",
"os",
".",
"remove... | 39.4 | 15.04 |
def one_version(self, index=0):
'''
Leaves only one version for each object.
:param index: List-like index of the version. 0 == first; -1 == last
'''
def prep(df):
start = sorted(df._start.tolist())[index]
return df[df._start == start]
return pd... | [
"def",
"one_version",
"(",
"self",
",",
"index",
"=",
"0",
")",
":",
"def",
"prep",
"(",
"df",
")",
":",
"start",
"=",
"sorted",
"(",
"df",
".",
"_start",
".",
"tolist",
"(",
")",
")",
"[",
"index",
"]",
"return",
"df",
"[",
"df",
".",
"_start"... | 33.272727 | 23.454545 |
def get_exif_data(filename):
"""Return a dict with the raw EXIF data."""
logger = logging.getLogger(__name__)
img = _read_image(filename)
try:
exif = img._getexif() or {}
except ZeroDivisionError:
logger.warning('Failed to read EXIF data.')
return None
data = {TAGS.ge... | [
"def",
"get_exif_data",
"(",
"filename",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"img",
"=",
"_read_image",
"(",
"filename",
")",
"try",
":",
"exif",
"=",
"img",
".",
"_getexif",
"(",
")",
"or",
"{",
"}",
"except",
... | 29.125 | 20.25 |
def audio_detection_sensitivity(self):
"""Sensitivity level of Camera audio detection."""
if not self.triggers:
return None
for trigger in self.triggers:
if trigger.get("type") != "audioAmplitude":
continue
sensitivity = trigger.get("sensitiv... | [
"def",
"audio_detection_sensitivity",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"triggers",
":",
"return",
"None",
"for",
"trigger",
"in",
"self",
".",
"triggers",
":",
"if",
"trigger",
".",
"get",
"(",
"\"type\"",
")",
"!=",
"\"audioAmplitude\"",
"... | 29.357143 | 17.071429 |
async def _on_status_change(self, update):
"""Update a service that has its status updated."""
info = update['payload']
new_number = info['new_status']
name = update['service']
if name not in self.services:
return
with self._state_lock:
is_chang... | [
"async",
"def",
"_on_status_change",
"(",
"self",
",",
"update",
")",
":",
"info",
"=",
"update",
"[",
"'payload'",
"]",
"new_number",
"=",
"info",
"[",
"'new_status'",
"]",
"name",
"=",
"update",
"[",
"'service'",
"]",
"if",
"name",
"not",
"in",
"self",... | 36.294118 | 20.117647 |
def generate_csv(path, out):
"""\
Walks through the `path` and generates the CSV file `out`
"""
def is_berlin_cable(filename):
return 'BERLIN' in filename
writer = UnicodeWriter(open(out, 'wb'), delimiter=';')
writer.writerow(('Reference ID', 'Created', 'Origin', 'Subject'))
for cabl... | [
"def",
"generate_csv",
"(",
"path",
",",
"out",
")",
":",
"def",
"is_berlin_cable",
"(",
"filename",
")",
":",
"return",
"'BERLIN'",
"in",
"filename",
"writer",
"=",
"UnicodeWriter",
"(",
"open",
"(",
"out",
",",
"'wb'",
")",
",",
"delimiter",
"=",
"';'"... | 46.7 | 17.8 |
def concatenate(self, tpl, axis=None):
"""
Concatenates sparse tensors.
Parameters
----------
tpl : tuple of sparse tensors
Tensors to be concatenated.
axis : int, optional
Axis along which concatenation should take place
"""
if ... | [
"def",
"concatenate",
"(",
"self",
",",
"tpl",
",",
"axis",
"=",
"None",
")",
":",
"if",
"axis",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"'Sparse tensor concatenation without axis argument is not supported'",
")",
"T",
"=",
"self",
"for",
"i",
"i... | 30.631579 | 14.842105 |
def read_reporting_revisions_get(self, project=None, fields=None, types=None, continuation_token=None, start_date_time=None, include_identity_ref=None, include_deleted=None, include_tag_ref=None, include_latest_only=None, expand=None, include_discussion_changes_only=None, max_page_size=None):
"""ReadReportingRe... | [
"def",
"read_reporting_revisions_get",
"(",
"self",
",",
"project",
"=",
"None",
",",
"fields",
"=",
"None",
",",
"types",
"=",
"None",
",",
"continuation_token",
"=",
"None",
",",
"start_date_time",
"=",
"None",
",",
"include_identity_ref",
"=",
"None",
",",
... | 84.666667 | 48.431373 |
def post_parse_response(self, response, **kwargs):
"""
Add scope claim to response, from the request, if not present in the
response
:param response: The response
:param kwargs: Extra Keyword arguments
:return: A possibly augmented response
"""
if "scope... | [
"def",
"post_parse_response",
"(",
"self",
",",
"response",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"\"scope\"",
"not",
"in",
"response",
":",
"try",
":",
"_key",
"=",
"kwargs",
"[",
"'state'",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"if"... | 32.083333 | 16 |
def _AsMessageList(msg):
"""Convert the provided list-as-JsonValue to a list."""
# This really needs to live in extra_types, but extra_types needs
# to import this file to be able to register codecs.
# TODO(craigcitro): Split out a codecs module and fix this ugly
# import.
from apitools.base.py ... | [
"def",
"_AsMessageList",
"(",
"msg",
")",
":",
"# This really needs to live in extra_types, but extra_types needs",
"# to import this file to be able to register codecs.",
"# TODO(craigcitro): Split out a codecs module and fix this ugly",
"# import.",
"from",
"apitools",
".",
"base",
"."... | 38.217391 | 16.869565 |
def run(self):
"""
Returns the sum of unread messages across all registered backends
"""
unread = 0
current_unread = 0
for id, backend in enumerate(self.backends):
temp = backend.unread or 0
unread = unread + temp
if id == self.current_... | [
"def",
"run",
"(",
"self",
")",
":",
"unread",
"=",
"0",
"current_unread",
"=",
"0",
"for",
"id",
",",
"backend",
"in",
"enumerate",
"(",
"self",
".",
"backends",
")",
":",
"temp",
"=",
"backend",
".",
"unread",
"or",
"0",
"unread",
"=",
"unread",
... | 29.545455 | 18.575758 |
def draw_rand_pos(self, radius, z_min, z_max,
min_r=np.array([0]), min_cell_interdist=10., **args):
"""
Draw some random location within radius, z_min, z_max,
and constrained by min_r and the minimum cell interdistance.
Returned argument is a list of dicts [{'xpos',... | [
"def",
"draw_rand_pos",
"(",
"self",
",",
"radius",
",",
"z_min",
",",
"z_max",
",",
"min_r",
"=",
"np",
".",
"array",
"(",
"[",
"0",
"]",
")",
",",
"min_cell_interdist",
"=",
"10.",
",",
"*",
"*",
"args",
")",
":",
"x",
"=",
"(",
"np",
".",
"r... | 36.472527 | 20.692308 |
def source(self, value):
"""
Setter for **self.__source** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"source"... | [
"def",
"source",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"unicode",
",",
"\"'{0}' attribute: '{1}' type is not 'unicode'!\"",
".",
"format",
"(",
"\"source\"",
",",
"value",
")"... | 35.230769 | 21.230769 |
def make_internal_signing_service(config, entity_id):
"""
Given configuration initiate an InternalSigningService instance
:param config: The signing service configuration
:param entity_id: The entity identifier
:return: A InternalSigningService instance
"""
_args = dict([(k, v) for k, v in... | [
"def",
"make_internal_signing_service",
"(",
"config",
",",
"entity_id",
")",
":",
"_args",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"config",
".",
"items",
"(",
")",
"if",
"k",
"in",
"KJ_SPECS",
"]",
")",
"_kj",
... | 32.692308 | 17.615385 |
def dvds_top_rentals(self, **kwargs):
"""Gets the current opening movies from the API.
Args:
limit (optional): limits the number of movies returned, default=10
country (optional): localized data for selected country, default="us"
Returns:
A dict respresentation of... | [
"def",
"dvds_top_rentals",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"self",
".",
"_get_path",
"(",
"'dvds_top_rentals'",
")",
"response",
"=",
"self",
".",
"_GET",
"(",
"path",
",",
"kwargs",
")",
"self",
".",
"_set_attrs_to_values",
... | 34.133333 | 20.466667 |
def synchronize(self, pid, vendorSpecific=None):
"""See Also: synchronizeResponse() Args: pid: vendorSpecific:
Returns:
"""
response = self.synchronizeResponse(pid, vendorSpecific)
return self._read_boolean_response(response) | [
"def",
"synchronize",
"(",
"self",
",",
"pid",
",",
"vendorSpecific",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"synchronizeResponse",
"(",
"pid",
",",
"vendorSpecific",
")",
"return",
"self",
".",
"_read_boolean_response",
"(",
"response",
")"
] | 32.5 | 18.5 |
def get_edge_citation(self, u: BaseEntity, v: BaseEntity, key: str) -> Optional[CitationDict]:
"""Get the citation for a given edge."""
return self._get_edge_attr(u, v, key, CITATION) | [
"def",
"get_edge_citation",
"(",
"self",
",",
"u",
":",
"BaseEntity",
",",
"v",
":",
"BaseEntity",
",",
"key",
":",
"str",
")",
"->",
"Optional",
"[",
"CitationDict",
"]",
":",
"return",
"self",
".",
"_get_edge_attr",
"(",
"u",
",",
"v",
",",
"key",
... | 65.666667 | 23 |
def spher_harms(l, m, inclination):
"""Return spherical harmonic polarizations
"""
# FIXME: we are using spin -2 weighted spherical harmonics for now,
# when possible switch to spheroidal harmonics.
Y_lm = lal.SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m).real
Y_lminusm = lal.SpinWei... | [
"def",
"spher_harms",
"(",
"l",
",",
"m",
",",
"inclination",
")",
":",
"# FIXME: we are using spin -2 weighted spherical harmonics for now,",
"# when possible switch to spheroidal harmonics.",
"Y_lm",
"=",
"lal",
".",
"SpinWeightedSphericalHarmonic",
"(",
"inclination",
",",
... | 39.416667 | 18.333333 |
def delete_all(self, model_class):
'''Drop all records from the table model_class.__name__.lower()
'''
assert hasattr(model_class, '_fields'), 'Not a valid model class'
table = model_class.__name__.lower()
with Session() as conn:
SQL = f'DELETE FROM {table}'
... | [
"def",
"delete_all",
"(",
"self",
",",
"model_class",
")",
":",
"assert",
"hasattr",
"(",
"model_class",
",",
"'_fields'",
")",
",",
"'Not a valid model class'",
"table",
"=",
"model_class",
".",
"__name__",
".",
"lower",
"(",
")",
"with",
"Session",
"(",
")... | 36.7 | 16.9 |
def json_data(self, instance, default=None):
"""Get a JSON compatible value
"""
value = self.get(instance)
return value or default | [
"def",
"json_data",
"(",
"self",
",",
"instance",
",",
"default",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"get",
"(",
"instance",
")",
"return",
"value",
"or",
"default"
] | 31.6 | 3.8 |
def clear_rr_ce_entries(self):
# type: () -> None
'''
A method to clear out all of the extent locations of all Rock Ridge
Continuation Entries that the PVD is tracking. This can be used to
reset all data before assigning new data.
Parameters:
None.
Retu... | [
"def",
"clear_rr_ce_entries",
"(",
"self",
")",
":",
"# type: () -> None",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'This Primary Volume Descriptor is not yet initialized'",
")",
"for",
"block",
"in",
... | 33.411765 | 24.470588 |
def _gen_3spec(op, path, xattr=False):
"""
Returns a Spec tuple suitable for passing to the underlying C extension.
This variant is called for operations that lack an input value.
:param str path: The path to fetch
:param bool xattr: Whether this is an extended attribute
:return: a spec suitabl... | [
"def",
"_gen_3spec",
"(",
"op",
",",
"path",
",",
"xattr",
"=",
"False",
")",
":",
"flags",
"=",
"0",
"if",
"xattr",
":",
"flags",
"|=",
"_P",
".",
"SDSPEC_F_XATTR",
"return",
"Spec",
"(",
"op",
",",
"path",
",",
"flags",
")"
] | 35 | 17.307692 |
def handle_request(self, request, **resources):
""" Get a method for request and execute.
:return object: method result
"""
if not request.method in self._meta.callmap.keys():
raise HttpError(
'Unknown or unsupported method \'%s\'' % request.method,
... | [
"def",
"handle_request",
"(",
"self",
",",
"request",
",",
"*",
"*",
"resources",
")",
":",
"if",
"not",
"request",
".",
"method",
"in",
"self",
".",
"_meta",
".",
"callmap",
".",
"keys",
"(",
")",
":",
"raise",
"HttpError",
"(",
"'Unknown or unsupported... | 34.625 | 19.375 |
def run_interactive(query, editor=None, just_count=False, default_no=False):
"""
Asks the user about each patch suggested by the result of the query.
@param query An instance of the Query class.
@param editor Name of editor to use for manual intervention, e.g.
'vim'... | [
"def",
"run_interactive",
"(",
"query",
",",
"editor",
"=",
"None",
",",
"just_count",
"=",
"False",
",",
"default_no",
"=",
"False",
")",
":",
"global",
"yes_to_all",
"# Load start from bookmark, if appropriate.",
"bookmark",
"=",
"_load_bookmark",
"(",
")",
"if"... | 37.489796 | 18.591837 |
def execute_as(collector):
"""Execute a command (after the --) as an assumed role (specified by --artifact)"""
# Gonna assume role anyway...
collector.configuration['amazon']._validated = True
# Find the arn we want to assume
account_id = collector.configuration['accounts'][collector.configuration[... | [
"def",
"execute_as",
"(",
"collector",
")",
":",
"# Gonna assume role anyway...",
"collector",
".",
"configuration",
"[",
"'amazon'",
"]",
".",
"_validated",
"=",
"True",
"# Find the arn we want to assume",
"account_id",
"=",
"collector",
".",
"configuration",
"[",
"'... | 46.090909 | 25.772727 |
def main(argv=None):
"""Main entry point for the cdstar CLI."""
args = docopt(__doc__, version=pycdstar.__version__, argv=argv, options_first=True)
subargs = [args['<command>']] + args['<args>']
if args['<command>'] in ['help', None]:
cmd = None
if len(subargs) > 1:
cmd = CO... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"args",
"=",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"pycdstar",
".",
"__version__",
",",
"argv",
"=",
"argv",
",",
"options_first",
"=",
"True",
")",
"subargs",
"=",
"[",
"args",
"[",
"'<comm... | 28.238095 | 16.238095 |
def image_member(self):
"""
Returns a json-schema document that represents an image member entity.
(a container of member entities).
"""
uri = "/%s/member" % self.uri_base
resp, resp_body = self.api.method_get(uri)
return resp_body | [
"def",
"image_member",
"(",
"self",
")",
":",
"uri",
"=",
"\"/%s/member\"",
"%",
"self",
".",
"uri_base",
"resp",
",",
"resp_body",
"=",
"self",
".",
"api",
".",
"method_get",
"(",
"uri",
")",
"return",
"resp_body"
] | 35 | 10.5 |
def add_code_challenge(request_args, service, **kwargs):
"""
PKCE RFC 7636 support
To be added as a post_construct method to an
:py:class:`oidcservice.oidc.service.Authorization` instance
:param service: The service that uses this function
:param request_args: Set of request arguments
:para... | [
"def",
"add_code_challenge",
"(",
"request_args",
",",
"service",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"cv_len",
"=",
"service",
".",
"service_context",
".",
"config",
"[",
"'code_challenge'",
"]",
"[",
"'length'",
"]",
"except",
"KeyError",
":",
... | 33.5 | 18.547619 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.