text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def migrate_flow_collection(apps, schema_editor): """Migrate 'flow_collection' field to 'entity_type'.""" Process = apps.get_model('flow', 'Process') DescriptorSchema = apps.get_model('flow', 'DescriptorSchema') for process in Process.objects.all(): process.entity_type = process.flow_collection...
[ "def", "migrate_flow_collection", "(", "apps", ",", "schema_editor", ")", ":", "Process", "=", "apps", ".", "get_model", "(", "'flow'", ",", "'Process'", ")", "DescriptorSchema", "=", "apps", ".", "get_model", "(", "'flow'", ",", "'DescriptorSchema'", ")", "fo...
44.529412
24
def send(self, obj, encoding='utf-8'): """ Sends a python object to the backend. The object **must be JSON serialisable**. :param obj: object to send :param encoding: encoding used to encode the json message into a bytes array, this should match CodeEdit.file.encodin...
[ "def", "send", "(", "self", ",", "obj", ",", "encoding", "=", "'utf-8'", ")", ":", "comm", "(", "'sending request: %r'", ",", "obj", ")", "msg", "=", "json", ".", "dumps", "(", "obj", ")", "msg", "=", "msg", ".", "encode", "(", "encoding", ")", "he...
34.8
13.733333
def generateFeatures(numFeatures): """Return string features. If <=62 features are requested, output will be single character alphanumeric strings. Otherwise, output will be ["F1", "F2", ...] """ # Capital letters, lowercase letters, numbers candidates = ([chr(i+65) for i in xrange(26)] + [...
[ "def", "generateFeatures", "(", "numFeatures", ")", ":", "# Capital letters, lowercase letters, numbers", "candidates", "=", "(", "[", "chr", "(", "i", "+", "65", ")", "for", "i", "in", "xrange", "(", "26", ")", "]", "+", "[", "chr", "(", "i", "+", "97",...
34
16.5625
def _inherit_option(self, name, val): """Return the inherited TransactionOption value.""" if val: return val txn_opts = self.options.default_transaction_options val = txn_opts and getattr(txn_opts, name) if val: return val return getattr(self.clien...
[ "def", "_inherit_option", "(", "self", ",", "name", ",", "val", ")", ":", "if", "val", ":", "return", "val", "txn_opts", "=", "self", ".", "options", ".", "default_transaction_options", "val", "=", "txn_opts", "and", "getattr", "(", "txn_opts", ",", "name"...
35.555556
13.222222
def handle_result(self, idents, parent, raw_msg, success=True): """handle a real task result, either success or failure""" # first, relay result to client engine = idents[0] client = idents[1] # swap_ids for ROUTER-ROUTER mirror raw_msg[:2] = [client,engine] # pri...
[ "def", "handle_result", "(", "self", ",", "idents", ",", "parent", ",", "raw_msg", ",", "success", "=", "True", ")", ":", "# first, relay result to client", "engine", "=", "idents", "[", "0", "]", "client", "=", "idents", "[", "1", "]", "# swap_ids for ROUTE...
37.909091
9.090909
def remove_description_by_type(self, type_p): """Delete all records which are equal to the passed type from the list in type_p of type :class:`VirtualSystemDescriptionType` """ if not isinstance(type_p, VirtualSystemDescriptionType): raise TypeError("type_p can only be an i...
[ "def", "remove_description_by_type", "(", "self", ",", "type_p", ")", ":", "if", "not", "isinstance", "(", "type_p", ",", "VirtualSystemDescriptionType", ")", ":", "raise", "TypeError", "(", "\"type_p can only be an instance of type VirtualSystemDescriptionType\"", ")", "...
43.9
20
def create_rl_lin_comb_method(op_name, klass, x_roles, y_roles): """ Creates a new binary special method with left and right versions, such as A.__mul__(B) <=> A*B, A.__rmul__(B) <=> [B*A if B.__mul__(A) fails] for target class. The method is called __op_name__. """ # This function w...
[ "def", "create_rl_lin_comb_method", "(", "op_name", ",", "klass", ",", "x_roles", ",", "y_roles", ")", ":", "# This function will became the methods.", "def", "new_method", "(", "self", ",", "other", ",", "x_roles", "=", "x_roles", ",", "y_roles", "=", "y_roles", ...
35.186047
18.813953
def run(sub_command, exit_handle=None, **options): """Run a command""" command = Command(sub_command, exit_handle) return command.run(**options)
[ "def", "run", "(", "sub_command", ",", "exit_handle", "=", "None", ",", "*", "*", "options", ")", ":", "command", "=", "Command", "(", "sub_command", ",", "exit_handle", ")", "return", "command", ".", "run", "(", "*", "*", "options", ")" ]
38.25
6
def transform_soups(config, soups, precomputed): """Mutate our soups to be better when we write them out later.""" fixup_internal_links(config, soups) ensure_headings_linkable(soups) # Do this after ensure_headings_linkable so that there will be links. generate_page_tocs(soups, precomputed) link_pantsrefs(...
[ "def", "transform_soups", "(", "config", ",", "soups", ",", "precomputed", ")", ":", "fixup_internal_links", "(", "config", ",", "soups", ")", "ensure_headings_linkable", "(", "soups", ")", "# Do this after ensure_headings_linkable so that there will be links.", "generate_p...
41.5
11.625
def _methodInTraceback(self, name, traceback): ''' Returns boolean whether traceback contains method from this instance ''' foundMethod = False for frame in self._frames(traceback): this = frame.f_locals.get('self') if this is self and frame.f_code.co_name == name: foundMethod = ...
[ "def", "_methodInTraceback", "(", "self", ",", "name", ",", "traceback", ")", ":", "foundMethod", "=", "False", "for", "frame", "in", "self", ".", "_frames", "(", "traceback", ")", ":", "this", "=", "frame", ".", "f_locals", ".", "get", "(", "'self'", ...
31.909091
17.909091
def get_priority_objects(data, nObj=1, seeds=None, seeds_multi_index=None, debug=False): """ Get N biggest objects from the selection or the object with seed. Similar function is in image_manipulation.select_objects_by_seeds(). Use it if possible. :param data: labeled ndarray :param nObj: number ...
[ "def", "get_priority_objects", "(", "data", ",", "nObj", "=", "1", ",", "seeds", "=", "None", ",", "seeds_multi_index", "=", "None", ",", "debug", "=", "False", ")", ":", "# Oznaceni dat.", "# labels - oznacena data.", "# length - pocet rozdilnych oznaceni.", "if", ...
35.0625
22.006944
def resource_collection_response(cls, offset=0, limit=20): """ This method is deprecated for version 1.1.0. Please use get_collection """ request_args = {'page[offset]': offset, 'page[limit]': limit} return cls.get_collection(request_args)
[ "def", "resource_collection_response", "(", "cls", ",", "offset", "=", "0", ",", "limit", "=", "20", ")", ":", "request_args", "=", "{", "'page[offset]'", ":", "offset", ",", "'page[limit]'", ":", "limit", "}", "return", "cls", ".", "get_collection", "(", ...
45.833333
15.5
def parse_date(s): """Fast %Y-%m-%d parsing.""" try: return datetime.date(int(s[:4]), int(s[5:7]), int(s[8:10])) except ValueError: # other accepted format used in one-day data set return datetime.datetime.strptime(s, '%d %B %Y').date()
[ "def", "parse_date", "(", "s", ")", ":", "try", ":", "return", "datetime", ".", "date", "(", "int", "(", "s", "[", ":", "4", "]", ")", ",", "int", "(", "s", "[", "5", ":", "7", "]", ")", ",", "int", "(", "s", "[", "8", ":", "10", "]", "...
43.333333
22.666667
def arches(self): """ Return a list of architectures for this task. :returns: a list of arch strings (eg ["ppc64le", "x86_64"]). The list is empty if this task has no arches associated with it. """ if self.method == 'image': return self.params[2] ...
[ "def", "arches", "(", "self", ")", ":", "if", "self", ".", "method", "==", "'image'", ":", "return", "self", ".", "params", "[", "2", "]", "if", "self", ".", "arch", ":", "return", "[", "self", ".", "arch", "]", "return", "[", "]" ]
31.416667
17.583333
def getVerificators(self): """Returns the user ids of the users that verified this analysis """ verifiers = list() actions = ["verify", "multi_verify"] for event in wf.getReviewHistory(self): if event['action'] in actions: verifiers.append(event['actor...
[ "def", "getVerificators", "(", "self", ")", ":", "verifiers", "=", "list", "(", ")", "actions", "=", "[", "\"verify\"", ",", "\"multi_verify\"", "]", "for", "event", "in", "wf", ".", "getReviewHistory", "(", "self", ")", ":", "if", "event", "[", "'action...
37.9
6.6
def get_val(self): """ Gets attribute's value. @return: stored value. @rtype: int @raise IOError: if corresponding file in /proc/sys cannot be read. """ file_obj = file(os.path.join(self._base, self._attr), 'r') try: val = int(file_obj.readlin...
[ "def", "get_val", "(", "self", ")", ":", "file_obj", "=", "file", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_base", ",", "self", ".", "_attr", ")", ",", "'r'", ")", "try", ":", "val", "=", "int", "(", "file_obj", ".", "readline", ...
26.857143
17.857143
def plot_precision_recall(y_true, y_probas, title='Precision-Recall Curve', plot_micro=True, classes_to_plot=None, ax=None, figsize=None, cmap='nipy_spectral', title_fontsize="large", ...
[ "def", "plot_precision_recall", "(", "y_true", ",", "y_probas", ",", "title", "=", "'Precision-Recall Curve'", ",", "plot_micro", "=", "True", ",", "classes_to_plot", "=", "None", ",", "ax", "=", "None", ",", "figsize", "=", "None", ",", "cmap", "=", "'nipy_...
39.582609
22.434783
def to_string(self): ''' API: to_string(self) Description: Returns string representation of node in dot language. Return: String representation of node. ''' node = list() node.append(quote_if_necessary(str(self.name))) node.append(' [')...
[ "def", "to_string", "(", "self", ")", ":", "node", "=", "list", "(", ")", "node", ".", "append", "(", "quote_if_necessary", "(", "str", "(", "self", ".", "name", ")", ")", ")", "node", ".", "append", "(", "' ['", ")", "flag", "=", "False", "for", ...
28.590909
16.954545
def get_def_conf(): '''return default configurations as simple dict''' ret = dict() for k,v in defConf.items(): ret[k] = v[0] return ret
[ "def", "get_def_conf", "(", ")", ":", "ret", "=", "dict", "(", ")", "for", "k", ",", "v", "in", "defConf", ".", "items", "(", ")", ":", "ret", "[", "k", "]", "=", "v", "[", "0", "]", "return", "ret" ]
25.833333
18.833333
def _keys2sls(self, keys, key2sl): """Convert an input key to a list of slices.""" sls = list() if isinstance(keys, tuple): for key in keys: sls.append(key2sl(key)) else: sls.append(key2sl(keys)) if len(sls) > self.ndim: fstr = ...
[ "def", "_keys2sls", "(", "self", ",", "keys", ",", "key2sl", ")", ":", "sls", "=", "list", "(", ")", "if", "isinstance", "(", "keys", ",", "tuple", ")", ":", "for", "key", "in", "keys", ":", "sls", ".", "append", "(", "key2sl", "(", "key", ")", ...
36.166667
12.416667
def stop(self): """Stop the Client, disconnect from queue """ if self.__end.is_set(): return self.__end.set() self.__send_retry_requests_timer.cancel() self.__threadpool.stop() self.__crud_threadpool.stop() self.__amqplink.stop() self._...
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "__end", ".", "is_set", "(", ")", ":", "return", "self", ".", "__end", ".", "set", "(", ")", "self", ".", "__send_retry_requests_timer", ".", "cancel", "(", ")", "self", ".", "__threadpool", "....
37.64
11.64
def hashsummary(self): """ Print a model summary - checksums of each layer parameters """ children = list(self.children()) result = [] for child in children: result.extend(hashlib.sha256(x.detach().cpu().numpy().tobytes()).hexdigest() for x in child.parameters()) r...
[ "def", "hashsummary", "(", "self", ")", ":", "children", "=", "list", "(", "self", ".", "children", "(", ")", ")", "result", "=", "[", "]", "for", "child", "in", "children", ":", "result", ".", "extend", "(", "hashlib", ".", "sha256", "(", "x", "."...
32.3
26.5
def set_defaults(self): """ All fields of Epm with a default value and that are null will be set to their default value. """ for table in self._tables.values(): for r in table: r.set_defaults()
[ "def", "set_defaults", "(", "self", ")", ":", "for", "table", "in", "self", ".", "_tables", ".", "values", "(", ")", ":", "for", "r", "in", "table", ":", "r", ".", "set_defaults", "(", ")" ]
35.285714
14.428571
def _set_return_address(self, state, ret_addr): """ Set the return address of the current state to a specific address. We assume we are at the beginning of a function, or in other words, we are about to execute the very first instruction of the function. :param SimState state: The progr...
[ "def", "_set_return_address", "(", "self", ",", "state", ",", "ret_addr", ")", ":", "# TODO: the following code is totally untested other than X86 and AMD64. Don't freak out if you find bugs :)", "# TODO: Test it", "ret_bvv", "=", "state", ".", "solver", ".", "BVV", "(", "ret...
43.888889
25.148148
def match_rules(self, log_data): """ Process a log line data message with app's pattern rules. Return a tuple with this data: Element #0 (app_matched): True if a rule match, False otherwise; Element #1 (has_full_match): True if a rule match and is a filter or the ...
[ "def", "match_rules", "(", "self", ",", "log_data", ")", ":", "for", "rule", "in", "self", ".", "rules", ":", "match", "=", "rule", ".", "regexp", ".", "search", "(", "log_data", ".", "message", ")", "if", "match", "is", "not", "None", ":", "gids", ...
51.196078
21.117647
def post_build(self, packet, payload): """Compute the 'sources_number' field when needed""" if self.sources_number is None: srcnum = struct.pack("!H", len(self.sources)) packet = packet[:26] + srcnum + packet[28:] return _ICMPv6.post_build(self, packet, payload)
[ "def", "post_build", "(", "self", ",", "packet", ",", "payload", ")", ":", "if", "self", ".", "sources_number", "is", "None", ":", "srcnum", "=", "struct", ".", "pack", "(", "\"!H\"", ",", "len", "(", "self", ".", "sources", ")", ")", "packet", "=", ...
50.833333
8.5
def as_sql(self, compiler, connection): """Compiles this expression into SQL.""" sql, params = super().as_sql(compiler, connection) return 'EXTRACT(epoch FROM {})'.format(sql), params
[ "def", "as_sql", "(", "self", ",", "compiler", ",", "connection", ")", ":", "sql", ",", "params", "=", "super", "(", ")", ".", "as_sql", "(", "compiler", ",", "connection", ")", "return", "'EXTRACT(epoch FROM {})'", ".", "format", "(", "sql", ")", ",", ...
40.8
15.6
def signal(self, container, instances=None, map_name=None, **kwargs): """ Sends a signal to a single running container configuration (but possibly multiple instances). If not specified with ``signal``, this signal is ``SIGKILL``. :param container: Container configuration name. :...
[ "def", "signal", "(", "self", ",", "container", ",", "instances", "=", "None", ",", "map_name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "run_actions", "(", "'signal'", ",", "container", ",", "instances", "=", "instances", ...
51.823529
22.882353
def rotate_du_by_yaw(self, du, heading): """Rotate all DOMs on DU by a given (yaw) heading.""" mask = (self.pmts.du == du) dom_ids = np.unique(self.pmts.dom_id[mask]) for dom_id in dom_ids: self.rotate_dom_by_yaw(dom_id, heading) self.reset_caches()
[ "def", "rotate_du_by_yaw", "(", "self", ",", "du", ",", "heading", ")", ":", "mask", "=", "(", "self", ".", "pmts", ".", "du", "==", "du", ")", "dom_ids", "=", "np", ".", "unique", "(", "self", ".", "pmts", ".", "dom_id", "[", "mask", "]", ")", ...
42.142857
7.142857
def babel_compile(source, **kwargs): """Compiles the given ``source`` from ES6 to ES5 using Babeljs""" presets = kwargs.get('presets') if not presets: kwargs['presets'] = ["es2015"] with open(BABEL_COMPILER, 'rb') as babel_js: return evaljs( (babel_js.read().decode('utf-8'), ...
[ "def", "babel_compile", "(", "source", ",", "*", "*", "kwargs", ")", ":", "presets", "=", "kwargs", ".", "get", "(", "'presets'", ")", "if", "not", "presets", ":", "kwargs", "[", "'presets'", "]", "=", "[", "\"es2015\"", "]", "with", "open", "(", "BA...
38.571429
12.642857
def create_empty_copy(G, with_data=True): """Return a copy of the graph G with all of the edges removed. Parameters ---------- G : graph A DyNetx graph with_data : bool (default=True) Include data. Notes ----- Graph and edge data is n...
[ "def", "create_empty_copy", "(", "G", ",", "with_data", "=", "True", ")", ":", "H", "=", "G", ".", "__class__", "(", ")", "H", ".", "add_nodes_from", "(", "G", ".", "nodes", "(", "data", "=", "with_data", ")", ")", "if", "with_data", ":", "H", ".",...
23.75
19
def set_state(self, light_id, **kwargs): ''' Sets state on the light, can be used like this: .. code-block:: python set_state(1, xy=[1,2]) ''' light = self.get_light(light_id) url = '/api/%s/lights/%s/state' % (self.username, light.light_id) response...
[ "def", "set_state", "(", "self", ",", "light_id", ",", "*", "*", "kwargs", ")", ":", "light", "=", "self", ".", "get_light", "(", "light_id", ")", "url", "=", "'/api/%s/lights/%s/state'", "%", "(", "self", ".", "username", ",", "light", ".", "light_id", ...
28
18.272727
def ensure_num_chosen_alts_equals_num_obs(obs_id_col, choice_col, df): """ Checks that the total number of recorded choices equals the total number of observations. If this is not the case, raise helpful ValueError messages. Parameters ---------- obs_id_col : str. Denotes the column in ...
[ "def", "ensure_num_chosen_alts_equals_num_obs", "(", "obs_id_col", ",", "choice_col", ",", "df", ")", ":", "num_obs", "=", "df", "[", "obs_id_col", "]", ".", "unique", "(", ")", ".", "shape", "[", "0", "]", "num_choices", "=", "df", "[", "choice_col", "]",...
35.242424
23.848485
def onresize(self, emitter, width, height): """ WebPage Event that occurs on webpage gets resized """ self._log.debug('App.onresize event occurred. Width:%s Height:%s'%(width, height))
[ "def", "onresize", "(", "self", ",", "emitter", ",", "width", ",", "height", ")", ":", "self", ".", "_log", ".", "debug", "(", "'App.onresize event occurred. Width:%s Height:%s'", "%", "(", "width", ",", "height", ")", ")" ]
51.25
13.25
def get_asset_content_mdata(): """Return default mdata map for AssetContent""" return { 'url': { 'element_label': { 'text': 'url', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTy...
[ "def", "get_asset_content_mdata", "(", ")", ":", "return", "{", "'url'", ":", "{", "'element_label'", ":", "{", "'text'", ":", "'url'", ",", "'languageTypeId'", ":", "str", "(", "DEFAULT_LANGUAGE_TYPE", ")", ",", "'scriptTypeId'", ":", "str", "(", "DEFAULT_SCR...
36.681319
15.681319
def from_kvs(keyvals): """ Create H2OCluster object from a list of key-value pairs. TODO: This method should be moved into the base H2OResponse class. """ obj = H2OCluster() obj._retrieved_at = time.time() for k, v in keyvals: if k in {"__meta", "_exc...
[ "def", "from_kvs", "(", "keyvals", ")", ":", "obj", "=", "H2OCluster", "(", ")", "obj", ".", "_retrieved_at", "=", "time", ".", "time", "(", ")", "for", "k", ",", "v", "in", "keyvals", ":", "if", "k", "in", "{", "\"__meta\"", ",", "\"_exclude_fields\...
36.733333
18.866667
def query_cat_recent_with_label(cat_id, label=None, num=8, kind='1', order=False): ''' query_cat_recent_with_label ''' if order: sort_criteria = TabPost.order.asc() else: sort_criteria = TabPost.time_create.desc() return TabPost.select().join( ...
[ "def", "query_cat_recent_with_label", "(", "cat_id", ",", "label", "=", "None", ",", "num", "=", "8", ",", "kind", "=", "'1'", ",", "order", "=", "False", ")", ":", "if", "order", ":", "sort_criteria", "=", "TabPost", ".", "order", ".", "asc", "(", "...
31.684211
18.631579
def ack(self, tup): """Indicate that processing of a Tuple has succeeded It is compatible with StreamParse API. """ if not isinstance(tup, HeronTuple): Log.error("Only HeronTuple type is supported in ack()") return if self.acking_enabled: ack_tuple = tuple_pb2.AckTuple() ac...
[ "def", "ack", "(", "self", ",", "tup", ")", ":", "if", "not", "isinstance", "(", "tup", ",", "HeronTuple", ")", ":", "Log", ".", "error", "(", "\"Only HeronTuple type is supported in ack()\"", ")", "return", "if", "self", ".", "acking_enabled", ":", "ack_tup...
36.347826
20.130435
def copy_to_clipboard(self, copy=True): """ Copies the selected items to the clipboard :param copy: True to copy, False to cut. """ urls = self.selected_urls() if not urls: return mime = self._UrlListMimeData(copy) mime.set_list(urls) c...
[ "def", "copy_to_clipboard", "(", "self", ",", "copy", "=", "True", ")", ":", "urls", "=", "self", ".", "selected_urls", "(", ")", "if", "not", "urls", ":", "return", "mime", "=", "self", ".", "_UrlListMimeData", "(", "copy", ")", "mime", ".", "set_list...
32.5
8.333333
def _parse_pubkey(stream, packet_type='pubkey'): """See https://tools.ietf.org/html/rfc4880#section-5.5 for details.""" p = {'type': packet_type} packet = io.BytesIO() with stream.capture(packet): p['version'] = stream.readfmt('B') p['created'] = stream.readfmt('>L') p['algo'] = ...
[ "def", "_parse_pubkey", "(", "stream", ",", "packet_type", "=", "'pubkey'", ")", ":", "p", "=", "{", "'type'", ":", "packet_type", "}", "packet", "=", "io", ".", "BytesIO", "(", ")", "with", "stream", ".", "capture", "(", "packet", ")", ":", "p", "["...
42.041667
14.166667
def find_substring_edge(self, substring, suffix_tree_id): """Returns an edge that matches the given substring. """ suffix_tree = self.suffix_tree_repo[suffix_tree_id] started = datetime.datetime.now() edge, ln = find_substring_edge(substring=substring, suffix_tree=suffix_tree, ed...
[ "def", "find_substring_edge", "(", "self", ",", "substring", ",", "suffix_tree_id", ")", ":", "suffix_tree", "=", "self", ".", "suffix_tree_repo", "[", "suffix_tree_id", "]", "started", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "edge", ",", "ln...
55.583333
25
def has_insert(self, shape): """Returns True if any of the inserts have the given shape.""" for insert in self.inserts: if insert.shape == shape: return True return False
[ "def", "has_insert", "(", "self", ",", "shape", ")", ":", "for", "insert", "in", "self", ".", "inserts", ":", "if", "insert", ".", "shape", "==", "shape", ":", "return", "True", "return", "False" ]
36.166667
8.833333
def get_current_value(self, use_cached=False): """Return the most recent DataPoint value written to a stream The current value is the last recorded data point for this stream. :param bool use_cached: If False, the function will always request the latest from Device Cloud. If True, ...
[ "def", "get_current_value", "(", "self", ",", "use_cached", "=", "False", ")", ":", "current_value", "=", "self", ".", "_get_stream_metadata", "(", "use_cached", ")", ".", "get", "(", "\"currentValue\"", ")", "if", "current_value", ":", "return", "DataPoint", ...
51.333333
31.222222
def address_exclude(self, other): """Remove an address from a larger block. For example: addr1 = IPNetwork('10.1.1.0/24') addr2 = IPNetwork('10.1.1.0/26') addr1.address_exclude(addr2) = [IPNetwork('10.1.1.64/26'), IPNetwork('10.1.1.128/25')] ...
[ "def", "address_exclude", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "_version", "==", "other", ".", "_version", ":", "raise", "TypeError", "(", "\"%s and %s are not of the same version\"", "%", "(", "str", "(", "self", ")", ",", "str", ...
35.181818
20.012987
def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code...
[ "def", "exists", "(", "vpc_id", "=", "None", ",", "name", "=", "None", ",", "cidr", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "t...
32.407407
26.111111
def get_tree(self, list_of_keys): """ gettree will extract the value from a nested tree INPUT list_of_keys: a list of keys ie. ['key1', 'key2'] USAGE >>> # Access the value for key2 within the nested dictionary >>> adv_dict({'key1': {'key2': 'value'}}).gettree(['key1', 'key...
[ "def", "get_tree", "(", "self", ",", "list_of_keys", ")", ":", "cur_obj", "=", "self", "for", "key", "in", "list_of_keys", ":", "cur_obj", "=", "cur_obj", ".", "get", "(", "key", ")", "if", "not", "cur_obj", ":", "break", "return", "cur_obj" ]
31.6
17.866667
def display_user(value, arg): ''' Return 'You' if value is equal to arg. Parameters: value should be a userprofile arg should be another user. Ideally, value should be a userprofile from an object and arg the user logged in. ''' if value.user == arg and arg.username !...
[ "def", "display_user", "(", "value", ",", "arg", ")", ":", "if", "value", ".", "user", "==", "arg", "and", "arg", ".", "username", "!=", "ANONYMOUS_USERNAME", ":", "return", "\"You\"", "else", ":", "return", "value", ".", "user", ".", "get_full_name", "(...
36.727273
18
def get_all_orders_ungrouped(self): """ Uses a generator to return all orders within. :py:class:`MarketOrder` objects are yielded directly, instead of being grouped in :py:class:`MarketItemsInRegionList` instances. .. note:: This is a generator! :rtype: generator ...
[ "def", "get_all_orders_ungrouped", "(", "self", ")", ":", "for", "olist", "in", "self", ".", "_orders", ".", "values", "(", ")", ":", "for", "order", "in", "olist", ".", "orders", ":", "yield", "order" ]
35.428571
16.285714
def get_scheduling_block(sub_array_id, block_id): """Return the list of scheduling blocks instances associated with the sub array""" block_ids = DB.get_sub_array_sbi_ids(sub_array_id) if block_id in block_ids: block = DB.get_block_details([block_id]).__next__() return block, HTTPStatus.O...
[ "def", "get_scheduling_block", "(", "sub_array_id", ",", "block_id", ")", ":", "block_ids", "=", "DB", ".", "get_sub_array_sbi_ids", "(", "sub_array_id", ")", "if", "block_id", "in", "block_ids", ":", "block", "=", "DB", ".", "get_block_details", "(", "[", "bl...
41.333333
12.777778
def zval_dict_from_potcar(potcar): """ Creates zval_dictionary for calculating the ionic polarization from Potcar object potcar: Potcar object """ zval_dict = {} for p in potcar: zval_dict.update({p.element: p.ZVAL}) return zval_dict
[ "def", "zval_dict_from_potcar", "(", "potcar", ")", ":", "zval_dict", "=", "{", "}", "for", "p", "in", "potcar", ":", "zval_dict", ".", "update", "(", "{", "p", ".", "element", ":", "p", ".", "ZVAL", "}", ")", "return", "zval_dict" ]
24
16.545455
def cli(env, identifier, enabled, port, weight, healthcheck_type, ip_address): """Edit the properties of a service group.""" mgr = SoftLayer.LoadBalancerManager(env.client) loadbal_id, service_id = loadbal.parse_id(identifier) # check if any input is provided if ((not any([ip_address, weight, por...
[ "def", "cli", "(", "env", ",", "identifier", ",", "enabled", ",", "port", ",", "weight", ",", "healthcheck_type", ",", "ip_address", ")", ":", "mgr", "=", "SoftLayer", ".", "LoadBalancerManager", "(", "env", ".", "client", ")", "loadbal_id", ",", "service_...
36.607143
17.928571
def _init_metadata(self): """stub""" self._rerandomize_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'rerandomize'), 'element_label': 'Randomize', 'inst...
[ "def", "_init_metadata", "(", "self", ")", ":", "self", ".", "_rerandomize_metadata", "=", "{", "'element_id'", ":", "Id", "(", "self", ".", "my_osid_object_form", ".", "_authority", ",", "self", ".", "my_osid_object_form", ".", "_namespace", ",", "'rerandomize'...
39.210526
12.263158
def create_same_as_file(self): """ creates a local data file with all of the owl:sameAs tags """ def find_preferred_uri(uri_list): index = None for i, uri in enumerate(uri_list): if uri.startswith("<http://id.loc.gov/authorities/subjects/"): ...
[ "def", "create_same_as_file", "(", "self", ")", ":", "def", "find_preferred_uri", "(", "uri_list", ")", ":", "index", "=", "None", "for", "i", ",", "uri", "in", "enumerate", "(", "uri_list", ")", ":", "if", "uri", ".", "startswith", "(", "\"<http://id.loc....
40.4375
15.46875
def tab(self): """ Advances the cursor position to the next (soft) tabstop. """ soft_tabs = self.tabstop - ((self._cx // self._cw) % self.tabstop) for _ in range(soft_tabs): self.putch(" ")
[ "def", "tab", "(", "self", ")", ":", "soft_tabs", "=", "self", ".", "tabstop", "-", "(", "(", "self", ".", "_cx", "//", "self", ".", "_cw", ")", "%", "self", ".", "tabstop", ")", "for", "_", "in", "range", "(", "soft_tabs", ")", ":", "self", "....
33.571429
14.714286
def _check_import_source(): """Check if tlgu imported, if not import it.""" path_rel = '~/cltk_data/greek/software/greek_software_tlgu/tlgu.h' path = os.path.expanduser(path_rel) if not os.path.isfile(path): try: corpus_importer = CorpusImporter('greek') ...
[ "def", "_check_import_source", "(", ")", ":", "path_rel", "=", "'~/cltk_data/greek/software/greek_software_tlgu/tlgu.h'", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path_rel", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "path", ")", ...
45
15.272727
def make_pkh_output(value, pubkey, witness=False): ''' int, bytearray -> TxOut ''' return _make_output( value=utils.i2le_padded(value, 8), output_script=make_pkh_output_script(pubkey, witness))
[ "def", "make_pkh_output", "(", "value", ",", "pubkey", ",", "witness", "=", "False", ")", ":", "return", "_make_output", "(", "value", "=", "utils", ".", "i2le_padded", "(", "value", ",", "8", ")", ",", "output_script", "=", "make_pkh_output_script", "(", ...
31.285714
18.428571
def netstat(name): ''' Retrieve the netstat information of the given process name. CLI Example: .. code-block:: bash salt '*' ps.netstat apache2 ''' sanitize_name = six.text_type(name) netstat_infos = __salt__['cmd.run']("netstat -nap") found_infos = [] ret = [] for in...
[ "def", "netstat", "(", "name", ")", ":", "sanitize_name", "=", "six", ".", "text_type", "(", "name", ")", "netstat_infos", "=", "__salt__", "[", "'cmd.run'", "]", "(", "\"netstat -nap\"", ")", "found_infos", "=", "[", "]", "ret", "=", "[", "]", "for", ...
25
19.947368
def conf_path(self): """ Retrieves the path to the MySQL configuration file. """ from burlap.system import distrib_id, distrib_release hostname = self.current_hostname if hostname not in self._conf_cache: self.env.conf_specifics[hostname] = self.env.conf_defau...
[ "def", "conf_path", "(", "self", ")", ":", "from", "burlap", ".", "system", "import", "distrib_id", ",", "distrib_release", "hostname", "=", "self", ".", "current_hostname", "if", "hostname", "not", "in", "self", ".", "_conf_cache", ":", "self", ".", "env", ...
43.357143
11.642857
def filter_svd(data, lapack_driver='gesdd', modes=[]): """ Return the svd-filtered signal using only the selected mode Provide the indices of the modes desired """ # Check input modes = np.asarray(modes,dtype=int) assert modes.ndim==1 assert modes.size>=1, "No modes selected !" u, s, ...
[ "def", "filter_svd", "(", "data", ",", "lapack_driver", "=", "'gesdd'", ",", "modes", "=", "[", "]", ")", ":", "# Check input", "modes", "=", "np", ".", "asarray", "(", "modes", ",", "dtype", "=", "int", ")", "assert", "modes", ".", "ndim", "==", "1"...
34.35
16.95
def file_fingerprint(fullpath): """ Get a metadata fingerprint for a file """ stat = os.stat(fullpath) return ','.join([str(value) for value in [stat.st_ino, stat.st_mtime, stat.st_size] if value])
[ "def", "file_fingerprint", "(", "fullpath", ")", ":", "stat", "=", "os", ".", "stat", "(", "fullpath", ")", "return", "','", ".", "join", "(", "[", "str", "(", "value", ")", "for", "value", "in", "[", "stat", ".", "st_ino", ",", "stat", ".", "st_mt...
51.5
19.75
def local_path(self, url, filename=None, decompress=False, download=False): """ What will the full local path be if we download the given file? """ if download: return self.fetch(url=url, filename=filename, decompress=decompress) else: filename = self.loca...
[ "def", "local_path", "(", "self", ",", "url", ",", "filename", "=", "None", ",", "decompress", "=", "False", ",", "download", "=", "False", ")", ":", "if", "download", ":", "return", "self", ".", "fetch", "(", "url", "=", "url", ",", "filename", "=",...
45.555556
22.444444
def get_deepest_subsumer(self,list_terms): ''' Returns the labels of the deepest node that subsumes all the terms in the list of terms id's provided ''' #To store with how many terms every nonterminal appears count_per_no_terminal = defaultdict(int) #To ...
[ "def", "get_deepest_subsumer", "(", "self", ",", "list_terms", ")", ":", "#To store with how many terms every nonterminal appears", "count_per_no_terminal", "=", "defaultdict", "(", "int", ")", "#To store the total deep of each noter for all the term ides (as we want the deepest)", "...
44.741935
20.741935
def add_product_to_product_set( self, product_set_id, product_id, location=None, project_id=None, retry=None, timeout=None, metadata=None, ): """ For the documentation see: :py:class:`~airflow.contrib.operators.gcp_vision_operat...
[ "def", "add_product_to_product_set", "(", "self", ",", "product_set_id", ",", "product_id", ",", "location", "=", "None", ",", "project_id", "=", "None", ",", "retry", "=", "None", ",", "timeout", "=", "None", ",", "metadata", "=", "None", ",", ")", ":", ...
34.423077
27.807692
def cherrypy_server_runner( app, global_conf=None, host='127.0.0.1', port=None, ssl_pem=None, protocol_version=None, numthreads=None, server_name=None, max=None, request_queue_size=None, timeout=None ): # pragma: no cover """ Entry point for CherryPy's WSGI server Serves the...
[ "def", "cherrypy_server_runner", "(", "app", ",", "global_conf", "=", "None", ",", "host", "=", "'127.0.0.1'", ",", "port", "=", "None", ",", "ssl_pem", "=", "None", ",", "protocol_version", "=", "None", ",", "numthreads", "=", "None", ",", "server_name", ...
28.571429
22.857143
def get_shared_people(self): """Retrieves all people that share their location with this account""" people = [] output = self._get_data() self._logger.debug(output) shared_entries = output[0] or [] for info in shared_entries: try: people.append...
[ "def", "get_shared_people", "(", "self", ")", ":", "people", "=", "[", "]", "output", "=", "self", ".", "_get_data", "(", ")", "self", ".", "_logger", ".", "debug", "(", "output", ")", "shared_entries", "=", "output", "[", "0", "]", "or", "[", "]", ...
40.25
14.25
def min_abs(self): '''Returns minimum absolute value.''' if self.__len__() == 0: return ArgumentError('empty set has no minimum absolute value.') if self.contains(0): return 0 return numpy.min([numpy.abs(val) for val in [self.max_neg(), s...
[ "def", "min_abs", "(", "self", ")", ":", "if", "self", ".", "__len__", "(", ")", "==", "0", ":", "return", "ArgumentError", "(", "'empty set has no minimum absolute value.'", ")", "if", "self", ".", "contains", "(", "0", ")", ":", "return", "0", "return", ...
41.444444
15.444444
def draw(self): """ Draw the elbow curve for the specified scores and values of K. """ # Plot the silhouette score against k self.ax.plot(self.k_values_, self.k_scores_, marker="D") if self.locate_elbow and self.elbow_value_!=None: elbow_label = "$elbow\ at\ k...
[ "def", "draw", "(", "self", ")", ":", "# Plot the silhouette score against k", "self", ".", "ax", ".", "plot", "(", "self", ".", "k_values_", ",", "self", ".", "k_scores_", ",", "marker", "=", "\"D\"", ")", "if", "self", ".", "locate_elbow", "and", "self",...
40.8
24.1
def _init_oauth(self, oauth_token, oauth_token_secret): "Store and initialize a verified set of OAuth credentials" self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret self._oauth = OAuth1( self.consumer_key, client_secret=self.consumer_sec...
[ "def", "_init_oauth", "(", "self", ",", "oauth_token", ",", "oauth_token_secret", ")", ":", "self", ".", "oauth_token", "=", "oauth_token", "self", ".", "oauth_token_secret", "=", "oauth_token_secret", "self", ".", "_oauth", "=", "OAuth1", "(", "self", ".", "c...
39.692308
15.230769
def make_published(self, request, queryset): """ Marks selected news items as published """ rows_updated = queryset.update(is_published=True) self.message_user(request, ungettext('%(count)d newsitem was published', ...
[ "def", "make_published", "(", "self", ",", "request", ",", "queryset", ")", ":", "rows_updated", "=", "queryset", ".", "update", "(", "is_published", "=", "True", ")", "self", ".", "message_user", "(", "request", ",", "ungettext", "(", "'%(count)d newsitem was...
47.444444
15.222222
def find_class(self, name): """Find the Class by its name.""" defclass = lib.EnvFindDefclass(self._env, name.encode()) if defclass == ffi.NULL: raise LookupError("Class '%s' not found" % name) return Class(self._env, defclass)
[ "def", "find_class", "(", "self", ",", "name", ")", ":", "defclass", "=", "lib", ".", "EnvFindDefclass", "(", "self", ".", "_env", ",", "name", ".", "encode", "(", ")", ")", "if", "defclass", "==", "ffi", ".", "NULL", ":", "raise", "LookupError", "("...
37.857143
15.142857
def run(self): ''' Run the api ''' ui = salt.spm.SPMCmdlineInterface() self.parse_args() self.setup_logfile_logger() v_dirs = [ self.config['spm_cache_dir'], ] verify_env(v_dirs, self.config['user'], ...
[ "def", "run", "(", "self", ")", ":", "ui", "=", "salt", ".", "spm", ".", "SPMCmdlineInterface", "(", ")", "self", ".", "parse_args", "(", ")", "self", ".", "setup_logfile_logger", "(", ")", "v_dirs", "=", "[", "self", ".", "config", "[", "'spm_cache_di...
27.941176
15.352941
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None): ''' .. versionadded:: 2015.8.0 Return a storage_conn object for the storage account ''' if conn_kwargs is None: conn_kwargs = {} if not storage_account: storage_account = config.get_cloud_config_val...
[ "def", "get_storage_conn", "(", "storage_account", "=", "None", ",", "storage_key", "=", "None", ",", "conn_kwargs", "=", "None", ")", ":", "if", "conn_kwargs", "is", "None", ":", "conn_kwargs", "=", "{", "}", "if", "not", "storage_account", ":", "storage_ac...
35.545455
22.909091
def add(self, command, response): """ Register a command/response pair. The command may be either a string (which is then automatically compiled into a regular expression), or a pre-compiled regular expression object. If the given response handler is a string, it is sen...
[ "def", "add", "(", "self", ",", "command", ",", "response", ")", ":", "command", "=", "re", ".", "compile", "(", "command", ")", "self", ".", "response_list", ".", "append", "(", "(", "command", ",", "response", ")", ")" ]
40.1
18.4
def _delete_vdev_info(self, vdev): """handle udev rules file.""" vdev = vdev.lower() rules_file_name = '/etc/udev/rules.d/51-qeth-0.0.%s.rules' % vdev cmd = 'rm -f %s\n' % rules_file_name address = '0.0.%s' % str(vdev).zfill(4) udev_file_name = '/etc/udev/rules.d/70-pers...
[ "def", "_delete_vdev_info", "(", "self", ",", "vdev", ")", ":", "vdev", "=", "vdev", ".", "lower", "(", ")", "rules_file_name", "=", "'/etc/udev/rules.d/51-qeth-0.0.%s.rules'", "%", "vdev", "cmd", "=", "'rm -f %s\\n'", "%", "rules_file_name", "address", "=", "'0...
44.333333
18.083333
def ErrorMessage(text, **kwargs): """Show an error message dialog to the user. This will raise a Zenity Error Dialog with a description of the error. text - A description of the error. kwargs - Optional command line parameters for Zenity such as height, width, etc.""" args = ...
[ "def", "ErrorMessage", "(", "text", ",", "*", "*", "kwargs", ")", ":", "args", "=", "[", "'--text=%s'", "%", "text", "]", "for", "generic_args", "in", "kwargs_helper", "(", "kwargs", ")", ":", "args", ".", "append", "(", "'--%s=%s'", "%", "generic_args",...
32.928571
17.714286
def simplefenestration(idf, fsd, deletebsd=True, setto000=False): """convert a bsd (fenestrationsurface:detailed) into a simple fenestrations""" funcs = (window, door, glazeddoor,) for func in funcs: fenestration = func(idf, fsd, deletebsd=deletebsd, setto000=setto000) i...
[ "def", "simplefenestration", "(", "idf", ",", "fsd", ",", "deletebsd", "=", "True", ",", "setto000", "=", "False", ")", ":", "funcs", "=", "(", "window", ",", "door", ",", "glazeddoor", ",", ")", "for", "func", "in", "funcs", ":", "fenestration", "=", ...
33.909091
17.909091
def get_prepopulated_value(field, instance): """ Returns preliminary value based on `populate_from`. """ if hasattr(field.populate_from, '__call__'): # AutoSlugField(populate_from=lambda instance: ...) return field.populate_from(instance) else: # AutoSlugField(populate_from='...
[ "def", "get_prepopulated_value", "(", "field", ",", "instance", ")", ":", "if", "hasattr", "(", "field", ".", "populate_from", ",", "'__call__'", ")", ":", "# AutoSlugField(populate_from=lambda instance: ...)", "return", "field", ".", "populate_from", "(", "instance",...
38
9.636364
def create_user(self, user_name, initial_password): """Create a new user with an initial password via provisioning API. It is not an error, if the user already existed before. If you get back an error 999, then the provisioning API is not enabled. :param user_name: name of user to be c...
[ "def", "create_user", "(", "self", ",", "user_name", ",", "initial_password", ")", ":", "res", "=", "self", ".", "_make_ocs_request", "(", "'POST'", ",", "self", ".", "OCS_SERVICE_CLOUD", ",", "'users'", ",", "data", "=", "{", "'password'", ":", "initial_pas...
37.24
18.92
def decompress(ctype, unc_len, data): """Decompress data. Arguments: Int:ctype -- Compression type LZO, ZLIB (*currently unused*). Int:unc_len -- Uncompressed data lenth. Str:data -- Data to be uncompessed. Returns: Uncompressed Data. """ if ctype == UBIFS_COMPR_LZO: ...
[ "def", "decompress", "(", "ctype", ",", "unc_len", ",", "data", ")", ":", "if", "ctype", "==", "UBIFS_COMPR_LZO", ":", "try", ":", "return", "lzo", ".", "decompress", "(", "b''", ".", "join", "(", "(", "b'\\xf0'", ",", "struct", ".", "pack", "(", "'>...
30.391304
18.304348
def save(self, fname: str): """ Saves the dataset to a binary .npy file. """ mx.nd.save(fname, self.source + self.target + self.label)
[ "def", "save", "(", "self", ",", "fname", ":", "str", ")", ":", "mx", ".", "nd", ".", "save", "(", "fname", ",", "self", ".", "source", "+", "self", ".", "target", "+", "self", ".", "label", ")" ]
32.4
9.2
def resource(self, uri, methods=frozenset({'GET'}), **kwargs): """ Decorates a function to be registered as a resource route. :param uri: path of the URL :param methods: list or tuple of methods allowed :param host: :param strict_slashes: :param stream: :...
[ "def", "resource", "(", "self", ",", "uri", ",", "methods", "=", "frozenset", "(", "{", "'GET'", "}", ")", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "f", ")", ":", "if", "kwargs", ".", "get", "(", "'stream'", ")", ":", "f", "....
34.913043
17.521739
def docker_environment(env): """ Transform dictionary of environment variables into Docker -e parameters. >>> result = docker_environment({'param1': 'val1', 'param2': 'val2'}) >>> result in ['-e "param1=val1" -e "param2=val2"', '-e "param2=val2" -e "param1=val1"'] True """ return ' '.join( ...
[ "def", "docker_environment", "(", "env", ")", ":", "return", "' '", ".", "join", "(", "[", "\"-e \\\"%s=%s\\\"\"", "%", "(", "key", ",", "value", ".", "replace", "(", "\"$\"", ",", "\"\\\\$\"", ")", ".", "replace", "(", "\"\\\"\"", ",", "\"\\\\\\\"\"", "...
41
25.909091
def options(self, context, module_options): ''' ACTION Enable/Disable RDP (choices: enable, disable) ''' if not 'ACTION' in module_options: context.log.error('ACTION option not specified!') exit(1) if module_options['ACTION'].lower() not in ['enable...
[ "def", "options", "(", "self", ",", "context", ",", "module_options", ")", ":", "if", "not", "'ACTION'", "in", "module_options", ":", "context", ".", "log", ".", "error", "(", "'ACTION option not specified!'", ")", "exit", "(", "1", ")", "if", "module_option...
33.071429
24.5
def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect w...
[ "def", "__get_conn", "(", "*", "*", "kwargs", ")", ":", "# This has only been tested on kvm and xen, it needs to be expanded to", "# support all vm layers supported by libvirt", "# Connection string works on bhyve, but auth is not tested.", "username", "=", "kwargs", ".", "get", "(",...
41.689189
23.608108
def misalignment(self,isotropic=False,**kwargs): """ NAME: misalignment PURPOSE: calculate the misalignment between the progenitor's frequency and the direction along which the stream disrupts INPUT: isotropic= (False), if True, return the...
[ "def", "misalignment", "(", "self", ",", "isotropic", "=", "False", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"In versions >1.3, the output unit of streamdf.misalignment has been changed to radian (from degree before)\"", ",", "galpyWarning", ")", ...
30.558824
30.794118
def run(self): """ Open a connection over the serial line and receive data lines """ if not self.device: return try: data = "" while (self.do_run): try: if (self.device.inWaiting() > 1): ...
[ "def", "run", "(", "self", ")", ":", "if", "not", "self", ".", "device", ":", "return", "try", ":", "data", "=", "\"\"", "while", "(", "self", ".", "do_run", ")", ":", "try", ":", "if", "(", "self", ".", "device", ".", "inWaiting", "(", ")", ">...
39.473684
15.315789
def summary_engine(**kwargs): """engine to extract summary data""" logger.debug("summary_engine") # farms = kwargs["farms"] farms = [] experiments = kwargs["experiments"] for experiment in experiments: if experiment.selected_summaries is None: selected_summaries = [ ...
[ "def", "summary_engine", "(", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "\"summary_engine\"", ")", "# farms = kwargs[\"farms\"]", "farms", "=", "[", "]", "experiments", "=", "kwargs", "[", "\"experiments\"", "]", "for", "experiment", "in", "ex...
30.518519
15.555556
def raise_for_version(self, line: str, position: int, version: str) -> None: """Check that a version string is valid for BEL documents. This means it's either in the YYYYMMDD or semantic version format. :param line: The line being parsed :param position: The position in the line being ...
[ "def", "raise_for_version", "(", "self", ",", "line", ":", "str", ",", "position", ":", "int", ",", "version", ":", "str", ")", "->", "None", ":", "if", "valid_date_version", "(", "version", ")", ":", "return", "if", "not", "SEMANTIC_VERSION_STRING_RE", "....
40.866667
20.533333
def save_formset_with_author(formset, user): """ Проставляет моделям из набора форм автора :param formset: набор форм :param user: автор :return: """ instances = formset.save(commit=False) for obj in formset.deleted_objects: obj.delete() for instance in instances: if ...
[ "def", "save_formset_with_author", "(", "formset", ",", "user", ")", ":", "instances", "=", "formset", ".", "save", "(", "commit", "=", "False", ")", "for", "obj", "in", "formset", ".", "deleted_objects", ":", "obj", ".", "delete", "(", ")", "for", "inst...
31.2
12.666667
def new_status(self, new_status): """ Sets the new_status of this BuildSetStatusChangedEvent. :param new_status: The new_status of this BuildSetStatusChangedEvent. :type: str """ allowed_values = ["NEW", "DONE", "REJECTED"] if new_status not in allowed_values: ...
[ "def", "new_status", "(", "self", ",", "new_status", ")", ":", "allowed_values", "=", "[", "\"NEW\"", ",", "\"DONE\"", ",", "\"REJECTED\"", "]", "if", "new_status", "not", "in", "allowed_values", ":", "raise", "ValueError", "(", "\"Invalid value for `new_status` (...
34.2
18.066667
def simulationStep(step=0): """ Make a simulation step and simulate up to the given millisecond in sim time. If the given value is 0 or absent, exactly one step is performed. Values smaller than or equal to the current sim time result in no action. """ global _stepListeners responses = _conn...
[ "def", "simulationStep", "(", "step", "=", "0", ")", ":", "global", "_stepListeners", "responses", "=", "_connections", "[", "\"\"", "]", ".", "simulationStep", "(", "step", ")", "for", "listener", "in", "_stepListeners", ":", "listener", ".", "step", "(", ...
38.818182
16.818182
def on_commit(self, changes): """Method that gets called when a model is changed. This serves to do the actual index writing. """ if _get_config(self)['enable_indexing'] is False: return None for wh in self.whoosheers: if not wh.auto_update: ...
[ "def", "on_commit", "(", "self", ",", "changes", ")", ":", "if", "_get_config", "(", "self", ")", "[", "'enable_indexing'", "]", "is", "False", ":", "return", "None", "for", "wh", "in", "self", ".", "whoosheers", ":", "if", "not", "wh", ".", "auto_upda...
42.409091
16.590909
def utc_offset_by_timezone(timezone_name): """Returns the UTC offset of the given timezone in hours. Arguments --------- timezone_name: str A string with a name of a timezone. Returns ------- int The UTC offset of the given timezone, in hours. """ return int(pytz.ti...
[ "def", "utc_offset_by_timezone", "(", "timezone_name", ")", ":", "return", "int", "(", "pytz", ".", "timezone", "(", "timezone_name", ")", ".", "utcoffset", "(", "utc_time", "(", ")", ")", ".", "total_seconds", "(", ")", "/", "SECONDS_IN_HOUR", ")" ]
26.066667
19.266667
def build_related_articles(related_articles): """ Given parsed data build a list of related article objects """ article_list = [] for related_article in related_articles: article = ea.RelatedArticle() if related_article.get('xlink_href'): article.xlink_href = related_art...
[ "def", "build_related_articles", "(", "related_articles", ")", ":", "article_list", "=", "[", "]", "for", "related_article", "in", "related_articles", ":", "article", "=", "ea", ".", "RelatedArticle", "(", ")", "if", "related_article", ".", "get", "(", "'xlink_h...
36
17.578947
def translate_docs_compact(self, ds, field_mapping=None, slim=None, map_identifiers=None, invert_subject_object=False, **kwargs): """ Translate golr association documents to a compact representation """ amap = {} logging.info("Translating docs to compact form. Slim={}".format(sli...
[ "def", "translate_docs_compact", "(", "self", ",", "ds", ",", "field_mapping", "=", "None", ",", "slim", "=", "None", ",", "map_identifiers", "=", "None", ",", "invert_subject_object", "=", "False", ",", "*", "*", "kwargs", ")", ":", "amap", "=", "{", "}...
38.689655
20.862069
def get_feature_names(self): """Get feature names. Returns ------- feature_names : list of strings Names of the features produced by transform. """ return ['temperature', 'pressure'] + [f'solvent.{x}' for x in range(1, self.max_solvents + 1)] + \ ...
[ "def", "get_feature_names", "(", "self", ")", ":", "return", "[", "'temperature'", ",", "'pressure'", "]", "+", "[", "f'solvent.{x}'", "for", "x", "in", "range", "(", "1", ",", "self", ".", "max_solvents", "+", "1", ")", "]", "+", "[", "f'solvent_amount....
37.8
22.4
def open_state_machine(path=None, recent_opened_notification=False): """ Open a state machine from respective file system path :param str path: file system path to the state machine :param bool recent_opened_notification: flags that indicates that this call also should update recently open :rtype rafc...
[ "def", "open_state_machine", "(", "path", "=", "None", ",", "recent_opened_notification", "=", "False", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "if", "path", "is", "None", ":", "if", "interface", ".", "open_folder_func", "is", "None", "...
48.410256
29.589744
def summary_pb(self): """Create a top-level experiment summary describing this experiment. The resulting summary should be written to a log directory that encloses all the individual sessions' log directories. Analogous to the low-level `experiment_pb` function in the `hparams.summary` module. ...
[ "def", "summary_pb", "(", "self", ")", ":", "hparam_infos", "=", "[", "]", "for", "hparam", "in", "self", ".", "_hparams", ":", "info", "=", "api_pb2", ".", "HParamInfo", "(", "name", "=", "hparam", ".", "name", ",", "description", "=", "hparam", ".", ...
33.178571
14.428571
def multi_assoc(self, values): '''Return a new tree with multiple values associated. The parameter values can either be a dictionary mapping indices to values, or a list of (index,value) tuples''' if isinstance(values, dict): nndict = dict([(i, LookupTreeNode(i, values[i])) f...
[ "def", "multi_assoc", "(", "self", ",", "values", ")", ":", "if", "isinstance", "(", "values", ",", "dict", ")", ":", "nndict", "=", "dict", "(", "[", "(", "i", ",", "LookupTreeNode", "(", "i", ",", "values", "[", "i", "]", ")", ")", "for", "i", ...
48.727273
22.363636
def get_assessments(self): """Gets any assessments associated with this activity. return: (osid.assessment.AssessmentList) - list of assessments raise: IllegalState - ``is_assessment_based_activity()`` is ``false`` raise: OperationFailed - unable to complete request ...
[ "def", "get_assessments", "(", "self", ")", ":", "# Implemented from template for osid.learning.Activity.get_assets_template", "if", "not", "bool", "(", "self", ".", "_my_map", "[", "'assessmentIds'", "]", ")", ":", "raise", "errors", ".", "IllegalState", "(", "'no as...
48.714286
24.095238