text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def fail(message=None, exit_status=None): """Prints the specified message and exits the program with the specified exit status. """ print('Error:', message, file=sys.stderr) sys.exit(exit_status or 1)
[ "def", "fail", "(", "message", "=", "None", ",", "exit_status", "=", "None", ")", ":", "print", "(", "'Error:'", ",", "message", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "exit_status", "or", "1", ")" ]
30.714286
11.428571
def get(self, vehicle_id, command, wake_if_asleep=False): # pylint: disable=unused-argument """Send get command to the vehicle_id. This is a wrapped function by wake_up. Parameters ---------- vehicle_id : string Identifier for the car on the owner-api endpo...
[ "def", "get", "(", "self", ",", "vehicle_id", ",", "command", ",", "wake_if_asleep", "=", "False", ")", ":", "# pylint: disable=unused-argument", "return", "self", ".", "__connection", ".", "get", "(", "'vehicles/%i/%s'", "%", "(", "vehicle_id", ",", "command",...
35.692308
22.730769
def initialize_delete_state_map(self): """This is a mapping of delete result message string to state. """ self.fabric_state_del_map = { fw_const.INIT_STATE_STR: fw_const.OS_IN_NETWORK_STATE, fw_const.OS_IN_NETWORK_DEL_FAIL: fw_const.OS_IN_NETWORK_STATE, ...
[ "def", "initialize_delete_state_map", "(", "self", ")", ":", "self", ".", "fabric_state_del_map", "=", "{", "fw_const", ".", "INIT_STATE_STR", ":", "fw_const", ".", "OS_IN_NETWORK_STATE", ",", "fw_const", ".", "OS_IN_NETWORK_DEL_FAIL", ":", "fw_const", ".", "OS_IN_N...
47.305556
6.861111
def release(self, shortname): """ Get a specific release by its shortname. :param shortname: str, eg. "ceph-3-0" :returns: deferred that when fired returns a Release (Munch, dict-like) object representing this release. :raises: ReleaseNotFoundException if this ...
[ "def", "release", "(", "self", ",", "shortname", ")", ":", "url", "=", "'api/v6/releases/?shortname=%s'", "%", "shortname", "releases", "=", "yield", "self", ".", "_get", "(", "url", ")", "# Note, even if this shortname does not exist, _get() will not errback", "# for t...
44.777778
17
def index_template_present(name, definition, check_definition=False): ''' Ensure that the named index template is present. name Name of the index to add definition Required dict for creation parameters as per https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templa...
[ "def", "index_template_present", "(", "name", ",", "definition", ",", "check_definition", "=", "False", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "...
44.72
26.88
def flatatt(attrs): """ Pilfered from `django.forms.utils`: Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. In the case of a boolean value, the key will appear without a value. Otherwise, the value ...
[ "def", "flatatt", "(", "attrs", ")", ":", "key_value_attrs", "=", "[", "]", "boolean_attrs", "=", "[", "]", "for", "attr", ",", "value", "in", "attrs", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "if", "val...
36.419355
20.354839
def get_hyperedge_attributes(self, hyperedge_id): """Given a hyperedge ID, get a dictionary of copies of that hyperedge's attributes. :param hyperedge_id: ID of the hyperedge to retrieve the attributes of. :returns: dict -- copy of each attribute of the specified hyperedge_id ...
[ "def", "get_hyperedge_attributes", "(", "self", ",", "hyperedge_id", ")", ":", "if", "not", "self", ".", "has_hyperedge_id", "(", "hyperedge_id", ")", ":", "raise", "ValueError", "(", "\"No such hyperedge exists.\"", ")", "dict_to_copy", "=", "self", ".", "_hypere...
45.111111
19.333333
def accept(self, evt): """ write setting to the preferences """ # determine if application is a script file or frozen exe (pyinstaller) frozen = getattr(sys, 'frozen', False) if frozen: app_file = sys.executable else: app_file = Pa...
[ "def", "accept", "(", "self", ",", "evt", ")", ":", "# determine if application is a script file or frozen exe (pyinstaller)\r", "frozen", "=", "getattr", "(", "sys", ",", "'frozen'", ",", "False", ")", "if", "frozen", ":", "app_file", "=", "sys", ".", "executable...
42.837838
19.864865
def refresher(name, refreshers=CompletionRefresher.refreshers): """Decorator to add the decorated function to the dictionary of refreshers. Any function decorated with a @refresher will be executed as part of the completion refresh routine.""" def wrapper(wrapped): refreshers[name] = wrapped ...
[ "def", "refresher", "(", "name", ",", "refreshers", "=", "CompletionRefresher", ".", "refreshers", ")", ":", "def", "wrapper", "(", "wrapped", ")", ":", "refreshers", "[", "name", "]", "=", "wrapped", "return", "wrapped", "return", "wrapper" ]
43.875
15
def put_stream(self, bucket, label, stream_object, params={}): ''' Create a new file to swift object storage. ''' self.claim_bucket(bucket) self.connection.put_object(bucket, label, stream_object, headers=self._convert_to_meta(params))
[ "def", "put_stream", "(", "self", ",", "bucket", ",", "label", ",", "stream_object", ",", "params", "=", "{", "}", ")", ":", "self", ".", "claim_bucket", "(", "bucket", ")", "self", ".", "connection", ".", "put_object", "(", "bucket", ",", "label", ","...
58.2
20.6
def traverse(self, window_length, offset=0, perspective_offset=0): """ Produce an iterator rolling windows rows over our data. Each emitted window will have `window_length` rows. Parameters ---------- window_length : int...
[ "def", "traverse", "(", "self", ",", "window_length", ",", "offset", "=", "0", ",", "perspective_offset", "=", "0", ")", ":", "data", "=", "self", ".", "_data", ".", "copy", "(", ")", "_check_window_params", "(", "data", ",", "window_length", ")", "retur...
32.586207
14.793103
def create_account(self, currency=None): """ Create a new account. This call is only available on the sandbox system. Please create accounts on fxtrade.oanda.com on our production system. See more: http://developer.oanda.com/rest-sandbox/accounts/#-a...
[ "def", "create_account", "(", "self", ",", "currency", "=", "None", ")", ":", "url", "=", "\"{0}/{1}/accounts\"", ".", "format", "(", "self", ".", "domain", ",", "self", ".", "API_VERSION", ")", "params", "=", "{", "\"currency\"", ":", "currency", "}", "...
37.611111
21.722222
def action(self, arg): """Delegate the actions specified in 'arg' to another method. """ if not arg: self.info_signal(['handle']) return True args = arg.split() signame = args[0] signame = self.is_name_or_number(args[0]) if not sign...
[ "def", "action", "(", "self", ",", "arg", ")", ":", "if", "not", "arg", ":", "self", ".", "info_signal", "(", "[", "'handle'", "]", ")", "return", "True", "args", "=", "arg", ".", "split", "(", ")", "signame", "=", "args", "[", "0", "]", "signame...
34.152174
14.717391
def _check_image_size(self, size): """ Check and fix the size of the image to 32 bits """ if size % 32 == 0: return (0, 0) else: image_border = 32 - (size % 32) if (image_border % 2) == 0: return (image_border / 2, image_border / 2) ...
[ "def", "_check_image_size", "(", "self", ",", "size", ")", ":", "if", "size", "%", "32", "==", "0", ":", "return", "(", "0", ",", "0", ")", "else", ":", "image_border", "=", "32", "-", "(", "size", "%", "32", ")", "if", "(", "image_border", "%", ...
38.3
13.3
def poke(self, context): """ poke for a non empty directory :return: Bool depending on the search criteria """ sb = self.hook(self.hdfs_conn_id).get_conn() result = [f for f in sb.ls([self.filepath], include_toplevel=True)] result = self.filter_for_ignored_ext(re...
[ "def", "poke", "(", "self", ",", "context", ")", ":", "sb", "=", "self", ".", "hook", "(", "self", ".", "hdfs_conn_id", ")", ".", "get_conn", "(", ")", "result", "=", "[", "f", "for", "f", "in", "sb", ".", "ls", "(", "[", "self", ".", "filepath...
46.944444
22.944444
def list_all_zones_by_id(region=None, key=None, keyid=None, profile=None): ''' List, by their IDs, all hosted zones in the bound account. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and k...
[ "def", "list_all_zones_by_id", "(", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "describe_hosted_zones", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid...
25.807692
27.346154
def constants(self): """ sequence of tuples (index, type, dereferenced value) of the constant pool entries. """ for i in range(1, len(self.consts)): t, _v = self.consts[i] if t: yield (i, t, self.deref_const(i))
[ "def", "constants", "(", "self", ")", ":", "for", "i", "in", "range", "(", "1", ",", "len", "(", "self", ".", "consts", ")", ")", ":", "t", ",", "_v", "=", "self", ".", "consts", "[", "i", "]", "if", "t", ":", "yield", "(", "i", ",", "t", ...
28.3
13.9
def main(): """pyprf_sim entry point.""" # Get list of input arguments (without first one, which is the path to the # function that is called): --NOTE: This is another way of accessing # input arguments, but since we use 'argparse' it is redundant. # lstArgs = sys.argv[1:] strWelcome = 'pyprf_s...
[ "def", "main", "(", ")", ":", "# Get list of input arguments (without first one, which is the path to the", "# function that is called): --NOTE: This is another way of accessing", "# input arguments, but since we use 'argparse' it is redundant.", "# lstArgs = sys.argv[1:]", "strWelcome", "=", ...
41.333333
24.296296
def movie(args): """ %prog movie test.tour test.clm ref.contigs.last Plot optimization history. """ p = OptionParser(movie.__doc__) p.add_option("--frames", default=500, type="int", help="Only plot every N frames") p.add_option("--engine", default="ffmpeg", choices=("ffmpeg...
[ "def", "movie", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "movie", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--frames\"", ",", "default", "=", "500", ",", "type", "=", "\"int\"", ",", "help", "=", "\"Only plot every N frames\"", ")...
35.253968
17.666667
def observable_copy(value, name, instance): """Return an observable container for HasProperties notifications This method creates a new container class to allow HasProperties instances to :code:`observe_mutations`. It returns a copy of the input value as this new class. The output class behaves id...
[ "def", "observable_copy", "(", "value", ",", "name", ",", "instance", ")", ":", "container_class", "=", "value", ".", "__class__", "if", "container_class", "in", "OBSERVABLE_REGISTRY", ":", "observable_class", "=", "OBSERVABLE_REGISTRY", "[", "container_class", "]",...
38.483871
17.903226
def is_leaf(self): """ Returns True if a Node has no subnodes >>> Node().is_leaf True >>> Node( 1, left=Node(2) ).is_leaf False """ return (not self.data) or \ (all(not bool(c) for c, p in self.children))
[ "def", "is_leaf", "(", "self", ")", ":", "return", "(", "not", "self", ".", "data", ")", "or", "(", "all", "(", "not", "bool", "(", "c", ")", "for", "c", ",", "p", "in", "self", ".", "children", ")", ")" ]
24.272727
18
def command(state, args): """List file priority rules.""" rules = query.files.get_priority_rules(state.db) print(tabulate(rules, headers=['ID', 'Regexp', 'Priority']))
[ "def", "command", "(", "state", ",", "args", ")", ":", "rules", "=", "query", ".", "files", ".", "get_priority_rules", "(", "state", ".", "db", ")", "print", "(", "tabulate", "(", "rules", ",", "headers", "=", "[", "'ID'", ",", "'Regexp'", ",", "'Pri...
44
12.75
def parse_resources_directory(self, rva, size=0, base_rva = None, level = 0, dirs=None): """Parse the resources directory. Given the RVA of the resources directory, it will process all its entries. The root will have the corresponding member of its structure, IM...
[ "def", "parse_resources_directory", "(", "self", ",", "rva", ",", "size", "=", "0", ",", "base_rva", "=", "None", ",", "level", "=", "0", ",", "dirs", "=", "None", ")", ":", "# OC Patch:", "if", "dirs", "is", "None", ":", "dirs", "=", "[", "rva", "...
41.493274
19.896861
def _GenOpenApiSpec(service_class_names, output_path, hostname=None, application_path=None, x_google_api_name=False): """Write openapi documents generated from the service classes to file. Args: service_class_names: A list of fully qualified ProtoRPC service names. output_path: The dire...
[ "def", "_GenOpenApiSpec", "(", "service_class_names", ",", "output_path", ",", "hostname", "=", "None", ",", "application_path", "=", "None", ",", "x_google_api_name", "=", "False", ")", ":", "output_files", "=", "[", "]", "service_configs", "=", "GenApiConfig", ...
44.192308
22.230769
def log_message(self, kind, alert): """Parses different event types and passes them to logging""" if kind == 'ERROR': logging.error(alert) else: logging.warning(alert) return
[ "def", "log_message", "(", "self", ",", "kind", ",", "alert", ")", ":", "if", "kind", "==", "'ERROR'", ":", "logging", ".", "error", "(", "alert", ")", "else", ":", "logging", ".", "warning", "(", "alert", ")", "return" ]
32
12.142857
def run(self): """ Starts the server run loop and returns after the server shuts down due to a shutdown-request, Harakiri signal, or unhandled exception. See the documentation for `Server.main` for full details on the chain of `Server` method calls. """ self.logger.info(...
[ "def", "run", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "'Service \"{service}\" server starting up, pysoa version {pysoa}, listening on transport {transport}.'", ".", "format", "(", "service", "=", "self", ".", "service_name", ",", "pysoa", "=", ...
40.083333
21.083333
def del_option(self, section, option): """ Deletes an option if the section and option exist """ if self.config.has_section(section): if self.config.has_option(section, option): self.config.remove_option(section, option) return (True, self.config.options(secti...
[ "def", "del_option", "(", "self", ",", "section", ",", "option", ")", ":", "if", "self", ".", "config", ".", "has_section", "(", "section", ")", ":", "if", "self", ".", "config", ".", "has_option", "(", "section", ",", "option", ")", ":", "self", "."...
56.375
13.75
def _publish_message(host, amqp_settings, routing_key, data): """Publish an AMQP message. Returns: bool: True if message was sent successfully. """ if host == "stdout": print("Published to %s: %s" % (routing_key, data)) return True try: conn = Connection(**remove_no...
[ "def", "_publish_message", "(", "host", ",", "amqp_settings", ",", "routing_key", ",", "data", ")", ":", "if", "host", "==", "\"stdout\"", ":", "print", "(", "\"Published to %s: %s\"", "%", "(", "routing_key", ",", "data", ")", ")", "return", "True", "try", ...
27.186047
20.023256
def bar_amplitude(self): "返回bar振幅" res = (self.high - self.low) / self.low res.name = 'bar_amplitude' return res
[ "def", "bar_amplitude", "(", "self", ")", ":", "res", "=", "(", "self", ".", "high", "-", "self", ".", "low", ")", "/", "self", ".", "low", "res", ".", "name", "=", "'bar_amplitude'", "return", "res" ]
28
14.8
def AsDict(self): """Represents an artifact as a dictionary. Returns: dict[str, object]: artifact attributes. """ sources = [] for source in self.sources: source_definition = { 'type': source.type_indicator, 'attributes': source.AsDict() } if source.suppo...
[ "def", "AsDict", "(", "self", ")", ":", "sources", "=", "[", "]", "for", "source", "in", "self", ".", "sources", ":", "source_definition", "=", "{", "'type'", ":", "source", ".", "type_indicator", ",", "'attributes'", ":", "source", ".", "AsDict", "(", ...
30.029412
15.764706
def generate_sitemap(sitemap: typing.Mapping, prefix: list=None): """Create a sitemap template from the given sitemap. The `sitemap` should be a mapping where the key is a string which represents a single URI segment, and the value is either another mapping or a callable (e.g. function) object. Ar...
[ "def", "generate_sitemap", "(", "sitemap", ":", "typing", ".", "Mapping", ",", "prefix", ":", "list", "=", "None", ")", ":", "# Ensures all generated urls are prefixed with a the prefix string", "if", "prefix", "is", "None", ":", "prefix", "=", "[", "]", "for", ...
41.152174
23.173913
def get_lldp_neighbor_detail_input_request_type_get_request_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail") config = get_lldp_neighbor_detail input = ET.SubElement(g...
[ "def", "get_lldp_neighbor_detail_input_request_type_get_request_interface_type", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_lldp_neighbor_detail", "=", "ET", ".", "Element", "(", "\"get_lldp_neighb...
48.928571
19.142857
def _add_minimization_vars(self): """Add variables and constraints for L1 norm minimization.""" self._z = self._prob.namespace(self._model.reactions, lower=0) # Define constraints v = self._v.set(self._model.reactions) z = self._z.set(self._model.reactions) self._prob....
[ "def", "_add_minimization_vars", "(", "self", ")", ":", "self", ".", "_z", "=", "self", ".", "_prob", ".", "namespace", "(", "self", ".", "_model", ".", "reactions", ",", "lower", "=", "0", ")", "# Define constraints", "v", "=", "self", ".", "_v", ".",...
35
19.9
def notify(self, subsystem, recipient, subject, body_html, body_text): """You can send messages either to channels and private groups by using the following formats #channel-name @username-direct-message Args: subsystem (`str`): Name of the subsystem originating the notific...
[ "def", "notify", "(", "self", ",", "subsystem", ",", "recipient", ",", "subject", ",", "body_html", ",", "body_text", ")", ":", "if", "not", "re", ".", "match", "(", "self", ".", "validation", ",", "recipient", ",", "re", ".", "I", ")", ":", "raise",...
35.236842
22.921053
def run(self, url=DEFAULT_AUTOBAHN_ROUTER, realm=DEFAULT_AUTOBAHN_REALM, authmethods=None, authid=None, authrole=None, authextra=None, blocking=False, callback=None, **kwargs): """ Start the background twisted thread and create the WAMP connection :param blocking: If ``F...
[ "def", "run", "(", "self", ",", "url", "=", "DEFAULT_AUTOBAHN_ROUTER", ",", "realm", "=", "DEFAULT_AUTOBAHN_REALM", ",", "authmethods", "=", "None", ",", "authid", "=", "None", ",", "authrole", "=", "None", ",", "authextra", "=", "None", ",", "blocking", "...
50.5
21.5
def keep_max_priority_effects(effects): """ Given a list of effects, only keep the ones with the maximum priority effect type. Parameters ---------- effects : list of MutationEffect subclasses Returns list of same length or shorter """ priority_values = map(effect_priority, effects...
[ "def", "keep_max_priority_effects", "(", "effects", ")", ":", "priority_values", "=", "map", "(", "effect_priority", ",", "effects", ")", "max_priority", "=", "max", "(", "priority_values", ")", "return", "[", "e", "for", "(", "e", ",", "p", ")", "in", "zi...
30.571429
17.857143
def resolve_node_modules(self): 'import the modules specified in init' if not self.resolved_node_modules: try: self.resolved_node_modules = [ importlib.import_module(mod, self.node_package) for mod in self.node_modules ]...
[ "def", "resolve_node_modules", "(", "self", ")", ":", "if", "not", "self", ".", "resolved_node_modules", ":", "try", ":", "self", ".", "resolved_node_modules", "=", "[", "importlib", ".", "import_module", "(", "mod", ",", "self", ".", "node_package", ")", "f...
34.846154
13.923077
def up(self, no_provision=False, provider=None, vm_name=None, provision=None, provision_with=None, stream_output=False): ''' Invoke `vagrant up` to start a box or boxes, possibly streaming the command output. vm_name=None: name of VM. provision_with: optional list of p...
[ "def", "up", "(", "self", ",", "no_provision", "=", "False", ",", "provider", "=", "None", ",", "vm_name", "=", "None", ",", "provision", "=", "None", ",", "provision_with", "=", "None", ",", "stream_output", "=", "False", ")", ":", "provider_arg", "=", ...
52.794872
28.589744
def remove_task(cls, task): """ :param Task|callable task: Remove 'task' from the list of tasks to run periodically """ with cls._lock: if not isinstance(task, Task): task = cls.resolved_task(task) if task: cls.tasks.remove(task) ...
[ "def", "remove_task", "(", "cls", ",", "task", ")", ":", "with", "cls", ".", "_lock", ":", "if", "not", "isinstance", "(", "task", ",", "Task", ")", ":", "task", "=", "cls", ".", "resolved_task", "(", "task", ")", "if", "task", ":", "cls", ".", "...
28.083333
16.916667
def computeStatsEigen(self): """ compute the eigen decomp using copied var stats to avoid concurrent read/write from other queue """ # TO-DO: figure out why this op has delays (possibly moving # eigenvectors around?) with tf.device('/cpu:0'): def removeNone(tensor_list): ...
[ "def", "computeStatsEigen", "(", "self", ")", ":", "# TO-DO: figure out why this op has delays (possibly moving", "# eigenvectors around?)", "with", "tf", ".", "device", "(", "'/cpu:0'", ")", ":", "def", "removeNone", "(", "tensor_list", ")", ":", "local_list", "=", "...
44.280702
14.017544
def topo(tess, registrations, properties=None, meta_data=None, chirality=None): ''' topo(tess, regs) yields a Topology object with the given tesselation object tess and the given registration map regs. ''' return Topology(tess, registrations, properties=properties, meta_data=meta_data, ...
[ "def", "topo", "(", "tess", ",", "registrations", ",", "properties", "=", "None", ",", "meta_data", "=", "None", ",", "chirality", "=", "None", ")", ":", "return", "Topology", "(", "tess", ",", "registrations", ",", "properties", "=", "properties", ",", ...
49.285714
31.571429
def create_network_interface(call=None, kwargs=None): ''' Create a network interface. ''' if call != 'action': raise SaltCloudSystemExit( 'The create_network_interface action must be called with -a or --action.' ) # pylint: disable=invalid-name IPAllocationMethod = g...
[ "def", "create_network_interface", "(", "call", "=", "None", ",", "kwargs", "=", "None", ")", ":", "if", "call", "!=", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The create_network_interface action must be called with -a or --action.'", ")", "# pylint: disabl...
35.08427
20.747191
def get_intersection(self, division): """Get intersection percentage of intersecting divisions.""" try: return IntersectRelationship.objects.get( from_division=self, to_division=division ).intersection except ObjectDoesNotExist: raise Exception...
[ "def", "get_intersection", "(", "self", ",", "division", ")", ":", "try", ":", "return", "IntersectRelationship", ".", "objects", ".", "get", "(", "from_division", "=", "self", ",", "to_division", "=", "division", ")", ".", "intersection", "except", "ObjectDoe...
45.625
14.875
def get_an_int(self, arg, msg_on_error, min_value=None, max_value=None): """Like cmdfns.get_an_int(), but if there's a stack frame use that in evaluation.""" ret_value = self.get_int_noerr(arg) if ret_value is None: if msg_on_error: self.errmsg(msg_on_error) ...
[ "def", "get_an_int", "(", "self", ",", "arg", ",", "msg_on_error", ",", "min_value", "=", "None", ",", "max_value", "=", "None", ")", ":", "ret_value", "=", "self", ".", "get_int_noerr", "(", "arg", ")", "if", "ret_value", "is", "None", ":", "if", "msg...
43.05
15.4
def is_artifact(self): # type: () -> bool """ Determines if this points to an actual artifact (e.g. a tarball) or if it points to an "abstract" thing like a path or a VCS location. """ from pipenv.patched.notpip._internal.vcs import vcs if self.scheme in vcs.all_...
[ "def", "is_artifact", "(", "self", ")", ":", "# type: () -> bool", "from", "pipenv", ".", "patched", ".", "notpip", ".", "_internal", ".", "vcs", "import", "vcs", "if", "self", ".", "scheme", "in", "vcs", ".", "all_schemes", ":", "return", "False", "return...
30.25
19.916667
def register_monitor(self, devices, events, callback): """Register a callback when events happen. If this method is called, it is guaranteed to take effect before the next call to ``_notify_event`` after this method returns. This method is safe to call from within a callback that is it...
[ "def", "register_monitor", "(", "self", ",", "devices", ",", "events", ",", "callback", ")", ":", "# Ensure we don't exhaust any iterables", "events", "=", "list", "(", "events", ")", "devices", "=", "list", "(", "devices", ")", "for", "event", "in", "events",...
34.1
22.333333
def _build_gan_trainer(self, input, model): """ We need to set tower_func because it's a TowerTrainer, and only TowerTrainer supports automatic graph creation for inference during training. If we don't care about inference during training, using tower_func is not needed. Just ca...
[ "def", "_build_gan_trainer", "(", "self", ",", "input", ",", "model", ")", ":", "# Build the graph", "self", ".", "tower_func", "=", "TowerFuncWrapper", "(", "model", ".", "build_graph", ",", "model", ".", "get_input_signature", "(", ")", ")", "with", "TowerCo...
47.285714
20.809524
def get_name_arg(argd, *argnames, default=None): """ Return the first argument value given in a docopt arg dict. When not given, return default. """ val = None for argname in argnames: if argd[argname]: val = argd[argname].lower().strip() break return val if v...
[ "def", "get_name_arg", "(", "argd", ",", "*", "argnames", ",", "default", "=", "None", ")", ":", "val", "=", "None", "for", "argname", "in", "argnames", ":", "if", "argd", "[", "argname", "]", ":", "val", "=", "argd", "[", "argname", "]", ".", "low...
32.6
9.8
def FindControl(control: Control, compare: Callable, maxDepth: int = 0xFFFFFFFF, findFromSelf: bool = False, foundIndex: int = 1) -> Control: """ control: `Control` or its subclass. compare: compare function with parameters (control: Control, depth: int) which returns bool. maxDepth: int, enum depth. ...
[ "def", "FindControl", "(", "control", ":", "Control", ",", "compare", ":", "Callable", ",", "maxDepth", ":", "int", "=", "0xFFFFFFFF", ",", "findFromSelf", ":", "bool", "=", "False", ",", "foundIndex", ":", "int", "=", "1", ")", "->", "Control", ":", "...
41.55
17.35
def is_file_excluded(self, repo_abspath, repo_file_path): """ Checks whether file at a given path is excluded. @param repo_abspath: Absolute path to the git repository. @type repo_abspath: str @param repo_file_path: Path to a file relative to repo_abspath. @type repo_fi...
[ "def", "is_file_excluded", "(", "self", ",", "repo_abspath", ",", "repo_file_path", ")", ":", "next", "(", "self", ".", "_check_attr_gens", "[", "repo_abspath", "]", ")", "attrs", "=", "self", ".", "_check_attr_gens", "[", "repo_abspath", "]", ".", "send", "...
36.75
19.875
def get_networks_by_name(self, name: str) -> List[Network]: """Get all networks with the given name. Useful for getting all versions of a given network.""" return self.session.query(Network).filter(Network.name.like(name)).all()
[ "def", "get_networks_by_name", "(", "self", ",", "name", ":", "str", ")", "->", "List", "[", "Network", "]", ":", "return", "self", ".", "session", ".", "query", "(", "Network", ")", ".", "filter", "(", "Network", ".", "name", ".", "like", "(", "name...
80.666667
19.666667
def unify_mp(b, partition_name): """Unify all of the segment partitions for a parent partition, then run stats on the MPR file""" with b.progress.start('coalesce_mp',0,message="MP coalesce {}".format(partition_name)) as ps: r = b.unify_partition(partition_name, None, ps) return r
[ "def", "unify_mp", "(", "b", ",", "partition_name", ")", ":", "with", "b", ".", "progress", ".", "start", "(", "'coalesce_mp'", ",", "0", ",", "message", "=", "\"MP coalesce {}\"", ".", "format", "(", "partition_name", ")", ")", "as", "ps", ":", "r", "...
42.285714
26.857143
def add_view(self, *args, **kwargs): """ Redirect to the change view if the singleton instance exists. """ try: singleton = self.model.objects.get() except (self.model.DoesNotExist, self.model.MultipleObjectsReturned): kwargs.setdefault("extra_context", {}...
[ "def", "add_view", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "singleton", "=", "self", ".", "model", ".", "objects", ".", "get", "(", ")", "except", "(", "self", ".", "model", ".", "DoesNotExist", ",", "self", ...
47.416667
17.583333
def reset(self, state_size_changed=False): """Reset parser state. Parameters ---------- state_size_changed : `bool`, optional `True` if maximum state size changed (default: `False`). """ if state_size_changed: self.state = deque(repeat('', self.st...
[ "def", "reset", "(", "self", ",", "state_size_changed", "=", "False", ")", ":", "if", "state_size_changed", ":", "self", ".", "state", "=", "deque", "(", "repeat", "(", "''", ",", "self", ".", "state_size", ")", ",", "maxlen", "=", "self", ".", "state_...
33.5
16
def on_press(self, event): 'on but-ton press we will see if the mouse is over us and store data' if event.inaxes != self.ax: return # contains, attrd = self.rect.contains(event) # if not contains: return # print('event contains', self.rect.xy) # x0, y0 ...
[ "def", "on_press", "(", "self", ",", "event", ")", ":", "if", "event", ".", "inaxes", "!=", "self", ".", "ax", ":", "return", "# contains, attrd = self.rect.contains(event)\r", "# if not contains: return\r", "# print('event contains', self.rect.xy)\r", "# x0, y0 = self.rect...
43.444444
15
def BSearchCeil(a, x, lo=0, hi=None): """Returns lowest i such as a[i] >= x, or -1 if x > all elements in a So, if x is in between two elements in a, this function will return the index of the higher element, hence "Ceil". Arguments: a -- ordered numeric sequence x -- element to se...
[ "def", "BSearchCeil", "(", "a", ",", "x", ",", "lo", "=", "0", ",", "hi", "=", "None", ")", ":", "if", "len", "(", "a", ")", "==", "0", ":", "return", "-", "1", "hi", "=", "hi", "if", "hi", "is", "not", "None", "else", "len", "(", "a", ")...
37.733333
12.2
def untlpy2highwirepy(untl_elements, **kwargs): """Convert a UNTL Python object to a highwire Python object.""" highwire_list = [] title = None publisher = None creation = None escape = kwargs.get('escape', False) for element in untl_elements.children: # If the UNTL element should be...
[ "def", "untlpy2highwirepy", "(", "untl_elements", ",", "*", "*", "kwargs", ")", ":", "highwire_list", "=", "[", "]", "title", "=", "None", "publisher", "=", "None", "creation", "=", "None", "escape", "=", "kwargs", ".", "get", "(", "'escape'", ",", "Fals...
45.813953
13.790698
def _build_youtube_dl_coprocessor(cls, session: AppSession, proxy_port: int): '''Build youtube-dl coprocessor.''' # Test early for executable wpull.processor.coprocessor.youtubedl.get_version(session.args.youtube_dl_exe) coprocessor = session.factory.new( 'YoutubeDlCoproces...
[ "def", "_build_youtube_dl_coprocessor", "(", "cls", ",", "session", ":", "AppSession", ",", "proxy_port", ":", "int", ")", ":", "# Test early for executable", "wpull", ".", "processor", ".", "coprocessor", ".", "youtubedl", ".", "get_version", "(", "session", ".",...
42.4
20.4
def verify(self): """ Returns True if the file contents match with the CRC32 attribute note: reset """ # remember file pointer pos = self.tell() self.seek(0) checksum = 0 for chunk in iter(lambda: self.read(1024), b''): checksum = cr...
[ "def", "verify", "(", "self", ")", ":", "# remember file pointer", "pos", "=", "self", ".", "tell", "(", ")", "self", ".", "seek", "(", "0", ")", "checksum", "=", "0", "for", "chunk", "in", "iter", "(", "lambda", ":", "self", ".", "read", "(", "102...
22.578947
21
def seq_int_arr(seqs): """Convert list of ACGT strings to matix of 1-4 ints Args: seqs (list of str): nucleotide sequences with only 'ACGT' characters Returns: numpy.array of int: matrix of integers from 1 to 4 inclusive representing A, C, G, and T str: nucleotide sequence string ...
[ "def", "seq_int_arr", "(", "seqs", ")", ":", "return", "np", ".", "array", "(", "[", "[", "NT_TO_INT", "[", "c", "]", "for", "c", "in", "x", ".", "upper", "(", ")", "]", "for", "x", "in", "seqs", "]", ")" ]
35.181818
25.454545
def update_keys(self): """Updates the Google API key with the text value""" from ...main import add_api_key add_api_key("google_api_key", self.google_api_key.get()) add_api_key("soundcloud_client_id", self.soundcloud_client_id.get())
[ "def", "update_keys", "(", "self", ")", ":", "from", ".", ".", ".", "main", "import", "add_api_key", "add_api_key", "(", "\"google_api_key\"", ",", "self", ".", "google_api_key", ".", "get", "(", ")", ")", "add_api_key", "(", "\"soundcloud_client_id\"", ",", ...
52.2
15.8
def abbreviate_tab_names_changed(self, settings, key, user_data): """If the gconf var abbreviate_tab_names be changed, this method will be called and will update tab names. """ abbreviate_tab_names = settings.get_boolean('abbreviate-tab-names') self.guake.abbreviate = abbreviate_...
[ "def", "abbreviate_tab_names_changed", "(", "self", ",", "settings", ",", "key", ",", "user_data", ")", ":", "abbreviate_tab_names", "=", "settings", ".", "get_boolean", "(", "'abbreviate-tab-names'", ")", "self", ".", "guake", ".", "abbreviate", "=", "abbreviate_...
52.285714
11.142857
def ext_pillar(minion_id, pillar, # pylint: disable=W0613 url, with_grains=False): ''' Read pillar data from HTTP response. :param str url: Url to request. :param bool with_grains: Whether to substitute strings in the url with their grain values. :retu...
[ "def", "ext_pillar", "(", "minion_id", ",", "pillar", ",", "# pylint: disable=W0613", "url", ",", "with_grains", "=", "False", ")", ":", "url", "=", "url", ".", "replace", "(", "'%s'", ",", "_quote", "(", "minion_id", ")", ")", "grain_pattern", "=", "r'<(?...
31.136364
24.909091
def add_jump_instruction(jump_arg, code_to_insert): """ Note: although it's adding a POP_JUMP_IF_TRUE, it's actually no longer used now (we could only return the return and possibly the load of the 'None' before the return -- not done yet because it needs work to fix all related tests). """ exte...
[ "def", "add_jump_instruction", "(", "jump_arg", ",", "code_to_insert", ")", ":", "extended_arg_list", "=", "[", "]", "if", "jump_arg", ">", "MAX_BYTE", ":", "extended_arg_list", "+=", "[", "EXTENDED_ARG", ",", "jump_arg", ">>", "8", "]", "jump_arg", "=", "jump...
51.769231
27.461538
def _equal(a, b, identityLong, relicCompare): """ Compares element @a to @b. If @b is @identityLong, returns a.isIdentity(). Otherwise, normalize a and b and use the relicCompare function to test for equality. """ # Check for an identity comparison. if isinstance(b, (long, int)) and b == id...
[ "def", "_equal", "(", "a", ",", "b", ",", "identityLong", ",", "relicCompare", ")", ":", "# Check for an identity comparison.", "if", "isinstance", "(", "b", ",", "(", "long", ",", "int", ")", ")", "and", "b", "==", "identityLong", ":", "return", "a", "....
34
16.705882
def start_semester_view(request): """ Initiates a semester"s worth of workshift, with the option to copy workshift types from the previous semester. """ page_name = "Start Semester" year, season = utils.get_year_season() start_date, end_date = utils.get_semester_start_end(year, season) ...
[ "def", "start_semester_view", "(", "request", ")", ":", "page_name", "=", "\"Start Semester\"", "year", ",", "season", "=", "utils", ".", "get_year_season", "(", ")", "start_date", ",", "end_date", "=", "utils", ".", "get_semester_start_end", "(", "year", ",", ...
32.314815
15.833333
def ADR(self, params): """ ADR Ra, [PC, #imm10_4] ADR Ra, label Load the address of label or the PC offset into Ra Ra must be a low register """ # TODO may need to rethink how I do PC, may need to be byte alligned # TODO This is wrong as each address is a...
[ "def", "ADR", "(", "self", ",", "params", ")", ":", "# TODO may need to rethink how I do PC, may need to be byte alligned", "# TODO This is wrong as each address is a word, not a byte. The filled value with its location (Do we want that, or the value at that location [Decompiled instruction])", ...
40.935484
31.193548
def encode(cls, line): """ Backslash escape line.value. """ if not line.encoded: line.value = cls.listSeparator.join(backslashEscape(val) for val in line.value) line.encoded=True
[ "def", "encode", "(", "cls", ",", "line", ")", ":", "if", "not", "line", ".", "encoded", ":", "line", ".", "value", "=", "cls", ".", "listSeparator", ".", "join", "(", "backslashEscape", "(", "val", ")", "for", "val", "in", "line", ".", "value", ")...
34.375
12.875
def hold(self, policy="combine"): ''' Activate a document hold. While a hold is active, no model changes will be applied, or trigger callbacks. Once ``unhold`` is called, the events collected during the hold will be applied according to the hold policy. Args: hold (...
[ "def", "hold", "(", "self", ",", "policy", "=", "\"combine\"", ")", ":", "if", "self", ".", "_hold", "is", "not", "None", "and", "self", ".", "_hold", "!=", "policy", ":", "log", ".", "warning", "(", "\"hold already active with '%s', ignoring '%s'\"", "%", ...
38.177778
24.888889
def get_compositions_by_ids(self, composition_ids): """Gets a ``CompositionList`` corresponding to the given ``IdList``. arg: composition_ids (osid.id.IdList): the list of ``Ids`` to retrieve return: (osid.repository.CompositionList) - the returned ``Compositi...
[ "def", "get_compositions_by_ids", "(", "self", ",", "composition_ids", ")", ":", "# Implemented from template for", "# osid.resource.ResourceLookupSession.get_resources_by_ids", "# NOTE: This implementation currently ignores plenary view", "collection", "=", "JSONClientValidated", "(", ...
47.382353
17.235294
def supernet(self, prefixlen_diff=1, new_prefix=None): """The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of ...
[ "def", "supernet", "(", "self", ",", "prefixlen_diff", "=", "1", ",", "new_prefix", "=", "None", ")", ":", "if", "self", ".", "_prefixlen", "==", "0", ":", "return", "self", "if", "new_prefix", "is", "not", "None", ":", "if", "new_prefix", ">", "self",...
40.5
21.05
def first(self): """ Return the first result of this Query or None if the result doesn't contain any row. """ results = self.rpc_model.search_read( self.domain, None, 1, self._order_by, self.fields, context=self.context ) return results and...
[ "def", "first", "(", "self", ")", ":", "results", "=", "self", ".", "rpc_model", ".", "search_read", "(", "self", ".", "domain", ",", "None", ",", "1", ",", "self", ".", "_order_by", ",", "self", ".", "fields", ",", "context", "=", "self", ".", "co...
33
13
def export(self, name, columns, points): """Export the stats to the Statsd server.""" for i in range(len(columns)): if not isinstance(points[i], Number): continue stat_name = '{}.{}.{}'.format(self.prefix, name, columns[i]) stat_value = points[i] ...
[ "def", "export", "(", "self", ",", "name", ",", "columns", ",", "points", ")", ":", "for", "i", "in", "range", "(", "len", "(", "columns", ")", ")", ":", "if", "not", "isinstance", "(", "points", "[", "i", "]", ",", "Number", ")", ":", "continue"...
47.230769
14.769231
def mlp(num_layers=2, num_hidden=64, activation=tf.tanh, layer_norm=False): """ Stack of fully-connected layers to be used in a policy / q-function approximator Parameters: ---------- num_layers: int number of fully-connected layers (default: 2) num_hidden: int ...
[ "def", "mlp", "(", "num_layers", "=", "2", ",", "num_hidden", "=", "64", ",", "activation", "=", "tf", ".", "tanh", ",", "layer_norm", "=", "False", ")", ":", "def", "network_fn", "(", "X", ")", ":", "h", "=", "tf", ".", "layers", ".", "flatten", ...
30.551724
29.172414
def new_clustered_sortind(x, k=10, row_key=None, cluster_key=None): """ Uses MiniBatch k-means clustering to cluster matrix into groups. Each cluster of rows is then sorted by `scorefunc` -- by default, the max peak height when all rows in a cluster are averaged, or cluster.mean(axis=0).max(). ...
[ "def", "new_clustered_sortind", "(", "x", ",", "k", "=", "10", ",", "row_key", "=", "None", ",", "cluster_key", "=", "None", ")", ":", "try", ":", "from", "sklearn", ".", "cluster", "import", "MiniBatchKMeans", "except", "ImportError", ":", "raise", "Impor...
36.047059
21.505882
def validate(self, raw_data, **kwargs): """Convert the raw_data to an integer. """ try: converted_data = int(raw_data) return super(IntegerField, self).validate(converted_data) except ValueError: raise ValidationException(self.messages['invalid'], rep...
[ "def", "validate", "(", "self", ",", "raw_data", ",", "*", "*", "kwargs", ")", ":", "try", ":", "converted_data", "=", "int", "(", "raw_data", ")", "return", "super", "(", "IntegerField", ",", "self", ")", ".", "validate", "(", "converted_data", ")", "...
36
17
def generic_encrypt(cipher_factory_map, plaintext, key, iv): """Encrypt data using the available backend. :param dict cipher_factory_map: Dictionary that maps the backend name to a cipher factory callable for that backend :param bytes plaintext: Plaintext data to encrypt :param bytes key: Encry...
[ "def", "generic_encrypt", "(", "cipher_factory_map", ",", "plaintext", ",", "key", ",", "iv", ")", ":", "if", "backend", "is", "None", ":", "raise", "PysnmpCryptoError", "(", "'Crypto backend not available'", ")", "return", "_ENCRYPT_MAP", "[", "backend", "]", "...
38.875
16.6875
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extracting dictionary of coefficients specific to required #...
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "# extracting dictionary of coefficients specific to required", "# intensity measure type.", "C", "=", "self", ".", "COEFFS_ASC", "[", "imt",...
45.931034
21.448276
def validate(self, require_all=True, scale='colors'): """Validate the visualization contents. Parameters ---------- require_all : boolean, default True If True (default), then all fields ``data``, ``scales``, ``axes``, and ``marks`` must be defined. The user is a...
[ "def", "validate", "(", "self", ",", "require_all", "=", "True", ",", "scale", "=", "'colors'", ")", ":", "super", "(", "self", ".", "__class__", ",", "self", ")", ".", "validate", "(", ")", "required_attribs", "=", "(", "'data'", ",", "'scales'", ",",...
42
16.214286
def parse_response(self, raw): """ Format the requested data model into a dictionary of DataFrames and a criteria map DataFrame. Take data returned by a requests.get call to Earthref. Parameters ---------- raw: 'requests.models.Response' Returns ...
[ "def", "parse_response", "(", "self", ",", "raw", ")", ":", "tables", "=", "raw", ".", "json", "(", ")", "[", "'tables'", "]", "crit", "=", "raw", ".", "json", "(", ")", "[", "'criteria_map'", "]", "return", "self", ".", "parse", "(", "tables", ","...
27.315789
15.842105
def define_params(self): ''' Define parameters. ''' input_dim = self.input_dim hidden_dim = self.hidden_dim prefix = self.name self.w_matrix = tf.Variable(tf.random_normal([input_dim, 3 * hidden_dim], stddev=0.1), name='/'.join(...
[ "def", "define_params", "(", "self", ")", ":", "input_dim", "=", "self", ".", "input_dim", "hidden_dim", "=", "self", ".", "hidden_dim", "prefix", "=", "self", ".", "name", "self", ".", "w_matrix", "=", "tf", ".", "Variable", "(", "tf", ".", "random_norm...
45.357143
24.357143
def remove_expired_nodes(self, node_ids=None): """ Removes all expired nodes from the nodelist. If a set of node_ids is passed in, those ids are checked to ensure they haven't been refreshed prior to a lock being acquired. Should only be run with a lock. :param list no...
[ "def", "remove_expired_nodes", "(", "self", ",", "node_ids", "=", "None", ")", ":", "nodes", "=", "self", ".", "find_expired_nodes", "(", "node_ids", ")", "if", "nodes", ":", "self", ".", "conn", ".", "client", ".", "hdel", "(", "self", ".", "nodelist_ke...
37.933333
21.133333
def create_geometry(self, input_geometry, dip, upper_depth, lower_depth, mesh_spacing=1.0): ''' If geometry is defined as a numpy array then create instance of nhlib.geo.line.Line class, otherwise if already instance of class accept class :param input_geo...
[ "def", "create_geometry", "(", "self", ",", "input_geometry", ",", "dip", ",", "upper_depth", ",", "lower_depth", ",", "mesh_spacing", "=", "1.0", ")", ":", "assert", "(", "(", "dip", ">", "0.", ")", "and", "(", "dip", "<=", "90.", ")", ")", "self", ...
40.697674
21.255814
def create_app(self, apps_path, name): """ Create Trionyx app in given path :param str path: path to create app in. :param str name: name of app :raises FileExistsError: """ app_path = os.path.join(apps_path, name.lower()) shutil.copytree(self.app_path, ...
[ "def", "create_app", "(", "self", ",", "apps_path", ",", "name", ")", ":", "app_path", "=", "os", ".", "path", ".", "join", "(", "apps_path", ",", "name", ".", "lower", "(", ")", ")", "shutil", ".", "copytree", "(", "self", ".", "app_path", ",", "a...
27.35
15.15
def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were...
[ "def", "associate_dhcp_options_to_vpc", "(", "dhcp_options_id", ",", "vpc_id", "=", "None", ",", "vpc_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", ...
45.903226
33.774194
def prepare_inventory(self): """ Prepares the inventory default under ``private_data_dir`` if it's not overridden by the constructor. """ if self.inventory is None: self.inventory = os.path.join(self.private_data_dir, "inventory")
[ "def", "prepare_inventory", "(", "self", ")", ":", "if", "self", ".", "inventory", "is", "None", ":", "self", ".", "inventory", "=", "os", ".", "path", ".", "join", "(", "self", ".", "private_data_dir", ",", "\"inventory\"", ")" ]
45
20.666667
def _create_resource_group(self, region, resource_group_name): """ Create resource group if it does not exist. """ resource_group_config = {'location': region} try: self.resource.resource_groups.create_or_update( resource_group_name, resource_group_co...
[ "def", "_create_resource_group", "(", "self", ",", "region", ",", "resource_group_name", ")", ":", "resource_group_config", "=", "{", "'location'", ":", "region", "}", "try", ":", "self", ".", "resource", ".", "resource_groups", ".", "create_or_update", "(", "re...
34.5
17.214286
def read_skysense_buffer(self): """Skysense stream format. :: ---------------------------------------------------------------------------------- Field SS MS MS MS MS MS MS MS MS MS MS MS MS MS MS TS TS TS TS TS TS RS RS RS --------------------------------------...
[ "def", "read_skysense_buffer", "(", "self", ")", ":", "SS_MSGLENGTH", "=", "24", "SS_STARTCHAR", "=", "0x24", "if", "len", "(", "self", ".", "buffer", ")", "<=", "SS_MSGLENGTH", ":", "return", "None", "messages", "=", "[", "]", "while", "len", "(", "self...
39.252874
20.321839
def apply(operations, a_tokens, b_tokens): """ Applies a sequences of operations to tokens -- copies tokens from `a_tokens` and `b_tokens` according to `operations`. :Parameters: operations : sequence of :~class:`deltas.Operation` Operations to perform a_tokens : list of `co...
[ "def", "apply", "(", "operations", ",", "a_tokens", ",", "b_tokens", ")", ":", "for", "operation", "in", "operations", ":", "if", "isinstance", "(", "operation", ",", "Equal", ")", ":", "#print(\"Equal: {0}\".format(str(a_tokens[operation.a1:operation.a2])))", "for", ...
35.818182
20.30303
def otsu(fpath): """ Returns value of otsu threshold for an image """ img = imread(fpath, as_grey=True) thresh = skimage.filter.threshold_otsu(img) return thresh
[ "def", "otsu", "(", "fpath", ")", ":", "img", "=", "imread", "(", "fpath", ",", "as_grey", "=", "True", ")", "thresh", "=", "skimage", ".", "filter", ".", "threshold_otsu", "(", "img", ")", "return", "thresh" ]
22.375
13.125
def get_transactions_json(self, include_investment=False, skip_duplicates=False, start_date=None, id=0): """Returns the raw JSON transaction data as downloaded from Mint. The JSON transaction data includes some additional information missing from the CSV data, such...
[ "def", "get_transactions_json", "(", "self", ",", "include_investment", "=", "False", ",", "skip_duplicates", "=", "False", ",", "start_date", "=", "None", ",", "id", "=", "0", ")", ":", "# Warning: This is a global property for the user that we are changing.", "self", ...
44.145161
18.693548
def dominator_tree_to_dot(self, filename): """ Export the dominator tree of the function to a dot file Args: filename (str) """ def description(node): desc ='{}\n'.format(node) desc += 'id: {}'.format(node.node_id) if node.domin...
[ "def", "dominator_tree_to_dot", "(", "self", ",", "filename", ")", ":", "def", "description", "(", "node", ")", ":", "desc", "=", "'{}\\n'", ".", "format", "(", "node", ")", "desc", "+=", "'id: {}'", ".", "format", "(", "node", ".", "node_id", ")", "if...
41.15
17.85
def remove_token(self, *, payer_id, credit_card_token_id): """ This feature allows you to delete a tokenized credit card register. Args: payer_id: credit_card_token_id: Returns: """ payload = { "language": self.client.language.value,...
[ "def", "remove_token", "(", "self", ",", "*", ",", "payer_id", ",", "credit_card_token_id", ")", ":", "payload", "=", "{", "\"language\"", ":", "self", ".", "client", ".", "language", ".", "value", ",", "\"command\"", ":", "PaymentCommand", ".", "REMOVE_TOKE...
29.92
18.08
def iter_links(self, elements): '''Iterate the document root for links. Returns: iterable: A iterator of :class:`LinkedInfo`. ''' for element in elements: if not isinstance(element, Element): continue for link_infos in self.iter_links...
[ "def", "iter_links", "(", "self", ",", "elements", ")", ":", "for", "element", "in", "elements", ":", "if", "not", "isinstance", "(", "element", ",", "Element", ")", ":", "continue", "for", "link_infos", "in", "self", ".", "iter_links_element", "(", "eleme...
30
19
def crypto_bloom_filter(record, # type: Sequence[Text] tokenizers, # type: List[Callable[[Text, Optional[Text]], Iterable[Text]]] schema, # type: Schema keys # type: Sequence[Sequence[bytes]] ): # type...
[ "def", "crypto_bloom_filter", "(", "record", ",", "# type: Sequence[Text]", "tokenizers", ",", "# type: List[Callable[[Text, Optional[Text]], Iterable[Text]]]", "schema", ",", "# type: Schema", "keys", "# type: Sequence[Sequence[bytes]]", ")", ":", "# type: (...) -> Tuple[bitarray, T...
42.658537
20.414634
def prior_class_dict(self): """ Returns ------- prior_class_dict: {Prior: class} A dictionary mapping_matrix priors to the class associated with their prior model. """ return {prior: cls for prior_model in self.prior_models for prior, cls in pr...
[ "def", "prior_class_dict", "(", "self", ")", ":", "return", "{", "prior", ":", "cls", "for", "prior_model", "in", "self", ".", "prior_models", "for", "prior", ",", "cls", "in", "prior_model", ".", "prior_class_dict", ".", "items", "(", ")", "}" ]
38.555556
19
def get_order(self, codes): """Return evidence codes in order shown in code2name.""" return sorted(codes, key=lambda e: [self.ev2idx.get(e)])
[ "def", "get_order", "(", "self", ",", "codes", ")", ":", "return", "sorted", "(", "codes", ",", "key", "=", "lambda", "e", ":", "[", "self", ".", "ev2idx", ".", "get", "(", "e", ")", "]", ")" ]
51.666667
12.333333
def update(self, identifier, new_instance): """ Update an encryptable field, make sure that: * We won't change the encryption context key * The new value is going to be encrypted * The return instance.plaintext is the updated one Note: Will expunge the returned instance ...
[ "def", "update", "(", "self", ",", "identifier", ",", "new_instance", ")", ":", "old_instance", "=", "self", ".", "retrieve", "(", "identifier", ")", "old_encrypted_identifier", "=", "old_instance", ".", "encrypted_identifier", "if", "(", "new_instance", ".", "e...
41.477273
23.659091
def _attempt_slice_recovery(self, shard_state, tstate): """Recover a slice. This is run when a slice had been previously attempted and output may have been written. If an output writer requires slice recovery, we run those logic to remove output duplicates. Otherwise we just retry the slice. I...
[ "def", "_attempt_slice_recovery", "(", "self", ",", "shard_state", ",", "tstate", ")", ":", "mapper_spec", "=", "tstate", ".", "mapreduce_spec", ".", "mapper", "if", "not", "(", "tstate", ".", "output_writer", "and", "tstate", ".", "output_writer", ".", "_supp...
46.384615
23.051282
def rgb_to_name(rgb_triplet, spec=u'css3'): """ Convert a 3-tuple of integers, suitable for use in an ``rgb()`` color triplet, to its corresponding normalized color name, if any such name exists. The optional keyword argument ``spec`` determines which specification's list of color names will be...
[ "def", "rgb_to_name", "(", "rgb_triplet", ",", "spec", "=", "u'css3'", ")", ":", "return", "hex_to_name", "(", "rgb_to_hex", "(", "normalize_integer_triplet", "(", "rgb_triplet", ")", ")", ",", "spec", "=", "spec", ")" ]
28.818182
22.181818