text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def twisted_absolute_path(path, request):
"""Hack to fix twisted not accepting absolute URIs"""
parsed = urlparse.urlparse(request.uri)
if parsed.scheme != '':
path_parts = parsed.path.lstrip('/').split('/')
request.prepath = path_parts[0:1]
request.postpath = path_parts[1:]
... | [
"def",
"twisted_absolute_path",
"(",
"path",
",",
"request",
")",
":",
"parsed",
"=",
"urlparse",
".",
"urlparse",
"(",
"request",
".",
"uri",
")",
"if",
"parsed",
".",
"scheme",
"!=",
"''",
":",
"path_parts",
"=",
"parsed",
".",
"path",
".",
"lstrip",
... | 40.222222 | 6.333333 |
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This func... | [
"def",
"nearest_neighbor",
"(",
"self",
",",
"vectors",
",",
"num",
"=",
"10",
",",
"batch_size",
"=",
"100",
",",
"show_progressbar",
"=",
"False",
",",
"return_names",
"=",
"True",
")",
":",
"vectors",
"=",
"np",
".",
"array",
"(",
"vectors",
")",
"i... | 37.285714 | 17.693878 |
def static_method(cls, f):
"""Decorator which dynamically binds static methods to the model for later use."""
setattr(cls, f.__name__, staticmethod(f))
return f | [
"def",
"static_method",
"(",
"cls",
",",
"f",
")",
":",
"setattr",
"(",
"cls",
",",
"f",
".",
"__name__",
",",
"staticmethod",
"(",
"f",
")",
")",
"return",
"f"
] | 45.25 | 11.75 |
def rate_limit_info():
""" Returns (requests_remaining, minutes_to_reset) """
import json
import time
r = requests.get(gh_url + "/rate_limit", auth=login.auth())
out = json.loads(r.text)
mins = (out["resources"]["core"]["reset"]-time.time())/60
return out["resources"]["core"]["remaining"], ... | [
"def",
"rate_limit_info",
"(",
")",
":",
"import",
"json",
"import",
"time",
"r",
"=",
"requests",
".",
"get",
"(",
"gh_url",
"+",
"\"/rate_limit\"",
",",
"auth",
"=",
"login",
".",
"auth",
"(",
")",
")",
"out",
"=",
"json",
".",
"loads",
"(",
"r",
... | 35.111111 | 19.777778 |
def create_overwrites_for_quarter(self,
col_to_overwrites,
next_qtr_start_idx,
last_per_qtr,
quarters_with_estimates_for_sid,
requ... | [
"def",
"create_overwrites_for_quarter",
"(",
"self",
",",
"col_to_overwrites",
",",
"next_qtr_start_idx",
",",
"last_per_qtr",
",",
"quarters_with_estimates_for_sid",
",",
"requested_quarter",
",",
"sid",
",",
"sid_idx",
",",
"columns",
")",
":",
"for",
"col",
"in",
... | 44.888889 | 16.083333 |
def download_large(self, image, url_field='url'):
"""Downlaod the binary data of an image attachment at large size.
:param str url_field: the field of the image with the right URL
:return: binary image data
:rtype: bytes
"""
return self.download(image, url_field=url_fie... | [
"def",
"download_large",
"(",
"self",
",",
"image",
",",
"url_field",
"=",
"'url'",
")",
":",
"return",
"self",
".",
"download",
"(",
"image",
",",
"url_field",
"=",
"url_field",
",",
"suffix",
"=",
"'large'",
")"
] | 36.777778 | 19.666667 |
def UploadSignedConfigBlob(content,
aff4_path,
client_context=None,
limit=None,
token=None):
"""Upload a signed blob into the datastore.
Args:
content: File content to upload.
aff4_path: aff4 path to... | [
"def",
"UploadSignedConfigBlob",
"(",
"content",
",",
"aff4_path",
",",
"client_context",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"token",
"=",
"None",
")",
":",
"if",
"limit",
"is",
"None",
":",
"limit",
"=",
"config",
".",
"CONFIG",
"[",
"\"Datast... | 30.068182 | 17.977273 |
def get_ansible_groups(group_map):
"""
Constructs a list of :class:`ansible.inventory.group.Group` objects from a
map of lists of host strings.
"""
# Some of this logic is cribbed from
# ansible.inventory.script.InventoryScript
all_hosts = {}
group_all = Group('all')
groups = [group... | [
"def",
"get_ansible_groups",
"(",
"group_map",
")",
":",
"# Some of this logic is cribbed from",
"# ansible.inventory.script.InventoryScript",
"all_hosts",
"=",
"{",
"}",
"group_all",
"=",
"Group",
"(",
"'all'",
")",
"groups",
"=",
"[",
"group_all",
"]",
"for",
"gname... | 29.714286 | 12.571429 |
def visit_Set(self, pattern):
""" Set have unordered values. """
if len(pattern.elts) > MAX_UNORDERED_LENGTH:
raise DamnTooLongPattern("Pattern for Set is too long")
return (isinstance(self.node, Set) and
any(self.check_list(self.node.elts, pattern_elts)
... | [
"def",
"visit_Set",
"(",
"self",
",",
"pattern",
")",
":",
"if",
"len",
"(",
"pattern",
".",
"elts",
")",
">",
"MAX_UNORDERED_LENGTH",
":",
"raise",
"DamnTooLongPattern",
"(",
"\"Pattern for Set is too long\"",
")",
"return",
"(",
"isinstance",
"(",
"self",
".... | 52.714286 | 15.571429 |
def wait_until(obj, att, desired, callback=None, interval=5, attempts=0,
verbose=False, verbose_atts=None):
"""
When changing the state of an object, it will commonly be in a transitional
state until the change is complete. This will reload the object every
`interval` seconds, and check its `att... | [
"def",
"wait_until",
"(",
"obj",
",",
"att",
",",
"desired",
",",
"callback",
"=",
"None",
",",
"interval",
"=",
"5",
",",
"attempts",
"=",
"0",
",",
"verbose",
"=",
"False",
",",
"verbose_atts",
"=",
"None",
")",
":",
"if",
"callback",
":",
"waiter"... | 57.686275 | 30.235294 |
def mac_address_table_consistency_check_mac_consistency_check_interval(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
mac_address_table = ET.SubElement(config, "mac-address-table", xmlns="urn:brocade.com:mgmt:brocade-mac-address-table")
consistency_chec... | [
"def",
"mac_address_table_consistency_check_mac_consistency_check_interval",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"mac_address_table",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"mac-... | 59.727273 | 32.727273 |
def _setup_configuration(self):
"""
All steps are accepted as classes. Instantiate them with the right
configuration and set them in a local property.
"""
self.configuration = dict(
schema_cls=self.schema_cls,
allowed_actions=self.allowed_actions,
... | [
"def",
"_setup_configuration",
"(",
"self",
")",
":",
"self",
".",
"configuration",
"=",
"dict",
"(",
"schema_cls",
"=",
"self",
".",
"schema_cls",
",",
"allowed_actions",
"=",
"self",
".",
"allowed_actions",
",",
"filter_by_fields",
"=",
"self",
".",
"filter_... | 42.806452 | 11.709677 |
def set(*args, **kw):
"""Set IRAF environment variables."""
if len(args) == 0:
if len(kw) != 0:
# normal case is only keyword,value pairs
for keyword, value in kw.items():
keyword = untranslateName(keyword)
svalue = str(value)
_var... | [
"def",
"set",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"if",
"len",
"(",
"kw",
")",
"!=",
"0",
":",
"# normal case is only keyword,value pairs",
"for",
"keyword",
",",
"value",
"in",
"kw",
".",... | 42.36 | 18.72 |
def send(self, sender: PytgbotApiBot):
"""
Send the message via pytgbot.
:param sender: The bot instance to send with.
:type sender: pytgbot.bot.Bot
:rtype: PytgbotApiMessage
"""
return sender.send_document(
# receiver, self.media, disable_notificat... | [
"def",
"send",
"(",
"self",
",",
"sender",
":",
"PytgbotApiBot",
")",
":",
"return",
"sender",
".",
"send_document",
"(",
"# receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id",
"document",
"=",
"self",
".",
"document",
",",
... | 47.538462 | 31.846154 |
def synthese(self, month=None):
"""
month format: YYYYMM
"""
if month is None and self.legislature == '2012-2017':
raise AssertionError('Global Synthesis on legislature does not work, see https://github.com/regardscitoyens/nosdeputes.fr/issues/69')
if month is None:
... | [
"def",
"synthese",
"(",
"self",
",",
"month",
"=",
"None",
")",
":",
"if",
"month",
"is",
"None",
"and",
"self",
".",
"legislature",
"==",
"'2012-2017'",
":",
"raise",
"AssertionError",
"(",
"'Global Synthesis on legislature does not work, see https://github.com/regar... | 37.214286 | 25.785714 |
def add_group_email_grant(self, permission, email_address, headers=None):
"""
Convenience method that provides a quick way to add an email group
grant to a key. This method retrieves the current ACL, creates a new
grant based on the parameters passed in, adds that grant to the ACL and
... | [
"def",
"add_group_email_grant",
"(",
"self",
",",
"permission",
",",
"email_address",
",",
"headers",
"=",
"None",
")",
":",
"acl",
"=",
"self",
".",
"get_acl",
"(",
"headers",
"=",
"headers",
")",
"acl",
".",
"add_group_email_grant",
"(",
"permission",
",",... | 47.45 | 20.75 |
def fiscal_code(self, gender: Optional[Gender] = None) -> str:
"""Return a random fiscal code.
:param gender: Gender's enum object.
:return: Fiscal code.
Example:
RSSMRA66R05D612U
"""
code = ''.join(self.random.choices(string.ascii_uppercase, k=6))
... | [
"def",
"fiscal_code",
"(",
"self",
",",
"gender",
":",
"Optional",
"[",
"Gender",
"]",
"=",
"None",
")",
"->",
"str",
":",
"code",
"=",
"''",
".",
"join",
"(",
"self",
".",
"random",
".",
"choices",
"(",
"string",
".",
"ascii_uppercase",
",",
"k",
... | 30.777778 | 19.444444 |
def result(self):
""" Get the table used for the results of the query. If the query is incomplete, this blocks.
Raises:
Exception if we timed out waiting for results or the query failed.
"""
self.wait()
if self.failed:
raise Exception('Query failed: %s' % str(self.errors))
return se... | [
"def",
"result",
"(",
"self",
")",
":",
"self",
".",
"wait",
"(",
")",
"if",
"self",
".",
"failed",
":",
"raise",
"Exception",
"(",
"'Query failed: %s'",
"%",
"str",
"(",
"self",
".",
"errors",
")",
")",
"return",
"self",
".",
"_table"
] | 32 | 20.8 |
def avl_release_parent(node):
"""
removes the parent of a child
"""
parent = node.parent
if parent is not None:
if parent.right is node:
parent.right = None
elif parent.left is node:
parent.left = None
else:
raise AssertionError('impossible... | [
"def",
"avl_release_parent",
"(",
"node",
")",
":",
"parent",
"=",
"node",
".",
"parent",
"if",
"parent",
"is",
"not",
"None",
":",
"if",
"parent",
".",
"right",
"is",
"node",
":",
"parent",
".",
"right",
"=",
"None",
"elif",
"parent",
".",
"left",
"... | 29.4 | 12.466667 |
def tree_statistics(tree):
"""
prints the types and counts of elements present in a SaltDocument tree,
e.g.::
layers: 3
sDocument: 1
nodes: 252
labels: 2946
edges: 531
"""
all_elements = tree.findall('//')
tag_counter = defaultdict(int)
for element i... | [
"def",
"tree_statistics",
"(",
"tree",
")",
":",
"all_elements",
"=",
"tree",
".",
"findall",
"(",
"'//'",
")",
"tag_counter",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"element",
"in",
"all_elements",
":",
"tag_counter",
"[",
"element",
".",
"tag",
"]",... | 24.833333 | 16.388889 |
def gather_facts_list(self, file):
"""
Return a list of facts.
"""
facts = []
contents = utils.file_to_string(os.path.join(self.paths["role"],
file))
contents = re.sub(r"\s+", "", contents)
matches = self.regex_facts.findal... | [
"def",
"gather_facts_list",
"(",
"self",
",",
"file",
")",
":",
"facts",
"=",
"[",
"]",
"contents",
"=",
"utils",
".",
"file_to_string",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"paths",
"[",
"\"role\"",
"]",
",",
"file",
")",
")",
"c... | 27.733333 | 16.666667 |
def run_cmds_on_all_switches(self, cmds):
"""Runs all cmds on all configured switches
This helper is used for ACL and rule creation/deletion as ACLs
and rules must exist on all switches.
"""
for switch in self._switches.values():
self.run_openstack_sg_cmds(cmds, swit... | [
"def",
"run_cmds_on_all_switches",
"(",
"self",
",",
"cmds",
")",
":",
"for",
"switch",
"in",
"self",
".",
"_switches",
".",
"values",
"(",
")",
":",
"self",
".",
"run_openstack_sg_cmds",
"(",
"cmds",
",",
"switch",
")"
] | 39.5 | 11.75 |
def WriteClientMetadata(self,
client_id,
certificate=None,
fleetspeak_enabled=None,
first_seen=None,
last_ping=None,
last_clock=None,
last... | [
"def",
"WriteClientMetadata",
"(",
"self",
",",
"client_id",
",",
"certificate",
"=",
"None",
",",
"fleetspeak_enabled",
"=",
"None",
",",
"first_seen",
"=",
"None",
",",
"last_ping",
"=",
"None",
",",
"last_clock",
"=",
"None",
",",
"last_ip",
"=",
"None",
... | 38.169811 | 14.584906 |
def create_appointment_group(self, appointment_group, **kwargs):
"""
Create a new Appointment Group.
:calls: `POST /api/v1/appointment_groups \
<https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.create>`_
:param appointment_group: The attr... | [
"def",
"create_appointment_group",
"(",
"self",
",",
"appointment_group",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"canvasapi",
".",
"appointment_group",
"import",
"AppointmentGroup",
"if",
"(",
"isinstance",
"(",
"appointment_group",
",",
"dict",
")",
"and",
... | 36.825 | 23.125 |
def getContextsForExpressions(self, body, getFingerprint=None, startIndex=0, maxResults=5, sparsity=1.0):
"""Bulk get contexts for input expressions
Args:
body, ExpressionOperation: The JSON encoded expression to be evaluated (required)
getFingerprint, bool: Configure if the fing... | [
"def",
"getContextsForExpressions",
"(",
"self",
",",
"body",
",",
"getFingerprint",
"=",
"None",
",",
"startIndex",
"=",
"0",
",",
"maxResults",
"=",
"5",
",",
"sparsity",
"=",
"1.0",
")",
":",
"return",
"self",
".",
"_expressions",
".",
"getContextsForBulk... | 61.714286 | 35.785714 |
def w(self, units=None):
"""
This returns a single array containing the phase-space positions.
Parameters
----------
units : `~gala.units.UnitSystem` (optional)
The unit system to represent the position and velocity in
before combining into the full array... | [
"def",
"w",
"(",
"self",
",",
"units",
"=",
"None",
")",
":",
"if",
"units",
"is",
"None",
":",
"if",
"self",
".",
"hamiltonian",
"is",
"None",
":",
"units",
"=",
"dimensionless",
"else",
":",
"units",
"=",
"self",
".",
"hamiltonian",
".",
"units",
... | 28.52 | 19.88 |
def write(self, fptr):
"""Write a JPEG 2000 Signature box to file.
"""
fptr.write(struct.pack('>I4s', 12, b'jP '))
fptr.write(struct.pack('>BBBB', *self.signature)) | [
"def",
"write",
"(",
"self",
",",
"fptr",
")",
":",
"fptr",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'>I4s'",
",",
"12",
",",
"b'jP '",
")",
")",
"fptr",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'>BBBB'",
",",
"*",
"self",
".",
"... | 38.6 | 9.4 |
def anonymous_login_view(request):
''' View for an admin to log her/himself out and login the anonymous user. '''
logout(request)
try:
spineless = User.objects.get(username=ANONYMOUS_USERNAME)
except User.DoesNotExist:
random_password = User.objects.make_random_password()
spinele... | [
"def",
"anonymous_login_view",
"(",
"request",
")",
":",
"logout",
"(",
"request",
")",
"try",
":",
"spineless",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"username",
"=",
"ANONYMOUS_USERNAME",
")",
"except",
"User",
".",
"DoesNotExist",
":",
"random_pas... | 51.388889 | 23.611111 |
def appendData(self, xdata, ydata, color='b', legendstr=None):
"""Adds the data to the plot
:param xdata: index values for data, plotted on x-axis
:type xdata: numpy.ndarray
:param ydata: value data to plot, dimension must match xdata
:type ydata: numpy.ndarray
"""
... | [
"def",
"appendData",
"(",
"self",
",",
"xdata",
",",
"ydata",
",",
"color",
"=",
"'b'",
",",
"legendstr",
"=",
"None",
")",
":",
"item",
"=",
"self",
".",
"plot",
"(",
"xdata",
",",
"ydata",
",",
"pen",
"=",
"color",
")",
"if",
"legendstr",
"is",
... | 38 | 14.083333 |
def container_rename_folder(object_id, input_params={}, always_retry=False, **kwargs):
"""
Invokes the /container-xxxx/renameFolder API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FrenameFolder
"""
return DXHTTPReq... | [
"def",
"container_rename_folder",
"(",
"object_id",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/%s/renameFolder'",
"%",
"object_id",
",",
"input_params",
",",
"alw... | 57.285714 | 38.142857 |
def parse(file_path):
'''Parse a YAML or JSON file.'''
_, ext = path.splitext(file_path)
if ext in ('.yaml', '.yml'):
func = yaml.load
elif ext == '.json':
func = json.load
else:
raise ValueError("Unrecognized config file type %s" % ext)
with open(file_path, 'r') as ... | [
"def",
"parse",
"(",
"file_path",
")",
":",
"_",
",",
"ext",
"=",
"path",
".",
"splitext",
"(",
"file_path",
")",
"if",
"ext",
"in",
"(",
"'.yaml'",
",",
"'.yml'",
")",
":",
"func",
"=",
"yaml",
".",
"load",
"elif",
"ext",
"==",
"'.json'",
":",
"... | 20.625 | 22.625 |
def reorder_resource_views(self, resource_views):
# type: (List[Union[ResourceView,Dict,str]]) -> None
"""Order resource views in resource.
Args:
resource_views (List[Union[ResourceView,Dict,str]]): A list of either resource view ids or resource views metadata from ResourceView obje... | [
"def",
"reorder_resource_views",
"(",
"self",
",",
"resource_views",
")",
":",
"# type: (List[Union[ResourceView,Dict,str]]) -> None",
"if",
"not",
"isinstance",
"(",
"resource_views",
",",
"list",
")",
":",
"raise",
"HDXError",
"(",
"'ResourceViews should be a list!'",
"... | 46.086957 | 24.391304 |
def _create_session(self, username, password):
"""Create HTTP session.
Args:
username (str): Timesketch username
password (str): Timesketch password
Returns:
requests.Session: Session object.
"""
session = requests.Session()
session.verify = False # Depending on SSL cert is ... | [
"def",
"_create_session",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"session",
"=",
"requests",
".",
"Session",
"(",
")",
"session",
".",
"verify",
"=",
"False",
"# Depending on SSL cert is verifiable",
"try",
":",
"response",
"=",
"session",
".... | 32.769231 | 16.384615 |
def run(self, node):
"""
Captures the use of locals() in render function.
"""
if self.get_call_name(node) != 'render':
return
issues = []
for arg in node.args:
if isinstance(arg, ast.Call) and arg.func.id == 'locals':
issues.append(... | [
"def",
"run",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"get_call_name",
"(",
"node",
")",
"!=",
"'render'",
":",
"return",
"issues",
"=",
"[",
"]",
"for",
"arg",
"in",
"node",
".",
"args",
":",
"if",
"isinstance",
"(",
"arg",
",",
"... | 30.125 | 13.75 |
def revoke_tokens(self):
"""
Revoke the authorization token and all tokens that were generated using it.
"""
self.is_active = False
self.save()
self.refresh_token.revoke_tokens() | [
"def",
"revoke_tokens",
"(",
"self",
")",
":",
"self",
".",
"is_active",
"=",
"False",
"self",
".",
"save",
"(",
")",
"self",
".",
"refresh_token",
".",
"revoke_tokens",
"(",
")"
] | 24.444444 | 19.111111 |
def p_primary_expr_no_brace_4(self, p):
"""primary_expr_no_brace : LPAREN expr RPAREN"""
if isinstance(p[2], self.asttypes.GroupingOp):
# this reduces the grouping operator to one.
p[0] = p[2]
else:
p[0] = self.asttypes.GroupingOp(expr=p[2])
p[0].s... | [
"def",
"p_primary_expr_no_brace_4",
"(",
"self",
",",
"p",
")",
":",
"if",
"isinstance",
"(",
"p",
"[",
"2",
"]",
",",
"self",
".",
"asttypes",
".",
"GroupingOp",
")",
":",
"# this reduces the grouping operator to one.",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
... | 40.125 | 12.875 |
def create(self, container, instances=None, map_name=None, **kwargs):
"""
Creates container instances for a container configuration.
:param container: Container name.
:type container: unicode | str
:param instances: Instance name to create. If not specified, will create all inst... | [
"def",
"create",
"(",
"self",
",",
"container",
",",
"instances",
"=",
"None",
",",
"map_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"run_actions",
"(",
"'create'",
",",
"container",
",",
"instances",
"=",
"instances",
... | 55.117647 | 24.411765 |
def get_default_options(num_machines=1, max_wallclock_seconds=1800, withmpi=False):
"""
Return an instance of the options dictionary with the minimally required parameters
for a JobCalculation and set to default values unless overriden
:param num_machines: set the number of nodes, default=1
:param ... | [
"def",
"get_default_options",
"(",
"num_machines",
"=",
"1",
",",
"max_wallclock_seconds",
"=",
"1800",
",",
"withmpi",
"=",
"False",
")",
":",
"return",
"{",
"'resources'",
":",
"{",
"'num_machines'",
":",
"int",
"(",
"num_machines",
")",
"}",
",",
"'max_wa... | 40.5625 | 25.1875 |
def texto_decimal(valor, remover_zeros=True):
"""Converte um valor :py:class:`decimal.Decimal` para texto, com a opção de
remover os zeros à direita não significativos. A conversão para texto irá
considerar o :py:module:`locale` para converter o texto pronto para
apresentação.
:param decimal.Decima... | [
"def",
"texto_decimal",
"(",
"valor",
",",
"remover_zeros",
"=",
"True",
")",
":",
"texto",
"=",
"'{:n}'",
".",
"format",
"(",
"valor",
")",
"if",
"remover_zeros",
":",
"dp",
"=",
"locale",
".",
"localeconv",
"(",
")",
".",
"get",
"(",
"'decimal_point'",... | 43.352941 | 21.117647 |
def get_scaled_cutout_wdht(self, x1, y1, x2, y2, new_wd, new_ht,
method='basic'):
"""Extract a region of the image defined by corners (x1, y1) and
(x2, y2) and resample it to fit dimensions (new_wd, new_ht).
`method` describes the method of interpolation used, whe... | [
"def",
"get_scaled_cutout_wdht",
"(",
"self",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"new_wd",
",",
"new_ht",
",",
"method",
"=",
"'basic'",
")",
":",
"if",
"method",
"in",
"(",
"'basic'",
",",
"'view'",
")",
":",
"shp",
"=",
"self",
".",... | 41.148148 | 20.666667 |
def _gcs_list_keys(bucket, pattern):
""" List all Google Cloud Storage keys in a specified bucket that match a pattern. """
data = [{'Name': obj.metadata.name,
'Type': obj.metadata.content_type,
'Size': obj.metadata.size,
'Updated': obj.metadata.updated_on}
for obj in _gcs... | [
"def",
"_gcs_list_keys",
"(",
"bucket",
",",
"pattern",
")",
":",
"data",
"=",
"[",
"{",
"'Name'",
":",
"obj",
".",
"metadata",
".",
"name",
",",
"'Type'",
":",
"obj",
".",
"metadata",
".",
"content_type",
",",
"'Size'",
":",
"obj",
".",
"metadata",
... | 55 | 11.5 |
def make_reply(msgname, types, arguments, major):
"""Helper method for constructing a reply message from a list or tuple.
Parameters
----------
msgname : str
Name of the reply message.
types : list of kattypes
The types of the reply message parameters (in order).
arguments : lis... | [
"def",
"make_reply",
"(",
"msgname",
",",
"types",
",",
"arguments",
",",
"major",
")",
":",
"status",
"=",
"arguments",
"[",
"0",
"]",
"if",
"status",
"==",
"\"fail\"",
":",
"return",
"Message",
".",
"reply",
"(",
"msgname",
",",
"*",
"pack_types",
"(... | 34.173913 | 17.913043 |
def list_dms (archive, compression, cmd, verbosity, interactive):
"""List a DMS archive."""
check_archive_ext(archive)
return [cmd, 'v', archive] | [
"def",
"list_dms",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
")",
":",
"check_archive_ext",
"(",
"archive",
")",
"return",
"[",
"cmd",
",",
"'v'",
",",
"archive",
"]"
] | 38.5 | 11.25 |
def add_organization(db, organization):
"""Add an organization to the registry.
This function adds an organization to the registry.
It checks first whether the organization is already on the registry.
When it is not found, the new organization is added. Otherwise,
it raises a 'AlreadyExistsError' e... | [
"def",
"add_organization",
"(",
"db",
",",
"organization",
")",
":",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"try",
":",
"add_organization_db",
"(",
"session",
",",
"organization",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",... | 38.52381 | 20.238095 |
def GetValueByPath(self, path_segments):
"""Retrieves a plist value by path.
Args:
path_segments (list[str]): path segment strings relative to the root
of the plist.
Returns:
object: The value of the key specified by the path or None.
"""
key = self.root_key
for path_segm... | [
"def",
"GetValueByPath",
"(",
"self",
",",
"path_segments",
")",
":",
"key",
"=",
"self",
".",
"root_key",
"for",
"path_segment",
"in",
"path_segments",
":",
"if",
"isinstance",
"(",
"key",
",",
"dict",
")",
":",
"try",
":",
"key",
"=",
"key",
"[",
"pa... | 21.090909 | 21.69697 |
def site_coordination_numbers( self ):
"""
Returns a dictionary of the coordination numbers for each site label. e.g.::
{ 'A' : { 4 }, 'B' : { 2, 4 } }
Args:
none
Returns:
coordination_numbers (Dict(Str:Set(Int))): dictionary of coordinatio... | [
"def",
"site_coordination_numbers",
"(",
"self",
")",
":",
"coordination_numbers",
"=",
"{",
"}",
"for",
"l",
"in",
"self",
".",
"site_labels",
":",
"coordination_numbers",
"[",
"l",
"]",
"=",
"set",
"(",
"[",
"len",
"(",
"site",
".",
"neighbours",
")",
... | 36.647059 | 24.294118 |
def get_active_clients():
"""Get a list of all active clients and their status"""
global drivers
if not drivers:
return jsonify([])
result = {client: get_client_info(client) for client in drivers}
return jsonify(result) | [
"def",
"get_active_clients",
"(",
")",
":",
"global",
"drivers",
"if",
"not",
"drivers",
":",
"return",
"jsonify",
"(",
"[",
"]",
")",
"result",
"=",
"{",
"client",
":",
"get_client_info",
"(",
"client",
")",
"for",
"client",
"in",
"drivers",
"}",
"retur... | 26.777778 | 21.555556 |
def volume_down(self, delta=0.1):
""" Decrement the volume by 0.1 (or delta) unless it is already 0.
Returns the new volume.
"""
if delta <= 0:
raise ValueError(
"volume delta must be greater than zero, not {}".format(delta))
return self.set_volume(sel... | [
"def",
"volume_down",
"(",
"self",
",",
"delta",
"=",
"0.1",
")",
":",
"if",
"delta",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"volume delta must be greater than zero, not {}\"",
".",
"format",
"(",
"delta",
")",
")",
"return",
"self",
".",
"set_volume",
... | 42.875 | 13.5 |
def send_at(self, value):
"""A unix timestamp specifying when your email should
be delivered.
:param value: A unix timestamp specifying when your email should
be delivered.
:type value: SendAt, int
"""
if isinstance(value, SendAt):
if value.personaliz... | [
"def",
"send_at",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"SendAt",
")",
":",
"if",
"value",
".",
"personalization",
"is",
"not",
"None",
":",
"try",
":",
"personalization",
"=",
"self",
".",
"_personalizations",
"[",
... | 37.923077 | 15.461538 |
def date_suggestions():
"""
Returns a list of relative date that is presented to the user as auto
complete suggestions.
"""
# don't use strftime, prevent locales to kick in
days_of_week = {
0: "Monday",
1: "Tuesday",
2: "Wednesday",
3: "Thursday",
4: "Frid... | [
"def",
"date_suggestions",
"(",
")",
":",
"# don't use strftime, prevent locales to kick in",
"days_of_week",
"=",
"{",
"0",
":",
"\"Monday\"",
",",
"1",
":",
"\"Tuesday\"",
",",
"2",
":",
"\"Wednesday\"",
",",
"3",
":",
"\"Thursday\"",
",",
"4",
":",
"\"Friday\... | 23.2 | 19.533333 |
def prepare_docset(
source, dest, name, index_page, enable_js, online_redirect_url
):
"""
Create boilerplate files & directories and copy vanilla docs inside.
Return a tuple of path to resources and connection to sqlite db.
"""
resources = os.path.join(dest, "Contents", "Resources")
docs = ... | [
"def",
"prepare_docset",
"(",
"source",
",",
"dest",
",",
"name",
",",
"index_page",
",",
"enable_js",
",",
"online_redirect_url",
")",
":",
"resources",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dest",
",",
"\"Contents\"",
",",
"\"Resources\"",
")",
"doc... | 32.153846 | 19.897436 |
def match(self, messy_data, threshold=0.5, n_matches=1, generator=False): # pragma: no cover
"""Identifies pairs of records that refer to the same entity, returns
tuples containing a set of record ids and a confidence score as a float
between 0 and 1. The record_ids within each set should refer... | [
"def",
"match",
"(",
"self",
",",
"messy_data",
",",
"threshold",
"=",
"0.5",
",",
"n_matches",
"=",
"1",
",",
"generator",
"=",
"False",
")",
":",
"# pragma: no cover",
"blocked_pairs",
"=",
"self",
".",
"_blockData",
"(",
"messy_data",
")",
"clusters",
"... | 44.25 | 27.194444 |
def from_query(query, engine=None, limit=None):
"""
Execute an ORM style query, and return the result in
:class:`prettytable.PrettyTable`.
:param query: an ``sqlalchemy.orm.Query`` object.
:param engine: an ``sqlalchemy.engine.base.Engine`` object.
:param limit: int, limit rows to return.
... | [
"def",
"from_query",
"(",
"query",
",",
"engine",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"if",
"limit",
"is",
"not",
"None",
":",
"query",
"=",
"query",
".",
"limit",
"(",
"limit",
")",
"result_proxy",
"=",
"execute_query_return_result_proxy",
... | 30.157895 | 16.578947 |
def enable_cloud_integration(self, id, **kwargs): # noqa: E501
"""Enable a specific cloud integration # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.enable_c... | [
"def",
"enable_cloud_integration",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"ena... | 43.238095 | 20.047619 |
def H9(self):
"Entropy."
if not hasattr(self, '_H9'):
self._H9 = -(self.P * np.log(self.P + self.eps)).sum(2).sum(1)
return self._H9 | [
"def",
"H9",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_H9'",
")",
":",
"self",
".",
"_H9",
"=",
"-",
"(",
"self",
".",
"P",
"*",
"np",
".",
"log",
"(",
"self",
".",
"P",
"+",
"self",
".",
"eps",
")",
")",
".",
"s... | 32.8 | 20.8 |
def publish(dataset_uri):
"""Return access URL to HTTP enabled (published) dataset.
Exits with error code 1 if the dataset_uri is not a dataset.
Exits with error code 2 if the dataset cannot be HTTP enabled.
"""
try:
dataset = dtoolcore.DataSet.from_uri(dataset_uri)
except dtoolcore.Dt... | [
"def",
"publish",
"(",
"dataset_uri",
")",
":",
"try",
":",
"dataset",
"=",
"dtoolcore",
".",
"DataSet",
".",
"from_uri",
"(",
"dataset_uri",
")",
"except",
"dtoolcore",
".",
"DtoolCoreTypeError",
":",
"print",
"(",
"\"Not a dataset: {}\"",
".",
"format",
"(",... | 29.304348 | 22.086957 |
def get_uint16(self):
"""Read the next token and interpret it as a 16-bit unsigned
integer.
@raises dns.exception.SyntaxError:
@rtype: int
"""
value = self.get_int()
if value < 0 or value > 65535:
raise dns.exception.SyntaxError('%d is not an unsigne... | [
"def",
"get_uint16",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"get_int",
"(",
")",
"if",
"value",
"<",
"0",
"or",
"value",
">",
"65535",
":",
"raise",
"dns",
".",
"exception",
".",
"SyntaxError",
"(",
"'%d is not an unsigned 16-bit integer'",
"%",... | 29.666667 | 19.083333 |
def mousePressEvent(self, event):
"""
Overloads when a mouse press occurs. If in editable mode, and the
click occurs on a selected index, then the editor will be created
and no selection change will occur.
:param event | <QMousePressEvent>
"""
item ... | [
"def",
"mousePressEvent",
"(",
"self",
",",
"event",
")",
":",
"item",
"=",
"self",
".",
"itemAt",
"(",
"event",
".",
"pos",
"(",
")",
")",
"column",
"=",
"self",
".",
"columnAt",
"(",
"event",
".",
"pos",
"(",
")",
".",
"x",
"(",
")",
")",
"mi... | 37.638889 | 18.694444 |
def format(self, record):
"""Space debug messages for more legibility."""
if record.levelno == logging.DEBUG:
record.msg = ' {}'.format(record.msg)
return super(AuditLogFormatter, self).format(record) | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"if",
"record",
".",
"levelno",
"==",
"logging",
".",
"DEBUG",
":",
"record",
".",
"msg",
"=",
"' {}'",
".",
"format",
"(",
"record",
".",
"msg",
")",
"return",
"super",
"(",
"AuditLogFormatter",
... | 46.4 | 9.4 |
def transform(self, buffer, mode=None, vertices=-1, *, first=0, instances=1) -> None:
'''
Transform vertices.
Stores the output in a single buffer.
The transform primitive (mode) must be the same as
the input primitive of the GeometryShader.
Args:
... | [
"def",
"transform",
"(",
"self",
",",
"buffer",
",",
"mode",
"=",
"None",
",",
"vertices",
"=",
"-",
"1",
",",
"*",
",",
"first",
"=",
"0",
",",
"instances",
"=",
"1",
")",
"->",
"None",
":",
"if",
"mode",
"is",
"None",
":",
"mode",
"=",
"POINT... | 38.095238 | 26.285714 |
def _compute_k(self, tau):
r"""Evaluate the kernel directly at the given values of `tau`.
Parameters
----------
tau : :py:class:`Matrix`, (`M`, `D`)
`M` inputs with dimension `D`.
Returns
-------
k : :py:class:`Array`, (`M`,)
... | [
"def",
"_compute_k",
"(",
"self",
",",
"tau",
")",
":",
"y",
"=",
"self",
".",
"_compute_y",
"(",
"tau",
")",
"return",
"y",
"**",
"(",
"-",
"self",
".",
"params",
"[",
"1",
"]",
")"
] | 30.2 | 14.8 |
def list_subdirs(self, marker=None, limit=None, prefix=None, delimiter=None,
full_listing=False):
"""
Return a list of the namesrepresenting the pseudo-subdirectories in
this container. You can use the marker and limit params to handle
pagination, and the prefix param to filt... | [
"def",
"list_subdirs",
"(",
"self",
",",
"marker",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"delimiter",
"=",
"None",
",",
"full_listing",
"=",
"False",
")",
":",
"return",
"self",
".",
"manager",
".",
"list_subdirs",
"(... | 56.818182 | 23.545455 |
def _send_commit_request(self, retry_delay=None, attempt=None):
"""Send a commit request with our last_processed_offset"""
# If there's a _commit_call, and it's not active, clear it, it probably
# just called us...
if self._commit_call and not self._commit_call.active():
self... | [
"def",
"_send_commit_request",
"(",
"self",
",",
"retry_delay",
"=",
"None",
",",
"attempt",
"=",
"None",
")",
":",
"# If there's a _commit_call, and it's not active, clear it, it probably",
"# just called us...",
"if",
"self",
".",
"_commit_call",
"and",
"not",
"self",
... | 43.228571 | 18.942857 |
def save(self, filename):
"""Save metadata to XML file"""
with io.open(filename,'w',encoding='utf-8') as f:
f.write(self.xml()) | [
"def",
"save",
"(",
"self",
",",
"filename",
")",
":",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"self",
".",
"xml",
"(",
")",
")"
] | 38 | 10.25 |
def get_hash(self, ireq, ireq_hashes=None):
"""
Retrieve hashes for a specific ``InstallRequirement`` instance.
:param ireq: An ``InstallRequirement`` to retrieve hashes for
:type ireq: :class:`~pip_shims.InstallRequirement`
:return: A set of hashes.
:rtype: Set
... | [
"def",
"get_hash",
"(",
"self",
",",
"ireq",
",",
"ireq_hashes",
"=",
"None",
")",
":",
"# We _ALWAYS MUST PRIORITIZE_ the inclusion of hashes from local sources",
"# PLEASE *DO NOT MODIFY THIS* TO CHECK WHETHER AN IREQ ALREADY HAS A HASH",
"# RESOLVED. The resolver will pull hashes from... | 44.606061 | 21.333333 |
def encode(self, word):
"""Return the Norphone code.
Parameters
----------
word : str
The word to transform
Returns
-------
str
The Norphone code
Examples
--------
>>> pe = Norphone()
>>> pe.encode('Hansen... | [
"def",
"encode",
"(",
"self",
",",
"word",
")",
":",
"word",
"=",
"word",
".",
"upper",
"(",
")",
"code",
"=",
"''",
"skip",
"=",
"0",
"if",
"word",
"[",
"0",
":",
"2",
"]",
"==",
"'AA'",
":",
"code",
"=",
"'Å'",
"skip",
"=",
"2",
"elif",
"... | 25.39759 | 19.843373 |
def _fetchall(self, query, vars, limit=None, offset=0):
"""
Return multiple rows.
"""
if limit is None:
limit = current_app.config['DEFAULT_PAGE_SIZE']
query += ' LIMIT %s OFFSET %s''' % (limit, offset)
cursor = self.get_db().cursor()
self._log(cursor,... | [
"def",
"_fetchall",
"(",
"self",
",",
"query",
",",
"vars",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"0",
")",
":",
"if",
"limit",
"is",
"None",
":",
"limit",
"=",
"current_app",
".",
"config",
"[",
"'DEFAULT_PAGE_SIZE'",
"]",
"query",
"+=",
"'... | 35.636364 | 8.545455 |
def get_logged_in_account(token_manager=None,
app_url=defaults.APP_URL):
"""
get the account details for logged in account of the auth token_manager
"""
return get_logged_in_account(token_manager=token_manager,
app_url=app_url)['id'] | [
"def",
"get_logged_in_account",
"(",
"token_manager",
"=",
"None",
",",
"app_url",
"=",
"defaults",
".",
"APP_URL",
")",
":",
"return",
"get_logged_in_account",
"(",
"token_manager",
"=",
"token_manager",
",",
"app_url",
"=",
"app_url",
")",
"[",
"'id'",
"]"
] | 37.75 | 16 |
def merge_global_settings(config, cli_options):
# type: (dict, dict) -> None
"""Merge "global" CLI options into main config
:param dict config: config dict
:param dict cli_options: cli options
"""
# check for valid version from YAML
if (not blobxfer.util.is_none_or_empty(config) and
... | [
"def",
"merge_global_settings",
"(",
"config",
",",
"cli_options",
")",
":",
"# type: (dict, dict) -> None",
"# check for valid version from YAML",
"if",
"(",
"not",
"blobxfer",
".",
"util",
".",
"is_none_or_empty",
"(",
"config",
")",
"and",
"(",
"'version'",
"not",
... | 44.288462 | 13.182692 |
def make_curve(report, success_name, fail_names):
"""
Make a success-failure curve.
:param report: A confidence report
(the type of object saved by make_confidence_report.py)
:param success_name: see plot_report_from_path
:param fail_names: see plot_report_from_path
:returns:
fail_optimal: list of f... | [
"def",
"make_curve",
"(",
"report",
",",
"success_name",
",",
"fail_names",
")",
":",
"success_results",
"=",
"report",
"[",
"success_name",
"]",
"fail_name",
"=",
"None",
"# pacify pylint",
"found",
"=",
"False",
"for",
"fail_name",
"in",
"fail_names",
":",
"... | 41.885714 | 20.674286 |
def matches(self, properties):
"""
Tests if the given criterion matches this LDAP criterion
:param properties: A dictionary of properties
:return: True if the properties matches this criterion, else False
"""
try:
# Use the comparator
return self.... | [
"def",
"matches",
"(",
"self",
",",
"properties",
")",
":",
"try",
":",
"# Use the comparator",
"return",
"self",
".",
"comparator",
"(",
"self",
".",
"value",
",",
"properties",
"[",
"self",
".",
"name",
"]",
")",
"except",
"KeyError",
":",
"# Criterion k... | 35.076923 | 17.692308 |
def fixed_vectors_encoding(index_encoded_sequences, letter_to_vector_df):
"""
Given a `n` x `k` matrix of integers such as that returned by `index_encoding()` and
a dataframe mapping each index to an arbitrary vector, return a `n * k * m`
array where the (`i`, `j`)'th element is `letter_to_vector_df.ilo... | [
"def",
"fixed_vectors_encoding",
"(",
"index_encoded_sequences",
",",
"letter_to_vector_df",
")",
":",
"(",
"num_sequences",
",",
"sequence_length",
")",
"=",
"index_encoded_sequences",
".",
"shape",
"target_shape",
"=",
"(",
"num_sequences",
",",
"sequence_length",
","... | 38.230769 | 25.461538 |
def _numpy24to32bit(data:np.ndarray, bigendian:bool=False) -> np.ndarray:
"""
data is a ubyte array of shape = (size,)
(interleaved channels if multichannel)
"""
target = np.zeros((data.shape[0] * 4 / 3,), dtype=np.ubyte)
if not bigendian:
target[3::4] = data[2::3]
target[2::4] ... | [
"def",
"_numpy24to32bit",
"(",
"data",
":",
"np",
".",
"ndarray",
",",
"bigendian",
":",
"bool",
"=",
"False",
")",
"->",
"np",
".",
"ndarray",
":",
"target",
"=",
"np",
".",
"zeros",
"(",
"(",
"data",
".",
"shape",
"[",
"0",
"]",
"*",
"4",
"/",
... | 31.052632 | 13.263158 |
def _initialize_slots(self, seed, hashvalues):
'''Initialize the slots of the LeanMinHash.
Args:
seed (int): The random seed controls the set of random
permutation functions generated for this LeanMinHash.
hashvalues: The hash values is the internal state of the ... | [
"def",
"_initialize_slots",
"(",
"self",
",",
"seed",
",",
"hashvalues",
")",
":",
"self",
".",
"seed",
"=",
"seed",
"self",
".",
"hashvalues",
"=",
"self",
".",
"_parse_hashvalues",
"(",
"hashvalues",
")"
] | 42.1 | 24.5 |
def create_deep_linking_urls(self, url_params):
"""
Bulk Creates Deep Linking URLs
See the URL https://dev.branch.io/references/http_api/#bulk-creating-deep-linking-urls
:param url_params: Array of values returned from "create_deep_link_url(..., skip_api_call=True)"
:return: Th... | [
"def",
"create_deep_linking_urls",
"(",
"self",
",",
"url_params",
")",
":",
"url",
"=",
"\"/v1/url/bulk/%s\"",
"%",
"self",
".",
"branch_key",
"method",
"=",
"\"POST\"",
"# Checks params",
"self",
".",
"_check_param",
"(",
"value",
"=",
"url_params",
",",
"type... | 34.352941 | 26.823529 |
def get_resource_usage(self):
"""GetResourceUsage.
[Preview API] Gets information about build resources in the system.
:rtype: :class:`<BuildResourceUsage> <azure.devops.v5_0.build.models.BuildResourceUsage>`
"""
response = self._send(http_method='GET',
... | [
"def",
"get_resource_usage",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_send",
"(",
"http_method",
"=",
"'GET'",
",",
"location_id",
"=",
"'3813d06c-9e36-4ea1-aac3-61a485d60e3d'",
",",
"version",
"=",
"'5.0-preview.2'",
")",
"return",
"self",
".",
"_... | 54.111111 | 21.111111 |
def sortino_ratio(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None,
_downside_risk=None):
"""
Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or np.n... | [
"def",
"sortino_ratio",
"(",
"returns",
",",
"required_return",
"=",
"0",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
",",
"_downside_risk",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
... | 29.746835 | 20.531646 |
def select_neighbors_by_layer(docgraph, node, layer, data=False):
"""
Get all neighboring nodes belonging to (any of) the given layer(s),
A neighboring node is a node that the given node connects to with an
outgoing edge.
Parameters
----------
docgraph : DiscourseDocumentGraph
docum... | [
"def",
"select_neighbors_by_layer",
"(",
"docgraph",
",",
"node",
",",
"layer",
",",
"data",
"=",
"False",
")",
":",
"for",
"node_id",
"in",
"docgraph",
".",
"neighbors_iter",
"(",
"node",
")",
":",
"node_layers",
"=",
"docgraph",
".",
"node",
"[",
"node_i... | 37.83871 | 20.225806 |
def scheme_specification(cls):
""" :meth:`.WSchemeHandler.scheme_specification` method implementation
"""
return WSchemeSpecification(
'ftp',
WURIComponentVerifier(WURI.Component.username, WURIComponentVerifier.Requirement.optional),
WURIComponentVerifier(WURI.Component.password, WURIComponentVerifier.Re... | [
"def",
"scheme_specification",
"(",
"cls",
")",
":",
"return",
"WSchemeSpecification",
"(",
"'ftp'",
",",
"WURIComponentVerifier",
"(",
"WURI",
".",
"Component",
".",
"username",
",",
"WURIComponentVerifier",
".",
"Requirement",
".",
"optional",
")",
",",
"WURICom... | 52 | 29.9 |
def script_item_encode(self, target_system, target_component, seq, name):
'''
Message encoding a mission script item. This message is emitted upon a
request for the next script item.
target_system : System ID (uint8_t)
target_c... | [
"def",
"script_item_encode",
"(",
"self",
",",
"target_system",
",",
"target_component",
",",
"seq",
",",
"name",
")",
":",
"return",
"MAVLink_script_item_message",
"(",
"target_system",
",",
"target_component",
",",
"seq",
",",
"name",
")"
] | 52.583333 | 32.916667 |
def to_color(self, value, maxvalue, scale, minvalue=0.0):
"""
convert continuous values into colors using matplotlib colorscales
:param value: value to be converted
:param maxvalue: max value in the colorscale
:param scale: lin, log, sqrt
:param minvalue: minimum of the i... | [
"def",
"to_color",
"(",
"self",
",",
"value",
",",
"maxvalue",
",",
"scale",
",",
"minvalue",
"=",
"0.0",
")",
":",
"if",
"scale",
"==",
"'lin'",
":",
"if",
"minvalue",
">=",
"maxvalue",
":",
"raise",
"Exception",
"(",
"'minvalue must be less than maxvalue'"... | 38.526316 | 19.842105 |
def untldict2py(untl_dict):
"""Convert a UNTL dictionary into a Python object."""
# Create the root element.
untl_root = PYUNTL_DISPATCH['metadata']()
untl_py_list = []
for element_name, element_list in untl_dict.items():
# Loop through the element dictionaries in the element list.
f... | [
"def",
"untldict2py",
"(",
"untl_dict",
")",
":",
"# Create the root element.",
"untl_root",
"=",
"PYUNTL_DISPATCH",
"[",
"'metadata'",
"]",
"(",
")",
"untl_py_list",
"=",
"[",
"]",
"for",
"element_name",
",",
"element_list",
"in",
"untl_dict",
".",
"items",
"("... | 44.25 | 12.807692 |
def _combine_results(self, match_as_dict):
'''Combine results from different parsed parts:
we look for non-empty results in values like
'postal_code_b' or 'postal_code_c' and store
them as main value.
So 'postal_code_b':'123456'
becomes:
... | [
"def",
"_combine_results",
"(",
"self",
",",
"match_as_dict",
")",
":",
"keys",
"=",
"[",
"]",
"vals",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"match_as_dict",
")",
":",
"if",
"k",
"[",
"-",
"2",
":",
"]",
"in",
... | 37.217391 | 12.26087 |
def goodnode(self, nodelist):
''' Goes through the provided list
and returns the first server node
that does not return an error.
'''
l = len(nodelist)
for n in range(self.current_node(l), l):
self.msg.message("Trying node " + str(n) + ": " + nodelist[n])
... | [
"def",
"goodnode",
"(",
"self",
",",
"nodelist",
")",
":",
"l",
"=",
"len",
"(",
"nodelist",
")",
"for",
"n",
"in",
"range",
"(",
"self",
".",
"current_node",
"(",
"l",
")",
",",
"l",
")",
":",
"self",
".",
"msg",
".",
"message",
"(",
"\"Trying n... | 39.411765 | 13.058824 |
def connect_socket(root_dir):
"""Connect to a daemon's socket.
Args:
root_dir (str): The directory that used as root by the daemon.
Returns:
socket.socket: A socket that is connected to the daemon.
"""
# Get config directory where the daemon socket is located
config_dir = os.pa... | [
"def",
"connect_socket",
"(",
"root_dir",
")",
":",
"# Get config directory where the daemon socket is located",
"config_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root_dir",
",",
"'.config/pueue'",
")",
"# Create Socket and exit with 1, if socket can't be created",
"tr... | 32.92 | 21.36 |
def Decode(self, encoded_data):
"""Decode the encoded data.
Args:
encoded_data (byte): encoded data.
Returns:
tuple(bytes, bytes): decoded data and remaining encoded data.
Raises:
BackEndError: if the base32 stream cannot be decoded.
"""
try:
decoded_data = base64.b32d... | [
"def",
"Decode",
"(",
"self",
",",
"encoded_data",
")",
":",
"try",
":",
"decoded_data",
"=",
"base64",
".",
"b32decode",
"(",
"encoded_data",
",",
"casefold",
"=",
"False",
")",
"except",
"(",
"TypeError",
",",
"binascii",
".",
"Error",
")",
"as",
"exce... | 27.4 | 21.9 |
def start(self, retry_limit=None):
"""
Try to connect to Twitter's streaming API.
:param retry_limit: The maximum number of retries in case of failures. Default is None (unlimited)
:raises :class:`~tweepy.error.TweepyError`: If there's some critical API error
"""
# Run t... | [
"def",
"start",
"(",
"self",
",",
"retry_limit",
"=",
"None",
")",
":",
"# Run tweepy stream",
"wrapper_listener",
"=",
"TweepyWrapperListener",
"(",
"listener",
"=",
"self",
".",
"listener",
")",
"stream",
"=",
"tweepy",
".",
"Stream",
"(",
"auth",
"=",
"se... | 45.8 | 24.666667 |
def get_pallete_length(grid):
"""
Takes a 2d grid and figures out how many different elements are in it, so
that we know how big to make the palette. Also avoids the unfortunate
red/green palette that results from too few elements.
Returns int indicating the length the palette should have.
"""
... | [
"def",
"get_pallete_length",
"(",
"grid",
")",
":",
"elements",
"=",
"list",
"(",
"set",
"(",
"flatten_array",
"(",
"grid",
")",
")",
")",
"length",
"=",
"len",
"(",
"elements",
")",
"if",
"type",
"(",
"elements",
"[",
"0",
"]",
")",
"is",
"str",
"... | 38.375 | 19.5 |
def _run(self):
"""Internal function to run the impact function with profiling."""
LOGGER.info('ANALYSIS : The impact function is starting.')
step_count = len(analysis_steps)
self.callback(0, step_count, analysis_steps['initialisation'])
# Set a unique name for this impact
... | [
"def",
"_run",
"(",
"self",
")",
":",
"LOGGER",
".",
"info",
"(",
"'ANALYSIS : The impact function is starting.'",
")",
"step_count",
"=",
"len",
"(",
"analysis_steps",
")",
"self",
".",
"callback",
"(",
"0",
",",
"step_count",
",",
"analysis_steps",
"[",
"'in... | 46.525424 | 20.166102 |
def reset_all_to_coefficients(self):
""" Resets the IOSystem and all extensions to coefficients.
This method calls reset_to_coefficients for the IOSystem and for
all Extensions in the system
Note
-----
The system can not be reconstructed after this steps
becaus... | [
"def",
"reset_all_to_coefficients",
"(",
"self",
")",
":",
"self",
".",
"reset_to_coefficients",
"(",
")",
"[",
"ee",
".",
"reset_to_coefficients",
"(",
")",
"for",
"ee",
"in",
"self",
".",
"get_extensions",
"(",
"data",
"=",
"True",
")",
"]",
"self",
".",... | 34.333333 | 22 |
def insert(self, table, kwargs, execute=True):
""".. :py:method::
Usage::
>>> insert('hospital', {'id': '12de3wrv', 'province': 'shanghai'})
insert into hospital (id, province) values ('12de3wrv', 'shanghai');
:param string table: table name
:param dict kwargs:... | [
"def",
"insert",
"(",
"self",
",",
"table",
",",
"kwargs",
",",
"execute",
"=",
"True",
")",
":",
"sql",
"=",
"\"insert into \"",
"+",
"table",
"+",
"\" ({}) values ({});\"",
"keys",
",",
"values",
"=",
"[",
"]",
",",
"[",
"]",
"[",
"(",
"keys",
".",... | 36.136364 | 23 |
def resolve_operands(self, encoding_map, operation, pc):
"""
Converts generic register references (such as $t0, $t1, etc), immediate values, and jump addresses
to their binary equivalents.
"""
convert = Encoder.to_binary
branch_replace = False
jump_replace = False... | [
"def",
"resolve_operands",
"(",
"self",
",",
"encoding_map",
",",
"operation",
",",
"pc",
")",
":",
"convert",
"=",
"Encoder",
".",
"to_binary",
"branch_replace",
"=",
"False",
"jump_replace",
"=",
"False",
"for",
"operand",
",",
"value",
"in",
"encoding_map",... | 44.836364 | 24.4 |
async def Set(self, annotations):
'''
annotations : typing.Sequence[~EntityAnnotations]
Returns -> typing.Sequence[~ErrorResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Annotations',
request='Set',
v... | [
"async",
"def",
"Set",
"(",
"self",
",",
"annotations",
")",
":",
"# map input types to rpc msg",
"_params",
"=",
"dict",
"(",
")",
"msg",
"=",
"dict",
"(",
"type",
"=",
"'Annotations'",
",",
"request",
"=",
"'Set'",
",",
"version",
"=",
"2",
",",
"param... | 32.357143 | 11.785714 |
def FIR_fix_header(fname_out, h):
"""
Write FIR Fixed-Point Filter Header Files
Mark Wickert February 2015
"""
M = len(h)
hq = int16(rint(h * 2 ** 15))
N = 8 # Coefficients per line
f = open(fname_out, 'wt')
f.write('//define a FIR coefficient Array\n\n')
f.writ... | [
"def",
"FIR_fix_header",
"(",
"fname_out",
",",
"h",
")",
":",
"M",
"=",
"len",
"(",
"h",
")",
"hq",
"=",
"int16",
"(",
"rint",
"(",
"h",
"*",
"2",
"**",
"15",
")",
")",
"N",
"=",
"8",
"# Coefficients per line\r",
"f",
"=",
"open",
"(",
"fname_ou... | 34.235294 | 15.176471 |
def __get_query_agg_ts(cls, field, time_field, interval=None,
time_zone=None, start=None, end=None,
agg_type='count', offset=None):
"""
Create an es_dsl aggregation object for getting the time series values for a field.
:param field: field t... | [
"def",
"__get_query_agg_ts",
"(",
"cls",
",",
"field",
",",
"time_field",
",",
"interval",
"=",
"None",
",",
"time_zone",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"agg_type",
"=",
"'count'",
",",
"offset",
"=",
"None",
")",... | 48.192308 | 26.634615 |
def fun_wv(xchannel, crpix1, crval1, cdelt1):
"""Compute wavelengths from channels.
The wavelength calibration is provided through the usual parameters
CRPIX1, CRVAL1 and CDELT1.
Parameters
----------
xchannel : numpy array
Input channels where the wavelengths will be evaluated.
cr... | [
"def",
"fun_wv",
"(",
"xchannel",
",",
"crpix1",
",",
"crval1",
",",
"cdelt1",
")",
":",
"wv",
"=",
"crval1",
"+",
"(",
"xchannel",
"-",
"crpix1",
")",
"*",
"cdelt1",
"return",
"wv"
] | 22.4 | 21.52 |
def NewFromJSON(data):
"""
Create a new SharedFile instance from a JSON dict.
Args:
data (dict): JSON dictionary representing a SharedFile.
Returns:
A SharedFile instance.
"""
return SharedFile(
sharekey=data.get('sharekey', None),
... | [
"def",
"NewFromJSON",
"(",
"data",
")",
":",
"return",
"SharedFile",
"(",
"sharekey",
"=",
"data",
".",
"get",
"(",
"'sharekey'",
",",
"None",
")",
",",
"name",
"=",
"data",
".",
"get",
"(",
"'name'",
",",
"None",
")",
",",
"user",
"=",
"User",
"."... | 36.3 | 11.766667 |
def dumpBlock(self, block_name):
"""
API the list all information related with the block_name
:param block_name: Name of block to be dumped (Required)
:type block_name: str
"""
try:
return self.dbsBlock.dumpBlock(block_name)
except HTTPError as he:
... | [
"def",
"dumpBlock",
"(",
"self",
",",
"block_name",
")",
":",
"try",
":",
"return",
"self",
".",
"dbsBlock",
".",
"dumpBlock",
"(",
"block_name",
")",
"except",
"HTTPError",
"as",
"he",
":",
"raise",
"he",
"except",
"dbsException",
"as",
"de",
":",
"dbsE... | 39.833333 | 22.055556 |
def _zero_many(self, i, j):
"""Sets value at each (i, j) to zero, preserving sparsity structure.
Here (i,j) index major and minor respectively.
"""
i, j, M, N = self._prepare_indices(i, j)
n_samples = len(i)
offsets = np.empty(n_samples, dtype=self.indices.dtype)
ret = _sparsetools.csr_sam... | [
"def",
"_zero_many",
"(",
"self",
",",
"i",
",",
"j",
")",
":",
"i",
",",
"j",
",",
"M",
",",
"N",
"=",
"self",
".",
"_prepare_indices",
"(",
"i",
",",
"j",
")",
"n_samples",
"=",
"len",
"(",
"i",
")",
"offsets",
"=",
"np",
".",
"empty",
"(",... | 38.65 | 18.7 |
def _update_bcbiovm():
"""Update or install a local bcbiovm install with tools and dependencies.
"""
print("## CWL support with bcbio-vm")
python_env = "python=3"
conda_bin, env_name = _add_environment("bcbiovm", python_env)
channels = _get_conda_channels(conda_bin)
base_cmd = [conda_bin, "i... | [
"def",
"_update_bcbiovm",
"(",
")",
":",
"print",
"(",
"\"## CWL support with bcbio-vm\"",
")",
"python_env",
"=",
"\"python=3\"",
"conda_bin",
",",
"env_name",
"=",
"_add_environment",
"(",
"\"bcbiovm\"",
",",
"python_env",
")",
"channels",
"=",
"_get_conda_channels"... | 50.636364 | 17.181818 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.