text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def cloud_add_link_task(cookie, tokens, source_url, save_path, vcode='', vcode_input=''): '''新建离线下载任务. source_url - 可以是http/https/ftp等一般的链接 可以是eMule这样的链接 path - 要保存到哪个目录, 比如 /Music/, 以/开头, 以/结尾的绝对路径. ''' url = ''.join([ const.PAN_URL, ...
[ "def", "cloud_add_link_task", "(", "cookie", ",", "tokens", ",", "source_url", ",", "save_path", ",", "vcode", "=", "''", ",", "vcode_input", "=", "''", ")", ":", "url", "=", "''", ".", "join", "(", "[", "const", ".", "PAN_URL", ",", "'rest/2.0/services/...
31.162162
0.001682
def build(self, text): super(PageTitle, self).build() """ :param text: Page title """ self.content = text
[ "def", "build", "(", "self", ",", "text", ")", ":", "super", "(", "PageTitle", ",", "self", ")", ".", "build", "(", ")", "self", ".", "content", "=", "text" ]
22
0.014599
def object_deserializer(obj): """Helper to deserialize a raw result dict into a proper dict. :param obj: The dict. """ for key, val in obj.items(): if isinstance(val, six.string_types) and DATETIME_REGEX.search(val): try: obj[key] = dates.localize_datetime(parser.par...
[ "def", "object_deserializer", "(", "obj", ")", ":", "for", "key", ",", "val", "in", "obj", ".", "items", "(", ")", ":", "if", "isinstance", "(", "val", ",", "six", ".", "string_types", ")", "and", "DATETIME_REGEX", ".", "search", "(", "val", ")", ":"...
32.833333
0.002469
def _default(cls, opts): """Setup default logger""" logging.basicConfig(level=logging.INFO, format=cls._log_format) return True
[ "def", "_default", "(", "cls", ",", "opts", ")", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "cls", ".", "_log_format", ")", "return", "True" ]
37
0.013245
def check_domain(self, service_id, version_number, name): """Checks the status of a domain's DNS record. Returns an array of 3 items. The first is the details for the domain. The second is the current CNAME of the domain. The third is a boolean indicating whether or not it has been properly setup to use Fastly.""" ...
[ "def", "check_domain", "(", "self", ",", "service_id", ",", "version_number", ",", "name", ")", ":", "content", "=", "self", ".", "_fetch", "(", "\"/service/%s/version/%d/domain/%s/check\"", "%", "(", "service_id", ",", "version_number", ",", "name", ")", ")", ...
114.75
0.015152
def _add_advices(target, advices): """Add advices on input target. :param Callable target: target from where add advices. :param advices: advices to weave on input target. :type advices: routine or list. :param bool ordered: ensure advices to add will be done in input order """ interceptio...
[ "def", "_add_advices", "(", "target", ",", "advices", ")", ":", "interception_fn", "=", "_get_function", "(", "target", ")", "target_advices", "=", "getattr", "(", "interception_fn", ",", "_ADVICES", ",", "[", "]", ")", "target_advices", "+=", "advices", "seta...
32.066667
0.00202
def player_stats(game_id): """Return dictionary of individual stats of a game with matching id. The additional pitching/batting is mostly the same stats, except it contains some useful stats such as groundouts/flyouts per pitcher (go/ao). MLB decided to have two box score files, thus we return...
[ "def", "player_stats", "(", "game_id", ")", ":", "# get data from data module", "box_score", "=", "mlbgame", ".", "data", ".", "get_box_score", "(", "game_id", ")", "box_score_tree", "=", "etree", ".", "parse", "(", "box_score", ")", ".", "getroot", "(", ")", ...
42.911111
0.000506
def _scatter_list(self, data, owner): """Distribute a list from one rank to other ranks in a cyclic manner Parameters ---------- data: list of pickle-able data owner: rank that owns the data Returns ------- A list containing the data in a cyclic layou...
[ "def", "_scatter_list", "(", "self", ",", "data", ",", "owner", ")", ":", "rank", "=", "self", ".", "comm", ".", "rank", "size", "=", "self", ".", "comm", ".", "size", "subject_submatrices", "=", "[", "]", "nblocks", "=", "self", ".", "comm", ".", ...
27.952381
0.001646
def _update_rto(self, R): """ Update RTO given a new roundtrip measurement R. """ if self._srtt is None: self._rttvar = R / 2 self._srtt = R else: self._rttvar = (1 - SCTP_RTO_BETA) * self._rttvar + SCTP_RTO_BETA * abs(self._srtt - R) ...
[ "def", "_update_rto", "(", "self", ",", "R", ")", ":", "if", "self", ".", "_srtt", "is", "None", ":", "self", ".", "_rttvar", "=", "R", "/", "2", "self", ".", "_srtt", "=", "R", "else", ":", "self", ".", "_rttvar", "=", "(", "1", "-", "SCTP_RTO...
42.545455
0.008368
def issuperset(self, other): """Is I{self} a superset of I{other}? @rtype: bool """ if not isinstance(other, Set): raise ValueError('other must be a Set instance') for item in other.items: if not item in self.items: return False r...
[ "def", "issuperset", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "Set", ")", ":", "raise", "ValueError", "(", "'other must be a Set instance'", ")", "for", "item", "in", "other", ".", "items", ":", "if", "not", "ite...
26.583333
0.009091
def _get_cache_path(source_file): """Return the path where the cache should be written/located. :param onto_name: name of the ontology or the full path :return: string, abs path to the cache file """ local_name = os.path.basename(source_file) cache_name = local_name + ".db" cache_dir = os.p...
[ "def", "_get_cache_path", "(", "source_file", ")", ":", "local_name", "=", "os", ".", "path", ".", "basename", "(", "source_file", ")", "cache_name", "=", "local_name", "+", "\".db\"", "cache_dir", "=", "os", ".", "path", ".", "join", "(", "current_app", "...
35
0.001988
def Schedule(self, tasks, mutation_pool, timestamp=None): """Schedule a set of Task() instances.""" non_fleetspeak_tasks = [] for queue, queued_tasks in iteritems( collection.Group(tasks, lambda x: x.queue)): if not queue: continue client_id = _GetClientIdFromQueue(queue) ...
[ "def", "Schedule", "(", "self", ",", "tasks", ",", "mutation_pool", ",", "timestamp", "=", "None", ")", ":", "non_fleetspeak_tasks", "=", "[", "]", "for", "queue", ",", "queued_tasks", "in", "iteritems", "(", "collection", ".", "Group", "(", "tasks", ",", ...
38.111111
0.01138
def transformer_ae_base_noatt(): """Set of hyperparameters.""" hparams = transformer_ae_base() hparams.reshape_method = "slice" hparams.bottleneck_kind = "dvq" hparams.hidden_size = 512 hparams.num_blocks = 1 hparams.num_decode_blocks = 1 hparams.z_size = 12 hparams.do_attend_decompress = False retu...
[ "def", "transformer_ae_base_noatt", "(", ")", ":", "hparams", "=", "transformer_ae_base", "(", ")", "hparams", ".", "reshape_method", "=", "\"slice\"", "hparams", ".", "bottleneck_kind", "=", "\"dvq\"", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", ...
29.090909
0.033333
def process(event_name, data): """Iterates over the event handler registry and execute each found handler. It takes the event name and its its `data`, passing the return of `ejson.loads(data)` to the found handlers. """ deserialized = loads(data) event_cls = find_event(event_name) event...
[ "def", "process", "(", "event_name", ",", "data", ")", ":", "deserialized", "=", "loads", "(", "data", ")", "event_cls", "=", "find_event", "(", "event_name", ")", "event", "=", "event_cls", "(", "event_name", ",", "deserialized", ")", "try", ":", "event",...
34.6875
0.000876
def _splice(value, n): """Splice `value` at its center, retaining a total of `n` characters. Parameters ---------- value : str n : int The total length of the returned ends will not be greater than this value. Characters will be dropped from the center to reach this limit. Ret...
[ "def", "_splice", "(", "value", ",", "n", ")", ":", "if", "n", "<=", "0", ":", "raise", "ValueError", "(", "\"n must be positive\"", ")", "value_len", "=", "len", "(", "value", ")", "center", "=", "value_len", "//", "2", "left", ",", "right", "=", "v...
25.571429
0.001346
def _get_drive_resource(self, drive_name): """Gets the DiskDrive resource if exists. :param drive_name: can be either "PhysicalDrives" or "LogicalDrives". :returns the list of drives. :raises: IloCommandNotSupportedError if the given drive resource doesn't exist...
[ "def", "_get_drive_resource", "(", "self", ",", "drive_name", ")", ":", "disk_details_list", "=", "[", "]", "array_uri_links", "=", "self", ".", "_create_list_of_array_controllers", "(", ")", "for", "array_link", "in", "array_uri_links", ":", "_", ",", "_", ",",...
45.153846
0.001112
def create_unique_autosave_filename(self, filename, autosave_dir): """ Create unique autosave file name for specified file name. Args: filename (str): original file name autosave_dir (str): directory in which autosave files are stored """ basename = osp.b...
[ "def", "create_unique_autosave_filename", "(", "self", ",", "filename", ",", "autosave_dir", ")", ":", "basename", "=", "osp", ".", "basename", "(", "filename", ")", "autosave_filename", "=", "osp", ".", "join", "(", "autosave_dir", ",", "basename", ")", "if",...
44
0.002472
def make_vector_plot(coordfile, columns=[1, 2, 3, 4], data=None, figure_id=None, title=None, axes=None, every=1, labelsize=8, ylimit=None, limit=None, xlower=None, ylower=None, output=None, headl=4, headw=3, xsh=0.0, ysh=0.0, fit=None, ...
[ "def", "make_vector_plot", "(", "coordfile", ",", "columns", "=", "[", "1", ",", "2", ",", "3", ",", "4", "]", ",", "data", "=", "None", ",", "figure_id", "=", "None", ",", "title", "=", "None", ",", "axes", "=", "None", ",", "every", "=", "1", ...
38.063291
0.000108
def _get_values(values, skipna, fill_value=None, fill_value_typ=None, isfinite=False, copy=True, mask=None): """ utility to get the values view, mask, dtype if necessary copy and mask using the specified fill_value copy = True will force the copy """ if is_datetime64tz_dtype(values)...
[ "def", "_get_values", "(", "values", ",", "skipna", ",", "fill_value", "=", "None", ",", "fill_value_typ", "=", "None", ",", "isfinite", "=", "False", ",", "copy", "=", "True", ",", "mask", "=", "None", ")", ":", "if", "is_datetime64tz_dtype", "(", "valu...
32.303571
0.000536
def parse_dot_data(s): """Parse DOT description in (unicode) string `s`. @return: Graphs that result from parsing. @rtype: `list` of `pydot.Dot` """ global top_graphs top_graphs = list() try: graphparser = graph_definition() graphparser.parseWithTabs() tokens = graph...
[ "def", "parse_dot_data", "(", "s", ")", ":", "global", "top_graphs", "top_graphs", "=", "list", "(", ")", "try", ":", "graphparser", "=", "graph_definition", "(", ")", "graphparser", ".", "parseWithTabs", "(", ")", "tokens", "=", "graphparser", ".", "parseSt...
26.263158
0.001934
def decode_file_iter(file_obj, codec_options=DEFAULT_CODEC_OPTIONS): """Decode bson data from a file to multiple documents as a generator. Works similarly to the decode_all function, but reads from the file object in chunks and parses bson in chunks, yielding one document at a time. :Parameters: ...
[ "def", "decode_file_iter", "(", "file_obj", ",", "codec_options", "=", "DEFAULT_CODEC_OPTIONS", ")", ":", "while", "True", ":", "# Read size of next object.", "size_data", "=", "file_obj", ".", "read", "(", "4", ")", "if", "len", "(", "size_data", ")", "==", "...
38.111111
0.000948
def create(self, path, value=b"", acl=None, ephemeral=False, sequence=False): """ wrapper that handles encoding (yay Py3k) """ super(XTransactionRequest, self).create(path, to_bytes(value), acl, ephemeral, sequence)
[ "def", "create", "(", "self", ",", "path", ",", "value", "=", "b\"\"", ",", "acl", "=", "None", ",", "ephemeral", "=", "False", ",", "sequence", "=", "False", ")", ":", "super", "(", "XTransactionRequest", ",", "self", ")", ".", "create", "(", "path"...
60.75
0.01626
def get_nearest_year_for_day(day): """ Returns the nearest year to now inferred from a Julian date. """ now = time.gmtime() result = now.tm_year # if the day is far greater than today, it must be from last year if day - now.tm_yday > 365 // 2: result -= 1 # if the day is far less than today, it must be for ne...
[ "def", "get_nearest_year_for_day", "(", "day", ")", ":", "now", "=", "time", ".", "gmtime", "(", ")", "result", "=", "now", ".", "tm_year", "# if the day is far greater than today, it must be from last year", "if", "day", "-", "now", ".", "tm_yday", ">", "365", ...
29.153846
0.033248
def parse_spec(self, spec): """Parse the given spec into a `specs.Spec` object. :param spec: a single spec string. :return: a single specs.Specs object. :raises: CmdLineSpecParser.BadSpecError if the address selector could not be parsed. """ if spec.endswith('::'): spec_path = spec[:-len...
[ "def", "parse_spec", "(", "self", ",", "spec", ")", ":", "if", "spec", ".", "endswith", "(", "'::'", ")", ":", "spec_path", "=", "spec", "[", ":", "-", "len", "(", "'::'", ")", "]", "return", "DescendantAddresses", "(", "self", ".", "_normalize_spec_pa...
39.368421
0.015666
def mtie_phase_fast(phase, rate=1.0, data_type="phase", taus=None): """ fast binary decomposition algorithm for MTIE See: STEFANO BREGNI "Fast Algorithms for TVAR and MTIE Computation in Characterization of Network Synchronization Performance" """ rate = float(rate) phase = np.asarray(p...
[ "def", "mtie_phase_fast", "(", "phase", ",", "rate", "=", "1.0", ",", "data_type", "=", "\"phase\"", ",", "taus", "=", "None", ")", ":", "rate", "=", "float", "(", "rate", ")", "phase", "=", "np", ".", "asarray", "(", "phase", ")", "k_max", "=", "i...
36.446429
0.01145
def get_text(self): """ Returns the current text. """ if self._multiline: return str(self._widget.toPlainText()) else: return str(self._widget.text())
[ "def", "get_text", "(", "self", ")", ":", "if", "self", ".", "_multiline", ":", "return", "str", "(", "self", ".", "_widget", ".", "toPlainText", "(", ")", ")", "else", ":", "return", "str", "(", "self", ".", "_widget", ".", "text", "(", ")", ")" ]
33.166667
0.02451
def is30(msg): """Check if a message is likely to be BDS code 2,0 Args: msg (String): 28 bytes hexadecimal message string Returns: bool: True or False """ if allzeros(msg): return False d = hex2bin(data(msg)) if d[0:8] != '00110000': return False # t...
[ "def", "is30", "(", "msg", ")", ":", "if", "allzeros", "(", "msg", ")", ":", "return", "False", "d", "=", "hex2bin", "(", "data", "(", "msg", ")", ")", "if", "d", "[", "0", ":", "8", "]", "!=", "'00110000'", ":", "return", "False", "# threat type...
17.740741
0.00198
def _polygon_from_coords(coords, fix_geom=False, swap=True, dims=2): """ Return Shapely Polygon from coordinates. - coords: list of alterating latitude / longitude coordinates - fix_geom: automatically fix geometry """ assert len(coords) % dims == 0 number_of_points = len(coords)/dims c...
[ "def", "_polygon_from_coords", "(", "coords", ",", "fix_geom", "=", "False", ",", "swap", "=", "True", ",", "dims", "=", "2", ")", ":", "assert", "len", "(", "coords", ")", "%", "dims", "==", "0", "number_of_points", "=", "len", "(", "coords", ")", "...
32.916667
0.00123
def opensearch(self, query, results=10, redirect=True): """ Execute a MediaWiki opensearch request, similar to search box suggestions and conforming to the OpenSearch specification Args: query (str): Title to search for results (int): Number of pages with...
[ "def", "opensearch", "(", "self", ",", "query", ",", "results", "=", "10", ",", "redirect", "=", "True", ")", ":", "self", ".", "_check_query", "(", "query", ",", "\"Query must be specified\"", ")", "query_params", "=", "{", "\"action\"", ":", "\"opensearch\...
35.939394
0.001642
def _doClobber(self): """Remove the work directory""" rc = yield self.runRmdir(self.workdir, timeout=self.timeout) if rc != RC_SUCCESS: raise RuntimeError("Failed to delete directory") return rc
[ "def", "_doClobber", "(", "self", ")", ":", "rc", "=", "yield", "self", ".", "runRmdir", "(", "self", ".", "workdir", ",", "timeout", "=", "self", ".", "timeout", ")", "if", "rc", "!=", "RC_SUCCESS", ":", "raise", "RuntimeError", "(", "\"Failed to delete...
38.833333
0.008403
def read_series_matrix(path, encoding): """Read the series matrix.""" assert isinstance(path, str) accessions = None titles = None celfile_urls = None with misc.smart_open_read(path, mode='rb', try_gzip=True) as fh: reader = csv.reader(fh, dialect='excel-tab', encoding=encoding) ...
[ "def", "read_series_matrix", "(", "path", ",", "encoding", ")", ":", "assert", "isinstance", "(", "path", ",", "str", ")", "accessions", "=", "None", "titles", "=", "None", "celfile_urls", "=", "None", "with", "misc", ".", "smart_open_read", "(", "path", "...
37.681818
0.002353
def k_array_rank_jit(a): """ Numba jit version of `k_array_rank`. Notes ----- An incorrect value will be returned without warning or error if overflow occurs during the computation. It is the user's responsibility to ensure that the rank of the input array fits within the range of possi...
[ "def", "k_array_rank_jit", "(", "a", ")", ":", "k", "=", "len", "(", "a", ")", "idx", "=", "a", "[", "0", "]", "for", "i", "in", "range", "(", "1", ",", "k", ")", ":", "idx", "+=", "comb_jit", "(", "a", "[", "i", "]", ",", "i", "+", "1", ...
29.368421
0.001736
def websocket(self, uri, *args, **kwargs): """Create a websocket route from a decorated function :param uri: endpoint at which the socket endpoint will be accessible. :type uri: str :param args: captures all of the positional arguments passed in :type args: tuple(Any) :pa...
[ "def", "websocket", "(", "self", ",", "uri", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'host'", ",", "None", ")", "kwargs", ".", "setdefault", "(", "'strict_slashes'", ",", "None", ")", "kwargs", ".", "se...
41
0.002073
def matrix(self): """The current calibration matrix for this device. Returns: (bool, (float, float, float, float, float, float)): :obj:`False` if no calibration is set and the returned matrix is the identity matrix, :obj:`True` otherwise. :obj:`tuple` representing the first two rows of a 3x3 matrix ...
[ "def", "matrix", "(", "self", ")", ":", "matrix", "=", "(", "c_float", "*", "6", ")", "(", ")", "rc", "=", "self", ".", "_libinput", ".", "libinput_device_config_calibration_get_matrix", "(", "self", ".", "_handle", ",", "matrix", ")", "return", "rc", ",...
33.066667
0.027451
def _decompress_into_buffer(self, out_buffer): """Decompress available input into an output buffer. Returns True if data in output buffer should be emitted. """ zresult = lib.ZSTD_decompressStream(self._decompressor._dctx, out_buffer, self._in...
[ "def", "_decompress_into_buffer", "(", "self", ",", "out_buffer", ")", ":", "zresult", "=", "lib", ".", "ZSTD_decompressStream", "(", "self", ".", "_decompressor", ".", "_dctx", ",", "out_buffer", ",", "self", ".", "_in_buffer", ")", "if", "self", ".", "_in_...
40.37037
0.001792
def find_signature_end(model_string): """ Find the index of the colon in the function signature. :param model_string: string source code of the model :return: int the index of the colon """ index, brace_depth = 0, 0 while index < len(model_string): ch = model_string[i...
[ "def", "find_signature_end", "(", "model_string", ")", ":", "index", ",", "brace_depth", "=", "0", ",", "0", "while", "index", "<", "len", "(", "model_string", ")", ":", "ch", "=", "model_string", "[", "index", "]", "if", "brace_depth", "==", "0", "and",...
31.304348
0.000673
def bulk_index(cls, documents, id_field='id', es=None, index=None): """Adds or updates a batch of documents. :arg documents: List of Python dicts representing individual documents to be added to the index .. Note:: This must be serializable into JSON. :...
[ "def", "bulk_index", "(", "cls", ",", "documents", ",", "id_field", "=", "'id'", ",", "es", "=", "None", ",", "index", "=", "None", ")", ":", "if", "es", "is", "None", ":", "es", "=", "cls", ".", "get_es", "(", ")", "if", "index", "is", "None", ...
28.536585
0.001653
def _construct_error_handling(self): """ Updates the Flask app with Error Handlers for different Error Codes """ self._app.register_error_handler(500, LambdaErrorResponses.generic_service_exception) self._app.register_error_handler(404, LambdaErrorResponses.generic_path_not_foun...
[ "def", "_construct_error_handling", "(", "self", ")", ":", "self", ".", "_app", ".", "register_error_handler", "(", "500", ",", "LambdaErrorResponses", ".", "generic_service_exception", ")", "self", ".", "_app", ".", "register_error_handler", "(", "404", ",", "Lam...
51.25
0.01199
def RootNode(self): """Return our current root node and appropriate adapter for it""" tree = self.loader.get_root( self.viewType ) adapter = self.loader.get_adapter( self.viewType ) rows = self.loader.get_rows( self.viewType ) adapter.SetPercentage(self.percentageView, a...
[ "def", "RootNode", "(", "self", ")", ":", "tree", "=", "self", ".", "loader", ".", "get_root", "(", "self", ".", "viewType", ")", "adapter", "=", "self", ".", "loader", ".", "get_adapter", "(", "self", ".", "viewType", ")", "rows", "=", "self", ".", ...
41.888889
0.031169
def _ExtractSymbols(desc_proto, package): """Pulls out all the symbols from a descriptor proto. Args: desc_proto: The proto to extract symbols from. package: The package containing the descriptor type. Yields: The fully qualified name found in the descriptor. """ message_name = '.'.join((packag...
[ "def", "_ExtractSymbols", "(", "desc_proto", ",", "package", ")", ":", "message_name", "=", "'.'", ".", "join", "(", "(", "package", ",", "desc_proto", ".", "name", ")", ")", "yield", "message_name", "for", "nested_type", "in", "desc_proto", ".", "nested_typ...
31.222222
0.01209
def blocking_request(self, msg, timeout=None, use_mid=None): """Send a request messsage and wait for its reply. Parameters ---------- msg : Message object The request Message to send. timeout : float in seconds How long to wait for a reply. The default is...
[ "def", "blocking_request", "(", "self", ",", "msg", ",", "timeout", "=", "None", ",", "use_mid", "=", "None", ")", ":", "assert", "(", "get_thread_ident", "(", ")", "!=", "self", ".", "ioloop_thread_id", ")", ",", "(", "'Cannot call blocking_request() in ioloo...
38.931034
0.001296
def bleu_score(predictions, labels, **unused_kwargs): """BLEU score computation between labels and predictions. An approximate BLEU scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4 and use brevity penalty. Also, this does not have be...
[ "def", "bleu_score", "(", "predictions", ",", "labels", ",", "*", "*", "unused_kwargs", ")", ":", "outputs", "=", "tf", ".", "to_int32", "(", "tf", ".", "argmax", "(", "predictions", ",", "axis", "=", "-", "1", ")", ")", "# Convert the outputs and labels t...
36.571429
0.010152
def online_help(param=None): """ Open online document in web browser. :param param: input parameter :type param : int or str :return: None """ try: PARAMS_LINK_KEYS = sorted(PARAMS_LINK.keys()) if param in PARAMS_LINK_KEYS: webbrowser.open_new_tab(DOCUMENT_ADR + ...
[ "def", "online_help", "(", "param", "=", "None", ")", ":", "try", ":", "PARAMS_LINK_KEYS", "=", "sorted", "(", "PARAMS_LINK", ".", "keys", "(", ")", ")", "if", "param", "in", "PARAMS_LINK_KEYS", ":", "webbrowser", ".", "open_new_tab", "(", "DOCUMENT_ADR", ...
36.090909
0.001227
def setSystemVariable(self, remote, name, value): """Set a system variable on CCU / Homegear""" if self._server is not None: return self._server.setSystemVariable(remote, name, value)
[ "def", "setSystemVariable", "(", "self", ",", "remote", ",", "name", ",", "value", ")", ":", "if", "self", ".", "_server", "is", "not", "None", ":", "return", "self", ".", "_server", ".", "setSystemVariable", "(", "remote", ",", "name", ",", "value", "...
52
0.009479
def main(): """ Get arguments and call the execution function""" if len(sys.argv) < 6: print("Usage: %s server_url username password namespace' \ ' classname" % sys.argv[0]) print('Using internal defaults') server_url = SERVER_URL namespace = TEST_NAMESPACE ...
[ "def", "main", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", "<", "6", ":", "print", "(", "\"Usage: %s server_url username password namespace' \\\n ' classname\"", "%", "sys", ".", "argv", "[", "0", "]", ")", "print", "(", "'Using inte...
29.777778
0.00241
def update_event_and_problem_id(self): """Update current_event_id and current_problem_id Those attributes are used for macros (SERVICEPROBLEMID ...) :return: None """ ok_up = self.__class__.ok_up # OK for service, UP for host if (self.state != self.last_state and self.l...
[ "def", "update_event_and_problem_id", "(", "self", ")", ":", "ok_up", "=", "self", ".", "__class__", ".", "ok_up", "# OK for service, UP for host", "if", "(", "self", ".", "state", "!=", "self", ".", "last_state", "and", "self", ".", "last_state", "!=", "'PEND...
51.8
0.001083
def _R2deriv(self,R,z,phi=0.,t=0.): """ NAME: _R2deriv PURPOSE: evaluate the second radial derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPU...
[ "def", "_R2deriv", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "return", "1.", "/", "(", "R", "**", "2.", "+", "(", "self", ".", "_a", "+", "nu", ".", "sqrt", "(", "z", "**", "2.", "+", "self", ...
31.277778
0.012069
def cleaned_selector(html): """ Clean parsel.selector. """ import parsel try: tree = _cleaned_html_tree(html) sel = parsel.Selector(root=tree, type='html') except (lxml.etree.XMLSyntaxError, lxml.etree.ParseError, lxml.etree.ParserError, UnicodeEnc...
[ "def", "cleaned_selector", "(", "html", ")", ":", "import", "parsel", "try", ":", "tree", "=", "_cleaned_html_tree", "(", "html", ")", "sel", "=", "parsel", ".", "Selector", "(", "root", "=", "tree", ",", "type", "=", "'html'", ")", "except", "(", "lxm...
28.285714
0.002445
def log_message(self, fmt, *fmt_args): """ Log to syslog. """ msg = self.my_address_string() + " - - " + fmt % fmt_args my_log_message(args, syslog.LOG_INFO, msg)
[ "def", "log_message", "(", "self", ",", "fmt", ",", "*", "fmt_args", ")", ":", "msg", "=", "self", ".", "my_address_string", "(", ")", "+", "\" - - \"", "+", "fmt", "%", "fmt_args", "my_log_message", "(", "args", ",", "syslog", ".", "LOG_INFO", ",", "m...
45.75
0.010753
def _get_dispatches_for_update(filter_kwargs): """Distributed friendly version using ``select for update``.""" dispatches = Dispatch.objects.prefetch_related('message').filter( **filter_kwargs ).select_for_update( **GET_DISPATCHES_ARGS[1] ).order_by('-message__time_created') try:...
[ "def", "_get_dispatches_for_update", "(", "filter_kwargs", ")", ":", "dispatches", "=", "Dispatch", ".", "objects", ".", "prefetch_related", "(", "'message'", ")", ".", "filter", "(", "*", "*", "filter_kwargs", ")", ".", "select_for_update", "(", "*", "*", "GE...
23.333333
0.001961
def unit_conversion(array, unit_prefix, current_prefix=""): """ Converts an array or value to of a certain unit scale to another unit scale. Accepted units are: E - exa - 1e18 P - peta - 1e15 T - tera - 1e12 G - giga - 1e9 M - mega - 1e6 k - kilo - 1e3 m - milli - 1e-3 ...
[ "def", "unit_conversion", "(", "array", ",", "unit_prefix", ",", "current_prefix", "=", "\"\"", ")", ":", "UnitDict", "=", "{", "'E'", ":", "1e18", ",", "'P'", ":", "1e15", ",", "'T'", ":", "1e12", ",", "'G'", ":", "1e9", ",", "'M'", ":", "1e6", ",...
26.55
0.002421
def making_blockstr(varblock,count,colorline,element,zoomblock,filename,sidebarstring,colorkeyfields): # starting wrapper that comes before html table code ''' if not colorkeyfields == False: start = """\n\tfunction addDataToMap%s(data, map) {\t\tvar skillsSelect = document.getElementById("mapStyle");\n\t\tvar sel...
[ "def", "making_blockstr", "(", "varblock", ",", "count", ",", "colorline", ",", "element", ",", "zoomblock", ",", "filename", ",", "sidebarstring", ",", "colorkeyfields", ")", ":", "# starting wrapper that comes before html table code", "start", "=", "\"\"\"\\n\\tfuncti...
40.58
0.03513
def azel2radec(az_deg: float, el_deg: float, lat_deg: float, lon_deg: float, time: datetime, usevallado: bool = False) -> Tuple[float, float]: """ viewing angle (az, el) to sky coordinates (ra, dec) Parameters ---------- az_deg : float or numpy.ndarray of float ...
[ "def", "azel2radec", "(", "az_deg", ":", "float", ",", "el_deg", ":", "float", ",", "lat_deg", ":", "float", ",", "lon_deg", ":", "float", ",", "time", ":", "datetime", ",", "usevallado", ":", "bool", "=", "False", ")", "->", "Tuple", "[", "float", "...
33.8
0.001438
def next_row(self): """Move to next row from currently selected row.""" row = self.currentIndex().row() rows = self.source_model.rowCount() if row + 1 == rows: row = -1 self.selectRow(row + 1)
[ "def", "next_row", "(", "self", ")", ":", "row", "=", "self", ".", "currentIndex", "(", ")", ".", "row", "(", ")", "rows", "=", "self", ".", "source_model", ".", "rowCount", "(", ")", "if", "row", "+", "1", "==", "rows", ":", "row", "=", "-", "...
34
0.008197
def create(self, prog=None, format=None): """ Creates and returns a representation of the graph using the Graphviz layout program given by 'prog', according to the given format. Writes the graph to a temporary dot file and processes it with the program given by '...
[ "def", "create", "(", "self", ",", "prog", "=", "None", ",", "format", "=", "None", ")", ":", "prog", "=", "self", ".", "program", "if", "prog", "is", "None", "else", "prog", "format", "=", "self", ".", "format", "if", "format", "is", "None", "else...
32.493333
0.00916
def plot_boundaries(all_boundaries, est_file, algo_ids=None, title=None, output_file=None): """Plots all the boundaries. Parameters ---------- all_boundaries: list A list of np.arrays containing the times of the boundaries, one array for each algorithm. est_file:...
[ "def", "plot_boundaries", "(", "all_boundaries", ",", "est_file", ",", "algo_ids", "=", "None", ",", "title", "=", "None", ",", "output_file", "=", "None", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "N", "=", "len", "(", "all_boundaries"...
34.1
0.000713
def deep_update(dict1, dict2): """Perform a deep merge of `dict2` into `dict1`. Note that `dict2` and any nested dicts are unchanged. Supports `ModifyList` instances. """ def flatten(v): if isinstance(v, ModifyList): return v.apply([]) elif isinstance(v, dict): ...
[ "def", "deep_update", "(", "dict1", ",", "dict2", ")", ":", "def", "flatten", "(", "v", ")", ":", "if", "isinstance", "(", "v", ",", "ModifyList", ")", ":", "return", "v", ".", "apply", "(", "[", "]", ")", "elif", "isinstance", "(", "v", ",", "di...
26.277778
0.001019
def get_execution_engine(self, name): """Return an execution engine instance.""" try: return self.execution_engines[name] except KeyError: raise InvalidEngineError("Unsupported execution engine: {}".format(name))
[ "def", "get_execution_engine", "(", "self", ",", "name", ")", ":", "try", ":", "return", "self", ".", "execution_engines", "[", "name", "]", "except", "KeyError", ":", "raise", "InvalidEngineError", "(", "\"Unsupported execution engine: {}\"", ".", "format", "(", ...
42.5
0.011538
def progress(request): """ Check status of task. """ if 'delete' in request.GET: models.MachineCache.objects.all().delete() models.InstituteCache.objects.all().delete() models.PersonCache.objects.all().delete() models.ProjectCache.objects.all().delete() return render( ...
[ "def", "progress", "(", "request", ")", ":", "if", "'delete'", "in", "request", ".", "GET", ":", "models", ".", "MachineCache", ".", "objects", ".", "all", "(", ")", ".", "delete", "(", ")", "models", ".", "InstituteCache", ".", "objects", ".", "all", ...
34.071429
0.001019
def extend(self, elem_seq): """Extends by appending the given sequence of elements of the same type as this one, copying each individual message. """ message_class = self._message_descriptor._concrete_class listener = self._message_listener values = self._values for message in elem_seq: ...
[ "def", "extend", "(", "self", ",", "elem_seq", ")", ":", "message_class", "=", "self", ".", "_message_descriptor", ".", "_concrete_class", "listener", "=", "self", ".", "_message_listener", "values", "=", "self", ".", "_values", "for", "message", "in", "elem_s...
36.461538
0.010288
def attack_single_step(self, x, eta, g_feat): """ TensorFlow implementation of the Fast Feature Gradient. This is a single step attack similar to Fast Gradient Method that attacks an internal representation. :param x: the input placeholder :param eta: A tensor the same shape as x that holds the...
[ "def", "attack_single_step", "(", "self", ",", "x", ",", "eta", ",", "g_feat", ")", ":", "adv_x", "=", "x", "+", "eta", "a_feat", "=", "self", ".", "model", ".", "fprop", "(", "adv_x", ")", "[", "self", ".", "layer", "]", "# feat.shape = (batch, c) or ...
31.571429
0.001463
def _block_tuple(iterator, dtypes, bsize=-1): """Pack rdd of tuples as tuples of arrays or scipy.sparse matrices.""" i = 0 blocked_tuple = None for tuple_i in iterator: if blocked_tuple is None: blocked_tuple = tuple([] for _ in range(len(tuple_i))) if (bsize > 0) and (i >= ...
[ "def", "_block_tuple", "(", "iterator", ",", "dtypes", ",", "bsize", "=", "-", "1", ")", ":", "i", "=", "0", "blocked_tuple", "=", "None", "for", "tuple_i", "in", "iterator", ":", "if", "blocked_tuple", "is", "None", ":", "blocked_tuple", "=", "tuple", ...
36.6
0.001332
def i8(self, name, value=None, align=None): """Add an 1 byte integer field to template. This is an convenience method that simply calls `Int` keyword with predefined length.""" self.int(1, name, value, align)
[ "def", "i8", "(", "self", ",", "name", ",", "value", "=", "None", ",", "align", "=", "None", ")", ":", "self", ".", "int", "(", "1", ",", "name", ",", "value", ",", "align", ")" ]
45.8
0.012876
def __cleanup(self): """ Wait at most twice as long as the given repetition interval for the _wrapper_function to terminate. If after that time the _wrapper_function has not terminated, send SIGTERM to and the process. Wait at most five times as long as ...
[ "def", "__cleanup", "(", "self", ")", ":", "# set run to False and wait some time -> see what happens ", "self", ".", "_run", ".", "value", "=", "False", "if", "check_process_termination", "(", "proc", "=", "self", ".", "_proc", ",", "timeout", "=", "2", ...
42.393939
0.013277
def K2findCampaigns_byname_main(args=None): """Exposes K2findCampaigns to the command line.""" parser = argparse.ArgumentParser( description="Check if a target is " "(or was) observable by any past or future " "observing campaig...
[ "def", "K2findCampaigns_byname_main", "(", "args", "=", "None", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Check if a target is \"", "\"(or was) observable by any past or future \"", "\"observing campaign of NASA's K2 mission.\"", ")...
47.297297
0.00112
def is_calculated_aes(ae): """ Return a True if of the aesthetics that are calculated Parameters ---------- ae : object Aesthetic mapping >>> is_calculated_aes('density') False >>> is_calculated_aes(4) False >>> is_calculated_aes('..density..') True >>> is_ca...
[ "def", "is_calculated_aes", "(", "ae", ")", ":", "if", "not", "isinstance", "(", "ae", ",", "str", ")", ":", "return", "False", "for", "pattern", "in", "(", "STAT_RE", ",", "DOTS_RE", ")", ":", "if", "pattern", ".", "search", "(", "ae", ")", ":", "...
17.485714
0.001548
def image_to_pdf_or_hocr(image, lang=None, config='', nice=0, extension='pdf'): ''' Returns the result of a Tesseract OCR run on the provided image to pdf/hocr ''' if extension not in {'pdf', 'hocr'}: raise ValueErr...
[ "def", "image_to_pdf_or_hocr", "(", "image", ",", "lang", "=", "None", ",", "config", "=", "''", ",", "nice", "=", "0", ",", "extension", "=", "'pdf'", ")", ":", "if", "extension", "not", "in", "{", "'pdf'", ",", "'hocr'", "}", ":", "raise", "ValueEr...
32.142857
0.010799
def gate_data(data, gate_params): """Apply a set of gating windows to a time series. Each gating window is defined by a central time, a given duration (centered on the given time) to zero out, and a given duration of smooth tapering on each side of the window. The window function used for tapering ...
[ "def", "gate_data", "(", "data", ",", "gate_params", ")", ":", "def", "inverted_tukey", "(", "M", ",", "n_pad", ")", ":", "midlen", "=", "M", "-", "2", "*", "n_pad", "if", "midlen", "<", "0", ":", "raise", "ValueError", "(", "\"No zeros left after applyi...
40.367347
0.001974
def clear_all(tgt=None, tgt_type='glob'): ''' .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Clear the cached pillar, grains, and mine data of the targeted minions CLI Example: .. code-block:: bash...
[ "def", "clear_all", "(", "tgt", "=", "None", ",", "tgt_type", "=", "'glob'", ")", ":", "return", "_clear_cache", "(", "tgt", ",", "tgt_type", ",", "clear_pillar_flag", "=", "True", ",", "clear_grains_flag", "=", "True", ",", "clear_mine_flag", "=", "True", ...
28.894737
0.001764
def takewhile_peek(predicate, iterable): """ Like takewhile, but takes a peekable iterable and doesn't consume the non-matching item. >>> items = Peekable(range(10)) >>> is_small = lambda n: n < 4 >>> small_items = takewhile_peek(is_small, items) >>> list(small_items) [0, 1, 2, 3] >>> list(items) [4, 5, 6...
[ "def", "takewhile_peek", "(", "predicate", ",", "iterable", ")", ":", "while", "True", ":", "try", ":", "if", "not", "predicate", "(", "iterable", ".", "peek", "(", ")", ")", ":", "break", "yield", "next", "(", "iterable", ")", "except", "StopIteration",...
18.292683
0.043038
def checkbox_uncheck(self, force_check=False): """ Wrapper to uncheck a checkbox """ if self.get_attribute('checked'): self.click(force_click=force_check)
[ "def", "checkbox_uncheck", "(", "self", ",", "force_check", "=", "False", ")", ":", "if", "self", ".", "get_attribute", "(", "'checked'", ")", ":", "self", ".", "click", "(", "force_click", "=", "force_check", ")" ]
32.166667
0.010101
def _get_error_message(self, model_class, method_name, action_method_name): """ Get assertion error message depending if there are actions permissions methods defined. """ if action_method_name: return "'{}' does not have '{}' or '{}' defined.".format(model_class, method_name...
[ "def", "_get_error_message", "(", "self", ",", "model_class", ",", "method_name", ",", "action_method_name", ")", ":", "if", "action_method_name", ":", "return", "\"'{}' does not have '{}' or '{}' defined.\"", ".", "format", "(", "model_class", ",", "method_name", ",", ...
54.375
0.011312
def attention_lm_moe_translation(): """Version to use for seq2seq.""" hparams = attention_lm_moe_base() hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.learning_rate = 0.4 hparams.prepend_mode = "prepend_inputs_masked_attention" hparams.max_length = 512 hparams....
[ "def", "attention_lm_moe_translation", "(", ")", ":", "hparams", "=", "attention_lm_moe_base", "(", ")", "hparams", ".", "layer_preprocess_sequence", "=", "\"n\"", "hparams", ".", "layer_postprocess_sequence", "=", "\"da\"", "hparams", ".", "learning_rate", "=", "0.4"...
36.642857
0.026616
def MakeProbs(self): """Transforms from odds to probabilities.""" for hypo, odds in self.Items(): self.Set(hypo, Probability(odds))
[ "def", "MakeProbs", "(", "self", ")", ":", "for", "hypo", ",", "odds", "in", "self", ".", "Items", "(", ")", ":", "self", ".", "Set", "(", "hypo", ",", "Probability", "(", "odds", ")", ")" ]
39
0.012579
def get_project_root(): """Get the project root folder as a string.""" cfg = get_project_configuration() # At this point it can be sure that the configuration file exists # Now make sure the project structure exists for dirname in ["raw-datasets", "preprocessed", ...
[ "def", "get_project_root", "(", ")", ":", "cfg", "=", "get_project_configuration", "(", ")", "# At this point it can be sure that the configuration file exists", "# Now make sure the project structure exists", "for", "dirname", "in", "[", "\"raw-datasets\"", ",", "\"preprocessed\...
42.75
0.000572
def p_attr(p): """ attr : OVER expr | INVERSE expr | INK expr | PAPER expr | BRIGHT expr | FLASH expr """ # ATTR_LIST are used by drawing commands: PLOT, DRAW, CIRCLE # BOLD and ITALIC are ignored by them, so we put them out of the # a...
[ "def", "p_attr", "(", "p", ")", ":", "# ATTR_LIST are used by drawing commands: PLOT, DRAW, CIRCLE", "# BOLD and ITALIC are ignored by them, so we put them out of the", "# attr definition so something like DRAW BOLD 1; .... will raise", "# a syntax error", "p", "[", "0", "]", "=", "mak...
35.714286
0.001949
def main(): """ NAME qqplot.py DESCRIPTION makes qq plot of input data against a Normal distribution. INPUT FORMAT takes real numbers in single column SYNTAX qqplot.py [-h][-i][-f FILE] OPTIONS -f FILE, specify file on command line -f...
[ "def", "main", "(", ")", ":", "fmt", ",", "plot", "=", "'svg'", ",", "0", "if", "'-h'", "in", "sys", ".", "argv", ":", "# check if help is needed", "print", "(", "main", ".", "__doc__", ")", "sys", ".", "exit", "(", ")", "# graceful quit", "if", "'-s...
28.8125
0.027268
def from_map(map): """ Creates a new PagingParams and sets it parameters from the specified map :param map: a AnyValueMap or StringValueMap to initialize this PagingParams :return: a newly created PagingParams. """ skip = map.get_as_nullable_integer("skip") take...
[ "def", "from_map", "(", "map", ")", ":", "skip", "=", "map", ".", "get_as_nullable_integer", "(", "\"skip\"", ")", "take", "=", "map", ".", "get_as_nullable_integer", "(", "\"take\"", ")", "total", "=", "map", ".", "get_as_nullable_boolean", "(", "\"total\"", ...
37.25
0.008734
def server_deployment_mode(command, parser, cluster, cl_args): ''' check the server deployment mode for the given cluster if it is valid return the valid set of args :param cluster: :param cl_args: :return: ''' # Read the cluster definition, if not found client_confs = cdefs.read_server_mode_cluster_d...
[ "def", "server_deployment_mode", "(", "command", ",", "parser", ",", "cluster", ",", "cl_args", ")", ":", "# Read the cluster definition, if not found", "client_confs", "=", "cdefs", ".", "read_server_mode_cluster_definition", "(", "cluster", ",", "cl_args", ")", "if", ...
34.5625
0.01524
def freq_resp(self, mode= 'dB', fs = 8000, ylim = [-100,2]): """ Frequency response plot """ iir_d.freqz_resp_cas_list([self.sos],mode,fs=fs) pylab.grid() pylab.ylim(ylim)
[ "def", "freq_resp", "(", "self", ",", "mode", "=", "'dB'", ",", "fs", "=", "8000", ",", "ylim", "=", "[", "-", "100", ",", "2", "]", ")", ":", "iir_d", ".", "freqz_resp_cas_list", "(", "[", "self", ".", "sos", "]", ",", "mode", ",", "fs", "=", ...
30.428571
0.045662
def any(self, cond): """ Check if a condition is met by any document in a list, where a condition can also be a sequence (e.g. list). >>> Query().f1.any(Query().f2 == 1) Matches:: {'f1': [{'f2': 1}, {'f2': 0}]} >>> Query().f1.any([1, 2, 3]) Matche...
[ "def", "any", "(", "self", ",", "cond", ")", ":", "if", "callable", "(", "cond", ")", ":", "def", "_cmp", "(", "value", ")", ":", "return", "is_sequence", "(", "value", ")", "and", "any", "(", "cond", "(", "e", ")", "for", "e", "in", "value", "...
27.823529
0.002043
def requires(self): """ Index all pages. """ for url in NEWSPAPERS: yield IndexPage(url=url, date=self.date)
[ "def", "requires", "(", "self", ")", ":", "for", "url", "in", "NEWSPAPERS", ":", "yield", "IndexPage", "(", "url", "=", "url", ",", "date", "=", "self", ".", "date", ")" ]
33.25
0.014706
def get_domain_smarthost(self, domainid, serverid): """Get a domain smarthost""" return self.api_call( ENDPOINTS['domainsmarthosts']['get'], dict(domainid=domainid, serverid=serverid))
[ "def", "get_domain_smarthost", "(", "self", ",", "domainid", ",", "serverid", ")", ":", "return", "self", ".", "api_call", "(", "ENDPOINTS", "[", "'domainsmarthosts'", "]", "[", "'get'", "]", ",", "dict", "(", "domainid", "=", "domainid", ",", "serverid", ...
44
0.008929
def lang_items(self, lang=None): """Yield pairs of (id, string) for the given language.""" if lang is None: lang = self.language yield from self.cache.setdefault(lang, {}).items()
[ "def", "lang_items", "(", "self", ",", "lang", "=", "None", ")", ":", "if", "lang", "is", "None", ":", "lang", "=", "self", ".", "language", "yield", "from", "self", ".", "cache", ".", "setdefault", "(", "lang", ",", "{", "}", ")", ".", "items", ...
42.2
0.009302
def until_cmd(listcmd, end_expects=None, save2logfile=None, coding = encoding): ''' 执行系统命令,并等待执行完 @param listcmd: 执行的命令,列表格式 @param end_expects: 命令执行结束,在输出的最后一行,正则搜素期望值,并设置 结果标志 @param save2logfile: 设置执行过程,保存的日志 @param coding: 设置输出编码 ''' ...
[ "def", "until_cmd", "(", "listcmd", ",", "end_expects", "=", "None", ",", "save2logfile", "=", "None", ",", "coding", "=", "encoding", ")", ":", "if", "end_expects", "and", "not", "isinstance", "(", "end_expects", ",", "p_compat", ".", "str", ")", ":", "...
38.176471
0.016529
def imagej_description_metadata(description): """Return metatata from ImageJ image description as dict. Raise ValueError if not a valid ImageJ description. >>> description = 'ImageJ=1.11a\\nimages=510\\nhyperstack=true\\n' >>> imagej_description_metadata(description) # doctest: +SKIP {'ImageJ': '...
[ "def", "imagej_description_metadata", "(", "description", ")", ":", "def", "_bool", "(", "val", ")", ":", "return", "{", "'true'", ":", "True", ",", "'false'", ":", "False", "}", "[", "val", ".", "lower", "(", ")", "]", "result", "=", "{", "}", "for"...
29.03125
0.001042
def wantDirectory(self, dirname): """Check if directory is eligible for test discovery""" if dirname in self.exclude_dirs: log.debug("excluded: %s" % dirname) return False else: return None
[ "def", "wantDirectory", "(", "self", ",", "dirname", ")", ":", "if", "dirname", "in", "self", ".", "exclude_dirs", ":", "log", ".", "debug", "(", "\"excluded: %s\"", "%", "dirname", ")", "return", "False", "else", ":", "return", "None" ]
34.714286
0.008032
def scgi_request(url, methodname, *params, **kw): """ Send a XMLRPC request over SCGI to the given URL. @param url: Endpoint URL. @param methodname: XMLRPC method name. @param params: Tuple of simple python objects. @keyword deserialize: Parse XML result? (default is True) @...
[ "def", "scgi_request", "(", "url", ",", "methodname", ",", "*", "params", ",", "*", "*", "kw", ")", ":", "xmlreq", "=", "xmlrpclib", ".", "dumps", "(", "params", ",", "methodname", ")", "xmlresp", "=", "SCGIRequest", "(", "url", ")", ".", "send", "("...
37.318182
0.001188
def install_npm(path=None, build_dir=None, source_dir=None, build_cmd='build', force=False, npm=None): """Return a Command for managing an npm installation. Note: The command is skipped if the `--skip-npm` flag is used. Parameters ---------- path: str, optional The base path of the node pa...
[ "def", "install_npm", "(", "path", "=", "None", ",", "build_dir", "=", "None", ",", "source_dir", "=", "None", ",", "build_cmd", "=", "'build'", ",", "force", "=", "False", ",", "npm", "=", "None", ")", ":", "class", "NPM", "(", "BaseCommand", ")", "...
37.087719
0.001382
def split_from_df(self, col:IntsOrStrs=2): "Split the data from the `col` in the dataframe in `self.inner_df`." valid_idx = np.where(self.inner_df.iloc[:,df_names_to_idx(col, self.inner_df)])[0] return self.split_by_idx(valid_idx)
[ "def", "split_from_df", "(", "self", ",", "col", ":", "IntsOrStrs", "=", "2", ")", ":", "valid_idx", "=", "np", ".", "where", "(", "self", ".", "inner_df", ".", "iloc", "[", ":", ",", "df_names_to_idx", "(", "col", ",", "self", ".", "inner_df", ")", ...
62.75
0.027559
def decrypt(data, _key): """ ACCEPT BYTES -> UTF8 -> JSON -> {"salt":s, "length":l, "data":d} """ # Key and iv have not been generated or provided, bail out if _key is None: Log.error("Expecting a key") _input = get_module("mo_json").json2value(data.decode('utf8'), leaves=False, flexibl...
[ "def", "decrypt", "(", "data", ",", "_key", ")", ":", "# Key and iv have not been generated or provided, bail out", "if", "_key", "is", "None", ":", "Log", ".", "error", "(", "\"Expecting a key\"", ")", "_input", "=", "get_module", "(", "\"mo_json\"", ")", ".", ...
36.076923
0.002077
def _sphinx_build(self, kind): """ Call sphinx to build documentation. Attribute `num_jobs` from the class is used. Parameters ---------- kind : {'html', 'latex'} Examples -------- >>> DocBuilder(num_jobs=4)._sphinx_build('html') """ ...
[ "def", "_sphinx_build", "(", "self", ",", "kind", ")", ":", "if", "kind", "not", "in", "(", "'html'", ",", "'latex'", ")", ":", "raise", "ValueError", "(", "'kind must be html or latex, '", "'not {}'", ".", "format", "(", "kind", ")", ")", "cmd", "=", "[...
31.464286
0.002203
def editText(scr, y, x, w, i=0, attr=curses.A_NORMAL, value='', fillchar=' ', truncchar='-', unprintablechar='.', completer=lambda text,idx: None, history=[], display=True): 'A better curses line editing widget.' ESC='^[' ENTER='^J' TAB='^I' def until_get_wch(): 'Ignores get_wch timeouts' ...
[ "def", "editText", "(", "scr", ",", "y", ",", "x", ",", "w", ",", "i", "=", "0", ",", "attr", "=", "curses", ".", "A_NORMAL", ",", "value", "=", "''", ",", "fillchar", "=", "' '", ",", "truncchar", "=", "'-'", ",", "unprintablechar", "=", "'.'", ...
37.090395
0.008456
def _can_allocate(struct): """ Checks that select structs can be allocated by the underlying operating system, not just advertised by the select module. We don't check select() because we'll be hopeful that most platforms that don't have it available will not advertise it. (ie: GAE) """ try: ...
[ "def", "_can_allocate", "(", "struct", ")", ":", "try", ":", "# select.poll() objects won't fail until used.", "if", "struct", "==", "'poll'", ":", "p", "=", "select", ".", "poll", "(", ")", "p", ".", "poll", "(", "0", ")", "# All others will fail on allocation....
36.647059
0.001565
def main(args=None): """ Run management command handled from command line. """ # Base command line parser. Help is not allowed because command # line is parsed in two stages - in the first stage is found setting # module of the application, in the second stage are found management # command'...
[ "def", "main", "(", "args", "=", "None", ")", ":", "# Base command line parser. Help is not allowed because command", "# line is parsed in two stages - in the first stage is found setting", "# module of the application, in the second stage are found management", "# command's arguments.", "pa...
36
0.000342
def guess_sequence(redeem_script): ''' str -> int If OP_CSV is used, guess an appropriate sequence Otherwise, disable RBF, but leave lock_time on. Fails if there's not a constant before OP_CSV ''' try: script_array = redeem_script.split() loc = script_array.index('OP_CHECKSEQ...
[ "def", "guess_sequence", "(", "redeem_script", ")", ":", "try", ":", "script_array", "=", "redeem_script", ".", "split", "(", ")", "loc", "=", "script_array", ".", "index", "(", "'OP_CHECKSEQUENCEVERIFY'", ")", "return", "int", "(", "script_array", "[", "loc",...
32
0.002336
def _find_phrases( self, sentence, syntax_layer, cutPhrases, cutMaxThreshold ): ''' Detects NP phrases by relying on local dependency relations: 1) Identifies potential heads of NP phrases; 2) Identifies consecutive words that can form an NP phrase: 2.1) pote...
[ "def", "_find_phrases", "(", "self", ",", "sentence", ",", "syntax_layer", ",", "cutPhrases", ",", "cutMaxThreshold", ")", ":", "NPattribPos", "=", "[", "'Y'", ",", "'S'", ",", "'A'", ",", "'C'", ",", "'G'", ",", "'H'", ",", "'N'", ",", "'O'", ",", "...
56.230159
0.010309
def view(self, request, application, label, roles, actions): """ Django view method. """ # Get the appropriate form status = None form = None if application.content_type.model != 'applicant': status = "You are already registered in the system." elif applicati...
[ "def", "view", "(", "self", ",", "request", ",", "application", ",", "label", ",", "roles", ",", "actions", ")", ":", "# Get the appropriate form", "status", "=", "None", "form", "=", "None", "if", "application", ".", "content_type", ".", "model", "!=", "'...
38.142857
0.001043
def save(self, fname, compression='blosc'): """ Save method for the data geometry object The data will be saved as a 'geo' file, which is a dictionary containing the elements of a data geometry object saved in the hd5 format using `deepdish`. Parameters --------...
[ "def", "save", "(", "self", ",", "fname", ",", "compression", "=", "'blosc'", ")", ":", "if", "hasattr", "(", "self", ",", "'dtype'", ")", ":", "if", "'list'", "in", "self", ".", "dtype", ":", "data", "=", "np", ".", "array", "(", "self", ".", "d...
33.3125
0.011543
def _get_label(self): '''Find the label for the output files for this calculation ''' if self._label is None: foundfiles = False for f in self._files: if ".files" in f: foundfiles = True self._label = f.sp...
[ "def", "_get_label", "(", "self", ")", ":", "if", "self", ".", "_label", "is", "None", ":", "foundfiles", "=", "False", "for", "f", "in", "self", ".", "_files", ":", "if", "\".files\"", "in", "f", ":", "foundfiles", "=", "True", "self", ".", "_label"...
41.121951
0.008691