text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def summary( self ): """ Creates a text string representing the current query and its children for this item. :return <str> """ child_text = [] for c in range(self.childCount()): child = self.child(c) text =...
[ "def", "summary", "(", "self", ")", ":", "child_text", "=", "[", "]", "for", "c", "in", "range", "(", "self", ".", "childCount", "(", ")", ")", ":", "child", "=", "self", ".", "child", "(", "c", ")", "text", "=", "[", "child", ".", "text", "(",...
29.45
0.021382
def copy_assets(self, path='assets'): """ Copy assets into the destination directory. """ path = os.path.join(self.root_path, path) for root, _, files in os.walk(path): for file in files: fullpath = os.path.join(root, file) relpath = os.path.relpath(fullpath, path) copy_to = os.path.join(self._...
[ "def", "copy_assets", "(", "self", ",", "path", "=", "'assets'", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "root_path", ",", "path", ")", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "path", ...
37
0.028571
def encode_string(self, value): """Convert ASCII, Latin-1 or UTF-8 to pure Unicode""" if not isinstance(value, str): return value try: return unicode(value, 'utf-8') except: # really, this should throw an exception. # in the interest of not breaking current ...
[ "def", "encode_string", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "return", "value", "try", ":", "return", "unicode", "(", "value", ",", "'utf-8'", ")", "except", ":", "# really, this should throw a...
39.083333
0.014583
def initialize(config): """ Initialize a connection to the Redis database. """ # Determine the client class to use if 'redis_client' in config: client = utils.find_entrypoint('turnstile.redis_client', config['redis_client'], required=True) else: ...
[ "def", "initialize", "(", "config", ")", ":", "# Determine the client class to use", "if", "'redis_client'", "in", "config", ":", "client", "=", "utils", ".", "find_entrypoint", "(", "'turnstile.redis_client'", ",", "config", "[", "'redis_client'", "]", ",", "requir...
37.051948
0.000341
def kill_all_process(self): """ Terminates all the running processes. By default it is set to false. Users can set to true in config once the method to get_pid is done deterministically either using pid_file or an accurate keyword """ if (runtime.get_active_config("cleanup_pending_process",False)):...
[ "def", "kill_all_process", "(", "self", ")", ":", "if", "(", "runtime", ".", "get_active_config", "(", "\"cleanup_pending_process\"", ",", "False", ")", ")", ":", "for", "process", "in", "self", ".", "get_processes", "(", ")", ":", "self", ".", "terminate", ...
44.111111
0.009877
def fit_heptad_register(crangles): """Attempts to fit a heptad repeat to a set of Crick angles. Parameters ---------- crangles: [float] A list of average Crick angles for the coiled coil. Returns ------- fit_data: [(float, float, float)] Sorted list of fits for each heptad ...
[ "def", "fit_heptad_register", "(", "crangles", ")", ":", "crangles", "=", "[", "x", "if", "x", ">", "0", "else", "360", "+", "x", "for", "x", "in", "crangles", "]", "hept_p", "=", "[", "x", "*", "(", "360.0", "/", "7.0", ")", "+", "(", "(", "36...
31.46875
0.001927
def _set(self): """Called internally by Client to indicate this request has finished""" self.__event.set() if self._complete_func: self.__run_completion_func(self._complete_func, self.id_)
[ "def", "_set", "(", "self", ")", ":", "self", ".", "__event", ".", "set", "(", ")", "if", "self", ".", "_complete_func", ":", "self", ".", "__run_completion_func", "(", "self", ".", "_complete_func", ",", "self", ".", "id_", ")" ]
44
0.008929
def fso_lexists(self, path): 'overlays os.path.lexists()' try: return self._lexists(self.deref(path, to_parent=True)) except os.error: return False
[ "def", "fso_lexists", "(", "self", ",", "path", ")", ":", "try", ":", "return", "self", ".", "_lexists", "(", "self", ".", "deref", "(", "path", ",", "to_parent", "=", "True", ")", ")", "except", "os", ".", "error", ":", "return", "False" ]
27.666667
0.017544
def execute(self, eopatch): """ Compute argmax/argmin of specified `data_feature` and `data_index` :param eopatch: Input eopatch :return: eopatch with added argmax/argmin features """ if self.mask_data: valid_data_mask = eopatch.mask['VALID_DATA'] else: ...
[ "def", "execute", "(", "self", ",", "eopatch", ")", ":", "if", "self", ".", "mask_data", ":", "valid_data_mask", "=", "eopatch", ".", "mask", "[", "'VALID_DATA'", "]", "else", ":", "valid_data_mask", "=", "eopatch", ".", "mask", "[", "'IS_DATA'", "]", "i...
34.969697
0.001686
def set(self, value = True): """Set the boolean parameter""" value = value in (True,1) or ( (isinstance(value, str) or (sys.version < '3' and isinstance(value, unicode))) and (value.lower() in ("1","yes","true","enabled"))) #pylint: disable=undefined-variable return super(BooleanParameter,self)....
[ "def", "set", "(", "self", ",", "value", "=", "True", ")", ":", "value", "=", "value", "in", "(", "True", ",", "1", ")", "or", "(", "(", "isinstance", "(", "value", ",", "str", ")", "or", "(", "sys", ".", "version", "<", "'3'", "and", "isinstan...
81.75
0.039394
def state_histogram(rho, ax=None, title="", threshold=0.001): """ Visualize a density matrix as a 3d bar plot with complex phase encoded as the bar color. This code is a modified version of `an equivalent function in qutip <http://qutip.org/docs/3.1.0/apidoc/functions.html#qutip.visualization.matri...
[ "def", "state_histogram", "(", "rho", ",", "ax", "=", "None", ",", "title", "=", "\"\"", ",", "threshold", "=", "0.001", ")", ":", "rho_amps", "=", "rho", ".", "data", ".", "toarray", "(", ")", ".", "ravel", "(", ")", "nqc", "=", "int", "(", "rou...
37.770833
0.001613
def ignore(self, argument_dest, **kwargs): """ Register an argument with type knack.arguments.ignore_type (hidden/ignored) :param argument_dest: The destination argument to apply the ignore type to :type argument_dest: str """ self._check_stale() if not self._applicable(...
[ "def", "ignore", "(", "self", ",", "argument_dest", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_stale", "(", ")", "if", "not", "self", ".", "_applicable", "(", ")", ":", "return", "dest_option", "=", "[", "'--__{}'", ".", "format", "(", "...
40.75
0.01
def move_window(win_key, bbox): """ CommandLine: # List windows wmctrl -l # List desktops wmctrl -d # Window info xwininfo -id 60817412 python -m utool.util_ubuntu XCtrl.move_window joncrall 0+1920,680,400,600,400 ...
[ "def", "move_window", "(", "win_key", ",", "bbox", ")", ":", "import", "utool", "as", "ut", "import", "plottool", "as", "pt", "# NOQA", "import", "plottool", ".", "screeninfo", "as", "screeninfo", "monitor_infos", "=", "{", "i", "+", "1", ":", "screeninfo"...
40.1125
0.001825
def generate_random_graph(num_vertices=250, prob_loop=0.5, **kwargs): """Creates a random graph where the edges have different types. This method calls :func:`.minimal_random_graph`, and then adds a loop to each vertex with ``prob_loop`` probability. It then calls :func:`.set_types_random` on the resul...
[ "def", "generate_random_graph", "(", "num_vertices", "=", "250", ",", "prob_loop", "=", "0.5", ",", "*", "*", "kwargs", ")", ":", "g", "=", "minimal_random_graph", "(", "num_vertices", ",", "*", "*", "kwargs", ")", "for", "v", "in", "g", ".", "nodes", ...
37.952381
0.000815
def delete(self, _id): """Delete a document or create a DELETE revision :param str _id: The ID of the document to be deleted :returns: JSON Mongo client response including the "n" key to show number of objects effected """ mongo_response = yield self.collection.remove({"_id": Ob...
[ "def", "delete", "(", "self", ",", "_id", ")", ":", "mongo_response", "=", "yield", "self", ".", "collection", ".", "remove", "(", "{", "\"_id\"", ":", "ObjectId", "(", "_id", ")", "}", ")", "raise", "Return", "(", "mongo_response", ")" ]
40.333333
0.008086
def gen_whoosh_database(kind_arr, post_type): ''' kind_arr, define the `type` except Post, Page, Wiki post_type, define the templates for different kind. ''' SITE_CFG['LANG'] = SITE_CFG.get('LANG', 'zh') # Using jieba lib for Chinese. if SITE_CFG['LANG'] == 'zh' and ChineseAnalyzer: ...
[ "def", "gen_whoosh_database", "(", "kind_arr", ",", "post_type", ")", ":", "SITE_CFG", "[", "'LANG'", "]", "=", "SITE_CFG", ".", "get", "(", "'LANG'", ",", "'zh'", ")", "# Using jieba lib for Chinese.", "if", "SITE_CFG", "[", "'LANG'", "]", "==", "'zh'", "an...
41.777778
0.00065
def send_password_changed_email(self, user): """Send the 'password has changed' notification email.""" # Verify config settings if not self.user_manager.USER_ENABLE_EMAIL: return if not self.user_manager.USER_SEND_PASSWORD_CHANGED_EMAIL: return # Notification emails are sent to...
[ "def", "send_password_changed_email", "(", "self", ",", "user", ")", ":", "# Verify config settings", "if", "not", "self", ".", "user_manager", ".", "USER_ENABLE_EMAIL", ":", "return", "if", "not", "self", ".", "user_manager", ".", "USER_SEND_PASSWORD_CHANGED_EMAIL", ...
42.411765
0.008141
def _get_item_position(self, idx): """Return a tuple of (start, end) indices of an item from its index.""" start = 0 if idx == 0 else self._index[idx - 1] + 1 end = self._index[idx] return start, end
[ "def", "_get_item_position", "(", "self", ",", "idx", ")", ":", "start", "=", "0", "if", "idx", "==", "0", "else", "self", ".", "_index", "[", "idx", "-", "1", "]", "+", "1", "end", "=", "self", ".", "_index", "[", "idx", "]", "return", "start", ...
45.4
0.008658
def deprecated(func: Callable) -> Callable: """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" @functools.wraps(func) def _new_func(*args: Any, **kwargs: Any) -> Any: warnings.simplefilter('always'...
[ "def", "deprecated", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "_new_func", "(", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Any", ":", "warnings...
49.923077
0.001513
def completer(*commands): """Decorate a function to be the completer function of commands. Arguments: commands: Names of command that should trigger this function object. ------------------------------ Interface of completer methods: @completer('some-other_command') def comple...
[ "def", "completer", "(", "*", "commands", ")", ":", "def", "decorated_func", "(", "f", ")", ":", "f", ".", "__complete_targets__", "=", "list", "(", "commands", ")", "return", "f", "return", "decorated_func" ]
33.952381
0.000682
def optimize(self, timeSeries, forecastingMethods=None, startingPercentage=0.0, endPercentage=100.0): """Runs the optimization on the given TimeSeries. :param TimeSeries timeSeries: TimeSeries instance that requires an optimized forecast. :param list forecastingMethods: List of forecastin...
[ "def", "optimize", "(", "self", ",", "timeSeries", ",", "forecastingMethods", "=", "None", ",", "startingPercentage", "=", "0.0", ",", "endPercentage", "=", "100.0", ")", ":", "# no forecasting methods provided", "if", "forecastingMethods", "is", "None", "or", "le...
64.666667
0.008708
def sorted_options(sort_options): """Sort sort options for display. :param sort_options: A dictionary containing the field name as key and asc/desc as value. :returns: A dictionary with sorting options for Invenio-Search-JS. """ return [ { 'title': v['title'], ...
[ "def", "sorted_options", "(", "sort_options", ")", ":", "return", "[", "{", "'title'", ":", "v", "[", "'title'", "]", ",", "'value'", ":", "(", "'-{0}'", ".", "format", "(", "k", ")", "if", "v", ".", "get", "(", "'default_order'", ",", "'asc'", ")", ...
32.25
0.001883
def get_active_schedulings(self): """Return EighthScheduledActivity's of this activity since the beginning of the year.""" blocks = EighthBlock.objects.get_blocks_this_year() scheduled_activities = EighthScheduledActivity.objects.filter(activity=self) scheduled_activities = scheduled_act...
[ "def", "get_active_schedulings", "(", "self", ")", ":", "blocks", "=", "EighthBlock", ".", "objects", ".", "get_blocks_this_year", "(", ")", "scheduled_activities", "=", "EighthScheduledActivity", ".", "objects", ".", "filter", "(", "activity", "=", "self", ")", ...
54.714286
0.010283
def tokenize(text, normalize_ascii=True): """ Convert a single string into a list of substrings split along punctuation and word boundaries. Keep whitespace intact by always attaching it to the previous token. Arguments: ---------- text : str normalize_ascii : bool, perform ...
[ "def", "tokenize", "(", "text", ",", "normalize_ascii", "=", "True", ")", ":", "# 1. If there's no punctuation, return immediately", "if", "no_punctuation", ".", "match", "(", "text", ")", ":", "return", "[", "text", "]", "# 2. let's standardize the input text to ascii ...
35.289474
0.000363
def getElementsBy(start_node: ParentNode, cond: Callable[['Element'], bool]) -> NodeList: """Return list of child elements of start_node which matches ``cond``. ``cond`` must be a function which gets a single argument ``Element``, and returns boolean. If the node matches requested conditi...
[ "def", "getElementsBy", "(", "start_node", ":", "ParentNode", ",", "cond", ":", "Callable", "[", "[", "'Element'", "]", ",", "bool", "]", ")", "->", "NodeList", ":", "elements", "=", "[", "]", "for", "child", "in", "start_node", ".", "children", ":", "...
36.631579
0.001401
def is_username(string, minlen=1, maxlen=15): """ Determines whether the @string pattern is username-like @string: #str being tested @minlen: minimum required username length @maxlen: maximum username length -> #bool """ if string: string = string.strip() ret...
[ "def", "is_username", "(", "string", ",", "minlen", "=", "1", ",", "maxlen", "=", "15", ")", ":", "if", "string", ":", "string", "=", "string", ".", "strip", "(", ")", "return", "username_re", ".", "match", "(", "string", ")", "and", "(", "minlen", ...
32.75
0.002475
def set_dns(name, dnsservers=None, searchdomains=None, path=None): ''' .. versionchanged:: 2015.5.0 The ``dnsservers`` and ``searchdomains`` parameters can now be passed as a comma-separated list. Update /etc/resolv.confo path path to the container parent default: /var...
[ "def", "set_dns", "(", "name", ",", "dnsservers", "=", "None", ",", "searchdomains", "=", "None", ",", "path", "=", "None", ")", ":", "if", "dnsservers", "is", "None", ":", "dnsservers", "=", "[", "'8.8.8.8'", ",", "'4.4.4.4'", "]", "elif", "not", "isi...
34.212766
0.000302
def get_state_transition_function(self): """ Returns the transition of the state variables as nested dict in the case of table type parameter and a nested structure in case of decision diagram parameter Example -------- >>> reader = PomdpXReader('Test_PomdpX.xml'...
[ "def", "get_state_transition_function", "(", "self", ")", ":", "state_transition_function", "=", "[", "]", "for", "variable", "in", "self", ".", "network", ".", "findall", "(", "'StateTransitionFunction'", ")", ":", "for", "var", "in", "variable", ".", "findall"...
41
0.001361
def makeNodeTuple(citation, idVal, nodeInfo, fullInfo, nodeType, count, coreCitesDict, coreValues, detailedValues, addCR): """Makes a tuple of idVal and a dict of the selected attributes""" d = {} if nodeInfo: if nodeType == 'full': if coreValues: if citation in coreCites...
[ "def", "makeNodeTuple", "(", "citation", ",", "idVal", ",", "nodeInfo", ",", "fullInfo", ",", "nodeType", ",", "count", ",", "coreCitesDict", ",", "coreValues", ",", "detailedValues", ",", "addCR", ")", ":", "d", "=", "{", "}", "if", "nodeInfo", ":", "if...
40.634615
0.002311
def get_nested_dicts_with_key_value(parent_dict: dict, key, value): """Return all nested dictionaries that contain a key with a specific value. A sub-case of NestedLookup.""" references = [] NestedLookup(parent_dict, references, NestedLookup.key_value_equality_factory(key, value)) return (document for d...
[ "def", "get_nested_dicts_with_key_value", "(", "parent_dict", ":", "dict", ",", "key", ",", "value", ")", ":", "references", "=", "[", "]", "NestedLookup", "(", "parent_dict", ",", "references", ",", "NestedLookup", ".", "key_value_equality_factory", "(", "key", ...
68.2
0.008696
def is_transport_reaction_annotations(rxn): """ Return boolean if a reaction is a transport reaction (from annotations). Parameters ---------- rxn: cobra.Reaction The metabolic reaction under investigation. """ reactants = set([(k, tuple(v)) for met in rxn.reactants ...
[ "def", "is_transport_reaction_annotations", "(", "rxn", ")", ":", "reactants", "=", "set", "(", "[", "(", "k", ",", "tuple", "(", "v", ")", ")", "for", "met", "in", "rxn", ".", "reactants", "for", "k", ",", "v", "in", "iteritems", "(", "met", ".", ...
43.555556
0.000832
def readonce(self, size = None): """ Read from current buffer. If current buffer is empty, returns an empty string. You can use `prepareRead` to read the next chunk of data. This is not a coroutine method. """ if self.eof: raise EOFError if se...
[ "def", "readonce", "(", "self", ",", "size", "=", "None", ")", ":", "if", "self", ".", "eof", ":", "raise", "EOFError", "if", "self", ".", "errored", ":", "raise", "IOError", "(", "'Stream is broken before EOF'", ")", "if", "size", "is", "not", "None", ...
34.095238
0.008152
def UGT(a: BitVec, b: BitVec) -> Bool: """Create an unsigned greater than expression. :param a: :param b: :return: """ return _comparison_helper(a, b, z3.UGT, default_value=False, inputs_equal=False)
[ "def", "UGT", "(", "a", ":", "BitVec", ",", "b", ":", "BitVec", ")", "->", "Bool", ":", "return", "_comparison_helper", "(", "a", ",", "b", ",", "z3", ".", "UGT", ",", "default_value", "=", "False", ",", "inputs_equal", "=", "False", ")" ]
27.125
0.008929
def text2wngram(text, output_file, n=3, chars=63636363, words=9090909, compress=False, verbosity=2): """ List of every word n-gram which occurred in the text, along with its number of occurrences. The maximum numbers of charactors and words that can be stored in the buffer are given by the chars and...
[ "def", "text2wngram", "(", "text", ",", "output_file", ",", "n", "=", "3", ",", "chars", "=", "63636363", ",", "words", "=", "9090909", ",", "compress", "=", "False", ",", "verbosity", "=", "2", ")", ":", "cmd", "=", "[", "'text2wngram'", "]", "if", ...
35.973684
0.009259
def parse_file(self, cu, analysis): """Generate data for single file""" if hasattr(analysis, 'parser'): filename = cu.file_locator.relative_filename(cu.filename) source_lines = analysis.parser.lines with cu.source_file() as source_file: source = source...
[ "def", "parse_file", "(", "self", ",", "cu", ",", "analysis", ")", ":", "if", "hasattr", "(", "analysis", ",", "'parser'", ")", ":", "filename", "=", "cu", ".", "file_locator", ".", "relative_filename", "(", "cu", ".", "filename", ")", "source_lines", "=...
37.489362
0.001106
def _dequantize(q, params): """Dequantize q according to params.""" if not params.quantize: return q return tf.to_float(tf.bitcast(q, tf.int16)) * params.quantization_scale
[ "def", "_dequantize", "(", "q", ",", "params", ")", ":", "if", "not", "params", ".", "quantize", ":", "return", "q", "return", "tf", ".", "to_float", "(", "tf", ".", "bitcast", "(", "q", ",", "tf", ".", "int16", ")", ")", "*", "params", ".", "qua...
35.6
0.021978
def wait_for_fun(fun, timeout=900, **kwargs): ''' Wait until a function finishes, or times out ''' start = time.time() log.debug('Attempting function %s', fun) trycount = 0 while True: trycount += 1 try: response = fun(**kwargs) if not isinstance(respo...
[ "def", "wait_for_fun", "(", "fun", ",", "timeout", "=", "900", ",", "*", "*", "kwargs", ")", ":", "start", "=", "time", ".", "time", "(", ")", "log", ".", "debug", "(", "'Attempting function %s'", ",", "fun", ")", "trycount", "=", "0", "while", "True...
33.4
0.001456
def open(in_file, in_fmt=None): """ Reads in a file from disk. Arguments: in_file: The name of the file to read in in_fmt: The format of in_file, if you want to be explicit Returns: numpy.ndarray """ fmt = in_file.split('.')[-1] if in_fmt: fmt = in_fmt f...
[ "def", "open", "(", "in_file", ",", "in_fmt", "=", "None", ")", ":", "fmt", "=", "in_file", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "if", "in_fmt", ":", "fmt", "=", "in_fmt", "fmt", "=", "fmt", ".", "lower", "(", ")", "if", "fmt", ...
24.8
0.001942
def load_file(self, file_path) -> List[str]: """ Loads the content of the text file """ content = [] content = read_lines_from_file(file_path) return content
[ "def", "load_file", "(", "self", ",", "file_path", ")", "->", "List", "[", "str", "]", ":", "content", "=", "[", "]", "content", "=", "read_lines_from_file", "(", "file_path", ")", "return", "content" ]
37
0.010582
def store_and_use_artifact(self, cache_key, src, results_dir=None): """Store and then extract the artifact from the given `src` iterator for the given cache_key. :param cache_key: Cache key for the artifact. :param src: Iterator over binary data to store for the artifact. :param str results_dir: The pa...
[ "def", "store_and_use_artifact", "(", "self", ",", "cache_key", ",", "src", ",", "results_dir", "=", "None", ")", ":", "with", "self", ".", "_tmpfile", "(", "cache_key", ",", "'read'", ")", "as", "tmp", ":", "for", "chunk", "in", "src", ":", "tmp", "."...
48.647059
0.013634
def size(cls, crawler): """Total operations pending for this crawler""" key = make_key('queue_pending', crawler) return unpack_int(conn.get(key))
[ "def", "size", "(", "cls", ",", "crawler", ")", ":", "key", "=", "make_key", "(", "'queue_pending'", ",", "crawler", ")", "return", "unpack_int", "(", "conn", ".", "get", "(", "key", ")", ")" ]
41.5
0.011834
def _generate_comparator(cls, field_names): """ Construct a comparator function based on the field names. The comparator returns the first non-zero comparison value. Inputs: field_names (iterable of strings): The field names to sort on. Returns: A compar...
[ "def", "_generate_comparator", "(", "cls", ",", "field_names", ")", ":", "# Ensure that field names is a list and not a tuple.", "field_names", "=", "list", "(", "field_names", ")", "# For fields that start with a '-', reverse the ordering of the", "# comparison.", "reverses", "=...
35.466667
0.001829
def simple_atmo(rgb, haze, contrast, bias): """ A simple, static (non-adaptive) atmospheric correction function. Parameters ---------- haze: float Amount of haze to adjust for. For example, 0.03 contrast : integer Enhances the intensity differences between the lighter and darker...
[ "def", "simple_atmo", "(", "rgb", ",", "haze", ",", "contrast", ",", "bias", ")", ":", "gamma_b", "=", "1", "-", "haze", "gamma_g", "=", "1", "-", "(", "haze", "/", "3.0", ")", "arr", "=", "np", ".", "empty", "(", "shape", "=", "(", "3", ",", ...
29.714286
0.001164
def evaluate_accuracy(data_iterator, network): """ Measure the accuracy of ResNet Parameters ---------- data_iterator: Iter examples of dataset network: ResNet Returns ---------- tuple of array element """ acc = mx.metric.Accuracy() # Iterate through data and l...
[ "def", "evaluate_accuracy", "(", "data_iterator", ",", "network", ")", ":", "acc", "=", "mx", ".", "metric", ".", "Accuracy", "(", ")", "# Iterate through data and label", "for", "i", ",", "(", "data", ",", "label", ")", "in", "enumerate", "(", "data_iterato...
27.181818
0.002153
def deinit(bus=DEFAULT_SPI_BUS, chip_select=DEFAULT_SPI_CHIP_SELECT): """Stops interrupts on all boards. Only required when using :func:`digital_read` and :func:`digital_write`. :param bus: SPI bus /dev/spidev<bus>.<chipselect> (default: {bus}) :type bus: int :param chip_select: SPI chip...
[ "def", "deinit", "(", "bus", "=", "DEFAULT_SPI_BUS", ",", "chip_select", "=", "DEFAULT_SPI_CHIP_SELECT", ")", ":", "global", "_pifacedigitals", "for", "pfd", "in", "_pifacedigitals", ":", "try", ":", "pfd", ".", "deinit_board", "(", ")", "except", "AttributeErro...
32.529412
0.001757
def main(model_folder, override=False): """Parse the info.yml from ``model_folder`` and create the model file.""" model_description_file = os.path.join(model_folder, "info.yml") # Read the model description file with open(model_description_file, 'r') as ymlfile: model_description = yaml.load(yml...
[ "def", "main", "(", "model_folder", ",", "override", "=", "False", ")", ":", "model_description_file", "=", "os", ".", "path", ".", "join", "(", "model_folder", ",", "\"info.yml\"", ")", "# Read the model description file", "with", "open", "(", "model_description_...
44.821429
0.00078
def next(self): """ :return: The next result item. :rtype: dict :raises StopIteration: If there is no more result. """ if self._cur_item is not None: res = self._cur_item self._cur_item = None return res r...
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "_cur_item", "is", "not", "None", ":", "res", "=", "self", ".", "_cur_item", "self", ".", "_cur_item", "=", "None", "return", "res", "return", "next", "(", "self", ".", "_ex_context", ")" ]
25.846154
0.014368
def get_current_round(self, tournament=1): """Get number of the current active round. Args: tournament (int): ID of the tournament (optional, defaults to 1) Returns: int: number of the current active round Example: >>> NumerAPI().get_current_round()...
[ "def", "get_current_round", "(", "self", ",", "tournament", "=", "1", ")", ":", "# zero is an alias for the current round!", "query", "=", "'''\n query($tournament: Int!) {\n rounds(tournament: $tournament\n number: 0) {\n number\n...
28.535714
0.002421
def axis_rotation_matrix(axis, theta): """Returns a rotation matrix around the given axis""" [x, y, z] = axis c = np.cos(theta) s = np.sin(theta) return np.array([ [x**2 + (1 - x**2) * c, x * y * (1 - c) - z * s, x * z * (1 - c) + y * s], [x * y * (1 - c) + z * s, y ** 2 + (1 - y**2)...
[ "def", "axis_rotation_matrix", "(", "axis", ",", "theta", ")", ":", "[", "x", ",", "y", ",", "z", "]", "=", "axis", "c", "=", "np", ".", "cos", "(", "theta", ")", "s", "=", "np", ".", "sin", "(", "theta", ")", "return", "np", ".", "array", "(...
43.1
0.009091
def set_type(self, value): """Setter for type attribute""" if self.action == "remove" and value != "probes": log = "Sources field 'type' when action is remove should always be 'probes'." raise MalFormattedSource(log) self._type = value
[ "def", "set_type", "(", "self", ",", "value", ")", ":", "if", "self", ".", "action", "==", "\"remove\"", "and", "value", "!=", "\"probes\"", ":", "log", "=", "\"Sources field 'type' when action is remove should always be 'probes'.\"", "raise", "MalFormattedSource", "(...
46.333333
0.010601
def script(vm_): ''' Return the script deployment object ''' script_name = config.get_cloud_config_value('script', vm_, __opts__) if not script_name: script_name = 'bootstrap-salt' return salt.utils.cloud.os_script( script_name, vm_, __opts__, salt.utils....
[ "def", "script", "(", "vm_", ")", ":", "script_name", "=", "config", ".", "get_cloud_config_value", "(", "'script'", ",", "vm_", ",", "__opts__", ")", "if", "not", "script_name", ":", "script_name", "=", "'bootstrap-salt'", "return", "salt", ".", "utils", "....
25.3125
0.002381
def signal_pid(pid, signum): """ Send the given process a signal. @returns: whether or not the process with the given pid was running """ try: os.kill(pid, signum) return True except OSError, e: # see man 2 kill if e.errno == errno.EPERM: # exists but...
[ "def", "signal_pid", "(", "pid", ",", "signum", ")", ":", "try", ":", "os", ".", "kill", "(", "pid", ",", "signum", ")", "return", "True", "except", "OSError", ",", "e", ":", "# see man 2 kill", "if", "e", ".", "errno", "==", "errno", ".", "EPERM", ...
25.666667
0.002088
def as_dict( self, display_source=False, display_sensitive=False, raw=False): """ Returns the current configuration as an OrderedDict of OrderedDicts. :param display_source: If False, the option value is returned. If True, a tuple of (option_value, source) is returned. So...
[ "def", "as_dict", "(", "self", ",", "display_source", "=", "False", ",", "display_sensitive", "=", "False", ",", "raw", "=", "False", ")", ":", "cfg", "=", "{", "}", "configs", "=", "[", "(", "'default'", ",", "self", ".", "airflow_defaults", ")", ",",...
41.016667
0.000794
def _cr_decode(self, msg): """CR: Custom values""" if int(msg[4:6]) > 0: index = int(msg[4:6])-1 return {'values': [self._cr_one_custom_value_decode(index, msg[6:12])]} else: part = 6 ret = [] for i in range(Max.SETTINGS.value): ...
[ "def", "_cr_decode", "(", "self", ",", "msg", ")", ":", "if", "int", "(", "msg", "[", "4", ":", "6", "]", ")", ">", "0", ":", "index", "=", "int", "(", "msg", "[", "4", ":", "6", "]", ")", "-", "1", "return", "{", "'values'", ":", "[", "s...
37
0.008791
def within(self, lat, lon, radius): ''' Apply a geo=$circle/$center filter. Radius is in meters. Subsequent within() calls replace earlier geo filters on this query. ''' self._geo = { "$circle": { "$center": [ factual.common.shared_filter_helpers.GeoScalar(lat), factual.common.shared_fi...
[ "def", "within", "(", "self", ",", "lat", ",", "lon", ",", "radius", ")", ":", "self", ".", "_geo", "=", "{", "\"$circle\"", ":", "{", "\"$center\"", ":", "[", "factual", ".", "common", ".", "shared_filter_helpers", ".", "GeoScalar", "(", "lat", ")", ...
28.642857
0.05314
def is_domain(value, **kwargs): """Indicate whether ``value`` is a valid domain. .. caution:: This validator does not verify that ``value`` **exists** as a domain. It merely verifies that its contents *might* exist as a domain. .. note:: This validator checks to validate that ``value``...
[ "def", "is_domain", "(", "value", ",", "*", "*", "kwargs", ")", ":", "try", ":", "value", "=", "validators", ".", "domain", "(", "value", ",", "*", "*", "kwargs", ")", "except", "SyntaxError", "as", "error", ":", "raise", "error", "except", "Exception"...
36.088889
0.002398
def pandas_mesh(df): """Create numpy 2-D "meshgrid" from 3+ columns in a Pandas DataFrame Arguments: df (DataFrame): Must have 3 or 4 columns of numerical data Returns: OrderedDict: column labels from the data frame are the keys, values are 2-D matrices All matrices have shape NxM, whe...
[ "def", "pandas_mesh", "(", "df", ")", ":", "xyz", "=", "[", "df", "[", "c", "]", ".", "values", "for", "c", "in", "df", ".", "columns", "]", "index", "=", "pd", ".", "MultiIndex", ".", "from_tuples", "(", "zip", "(", "xyz", "[", "0", "]", ",", ...
36.340426
0.002281
def create(self, path, data=None): """Send a POST CRUD API request to the given path using the given data which will be converted to json""" return self.handleresult(self.r.post(urljoin(self.url + CRUD_PATH, path), ...
[ "def", "create", "(", "self", ",", "path", ",", "data", "=", "None", ")", ":", "return", "self", ".", "handleresult", "(", "self", ".", "r", ".", "post", "(", "urljoin", "(", "self", ".", "url", "+", "CRUD_PATH", ",", "path", ")", ",", "data", "=...
59.166667
0.008333
def _process_book(html_chunk): """ Parse available informations about book from the book details page. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: obj: :class:`structures.Publication` instance with book details. """ title, book_url = ...
[ "def", "_process_book", "(", "html_chunk", ")", ":", "title", ",", "book_url", "=", "_parse_title_url", "(", "html_chunk", ")", "# download page with details", "data", "=", "DOWNER", ".", "download", "(", "book_url", ")", "dom", "=", "dhtmlparser", ".", "parseSt...
27.942857
0.001976
def open(self, name, *mode): """ Return an open file object for a file in the reference package. """ return self.file_factory(self.file_path(name), *mode)
[ "def", "open", "(", "self", ",", "name", ",", "*", "mode", ")", ":", "return", "self", ".", "file_factory", "(", "self", ".", "file_path", "(", "name", ")", ",", "*", "mode", ")" ]
36.4
0.010753
def write_stream (stream, holders, defaultsection=None): """Very simple writing in ini format. The simple stringification of each value in each Holder is printed, and no escaping is performed. (This is most relevant for multiline values or ones containing pound signs.) `None` values are skipped. Ar...
[ "def", "write_stream", "(", "stream", ",", "holders", ",", "defaultsection", "=", "None", ")", ":", "anybefore", "=", "False", "for", "h", "in", "holders", ":", "if", "anybefore", ":", "print", "(", "''", ",", "file", "=", "stream", ")", "s", "=", "h...
29.189189
0.012545
def _create_single_feature_method(feature): """Return a function that will detect a single feature. Args: feature (enum): A specific feature defined as a member of :class:`~enums.Feature.Type`. Returns: function: A helper function to detect just that feature. """ # Defi...
[ "def", "_create_single_feature_method", "(", "feature", ")", ":", "# Define the function properties.", "fx_name", "=", "feature", ".", "name", ".", "lower", "(", ")", "if", "\"detection\"", "in", "fx_name", ":", "fx_doc", "=", "\"Perform {0}.\"", ".", "format", "(...
35.568966
0.001415
def priority_compare(self, other): """ Compares the MIME::Type based on how reliable it is before doing a normal <=> comparison. Used by MIME::Types#[] to sort types. The comparisons involved are: 1. self.simplified <=> other.simplified (ensures that we don't try to co...
[ "def", "priority_compare", "(", "self", ",", "other", ")", ":", "pc", "=", "cmp", "(", "self", ".", "simplified", ",", "other", ".", "simplified", ")", "if", "pc", "is", "0", ":", "if", "self", ".", "is_registered", "!=", "other", ".", "is_registered",...
46.361111
0.001761
def from_json(buffer, auto_flatten=True, raise_for_index=True): """Parses a JSON string into either a view or an index. If auto flatten is enabled a sourcemap index that does not contain external references is automatically flattened into a view. By default if an index would be returned an `IndexedSou...
[ "def", "from_json", "(", "buffer", ",", "auto_flatten", "=", "True", ",", "raise_for_index", "=", "True", ")", ":", "buffer", "=", "to_bytes", "(", "buffer", ")", "view_out", "=", "_ffi", ".", "new", "(", "'lsm_view_t **'", ")", "index_out", "=", "_ffi", ...
38.071429
0.000915
def _is_at_qry_end(self, nucmer_hit): '''Returns True iff the hit is "close enough" to the end of the query sequence''' hit_coords = nucmer_hit.qry_coords() return hit_coords.end >= nucmer_hit.qry_length - self.qry_end_tolerance
[ "def", "_is_at_qry_end", "(", "self", ",", "nucmer_hit", ")", ":", "hit_coords", "=", "nucmer_hit", ".", "qry_coords", "(", ")", "return", "hit_coords", ".", "end", ">=", "nucmer_hit", ".", "qry_length", "-", "self", ".", "qry_end_tolerance" ]
62.25
0.011905
def coord_grid(self): """Draw a grid of RA/DEC on Canvas.""" import math,ephem ra2=math.pi*2 ra1=0 dec1=-1*math.pi/2.0 dec2=math.pi/2.0 ## grid space choices ## ra space in hours ra_grids=["06:00:00", "03:00:00", ...
[ "def", "coord_grid", "(", "self", ")", ":", "import", "math", ",", "ephem", "ra2", "=", "math", ".", "pi", "*", "2", "ra1", "=", "0", "dec1", "=", "-", "1", "*", "math", ".", "pi", "/", "2.0", "dec2", "=", "math", ".", "pi", "/", "2.0", "## g...
30.542857
0.032623
def reference_handler(self,iobject, fact, attr_info, add_fact_kargs): """ Handler for facts that contain a reference to a fact. See below in the comment regarding the fact_handler_list for a description of the signature of handler functions. As shown below in the handler list, t...
[ "def", "reference_handler", "(", "self", ",", "iobject", ",", "fact", ",", "attr_info", ",", "add_fact_kargs", ")", ":", "(", "namespace_uri", ",", "uid", ")", "=", "(", "self", ".", "identifier_ns_uri", ",", "attr_info", "[", "'idref'", "]", ")", "# We ar...
43.5
0.008176
def MatchBestComponentName(self, component): """Returns the name of the component which matches best our base listing. In order to do the best case insensitive matching we list the files in the base handler and return the base match for this component. Args: component: A component name which sho...
[ "def", "MatchBestComponentName", "(", "self", ",", "component", ")", ":", "fd", "=", "self", ".", "OpenAsContainer", "(", ")", "# Adjust the component casing", "file_listing", "=", "set", "(", "fd", ".", "ListNames", "(", ")", ")", "# First try an exact match", ...
29.735294
0.008621
def assortativity_attributes(user): """ Computes the assortativity of the nominal attributes. This indicator measures the homophily of the current user with his correspondants, for each attributes. It returns a value between 0 (no assortativity) and 1 (all the contacts share the same value): th...
[ "def", "assortativity_attributes", "(", "user", ")", ":", "matrix", "=", "matrix_undirected_unweighted", "(", "user", ")", "neighbors", "=", "[", "k", "for", "k", "in", "user", ".", "network", ".", "keys", "(", ")", "if", "k", "!=", "user", ".", "name", ...
39.206897
0.001717
def search(T, dist, w, i=0): """Searches for w[i:] in trie T with distance at most dist """ if i == len(w): if T is not None and T.isWord and dist == 0: return "" else: return None if T is None: return None f = search(T.s[w[i]], dist, w, i + 1) #...
[ "def", "search", "(", "T", ",", "dist", ",", "w", ",", "i", "=", "0", ")", ":", "if", "i", "==", "len", "(", "w", ")", ":", "if", "T", "is", "not", "None", "and", "T", ".", "isWord", "and", "dist", "==", "0", ":", "return", "\"\"", "else", ...
29.782609
0.001414
def get_repo_data(saltenv='base'): ''' Returns the existing package metadata db. Will create it, if it does not exist, however will not refresh it. Args: saltenv (str): Salt environment. Default ``base`` Returns: dict: A dict containing contents of metadata db. CLI Example: ...
[ "def", "get_repo_data", "(", "saltenv", "=", "'base'", ")", ":", "# we only call refresh_db if it does not exist, as we want to return", "# the existing data even if its old, other parts of the code call this,", "# but they will call refresh if they need too.", "repo_details", "=", "_get_r...
32.446809
0.00191
def convert_to(obj, ac_ordered=False, ac_dict=None, **options): """ Convert a mapping objects to a dict or object of 'to_type' recursively. Borrowed basic idea and implementation from bunch.unbunchify. (bunch is distributed under MIT license same as this.) :param obj: A mapping objects or other pri...
[ "def", "convert_to", "(", "obj", ",", "ac_ordered", "=", "False", ",", "ac_dict", "=", "None", ",", "*", "*", "options", ")", ":", "options", ".", "update", "(", "ac_ordered", "=", "ac_ordered", ",", "ac_dict", "=", "ac_dict", ")", "if", "anyconfig", "...
39.846154
0.000943
def security_rule_delete(security_rule, security_group, resource_group, **kwargs): ''' .. versionadded:: 2019.2.0 Delete a security rule within a specified security group. :param name: The name of the security rule to delete. :param security_group: The network security gr...
[ "def", "security_rule_delete", "(", "security_rule", ",", "security_group", ",", "resource_group", ",", "*", "*", "kwargs", ")", ":", "result", "=", "False", "netconn", "=", "__utils__", "[", "'azurearm.get_client'", "]", "(", "'network'", ",", "*", "*", "kwar...
28.861111
0.001862
def create_dataset(self, owner_id, **kwargs): """Create a new dataset :param owner_id: Username of the owner of the new dataset :type owner_id: str :param title: Dataset title (will be used to generate dataset id on creation) :type title: str :param descripti...
[ "def", "create_dataset", "(", "self", ",", "owner_id", ",", "*", "*", "kwargs", ")", ":", "request", "=", "self", ".", "__build_dataset_obj", "(", "lambda", ":", "_swagger", ".", "DatasetCreateRequest", "(", "title", "=", "kwargs", ".", "get", "(", "'title...
41.350877
0.000829
def _complement_tag_options(options): """ :param options: Keyword options :: dict >>> ref = _TAGS.copy() >>> ref["text"] = "#text" >>> opts = _complement_tag_options({"tags": {"text": ref["text"]}}) >>> del opts["tags"] # To simplify comparison. >>> sorted(opts.items()) [('attrs', '@at...
[ "def", "_complement_tag_options", "(", "options", ")", ":", "if", "not", "all", "(", "nt", "in", "options", "for", "nt", "in", "_TAGS", ")", ":", "tags", "=", "options", ".", "get", "(", "\"tags\"", ",", "{", "}", ")", "for", "ntype", ",", "tag", "...
33
0.001733
def validate(self): """ Verify that the value of the LongInteger is valid. Raises: TypeError: if the value is not of type int or long ValueError: if the value cannot be represented by a signed 64-bit integer """ if self.value is not None: ...
[ "def", "validate", "(", "self", ")", ":", "if", "self", ".", "value", "is", "not", "None", ":", "if", "not", "isinstance", "(", "self", ".", "value", ",", "six", ".", "integer_types", ")", ":", "raise", "TypeError", "(", "'expected (one of): {0}, observed:...
41.75
0.002342
def parse_to_dict(self): """ parse raw CSV into dictionary """ lst = [] with open(self.fname, 'r') as f: hdr = f.readline() self.hdrs = hdr.split(',') #print("self.hdrs = ", self.hdrs) for line in f: cols = line.spli...
[ "def", "parse_to_dict", "(", "self", ")", ":", "lst", "=", "[", "]", "with", "open", "(", "self", ".", "fname", ",", "'r'", ")", "as", "f", ":", "hdr", "=", "f", ".", "readline", "(", ")", "self", ".", "hdrs", "=", "hdr", ".", "split", "(", "...
38.181818
0.009292
def macro(name): """Replaces :func:`~flask_admin.model.template.macro`, adding support for using macros imported from another file. For example: .. code:: html+jinja {# templates/admin/column_formatters.html #} {% macro email(model, column) %} {% set address = model[column] %} ...
[ "def", "macro", "(", "name", ")", ":", "def", "wrapper", "(", "view", ",", "context", ",", "model", ",", "column", ")", ":", "if", "'.'", "in", "name", ":", "macro_import_name", ",", "macro_name", "=", "name", ".", "split", "(", "'.'", ")", "m", "=...
27.642857
0.002496
def mavlink_packet(self, m): '''handle an incoming mavlink packet''' #do nothing if not caibrating if (self.calibrating == False): return if m.get_type() == 'RC_CHANNELS_RAW': for i in range(1,self.num_channels+1): v = getattr(m, 'chan%u_raw' % i)...
[ "def", "mavlink_packet", "(", "self", ",", "m", ")", ":", "#do nothing if not caibrating", "if", "(", "self", ".", "calibrating", "==", "False", ")", ":", "return", "if", "m", ".", "get_type", "(", ")", "==", "'RC_CHANNELS_RAW'", ":", "for", "i", "in", "...
39.625
0.010786
def install_visiting(self, path, visitor, prefix=None): """ Installs all the modules found in the given path if they are accepted by the visitor. The visitor must be a callable accepting 3 parameters: * fullname: The full name of the module * is_package: If True, ...
[ "def", "install_visiting", "(", "self", ",", "path", ",", "visitor", ",", "prefix", "=", "None", ")", ":", "# Validate the path", "if", "not", "path", ":", "raise", "ValueError", "(", "\"Empty path\"", ")", "elif", "not", "is_string", "(", "path", ")", ":"...
37.459459
0.000703
def filter(self, func, dropna=True, *args, **kwargs): # noqa """ Return a copy of a DataFrame excluding elements from groups that do not satisfy the boolean criterion specified by func. Parameters ---------- f : function Function to apply to each subframe. S...
[ "def", "filter", "(", "self", ",", "func", ",", "dropna", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# noqa", "indices", "=", "[", "]", "obj", "=", "self", ".", "_selected_obj", "gen", "=", "self", ".", "grouper", ".", "ge...
33.213115
0.000959
def get_pstats(pstatfile, n): """ Return profiling information as an RST table. :param pstatfile: path to a .pstat file :param n: the maximum number of stats to retrieve """ with tempfile.TemporaryFile(mode='w+') as stream: ps = pstats.Stats(pstatfile, stream=stream) ps.sort_sta...
[ "def", "get_pstats", "(", "pstatfile", ",", "n", ")", ":", "with", "tempfile", ".", "TemporaryFile", "(", "mode", "=", "'w+'", ")", "as", "stream", ":", "ps", "=", "pstats", ".", "Stats", "(", "pstatfile", ",", "stream", "=", "stream", ")", "ps", "."...
40.606061
0.000729
def PrintField(self, field, value): """Print a single field name/value pair.""" out = self.out out.write(' ' * self.indent) if self.use_field_number: out.write(str(field.number)) else: if field.is_extension: out.write('[') if (field.containing_type.GetOptions().message_se...
[ "def", "PrintField", "(", "self", ",", "field", ",", "value", ")", ":", "out", "=", "self", ".", "out", "out", ".", "write", "(", "' '", "*", "self", ".", "indent", ")", "if", "self", ".", "use_field_number", ":", "out", ".", "write", "(", "str", ...
33.875
0.011659
def listdir(self, name, **kwargs): """ Returns a list of the files under the specified path. This is different from list as it will only give you files under the current directory, much like ls. name must be in the form of `s3://bucket/prefix/` Parameters -----...
[ "def", "listdir", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "_is_s3", "(", "name", ")", ",", "\"name must be in form s3://bucket/prefix/\"", "if", "not", "name", ".", "endswith", "(", "'/'", ")", ":", "name", "+=...
32.666667
0.002478
def collect(self, top, sup, argv=None, parent=""): """ means this element is part of a larger object, hence a property of that object """ try: argv_copy = sd_copy(argv) return [self.repr(top, sup, argv_copy, parent=parent)], [] except AttributeError as e...
[ "def", "collect", "(", "self", ",", "top", ",", "sup", ",", "argv", "=", "None", ",", "parent", "=", "\"\"", ")", ":", "try", ":", "argv_copy", "=", "sd_copy", "(", "argv", ")", "return", "[", "self", ".", "repr", "(", "top", ",", "sup", ",", "...
37.2
0.010499
def _phi0(self, tau, delta): """Ideal gas Helmholtz free energy and derivatives Parameters ---------- tau : float Inverse reduced temperature Tc/T, [-] delta : float Reduced density rho/rhoc, [-] Returns ------- prop : dictionary ...
[ "def", "_phi0", "(", "self", ",", "tau", ",", "delta", ")", ":", "Fi0", "=", "self", ".", "Fi0", "fio", "=", "Fi0", "[", "\"ao_log\"", "]", "[", "0", "]", "*", "log", "(", "delta", ")", "+", "Fi0", "[", "\"ao_log\"", "]", "[", "1", "]", "*", ...
30.546875
0.000991
def request_raw(self, method, url, params=None, supplied_headers=None): """ Mechanism for issuing an API call """ from stripe import api_version if self.api_key: my_api_key = self.api_key else: from stripe import api_key my_api_key = a...
[ "def", "request_raw", "(", "self", ",", "method", ",", "url", ",", "params", "=", "None", ",", "supplied_headers", "=", "None", ")", ":", "from", "stripe", "import", "api_version", "if", "self", ".", "api_key", ":", "my_api_key", "=", "self", ".", "api_k...
38.290323
0.000547
def _start_ec2_instances(awsclient, ec2_instances, wait=True): """Helper to start ec2 instances :param awsclient: :param ec2_instances: :param wait: waits for instances to start :return: """ if len(ec2_instances) == 0: return client_ec2 = awsclient.get_client('ec2') # get s...
[ "def", "_start_ec2_instances", "(", "awsclient", ",", "ec2_instances", ",", "wait", "=", "True", ")", ":", "if", "len", "(", "ec2_instances", ")", "==", "0", ":", "return", "client_ec2", "=", "awsclient", ".", "get_client", "(", "'ec2'", ")", "# get stopped ...
32.897436
0.000757
def var(self): """ Variance value as a result of an uncertainty calculation """ mn = self.mean vr = np.mean((self._mcpts - mn) ** 2) return vr
[ "def", "var", "(", "self", ")", ":", "mn", "=", "self", ".", "mean", "vr", "=", "np", ".", "mean", "(", "(", "self", ".", "_mcpts", "-", "mn", ")", "**", "2", ")", "return", "vr" ]
26.285714
0.010526
def die(self, password=''): """ Tells the IRCd to die. Optional arguments: * password='' - Die command password. """ with self.lock: self.send('DIE :%s' % password, error_check=True)
[ "def", "die", "(", "self", ",", "password", "=", "''", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "send", "(", "'DIE :%s'", "%", "password", ",", "error_check", "=", "True", ")" ]
29.375
0.008264
def _shouldConnect(self, node): """ Check whether this node should initiate a connection to another node :param node: the other node :type node: Node """ return isinstance(node, TCPNode) and node not in self._preventConnectNodes and (self._selfIsReadonlyNode or self._se...
[ "def", "_shouldConnect", "(", "self", ",", "node", ")", ":", "return", "isinstance", "(", "node", ",", "TCPNode", ")", "and", "node", "not", "in", "self", ".", "_preventConnectNodes", "and", "(", "self", ".", "_selfIsReadonlyNode", "or", "self", ".", "_sel...
38
0.008571
def surfpt(positn, u, a, b, c): """ Determine the intersection of a line-of-sight vector with the surface of an ellipsoid. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/surfpt_c.html :param positn: Position of the observer in body-fixed frame. :type positn: 3-Element Array of floats ...
[ "def", "surfpt", "(", "positn", ",", "u", ",", "a", ",", "b", ",", "c", ")", ":", "a", "=", "ctypes", ".", "c_double", "(", "a", ")", "b", "=", "ctypes", ".", "c_double", "(", "b", ")", "c", "=", "ctypes", ".", "c_double", "(", "c", ")", "p...
37.689655
0.000892
def _compute_hamming_matrix(N): """Compute and store a Hamming matrix for |N| nodes. Hamming matrices have the following sizes:: N MBs == === 9 2 10 8 11 32 12 128 13 512 Given these sizes and the fact that large matrices are needed infrequ...
[ "def", "_compute_hamming_matrix", "(", "N", ")", ":", "possible_states", "=", "np", ".", "array", "(", "list", "(", "utils", ".", "all_states", "(", "(", "N", ")", ")", ")", ")", "return", "cdist", "(", "possible_states", ",", "possible_states", ",", "'h...
31.833333
0.001271
def parse_import_directory(self, rva, size): """Walk and parse the import directory.""" import_descs = [] while True: try: # If the RVA is invalid all would blow up. Some EXEs seem to be # specially nasty and have an invalid RVA. ...
[ "def", "parse_import_directory", "(", "self", ",", "rva", ",", "size", ")", ":", "import_descs", "=", "[", "]", "while", "True", ":", "try", ":", "# If the RVA is invalid all would blow up. Some EXEs seem to be", "# specially nasty and have an invalid RVA.", "data", "=", ...
39.791045
0.016837
def do_s1(self, line): """Send a SelectAndOperate BinaryOutput (group 12) index 8 LATCH_ON to the Outstation. Command syntax is: s1""" self.application.send_select_and_operate_command(opendnp3.ControlRelayOutputBlock(opendnp3.ControlCode.LATCH_ON), ...
[ "def", "do_s1", "(", "self", ",", "line", ")", ":", "self", ".", "application", ".", "send_select_and_operate_command", "(", "opendnp3", ".", "ControlRelayOutputBlock", "(", "opendnp3", ".", "ControlCode", ".", "LATCH_ON", ")", ",", "8", ",", "command_callback",...
79
0.010025
def to_web(self, host=None, user=None, password=None): """Send the model to BEL Commons by wrapping :py:func:`pybel.to_web` The parameters ``host``, ``user``, and ``password`` all check the PyBEL configuration, which is located at ``~/.config/pybel/config.json`` by default Para...
[ "def", "to_web", "(", "self", ",", "host", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ")", ":", "response", "=", "pybel", ".", "to_web", "(", "self", ".", "model", ",", "host", "=", "host", ",", "user", "=", "user", ",",...
43.387097
0.001455
def ngayThangNamCanChi(nn, tt, nnnn, duongLich=True, timeZone=7): """chuyển đổi năm, tháng âm/dương lịch sang Can, Chi trong tiếng Việt. Không tính đến can ngày vì phải chuyển đổi qua lịch Julius. Hàm tìm can ngày là hàm canChiNgay(nn, tt, nnnn, duongLich=True,\ timeZone...
[ "def", "ngayThangNamCanChi", "(", "nn", ",", "tt", ",", "nnnn", ",", "duongLich", "=", "True", ",", "timeZone", "=", "7", ")", ":", "if", "duongLich", "is", "True", ":", "[", "nn", ",", "tt", ",", "nnnn", ",", "thangNhuan", "]", "=", "ngayThangNam", ...
30.8
0.001259
def qualify(ref, resolvers, defns=Namespace.default): """ Get a reference that is I{qualified} by namespace. @param ref: A referenced schema type name. @type ref: str @param resolvers: A list of objects to be used to resolve types. @type resolvers: [L{sax.element.Element},] @param defns: An ...
[ "def", "qualify", "(", "ref", ",", "resolvers", ",", "defns", "=", "Namespace", ".", "default", ")", ":", "ns", "=", "None", "p", ",", "n", "=", "splitPrefix", "(", "ref", ")", "if", "p", "is", "not", "None", ":", "if", "not", "isinstance", "(", ...
34.655172
0.000968
def zip_sequences(G, allseqs, color="white"): """ Fuse certain nodes together, if they contain same data except for the sequence name. """ for s in zip(*allseqs): groups = defaultdict(list) for x in s: part = x.split('_', 1)[1] groups[part].append(x) f...
[ "def", "zip_sequences", "(", "G", ",", "allseqs", ",", "color", "=", "\"white\"", ")", ":", "for", "s", "in", "zip", "(", "*", "allseqs", ")", ":", "groups", "=", "defaultdict", "(", "list", ")", "for", "x", "in", "s", ":", "part", "=", "x", ".",...
32.6
0.001988
def ParallelCalculate(cls,syslst,properties=['energy'],system_changes=all_changes): ''' Run a series of calculations in parallel using (implicitely) some remote machine/cluster. The function returns the list of systems ready for the extraction of calculated properties. ''' ...
[ "def", "ParallelCalculate", "(", "cls", ",", "syslst", ",", "properties", "=", "[", "'energy'", "]", ",", "system_changes", "=", "all_changes", ")", ":", "print", "(", "'Launching:'", ",", "end", "=", "' '", ")", "sys", ".", "stdout", ".", "flush", "(", ...
37.08
0.017876