text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def update(self, newinfo): '''update the image''' self.text = newinfo.text if self.textctrl is not None: self.textctrl.Clear() self.textctrl.WriteText(self.text) self._resize()
[ "def", "update", "(", "self", ",", "newinfo", ")", ":", "self", ".", "text", "=", "newinfo", ".", "text", "if", "self", ".", "textctrl", "is", "not", "None", ":", "self", ".", "textctrl", ".", "Clear", "(", ")", "self", ".", "textctrl", ".", "Write...
32.857143
8.857143
def __construct_python_version(self): """ Construct a setuptools compatible Python version string. Constructed based on the environment's reported sys.version_info. """ major, minor, micro, release_level, serial = self.sys_version_info assert release_level in ("...
[ "def", "__construct_python_version", "(", "self", ")", ":", "major", ",", "minor", ",", "micro", ",", "release_level", ",", "serial", "=", "self", ".", "sys_version_info", "assert", "release_level", "in", "(", "\"alfa\"", ",", "\"beta\"", ",", "\"candidate\"", ...
41.933333
17
def create_qc(self, product_id=None, expected_result='', actual_result='', weight=100, status='success', **kwargs): ''' create_qc(self, product_id=None, expected_result='', actual_result='', weight=100, status='success', **kwargs) Create Quality Criteria :Parameters: * *product...
[ "def", "create_qc", "(", "self", ",", "product_id", "=", "None", ",", "expected_result", "=", "''", ",", "actual_result", "=", "''", ",", "weight", "=", "100", ",", "status", "=", "'success'", ",", "*", "*", "kwargs", ")", ":", "request_data", "=", "{"...
58.235294
42.941176
def make_heatmap(self, unstacked_df, singleletters): fig, ax = plt.subplots(num=None, figsize=(10,len(unstacked_df)/3), dpi=80, facecolor='w', edgecolor='k') #heatmap = ax.pcolor(unstacked_df, cmap=plt.cm.Reds, alpha=2, vmax = 5) #heatmap = ax.pcolor(unstacked_df, cmap=plt.cm.gist_ncar_r, alp...
[ "def", "make_heatmap", "(", "self", ",", "unstacked_df", ",", "singleletters", ")", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "num", "=", "None", ",", "figsize", "=", "(", "10", ",", "len", "(", "unstacked_df", ")", "/", "3", ")", ",...
43.162791
27.906977
def insert_node_node(**kw): """ Link a node to another node. node_id -> target_node_id. Where `node_id` is the parent and `target_node_id` is the child. """ with current_app.app_context(): insert_query(name='select_link_node_from_node.sql', node_id=kw.get('node_id')) db.execute(text...
[ "def", "insert_node_node", "(", "*", "*", "kw", ")", ":", "with", "current_app", ".", "app_context", "(", ")", ":", "insert_query", "(", "name", "=", "'select_link_node_from_node.sql'", ",", "node_id", "=", "kw", ".", "get", "(", "'node_id'", ")", ")", "db...
45.5
18.25
def sample_stats_to_xarray(self): """Extract sample_stats from posterior.""" posterior = self.posterior posterior_model = self.posterior_model # copy dims and coords dims = deepcopy(self.dims) if self.dims is not None else {} coords = deepcopy(self.coords) if self.c...
[ "def", "sample_stats_to_xarray", "(", "self", ")", ":", "posterior", "=", "self", ".", "posterior", "posterior_model", "=", "self", ".", "posterior_model", "# copy dims and coords\r", "dims", "=", "deepcopy", "(", "self", ".", "dims", ")", "if", "self", ".", "...
42.052632
20.842105
def write_recovery(page, injList): """ Write injection recovery plots to markup.page object page """ th = ['']+injList td = [] plots = ['sky_error_time','sky_error_mchirp','sky_error_distance'] text = { 'sky_error_time':'Sky error vs time',\ 'sky_error_mchirp':'S...
[ "def", "write_recovery", "(", "page", ",", "injList", ")", ":", "th", "=", "[", "''", "]", "+", "injList", "td", "=", "[", "]", "plots", "=", "[", "'sky_error_time'", ",", "'sky_error_mchirp'", ",", "'sky_error_distance'", "]", "text", "=", "{", "'sky_er...
27
20.533333
def from_Message(cls, kmsg): """ Message -> Entrypoint :param kser.schemas.Message kmsg: Kafka message :return: a entrypoint :rtype kser.entry.Entrypoint """ return cls( uuid=kmsg.uuid, params=kmsg.params, result=kmsg.result, metadata=kmsg.metadat...
[ "def", "from_Message", "(", "cls", ",", "kmsg", ")", ":", "return", "cls", "(", "uuid", "=", "kmsg", ".", "uuid", ",", "params", "=", "kmsg", ".", "params", ",", "result", "=", "kmsg", ".", "result", ",", "metadata", "=", "kmsg", ".", "metadata", "...
29.181818
15.181818
def _merge_selectors(left, right): """Given two selector chains (lists of simple selectors), return a list of selector chains representing elements matched by both of them. This operation is not exact, and involves some degree of fudging -- the wackier and more divergent the input, the more fudging. I...
[ "def", "_merge_selectors", "(", "left", ",", "right", ")", ":", "if", "not", "left", "or", "not", "right", ":", "# At least one is empty, so there are no conflicts; just return", "# whichever isn't empty. Remember to return a LIST, though", "return", "[", "left", "or", "ri...
35.128205
22.435897
def prioritize(): """ Yield the messages in the queue in the order they should be sent. """ while True: hp_qs = Message.objects.high_priority().using('default') mp_qs = Message.objects.medium_priority().using('default') lp_qs = Message.objects.low_priority().using('default') ...
[ "def", "prioritize", "(", ")", ":", "while", "True", ":", "hp_qs", "=", "Message", ".", "objects", ".", "high_priority", "(", ")", ".", "using", "(", "'default'", ")", "mp_qs", "=", "Message", ".", "objects", ".", "medium_priority", "(", ")", ".", "usi...
42
18.736842
def find_depth(data, s='', level=None): """ return or assert the depth (number of `|`) of variables Parameters ---------- data : pd.Series of strings IAMC-style variables s : str, default '' remove leading `s` from any variable in `data` level : int or str, default None ...
[ "def", "find_depth", "(", "data", ",", "s", "=", "''", ",", "level", "=", "None", ")", ":", "# remove wildcard as last character from string, escape regex characters", "_s", "=", "re", ".", "compile", "(", "'^'", "+", "_escape_regexp", "(", "s", ".", "rstrip", ...
34.071429
20.738095
def subscribe_and_validate(self, topic, qos, payload, timeout=1): """ Subscribe to a topic and validate that the specified payload is received within timeout. It is required that a connection has been established using `Connect` keyword. The payload can be specified as a python regular e...
[ "def", "subscribe_and_validate", "(", "self", ",", "topic", ",", "qos", ",", "payload", ",", "timeout", "=", "1", ")", ":", "seconds", "=", "convert_time", "(", "timeout", ")", "self", ".", "_verified", "=", "False", "logger", ".", "info", "(", "'Subscri...
34.916667
22.361111
def _save_obj_without_attr(obj, attr_list, path, values_to_save=None): """ Save object with attributes from attr_list. Parameters ---------- obj: obj Object of class with __dict__ attribute. attr_list: list List with attributes to exclude from saving to dill object. If empty ...
[ "def", "_save_obj_without_attr", "(", "obj", ",", "attr_list", ",", "path", ",", "values_to_save", "=", "None", ")", ":", "if", "values_to_save", "is", "None", ":", "values_to_save", "=", "[", "None", "]", "*", "len", "(", "attr_list", ")", "saved_attr_dict"...
31.545455
17.30303
def subkey_secret_exponent_chain_code_pair( generator, secret_exponent, chain_code_bytes, i, is_hardened, public_pair=None): """ Yield info for a child node for this node. generator: the ecdsa generator secret_exponent: base secret exponent chain_code: base chain cod...
[ "def", "subkey_secret_exponent_chain_code_pair", "(", "generator", ",", "secret_exponent", ",", "chain_code_bytes", ",", "i", ",", "is_hardened", ",", "public_pair", "=", "None", ")", ":", "ORDER", "=", "generator", ".", "order", "(", ")", "i_as_bytes", "=", "st...
35.02439
21.804878
def delete_session(self, ticket): ''' Delete a session record associated with a service ticket. ''' assert isinstance(self.session_storage_adapter, CASSessionAdapter) logging.debug('[CAS] Deleting session for ticket {}'.format(ticket)) self.session_storage_adapter.delete(...
[ "def", "delete_session", "(", "self", ",", "ticket", ")", ":", "assert", "isinstance", "(", "self", ".", "session_storage_adapter", ",", "CASSessionAdapter", ")", "logging", ".", "debug", "(", "'[CAS] Deleting session for ticket {}'", ".", "format", "(", "ticket", ...
45.857143
24.428571
def contains(self, value, equality_comparer=operator.eq): '''Determines whether the sequence contains a particular value. Execution is immediate. Depending on the type of the sequence, all or none of the sequence may be consumed by this operation. Note: This method uses immediate execu...
[ "def", "contains", "(", "self", ",", "value", ",", "equality_comparer", "=", "operator", ".", "eq", ")", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "ValueError", "(", "\"Attempt to call contains() on a \"", "\"closed Queryable.\"", ")", "if", "n...
32.909091
24.909091
def _get_pk_value(self, instance): """ Get the primary key field value for a model instance. :param instance: The model instance to get the primary key for. :type instance: Model :return: The primary key value of the given model instance. """ pk_field = instance....
[ "def", "_get_pk_value", "(", "self", ",", "instance", ")", ":", "pk_field", "=", "instance", ".", "_meta", ".", "pk", ".", "name", "pk", "=", "getattr", "(", "instance", ",", "pk_field", ",", "None", ")", "# Check to make sure that we got an pk not a model objec...
35.533333
15.533333
def _query(self, url=None, params=""): """ method to query a URL with the given parameters Parameters: url -> URL to query params -> dictionary with parameter values Returns: HTTP response code, headers If an exception occurred, head...
[ "def", "_query", "(", "self", ",", "url", "=", "None", ",", "params", "=", "\"\"", ")", ":", "if", "url", "is", "None", ":", "raise", "NoUrlError", "(", "\"No URL was provided.\"", ")", "# return values", "headers", "=", "{", "'location'", ":", "None", "...
36.857143
15.761905
def githubtunnel(user1, server1, user2, server2, port, verbose, stanford=False): """ Opens a nested tunnel, first to *user1*@*server1*, then to *user2*@*server2*, for accessing on *port*. If *verbose* is true, prints various ssh commands. If *stanford* is true, shifts ports up by 1. Attempts to g...
[ "def", "githubtunnel", "(", "user1", ",", "server1", ",", "user2", ",", "server2", ",", "port", ",", "verbose", ",", "stanford", "=", "False", ")", ":", "if", "stanford", ":", "port_shift", "=", "1", "else", ":", "port_shift", "=", "0", "# command1 = 'ss...
40.75
32.6875
def _get_template_list(self): " Get the hierarchy of templates belonging to the object/box_type given. " t_list = [] if hasattr(self.obj, 'category_id') and self.obj.category_id: cat = self.obj.category base_path = 'box/category/%s/content_type/%s/' % (cat.path, self.name...
[ "def", "_get_template_list", "(", "self", ")", ":", "t_list", "=", "[", "]", "if", "hasattr", "(", "self", ".", "obj", ",", "'category_id'", ")", "and", "self", ".", "obj", ".", "category_id", ":", "cat", "=", "self", ".", "obj", ".", "category", "ba...
45.52381
22.857143
def search_reports_page(self, search_term=None, enclave_ids=None, from_time=None, to_time=None, tags=None, excluded_tags=None, page_size=None, ...
[ "def", "search_reports_page", "(", "self", ",", "search_term", "=", "None", ",", "enclave_ids", "=", "None", ",", "from_time", "=", "None", ",", "to_time", "=", "None", ",", "tags", "=", "None", ",", "excluded_tags", "=", "None", ",", "page_size", "=", "...
45.162791
24.511628
def merge_dict(d0, d1, add_new_keys=False, append_arrays=False): """Recursively merge the contents of python dictionary d0 with the contents of another python dictionary, d1. Parameters ---------- d0 : dict The input dictionary. d1 : dict Dictionary to be merged with the input di...
[ "def", "merge_dict", "(", "d0", ",", "d1", ",", "add_new_keys", "=", "False", ",", "append_arrays", "=", "False", ")", ":", "if", "d1", "is", "None", ":", "return", "d0", "elif", "d0", "is", "None", ":", "return", "d1", "elif", "d0", "is", "None", ...
27.328125
21.125
def extract_keywords(icss): """Helper function Parameters ---------- icss : string comma-separated string Returns ------- kws : list of string set of keywords paramdict : dict dict of {parameterized_keyword: parameter_valu...
[ "def", "extract_keywords", "(", "icss", ")", ":", "# Force to lower case & split into keywords", "kws", "=", "set", "(", "icss", ".", "lower", "(", ")", ".", "split", "(", "','", ")", ")", "#parameterized keywords require special handling", "paramdict", "=", "{", ...
25.166667
17
def values_for_column(self, column_name, limit=10000): """Retrieve some values for the given column""" logging.info( 'Getting values for columns [{}] limited to [{}]' .format(column_name, limit)) # TODO: Use Lexicographi...
[ "def", "values_for_column", "(", "self", ",", "column_name", ",", "limit", "=", "10000", ")", ":", "logging", ".", "info", "(", "'Getting values for columns [{}] limited to [{}]'", ".", "format", "(", "column_name", ",", "limit", ")", ")", "# TODO: Use Lexicographic...
37.925926
16.62963
def i2m(self, pkt, x): """Convert internal value to machine value""" if x is None: # Try to return zero if undefined x = self.h2i(pkt, 0) return x
[ "def", "i2m", "(", "self", ",", "pkt", ",", "x", ")", ":", "if", "x", "is", "None", ":", "# Try to return zero if undefined", "x", "=", "self", ".", "h2i", "(", "pkt", ",", "0", ")", "return", "x" ]
31.5
12.333333
def multi_shift(df, window): """ get last N rows RELATIVE to another row in pandas http://stackoverflow.com/questions/25724056/how-to-get-last-n-rows-relative-to-another-row-in-pandas-vector-solution """ if isinstance(df, pd.Series): df = pd.DataFrame(df) dfs = [df.shift(i) for i in np....
[ "def", "multi_shift", "(", "df", ",", "window", ")", ":", "if", "isinstance", "(", "df", ",", "pd", ".", "Series", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "df", ")", "dfs", "=", "[", "df", ".", "shift", "(", "i", ")", "for", "i", "i...
40.75
18.083333
def common_parent(self, node): """ Return the common parent of two entities If the entities have no common parent, return None. Parameters ---------- node : instance of Node The other node. Returns ------- parent : instance of Node |...
[ "def", "common_parent", "(", "self", ",", "node", ")", ":", "p1", "=", "self", ".", "parent_chain", "(", ")", "p2", "=", "node", ".", "parent_chain", "(", ")", "for", "p", "in", "p1", ":", "if", "p", "in", "p2", ":", "return", "p", "return", "Non...
22.545455
17.272727
def _process_pubmed_ids(pubmed_ids): """ Take a list of pubmed IDs and add PMID prefix Args: :param pubmed_ids - string representing publication ids seperated by a | symbol Returns: :return list: Pubmed curies """ ...
[ "def", "_process_pubmed_ids", "(", "pubmed_ids", ")", ":", "if", "pubmed_ids", ".", "strip", "(", ")", "==", "''", ":", "id_list", "=", "[", "]", "else", ":", "id_list", "=", "pubmed_ids", ".", "split", "(", "'|'", ")", "for", "(", "i", ",", "val", ...
30.705882
13.294118
def bulk_related_objects(self, objs, using=DEFAULT_DB_ALIAS): """ Return all objects related to ``objs`` via this ``GenericRelation``. """ if self.delete_related: return super(AuditlogHistoryField, self).bulk_related_objects(objs, using) # When deleting, Collector.co...
[ "def", "bulk_related_objects", "(", "self", ",", "objs", ",", "using", "=", "DEFAULT_DB_ALIAS", ")", ":", "if", "self", ".", "delete_related", ":", "return", "super", "(", "AuditlogHistoryField", ",", "self", ")", ".", "bulk_related_objects", "(", "objs", ",",...
44.818182
23.181818
def do_GET_body(self): """Create body of GET.""" iiif = self.iiif if (len(self.path) > 1024): raise IIIFError(code=414, text="URI Too Long: Max 1024 chars, got %d\n" % len(self.path)) try: # self.path has leading / then identifier/param...
[ "def", "do_GET_body", "(", "self", ")", ":", "iiif", "=", "self", ".", "iiif", "if", "(", "len", "(", "self", ".", "path", ")", ">", "1024", ")", ":", "raise", "IIIFError", "(", "code", "=", "414", ",", "text", "=", "\"URI Too Long: Max 1024 chars, got...
49.875
20.0625
def build_from_token_counts(self, token_counts, min_count, num_iterations=4): """Train a SubwordTextTokenizer based on a dictionary of word counts. Args: token_counts: a dictionary of Unicode strings to int. min_count: an integer - discard subtokens with lower counts. num_...
[ "def", "build_from_token_counts", "(", "self", ",", "token_counts", ",", "min_count", ",", "num_iterations", "=", "4", ")", ":", "self", ".", "_init_alphabet_from_tokens", "(", "six", ".", "iterkeys", "(", "token_counts", ")", ")", "# Bootstrap the initial list of s...
51.409091
24.5
def detachRequest(GmmCause_presence=0): """DETACH REQUEST Section 9.4.5""" a = TpPd(pd=0x3) b = MessageType(mesType=0x5) # 00000101 c = DetachTypeAndForceToStandby() packet = a / b / c if GmmCause_presence is 1: e = GmmCause(ieiGC=0x25) packet = packet / e return packet
[ "def", "detachRequest", "(", "GmmCause_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x5", ")", "# 00000101", "c", "=", "DetachTypeAndForceToStandby", "(", ")", "packet", "=", ...
30.6
10
def _most_constrained_variable_chooser(problem, variables, domains): ''' Choose the variable that has less available values. ''' # the variable with fewer values available return sorted(variables, key=lambda v: len(domains[v]))[0]
[ "def", "_most_constrained_variable_chooser", "(", "problem", ",", "variables", ",", "domains", ")", ":", "# the variable with fewer values available", "return", "sorted", "(", "variables", ",", "key", "=", "lambda", "v", ":", "len", "(", "domains", "[", "v", "]", ...
40.833333
22.833333
def sample(self, count=5, fields=None, sampling=None, use_cache=True, dialect=None, billing_tier=None): """Retrieves a sampling of rows for the query. Args: count: an optional count of rows to retrieve which is used if a specific sampling is not specified (default 5). fields:...
[ "def", "sample", "(", "self", ",", "count", "=", "5", ",", "fields", "=", "None", ",", "sampling", "=", "None", ",", "use_cache", "=", "True", ",", "dialect", "=", "None", ",", "billing_tier", "=", "None", ")", ":", "return", "Query", ".", "sampling_...
59.678571
30.214286
def align_chunk_with_ner(self, ner_xml_path, i_chunk, o_chunk): ''' iterate through ner_xml_path to fuse with i_chunk into o_chunk ''' ## prepare to iterate over the input chunk input_iter = i_chunk.__iter__() all_ner = xml.dom.minidom.parse(open(ner_xml_path)) ## this converts...
[ "def", "align_chunk_with_ner", "(", "self", ",", "ner_xml_path", ",", "i_chunk", ",", "o_chunk", ")", ":", "## prepare to iterate over the input chunk", "input_iter", "=", "i_chunk", ".", "__iter__", "(", ")", "all_ner", "=", "xml", ".", "dom", ".", "minidom", "...
42.258427
24.325843
def run(self, input_dir, output_dir, epsilon): """Runs attack inside Docker. Args: input_dir: directory with input (dataset). output_dir: directory where output (adversarial images) should be written. epsilon: maximum allowed size of adversarial perturbation, should be in range [0, 25...
[ "def", "run", "(", "self", ",", "input_dir", ",", "output_dir", ",", "epsilon", ")", ":", "print", "(", "'Running attack '", ",", "self", ".", "name", ")", "cmd", "=", "[", "self", ".", "docker_binary", "(", ")", ",", "'run'", ",", "'-v'", ",", "'{0}...
35.363636
13.909091
def _dispense_plunger_position(self, ul): """Calculate axis position for a given liquid volume. Translates the passed liquid volume to absolute coordinates on the axis associated with this pipette. Calibration of the pipette motor's ul-to-mm conversion is required """ m...
[ "def", "_dispense_plunger_position", "(", "self", ",", "ul", ")", ":", "millimeters", "=", "ul", "/", "self", ".", "_ul_per_mm", "(", "ul", ",", "'dispense'", ")", "destination_mm", "=", "self", ".", "_get_plunger_position", "(", "'bottom'", ")", "+", "milli...
43.181818
18.636364
def plot(f, lcar=1.0e-1): """Plot function over a disk. """ import matplotlib import matplotlib.pyplot as plt import pygmsh geom = pygmsh.built_in.Geometry() geom.add_circle([0.0, 0.0, 0.0], 1.0, lcar, num_sections=4, compound=True) points, cells, _, _, _ = pygmsh.generate_mesh(geom, ve...
[ "def", "plot", "(", "f", ",", "lcar", "=", "1.0e-1", ")", ":", "import", "matplotlib", "import", "matplotlib", ".", "pyplot", "as", "plt", "import", "pygmsh", "geom", "=", "pygmsh", ".", "built_in", ".", "Geometry", "(", ")", "geom", ".", "add_circle", ...
28.606061
20.787879
def list_(): '''List available environments and modules''' click.echo('Cached Environments') environments = list(EnvironmentCache) click.echo(format_objects(environments, children=False))
[ "def", "list_", "(", ")", ":", "click", ".", "echo", "(", "'Cached Environments'", ")", "environments", "=", "list", "(", "EnvironmentCache", ")", "click", ".", "echo", "(", "format_objects", "(", "environments", ",", "children", "=", "False", ")", ")" ]
28.428571
20.142857
def export_content_courses(self, course_id, export_type, skip_notifications=None): """ Export content. Begin a content export job for a course, group, or user. You can use the {api:ProgressController#show Progress API} to track the progress of the export. The mig...
[ "def", "export_content_courses", "(", "self", ",", "course_id", ",", "export_type", ",", "skip_notifications", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - course_id\r", "\"\"\"ID\"\"\"", "p...
47.857143
26.285714
def _fullqualname_method_py3(obj): """Fully qualified name for 'method' objects in Python 3. """ if inspect.isclass(obj.__self__): cls = obj.__self__.__qualname__ else: cls = obj.__self__.__class__.__qualname__ return obj.__self__.__module__ + '.' + cls + '.' + obj.__name__
[ "def", "_fullqualname_method_py3", "(", "obj", ")", ":", "if", "inspect", ".", "isclass", "(", "obj", ".", "__self__", ")", ":", "cls", "=", "obj", ".", "__self__", ".", "__qualname__", "else", ":", "cls", "=", "obj", ".", "__self__", ".", "__class__", ...
30.3
15.7
def _log_variables(self, epoch_data: EpochData): """ Log variables from the epoch data. .. warning:: At the moment, only scalars and dicts of scalars are properly formatted and logged. Other value types are ignored by default. One may set ``on_unknown_type`` to ...
[ "def", "_log_variables", "(", "self", ",", "epoch_data", ":", "EpochData", ")", ":", "for", "stream_name", "in", "epoch_data", ".", "keys", "(", ")", ":", "stream_data", "=", "epoch_data", "[", "stream_name", "]", "variables", "=", "self", ".", "_variables",...
57.317073
27.512195
def setex(self, key, seconds, value): """Set key to hold the string value and set key to timeout after a given number of seconds. :meth:`~tredis.RedisClient.setex` is atomic, and can be reproduced by using :meth:`~tredis.RedisClient.set` and :meth:`~tredis.RedisClient.expire` in...
[ "def", "setex", "(", "self", ",", "key", ",", "seconds", ",", "value", ")", ":", "return", "self", ".", "_execute", "(", "[", "b'SETEX'", ",", "key", ",", "ascii", "(", "seconds", ")", ",", "value", "]", ",", "b'OK'", ")" ]
38.607143
19
def create(self, jti, aud=''): """Adds a token to the blacklist. Args: jti (str): the jti of the JWT to blacklist. aud (str, optional): The JWT's aud claim. The client_id of the application for which it was issued. body (dict): See: http...
[ "def", "create", "(", "self", ",", "jti", ",", "aud", "=", "''", ")", ":", "return", "self", ".", "client", ".", "post", "(", "self", ".", "url", ",", "data", "=", "{", "'jti'", ":", "jti", ",", "'aud'", ":", "aud", "}", ")" ]
35
23.769231
def stmt2dzn(name, val, declare=True, assign=True, wrap=True): """Returns a dzn statement declaring and assigning the given value. Parameters ---------- val The value to serialize. declare : bool Whether to include the declaration of the variable in the statement or just the...
[ "def", "stmt2dzn", "(", "name", ",", "val", ",", "declare", "=", "True", ",", "assign", "=", "True", ",", "wrap", "=", "True", ")", ":", "if", "not", "(", "declare", "or", "assign", ")", ":", "raise", "ValueError", "(", "'The statement must be a declarat...
27.611111
20.888889
def exit(status=0): """ Terminate the program with the given status code. """ if status == 0: lab.io.printf(lab.io.Colours.GREEN, "Done.") else: lab.io.printf(lab.io.Colours.RED, "Error {0}".format(status)) sys.exit(status)
[ "def", "exit", "(", "status", "=", "0", ")", ":", "if", "status", "==", "0", ":", "lab", ".", "io", ".", "printf", "(", "lab", ".", "io", ".", "Colours", ".", "GREEN", ",", "\"Done.\"", ")", "else", ":", "lab", ".", "io", ".", "printf", "(", ...
28.333333
16.333333
def _log_to_file(self, etype, source, msg='', target='', hostmask='', params=''): """Override `log()` if bot is not initialized with a database connection. Do not call this method directly. """ today = datetime.utcnow() # TODO: Use self.locale['timezone'] for changing time ...
[ "def", "_log_to_file", "(", "self", ",", "etype", ",", "source", ",", "msg", "=", "''", ",", "target", "=", "''", ",", "hostmask", "=", "''", ",", "params", "=", "''", ")", ":", "today", "=", "datetime", ".", "utcnow", "(", ")", "# TODO: Use self.loc...
45.391304
17.73913
def convert_raw_tuple(value_tuple, format_string): """ Convert a tuple of raw values, according to the given line format. :param tuple value_tuple: the tuple of raw values :param str format_string: the format of the tuple :rtype: list of tuples """ values = [] for v, c in zip(value_tup...
[ "def", "convert_raw_tuple", "(", "value_tuple", ",", "format_string", ")", ":", "values", "=", "[", "]", "for", "v", ",", "c", "in", "zip", "(", "value_tuple", ",", "format_string", ")", ":", "if", "v", "is", "None", ":", "# append None", "values", ".", ...
30.0625
16.21875
def tuple(data, field_name): """ RETURN LIST OF TUPLES """ if isinstance(data, Cube): Log.error("not supported yet") if isinstance(data, FlatList): Log.error("not supported yet") if is_data(field_name) and "value" in field_name: # SIMPLIFY {"value":value} AS STRING ...
[ "def", "tuple", "(", "data", ",", "field_name", ")", ":", "if", "isinstance", "(", "data", ",", "Cube", ")", ":", "Log", ".", "error", "(", "\"not supported yet\"", ")", "if", "isinstance", "(", "data", ",", "FlatList", ")", ":", "Log", ".", "error", ...
29.878788
12.969697
def string_is_url(test_str): """ Test to see if a string is a URL or not, defined in this case as a string for which urlparse returns a scheme component >>> string_is_url('somestring') False >>> string_is_url('https://some.domain.org/path') True """ parsed = urlparse.urlparse(test_str) ...
[ "def", "string_is_url", "(", "test_str", ")", ":", "parsed", "=", "urlparse", ".", "urlparse", "(", "test_str", ")", "return", "parsed", ".", "scheme", "is", "not", "None", "and", "parsed", ".", "scheme", "!=", "''" ]
33.636364
14
def cache(cache_directory_path): """Display / set / update the dtool cache directory.""" if not cache_directory_path: click.secho(dtool_config.utils.get_cache( CONFIG_PATH, )) else: click.secho(dtool_config.utils.set_cache( CONFIG_PATH, cache_direc...
[ "def", "cache", "(", "cache_directory_path", ")", ":", "if", "not", "cache_directory_path", ":", "click", ".", "secho", "(", "dtool_config", ".", "utils", ".", "get_cache", "(", "CONFIG_PATH", ",", ")", ")", "else", ":", "click", ".", "secho", "(", "dtool_...
30
15
def _init_metadata(self, **kwargs): """Initialize form metadata""" osid_objects.OsidObjectForm._init_metadata(self, **kwargs) self._output_score_default = self._mdata['output_score']['default_decimal_values'][0] self._input_score_end_range_default = self._mdata['input_score_end_range']['...
[ "def", "_init_metadata", "(", "self", ",", "*", "*", "kwargs", ")", ":", "osid_objects", ".", "OsidObjectForm", ".", "_init_metadata", "(", "self", ",", "*", "*", "kwargs", ")", "self", ".", "_output_score_default", "=", "self", ".", "_mdata", "[", "'outpu...
76.333333
38.333333
def create(self, callback_url): """Register a new Subscription on this collection's parent object. Args: callback_url (str): URI of an active endpoint which can receive notifications. Returns: A round.Subscription object if successful. """ resourc...
[ "def", "create", "(", "self", ",", "callback_url", ")", ":", "resource", "=", "self", ".", "resource", ".", "create", "(", "{", "'subscribed_to'", ":", "'address'", ",", "'callback_url'", ":", "callback_url", "}", ")", "subscription", "=", "self", ".", "wr...
35.533333
19.066667
def uniprot_reviewed_checker_batch(uniprot_ids): """Batch check if uniprot IDs are reviewed or not Args: uniprot_ids: UniProt ID or list of UniProt IDs Returns: A dictionary of {UniProtID: Boolean} """ uniprot_ids = ssbio.utils.force_list(uniprot_ids) invalid_ids = [i for i i...
[ "def", "uniprot_reviewed_checker_batch", "(", "uniprot_ids", ")", ":", "uniprot_ids", "=", "ssbio", ".", "utils", ".", "force_list", "(", "uniprot_ids", ")", "invalid_ids", "=", "[", "i", "for", "i", "in", "uniprot_ids", "if", "not", "is_valid_uniprot_id", "(", ...
32.333333
24.777778
def replace_between_tags(text, repl_, start_tag, end_tag=None): r""" Replaces text between sentinal lines in a block of text. Args: text (str): repl_ (str): start_tag (str): end_tag (str): (default=None) Returns: str: new_text CommandLine: python -m...
[ "def", "replace_between_tags", "(", "text", ",", "repl_", ",", "start_tag", ",", "end_tag", "=", "None", ")", ":", "new_lines", "=", "[", "]", "editing", "=", "False", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", "for", "line", "in", "lines",...
25.796296
18.888889
def valid_daily_max_temperature(comp, units='K'): r"""Decorator to check that a computation runs on a valid temperature dataset.""" @wraps(comp) def func(tasmax, *args, **kwds): check_valid_temperature(tasmax, units) check_valid(tasmax, 'cell_methods', 'time: maximum within days') r...
[ "def", "valid_daily_max_temperature", "(", "comp", ",", "units", "=", "'K'", ")", ":", "@", "wraps", "(", "comp", ")", "def", "func", "(", "tasmax", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "check_valid_temperature", "(", "tasmax", ",", "unit...
36.1
18.2
def write_hdf5_dict(tsdict, h5f, group=None, **kwargs): """Write a `TimeSeriesBaseDict` to HDF5 Each series in the dict is written as a dataset in the group """ # create group if needed if group and group not in h5f: h5g = h5f.create_group(group) elif group: h5g = h5f[group] ...
[ "def", "write_hdf5_dict", "(", "tsdict", ",", "h5f", ",", "group", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# create group if needed", "if", "group", "and", "group", "not", "in", "h5f", ":", "h5g", "=", "h5f", ".", "create_group", "(", "group", ...
28.647059
15.352941
def receive_data(self, data): # type: (bytes) -> None """ Pass some received data to the connection for handling. A list of events that the remote peer triggered by sending this data can be retrieved with :meth:`~wsproto.connection.Connection.events`. :param data: The d...
[ "def", "receive_data", "(", "self", ",", "data", ")", ":", "# type: (bytes) -> None", "if", "data", "is", "None", ":", "# \"If _The WebSocket Connection is Closed_ and no Close control", "# frame was received by the endpoint (such as could occur if the", "# underlying transport conne...
43.84
24.48
def unmap_vc(self, port1, dlci1, port2, dlci2): """ Deletes a Virtual Circuit connection (unidirectional). :param port1: input port :param dlci1: input DLCI :param port2: output port :param dlci2: output DLCI """ if port1 not in self._nios: r...
[ "def", "unmap_vc", "(", "self", ",", "port1", ",", "dlci1", ",", "port2", ",", "dlci2", ")", ":", "if", "port1", "not", "in", "self", ".", "_nios", ":", "raise", "DynamipsError", "(", "\"Port {} is not allocated\"", ".", "format", "(", "port1", ")", ")",...
68.0625
48.375
def _get_local_files(self, path): """Returns a dictionary of all the files under a path.""" if not path: raise ValueError("No path specified") files = defaultdict(lambda: None) path_len = len(path) + 1 for root, dirs, filenames in os.walk(path): for name i...
[ "def", "_get_local_files", "(", "self", ",", "path", ")", ":", "if", "not", "path", ":", "raise", "ValueError", "(", "\"No path specified\"", ")", "files", "=", "defaultdict", "(", "lambda", ":", "None", ")", "path_len", "=", "len", "(", "path", ")", "+"...
41.636364
10.454545
def load_spectrum(path, smoothing=181, DF=-8.): """Load a Phoenix model atmosphere spectrum. path : string The file path to load. smoothing : integer Smoothing to apply. If None, do not smooth. If an integer, smooth with a Hamming window. Otherwise, the variable is assumed to be a differe...
[ "def", "load_spectrum", "(", "path", ",", "smoothing", "=", "181", ",", "DF", "=", "-", "8.", ")", ":", "try", ":", "ang", ",", "lflam", "=", "np", ".", "loadtxt", "(", "path", ",", "usecols", "=", "(", "0", ",", "1", ")", ")", ".", "T", "exc...
36.216667
24.033333
def is_ready(self, key): """Returns true if a result is available for ``key``.""" if self.pending_callbacks is None or key not in self.pending_callbacks: raise UnknownKeyError("key %r is not pending" % (key,)) return key in self.results
[ "def", "is_ready", "(", "self", ",", "key", ")", ":", "if", "self", ".", "pending_callbacks", "is", "None", "or", "key", "not", "in", "self", ".", "pending_callbacks", ":", "raise", "UnknownKeyError", "(", "\"key %r is not pending\"", "%", "(", "key", ",", ...
53.6
17.6
def abslistdir(directory): """ returns a list of absolute filepaths for all files found in the given directory. """ abs_dir = os.path.abspath(directory) filenames = os.listdir(abs_dir) return [os.path.join(abs_dir, filename) for filename in filenames]
[ "def", "abslistdir", "(", "directory", ")", ":", "abs_dir", "=", "os", ".", "path", ".", "abspath", "(", "directory", ")", "filenames", "=", "os", ".", "listdir", "(", "abs_dir", ")", "return", "[", "os", ".", "path", ".", "join", "(", "abs_dir", ","...
34
13.5
def complete(self): """Complete the message. This removes the message from the queue. :raises: ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled. :raises: ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired. ...
[ "def", "complete", "(", "self", ")", ":", "self", ".", "_is_live", "(", "'complete'", ")", "try", ":", "self", ".", "message", ".", "accept", "(", ")", "except", "Exception", "as", "e", ":", "raise", "MessageSettleFailed", "(", "\"complete\"", ",", "e", ...
45.6
28.466667
def create_attributes(klass, attributes, previous_object=None): """ Attributes for resource creation. """ return { 'name': attributes.get( 'name', previous_object.name if previous_object is not None else '' ), 'descript...
[ "def", "create_attributes", "(", "klass", ",", "attributes", ",", "previous_object", "=", "None", ")", ":", "return", "{", "'name'", ":", "attributes", ".", "get", "(", "'name'", ",", "previous_object", ".", "name", "if", "previous_object", "is", "not", "Non...
36.526316
22.210526
def getDBusEnvEndpoints(reactor, client=True): """ Creates endpoints from the DBUS_SESSION_BUS_ADDRESS environment variable @rtype: C{list} of L{twisted.internet.interfaces.IStreamServerEndpoint} @returns: A list of endpoint instances """ env = os.environ.get('DBUS_SESSION_BUS_ADDRESS', None) ...
[ "def", "getDBusEnvEndpoints", "(", "reactor", ",", "client", "=", "True", ")", ":", "env", "=", "os", ".", "environ", ".", "get", "(", "'DBUS_SESSION_BUS_ADDRESS'", ",", "None", ")", "if", "env", "is", "None", ":", "raise", "Exception", "(", "'DBus Session...
37.25
19.583333
def to_dict(self): """ convert the fields of the object into a dictionnary """ dico = dict() for field in self.fields.keys(): if field == "flags": dico[field] = self.flags2text() elif field == "state": dico[field] = self.sta...
[ "def", "to_dict", "(", "self", ")", ":", "dico", "=", "dict", "(", ")", "for", "field", "in", "self", ".", "fields", ".", "keys", "(", ")", ":", "if", "field", "==", "\"flags\"", ":", "dico", "[", "field", "]", "=", "self", ".", "flags2text", "("...
31.307692
11
def group_lines(lines): """Split a list of lines using empty lines as separators.""" groups = [] group = [] for line in lines: if line.strip() == "": groups.append(group[:]) group = [] continue group.append(line) if group: groups.append(g...
[ "def", "group_lines", "(", "lines", ")", ":", "groups", "=", "[", "]", "group", "=", "[", "]", "for", "line", "in", "lines", ":", "if", "line", ".", "strip", "(", ")", "==", "\"\"", ":", "groups", ".", "append", "(", "group", "[", ":", "]", ")"...
20.75
20.75
def getAppDir(): """ Return our application dir. Create it if it doesn't exist. """ # Be sure the resource dir exists theDir = os.path.expanduser('~/.')+APP_NAME.lower() if not os.path.exists(theDir): try: os.mkdir(theDir) except OSError: print('Could not create ...
[ "def", "getAppDir", "(", ")", ":", "# Be sure the resource dir exists", "theDir", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.'", ")", "+", "APP_NAME", ".", "lower", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "theDir", ")", ...
37
14.727273
def generate_reciprocal_vectors_squared(a1, a2, a3, encut): """ Generate reciprocal vector magnitudes within the cutoff along the specied lattice vectors. Args: a1: Lattice vector a (in Bohrs) a2: Lattice vector b (in Bohrs) a3: Lattice vector c (in Bohrs) encut: Reciproc...
[ "def", "generate_reciprocal_vectors_squared", "(", "a1", ",", "a2", ",", "a3", ",", "encut", ")", ":", "for", "vec", "in", "genrecip", "(", "a1", ",", "a2", ",", "a3", ",", "encut", ")", ":", "yield", "np", ".", "dot", "(", "vec", ",", "vec", ")" ]
35.5625
16.1875
def get_all(cls, parent=None, **params): if parent is not None: route = copy(parent.route) else: route = {} if cls.ID_NAME is not None: # Empty string triggers "get all resources" route[cls.ID_NAME] = "" base_obj = cls(key=parent.key, rou...
[ "def", "get_all", "(", "cls", ",", "parent", "=", "None", ",", "*", "*", "params", ")", ":", "if", "parent", "is", "not", "None", ":", "route", "=", "copy", "(", "parent", ".", "route", ")", "else", ":", "route", "=", "{", "}", "if", "cls", "."...
32.235294
18.382353
def audio(audio, sample_rate, name=None, out=None, subdir='', timeout=5, **kwargs): """summary audio files to listen on a browser. An sampled array is converted as WAV audio file, saved to output directory, and reported to the ChainerUI server. The audio file is saved every called this functi...
[ "def", "audio", "(", "audio", ",", "sample_rate", ",", "name", "=", "None", ",", "out", "=", "None", ",", "subdir", "=", "''", ",", "timeout", "=", "5", ",", "*", "*", "kwargs", ")", ":", "from", "chainerui", ".", "report", ".", "audio_report", "im...
38.535714
20.696429
def xpointerNewContext(self, doc, origin): """Create a new XPointer context """ if doc is None: doc__o = None else: doc__o = doc._o if origin is None: origin__o = None else: origin__o = origin._o ret = libxml2mod.xmlXPtrNewContext(doc__o, self._o, origin__o) if re...
[ "def", "xpointerNewContext", "(", "self", ",", "doc", ",", "origin", ")", ":", "if", "doc", "is", "None", ":", "doc__o", "=", "None", "else", ":", "doc__o", "=", "doc", ".", "_o", "if", "origin", "is", "None", ":", "origin__o", "=", "None", "else", ...
42.6
10.4
def ensure_path(path, acls=None, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Ensure Znode path exists path Parent path to create acls list of acls dictionaries to be assigned (Default: None) profile Configured...
[ "def", "ensure_path", "(", "path", ",", "acls", "=", "None", ",", "profile", "=", "None", ",", "hosts", "=", "None", ",", "scheme", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "default_acl", "=", "None", ")", ":", ...
26.452381
28.738095
def _semsim(self, c1, c2): """ Computes the semantic similarity between two concepts. The semantic similarity is a combination of two sem sims: 1. An "explicit" sem sim metric, that is, one which is directly encoded in the WordNet graph. Here it is just Wu-Palmer simila...
[ "def", "_semsim", "(", "self", ",", "c1", ",", "c2", ")", ":", "if", "c1", "==", "c2", ":", "return", "1.", "if", "(", "c1", ",", "c2", ")", "in", "self", ".", "concept_sims", ":", "return", "self", ".", "concept_sims", "[", "(", "c1", ",", "c2...
37.411765
25.098039
def set_stable_spot_instance_settings(self, maximum_bid_price_percentage=None, timeout_for_request=None, allow_fallback=True): """ Purchase options for stable spot instances. `maximum_bid_price_percentage`: Maxi...
[ "def", "set_stable_spot_instance_settings", "(", "self", ",", "maximum_bid_price_percentage", "=", "None", ",", "timeout_for_request", "=", "None", ",", "allow_fallback", "=", "True", ")", ":", "self", ".", "hadoop_settings", "[", "'stable_spot_instance_settings'", "]",...
48.25
25.15
def calculate_descriptors(self,mol): """Calculates descriptors such as logP, charges and MR and saves that in a dictionary.""" #make dictionary self.ligand_atoms = {index:{"name":x.name} for index,x in enumerate(self.topology_data.universe.ligand_noH.atoms)} #Calculate logP and MR contribs = self.calculate_l...
[ "def", "calculate_descriptors", "(", "self", ",", "mol", ")", ":", "#make dictionary", "self", ".", "ligand_atoms", "=", "{", "index", ":", "{", "\"name\"", ":", "x", ".", "name", "}", "for", "index", ",", "x", "in", "enumerate", "(", "self", ".", "top...
37.863636
21.181818
def nn_model(X, Y, n_h, num_iterations=10000, print_cost=False): """ Arguments: X -- dataset of shape (2, number of examples) Y -- labels of shape (1, number of examples) n_h -- size of the hidden layer num_iterations -- Number of iterations in gradient descent loop print_cost -- if True, pr...
[ "def", "nn_model", "(", "X", ",", "Y", ",", "n_h", ",", "num_iterations", "=", "10000", ",", "print_cost", "=", "False", ")", ":", "np", ".", "random", ".", "seed", "(", "3", ")", "n_x", "=", "layer_sizes", "(", "X", ",", "Y", ")", "[", "0", "]...
34.456522
23.282609
def length(self): """The number of elements changed. :rtype: int .. code:: python assert change.length == len(change.indices) assert change.length == len(change.elements) """ span = self._stop - self._start length, modulo = divmod(span, self._st...
[ "def", "length", "(", "self", ")", ":", "span", "=", "self", ".", "_stop", "-", "self", ".", "_start", "length", ",", "modulo", "=", "divmod", "(", "span", ",", "self", ".", "_step", ")", "if", "length", "<", "0", ":", "return", "0", "if", "modul...
25.117647
18
def GetNearestStops(self, lat, lon, n=1): """Return the n nearest stops to lat,lon""" dist_stop_list = [] for s in self.stops.values(): # TODO: Use util.ApproximateDistanceBetweenStops? dist = (s.stop_lat - lat)**2 + (s.stop_lon - lon)**2 if len(dist_stop_list) < n: bisect.insort(d...
[ "def", "GetNearestStops", "(", "self", ",", "lat", ",", "lon", ",", "n", "=", "1", ")", ":", "dist_stop_list", "=", "[", "]", "for", "s", "in", "self", ".", "stops", ".", "values", "(", ")", ":", "# TODO: Use util.ApproximateDistanceBetweenStops?", "dist",...
45.166667
9.75
def rule_n5xx(filename, rule_name, rule_conf, class_type): """Validate filename against a pattern if the filename passes the filter. Args: filename (str): The name of the file being parsed by flake8. rule_name (str): The name of the rule. rule_conf (dict): The dictionary containing the ...
[ "def", "rule_n5xx", "(", "filename", ",", "rule_name", ",", "rule_conf", ",", "class_type", ")", ":", "line_num", "=", "0", "code", "=", "_generate_mark_code", "(", "rule_name", ")", "message", "=", "\"N5{} filename failed regex validation '{}'\"", ".", "format", ...
42.681818
28.318182
def add_nio(self, nio, port_number): """ Adds a NIO as new port on Frame Relay switch. :param nio: NIO instance to add :param port_number: port to allocate for the NIO """ if port_number in self._nios: raise DynamipsError("Port {} isn't free".format(port_num...
[ "def", "add_nio", "(", "self", ",", "nio", ",", "port_number", ")", ":", "if", "port_number", "in", "self", ".", "_nios", ":", "raise", "DynamipsError", "(", "\"Port {} isn't free\"", ".", "format", "(", "port_number", ")", ")", "log", ".", "info", "(", ...
46.166667
28.388889
def decrypt_element(encrypted_data, key, debug=False, inplace=False): """ Decrypts an encrypted element. :param encrypted_data: The encrypted data. :type: lxml.etree.Element | DOMElement | basestring :param key: The key. :type: string :param debug: Activate the...
[ "def", "decrypt_element", "(", "encrypted_data", ",", "key", ",", "debug", "=", "False", ",", "inplace", "=", "False", ")", ":", "if", "isinstance", "(", "encrypted_data", ",", "Element", ")", ":", "encrypted_data", "=", "OneLogin_Saml2_XML", ".", "to_etree", ...
35.969697
22.151515
def get_caller_text(frame): """ Return the expression that calls the frame """ def find_match_node(node): "Find a candidate ast node" match_node = None for chd in ast.iter_child_nodes(node): if getattr(chd, "lineno", 0) > frame.f_back.f_lineno: break ...
[ "def", "get_caller_text", "(", "frame", ")", ":", "def", "find_match_node", "(", "node", ")", ":", "\"Find a candidate ast node\"", "match_node", "=", "None", "for", "chd", "in", "ast", ".", "iter_child_nodes", "(", "node", ")", ":", "if", "getattr", "(", "c...
44
17.75
def _to_map_job_config(cls, mr_spec, # TODO(user): Remove this parameter after it can be # read from mr_spec. queue_name): """Converts model.MapreduceSpec back to JobConfig. This method allows our internal metho...
[ "def", "_to_map_job_config", "(", "cls", ",", "mr_spec", ",", "# TODO(user): Remove this parameter after it can be", "# read from mr_spec.", "queue_name", ")", ":", "mapper_spec", "=", "mr_spec", ".", "mapper", "# 0 means all the old APIs before api_version is introduced.", "api_...
47.230769
19.707692
def mroc(adjacency_matrix, alpha): """ Extracts hierarchical community features using the MROC method. Introduced in: Wang, X., Tang, L., Liu, H., & Wang, L. (2013). Learning with multi-resolution overlapping communities. Knowledge and information systems, 36(2), 517-5...
[ "def", "mroc", "(", "adjacency_matrix", ",", "alpha", ")", ":", "# Find number of nodes", "number_of_nodes", "=", "adjacency_matrix", ".", "shape", "[", "0", "]", "####################################################################################################################",...
37.270588
21.152941
def getArguments(parser): "Provides additional validation of the arguments collected by argparse." args = parser.parse_args() # get the number of dimensions in the image if args.example: args.example_image, args.example_header = load(args.example) dimensions = args.example_image.ndim ...
[ "def", "getArguments", "(", "parser", ")", ":", "args", "=", "parser", ".", "parse_args", "(", ")", "# get the number of dimensions in the image", "if", "args", ".", "example", ":", "args", ".", "example_image", ",", "args", ".", "example_header", "=", "load", ...
57.434783
37.173913
def _handle_parameter(self, default): """Handle a case where a parameter is at the head of the tokens. *default* is the value to use if no parameter name is defined. """ key = None showkey = False self._push() while self._tokens: token = self._tokens....
[ "def", "_handle_parameter", "(", "self", ",", "default", ")", ":", "key", "=", "None", "showkey", "=", "False", "self", ".", "_push", "(", ")", "while", "self", ".", "_tokens", ":", "token", "=", "self", ".", "_tokens", ".", "pop", "(", ")", "if", ...
40.041667
15.166667
def two_qubit_matrix_to_ion_operations(q0: ops.Qid, q1: ops.Qid, mat: np.ndarray, atol: float = 1e-8 ) -> List[ops.Operation]: """Decomposes a two-qubit operati...
[ "def", "two_qubit_matrix_to_ion_operations", "(", "q0", ":", "ops", ".", "Qid", ",", "q1", ":", "ops", ".", "Qid", ",", "mat", ":", "np", ".", "ndarray", ",", "atol", ":", "float", "=", "1e-8", ")", "->", "List", "[", "ops", ".", "Operation", "]", ...
40.571429
16.809524
def is_dataset(ds): """Whether ds is a Dataset. Compatible across TF versions.""" import tensorflow as tf from tensorflow_datasets.core.utils import py_utils dataset_types = [tf.data.Dataset] v1_ds = py_utils.rgetattr(tf, "compat.v1.data.Dataset", None) v2_ds = py_utils.rgetattr(tf, "compat.v2.data.Dataset"...
[ "def", "is_dataset", "(", "ds", ")", ":", "import", "tensorflow", "as", "tf", "from", "tensorflow_datasets", ".", "core", ".", "utils", "import", "py_utils", "dataset_types", "=", "[", "tf", ".", "data", ".", "Dataset", "]", "v1_ds", "=", "py_utils", ".", ...
39.5
13.083333
def _showItemContextMenu(self, item, point, col): """Callback for contextMenuRequested() signal. Pops up item menu, if defined""" self._startOrStopEditing() menu = getattr(item, '_menu', None) if menu: # self._current_item tells callbacks what item the menu was referring to ...
[ "def", "_showItemContextMenu", "(", "self", ",", "item", ",", "point", ",", "col", ")", ":", "self", ".", "_startOrStopEditing", "(", ")", "menu", "=", "getattr", "(", "item", ",", "'_menu'", ",", "None", ")", "if", "menu", ":", "# self._current_item tells...
42.166667
11.75
def lookup_ips (ips): """ Return set of host names that resolve to given ips. """ hosts = set() for ip in ips: try: hosts.add(socket.gethostbyaddr(ip)[0]) except socket.error: hosts.add(ip) return hosts
[ "def", "lookup_ips", "(", "ips", ")", ":", "hosts", "=", "set", "(", ")", "for", "ip", "in", "ips", ":", "try", ":", "hosts", ".", "add", "(", "socket", ".", "gethostbyaddr", "(", "ip", ")", "[", "0", "]", ")", "except", "socket", ".", "error", ...
23.272727
15.272727
def _request_reports(self, resource_param_name, resources, endpoint_name): """Sends multiples requests for the resources to a particular endpoint. Args: resource_param_name: a string name of the resource parameter. resources: list of of the resources. endpoint_name: ...
[ "def", "_request_reports", "(", "self", ",", "resource_param_name", ",", "resources", ",", "endpoint_name", ")", ":", "params", "=", "[", "{", "resource_param_name", ":", "resource", ",", "'apikey'", ":", "self", ".", "_api_key", "}", "for", "resource", "in", ...
50.25
25.25
def _set_name(self, name): """ Sets the name of this asset. :param name: The name of the asset :type name: str """ if self._is_identifier_quoted(name): self._quoted = True name = self._trim_quotes(name) if "." in name: parts =...
[ "def", "_set_name", "(", "self", ",", "name", ")", ":", "if", "self", ".", "_is_identifier_quoted", "(", "name", ")", ":", "self", ".", "_quoted", "=", "True", "name", "=", "self", ".", "_trim_quotes", "(", "name", ")", "if", "\".\"", "in", "name", "...
24.529412
13
def get_workspace_tfvars_file(path, environment, region): """Determine Terraform workspace-specific tfvars file name.""" for name in gen_workspace_tfvars_files(environment, region): if os.path.isfile(os.path.join(path, name)): return name return "%s.tfvars" % environment
[ "def", "get_workspace_tfvars_file", "(", "path", ",", "environment", ",", "region", ")", ":", "for", "name", "in", "gen_workspace_tfvars_files", "(", "environment", ",", "region", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", "....
49.666667
12.333333
def get_or_create_environment(self, repo: str, branch: str, git_repo: Repo, repo_path: Path) -> str: """ Returns the path to the current Python executable. """ return sys.executable
[ "def", "get_or_create_environment", "(", "self", ",", "repo", ":", "str", ",", "branch", ":", "str", ",", "git_repo", ":", "Repo", ",", "repo_path", ":", "Path", ")", "->", "str", ":", "return", "sys", ".", "executable" ]
50.5
17.75
def processInput(self, dataAveraging=False, windowSize=None): """ #TODO: docstring :param dataAveraging: #TODO: docstring :param windowSize: #TODO: docstring """ self.dependentVar = numpy.array(self.dependentVarInput, dtype=numpy.float64 ...
[ "def", "processInput", "(", "self", ",", "dataAveraging", "=", "False", ",", "windowSize", "=", "None", ")", ":", "self", ".", "dependentVar", "=", "numpy", ".", "array", "(", "self", ".", "dependentVarInput", ",", "dtype", "=", "numpy", ".", "float64", ...
44.657143
18.685714
async def _handle_found_values(self, values): """ We got some values! Exciting. But let's make sure they're all the same or freak out a little bit. Also, make sure we tell the nearest node that *didn't* have the value to store it. """ value_counts = Counter(val...
[ "async", "def", "_handle_found_values", "(", "self", ",", "values", ")", ":", "value_counts", "=", "Counter", "(", "values", ")", "if", "len", "(", "value_counts", ")", "!=", "1", ":", "log", ".", "warning", "(", "\"Got multiple values for key %i: %s\"", ",", ...
39.529412
14.941176
def mri_head_reco_op_32_channel(): """Reconstruction operator for 32 channel MRI of a head. This is a T2 weighted TSE scan of a healthy volunteer. The reconstruction operator is the sum of the modulus of each channel. See the data source with DOI `10.5281/zenodo.800527`_ or the `project webpage`_...
[ "def", "mri_head_reco_op_32_channel", "(", ")", ":", "# To get the same rotation as in the reference article", "space", "=", "odl", ".", "uniform_discr", "(", "min_pt", "=", "[", "-", "115.2", ",", "-", "115.2", "]", ",", "max_pt", "=", "[", "115.2", ",", "115.2...
32.862069
22.62069
def enable(identifier = None, *args, **kwargs): ''' Enables a specific cache for the current session. Remember that is has to be registered. ''' global cache if not identifier: for item in (config['default-caches'] + ['NoCache']): if caches.has_key(item): debug('Enabling default cache %s...' % (item,)) ...
[ "def", "enable", "(", "identifier", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "global", "cache", "if", "not", "identifier", ":", "for", "item", "in", "(", "config", "[", "'default-caches'", "]", "+", "[", "'NoCache'", "]", ")"...
42.84
26.44