text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def location (self, pos): """Formats the location of the given SeqPos as: filename:line:col: """ result = '' if self.filename: result += self.filename + ':' if pos: result += str(pos) return result
[ "def", "location", "(", "self", ",", "pos", ")", ":", "result", "=", "''", "if", "self", ".", "filename", ":", "result", "+=", "self", ".", "filename", "+", "':'", "if", "pos", ":", "result", "+=", "str", "(", "pos", ")", "return", "result" ]
21.090909
16.909091
def _creation_options_for_cog(creation_options, source_profile, blocksize): """ it uses the profile of the source raster, override anything using the creation_options and guarantees we will have tiled raster and blocksize """ if not(creation_options): creation_options = {} creation_options["blocksize"] = blocksize creation_options["tiled"] = True defaults = {"nodata": None, "compress": "lzw"} for key in ["nodata", "compress"]: if key not in creation_options: creation_options[key] = source_profile.get(key, defaults.get(key)) return creation_options
[ "def", "_creation_options_for_cog", "(", "creation_options", ",", "source_profile", ",", "blocksize", ")", ":", "if", "not", "(", "creation_options", ")", ":", "creation_options", "=", "{", "}", "creation_options", "[", "\"blocksize\"", "]", "=", "blocksize", "creation_options", "[", "\"tiled\"", "]", "=", "True", "defaults", "=", "{", "\"nodata\"", ":", "None", ",", "\"compress\"", ":", "\"lzw\"", "}", "for", "key", "in", "[", "\"nodata\"", ",", "\"compress\"", "]", ":", "if", "key", "not", "in", "creation_options", ":", "creation_options", "[", "key", "]", "=", "source_profile", ".", "get", "(", "key", ",", "defaults", ".", "get", "(", "key", ")", ")", "return", "creation_options" ]
40.533333
15.866667
def create(self, set): """ Creates a new Set. """ target_url = self.client.get_url('SET', 'POST', 'create') r = self.client.request('POST', target_url, json=set._serialize()) return set._deserialize(r.json(), self)
[ "def", "create", "(", "self", ",", "set", ")", ":", "target_url", "=", "self", ".", "client", ".", "get_url", "(", "'SET'", ",", "'POST'", ",", "'create'", ")", "r", "=", "self", ".", "client", ".", "request", "(", "'POST'", ",", "target_url", ",", "json", "=", "set", ".", "_serialize", "(", ")", ")", "return", "set", ".", "_deserialize", "(", "r", ".", "json", "(", ")", ",", "self", ")" ]
36.571429
14
def load(file_or_path): """ Load a previously pickled model, using `m.pickle('path/to/file.pickle)'` :param file_name: path/to/file.pickle """ from pickle import UnpicklingError _python3 = True try: import cPickle as pickle _python3 = False except ImportError: #python3 import pickle try: if _python3: strcl = str p3kw = dict(encoding='latin1') return _unpickle(file_or_path, pickle, strcl, p3kw) else: strcl = basestring p3kw = {} return _unpickle(file_or_path, pickle, strcl, p3kw) except UnpicklingError: # pragma: no coverage import pickle return _unpickle(file_or_path, pickle, strcl, p3kw)
[ "def", "load", "(", "file_or_path", ")", ":", "from", "pickle", "import", "UnpicklingError", "_python3", "=", "True", "try", ":", "import", "cPickle", "as", "pickle", "_python3", "=", "False", "except", "ImportError", ":", "#python3", "import", "pickle", "try", ":", "if", "_python3", ":", "strcl", "=", "str", "p3kw", "=", "dict", "(", "encoding", "=", "'latin1'", ")", "return", "_unpickle", "(", "file_or_path", ",", "pickle", ",", "strcl", ",", "p3kw", ")", "else", ":", "strcl", "=", "basestring", "p3kw", "=", "{", "}", "return", "_unpickle", "(", "file_or_path", ",", "pickle", ",", "strcl", ",", "p3kw", ")", "except", "UnpicklingError", ":", "# pragma: no coverage", "import", "pickle", "return", "_unpickle", "(", "file_or_path", ",", "pickle", ",", "strcl", ",", "p3kw", ")" ]
27.703704
18.222222
def delete(self, filename=''): """Deletes given file or directory. If no filename is passed, current directory is removed. """ self._raise_if_none() fn = path_join(self.path, filename) try: if isfile(fn): remove(fn) else: removedirs(fn) except OSError as why: if why.errno == errno.ENOENT: pass else: raise why
[ "def", "delete", "(", "self", ",", "filename", "=", "''", ")", ":", "self", ".", "_raise_if_none", "(", ")", "fn", "=", "path_join", "(", "self", ".", "path", ",", "filename", ")", "try", ":", "if", "isfile", "(", "fn", ")", ":", "remove", "(", "fn", ")", "else", ":", "removedirs", "(", "fn", ")", "except", "OSError", "as", "why", ":", "if", "why", ".", "errno", "==", "errno", ".", "ENOENT", ":", "pass", "else", ":", "raise", "why" ]
27.235294
13.705882
async def destroy(self, container = None): """ Destroy the created subqueue to change the behavior back to Lock """ if container is None: container = RoutineContainer(self.scheduler) if self.queue is not None: await container.syscall_noreturn(syscall_removequeue(self.scheduler.queue, self.queue)) self.queue = None
[ "async", "def", "destroy", "(", "self", ",", "container", "=", "None", ")", ":", "if", "container", "is", "None", ":", "container", "=", "RoutineContainer", "(", "self", ".", "scheduler", ")", "if", "self", ".", "queue", "is", "not", "None", ":", "await", "container", ".", "syscall_noreturn", "(", "syscall_removequeue", "(", "self", ".", "scheduler", ".", "queue", ",", "self", ".", "queue", ")", ")", "self", ".", "queue", "=", "None" ]
42.555556
15.222222
def ace(args): """ %prog ace bamfile fastafile convert bam format to ace format. This often allows the remapping to be assessed as a denovo assembly format. bam file needs to be indexed. also creates a .mates file to be used in amos/bambus, and .astat file to mark whether the contig is unique or repetitive based on A-statistics in Celera assembler. """ p = OptionParser(ace.__doc__) p.add_option("--splitdir", dest="splitdir", default="outRoot", help="split the ace per contig to dir [default: %default]") p.add_option("--unpaired", dest="unpaired", default=False, help="remove read pairs on the same contig [default: %default]") p.add_option("--minreadno", dest="minreadno", default=3, type="int", help="minimum read numbers per contig [default: %default]") p.add_option("--minctgsize", dest="minctgsize", default=100, type="int", help="minimum contig size per contig [default: %default]") p.add_option("--astat", default=False, action="store_true", help="create .astat to list repetitiveness [default: %default]") p.add_option("--readids", default=False, action="store_true", help="create file of mapped and unmapped ids [default: %default]") from pysam import Samfile opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) bamfile, fastafile = args astat = opts.astat readids = opts.readids f = Fasta(fastafile) prefix = bamfile.split(".")[0] acefile = prefix + ".ace" readsfile = prefix + ".reads" astatfile = prefix + ".astat" logging.debug("Load {0}".format(bamfile)) s = Samfile(bamfile, "rb") ncontigs = s.nreferences genomesize = sum(x for a, x in f.itersizes()) logging.debug("Total {0} contigs with size {1} base".format(ncontigs, genomesize)) qual = "20" # default qual totalreads = sum(s.count(x) for x in s.references) logging.debug("Total {0} reads mapped".format(totalreads)) fw = open(acefile, "w") if astat: astatfw = open(astatfile, "w") if readids: readsfw = open(readsfile, "w") print("AS {0} {1}".format(ncontigs, totalreads), file=fw) print(file=fw) for i, contig in enumerate(s.references): cseq = f[contig] nbases = len(cseq) mapped_reads = [x for x in s.fetch(contig) if not x.is_unmapped] nreads = len(mapped_reads) nsegments = 0 print("CO {0} {1} {2} {3} U".format(contig, nbases, nreads, nsegments), file=fw) print(fill(str(cseq.seq)), file=fw) print(file=fw) if astat: astat = Astat(nbases, nreads, genomesize, totalreads) print("{0}\t{1:.1f}".format(contig, astat), file=astatfw) text = fill([qual] * nbases, delimiter=" ", width=30) print("BQ\n{0}".format(text), file=fw) print(file=fw) rnames = [] for a in mapped_reads: readname = a.qname rname = readname if readids: print(readname, file=readsfw) rnames.append(rname) strand = "C" if a.is_reverse else "U" paddedstart = a.pos + 1 # 0-based to 1-based af = "AF {0} {1} {2}".format(rname, strand, paddedstart) print(af, file=fw) print(file=fw) for a, rname in zip(mapped_reads, rnames): aseq, npadded = cigar_to_seq(a) if aseq is None: continue ninfos = 0 ntags = 0 alen = len(aseq) rd = "RD {0} {1} {2} {3}\n{4}".format(rname, alen, ninfos, ntags, fill(aseq)) qs = "QA 1 {0} 1 {0}".format(alen) print(rd, file=fw) print(file=fw) print(qs, file=fw) print(file=fw)
[ "def", "ace", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "ace", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--splitdir\"", ",", "dest", "=", "\"splitdir\"", ",", "default", "=", "\"outRoot\"", ",", "help", "=", "\"split the ace per contig to dir [default: %default]\"", ")", "p", ".", "add_option", "(", "\"--unpaired\"", ",", "dest", "=", "\"unpaired\"", ",", "default", "=", "False", ",", "help", "=", "\"remove read pairs on the same contig [default: %default]\"", ")", "p", ".", "add_option", "(", "\"--minreadno\"", ",", "dest", "=", "\"minreadno\"", ",", "default", "=", "3", ",", "type", "=", "\"int\"", ",", "help", "=", "\"minimum read numbers per contig [default: %default]\"", ")", "p", ".", "add_option", "(", "\"--minctgsize\"", ",", "dest", "=", "\"minctgsize\"", ",", "default", "=", "100", ",", "type", "=", "\"int\"", ",", "help", "=", "\"minimum contig size per contig [default: %default]\"", ")", "p", ".", "add_option", "(", "\"--astat\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"create .astat to list repetitiveness [default: %default]\"", ")", "p", ".", "add_option", "(", "\"--readids\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"create file of mapped and unmapped ids [default: %default]\"", ")", "from", "pysam", "import", "Samfile", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "2", ":", "sys", ".", "exit", "(", "not", "p", ".", "print_help", "(", ")", ")", "bamfile", ",", "fastafile", "=", "args", "astat", "=", "opts", ".", "astat", "readids", "=", "opts", ".", "readids", "f", "=", "Fasta", "(", "fastafile", ")", "prefix", "=", "bamfile", ".", "split", "(", "\".\"", ")", "[", "0", "]", "acefile", "=", "prefix", "+", "\".ace\"", "readsfile", "=", "prefix", "+", "\".reads\"", "astatfile", "=", "prefix", "+", "\".astat\"", "logging", ".", "debug", "(", "\"Load {0}\"", ".", "format", "(", "bamfile", ")", ")", "s", "=", "Samfile", "(", "bamfile", ",", "\"rb\"", ")", "ncontigs", "=", "s", ".", "nreferences", "genomesize", "=", "sum", "(", "x", "for", "a", ",", "x", "in", "f", ".", "itersizes", "(", ")", ")", "logging", ".", "debug", "(", "\"Total {0} contigs with size {1} base\"", ".", "format", "(", "ncontigs", ",", "genomesize", ")", ")", "qual", "=", "\"20\"", "# default qual", "totalreads", "=", "sum", "(", "s", ".", "count", "(", "x", ")", "for", "x", "in", "s", ".", "references", ")", "logging", ".", "debug", "(", "\"Total {0} reads mapped\"", ".", "format", "(", "totalreads", ")", ")", "fw", "=", "open", "(", "acefile", ",", "\"w\"", ")", "if", "astat", ":", "astatfw", "=", "open", "(", "astatfile", ",", "\"w\"", ")", "if", "readids", ":", "readsfw", "=", "open", "(", "readsfile", ",", "\"w\"", ")", "print", "(", "\"AS {0} {1}\"", ".", "format", "(", "ncontigs", ",", "totalreads", ")", ",", "file", "=", "fw", ")", "print", "(", "file", "=", "fw", ")", "for", "i", ",", "contig", "in", "enumerate", "(", "s", ".", "references", ")", ":", "cseq", "=", "f", "[", "contig", "]", "nbases", "=", "len", "(", "cseq", ")", "mapped_reads", "=", "[", "x", "for", "x", "in", "s", ".", "fetch", "(", "contig", ")", "if", "not", "x", ".", "is_unmapped", "]", "nreads", "=", "len", "(", "mapped_reads", ")", "nsegments", "=", "0", "print", "(", "\"CO {0} {1} {2} {3} U\"", ".", "format", "(", "contig", ",", "nbases", ",", "nreads", ",", "nsegments", ")", ",", "file", "=", "fw", ")", "print", "(", "fill", "(", "str", "(", "cseq", ".", "seq", ")", ")", ",", "file", "=", "fw", ")", "print", "(", "file", "=", "fw", ")", "if", "astat", ":", "astat", "=", "Astat", "(", "nbases", ",", "nreads", ",", "genomesize", ",", "totalreads", ")", "print", "(", "\"{0}\\t{1:.1f}\"", ".", "format", "(", "contig", ",", "astat", ")", ",", "file", "=", "astatfw", ")", "text", "=", "fill", "(", "[", "qual", "]", "*", "nbases", ",", "delimiter", "=", "\" \"", ",", "width", "=", "30", ")", "print", "(", "\"BQ\\n{0}\"", ".", "format", "(", "text", ")", ",", "file", "=", "fw", ")", "print", "(", "file", "=", "fw", ")", "rnames", "=", "[", "]", "for", "a", "in", "mapped_reads", ":", "readname", "=", "a", ".", "qname", "rname", "=", "readname", "if", "readids", ":", "print", "(", "readname", ",", "file", "=", "readsfw", ")", "rnames", ".", "append", "(", "rname", ")", "strand", "=", "\"C\"", "if", "a", ".", "is_reverse", "else", "\"U\"", "paddedstart", "=", "a", ".", "pos", "+", "1", "# 0-based to 1-based", "af", "=", "\"AF {0} {1} {2}\"", ".", "format", "(", "rname", ",", "strand", ",", "paddedstart", ")", "print", "(", "af", ",", "file", "=", "fw", ")", "print", "(", "file", "=", "fw", ")", "for", "a", ",", "rname", "in", "zip", "(", "mapped_reads", ",", "rnames", ")", ":", "aseq", ",", "npadded", "=", "cigar_to_seq", "(", "a", ")", "if", "aseq", "is", "None", ":", "continue", "ninfos", "=", "0", "ntags", "=", "0", "alen", "=", "len", "(", "aseq", ")", "rd", "=", "\"RD {0} {1} {2} {3}\\n{4}\"", ".", "format", "(", "rname", ",", "alen", ",", "ninfos", ",", "ntags", ",", "fill", "(", "aseq", ")", ")", "qs", "=", "\"QA 1 {0} 1 {0}\"", ".", "format", "(", "alen", ")", "print", "(", "rd", ",", "file", "=", "fw", ")", "print", "(", "file", "=", "fw", ")", "print", "(", "qs", ",", "file", "=", "fw", ")", "print", "(", "file", "=", "fw", ")" ]
33.008696
21.686957
def pop_cell(self, idy=None, idx=None, tags=False): """Pops a cell, default the last of the last row""" idy = idy if idy is not None else len(self.body) - 1 idx = idx if idx is not None else len(self.body[idy]) - 1 cell = self.body[idy].pop(idx) return cell if tags else cell.childs[0]
[ "def", "pop_cell", "(", "self", ",", "idy", "=", "None", ",", "idx", "=", "None", ",", "tags", "=", "False", ")", ":", "idy", "=", "idy", "if", "idy", "is", "not", "None", "else", "len", "(", "self", ".", "body", ")", "-", "1", "idx", "=", "idx", "if", "idx", "is", "not", "None", "else", "len", "(", "self", ".", "body", "[", "idy", "]", ")", "-", "1", "cell", "=", "self", ".", "body", "[", "idy", "]", ".", "pop", "(", "idx", ")", "return", "cell", "if", "tags", "else", "cell", ".", "childs", "[", "0", "]" ]
53.333333
10.833333
def update_attr(self, attr): """Update input attr in self. Return list of attributes with changed values. """ changed_attr = [] for key, value in attr.items(): if value is None: continue if getattr(self, "_{0}".format(key), None) != value: changed_attr.append(key) self.__setattr__("_{0}".format(key), value) _LOGGER.debug('%s: update %s with %s', self.name, key, value) return changed_attr
[ "def", "update_attr", "(", "self", ",", "attr", ")", ":", "changed_attr", "=", "[", "]", "for", "key", ",", "value", "in", "attr", ".", "items", "(", ")", ":", "if", "value", "is", "None", ":", "continue", "if", "getattr", "(", "self", ",", "\"_{0}\"", ".", "format", "(", "key", ")", ",", "None", ")", "!=", "value", ":", "changed_attr", ".", "append", "(", "key", ")", "self", ".", "__setattr__", "(", "\"_{0}\"", ".", "format", "(", "key", ")", ",", "value", ")", "_LOGGER", ".", "debug", "(", "'%s: update %s with %s'", ",", "self", ".", "name", ",", "key", ",", "value", ")", "return", "changed_attr" ]
36.714286
14.428571
async def invoke(self, context): """Claims and processes Taskcluster work. Args: context (scriptworker.context.Context): context of worker Returns: status code of build """ try: # Note: claim_work(...) might not be safely interruptible! See # https://bugzilla.mozilla.org/show_bug.cgi?id=1524069 tasks = await self._run_cancellable(claim_work(context)) if not tasks or not tasks.get('tasks', []): await self._run_cancellable(asyncio.sleep(context.config['poll_interval'])) return None # Assume only a single task, but should more than one fall through, # run them sequentially. A side effect is our return status will # be the status of the final task run. status = None for task_defn in tasks.get('tasks', []): prepare_to_run_task(context, task_defn) reclaim_fut = context.event_loop.create_task(reclaim_task(context, context.task)) try: status = await do_run_task(context, self._run_cancellable, self._to_cancellable_process) artifacts_paths = filepaths_in_dir(context.config['artifact_dir']) except WorkerShutdownDuringTask: shutdown_artifact_paths = [os.path.join('public', 'logs', log_file) for log_file in ['chain_of_trust.log', 'live_backing.log']] artifacts_paths = [path for path in shutdown_artifact_paths if os.path.isfile(os.path.join(context.config['artifact_dir'], path))] status = STATUSES['worker-shutdown'] status = worst_level(status, await do_upload(context, artifacts_paths)) await complete_task(context, status) reclaim_fut.cancel() cleanup(context) return status except asyncio.CancelledError: return None
[ "async", "def", "invoke", "(", "self", ",", "context", ")", ":", "try", ":", "# Note: claim_work(...) might not be safely interruptible! See", "# https://bugzilla.mozilla.org/show_bug.cgi?id=1524069", "tasks", "=", "await", "self", ".", "_run_cancellable", "(", "claim_work", "(", "context", ")", ")", "if", "not", "tasks", "or", "not", "tasks", ".", "get", "(", "'tasks'", ",", "[", "]", ")", ":", "await", "self", ".", "_run_cancellable", "(", "asyncio", ".", "sleep", "(", "context", ".", "config", "[", "'poll_interval'", "]", ")", ")", "return", "None", "# Assume only a single task, but should more than one fall through,", "# run them sequentially. A side effect is our return status will", "# be the status of the final task run.", "status", "=", "None", "for", "task_defn", "in", "tasks", ".", "get", "(", "'tasks'", ",", "[", "]", ")", ":", "prepare_to_run_task", "(", "context", ",", "task_defn", ")", "reclaim_fut", "=", "context", ".", "event_loop", ".", "create_task", "(", "reclaim_task", "(", "context", ",", "context", ".", "task", ")", ")", "try", ":", "status", "=", "await", "do_run_task", "(", "context", ",", "self", ".", "_run_cancellable", ",", "self", ".", "_to_cancellable_process", ")", "artifacts_paths", "=", "filepaths_in_dir", "(", "context", ".", "config", "[", "'artifact_dir'", "]", ")", "except", "WorkerShutdownDuringTask", ":", "shutdown_artifact_paths", "=", "[", "os", ".", "path", ".", "join", "(", "'public'", ",", "'logs'", ",", "log_file", ")", "for", "log_file", "in", "[", "'chain_of_trust.log'", ",", "'live_backing.log'", "]", "]", "artifacts_paths", "=", "[", "path", "for", "path", "in", "shutdown_artifact_paths", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "context", ".", "config", "[", "'artifact_dir'", "]", ",", "path", ")", ")", "]", "status", "=", "STATUSES", "[", "'worker-shutdown'", "]", "status", "=", "worst_level", "(", "status", ",", "await", "do_upload", "(", "context", ",", "artifacts_paths", ")", ")", "await", "complete_task", "(", "context", ",", "status", ")", "reclaim_fut", ".", "cancel", "(", ")", "cleanup", "(", "context", ")", "return", "status", "except", "asyncio", ".", "CancelledError", ":", "return", "None" ]
48.357143
27.880952
def _compute_centers(self, X, sparse, rs): """Generate centers, then compute tau, dF and dN vals""" super(GRBFRandomLayer, self)._compute_centers(X, sparse, rs) centers = self.components_['centers'] sorted_distances = np.sort(squareform(pdist(centers))) self.dF_vals = sorted_distances[:, -1] self.dN_vals = sorted_distances[:, 1]/100.0 #self.dN_vals = 0.0002 * np.ones(self.dF_vals.shape) tauNum = np.log(np.log(self.grbf_lambda) / np.log(1.0 - self.grbf_lambda)) tauDenom = np.log(self.dF_vals/self.dN_vals) self.tau_vals = tauNum/tauDenom self._extra_args['taus'] = self.tau_vals
[ "def", "_compute_centers", "(", "self", ",", "X", ",", "sparse", ",", "rs", ")", ":", "super", "(", "GRBFRandomLayer", ",", "self", ")", ".", "_compute_centers", "(", "X", ",", "sparse", ",", "rs", ")", "centers", "=", "self", ".", "components_", "[", "'centers'", "]", "sorted_distances", "=", "np", ".", "sort", "(", "squareform", "(", "pdist", "(", "centers", ")", ")", ")", "self", ".", "dF_vals", "=", "sorted_distances", "[", ":", ",", "-", "1", "]", "self", ".", "dN_vals", "=", "sorted_distances", "[", ":", ",", "1", "]", "/", "100.0", "#self.dN_vals = 0.0002 * np.ones(self.dF_vals.shape)", "tauNum", "=", "np", ".", "log", "(", "np", ".", "log", "(", "self", ".", "grbf_lambda", ")", "/", "np", ".", "log", "(", "1.0", "-", "self", ".", "grbf_lambda", ")", ")", "tauDenom", "=", "np", ".", "log", "(", "self", ".", "dF_vals", "/", "self", ".", "dN_vals", ")", "self", ".", "tau_vals", "=", "tauNum", "/", "tauDenom", "self", ".", "_extra_args", "[", "'taus'", "]", "=", "self", ".", "tau_vals" ]
35.894737
20
def epochs(self): """Get epochs as generator Returns ------- list of dict each epoch is defined by start_time and end_time (in s in reference to the start of the recordings) and a string of the sleep stage, and a string of the signal quality. If you specify stages_of_interest, only epochs belonging to those stages will be included (can be an empty list). Raises ------ IndexError When there is no rater / epochs at all """ if self.rater is None: raise IndexError('You need to have at least one rater') for one_epoch in self.rater.iterfind('stages/epoch'): epoch = {'start': int(one_epoch.find('epoch_start').text), 'end': int(one_epoch.find('epoch_end').text), 'stage': one_epoch.find('stage').text, 'quality': one_epoch.find('quality').text } yield epoch
[ "def", "epochs", "(", "self", ")", ":", "if", "self", ".", "rater", "is", "None", ":", "raise", "IndexError", "(", "'You need to have at least one rater'", ")", "for", "one_epoch", "in", "self", ".", "rater", ".", "iterfind", "(", "'stages/epoch'", ")", ":", "epoch", "=", "{", "'start'", ":", "int", "(", "one_epoch", ".", "find", "(", "'epoch_start'", ")", ".", "text", ")", ",", "'end'", ":", "int", "(", "one_epoch", ".", "find", "(", "'epoch_end'", ")", ".", "text", ")", ",", "'stage'", ":", "one_epoch", ".", "find", "(", "'stage'", ")", ".", "text", ",", "'quality'", ":", "one_epoch", ".", "find", "(", "'quality'", ")", ".", "text", "}", "yield", "epoch" ]
37.259259
23.148148
def pathsplit(value, sep=os.pathsep): ''' Get enviroment PATH elements as list. This function only cares about spliting across OSes. :param value: path string, as given by os.environ['PATH'] :type value: str :param sep: PATH separator, defaults to os.pathsep :type sep: str :yields: every path :ytype: str ''' for part in value.split(sep): if part[:1] == part[-1:] == '"' or part[:1] == part[-1:] == '\'': part = part[1:-1] yield part
[ "def", "pathsplit", "(", "value", ",", "sep", "=", "os", ".", "pathsep", ")", ":", "for", "part", "in", "value", ".", "split", "(", "sep", ")", ":", "if", "part", "[", ":", "1", "]", "==", "part", "[", "-", "1", ":", "]", "==", "'\"'", "or", "part", "[", ":", "1", "]", "==", "part", "[", "-", "1", ":", "]", "==", "'\\''", ":", "part", "=", "part", "[", "1", ":", "-", "1", "]", "yield", "part" ]
28.941176
21.058824
def detect_credentials(config_name, extra_environ=None, filenames=None, aws_profile_name=None, default_value=Ellipsis): ''' detect_credentials(config_name) attempts to locate Amazon S3 Bucket credentials from the given configuration item config_name. The following optional arguments are accepted: * extra_environ (default: None) may specify a string or a tuple (key_name, secret_name) or a list of strings or tuples; strings are treated as an additional environment variable that should be checked for credentials while tuples are treated as paired varialbes: if both are defined, then they are checked as separate holders of a key/secret pair. Note that a list of strings is considered a pair of solo environment varialbes while a tuple of strings is considered a single (key_name, secret_name) pair. * filenames (default: None) may specify a list of filenames that are checked in order for credentials. * aws_profile_name (default: None) may specify a profile name that appears in the ~/.aws/credentials file that will be checked for aws_access_key_id and aws_secret_access_key values. The files ~/.amazon/credentials and ~/.credentials are also checked. Note that this may be a list of profiles to check. * default_value (default: Ellipsis) may specify a value to return when no credentials are found; if this value is None, then it is always returned; otherwise, the value is passed through to_credentials() and any errors are allowed to propagate out of detect_credentials(). If default_value is Ellipsis then an error is simply raised stating that no credentials could be found. The detect_credentials() function looks at the following locations in the following order, assuming that it has been provided with the relevant information: * first, if the Neuropythy configuration variable config_name is set via either the npythyrc file or the associated environment variable, then it is coerced into credentials; * next, if the environment contains both the variables key_name and secret_name (from the optional argument key_secret_environ), then these values are used; * next, if the filenames argument is given, then all files it refers to are checked for credentials; these files are expanded with both os.expanduser and os.expandvars. * finally, if no credentials were detected, an error is raised. ''' # Check the config first: if config_name is not None and config[config_name] is not None: return config[config_name] # Okay, not found there; check the key/secret environment variables if extra_environ is None: extra_environ = [] elif pimms.is_str(extra_environ): extra_environ = [extra_environ] elif pimms.is_vector(extra_environ): if pimms.is_vector(extra_environ, str): if len(extra_environ) == 2 and isinstance(extra_environ, _tuple_type): extra_environ = [extra_environ] elif not pimms.is_matrix(extra_environ, str): raise ValueError('extra_environ must be a string, tuple of strings, or list of these') for ee in extra_environ: if pimms.is_str(ee): if ee in os.environ: try: return to_credentials(q) except Exception: pass elif pimms.is_vector(ee, str) and len(ee) == 2: if ee[0] in os.environ and ee[1] in os.environ: (k,s) = [os.environ[q] for q in ee] if len(k) > 0 and len(s) > 0: continue return (k,s) else: raise ValueError('cannot interpret extra_environ argument: %s' % ee) # Okay, next we check the filenames if filenames is None: filenames = [] elif pimms.is_str(filenames): filenames = [filenames] for flnm in filenames: flnm = os.expanduser(os.expandvars(flnm)) if os.path.isfile(flnm): try: return to_credentials(flnm) except Exception: pass # okay... let's check the AWS credentials file, if it exists if pimms.is_str(aws_profile_name): aws_profile_name = [aws_profile_name] elif aws_profile_name is None or len(aws_profile_name) == 0: aws_profile_name = None elif not pimms.is_vector(aws_profile_name, str): raise ValueError('Invalid aws_profile_name value: %s' % aws_profile_name) if aws_profile_name is not None: try: cc = confparse.ConfigParser() cc.read([os.expanduser(os.path.join('~', '.aws', 'credentials')), os.expanduser(os.path.join('~', '.amazon', 'credentials')), os.expanduser(os.path.join('~', '.credentials'))]) for awsprof in aws_profile_names: try: aws_access_key_id = cc.get(awsprof, 'aws_access_key_id') aws_secret_access_key = cc.get(awsprof, 'aws_secret_access_key') return (aws_access_key_id, aws_secret_access_key) except Exception: pass except Exception: pass # no match! if default_value is None: return None elif default_value is Ellipsis: if config_name is None: raise ValueError('No valid credentials were detected') else: raise ValueError('No valid credentials (%s) were detected' % config_name) else: return to_credentials(default_value)
[ "def", "detect_credentials", "(", "config_name", ",", "extra_environ", "=", "None", ",", "filenames", "=", "None", ",", "aws_profile_name", "=", "None", ",", "default_value", "=", "Ellipsis", ")", ":", "# Check the config first:", "if", "config_name", "is", "not", "None", "and", "config", "[", "config_name", "]", "is", "not", "None", ":", "return", "config", "[", "config_name", "]", "# Okay, not found there; check the key/secret environment variables", "if", "extra_environ", "is", "None", ":", "extra_environ", "=", "[", "]", "elif", "pimms", ".", "is_str", "(", "extra_environ", ")", ":", "extra_environ", "=", "[", "extra_environ", "]", "elif", "pimms", ".", "is_vector", "(", "extra_environ", ")", ":", "if", "pimms", ".", "is_vector", "(", "extra_environ", ",", "str", ")", ":", "if", "len", "(", "extra_environ", ")", "==", "2", "and", "isinstance", "(", "extra_environ", ",", "_tuple_type", ")", ":", "extra_environ", "=", "[", "extra_environ", "]", "elif", "not", "pimms", ".", "is_matrix", "(", "extra_environ", ",", "str", ")", ":", "raise", "ValueError", "(", "'extra_environ must be a string, tuple of strings, or list of these'", ")", "for", "ee", "in", "extra_environ", ":", "if", "pimms", ".", "is_str", "(", "ee", ")", ":", "if", "ee", "in", "os", ".", "environ", ":", "try", ":", "return", "to_credentials", "(", "q", ")", "except", "Exception", ":", "pass", "elif", "pimms", ".", "is_vector", "(", "ee", ",", "str", ")", "and", "len", "(", "ee", ")", "==", "2", ":", "if", "ee", "[", "0", "]", "in", "os", ".", "environ", "and", "ee", "[", "1", "]", "in", "os", ".", "environ", ":", "(", "k", ",", "s", ")", "=", "[", "os", ".", "environ", "[", "q", "]", "for", "q", "in", "ee", "]", "if", "len", "(", "k", ")", ">", "0", "and", "len", "(", "s", ")", ">", "0", ":", "continue", "return", "(", "k", ",", "s", ")", "else", ":", "raise", "ValueError", "(", "'cannot interpret extra_environ argument: %s'", "%", "ee", ")", "# Okay, next we check the filenames", "if", "filenames", "is", "None", ":", "filenames", "=", "[", "]", "elif", "pimms", ".", "is_str", "(", "filenames", ")", ":", "filenames", "=", "[", "filenames", "]", "for", "flnm", "in", "filenames", ":", "flnm", "=", "os", ".", "expanduser", "(", "os", ".", "expandvars", "(", "flnm", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "flnm", ")", ":", "try", ":", "return", "to_credentials", "(", "flnm", ")", "except", "Exception", ":", "pass", "# okay... let's check the AWS credentials file, if it exists", "if", "pimms", ".", "is_str", "(", "aws_profile_name", ")", ":", "aws_profile_name", "=", "[", "aws_profile_name", "]", "elif", "aws_profile_name", "is", "None", "or", "len", "(", "aws_profile_name", ")", "==", "0", ":", "aws_profile_name", "=", "None", "elif", "not", "pimms", ".", "is_vector", "(", "aws_profile_name", ",", "str", ")", ":", "raise", "ValueError", "(", "'Invalid aws_profile_name value: %s'", "%", "aws_profile_name", ")", "if", "aws_profile_name", "is", "not", "None", ":", "try", ":", "cc", "=", "confparse", ".", "ConfigParser", "(", ")", "cc", ".", "read", "(", "[", "os", ".", "expanduser", "(", "os", ".", "path", ".", "join", "(", "'~'", ",", "'.aws'", ",", "'credentials'", ")", ")", ",", "os", ".", "expanduser", "(", "os", ".", "path", ".", "join", "(", "'~'", ",", "'.amazon'", ",", "'credentials'", ")", ")", ",", "os", ".", "expanduser", "(", "os", ".", "path", ".", "join", "(", "'~'", ",", "'.credentials'", ")", ")", "]", ")", "for", "awsprof", "in", "aws_profile_names", ":", "try", ":", "aws_access_key_id", "=", "cc", ".", "get", "(", "awsprof", ",", "'aws_access_key_id'", ")", "aws_secret_access_key", "=", "cc", ".", "get", "(", "awsprof", ",", "'aws_secret_access_key'", ")", "return", "(", "aws_access_key_id", ",", "aws_secret_access_key", ")", "except", "Exception", ":", "pass", "except", "Exception", ":", "pass", "# no match!", "if", "default_value", "is", "None", ":", "return", "None", "elif", "default_value", "is", "Ellipsis", ":", "if", "config_name", "is", "None", ":", "raise", "ValueError", "(", "'No valid credentials were detected'", ")", "else", ":", "raise", "ValueError", "(", "'No valid credentials (%s) were detected'", "%", "config_name", ")", "else", ":", "return", "to_credentials", "(", "default_value", ")" ]
59.877778
28.344444
def wait_until(obj, att, desired, callback=None, interval=5, attempts=0, verbose=False, verbose_atts=None): """ When changing the state of an object, it will commonly be in a transitional state until the change is complete. This will reload the object every `interval` seconds, and check its `att` attribute until the `desired` value is reached, or until the maximum number of attempts is reached. The updated object is returned. It is up to the calling program to check the returned object to make sure that it successfully reached the desired state. Once the desired value of the attribute is reached, the method returns. If not, it will re-try until the attribute's value matches one of the `desired` values. By default (attempts=0) it will loop infinitely until the attribute reaches the desired value. You can optionally limit the number of times that the object is reloaded by passing a positive value to `attempts`. If the attribute has not reached the desired value by then, the method will exit. If `verbose` is True, each attempt will print out the current value of the watched attribute and the time that has elapsed since the original request. Also, if `verbose_atts` is specified, the values of those attributes will also be output. If `verbose` is False, then `verbose_atts` has no effect. Note that `desired` can be a list of values; if the attribute becomes equal to any of those values, this will succeed. For example, when creating a new cloud server, it will initially have a status of 'BUILD', and you can't work with it until its status is 'ACTIVE'. However, there might be a problem with the build process, and the server will change to a status of 'ERROR'. So for this case you need to set the `desired` parameter to `['ACTIVE', 'ERROR']`. If you simply pass 'ACTIVE' as the desired state, this will loop indefinitely if a build fails, as the server will never reach a status of 'ACTIVE'. Since this process of waiting can take a potentially long time, and will block your program's execution until the desired state of the object is reached, you may specify a callback function. The callback can be any callable that accepts a single parameter; the parameter it receives will be either the updated object (success), or None (failure). If a callback is specified, the program will return immediately after spawning the wait process in a separate thread. """ if callback: waiter = _WaitThread(obj=obj, att=att, desired=desired, callback=callback, interval=interval, attempts=attempts, verbose=verbose, verbose_atts=verbose_atts) waiter.start() return waiter else: return _wait_until(obj=obj, att=att, desired=desired, callback=None, interval=interval, attempts=attempts, verbose=verbose, verbose_atts=verbose_atts)
[ "def", "wait_until", "(", "obj", ",", "att", ",", "desired", ",", "callback", "=", "None", ",", "interval", "=", "5", ",", "attempts", "=", "0", ",", "verbose", "=", "False", ",", "verbose_atts", "=", "None", ")", ":", "if", "callback", ":", "waiter", "=", "_WaitThread", "(", "obj", "=", "obj", ",", "att", "=", "att", ",", "desired", "=", "desired", ",", "callback", "=", "callback", ",", "interval", "=", "interval", ",", "attempts", "=", "attempts", ",", "verbose", "=", "verbose", ",", "verbose_atts", "=", "verbose_atts", ")", "waiter", ".", "start", "(", ")", "return", "waiter", "else", ":", "return", "_wait_until", "(", "obj", "=", "obj", ",", "att", "=", "att", ",", "desired", "=", "desired", ",", "callback", "=", "None", ",", "interval", "=", "interval", ",", "attempts", "=", "attempts", ",", "verbose", "=", "verbose", ",", "verbose_atts", "=", "verbose_atts", ")" ]
57.686275
30.235294
def get_jwt_secret(): """ Get the JWT secret :return: str """ secret_key = __options__.get("jwt_secret") or config("JWT_SECRET") or config("SECRET_KEY") if not secret_key: raise exceptions.AuthError("Missing config JWT/SECRET_KEY") return secret_key
[ "def", "get_jwt_secret", "(", ")", ":", "secret_key", "=", "__options__", ".", "get", "(", "\"jwt_secret\"", ")", "or", "config", "(", "\"JWT_SECRET\"", ")", "or", "config", "(", "\"SECRET_KEY\"", ")", "if", "not", "secret_key", ":", "raise", "exceptions", ".", "AuthError", "(", "\"Missing config JWT/SECRET_KEY\"", ")", "return", "secret_key" ]
30.777778
19.888889
def atlas_peer_getinfo( peer_hostport, timeout=None, peer_table=None ): """ Get host info Return the rpc_getinfo() response on success Return None on error """ if timeout is None: timeout = atlas_ping_timeout() host, port = url_to_host_port( peer_hostport ) RPC = get_rpc_client_class() rpc = RPC( host, port, timeout=timeout ) assert not atlas_peer_table_is_locked_by_me() log.debug("getinfo %s" % peer_hostport) res = None try: res = blockstack_getinfo( proxy=rpc ) if 'error' in res: log.error("Failed to getinfo on %s: %s" % (peer_hostport, res['error'])) if 'last_block_processed' not in res: log.error("Missing last_block_processed response from {}".format(peer_hostport)) res = {'error': 'Remote peer {} did not rely last_block_processed'.format(peer_hostport)} if 'stale' in res and res['stale']: log.error("Remote host {} is well behind the chain tip".format(peer_hostport)) res = {'error': 'Remote peer {} is well behind the chain tip'.format(peer_hostport)} if 'testnet' in res: if (res['testnet'] and not BLOCKSTACK_TEST and not BLOCKSTACK_PUBLIC_TESTNET) or (not res['testnet'] and (BLOCKSTACK_TEST or BLOCKSTACK_PUBLIC_TESTNET)): if BLOCKSTACK_TEST or BLOCKSTACK_PUBLIC_TESTNET: log.error("Remote host {} is a mainnet host, and we're testnet".format(peer_hostport)) res = {'error': 'Remote peer {} is a mainnet host, and we\'re testnet'.format(peer_hostport)} else: log.error("Remote host {} is a testnet host".format(peer_hostport)) res = {'error': 'Remote peer {} is a testnet host'.format(peer_hostport)} else: # assume mainnet if BLOCKSTACK_TEST or BLOCKSTACK_PUBLIC_TESTNET: log.error("Remote host {} is a mainnet host, and we're testnet".format(peer_hostport)) res = {'error': 'Remote peer {} is a mainnet host, and we\'re testnet'.format(peer_hostport)} except (socket.timeout, socket.gaierror, socket.herror, socket.error), se: atlas_log_socket_error( "getinfo(%s)" % peer_hostport, peer_hostport, se ) except AssertionError, ae: log.exception(ae) log.error("Invalid server reply for getinfo from %s" % peer_hostport) except Exception, e: log.exception(e) log.error("Failed to get response from %s" % peer_hostport) if res is not None: err = False if json_is_error(res): log.error("Failed to contact {}: replied error '{}'".format(peer_hostport, res['error'])) err = True if 'stale' in res and res['stale']: # peer is behind the chain tip log.warning("Peer {} reports that it is too far behind the chain tip. Ignoring for now.".format(peer_hostport)) err = True if err: res = None else: log.error("Failed to contact {}: no response".format(peer_hostport)) # update health with AtlasPeerTableLocked(peer_table) as ptbl: if ptbl.has_key(peer_hostport): atlas_peer_update_health( peer_hostport, (res is not None), peer_table=ptbl ) return res
[ "def", "atlas_peer_getinfo", "(", "peer_hostport", ",", "timeout", "=", "None", ",", "peer_table", "=", "None", ")", ":", "if", "timeout", "is", "None", ":", "timeout", "=", "atlas_ping_timeout", "(", ")", "host", ",", "port", "=", "url_to_host_port", "(", "peer_hostport", ")", "RPC", "=", "get_rpc_client_class", "(", ")", "rpc", "=", "RPC", "(", "host", ",", "port", ",", "timeout", "=", "timeout", ")", "assert", "not", "atlas_peer_table_is_locked_by_me", "(", ")", "log", ".", "debug", "(", "\"getinfo %s\"", "%", "peer_hostport", ")", "res", "=", "None", "try", ":", "res", "=", "blockstack_getinfo", "(", "proxy", "=", "rpc", ")", "if", "'error'", "in", "res", ":", "log", ".", "error", "(", "\"Failed to getinfo on %s: %s\"", "%", "(", "peer_hostport", ",", "res", "[", "'error'", "]", ")", ")", "if", "'last_block_processed'", "not", "in", "res", ":", "log", ".", "error", "(", "\"Missing last_block_processed response from {}\"", ".", "format", "(", "peer_hostport", ")", ")", "res", "=", "{", "'error'", ":", "'Remote peer {} did not rely last_block_processed'", ".", "format", "(", "peer_hostport", ")", "}", "if", "'stale'", "in", "res", "and", "res", "[", "'stale'", "]", ":", "log", ".", "error", "(", "\"Remote host {} is well behind the chain tip\"", ".", "format", "(", "peer_hostport", ")", ")", "res", "=", "{", "'error'", ":", "'Remote peer {} is well behind the chain tip'", ".", "format", "(", "peer_hostport", ")", "}", "if", "'testnet'", "in", "res", ":", "if", "(", "res", "[", "'testnet'", "]", "and", "not", "BLOCKSTACK_TEST", "and", "not", "BLOCKSTACK_PUBLIC_TESTNET", ")", "or", "(", "not", "res", "[", "'testnet'", "]", "and", "(", "BLOCKSTACK_TEST", "or", "BLOCKSTACK_PUBLIC_TESTNET", ")", ")", ":", "if", "BLOCKSTACK_TEST", "or", "BLOCKSTACK_PUBLIC_TESTNET", ":", "log", ".", "error", "(", "\"Remote host {} is a mainnet host, and we're testnet\"", ".", "format", "(", "peer_hostport", ")", ")", "res", "=", "{", "'error'", ":", "'Remote peer {} is a mainnet host, and we\\'re testnet'", ".", "format", "(", "peer_hostport", ")", "}", "else", ":", "log", ".", "error", "(", "\"Remote host {} is a testnet host\"", ".", "format", "(", "peer_hostport", ")", ")", "res", "=", "{", "'error'", ":", "'Remote peer {} is a testnet host'", ".", "format", "(", "peer_hostport", ")", "}", "else", ":", "# assume mainnet ", "if", "BLOCKSTACK_TEST", "or", "BLOCKSTACK_PUBLIC_TESTNET", ":", "log", ".", "error", "(", "\"Remote host {} is a mainnet host, and we're testnet\"", ".", "format", "(", "peer_hostport", ")", ")", "res", "=", "{", "'error'", ":", "'Remote peer {} is a mainnet host, and we\\'re testnet'", ".", "format", "(", "peer_hostport", ")", "}", "except", "(", "socket", ".", "timeout", ",", "socket", ".", "gaierror", ",", "socket", ".", "herror", ",", "socket", ".", "error", ")", ",", "se", ":", "atlas_log_socket_error", "(", "\"getinfo(%s)\"", "%", "peer_hostport", ",", "peer_hostport", ",", "se", ")", "except", "AssertionError", ",", "ae", ":", "log", ".", "exception", "(", "ae", ")", "log", ".", "error", "(", "\"Invalid server reply for getinfo from %s\"", "%", "peer_hostport", ")", "except", "Exception", ",", "e", ":", "log", ".", "exception", "(", "e", ")", "log", ".", "error", "(", "\"Failed to get response from %s\"", "%", "peer_hostport", ")", "if", "res", "is", "not", "None", ":", "err", "=", "False", "if", "json_is_error", "(", "res", ")", ":", "log", ".", "error", "(", "\"Failed to contact {}: replied error '{}'\"", ".", "format", "(", "peer_hostport", ",", "res", "[", "'error'", "]", ")", ")", "err", "=", "True", "if", "'stale'", "in", "res", "and", "res", "[", "'stale'", "]", ":", "# peer is behind the chain tip", "log", ".", "warning", "(", "\"Peer {} reports that it is too far behind the chain tip. Ignoring for now.\"", ".", "format", "(", "peer_hostport", ")", ")", "err", "=", "True", "if", "err", ":", "res", "=", "None", "else", ":", "log", ".", "error", "(", "\"Failed to contact {}: no response\"", ".", "format", "(", "peer_hostport", ")", ")", "# update health", "with", "AtlasPeerTableLocked", "(", "peer_table", ")", "as", "ptbl", ":", "if", "ptbl", ".", "has_key", "(", "peer_hostport", ")", ":", "atlas_peer_update_health", "(", "peer_hostport", ",", "(", "res", "is", "not", "None", ")", ",", "peer_table", "=", "ptbl", ")", "return", "res" ]
40.234568
30.283951
def req(self, method, params=()): """send request to ppcoind""" response = self.session.post( self.url, data=json.dumps({"method": method, "params": params, "jsonrpc": "1.1"}), ).json() if response["error"] is not None: return response["error"] else: return response["result"]
[ "def", "req", "(", "self", ",", "method", ",", "params", "=", "(", ")", ")", ":", "response", "=", "self", ".", "session", ".", "post", "(", "self", ".", "url", ",", "data", "=", "json", ".", "dumps", "(", "{", "\"method\"", ":", "method", ",", "\"params\"", ":", "params", ",", "\"jsonrpc\"", ":", "\"1.1\"", "}", ")", ",", ")", ".", "json", "(", ")", "if", "response", "[", "\"error\"", "]", "is", "not", "None", ":", "return", "response", "[", "\"error\"", "]", "else", ":", "return", "response", "[", "\"result\"", "]" ]
29.583333
17.666667
def get_all_lower(self): """Return all parent GO IDs through both reverse 'is_a' and all relationships.""" all_lower = set() for lower in self.get_goterms_lower(): all_lower.add(lower.item_id) all_lower |= lower.get_all_lower() return all_lower
[ "def", "get_all_lower", "(", "self", ")", ":", "all_lower", "=", "set", "(", ")", "for", "lower", "in", "self", ".", "get_goterms_lower", "(", ")", ":", "all_lower", ".", "add", "(", "lower", ".", "item_id", ")", "all_lower", "|=", "lower", ".", "get_all_lower", "(", ")", "return", "all_lower" ]
42
8.428571
def extract_subset(self, input_data_tiles=None, out_tile=None): """ Extract subset from multiple tiles. input_data_tiles : list of (``Tile``, process data) tuples out_tile : ``Tile`` Returns ------- NumPy array or list of features. """ if self.METADATA["data_type"] == "raster": mosaic = create_mosaic(input_data_tiles) return extract_from_array( in_raster=prepare_array( mosaic.data, nodata=self.nodata, dtype=self.output_params["dtype"] ), in_affine=mosaic.affine, out_tile=out_tile ) elif self.METADATA["data_type"] == "vector": return [ feature for feature in list( chain.from_iterable([features for _, features in input_data_tiles]) ) if shape(feature["geometry"]).intersects(out_tile.bbox) ]
[ "def", "extract_subset", "(", "self", ",", "input_data_tiles", "=", "None", ",", "out_tile", "=", "None", ")", ":", "if", "self", ".", "METADATA", "[", "\"data_type\"", "]", "==", "\"raster\"", ":", "mosaic", "=", "create_mosaic", "(", "input_data_tiles", ")", "return", "extract_from_array", "(", "in_raster", "=", "prepare_array", "(", "mosaic", ".", "data", ",", "nodata", "=", "self", ".", "nodata", ",", "dtype", "=", "self", ".", "output_params", "[", "\"dtype\"", "]", ")", ",", "in_affine", "=", "mosaic", ".", "affine", ",", "out_tile", "=", "out_tile", ")", "elif", "self", ".", "METADATA", "[", "\"data_type\"", "]", "==", "\"vector\"", ":", "return", "[", "feature", "for", "feature", "in", "list", "(", "chain", ".", "from_iterable", "(", "[", "features", "for", "_", ",", "features", "in", "input_data_tiles", "]", ")", ")", "if", "shape", "(", "feature", "[", "\"geometry\"", "]", ")", ".", "intersects", "(", "out_tile", ".", "bbox", ")", "]" ]
34.586207
15.896552
def ko_bindings(model): """ Given a model, returns the Knockout data bindings. """ try: if isinstance(model, str): modelName = model else: modelName = model.__class__.__name__ modelBindingsString = "ko.applyBindings(new " + modelName + "ViewModel(), $('#" + modelName.lower() + "s')[0]);" return modelBindingsString except Exception as e: logger.error(e) return ''
[ "def", "ko_bindings", "(", "model", ")", ":", "try", ":", "if", "isinstance", "(", "model", ",", "str", ")", ":", "modelName", "=", "model", "else", ":", "modelName", "=", "model", ".", "__class__", ".", "__name__", "modelBindingsString", "=", "\"ko.applyBindings(new \"", "+", "modelName", "+", "\"ViewModel(), $('#\"", "+", "modelName", ".", "lower", "(", ")", "+", "\"s')[0]);\"", "return", "modelBindingsString", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "e", ")", "return", "''" ]
26.058824
22.058824
def add(message, level=0, user=None, message_short=None,log_file_name='%s/pyscada_daemon.log' % settings.BASE_DIR,): """ add a new massage/error notice to the log <0 - Debug 1 - Emergency 2 - Critical 3 - Errors 4 - Alerts 5 - Warnings 6 - Notification (webnotice) 7 - Information (webinfo) 8 - Notification (notice) 9 - Information (info) """ #if not access(path.dirname(self.log_file_name), W_OK): # self.stderr.write("logfile path is not writeable\n") # sys.exit(0) #if access(self.log_file_name, F_OK) and not access(self.log_file_name, W_OK): # self.stderr.write("logfile is not writeable\n") # sys.exit(0) if message_short is None: message_len = len(message) if message_len > 35: message_short = message[0:31] + '...' else: message_short = message #log_ob = Log(message=message, level=level, message_short=message_short, timestamp=time()) #if user: # log_ob.user = user #log_ob.save() stdout = open(log_file_name, "a+") stdout.write("%s (%s,%d):%s\n" % (datetime.now().isoformat(' '),'none',level,message)) stdout.flush()
[ "def", "add", "(", "message", ",", "level", "=", "0", ",", "user", "=", "None", ",", "message_short", "=", "None", ",", "log_file_name", "=", "'%s/pyscada_daemon.log'", "%", "settings", ".", "BASE_DIR", ",", ")", ":", "#if not access(path.dirname(self.log_file_name), W_OK):", "# self.stderr.write(\"logfile path is not writeable\\n\")", "# sys.exit(0)", "#if access(self.log_file_name, F_OK) and not access(self.log_file_name, W_OK):", "# self.stderr.write(\"logfile is not writeable\\n\")", "# sys.exit(0)", "if", "message_short", "is", "None", ":", "message_len", "=", "len", "(", "message", ")", "if", "message_len", ">", "35", ":", "message_short", "=", "message", "[", "0", ":", "31", "]", "+", "'...'", "else", ":", "message_short", "=", "message", "#log_ob = Log(message=message, level=level, message_short=message_short, timestamp=time())", "#if user:", "# log_ob.user = user", "#log_ob.save()", "stdout", "=", "open", "(", "log_file_name", ",", "\"a+\"", ")", "stdout", ".", "write", "(", "\"%s (%s,%d):%s\\n\"", "%", "(", "datetime", ".", "now", "(", ")", ".", "isoformat", "(", "' '", ")", ",", "'none'", ",", "level", ",", "message", ")", ")", "stdout", ".", "flush", "(", ")" ]
32.388889
22
def reset_clipboard(self): """ Resets the clipboard, so that old elements do not pollute the new selection that is copied into the clipboard. :return: """ # reset selections for state_element_attr in ContainerState.state_element_attrs: self.model_copies[state_element_attr] = [] # reset parent state_id the copied elements are taken from self.copy_parent_state_id = None self.reset_clipboard_mapping_dicts()
[ "def", "reset_clipboard", "(", "self", ")", ":", "# reset selections", "for", "state_element_attr", "in", "ContainerState", ".", "state_element_attrs", ":", "self", ".", "model_copies", "[", "state_element_attr", "]", "=", "[", "]", "# reset parent state_id the copied elements are taken from", "self", ".", "copy_parent_state_id", "=", "None", "self", ".", "reset_clipboard_mapping_dicts", "(", ")" ]
34.642857
18.785714
def get(tag: {str, 'Language'}, normalize=True) -> 'Language': """ Create a Language object from a language tag string. If normalize=True, non-standard or overlong tags will be replaced as they're interpreted. This is recommended. Here are several examples of language codes, which are also test cases. Most language codes are straightforward, but these examples will get pretty obscure toward the end. >>> Language.get('en-US') Language.make(language='en', region='US') >>> Language.get('zh-Hant') Language.make(language='zh', script='Hant') >>> Language.get('und') Language.make() This function is idempotent, in case you already have a Language object: >>> Language.get(Language.get('en-us')) Language.make(language='en', region='US') The non-code 'root' is sometimes used to represent the lack of any language information, similar to 'und'. >>> Language.get('root') Language.make() By default, getting a Language object will automatically convert deprecated tags: >>> Language.get('iw') Language.make(language='he') >>> Language.get('in') Language.make(language='id') One type of deprecated tag that should be replaced is for sign languages, which used to all be coded as regional variants of a fictitious global sign language called 'sgn'. Of course, there is no global sign language, so sign languages now have their own language codes. >>> Language.get('sgn-US') Language.make(language='ase') >>> Language.get('sgn-US', normalize=False) Language.make(language='sgn', region='US') 'en-gb-oed' is a tag that's grandfathered into the standard because it has been used to mean "spell-check this with Oxford English Dictionary spelling", but that tag has the wrong shape. We interpret this as the new standardized tag 'en-gb-oxendict', unless asked not to normalize. >>> Language.get('en-gb-oed') Language.make(language='en', region='GB', variants=['oxendict']) >>> Language.get('en-gb-oed', normalize=False) Language.make(language='en-gb-oed') 'zh-min-nan' is another oddly-formed tag, used to represent the Southern Min language, which includes Taiwanese as a regional form. It now has its own language code. >>> Language.get('zh-min-nan') Language.make(language='nan') There's not much we can do with the vague tag 'zh-min': >>> Language.get('zh-min') Language.make(language='zh-min') Occasionally Wiktionary will use 'extlang' tags in strange ways, such as using the tag 'und-ibe' for some unspecified Iberian language. >>> Language.get('und-ibe') Language.make(extlangs=['ibe']) Here's an example of replacing multiple deprecated tags. The language tag 'sh' (Serbo-Croatian) ended up being politically problematic, and different standards took different steps to address this. The IANA made it into a macrolanguage that contains 'sr', 'hr', and 'bs'. Unicode further decided that it's a legacy tag that should be interpreted as 'sr-Latn', which the language matching rules say is mutually intelligible with all those languages. We complicate the example by adding on the region tag 'QU', an old provisional tag for the European Union, which is now standardized as 'EU'. >>> Language.get('sh-QU') Language.make(language='sr', script='Latn', region='EU') """ if isinstance(tag, Language): if not normalize: # shortcut: we have the tag already return tag # We might need to normalize this tag. Convert it back into a # string tag, to cover all the edge cases of normalization in a # way that we've already solved. tag = tag.to_tag() if (tag, normalize) in Language._PARSE_CACHE: return Language._PARSE_CACHE[tag, normalize] data = {} # if the complete tag appears as something to normalize, do the # normalization right away. Smash case when checking, because the # case normalization that comes from parse_tag() hasn't been applied # yet. tag_lower = tag.lower() if normalize and tag_lower in LANGUAGE_REPLACEMENTS: tag = LANGUAGE_REPLACEMENTS[tag_lower] components = parse_tag(tag) for typ, value in components: if typ == 'extlang' and normalize and 'language' in data: # smash extlangs when possible minitag = '%s-%s' % (data['language'], value) norm = LANGUAGE_REPLACEMENTS.get(minitag.lower()) if norm is not None: data.update( Language.get(norm, normalize).to_dict() ) else: data.setdefault('extlangs', []).append(value) elif typ in {'extlang', 'variant', 'extension'}: data.setdefault(typ + 's', []).append(value) elif typ == 'language': if value == 'und': pass elif normalize: replacement = LANGUAGE_REPLACEMENTS.get(value.lower()) if replacement is not None: # parse the replacement if necessary -- this helps with # Serbian and Moldovan data.update( Language.get(replacement, normalize).to_dict() ) else: data['language'] = value else: data['language'] = value elif typ == 'region': if normalize: data['region'] = REGION_REPLACEMENTS.get(value.lower(), value) else: data['region'] = value elif typ == 'grandfathered': # If we got here, we got a grandfathered tag but we were asked # not to normalize it, or the CLDR data doesn't know how to # normalize it. The best we can do is set the entire tag as the # language. data['language'] = value else: data[typ] = value result = Language.make(**data) Language._PARSE_CACHE[tag, normalize] = result return result
[ "def", "get", "(", "tag", ":", "{", "str", ",", "'Language'", "}", ",", "normalize", "=", "True", ")", "->", "'Language'", ":", "if", "isinstance", "(", "tag", ",", "Language", ")", ":", "if", "not", "normalize", ":", "# shortcut: we have the tag already", "return", "tag", "# We might need to normalize this tag. Convert it back into a", "# string tag, to cover all the edge cases of normalization in a", "# way that we've already solved.", "tag", "=", "tag", ".", "to_tag", "(", ")", "if", "(", "tag", ",", "normalize", ")", "in", "Language", ".", "_PARSE_CACHE", ":", "return", "Language", ".", "_PARSE_CACHE", "[", "tag", ",", "normalize", "]", "data", "=", "{", "}", "# if the complete tag appears as something to normalize, do the", "# normalization right away. Smash case when checking, because the", "# case normalization that comes from parse_tag() hasn't been applied", "# yet.", "tag_lower", "=", "tag", ".", "lower", "(", ")", "if", "normalize", "and", "tag_lower", "in", "LANGUAGE_REPLACEMENTS", ":", "tag", "=", "LANGUAGE_REPLACEMENTS", "[", "tag_lower", "]", "components", "=", "parse_tag", "(", "tag", ")", "for", "typ", ",", "value", "in", "components", ":", "if", "typ", "==", "'extlang'", "and", "normalize", "and", "'language'", "in", "data", ":", "# smash extlangs when possible", "minitag", "=", "'%s-%s'", "%", "(", "data", "[", "'language'", "]", ",", "value", ")", "norm", "=", "LANGUAGE_REPLACEMENTS", ".", "get", "(", "minitag", ".", "lower", "(", ")", ")", "if", "norm", "is", "not", "None", ":", "data", ".", "update", "(", "Language", ".", "get", "(", "norm", ",", "normalize", ")", ".", "to_dict", "(", ")", ")", "else", ":", "data", ".", "setdefault", "(", "'extlangs'", ",", "[", "]", ")", ".", "append", "(", "value", ")", "elif", "typ", "in", "{", "'extlang'", ",", "'variant'", ",", "'extension'", "}", ":", "data", ".", "setdefault", "(", "typ", "+", "'s'", ",", "[", "]", ")", ".", "append", "(", "value", ")", "elif", "typ", "==", "'language'", ":", "if", "value", "==", "'und'", ":", "pass", "elif", "normalize", ":", "replacement", "=", "LANGUAGE_REPLACEMENTS", ".", "get", "(", "value", ".", "lower", "(", ")", ")", "if", "replacement", "is", "not", "None", ":", "# parse the replacement if necessary -- this helps with", "# Serbian and Moldovan", "data", ".", "update", "(", "Language", ".", "get", "(", "replacement", ",", "normalize", ")", ".", "to_dict", "(", ")", ")", "else", ":", "data", "[", "'language'", "]", "=", "value", "else", ":", "data", "[", "'language'", "]", "=", "value", "elif", "typ", "==", "'region'", ":", "if", "normalize", ":", "data", "[", "'region'", "]", "=", "REGION_REPLACEMENTS", ".", "get", "(", "value", ".", "lower", "(", ")", ",", "value", ")", "else", ":", "data", "[", "'region'", "]", "=", "value", "elif", "typ", "==", "'grandfathered'", ":", "# If we got here, we got a grandfathered tag but we were asked", "# not to normalize it, or the CLDR data doesn't know how to", "# normalize it. The best we can do is set the entire tag as the", "# language.", "data", "[", "'language'", "]", "=", "value", "else", ":", "data", "[", "typ", "]", "=", "value", "result", "=", "Language", ".", "make", "(", "*", "*", "data", ")", "Language", ".", "_PARSE_CACHE", "[", "tag", ",", "normalize", "]", "=", "result", "return", "result" ]
39.39759
22.542169
def smart_cast2(var): r""" if the variable is a string tries to cast it to a reasonable value. maybe can just use eval. FIXME: funcname Args: var (unknown): Returns: unknown: some var CommandLine: python -m utool.util_type --test-smart_cast2 Example: >>> # ENABLE_DOCTEST >>> from utool.util_type import * # NOQA >>> import utool as ut >>> # build test data >>> var_list = ['?', 1, '1', '1.0', '1.2', 'True', None, 'None'] >>> # execute function >>> castvar_list = [smart_cast2(var) for var in var_list] >>> # verify results >>> result = ut.repr4(castvar_list, nl=False) >>> print(result) ['?', 1, 1, 1.0, 1.2, True, None, None] """ if var is None: return None if isinstance(var, six.string_types): castvar = None lower = var.lower() if lower == 'true': return True elif lower == 'false': return False elif lower == 'none': return None if var.startswith('[') and var.endswith(']'): #import re #subvar_list = re.split(r',\s*' + ut.negative_lookahead(r'[^\[\]]*\]'), var[1:-1]) return smart_cast(var[1:-1], list) elif var.startswith('(') and var.endswith(')'): #import re #subvar_list = re.split(r',\s*' + ut.negative_lookahead(r'[^\[\]]*\]'), var[1:-1]) return tuple(smart_cast(var[1:-1], list)) type_list = [int, float] for type_ in type_list: castvar = try_cast(var, type_) if castvar is not None: break if castvar is None: castvar = var else: castvar = var return castvar
[ "def", "smart_cast2", "(", "var", ")", ":", "if", "var", "is", "None", ":", "return", "None", "if", "isinstance", "(", "var", ",", "six", ".", "string_types", ")", ":", "castvar", "=", "None", "lower", "=", "var", ".", "lower", "(", ")", "if", "lower", "==", "'true'", ":", "return", "True", "elif", "lower", "==", "'false'", ":", "return", "False", "elif", "lower", "==", "'none'", ":", "return", "None", "if", "var", ".", "startswith", "(", "'['", ")", "and", "var", ".", "endswith", "(", "']'", ")", ":", "#import re", "#subvar_list = re.split(r',\\s*' + ut.negative_lookahead(r'[^\\[\\]]*\\]'), var[1:-1])", "return", "smart_cast", "(", "var", "[", "1", ":", "-", "1", "]", ",", "list", ")", "elif", "var", ".", "startswith", "(", "'('", ")", "and", "var", ".", "endswith", "(", "')'", ")", ":", "#import re", "#subvar_list = re.split(r',\\s*' + ut.negative_lookahead(r'[^\\[\\]]*\\]'), var[1:-1])", "return", "tuple", "(", "smart_cast", "(", "var", "[", "1", ":", "-", "1", "]", ",", "list", ")", ")", "type_list", "=", "[", "int", ",", "float", "]", "for", "type_", "in", "type_list", ":", "castvar", "=", "try_cast", "(", "var", ",", "type_", ")", "if", "castvar", "is", "not", "None", ":", "break", "if", "castvar", "is", "None", ":", "castvar", "=", "var", "else", ":", "castvar", "=", "var", "return", "castvar" ]
31.053571
18.178571
def set_cookie(self, key, value, expiration='Infinity', path='/', domain='', secure=False): """ expiration (int): seconds after with the cookie automatically gets deleted """ secure = 'true' if secure else 'false' self.app_instance.execute_javascript(""" var sKey = "%(sKey)s"; var sValue = "%(sValue)s"; var vEnd = eval("%(vEnd)s"); var sPath = "%(sPath)s"; var sDomain = "%(sDomain)s"; var bSecure = %(bSecure)s; if( (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) == false ){ var sExpires = ""; if (vEnd) { switch (vEnd.constructor) { case Number: sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd; break; case String: sExpires = "; expires=" + vEnd; break; case Date: sExpires = "; expires=" + vEnd.toUTCString(); break; } } document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : ""); } """%{'sKey': key, 'sValue': value, 'vEnd': expiration, 'sPath': path, 'sDomain': domain, 'bSecure': secure})
[ "def", "set_cookie", "(", "self", ",", "key", ",", "value", ",", "expiration", "=", "'Infinity'", ",", "path", "=", "'/'", ",", "domain", "=", "''", ",", "secure", "=", "False", ")", ":", "secure", "=", "'true'", "if", "secure", "else", "'false'", "self", ".", "app_instance", ".", "execute_javascript", "(", "\"\"\"\n var sKey = \"%(sKey)s\";\n var sValue = \"%(sValue)s\";\n var vEnd = eval(\"%(vEnd)s\");\n var sPath = \"%(sPath)s\"; \n var sDomain = \"%(sDomain)s\"; \n var bSecure = %(bSecure)s;\n if( (!sKey || /^(?:expires|max\\-age|path|domain|secure)$/i.test(sKey)) == false ){\n var sExpires = \"\";\n if (vEnd) {\n switch (vEnd.constructor) {\n case Number:\n sExpires = vEnd === Infinity ? \"; expires=Fri, 31 Dec 9999 23:59:59 GMT\" : \"; max-age=\" + vEnd;\n break;\n case String:\n sExpires = \"; expires=\" + vEnd;\n break;\n case Date:\n sExpires = \"; expires=\" + vEnd.toUTCString();\n break;\n }\n }\n document.cookie = encodeURIComponent(sKey) + \"=\" + encodeURIComponent(sValue) + sExpires + (sDomain ? \"; domain=\" + sDomain : \"\") + (sPath ? \"; path=\" + sPath : \"\") + (bSecure ? \"; secure\" : \"\");\n }\n \"\"\"", "%", "{", "'sKey'", ":", "key", ",", "'sValue'", ":", "value", ",", "'vEnd'", ":", "expiration", ",", "'sPath'", ":", "path", ",", "'sDomain'", ":", "domain", ",", "'bSecure'", ":", "secure", "}", ")" ]
50.064516
21.032258
def all_pairs(sets, similarity_func_name="jaccard", similarity_threshold=0.5): """Find all pairs of sets with similarity greater than a threshold. This is an implementation of the All-Pair-Binary algorithm in the paper "Scaling Up All Pairs Similarity Search" by Bayardo et al., with position filter enhancement. Args: sets (list): a list of sets, each entry is an iterable representing a set. similarity_func_name (str): the name of the similarity function used; this function currently supports `"jaccard"` and `"cosine"`. similarity_threshold (float): the threshold used, must be a float between 0 and 1.0. Returns: pairs (Iterator[tuple]): an iterator of tuples `(x, y, similarity)` where `x` and `y` are the indices of sets in the input list `sets`. """ if not isinstance(sets, list) or len(sets) == 0: raise ValueError("Input parameter sets must be a non-empty list.") if similarity_func_name not in _similarity_funcs: raise ValueError("Similarity function {} is not supported.".format( similarity_func_name)) if similarity_threshold < 0 or similarity_threshold > 1.0: raise ValueError("Similarity threshold must be in the range [0, 1].") if similarity_func_name not in _symmetric_similarity_funcs: raise ValueError("The similarity function must be symmetric " "({})".format(", ".join(_symmetric_similarity_funcs))) similarity_func = _similarity_funcs[similarity_func_name] overlap_threshold_func = _overlap_threshold_funcs[similarity_func_name] position_filter_func = _position_filter_funcs[similarity_func_name] sets, _ = _frequency_order_transform(sets) index = defaultdict(list) logging.debug("Find all pairs with similarities >= {}...".format( similarity_threshold)) count = 0 for x1 in np.argsort([len(s) for s in sets]): s1 = sets[x1] t = overlap_threshold_func(len(s1), similarity_threshold) prefix_size = len(s1) - t + 1 prefix = s1[:prefix_size] # Find candidates using tokens in the prefix. candidates = set([x2 for p1, token in enumerate(prefix) for x2, p2 in index[token] if position_filter_func(s1, sets[x2], p1, p2, similarity_threshold)]) for x2 in candidates: s2 = sets[x2] sim = similarity_func(s1, s2) if sim < similarity_threshold: continue # Output reverse-ordered set index pair (larger first). yield tuple(sorted([x1, x2], reverse=True) + [sim,]) count += 1 # Insert this prefix into index. for j, token in enumerate(prefix): index[token].append((x1, j)) logging.debug("{} pairs found.".format(count))
[ "def", "all_pairs", "(", "sets", ",", "similarity_func_name", "=", "\"jaccard\"", ",", "similarity_threshold", "=", "0.5", ")", ":", "if", "not", "isinstance", "(", "sets", ",", "list", ")", "or", "len", "(", "sets", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Input parameter sets must be a non-empty list.\"", ")", "if", "similarity_func_name", "not", "in", "_similarity_funcs", ":", "raise", "ValueError", "(", "\"Similarity function {} is not supported.\"", ".", "format", "(", "similarity_func_name", ")", ")", "if", "similarity_threshold", "<", "0", "or", "similarity_threshold", ">", "1.0", ":", "raise", "ValueError", "(", "\"Similarity threshold must be in the range [0, 1].\"", ")", "if", "similarity_func_name", "not", "in", "_symmetric_similarity_funcs", ":", "raise", "ValueError", "(", "\"The similarity function must be symmetric \"", "\"({})\"", ".", "format", "(", "\", \"", ".", "join", "(", "_symmetric_similarity_funcs", ")", ")", ")", "similarity_func", "=", "_similarity_funcs", "[", "similarity_func_name", "]", "overlap_threshold_func", "=", "_overlap_threshold_funcs", "[", "similarity_func_name", "]", "position_filter_func", "=", "_position_filter_funcs", "[", "similarity_func_name", "]", "sets", ",", "_", "=", "_frequency_order_transform", "(", "sets", ")", "index", "=", "defaultdict", "(", "list", ")", "logging", ".", "debug", "(", "\"Find all pairs with similarities >= {}...\"", ".", "format", "(", "similarity_threshold", ")", ")", "count", "=", "0", "for", "x1", "in", "np", ".", "argsort", "(", "[", "len", "(", "s", ")", "for", "s", "in", "sets", "]", ")", ":", "s1", "=", "sets", "[", "x1", "]", "t", "=", "overlap_threshold_func", "(", "len", "(", "s1", ")", ",", "similarity_threshold", ")", "prefix_size", "=", "len", "(", "s1", ")", "-", "t", "+", "1", "prefix", "=", "s1", "[", ":", "prefix_size", "]", "# Find candidates using tokens in the prefix.", "candidates", "=", "set", "(", "[", "x2", "for", "p1", ",", "token", "in", "enumerate", "(", "prefix", ")", "for", "x2", ",", "p2", "in", "index", "[", "token", "]", "if", "position_filter_func", "(", "s1", ",", "sets", "[", "x2", "]", ",", "p1", ",", "p2", ",", "similarity_threshold", ")", "]", ")", "for", "x2", "in", "candidates", ":", "s2", "=", "sets", "[", "x2", "]", "sim", "=", "similarity_func", "(", "s1", ",", "s2", ")", "if", "sim", "<", "similarity_threshold", ":", "continue", "# Output reverse-ordered set index pair (larger first).", "yield", "tuple", "(", "sorted", "(", "[", "x1", ",", "x2", "]", ",", "reverse", "=", "True", ")", "+", "[", "sim", ",", "]", ")", "count", "+=", "1", "# Insert this prefix into index.", "for", "j", ",", "token", "in", "enumerate", "(", "prefix", ")", ":", "index", "[", "token", "]", ".", "append", "(", "(", "x1", ",", "j", ")", ")", "logging", ".", "debug", "(", "\"{} pairs found.\"", ".", "format", "(", "count", ")", ")" ]
47.898305
19.118644
def _addUserToGroup(self, username, group="Clients"): """Add user to the goup """ portal_groups = api.portal.get_tool("portal_groups") group = portal_groups.getGroupById('Clients') group.addMember(username)
[ "def", "_addUserToGroup", "(", "self", ",", "username", ",", "group", "=", "\"Clients\"", ")", ":", "portal_groups", "=", "api", ".", "portal", ".", "get_tool", "(", "\"portal_groups\"", ")", "group", "=", "portal_groups", ".", "getGroupById", "(", "'Clients'", ")", "group", ".", "addMember", "(", "username", ")" ]
40.166667
8.833333
def query_domain(self, domain, typenames, domainquerytype='list', count=False): """ Query by property domain values """ objects = self._get_repo_filter(Layer.objects) if domainquerytype == 'range': return [tuple(objects.aggregate(Min(domain), Max(domain)).values())] else: if count: return [(d[domain], d['%s__count' % domain]) for d in objects.values(domain).annotate(Count(domain))] else: return objects.values_list(domain).distinct()
[ "def", "query_domain", "(", "self", ",", "domain", ",", "typenames", ",", "domainquerytype", "=", "'list'", ",", "count", "=", "False", ")", ":", "objects", "=", "self", ".", "_get_repo_filter", "(", "Layer", ".", "objects", ")", "if", "domainquerytype", "==", "'range'", ":", "return", "[", "tuple", "(", "objects", ".", "aggregate", "(", "Min", "(", "domain", ")", ",", "Max", "(", "domain", ")", ")", ".", "values", "(", ")", ")", "]", "else", ":", "if", "count", ":", "return", "[", "(", "d", "[", "domain", "]", ",", "d", "[", "'%s__count'", "%", "domain", "]", ")", "for", "d", "in", "objects", ".", "values", "(", "domain", ")", ".", "annotate", "(", "Count", "(", "domain", ")", ")", "]", "else", ":", "return", "objects", ".", "values_list", "(", "domain", ")", ".", "distinct", "(", ")" ]
37.6
21.733333
def is_in_plane(self, pp, dist_tolerance): """ Determines if point pp is in the plane within the tolerance dist_tolerance :param pp: point to be tested :param dist_tolerance: tolerance on the distance to the plane within which point pp is considered in the plane :return: True if pp is in the plane, False otherwise """ return np.abs(np.dot(self.normal_vector, pp) + self._coefficients[3]) <= dist_tolerance
[ "def", "is_in_plane", "(", "self", ",", "pp", ",", "dist_tolerance", ")", ":", "return", "np", ".", "abs", "(", "np", ".", "dot", "(", "self", ".", "normal_vector", ",", "pp", ")", "+", "self", ".", "_coefficients", "[", "3", "]", ")", "<=", "dist_tolerance" ]
57
25
def find_mean_vector(*args, **kwargs): """ Returns the mean vector for a set of measurments. By default, this expects the input to be plunges and bearings, but the type of input can be controlled through the ``measurement`` kwarg. Parameters ---------- *args : 2 or 3 sequences of measurements By default, this will be expected to be ``plunge`` & ``bearing``, both array-like sequences representing linear features. (Rake measurements require three parameters, thus the variable number of arguments.) The *measurement* kwarg controls how these arguments are interpreted. measurement : string, optional Controls how the input arguments are interpreted. Defaults to ``"lines"``. May be one of the following: ``"poles"`` : strikes, dips Arguments are assumed to be sequences of strikes and dips of planes. Poles to these planes are used for analysis. ``"lines"`` : plunges, bearings Arguments are assumed to be sequences of plunges and bearings of linear features. ``"rakes"`` : strikes, dips, rakes Arguments are assumed to be sequences of strikes, dips, and rakes along the plane. ``"radians"`` : lon, lat Arguments are assumed to be "raw" longitudes and latitudes in the stereonet's underlying coordinate system. Returns ------- mean_vector : tuple of two floats The plunge and bearing of the mean vector (in degrees). r_value : float The length of the mean vector (a value between 0 and 1). """ lon, lat = _convert_measurements(args, kwargs.get('measurement', 'lines')) vector, r_value = stereonet_math.mean_vector(lon, lat) plunge, bearing = stereonet_math.geographic2plunge_bearing(*vector) return (plunge[0], bearing[0]), r_value
[ "def", "find_mean_vector", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lon", ",", "lat", "=", "_convert_measurements", "(", "args", ",", "kwargs", ".", "get", "(", "'measurement'", ",", "'lines'", ")", ")", "vector", ",", "r_value", "=", "stereonet_math", ".", "mean_vector", "(", "lon", ",", "lat", ")", "plunge", ",", "bearing", "=", "stereonet_math", ".", "geographic2plunge_bearing", "(", "*", "vector", ")", "return", "(", "plunge", "[", "0", "]", ",", "bearing", "[", "0", "]", ")", ",", "r_value" ]
41.434783
23.478261
def calc_paired_insert_stats(in_bam, nsample=1000000): """Retrieve statistics for paired end read insert distances. """ dists = [] n = 0 with pysam.Samfile(in_bam, "rb") as in_pysam: for read in in_pysam: if read.is_proper_pair and read.is_read1: n += 1 dists.append(abs(read.isize)) if n >= nsample: break return insert_size_stats(dists)
[ "def", "calc_paired_insert_stats", "(", "in_bam", ",", "nsample", "=", "1000000", ")", ":", "dists", "=", "[", "]", "n", "=", "0", "with", "pysam", ".", "Samfile", "(", "in_bam", ",", "\"rb\"", ")", "as", "in_pysam", ":", "for", "read", "in", "in_pysam", ":", "if", "read", ".", "is_proper_pair", "and", "read", ".", "is_read1", ":", "n", "+=", "1", "dists", ".", "append", "(", "abs", "(", "read", ".", "isize", ")", ")", "if", "n", ">=", "nsample", ":", "break", "return", "insert_size_stats", "(", "dists", ")" ]
33.692308
11.923077
def create_sysdig_capture(self, hostname, capture_name, duration, capture_filter='', folder='/'): '''**Description** Create a new sysdig capture. The capture will be immediately started. **Arguments** - **hostname**: the hostname of the instrumented host where the capture will be taken. - **capture_name**: the name of the capture. - **duration**: the duration of the capture, in seconds. - **capture_filter**: a sysdig filter expression. - **folder**: directory in the S3 bucket where the capture will be saved. **Success Return Value** A dictionary showing the details of the new capture. **Example** `examples/create_sysdig_capture.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_sysdig_capture.py>`_ ''' res = self.get_connected_agents() if not res[0]: return res capture_agent = None for agent in res[1]: if hostname == agent['hostName']: capture_agent = agent break if capture_agent is None: return [False, hostname + ' not found'] data = { 'agent': capture_agent, 'name': capture_name, 'duration': duration, 'folder': folder, 'filters': capture_filter, 'bucketName': '', 'source': self.product } res = requests.post(self.url + '/api/sysdig', headers=self.hdrs, data=json.dumps(data), verify=self.ssl_verify) return self._request_result(res)
[ "def", "create_sysdig_capture", "(", "self", ",", "hostname", ",", "capture_name", ",", "duration", ",", "capture_filter", "=", "''", ",", "folder", "=", "'/'", ")", ":", "res", "=", "self", ".", "get_connected_agents", "(", ")", "if", "not", "res", "[", "0", "]", ":", "return", "res", "capture_agent", "=", "None", "for", "agent", "in", "res", "[", "1", "]", ":", "if", "hostname", "==", "agent", "[", "'hostName'", "]", ":", "capture_agent", "=", "agent", "break", "if", "capture_agent", "is", "None", ":", "return", "[", "False", ",", "hostname", "+", "' not found'", "]", "data", "=", "{", "'agent'", ":", "capture_agent", ",", "'name'", ":", "capture_name", ",", "'duration'", ":", "duration", ",", "'folder'", ":", "folder", ",", "'filters'", ":", "capture_filter", ",", "'bucketName'", ":", "''", ",", "'source'", ":", "self", ".", "product", "}", "res", "=", "requests", ".", "post", "(", "self", ".", "url", "+", "'/api/sysdig'", ",", "headers", "=", "self", ".", "hdrs", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
37.255814
25.348837
def rnaseq_prep_samples(config, run_info_yaml, parallel, dirs, samples): """ organizes RNA-seq and small-RNAseq samples, converting from BAM if necessary and trimming if necessary """ pipeline = dd.get_in_samples(samples, dd.get_analysis) trim_reads_set = any([tz.get_in(["algorithm", "trim_reads"], d) for d in dd.sample_data_iterator(samples)]) resources = ["picard"] needs_trimming = (_is_smallrnaseq(pipeline) or trim_reads_set) if needs_trimming: resources.append("atropos") with prun.start(_wres(parallel, resources), samples, config, dirs, "trimming", max_multicore=1 if not needs_trimming else None) as run_parallel: with profile.report("organize samples", dirs): samples = run_parallel("organize_samples", [[dirs, config, run_info_yaml, [x[0]["description"] for x in samples]]]) samples = run_parallel("prepare_sample", samples) if needs_trimming: with profile.report("adapter trimming", dirs): if _is_smallrnaseq(pipeline): samples = run_parallel("trim_srna_sample", samples) else: samples = run_parallel("trim_sample", samples) return samples
[ "def", "rnaseq_prep_samples", "(", "config", ",", "run_info_yaml", ",", "parallel", ",", "dirs", ",", "samples", ")", ":", "pipeline", "=", "dd", ".", "get_in_samples", "(", "samples", ",", "dd", ".", "get_analysis", ")", "trim_reads_set", "=", "any", "(", "[", "tz", ".", "get_in", "(", "[", "\"algorithm\"", ",", "\"trim_reads\"", "]", ",", "d", ")", "for", "d", "in", "dd", ".", "sample_data_iterator", "(", "samples", ")", "]", ")", "resources", "=", "[", "\"picard\"", "]", "needs_trimming", "=", "(", "_is_smallrnaseq", "(", "pipeline", ")", "or", "trim_reads_set", ")", "if", "needs_trimming", ":", "resources", ".", "append", "(", "\"atropos\"", ")", "with", "prun", ".", "start", "(", "_wres", "(", "parallel", ",", "resources", ")", ",", "samples", ",", "config", ",", "dirs", ",", "\"trimming\"", ",", "max_multicore", "=", "1", "if", "not", "needs_trimming", "else", "None", ")", "as", "run_parallel", ":", "with", "profile", ".", "report", "(", "\"organize samples\"", ",", "dirs", ")", ":", "samples", "=", "run_parallel", "(", "\"organize_samples\"", ",", "[", "[", "dirs", ",", "config", ",", "run_info_yaml", ",", "[", "x", "[", "0", "]", "[", "\"description\"", "]", "for", "x", "in", "samples", "]", "]", "]", ")", "samples", "=", "run_parallel", "(", "\"prepare_sample\"", ",", "samples", ")", "if", "needs_trimming", ":", "with", "profile", ".", "report", "(", "\"adapter trimming\"", ",", "dirs", ")", ":", "if", "_is_smallrnaseq", "(", "pipeline", ")", ":", "samples", "=", "run_parallel", "(", "\"trim_srna_sample\"", ",", "samples", ")", "else", ":", "samples", "=", "run_parallel", "(", "\"trim_sample\"", ",", "samples", ")", "return", "samples" ]
52.2
22.28
def cursor_up(self, count=None): """Move cursor up the indicated # of lines in same column. Cursor stops at top margin. :param int count: number of lines to skip. """ top, _bottom = self.margins or Margins(0, self.lines - 1) self.cursor.y = max(self.cursor.y - (count or 1), top)
[ "def", "cursor_up", "(", "self", ",", "count", "=", "None", ")", ":", "top", ",", "_bottom", "=", "self", ".", "margins", "or", "Margins", "(", "0", ",", "self", ".", "lines", "-", "1", ")", "self", ".", "cursor", ".", "y", "=", "max", "(", "self", ".", "cursor", ".", "y", "-", "(", "count", "or", "1", ")", ",", "top", ")" ]
40.125
13.75
def is_instance_throughput_too_low(self, inst_id): """ Return whether the throughput of the master instance is greater than the acceptable threshold """ r = self.instance_throughput_ratio(inst_id) if r is None: logger.debug("{} instance {} throughput is not " "measurable.".format(self, inst_id)) return None too_low = r < self.Delta if too_low: logger.display("{}{} instance {} throughput ratio {} is lower than Delta {}.". format(MONITORING_PREFIX, self, inst_id, r, self.Delta)) else: logger.trace("{} instance {} throughput ratio {} is acceptable.". format(self, inst_id, r)) return too_low
[ "def", "is_instance_throughput_too_low", "(", "self", ",", "inst_id", ")", ":", "r", "=", "self", ".", "instance_throughput_ratio", "(", "inst_id", ")", "if", "r", "is", "None", ":", "logger", ".", "debug", "(", "\"{} instance {} throughput is not \"", "\"measurable.\"", ".", "format", "(", "self", ",", "inst_id", ")", ")", "return", "None", "too_low", "=", "r", "<", "self", ".", "Delta", "if", "too_low", ":", "logger", ".", "display", "(", "\"{}{} instance {} throughput ratio {} is lower than Delta {}.\"", ".", "format", "(", "MONITORING_PREFIX", ",", "self", ",", "inst_id", ",", "r", ",", "self", ".", "Delta", ")", ")", "else", ":", "logger", ".", "trace", "(", "\"{} instance {} throughput ratio {} is acceptable.\"", ".", "format", "(", "self", ",", "inst_id", ",", "r", ")", ")", "return", "too_low" ]
43.444444
20.222222
def get_source_code(items): """ Extract source code of given items, and concatenate and dedent it. """ sources = [] prev_class_name = None for func in items: try: lines, lineno = inspect.getsourcelines(func) except TypeError: continue if not lines: continue src = "\n".join(line.rstrip() for line in lines) src = textwrap.dedent(src) class_name = None if inspect.ismethod(func): # Add class name if hasattr(func, 'im_class'): class_name = func.im_class.__name__ elif hasattr(func, '__qualname__'): names = func.__qualname__.split('.') if len(names) > 1: class_name = names[-2] if class_name and prev_class_name != class_name: src = "class {0}:\n {1}".format( class_name, src.replace("\n", "\n ")) elif class_name: src = " {1}".format( class_name, src.replace("\n", "\n ")) sources.append(src) prev_class_name = class_name return "\n\n".join(sources).rstrip()
[ "def", "get_source_code", "(", "items", ")", ":", "sources", "=", "[", "]", "prev_class_name", "=", "None", "for", "func", "in", "items", ":", "try", ":", "lines", ",", "lineno", "=", "inspect", ".", "getsourcelines", "(", "func", ")", "except", "TypeError", ":", "continue", "if", "not", "lines", ":", "continue", "src", "=", "\"\\n\"", ".", "join", "(", "line", ".", "rstrip", "(", ")", "for", "line", "in", "lines", ")", "src", "=", "textwrap", ".", "dedent", "(", "src", ")", "class_name", "=", "None", "if", "inspect", ".", "ismethod", "(", "func", ")", ":", "# Add class name", "if", "hasattr", "(", "func", ",", "'im_class'", ")", ":", "class_name", "=", "func", ".", "im_class", ".", "__name__", "elif", "hasattr", "(", "func", ",", "'__qualname__'", ")", ":", "names", "=", "func", ".", "__qualname__", ".", "split", "(", "'.'", ")", "if", "len", "(", "names", ")", ">", "1", ":", "class_name", "=", "names", "[", "-", "2", "]", "if", "class_name", "and", "prev_class_name", "!=", "class_name", ":", "src", "=", "\"class {0}:\\n {1}\"", ".", "format", "(", "class_name", ",", "src", ".", "replace", "(", "\"\\n\"", ",", "\"\\n \"", ")", ")", "elif", "class_name", ":", "src", "=", "\" {1}\"", ".", "format", "(", "class_name", ",", "src", ".", "replace", "(", "\"\\n\"", ",", "\"\\n \"", ")", ")", "sources", ".", "append", "(", "src", ")", "prev_class_name", "=", "class_name", "return", "\"\\n\\n\"", ".", "join", "(", "sources", ")", ".", "rstrip", "(", ")" ]
28.75
17.1
def process(self): """Periodic nonblocking processes""" super(NativeBLEVirtualInterface, self).process() if (not self._stream_sm_running) and (not self.reports.empty()): self._stream_data() if (not self._trace_sm_running) and (not self.traces.empty()): self._send_trace()
[ "def", "process", "(", "self", ")", ":", "super", "(", "NativeBLEVirtualInterface", ",", "self", ")", ".", "process", "(", ")", "if", "(", "not", "self", ".", "_stream_sm_running", ")", "and", "(", "not", "self", ".", "reports", ".", "empty", "(", ")", ")", ":", "self", ".", "_stream_data", "(", ")", "if", "(", "not", "self", ".", "_trace_sm_running", ")", "and", "(", "not", "self", ".", "traces", ".", "empty", "(", ")", ")", ":", "self", ".", "_send_trace", "(", ")" ]
32.1
23.9
def _get_artifact_context(run, file_type): """Gets the artifact details for the given run and file_type.""" sha1sum = None image_file = False log_file = False config_file = False if request.path == '/image': image_file = True if file_type == 'before': sha1sum = run.ref_image elif file_type == 'diff': sha1sum = run.diff_image elif file_type == 'after': sha1sum = run.image else: abort(400) elif request.path == '/log': log_file = True if file_type == 'before': sha1sum = run.ref_log elif file_type == 'diff': sha1sum = run.diff_log elif file_type == 'after': sha1sum = run.log else: abort(400) elif request.path == '/config': config_file = True if file_type == 'before': sha1sum = run.ref_config elif file_type == 'after': sha1sum = run.config else: abort(400) return image_file, log_file, config_file, sha1sum
[ "def", "_get_artifact_context", "(", "run", ",", "file_type", ")", ":", "sha1sum", "=", "None", "image_file", "=", "False", "log_file", "=", "False", "config_file", "=", "False", "if", "request", ".", "path", "==", "'/image'", ":", "image_file", "=", "True", "if", "file_type", "==", "'before'", ":", "sha1sum", "=", "run", ".", "ref_image", "elif", "file_type", "==", "'diff'", ":", "sha1sum", "=", "run", ".", "diff_image", "elif", "file_type", "==", "'after'", ":", "sha1sum", "=", "run", ".", "image", "else", ":", "abort", "(", "400", ")", "elif", "request", ".", "path", "==", "'/log'", ":", "log_file", "=", "True", "if", "file_type", "==", "'before'", ":", "sha1sum", "=", "run", ".", "ref_log", "elif", "file_type", "==", "'diff'", ":", "sha1sum", "=", "run", ".", "diff_log", "elif", "file_type", "==", "'after'", ":", "sha1sum", "=", "run", ".", "log", "else", ":", "abort", "(", "400", ")", "elif", "request", ".", "path", "==", "'/config'", ":", "config_file", "=", "True", "if", "file_type", "==", "'before'", ":", "sha1sum", "=", "run", ".", "ref_config", "elif", "file_type", "==", "'after'", ":", "sha1sum", "=", "run", ".", "config", "else", ":", "abort", "(", "400", ")", "return", "image_file", ",", "log_file", ",", "config_file", ",", "sha1sum" ]
28.567568
13
def match(self, command_context=None, **command_env): """ Check if context request is compatible with adapters specification. True - if compatible, False - otherwise :param command_context: context to check :param command_env: command environment :return: bool """ spec = self.specification() if command_context is None and spec is None: return True elif command_context is not None and spec is not None: return command_context == spec return False
[ "def", "match", "(", "self", ",", "command_context", "=", "None", ",", "*", "*", "command_env", ")", ":", "spec", "=", "self", ".", "specification", "(", ")", "if", "command_context", "is", "None", "and", "spec", "is", "None", ":", "return", "True", "elif", "command_context", "is", "not", "None", "and", "spec", "is", "not", "None", ":", "return", "command_context", "==", "spec", "return", "False" ]
33
13.857143
def get_store_profile_by_id(cls, store_profile_id, **kwargs): """Find StoreProfile Return single instance of StoreProfile by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_store_profile_by_id(store_profile_id, async=True) >>> result = thread.get() :param async bool :param str store_profile_id: ID of storeProfile to return (required) :return: StoreProfile If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._get_store_profile_by_id_with_http_info(store_profile_id, **kwargs) else: (data) = cls._get_store_profile_by_id_with_http_info(store_profile_id, **kwargs) return data
[ "def", "get_store_profile_by_id", "(", "cls", ",", "store_profile_id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_get_store_profile_by_id_with_http_info", "(", "store_profile_id", ",", "*", "*", "kwargs", ")", "else", ":", "(", "data", ")", "=", "cls", ".", "_get_store_profile_by_id_with_http_info", "(", "store_profile_id", ",", "*", "*", "kwargs", ")", "return", "data" ]
44.095238
21.857143
def prototype(self, name, argtypes, restype=None): """Define argument / return types for the specified C function""" function = self.function(name) function.argtypes = argtypes if restype: function.restype = restype
[ "def", "prototype", "(", "self", ",", "name", ",", "argtypes", ",", "restype", "=", "None", ")", ":", "function", "=", "self", ".", "function", "(", "name", ")", "function", ".", "argtypes", "=", "argtypes", "if", "restype", ":", "function", ".", "restype", "=", "restype" ]
42.333333
6.5
def read_umi_tools(filename: PathLike, dtype: str='float32') -> AnnData: """Read a gzipped condensed count matrix from umi_tools. Parameters ---------- filename File name to read from. """ # import pandas for conversion of a dict of dicts into a matrix # import gzip to read a gzipped file :-) import gzip from pandas import DataFrame dod = {} # this will contain basically everything fh = gzip.open(fspath(filename)) header = fh.readline() # read the first line for line in fh: t = line.decode('ascii').split('\t') # gzip read bytes, hence the decoding try: dod[t[1]].update({t[0]:int(t[2])}) except KeyError: dod[t[1]] = {t[0]:int(t[2])} df = DataFrame.from_dict(dod, orient='index') # build the matrix df.fillna(value=0., inplace=True) # many NaN, replace with zeros return AnnData(np.array(df), {'obs_names': df.index}, {'var_names': df.columns}, dtype=dtype)
[ "def", "read_umi_tools", "(", "filename", ":", "PathLike", ",", "dtype", ":", "str", "=", "'float32'", ")", "->", "AnnData", ":", "# import pandas for conversion of a dict of dicts into a matrix", "# import gzip to read a gzipped file :-)", "import", "gzip", "from", "pandas", "import", "DataFrame", "dod", "=", "{", "}", "# this will contain basically everything", "fh", "=", "gzip", ".", "open", "(", "fspath", "(", "filename", ")", ")", "header", "=", "fh", ".", "readline", "(", ")", "# read the first line", "for", "line", "in", "fh", ":", "t", "=", "line", ".", "decode", "(", "'ascii'", ")", ".", "split", "(", "'\\t'", ")", "# gzip read bytes, hence the decoding", "try", ":", "dod", "[", "t", "[", "1", "]", "]", ".", "update", "(", "{", "t", "[", "0", "]", ":", "int", "(", "t", "[", "2", "]", ")", "}", ")", "except", "KeyError", ":", "dod", "[", "t", "[", "1", "]", "]", "=", "{", "t", "[", "0", "]", ":", "int", "(", "t", "[", "2", "]", ")", "}", "df", "=", "DataFrame", ".", "from_dict", "(", "dod", ",", "orient", "=", "'index'", ")", "# build the matrix", "df", ".", "fillna", "(", "value", "=", "0.", ",", "inplace", "=", "True", ")", "# many NaN, replace with zeros", "return", "AnnData", "(", "np", ".", "array", "(", "df", ")", ",", "{", "'obs_names'", ":", "df", ".", "index", "}", ",", "{", "'var_names'", ":", "df", ".", "columns", "}", ",", "dtype", "=", "dtype", ")" ]
35.777778
22.259259
def from_filename(cls, filename, sync_from_start=True): """ Create a `Lexer` from a filename. """ # Inline imports: the Pygments dependency is optional! from pygments.util import ClassNotFound from pygments.lexers import get_lexer_for_filename try: pygments_lexer = get_lexer_for_filename(filename) except ClassNotFound: return SimpleLexer() else: return cls(pygments_lexer.__class__, sync_from_start=sync_from_start)
[ "def", "from_filename", "(", "cls", ",", "filename", ",", "sync_from_start", "=", "True", ")", ":", "# Inline imports: the Pygments dependency is optional!", "from", "pygments", ".", "util", "import", "ClassNotFound", "from", "pygments", ".", "lexers", "import", "get_lexer_for_filename", "try", ":", "pygments_lexer", "=", "get_lexer_for_filename", "(", "filename", ")", "except", "ClassNotFound", ":", "return", "SimpleLexer", "(", ")", "else", ":", "return", "cls", "(", "pygments_lexer", ".", "__class__", ",", "sync_from_start", "=", "sync_from_start", ")" ]
36.642857
17.071429
def validate(self, value, add_comments=False, schema_name="map"): """ verbose - also return the jsonschema error details """ validator = self.get_schema_validator(schema_name) error_messages = [] if isinstance(value, list): for d in value: error_messages += self._validate(d, validator, add_comments, schema_name) else: error_messages = self._validate(value, validator, add_comments, schema_name) return error_messages
[ "def", "validate", "(", "self", ",", "value", ",", "add_comments", "=", "False", ",", "schema_name", "=", "\"map\"", ")", ":", "validator", "=", "self", ".", "get_schema_validator", "(", "schema_name", ")", "error_messages", "=", "[", "]", "if", "isinstance", "(", "value", ",", "list", ")", ":", "for", "d", "in", "value", ":", "error_messages", "+=", "self", ".", "_validate", "(", "d", ",", "validator", ",", "add_comments", ",", "schema_name", ")", "else", ":", "error_messages", "=", "self", ".", "_validate", "(", "value", ",", "validator", ",", "add_comments", ",", "schema_name", ")", "return", "error_messages" ]
34.066667
23.133333
def sendMessage(self, data): """ Send websocket data frame to the client. If data is a unicode object then the frame is sent as Text. If the data is a bytearray object then the frame is sent as Binary. """ opcode = BINARY if _check_unicode(data): opcode = TEXT self._sendMessage(False, opcode, data)
[ "def", "sendMessage", "(", "self", ",", "data", ")", ":", "opcode", "=", "BINARY", "if", "_check_unicode", "(", "data", ")", ":", "opcode", "=", "TEXT", "self", ".", "_sendMessage", "(", "False", ",", "opcode", ",", "data", ")" ]
34.363636
16.363636
def import_submodules(name, submodules=None): """Import all submodules for a package/module name""" sys.path.insert(0, name) if submodules: for submodule in submodules: import_string('{0}.{1}'.format(name, submodule)) else: for item in pkgutil.walk_packages([name]): import_string('{0}.{1}'.format(name, item[1]))
[ "def", "import_submodules", "(", "name", ",", "submodules", "=", "None", ")", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "name", ")", "if", "submodules", ":", "for", "submodule", "in", "submodules", ":", "import_string", "(", "'{0}.{1}'", ".", "format", "(", "name", ",", "submodule", ")", ")", "else", ":", "for", "item", "in", "pkgutil", ".", "walk_packages", "(", "[", "name", "]", ")", ":", "import_string", "(", "'{0}.{1}'", ".", "format", "(", "name", ",", "item", "[", "1", "]", ")", ")" ]
40.111111
13.555556
def next_release(major=False, minor=False, patch=True): """Get next release version (by major, minor or patch)""" import semantic_version prev = run('git describe --abbrev=0 --tags', warn=True, hide=True).stdout or '0.0.0' ver = semantic_version.Version.coerce(prev.strip()) print('current version:', ver) if major: print('next major release:', ver.next_major()) return ver.next_major() if minor: print('next minor release:', ver.next_minor()) return ver.next_minor() if patch: print('next patch release:', ver.next_patch()) return ver.next_patch() print('next release <undefined>') return None
[ "def", "next_release", "(", "major", "=", "False", ",", "minor", "=", "False", ",", "patch", "=", "True", ")", ":", "import", "semantic_version", "prev", "=", "run", "(", "'git describe --abbrev=0 --tags'", ",", "warn", "=", "True", ",", "hide", "=", "True", ")", ".", "stdout", "or", "'0.0.0'", "ver", "=", "semantic_version", ".", "Version", ".", "coerce", "(", "prev", ".", "strip", "(", ")", ")", "print", "(", "'current version:'", ",", "ver", ")", "if", "major", ":", "print", "(", "'next major release:'", ",", "ver", ".", "next_major", "(", ")", ")", "return", "ver", ".", "next_major", "(", ")", "if", "minor", ":", "print", "(", "'next minor release:'", ",", "ver", ".", "next_minor", "(", ")", ")", "return", "ver", ".", "next_minor", "(", ")", "if", "patch", ":", "print", "(", "'next patch release:'", ",", "ver", ".", "next_patch", "(", ")", ")", "return", "ver", ".", "next_patch", "(", ")", "print", "(", "'next release <undefined>'", ")", "return", "None" ]
35.052632
18.684211
def get_property_names(self, is_allprop): """Return list of supported property names in Clark Notation. See DAVResource.get_property_names() """ # Let base class implementation add supported live and dead properties propNameList = super(VirtualResource, self).get_property_names(is_allprop) # Add custom live properties (report on 'allprop' and 'propnames') propNameList.extend(VirtualResource._supportedProps) return propNameList
[ "def", "get_property_names", "(", "self", ",", "is_allprop", ")", ":", "# Let base class implementation add supported live and dead properties", "propNameList", "=", "super", "(", "VirtualResource", ",", "self", ")", ".", "get_property_names", "(", "is_allprop", ")", "# Add custom live properties (report on 'allprop' and 'propnames')", "propNameList", ".", "extend", "(", "VirtualResource", ".", "_supportedProps", ")", "return", "propNameList" ]
48.6
19.2
def check(id_): """Check bibdocs.""" BibRecDocs, BibDoc = _import_bibdoc() try: BibDoc(id_).list_all_files() except Exception: click.secho("BibDoc {0} failed check.".format(id_), fg='red')
[ "def", "check", "(", "id_", ")", ":", "BibRecDocs", ",", "BibDoc", "=", "_import_bibdoc", "(", ")", "try", ":", "BibDoc", "(", "id_", ")", ".", "list_all_files", "(", ")", "except", "Exception", ":", "click", ".", "secho", "(", "\"BibDoc {0} failed check.\"", ".", "format", "(", "id_", ")", ",", "fg", "=", "'red'", ")" ]
26.75
18.75
def set_command_attributes(self, name, attributes): """ Sets the xml attributes of a specified command. """ if self.command_exists(name): command = self.commands.get(name) command['attributes'] = attributes
[ "def", "set_command_attributes", "(", "self", ",", "name", ",", "attributes", ")", ":", "if", "self", ".", "command_exists", "(", "name", ")", ":", "command", "=", "self", ".", "commands", ".", "get", "(", "name", ")", "command", "[", "'attributes'", "]", "=", "attributes" ]
48.4
5
def get_environ(self, key, default=None, cast=None): """Get value from environment variable using os.environ.get :param key: The name of the setting value, will always be upper case :param default: In case of not found it will be returned :param cast: Should cast in to @int, @float, @bool or @json ? or cast must be true to use cast inference :return: The value if found, default or None """ key = key.upper() data = self.environ.get(key, default) if data: if cast in converters: data = converters.get(cast)(data) if cast is True: data = parse_conf_data(data, tomlfy=True) return data
[ "def", "get_environ", "(", "self", ",", "key", ",", "default", "=", "None", ",", "cast", "=", "None", ")", ":", "key", "=", "key", ".", "upper", "(", ")", "data", "=", "self", ".", "environ", ".", "get", "(", "key", ",", "default", ")", "if", "data", ":", "if", "cast", "in", "converters", ":", "data", "=", "converters", ".", "get", "(", "cast", ")", "(", "data", ")", "if", "cast", "is", "True", ":", "data", "=", "parse_conf_data", "(", "data", ",", "tomlfy", "=", "True", ")", "return", "data" ]
42.058824
16.058824
def create_namespaced_deployment_rollback(self, name, namespace, body, **kwargs): # noqa: E501 """create_namespaced_deployment_rollback # noqa: E501 create rollback of a Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_deployment_rollback(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the DeploymentRollback (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param ExtensionsV1beta1DeploymentRollback body: (required) :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param bool include_uninitialized: If IncludeUninitialized is specified, the object may be returned without completing initialization. :param str pretty: If 'true', then the output is pretty printed. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.create_namespaced_deployment_rollback_with_http_info(name, namespace, body, **kwargs) # noqa: E501 else: (data) = self.create_namespaced_deployment_rollback_with_http_info(name, namespace, body, **kwargs) # noqa: E501 return data
[ "def", "create_namespaced_deployment_rollback", "(", "self", ",", "name", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "create_namespaced_deployment_rollback_with_http_info", "(", "name", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "create_namespaced_deployment_rollback_with_http_info", "(", "name", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
66.653846
39.384615
def get_scrollbar_position_height(self): """Return the pixel span height of the scrollbar area in which the slider handle may move""" vsb = self.editor.verticalScrollBar() style = vsb.style() opt = QStyleOptionSlider() vsb.initStyleOption(opt) # Get the area in which the slider handle may move. groove_rect = style.subControlRect( QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarGroove, self) return float(groove_rect.height())
[ "def", "get_scrollbar_position_height", "(", "self", ")", ":", "vsb", "=", "self", ".", "editor", ".", "verticalScrollBar", "(", ")", "style", "=", "vsb", ".", "style", "(", ")", "opt", "=", "QStyleOptionSlider", "(", ")", "vsb", ".", "initStyleOption", "(", "opt", ")", "# Get the area in which the slider handle may move.", "groove_rect", "=", "style", ".", "subControlRect", "(", "QStyle", ".", "CC_ScrollBar", ",", "opt", ",", "QStyle", ".", "SC_ScrollBarGroove", ",", "self", ")", "return", "float", "(", "groove_rect", ".", "height", "(", ")", ")" ]
38.692308
13.076923
def addMenuLabel(menu, text): """Adds a QLabel contaning text to the given menu""" qaw = QWidgetAction(menu) lab = QLabel(text, menu) qaw.setDefaultWidget(lab) lab.setAlignment(Qt.AlignCenter) lab.setFrameShape(QFrame.StyledPanel) lab.setFrameShadow(QFrame.Sunken) menu.addAction(qaw) return lab
[ "def", "addMenuLabel", "(", "menu", ",", "text", ")", ":", "qaw", "=", "QWidgetAction", "(", "menu", ")", "lab", "=", "QLabel", "(", "text", ",", "menu", ")", "qaw", ".", "setDefaultWidget", "(", "lab", ")", "lab", ".", "setAlignment", "(", "Qt", ".", "AlignCenter", ")", "lab", ".", "setFrameShape", "(", "QFrame", ".", "StyledPanel", ")", "lab", ".", "setFrameShadow", "(", "QFrame", ".", "Sunken", ")", "menu", ".", "addAction", "(", "qaw", ")", "return", "lab" ]
32.2
9.6
def read(self, vals): """Read values. Args: vals (list): list of strings representing values """ i = 0 if len(vals[i]) == 0: self.ground_temperature_depth = None else: self.ground_temperature_depth = vals[i] i += 1 if len(vals[i]) == 0: self.depth_soil_conductivity = None else: self.depth_soil_conductivity = vals[i] i += 1 if len(vals[i]) == 0: self.depth_soil_density = None else: self.depth_soil_density = vals[i] i += 1 if len(vals[i]) == 0: self.depth_soil_specific_heat = None else: self.depth_soil_specific_heat = vals[i] i += 1 if len(vals[i]) == 0: self.depth_january_average_ground_temperature = None else: self.depth_january_average_ground_temperature = vals[i] i += 1 if len(vals[i]) == 0: self.depth_february_average_ground_temperature = None else: self.depth_february_average_ground_temperature = vals[i] i += 1 if len(vals[i]) == 0: self.depth_march_average_ground_temperature = None else: self.depth_march_average_ground_temperature = vals[i] i += 1 if len(vals[i]) == 0: self.depth_april_average_ground_temperature = None else: self.depth_april_average_ground_temperature = vals[i] i += 1 if len(vals[i]) == 0: self.depth_may_average_ground_temperature = None else: self.depth_may_average_ground_temperature = vals[i] i += 1 if len(vals[i]) == 0: self.depth_june_average_ground_temperature = None else: self.depth_june_average_ground_temperature = vals[i] i += 1 if len(vals[i]) == 0: self.depth_july_average_ground_temperature = None else: self.depth_july_average_ground_temperature = vals[i] i += 1 if len(vals[i]) == 0: self.depth_august_average_ground_temperature = None else: self.depth_august_average_ground_temperature = vals[i] i += 1 if len(vals[i]) == 0: self.depth_september_average_ground_temperature = None else: self.depth_september_average_ground_temperature = vals[i] i += 1 if len(vals[i]) == 0: self.depth_october_average_ground_temperature = None else: self.depth_october_average_ground_temperature = vals[i] i += 1 if len(vals[i]) == 0: self.depth_november_average_ground_temperature = None else: self.depth_november_average_ground_temperature = vals[i] i += 1 if len(vals[i]) == 0: self.depth_december_average_ground_temperature = None else: self.depth_december_average_ground_temperature = vals[i] i += 1
[ "def", "read", "(", "self", ",", "vals", ")", ":", "i", "=", "0", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "ground_temperature_depth", "=", "None", "else", ":", "self", ".", "ground_temperature_depth", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "depth_soil_conductivity", "=", "None", "else", ":", "self", ".", "depth_soil_conductivity", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "depth_soil_density", "=", "None", "else", ":", "self", ".", "depth_soil_density", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "depth_soil_specific_heat", "=", "None", "else", ":", "self", ".", "depth_soil_specific_heat", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "depth_january_average_ground_temperature", "=", "None", "else", ":", "self", ".", "depth_january_average_ground_temperature", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "depth_february_average_ground_temperature", "=", "None", "else", ":", "self", ".", "depth_february_average_ground_temperature", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "depth_march_average_ground_temperature", "=", "None", "else", ":", "self", ".", "depth_march_average_ground_temperature", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "depth_april_average_ground_temperature", "=", "None", "else", ":", "self", ".", "depth_april_average_ground_temperature", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "depth_may_average_ground_temperature", "=", "None", "else", ":", "self", ".", "depth_may_average_ground_temperature", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "depth_june_average_ground_temperature", "=", "None", "else", ":", "self", ".", "depth_june_average_ground_temperature", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "depth_july_average_ground_temperature", "=", "None", "else", ":", "self", ".", "depth_july_average_ground_temperature", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "depth_august_average_ground_temperature", "=", "None", "else", ":", "self", ".", "depth_august_average_ground_temperature", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "depth_september_average_ground_temperature", "=", "None", "else", ":", "self", ".", "depth_september_average_ground_temperature", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "depth_october_average_ground_temperature", "=", "None", "else", ":", "self", ".", "depth_october_average_ground_temperature", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "depth_november_average_ground_temperature", "=", "None", "else", ":", "self", ".", "depth_november_average_ground_temperature", "=", "vals", "[", "i", "]", "i", "+=", "1", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "depth_december_average_ground_temperature", "=", "None", "else", ":", "self", ".", "depth_december_average_ground_temperature", "=", "vals", "[", "i", "]", "i", "+=", "1" ]
33.761364
21.034091
def actualize (self, scanner = None): """ Generates all the actual targets and sets up build actions for this target. If 'scanner' is specified, creates an additional target with the same location as actual target, which will depend on the actual target and be associated with 'scanner'. That additional target is returned. See the docs (#dependency_scanning) for rationale. Target must correspond to a file if 'scanner' is specified. If scanner is not specified, then actual target is returned. """ if __debug__: from .scanner import Scanner assert scanner is None or isinstance(scanner, Scanner) actual_name = self.actualize_no_scanner () if self.always_: bjam.call("ALWAYS", actual_name) if not scanner: return actual_name else: # Add the scanner instance to the grist for name. g = '-'.join ([ungrist(get_grist(actual_name)), str(id(scanner))]) name = replace_grist (actual_name, '<' + g + '>') if name not in self.made_: self.made_ [name] = True self.project_.manager ().engine ().add_dependency (name, actual_name) self.actualize_location (name) self.project_.manager ().scanners ().install (scanner, name, str (self)) return name
[ "def", "actualize", "(", "self", ",", "scanner", "=", "None", ")", ":", "if", "__debug__", ":", "from", ".", "scanner", "import", "Scanner", "assert", "scanner", "is", "None", "or", "isinstance", "(", "scanner", ",", "Scanner", ")", "actual_name", "=", "self", ".", "actualize_no_scanner", "(", ")", "if", "self", ".", "always_", ":", "bjam", ".", "call", "(", "\"ALWAYS\"", ",", "actual_name", ")", "if", "not", "scanner", ":", "return", "actual_name", "else", ":", "# Add the scanner instance to the grist for name.", "g", "=", "'-'", ".", "join", "(", "[", "ungrist", "(", "get_grist", "(", "actual_name", ")", ")", ",", "str", "(", "id", "(", "scanner", ")", ")", "]", ")", "name", "=", "replace_grist", "(", "actual_name", ",", "'<'", "+", "g", "+", "'>'", ")", "if", "name", "not", "in", "self", ".", "made_", ":", "self", ".", "made_", "[", "name", "]", "=", "True", "self", ".", "project_", ".", "manager", "(", ")", ".", "engine", "(", ")", ".", "add_dependency", "(", "name", ",", "actual_name", ")", "self", ".", "actualize_location", "(", "name", ")", "self", ".", "project_", ".", "manager", "(", ")", ".", "scanners", "(", ")", ".", "install", "(", "scanner", ",", "name", ",", "str", "(", "self", ")", ")", "return", "name" ]
36.435897
25.384615
def update_edge_keys(G): """ Update the keys of edges that share a u, v with another edge but differ in geometry. For example, two one-way streets from u to v that bow away from each other as separate streets, rather than opposite direction edges of a single street. Parameters ---------- G : networkx multidigraph Returns ------- networkx multigraph """ # identify all the edges that are duplicates based on a sorted combination # of their origin, destination, and key. that is, edge uv will match edge vu # as a duplicate, but only if they have the same key edges = graph_to_gdfs(G, nodes=False, fill_edge_geometry=False) edges['uvk'] = edges.apply(lambda row: '_'.join(sorted([str(row['u']), str(row['v'])]) + [str(row['key'])]), axis=1) edges['dupe'] = edges['uvk'].duplicated(keep=False) dupes = edges[edges['dupe']==True].dropna(subset=['geometry']) different_streets = [] groups = dupes[['geometry', 'uvk', 'u', 'v', 'key', 'dupe']].groupby('uvk') # for each set of duplicate edges for label, group in groups: # if there are more than 2 edges here, make sure to compare all if len(group['geometry']) > 2: l = group['geometry'].tolist() l.append(l[0]) geom_pairs = list(zip(l[:-1], l[1:])) # otherwise, just compare the first edge to the second edge else: geom_pairs = [(group['geometry'].iloc[0], group['geometry'].iloc[1])] # for each pair of edges to compare for geom1, geom2 in geom_pairs: # if they don't have the same geometry, flag them as different streets if not is_same_geometry(geom1, geom2): # add edge uvk, but not edge vuk, otherwise we'll iterate both their keys # and they'll still duplicate each other at the end of this process different_streets.append((group['u'].iloc[0], group['v'].iloc[0], group['key'].iloc[0])) # for each unique different street, iterate its key + 1 so it's unique for u, v, k in set(different_streets): # filter out key if it appears in data dict as we'll pass it explicitly attributes = {k:v for k, v in G[u][v][k].items() if k != 'key'} G.add_edge(u, v, key=k+1, **attributes) G.remove_edge(u, v, key=k) return G
[ "def", "update_edge_keys", "(", "G", ")", ":", "# identify all the edges that are duplicates based on a sorted combination", "# of their origin, destination, and key. that is, edge uv will match edge vu", "# as a duplicate, but only if they have the same key", "edges", "=", "graph_to_gdfs", "(", "G", ",", "nodes", "=", "False", ",", "fill_edge_geometry", "=", "False", ")", "edges", "[", "'uvk'", "]", "=", "edges", ".", "apply", "(", "lambda", "row", ":", "'_'", ".", "join", "(", "sorted", "(", "[", "str", "(", "row", "[", "'u'", "]", ")", ",", "str", "(", "row", "[", "'v'", "]", ")", "]", ")", "+", "[", "str", "(", "row", "[", "'key'", "]", ")", "]", ")", ",", "axis", "=", "1", ")", "edges", "[", "'dupe'", "]", "=", "edges", "[", "'uvk'", "]", ".", "duplicated", "(", "keep", "=", "False", ")", "dupes", "=", "edges", "[", "edges", "[", "'dupe'", "]", "==", "True", "]", ".", "dropna", "(", "subset", "=", "[", "'geometry'", "]", ")", "different_streets", "=", "[", "]", "groups", "=", "dupes", "[", "[", "'geometry'", ",", "'uvk'", ",", "'u'", ",", "'v'", ",", "'key'", ",", "'dupe'", "]", "]", ".", "groupby", "(", "'uvk'", ")", "# for each set of duplicate edges", "for", "label", ",", "group", "in", "groups", ":", "# if there are more than 2 edges here, make sure to compare all", "if", "len", "(", "group", "[", "'geometry'", "]", ")", ">", "2", ":", "l", "=", "group", "[", "'geometry'", "]", ".", "tolist", "(", ")", "l", ".", "append", "(", "l", "[", "0", "]", ")", "geom_pairs", "=", "list", "(", "zip", "(", "l", "[", ":", "-", "1", "]", ",", "l", "[", "1", ":", "]", ")", ")", "# otherwise, just compare the first edge to the second edge", "else", ":", "geom_pairs", "=", "[", "(", "group", "[", "'geometry'", "]", ".", "iloc", "[", "0", "]", ",", "group", "[", "'geometry'", "]", ".", "iloc", "[", "1", "]", ")", "]", "# for each pair of edges to compare", "for", "geom1", ",", "geom2", "in", "geom_pairs", ":", "# if they don't have the same geometry, flag them as different streets", "if", "not", "is_same_geometry", "(", "geom1", ",", "geom2", ")", ":", "# add edge uvk, but not edge vuk, otherwise we'll iterate both their keys", "# and they'll still duplicate each other at the end of this process", "different_streets", ".", "append", "(", "(", "group", "[", "'u'", "]", ".", "iloc", "[", "0", "]", ",", "group", "[", "'v'", "]", ".", "iloc", "[", "0", "]", ",", "group", "[", "'key'", "]", ".", "iloc", "[", "0", "]", ")", ")", "# for each unique different street, iterate its key + 1 so it's unique", "for", "u", ",", "v", ",", "k", "in", "set", "(", "different_streets", ")", ":", "# filter out key if it appears in data dict as we'll pass it explicitly", "attributes", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "G", "[", "u", "]", "[", "v", "]", "[", "k", "]", ".", "items", "(", ")", "if", "k", "!=", "'key'", "}", "G", ".", "add_edge", "(", "u", ",", "v", ",", "key", "=", "k", "+", "1", ",", "*", "*", "attributes", ")", "G", ".", "remove_edge", "(", "u", ",", "v", ",", "key", "=", "k", ")", "return", "G" ]
42.654545
26.254545
def dlogpdf_dlink(self, link_f, y, Y_metadata=None): """ Gradient of the log likelihood function at y, given link(f) w.r.t link(f) .. math:: \\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)} = \\beta (\\log \\beta y_{i}) - \\Psi(\\alpha_{i})\\beta\\\\ \\alpha_{i} = \\beta y_{i} :param link_f: latent variables (f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: Y_metadata which is not used in gamma distribution :returns: gradient of likelihood evaluated at points :rtype: Nx1 array """ grad = self.beta*np.log(self.beta*y) - special.psi(self.beta*link_f)*self.beta #old #return -self.gp_link.dtransf_df(gp)*self.beta*np.log(obs) + special.psi(self.gp_link.transf(gp)*self.beta) * self.gp_link.dtransf_df(gp)*self.beta return grad
[ "def", "dlogpdf_dlink", "(", "self", ",", "link_f", ",", "y", ",", "Y_metadata", "=", "None", ")", ":", "grad", "=", "self", ".", "beta", "*", "np", ".", "log", "(", "self", ".", "beta", "*", "y", ")", "-", "special", ".", "psi", "(", "self", ".", "beta", "*", "link_f", ")", "*", "self", ".", "beta", "#old", "#return -self.gp_link.dtransf_df(gp)*self.beta*np.log(obs) + special.psi(self.gp_link.transf(gp)*self.beta) * self.gp_link.dtransf_df(gp)*self.beta", "return", "grad" ]
42.47619
29.047619
def run_mp(songs): """ Concurrently calls get_lyrics to fetch the lyrics of a large list of songs. """ stats = Stats() if CONFIG['debug']: good = open('found', 'w') bad = open('notfound', 'w') logger.debug('Launching a pool of %d processes\n', CONFIG['jobcount']) chunksize = math.ceil(len(songs) / os.cpu_count()) try: with Pool(CONFIG['jobcount']) as pool: for result in pool.imap_unordered(get_lyrics, songs, chunksize): if result is None: continue for source, runtime in result.runtimes.items(): stats.add_result(source, result.source == source, runtime) found = process_result(result) if CONFIG['debug']: if found: good.write(f'{id_source(source)}: {result.song}\n') good.flush() else: bad.write(str(result.song) + '\n') bad.flush() finally: if CONFIG['debug']: good.close() bad.close() return stats
[ "def", "run_mp", "(", "songs", ")", ":", "stats", "=", "Stats", "(", ")", "if", "CONFIG", "[", "'debug'", "]", ":", "good", "=", "open", "(", "'found'", ",", "'w'", ")", "bad", "=", "open", "(", "'notfound'", ",", "'w'", ")", "logger", ".", "debug", "(", "'Launching a pool of %d processes\\n'", ",", "CONFIG", "[", "'jobcount'", "]", ")", "chunksize", "=", "math", ".", "ceil", "(", "len", "(", "songs", ")", "/", "os", ".", "cpu_count", "(", ")", ")", "try", ":", "with", "Pool", "(", "CONFIG", "[", "'jobcount'", "]", ")", "as", "pool", ":", "for", "result", "in", "pool", ".", "imap_unordered", "(", "get_lyrics", ",", "songs", ",", "chunksize", ")", ":", "if", "result", "is", "None", ":", "continue", "for", "source", ",", "runtime", "in", "result", ".", "runtimes", ".", "items", "(", ")", ":", "stats", ".", "add_result", "(", "source", ",", "result", ".", "source", "==", "source", ",", "runtime", ")", "found", "=", "process_result", "(", "result", ")", "if", "CONFIG", "[", "'debug'", "]", ":", "if", "found", ":", "good", ".", "write", "(", "f'{id_source(source)}: {result.song}\\n'", ")", "good", ".", "flush", "(", ")", "else", ":", "bad", ".", "write", "(", "str", "(", "result", ".", "song", ")", "+", "'\\n'", ")", "bad", ".", "flush", "(", ")", "finally", ":", "if", "CONFIG", "[", "'debug'", "]", ":", "good", ".", "close", "(", ")", "bad", ".", "close", "(", ")", "return", "stats" ]
32.085714
20.257143
def write(self, filename=None): """Write array to xvg file *filename* in NXY format. .. Note:: Only plain files working at the moment, not compressed. """ self._init_filename(filename) with utilities.openany(self.real_filename, 'w') as xvg: xvg.write("# xmgrace compatible NXY data file\n" "# Written by gromacs.formats.XVG()\n") xvg.write("# :columns: {0!r}\n".format(self.names)) for xyy in self.array.T: xyy.tofile(xvg, sep=" ", format="%-8s") # quick and dirty ascii output...--no compression! xvg.write('\n')
[ "def", "write", "(", "self", ",", "filename", "=", "None", ")", ":", "self", ".", "_init_filename", "(", "filename", ")", "with", "utilities", ".", "openany", "(", "self", ".", "real_filename", ",", "'w'", ")", "as", "xvg", ":", "xvg", ".", "write", "(", "\"# xmgrace compatible NXY data file\\n\"", "\"# Written by gromacs.formats.XVG()\\n\"", ")", "xvg", ".", "write", "(", "\"# :columns: {0!r}\\n\"", ".", "format", "(", "self", ".", "names", ")", ")", "for", "xyy", "in", "self", ".", "array", ".", "T", ":", "xyy", ".", "tofile", "(", "xvg", ",", "sep", "=", "\" \"", ",", "format", "=", "\"%-8s\"", ")", "# quick and dirty ascii output...--no compression!", "xvg", ".", "write", "(", "'\\n'", ")" ]
48.692308
19.384615
def close(self, code=3000, message='Go away!'): """ Close session. @param code: Closing code @param message: Closing message """ if self.state != SESSION_STATE.CLOSED: # Notify handler if self.handler is not None: self.handler.send_pack(proto.disconnect(code, message)) super(Session, self).close(code, message)
[ "def", "close", "(", "self", ",", "code", "=", "3000", ",", "message", "=", "'Go away!'", ")", ":", "if", "self", ".", "state", "!=", "SESSION_STATE", ".", "CLOSED", ":", "# Notify handler", "if", "self", ".", "handler", "is", "not", "None", ":", "self", ".", "handler", ".", "send_pack", "(", "proto", ".", "disconnect", "(", "code", ",", "message", ")", ")", "super", "(", "Session", ",", "self", ")", ".", "close", "(", "code", ",", "message", ")" ]
30
14.846154
def infix(self, node, children): 'infix = "(" expr operator expr ")"' _, expr1, operator, expr2, _ = children return operator(expr1, expr2)
[ "def", "infix", "(", "self", ",", "node", ",", "children", ")", ":", "_", ",", "expr1", ",", "operator", ",", "expr2", ",", "_", "=", "children", "return", "operator", "(", "expr1", ",", "expr2", ")" ]
40
5.5
def should_skip_file(name): """ Checks if a file should be skipped based on its name. If it should be skipped, returns the reason, otherwise returns None. """ if name.startswith('.'): return 'Skipping hidden file %(filename)s' if name.endswith('~') or name.endswith('.bak'): return 'Skipping backup file %(filename)s' if name.endswith('.pyc') or name.endswith('.pyo'): return 'Skipping %s file ' % os.path.splitext(name)[1] + '%(filename)s' if name.endswith('$py.class'): return 'Skipping $py.class file %(filename)s' if name in ('CVS', '_darcs'): return 'Skipping version control directory %(filename)s' return None
[ "def", "should_skip_file", "(", "name", ")", ":", "if", "name", ".", "startswith", "(", "'.'", ")", ":", "return", "'Skipping hidden file %(filename)s'", "if", "name", ".", "endswith", "(", "'~'", ")", "or", "name", ".", "endswith", "(", "'.bak'", ")", ":", "return", "'Skipping backup file %(filename)s'", "if", "name", ".", "endswith", "(", "'.pyc'", ")", "or", "name", ".", "endswith", "(", "'.pyo'", ")", ":", "return", "'Skipping %s file '", "%", "os", ".", "path", ".", "splitext", "(", "name", ")", "[", "1", "]", "+", "'%(filename)s'", "if", "name", ".", "endswith", "(", "'$py.class'", ")", ":", "return", "'Skipping $py.class file %(filename)s'", "if", "name", "in", "(", "'CVS'", ",", "'_darcs'", ")", ":", "return", "'Skipping version control directory %(filename)s'", "return", "None" ]
38
16.555556
def get_default_config_help(self): """ Returns the help text for the configuration options for this handler """ config = super(NullHandler, self).get_default_config_help() config.update({ }) return config
[ "def", "get_default_config_help", "(", "self", ")", ":", "config", "=", "super", "(", "NullHandler", ",", "self", ")", ".", "get_default_config_help", "(", ")", "config", ".", "update", "(", "{", "}", ")", "return", "config" ]
25.3
21.5
def solve(self): """ Solve the OLL. Returns an Formula. """ if not isinstance(self.cube, Cube): raise ValueError("Use Solver.feed(cube) to feed the cube to solver.") self.recognise() self.cube(algo_dict[self.case]) return algo_dict[self.case]
[ "def", "solve", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "cube", ",", "Cube", ")", ":", "raise", "ValueError", "(", "\"Use Solver.feed(cube) to feed the cube to solver.\"", ")", "self", ".", "recognise", "(", ")", "self", ".", "cube", "(", "algo_dict", "[", "self", ".", "case", "]", ")", "return", "algo_dict", "[", "self", ".", "case", "]" ]
33.555556
10.222222
def _set_raw_return(self, sep): """Set the output raw return section :param sep: the separator of current style """ raw = '' if self.dst.style['out'] == 'numpydoc': raw += '\n' spaces = ' ' * 4 with_space = lambda s: '\n'.join([self.docs['out']['spaces'] + spaces + l.lstrip() if i > 0 else l for i, l in enumerate(s.splitlines())]) raw += self.dst.numpydoc.get_key_section_header('return', self.docs['out']['spaces']) if self.docs['out']['rtype']: rtype = self.docs['out']['rtype'] else: rtype = 'type' # case of several returns if type(self.docs['out']['return']) is list: for ret_elem in self.docs['out']['return']: # if tuple (name, desc, rtype) else string desc if type(ret_elem) is tuple and len(ret_elem) == 3: rtype = ret_elem[2] if rtype is None: rtype = '' raw += self.docs['out']['spaces'] if ret_elem[0]: raw += ret_elem[0] + ' : ' raw += rtype + '\n' + self.docs['out']['spaces'] + spaces + with_space(ret_elem[1]).strip() + '\n' else: # There can be a problem raw += self.docs['out']['spaces'] + rtype + '\n' raw += self.docs['out']['spaces'] + spaces + with_space(str(ret_elem)).strip() + '\n' # case of a unique return elif self.docs['out']['return'] is not None: raw += self.docs['out']['spaces'] + rtype raw += '\n' + self.docs['out']['spaces'] + spaces + with_space(self.docs['out']['return']).strip() + '\n' elif self.dst.style['out'] == 'google': raw += '\n' spaces = ' ' * 2 with_space = lambda s: '\n'.join([self.docs['out']['spaces'] + spaces +\ l.lstrip() if i > 0 else\ l for i, l in enumerate(s.splitlines())]) raw += self.dst.googledoc.get_key_section_header('return', self.docs['out']['spaces']) if self.docs['out']['rtype']: rtype = self.docs['out']['rtype'] else: rtype = None # case of several returns if type(self.docs['out']['return']) is list: for ret_elem in self.docs['out']['return']: # if tuple (name=None, desc, rtype) else string desc if type(ret_elem) is tuple and len(ret_elem) == 3: rtype = ret_elem[2] if rtype is None: rtype = '' raw += self.docs['out']['spaces'] + spaces raw += rtype + ': ' + with_space(ret_elem[1]).strip() + '\n' else: # There can be a problem if rtype: raw += self.docs['out']['spaces'] + spaces + rtype + ': ' raw += with_space(str(ret_elem)).strip() + '\n' else: raw += self.docs['out']['spaces'] + spaces + with_space(str(ret_elem)).strip() + '\n' # case of a unique return elif self.docs['out']['return'] is not None: if rtype: raw += self.docs['out']['spaces'] + spaces + rtype + ': ' raw += with_space(self.docs['out']['return']).strip() + '\n' else: raw += self.docs['out']['spaces'] + spaces + with_space(self.docs['out']['return']).strip() + '\n' elif self.dst.style['out'] == 'groups': pass else: with_space = lambda s: '\n'.join([self.docs['out']['spaces'] + l if i > 0 else l for i, l in enumerate(s.splitlines())]) if self.docs['out']['return']: if not self.docs['out']['params']: raw += '\n' raw += self.docs['out']['spaces'] + self.dst.get_key('return', 'out') + sep + with_space(self.docs['out']['return'].rstrip()).strip() + '\n' if self.docs['out']['rtype']: if not self.docs['out']['params']: raw += '\n' raw += self.docs['out']['spaces'] + self.dst.get_key('rtype', 'out') + sep + self.docs['out']['rtype'].rstrip() + '\n' return raw
[ "def", "_set_raw_return", "(", "self", ",", "sep", ")", ":", "raw", "=", "''", "if", "self", ".", "dst", ".", "style", "[", "'out'", "]", "==", "'numpydoc'", ":", "raw", "+=", "'\\n'", "spaces", "=", "' '", "*", "4", "with_space", "=", "lambda", "s", ":", "'\\n'", ".", "join", "(", "[", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", "+", "spaces", "+", "l", ".", "lstrip", "(", ")", "if", "i", ">", "0", "else", "l", "for", "i", ",", "l", "in", "enumerate", "(", "s", ".", "splitlines", "(", ")", ")", "]", ")", "raw", "+=", "self", ".", "dst", ".", "numpydoc", ".", "get_key_section_header", "(", "'return'", ",", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", ")", "if", "self", ".", "docs", "[", "'out'", "]", "[", "'rtype'", "]", ":", "rtype", "=", "self", ".", "docs", "[", "'out'", "]", "[", "'rtype'", "]", "else", ":", "rtype", "=", "'type'", "# case of several returns", "if", "type", "(", "self", ".", "docs", "[", "'out'", "]", "[", "'return'", "]", ")", "is", "list", ":", "for", "ret_elem", "in", "self", ".", "docs", "[", "'out'", "]", "[", "'return'", "]", ":", "# if tuple (name, desc, rtype) else string desc", "if", "type", "(", "ret_elem", ")", "is", "tuple", "and", "len", "(", "ret_elem", ")", "==", "3", ":", "rtype", "=", "ret_elem", "[", "2", "]", "if", "rtype", "is", "None", ":", "rtype", "=", "''", "raw", "+=", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", "if", "ret_elem", "[", "0", "]", ":", "raw", "+=", "ret_elem", "[", "0", "]", "+", "' : '", "raw", "+=", "rtype", "+", "'\\n'", "+", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", "+", "spaces", "+", "with_space", "(", "ret_elem", "[", "1", "]", ")", ".", "strip", "(", ")", "+", "'\\n'", "else", ":", "# There can be a problem", "raw", "+=", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", "+", "rtype", "+", "'\\n'", "raw", "+=", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", "+", "spaces", "+", "with_space", "(", "str", "(", "ret_elem", ")", ")", ".", "strip", "(", ")", "+", "'\\n'", "# case of a unique return", "elif", "self", ".", "docs", "[", "'out'", "]", "[", "'return'", "]", "is", "not", "None", ":", "raw", "+=", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", "+", "rtype", "raw", "+=", "'\\n'", "+", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", "+", "spaces", "+", "with_space", "(", "self", ".", "docs", "[", "'out'", "]", "[", "'return'", "]", ")", ".", "strip", "(", ")", "+", "'\\n'", "elif", "self", ".", "dst", ".", "style", "[", "'out'", "]", "==", "'google'", ":", "raw", "+=", "'\\n'", "spaces", "=", "' '", "*", "2", "with_space", "=", "lambda", "s", ":", "'\\n'", ".", "join", "(", "[", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", "+", "spaces", "+", "l", ".", "lstrip", "(", ")", "if", "i", ">", "0", "else", "l", "for", "i", ",", "l", "in", "enumerate", "(", "s", ".", "splitlines", "(", ")", ")", "]", ")", "raw", "+=", "self", ".", "dst", ".", "googledoc", ".", "get_key_section_header", "(", "'return'", ",", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", ")", "if", "self", ".", "docs", "[", "'out'", "]", "[", "'rtype'", "]", ":", "rtype", "=", "self", ".", "docs", "[", "'out'", "]", "[", "'rtype'", "]", "else", ":", "rtype", "=", "None", "# case of several returns", "if", "type", "(", "self", ".", "docs", "[", "'out'", "]", "[", "'return'", "]", ")", "is", "list", ":", "for", "ret_elem", "in", "self", ".", "docs", "[", "'out'", "]", "[", "'return'", "]", ":", "# if tuple (name=None, desc, rtype) else string desc", "if", "type", "(", "ret_elem", ")", "is", "tuple", "and", "len", "(", "ret_elem", ")", "==", "3", ":", "rtype", "=", "ret_elem", "[", "2", "]", "if", "rtype", "is", "None", ":", "rtype", "=", "''", "raw", "+=", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", "+", "spaces", "raw", "+=", "rtype", "+", "': '", "+", "with_space", "(", "ret_elem", "[", "1", "]", ")", ".", "strip", "(", ")", "+", "'\\n'", "else", ":", "# There can be a problem", "if", "rtype", ":", "raw", "+=", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", "+", "spaces", "+", "rtype", "+", "': '", "raw", "+=", "with_space", "(", "str", "(", "ret_elem", ")", ")", ".", "strip", "(", ")", "+", "'\\n'", "else", ":", "raw", "+=", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", "+", "spaces", "+", "with_space", "(", "str", "(", "ret_elem", ")", ")", ".", "strip", "(", ")", "+", "'\\n'", "# case of a unique return", "elif", "self", ".", "docs", "[", "'out'", "]", "[", "'return'", "]", "is", "not", "None", ":", "if", "rtype", ":", "raw", "+=", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", "+", "spaces", "+", "rtype", "+", "': '", "raw", "+=", "with_space", "(", "self", ".", "docs", "[", "'out'", "]", "[", "'return'", "]", ")", ".", "strip", "(", ")", "+", "'\\n'", "else", ":", "raw", "+=", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", "+", "spaces", "+", "with_space", "(", "self", ".", "docs", "[", "'out'", "]", "[", "'return'", "]", ")", ".", "strip", "(", ")", "+", "'\\n'", "elif", "self", ".", "dst", ".", "style", "[", "'out'", "]", "==", "'groups'", ":", "pass", "else", ":", "with_space", "=", "lambda", "s", ":", "'\\n'", ".", "join", "(", "[", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", "+", "l", "if", "i", ">", "0", "else", "l", "for", "i", ",", "l", "in", "enumerate", "(", "s", ".", "splitlines", "(", ")", ")", "]", ")", "if", "self", ".", "docs", "[", "'out'", "]", "[", "'return'", "]", ":", "if", "not", "self", ".", "docs", "[", "'out'", "]", "[", "'params'", "]", ":", "raw", "+=", "'\\n'", "raw", "+=", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", "+", "self", ".", "dst", ".", "get_key", "(", "'return'", ",", "'out'", ")", "+", "sep", "+", "with_space", "(", "self", ".", "docs", "[", "'out'", "]", "[", "'return'", "]", ".", "rstrip", "(", ")", ")", ".", "strip", "(", ")", "+", "'\\n'", "if", "self", ".", "docs", "[", "'out'", "]", "[", "'rtype'", "]", ":", "if", "not", "self", ".", "docs", "[", "'out'", "]", "[", "'params'", "]", ":", "raw", "+=", "'\\n'", "raw", "+=", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", "+", "self", ".", "dst", ".", "get_key", "(", "'rtype'", ",", "'out'", ")", "+", "sep", "+", "self", ".", "docs", "[", "'out'", "]", "[", "'rtype'", "]", ".", "rstrip", "(", ")", "+", "'\\n'", "return", "raw" ]
54.47619
24.988095
def check_solver(self, image_x, image_y, kwargs_lens): """ returns the precision of the solver to match the image position :param kwargs_lens: full lens model (including solved parameters) :param image_x: point source in image :param image_y: point source in image :return: precision of Euclidean distances between the different rays arriving at the image positions """ source_x, source_y = self._lensModel.ray_shooting(image_x, image_y, kwargs_lens) dist = np.sqrt((source_x - source_x[0]) ** 2 + (source_y - source_y[0]) ** 2) return dist
[ "def", "check_solver", "(", "self", ",", "image_x", ",", "image_y", ",", "kwargs_lens", ")", ":", "source_x", ",", "source_y", "=", "self", ".", "_lensModel", ".", "ray_shooting", "(", "image_x", ",", "image_y", ",", "kwargs_lens", ")", "dist", "=", "np", ".", "sqrt", "(", "(", "source_x", "-", "source_x", "[", "0", "]", ")", "**", "2", "+", "(", "source_y", "-", "source_y", "[", "0", "]", ")", "**", "2", ")", "return", "dist" ]
50.833333
25.833333
def wsgi_wrap(app): ''' Wraps a standard wsgi application e.g.: def app(environ, start_response) It intercepts the start_response callback and grabs the results from it so it can return the status, headers, and body as a tuple ''' @wraps(app) def wrapped(environ, start_response): status_headers = [None, None] def _start_response(status, headers): status_headers[:] = [status, headers] body = app(environ, _start_response) ret = body, status_headers[0], status_headers[1] return ret return wrapped
[ "def", "wsgi_wrap", "(", "app", ")", ":", "@", "wraps", "(", "app", ")", "def", "wrapped", "(", "environ", ",", "start_response", ")", ":", "status_headers", "=", "[", "None", ",", "None", "]", "def", "_start_response", "(", "status", ",", "headers", ")", ":", "status_headers", "[", ":", "]", "=", "[", "status", ",", "headers", "]", "body", "=", "app", "(", "environ", ",", "_start_response", ")", "ret", "=", "body", ",", "status_headers", "[", "0", "]", ",", "status_headers", "[", "1", "]", "return", "ret", "return", "wrapped" ]
35.9375
15.8125
def override_tab_value(data, headers, new_value=' ', **_): """Override tab values in the *data* with *new_value*. :param iterable data: An :term:`iterable` (e.g. list) of rows. :param iterable headers: The column headers. :param new_value: The new value to use for tab. :return: The processed data and headers. :rtype: tuple """ return (([v.replace('\t', new_value) if isinstance(v, text_type) else v for v in row] for row in data), headers)
[ "def", "override_tab_value", "(", "data", ",", "headers", ",", "new_value", "=", "' '", ",", "*", "*", "_", ")", ":", "return", "(", "(", "[", "v", ".", "replace", "(", "'\\t'", ",", "new_value", ")", "if", "isinstance", "(", "v", ",", "text_type", ")", "else", "v", "for", "v", "in", "row", "]", "for", "row", "in", "data", ")", ",", "headers", ")" ]
37.846154
17.923077
def _find_field(cls, field, doc): """Find the field in the document which matches the given field. The field may be in dot notation, eg "a.b.c". Returns a list with a single tuple (path, field_value) or the empty list if the field is not present. """ path = field.split(".") try: for key in path: doc = doc[key] return [(path, doc)] except (KeyError, TypeError): return []
[ "def", "_find_field", "(", "cls", ",", "field", ",", "doc", ")", ":", "path", "=", "field", ".", "split", "(", "\".\"", ")", "try", ":", "for", "key", "in", "path", ":", "doc", "=", "doc", "[", "key", "]", "return", "[", "(", "path", ",", "doc", ")", "]", "except", "(", "KeyError", ",", "TypeError", ")", ":", "return", "[", "]" ]
34
15.642857
def login(): """ This route has two purposes. First, it is used by the user to login. Second, it is used by the CAS to respond with the `ticket` after the user logs in successfully. When the user accesses this url, they are redirected to the CAS to login. If the login was successful, the CAS will respond to this route with the ticket in the url. The ticket is then validated. If validation was successful the logged in username is saved in the user's session under the key `CAS_USERNAME_SESSION_KEY` and the user's attributes are saved under the key 'CAS_USERNAME_ATTRIBUTE_KEY' """ cas_token_session_key = current_app.config['CAS_TOKEN_SESSION_KEY'] redirect_url = create_cas_login_url( current_app.config['CAS_SERVER'], current_app.config['CAS_LOGIN_ROUTE'], flask.url_for('.login', origin=flask.session.get('CAS_AFTER_LOGIN_SESSION_URL'), _external=True)) if 'ticket' in flask.request.args: flask.session[cas_token_session_key] = flask.request.args['ticket'] if cas_token_session_key in flask.session: if validate(flask.session[cas_token_session_key]): if 'CAS_AFTER_LOGIN_SESSION_URL' in flask.session: redirect_url = flask.session.pop('CAS_AFTER_LOGIN_SESSION_URL') elif flask.request.args.get('origin'): redirect_url = flask.request.args['origin'] else: redirect_url = flask.url_for( current_app.config['CAS_AFTER_LOGIN']) else: del flask.session[cas_token_session_key] current_app.logger.debug('Redirecting to: {0}'.format(redirect_url)) return flask.redirect(redirect_url)
[ "def", "login", "(", ")", ":", "cas_token_session_key", "=", "current_app", ".", "config", "[", "'CAS_TOKEN_SESSION_KEY'", "]", "redirect_url", "=", "create_cas_login_url", "(", "current_app", ".", "config", "[", "'CAS_SERVER'", "]", ",", "current_app", ".", "config", "[", "'CAS_LOGIN_ROUTE'", "]", ",", "flask", ".", "url_for", "(", "'.login'", ",", "origin", "=", "flask", ".", "session", ".", "get", "(", "'CAS_AFTER_LOGIN_SESSION_URL'", ")", ",", "_external", "=", "True", ")", ")", "if", "'ticket'", "in", "flask", ".", "request", ".", "args", ":", "flask", ".", "session", "[", "cas_token_session_key", "]", "=", "flask", ".", "request", ".", "args", "[", "'ticket'", "]", "if", "cas_token_session_key", "in", "flask", ".", "session", ":", "if", "validate", "(", "flask", ".", "session", "[", "cas_token_session_key", "]", ")", ":", "if", "'CAS_AFTER_LOGIN_SESSION_URL'", "in", "flask", ".", "session", ":", "redirect_url", "=", "flask", ".", "session", ".", "pop", "(", "'CAS_AFTER_LOGIN_SESSION_URL'", ")", "elif", "flask", ".", "request", ".", "args", ".", "get", "(", "'origin'", ")", ":", "redirect_url", "=", "flask", ".", "request", ".", "args", "[", "'origin'", "]", "else", ":", "redirect_url", "=", "flask", ".", "url_for", "(", "current_app", ".", "config", "[", "'CAS_AFTER_LOGIN'", "]", ")", "else", ":", "del", "flask", ".", "session", "[", "cas_token_session_key", "]", "current_app", ".", "logger", ".", "debug", "(", "'Redirecting to: {0}'", ".", "format", "(", "redirect_url", ")", ")", "return", "flask", ".", "redirect", "(", "redirect_url", ")" ]
41.121951
22.682927
def cumulative_sum(self): """ Return the cumulative sum of the elements in the SArray. Returns an SArray where each element in the output corresponds to the sum of all the elements preceding and including it. The SArray is expected to be of numeric type (int, float), or a numeric vector type. Returns ------- out : sarray[int, float, array.array] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. - For SArray's of type array.array, all entries are expected to be of the same size. Examples -------- >>> sa = SArray([1, 2, 3, 4, 5]) >>> sa.cumulative_sum() dtype: int rows: 3 [1, 3, 6, 10, 15] """ from .. import extensions agg_op = "__builtin__cum_sum__" return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op))
[ "def", "cumulative_sum", "(", "self", ")", ":", "from", ".", ".", "import", "extensions", "agg_op", "=", "\"__builtin__cum_sum__\"", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "builtin_cumulative_aggregate", "(", "agg_op", ")", ")" ]
31.966667
22.166667
def create_rename_entry( step: 'projects.ProjectStep', insertion_index: int = None, stash_path: str = None ) -> typing.Union[None, STEP_RENAME]: """ Creates a STEP_RENAME for the given ProjectStep instance :param step: The ProjectStep instance for which the STEP_RENAME will be created :param insertion_index: An optional index where a step will be inserted as part of this renaming process. Allows files to be renamed prior to the insertion of the step to prevent conflicts. :param stash_path: :return: """ project = step.project name = step.definition.name name_parts = naming.explode_filename(name, project.naming_scheme) index = project.index_of_step(name) name_index = index if insertion_index is not None and insertion_index <= index: # Adjusts indexing when renaming is for the purpose of # inserting a new step name_index += 1 name_parts['index'] = name_index new_name = naming.assemble_filename( scheme=project.naming_scheme, **name_parts ) if name == new_name: return None if not stash_path: fd, stash_path = tempfile.mkstemp( prefix='{}-{}--{}--'.format(step.reference_id, name, new_name) ) os.close(fd) return STEP_RENAME( id=step.reference_id, index=index, old_name=name, new_name=new_name, old_path=step.source_path, stash_path=stash_path, new_path=os.path.join(step.project.source_directory, new_name) )
[ "def", "create_rename_entry", "(", "step", ":", "'projects.ProjectStep'", ",", "insertion_index", ":", "int", "=", "None", ",", "stash_path", ":", "str", "=", "None", ")", "->", "typing", ".", "Union", "[", "None", ",", "STEP_RENAME", "]", ":", "project", "=", "step", ".", "project", "name", "=", "step", ".", "definition", ".", "name", "name_parts", "=", "naming", ".", "explode_filename", "(", "name", ",", "project", ".", "naming_scheme", ")", "index", "=", "project", ".", "index_of_step", "(", "name", ")", "name_index", "=", "index", "if", "insertion_index", "is", "not", "None", "and", "insertion_index", "<=", "index", ":", "# Adjusts indexing when renaming is for the purpose of", "# inserting a new step", "name_index", "+=", "1", "name_parts", "[", "'index'", "]", "=", "name_index", "new_name", "=", "naming", ".", "assemble_filename", "(", "scheme", "=", "project", ".", "naming_scheme", ",", "*", "*", "name_parts", ")", "if", "name", "==", "new_name", ":", "return", "None", "if", "not", "stash_path", ":", "fd", ",", "stash_path", "=", "tempfile", ".", "mkstemp", "(", "prefix", "=", "'{}-{}--{}--'", ".", "format", "(", "step", ".", "reference_id", ",", "name", ",", "new_name", ")", ")", "os", ".", "close", "(", "fd", ")", "return", "STEP_RENAME", "(", "id", "=", "step", ".", "reference_id", ",", "index", "=", "index", ",", "old_name", "=", "name", ",", "new_name", "=", "new_name", ",", "old_path", "=", "step", ".", "source_path", ",", "stash_path", "=", "stash_path", ",", "new_path", "=", "os", ".", "path", ".", "join", "(", "step", ".", "project", ".", "source_directory", ",", "new_name", ")", ")" ]
29.226415
19.415094
def nonspeech_fragments(self): """ Iterates through the nonspeech fragments in the list (which are sorted). :rtype: generator of (int, :class:`~aeneas.syncmap.SyncMapFragment`) """ for i, fragment in enumerate(self.__fragments): if fragment.fragment_type == SyncMapFragment.NONSPEECH: yield (i, fragment)
[ "def", "nonspeech_fragments", "(", "self", ")", ":", "for", "i", ",", "fragment", "in", "enumerate", "(", "self", ".", "__fragments", ")", ":", "if", "fragment", ".", "fragment_type", "==", "SyncMapFragment", ".", "NONSPEECH", ":", "yield", "(", "i", ",", "fragment", ")" ]
37.2
16.6
def get_pkg_module_names(package_path): """Returns module filenames from package. Args: package_path: Path to Python package. Returns: A set of module filenames. """ module_names = set() for fobj, modname, _ in pkgutil.iter_modules(path=[package_path]): filename = os.path.join(fobj.path, '%s.py' % modname) if os.path.exists(filename): module_names.add(os.path.abspath(filename)) return module_names
[ "def", "get_pkg_module_names", "(", "package_path", ")", ":", "module_names", "=", "set", "(", ")", "for", "fobj", ",", "modname", ",", "_", "in", "pkgutil", ".", "iter_modules", "(", "path", "=", "[", "package_path", "]", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "fobj", ".", "path", ",", "'%s.py'", "%", "modname", ")", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "module_names", ".", "add", "(", "os", ".", "path", ".", "abspath", "(", "filename", ")", ")", "return", "module_names" ]
32.857143
15.285714
def _run_configure_script(self, script): """Run the script to install the Juju agent on the target machine. :param str script: The script returned by the ProvisioningScript API :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the upload fails """ _, tmpFile = tempfile.mkstemp() with open(tmpFile, 'w') as f: f.write(script) try: # get ssh client ssh = self._get_ssh_client( self.host, "ubuntu", self.private_key_path, ) # copy the local copy of the script to the remote machine sftp = paramiko.SFTPClient.from_transport(ssh.get_transport()) sftp.put( tmpFile, tmpFile, ) # run the provisioning script stdout, stderr = self._run_command( ssh, "sudo /bin/bash {}".format(tmpFile), ) except paramiko.ssh_exception.AuthenticationException as e: raise e finally: os.remove(tmpFile) ssh.close()
[ "def", "_run_configure_script", "(", "self", ",", "script", ")", ":", "_", ",", "tmpFile", "=", "tempfile", ".", "mkstemp", "(", ")", "with", "open", "(", "tmpFile", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "script", ")", "try", ":", "# get ssh client", "ssh", "=", "self", ".", "_get_ssh_client", "(", "self", ".", "host", ",", "\"ubuntu\"", ",", "self", ".", "private_key_path", ",", ")", "# copy the local copy of the script to the remote machine", "sftp", "=", "paramiko", ".", "SFTPClient", ".", "from_transport", "(", "ssh", ".", "get_transport", "(", ")", ")", "sftp", ".", "put", "(", "tmpFile", ",", "tmpFile", ",", ")", "# run the provisioning script", "stdout", ",", "stderr", "=", "self", ".", "_run_command", "(", "ssh", ",", "\"sudo /bin/bash {}\"", ".", "format", "(", "tmpFile", ")", ",", ")", "except", "paramiko", ".", "ssh_exception", ".", "AuthenticationException", "as", "e", ":", "raise", "e", "finally", ":", "os", ".", "remove", "(", "tmpFile", ")", "ssh", ".", "close", "(", ")" ]
30.026316
19.473684
def format_modified(self, modified, sep=" "): """Format modification date in UTC if it's not None. @param modified: modification date in UTC @ptype modified: datetime or None @return: formatted date or empty string @rtype: unicode """ if modified is not None: return modified.strftime("%Y-%m-%d{0}%H:%M:%S.%fZ".format(sep)) return u""
[ "def", "format_modified", "(", "self", ",", "modified", ",", "sep", "=", "\" \"", ")", ":", "if", "modified", "is", "not", "None", ":", "return", "modified", ".", "strftime", "(", "\"%Y-%m-%d{0}%H:%M:%S.%fZ\"", ".", "format", "(", "sep", ")", ")", "return", "u\"\"" ]
40.1
10.4
def upgrade(self, flag): """Upgrade Slackware binary packages with new """ for pkg in self.binary: try: subprocess.call("upgradepkg {0} {1}".format(flag, pkg), shell=True) check = pkg[:-4].split("/")[-1] if os.path.isfile(self.meta.pkg_path + check): print("Completed!\n") else: raise SystemExit() except subprocess.CalledProcessError: self._not_found("Can't upgrade", self.binary, pkg) raise SystemExit(1)
[ "def", "upgrade", "(", "self", ",", "flag", ")", ":", "for", "pkg", "in", "self", ".", "binary", ":", "try", ":", "subprocess", ".", "call", "(", "\"upgradepkg {0} {1}\"", ".", "format", "(", "flag", ",", "pkg", ")", ",", "shell", "=", "True", ")", "check", "=", "pkg", "[", ":", "-", "4", "]", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "meta", ".", "pkg_path", "+", "check", ")", ":", "print", "(", "\"Completed!\\n\"", ")", "else", ":", "raise", "SystemExit", "(", ")", "except", "subprocess", ".", "CalledProcessError", ":", "self", ".", "_not_found", "(", "\"Can't upgrade\"", ",", "self", ".", "binary", ",", "pkg", ")", "raise", "SystemExit", "(", "1", ")" ]
40.533333
11.6
def extract_metainfo_files_from_package( package, output_folder, debug=False ): """ Extracts metdata files from the given package to the given folder, which may be referenced in any way that is permitted in a requirements.txt file or install_requires=[] listing. Current supported metadata files that will be extracted: - pytoml.yml (only if package wasn't obtained as wheel) - METADATA """ if package is None: raise ValueError("package cannot be None") if not os.path.exists(output_folder) or os.path.isfile(output_folder): raise ValueError("output folder needs to be existing folder") # A temp folder for making a package copy in case it's a local folder, # because extracting metadata might modify files # (creating sdists/wheels...) temp_folder = tempfile.mkdtemp(prefix="pythonpackage-package-copy-") try: # Package is indeed a folder! Get a temp copy to work on: if is_filesystem_path(package): shutil.copytree( parse_as_folder_reference(package), os.path.join(temp_folder, "package") ) package = os.path.join(temp_folder, "package") # Because PEP517 can be noisy and contextlib.redirect_* fails to # contain it, we will run the actual analysis in a separate process: try: subprocess.check_output([ sys.executable, "-c", "import importlib\n" "import json\n" "import os\n" "import sys\n" "sys.path = [os.path.dirname(sys.argv[3])] + sys.path\n" "m = importlib.import_module(\n" " os.path.basename(sys.argv[3]).partition('.')[0]\n" ")\n" "m._extract_metainfo_files_from_package_unsafe(" " sys.argv[1]," " sys.argv[2]," ")", package, output_folder, os.path.abspath(__file__)], stderr=subprocess.STDOUT, # make sure stderr is muted. cwd=os.path.join(os.path.dirname(__file__), "..") ) except subprocess.CalledProcessError as e: output = e.output.decode("utf-8", "replace") if debug: print("Got error obtaining meta info.") print("Detail output:") print(output) print("End of Detail output.") raise ValueError( "failed to obtain meta info - " "is '{}' a valid package? " "Detailed output:\n{}".format(package, output) ) finally: shutil.rmtree(temp_folder)
[ "def", "extract_metainfo_files_from_package", "(", "package", ",", "output_folder", ",", "debug", "=", "False", ")", ":", "if", "package", "is", "None", ":", "raise", "ValueError", "(", "\"package cannot be None\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "output_folder", ")", "or", "os", ".", "path", ".", "isfile", "(", "output_folder", ")", ":", "raise", "ValueError", "(", "\"output folder needs to be existing folder\"", ")", "# A temp folder for making a package copy in case it's a local folder,", "# because extracting metadata might modify files", "# (creating sdists/wheels...)", "temp_folder", "=", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "\"pythonpackage-package-copy-\"", ")", "try", ":", "# Package is indeed a folder! Get a temp copy to work on:", "if", "is_filesystem_path", "(", "package", ")", ":", "shutil", ".", "copytree", "(", "parse_as_folder_reference", "(", "package", ")", ",", "os", ".", "path", ".", "join", "(", "temp_folder", ",", "\"package\"", ")", ")", "package", "=", "os", ".", "path", ".", "join", "(", "temp_folder", ",", "\"package\"", ")", "# Because PEP517 can be noisy and contextlib.redirect_* fails to", "# contain it, we will run the actual analysis in a separate process:", "try", ":", "subprocess", ".", "check_output", "(", "[", "sys", ".", "executable", ",", "\"-c\"", ",", "\"import importlib\\n\"", "\"import json\\n\"", "\"import os\\n\"", "\"import sys\\n\"", "\"sys.path = [os.path.dirname(sys.argv[3])] + sys.path\\n\"", "\"m = importlib.import_module(\\n\"", "\" os.path.basename(sys.argv[3]).partition('.')[0]\\n\"", "\")\\n\"", "\"m._extract_metainfo_files_from_package_unsafe(\"", "\" sys.argv[1],\"", "\" sys.argv[2],\"", "\")\"", ",", "package", ",", "output_folder", ",", "os", ".", "path", ".", "abspath", "(", "__file__", ")", "]", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "# make sure stderr is muted.", "cwd", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"..\"", ")", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "output", "=", "e", ".", "output", ".", "decode", "(", "\"utf-8\"", ",", "\"replace\"", ")", "if", "debug", ":", "print", "(", "\"Got error obtaining meta info.\"", ")", "print", "(", "\"Detail output:\"", ")", "print", "(", "output", ")", "print", "(", "\"End of Detail output.\"", ")", "raise", "ValueError", "(", "\"failed to obtain meta info - \"", "\"is '{}' a valid package? \"", "\"Detailed output:\\n{}\"", ".", "format", "(", "package", ",", "output", ")", ")", "finally", ":", "shutil", ".", "rmtree", "(", "temp_folder", ")" ]
38.8
19.385714
def IntGreaterThanZero(n): """If *n* is an integer > 0, returns it, otherwise an error.""" try: n = int(n) except: raise ValueError("%s is not an integer" % n) if n <= 0: raise ValueError("%d is not > 0" % n) else: return n
[ "def", "IntGreaterThanZero", "(", "n", ")", ":", "try", ":", "n", "=", "int", "(", "n", ")", "except", ":", "raise", "ValueError", "(", "\"%s is not an integer\"", "%", "n", ")", "if", "n", "<=", "0", ":", "raise", "ValueError", "(", "\"%d is not > 0\"", "%", "n", ")", "else", ":", "return", "n" ]
26.6
19.5
def friendships_destroy(self, user_id=None, screen_name=None): """ Allows the authenticating user to unfollow the specified user. https://dev.twitter.com/docs/api/1.1/post/friendships/destroy :param str user_id: The screen name of the user for whom to unfollow. Required if ``screen_name`` isn't given. :param str screen_name: The ID of the user for whom to unfollow. Required if ``user_id`` isn't given. :returns: A dict containing the newly unfollowed user. """ params = {} set_str_param(params, 'user_id', user_id) set_str_param(params, 'screen_name', screen_name) return self._post_api('friendships/destroy.json', params)
[ "def", "friendships_destroy", "(", "self", ",", "user_id", "=", "None", ",", "screen_name", "=", "None", ")", ":", "params", "=", "{", "}", "set_str_param", "(", "params", ",", "'user_id'", ",", "user_id", ")", "set_str_param", "(", "params", ",", "'screen_name'", ",", "screen_name", ")", "return", "self", ".", "_post_api", "(", "'friendships/destroy.json'", ",", "params", ")" ]
37.85
20.95
def get_active_choices(self, language_code=None, site_id=None): """ Find out which translations should be visible in the site. It returns a list with either a single choice (the current language), or a list with the current language + fallback language. """ if language_code is None: language_code = get_language() lang_dict = self.get_language(language_code, site_id=site_id) if not lang_dict['hide_untranslated']: return [language_code] + [lang for lang in lang_dict['fallbacks'] if lang != language_code] else: return [language_code]
[ "def", "get_active_choices", "(", "self", ",", "language_code", "=", "None", ",", "site_id", "=", "None", ")", ":", "if", "language_code", "is", "None", ":", "language_code", "=", "get_language", "(", ")", "lang_dict", "=", "self", ".", "get_language", "(", "language_code", ",", "site_id", "=", "site_id", ")", "if", "not", "lang_dict", "[", "'hide_untranslated'", "]", ":", "return", "[", "language_code", "]", "+", "[", "lang", "for", "lang", "in", "lang_dict", "[", "'fallbacks'", "]", "if", "lang", "!=", "language_code", "]", "else", ":", "return", "[", "language_code", "]" ]
45.142857
20.714286
def install_programmer(programmer_id, programmer_options, replace_existing=False): """install programmer in programmers.txt. :param programmer_id: string identifier :param programmer_options: dict like :param replace_existing: bool :rtype: None """ doaction = 0 if programmer_id in programmers().keys(): log.debug('programmer already exists: %s', programmer_id) if replace_existing: log.debug('remove programmer: %s', programmer_id) remove_programmer(programmer_id) doaction = 1 else: doaction = 1 if doaction: lines = bunch2properties(programmer_id, programmer_options) programmers_txt().write_lines([''] + lines, append=1)
[ "def", "install_programmer", "(", "programmer_id", ",", "programmer_options", ",", "replace_existing", "=", "False", ")", ":", "doaction", "=", "0", "if", "programmer_id", "in", "programmers", "(", ")", ".", "keys", "(", ")", ":", "log", ".", "debug", "(", "'programmer already exists: %s'", ",", "programmer_id", ")", "if", "replace_existing", ":", "log", ".", "debug", "(", "'remove programmer: %s'", ",", "programmer_id", ")", "remove_programmer", "(", "programmer_id", ")", "doaction", "=", "1", "else", ":", "doaction", "=", "1", "if", "doaction", ":", "lines", "=", "bunch2properties", "(", "programmer_id", ",", "programmer_options", ")", "programmers_txt", "(", ")", ".", "write_lines", "(", "[", "''", "]", "+", "lines", ",", "append", "=", "1", ")" ]
32.818182
19.363636
def _set_ip_acl_interface(self, v, load=False): """ Setter method for ip_acl_interface, mapped from YANG variable /interface/tengigabitethernet/ip_acl_interface (container) If this variable is read-only (config: false) in the source YANG file, then _set_ip_acl_interface is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ip_acl_interface() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=ip_acl_interface.ip_acl_interface, is_container='container', presence=False, yang_name="ip-acl-interface", rest_name="", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'sort-priority': u'109'}}, namespace='urn:brocade.com:mgmt:brocade-ip-access-list', defining_module='brocade-ip-access-list', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """ip_acl_interface must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=ip_acl_interface.ip_acl_interface, is_container='container', presence=False, yang_name="ip-acl-interface", rest_name="", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'sort-priority': u'109'}}, namespace='urn:brocade.com:mgmt:brocade-ip-access-list', defining_module='brocade-ip-access-list', yang_type='container', is_config=True)""", }) self.__ip_acl_interface = t if hasattr(self, '_set'): self._set()
[ "def", "_set_ip_acl_interface", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", "=", "ip_acl_interface", ".", "ip_acl_interface", ",", "is_container", "=", "'container'", ",", "presence", "=", "False", ",", "yang_name", "=", "\"ip-acl-interface\"", ",", "rest_name", "=", "\"\"", ",", "parent", "=", "self", ",", "path_helper", "=", "self", ".", "_path_helper", ",", "extmethods", "=", "self", ".", "_extmethods", ",", "register_paths", "=", "True", ",", "extensions", "=", "{", "u'tailf-common'", ":", "{", "u'cli-drop-node-name'", ":", "None", ",", "u'sort-priority'", ":", "u'109'", "}", "}", ",", "namespace", "=", "'urn:brocade.com:mgmt:brocade-ip-access-list'", ",", "defining_module", "=", "'brocade-ip-access-list'", ",", "yang_type", "=", "'container'", ",", "is_config", "=", "True", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "{", "'error-string'", ":", "\"\"\"ip_acl_interface must be of a type compatible with container\"\"\"", ",", "'defined-type'", ":", "\"container\"", ",", "'generated-type'", ":", "\"\"\"YANGDynClass(base=ip_acl_interface.ip_acl_interface, is_container='container', presence=False, yang_name=\"ip-acl-interface\", rest_name=\"\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'sort-priority': u'109'}}, namespace='urn:brocade.com:mgmt:brocade-ip-access-list', defining_module='brocade-ip-access-list', yang_type='container', is_config=True)\"\"\"", ",", "}", ")", "self", ".", "__ip_acl_interface", "=", "t", "if", "hasattr", "(", "self", ",", "'_set'", ")", ":", "self", ".", "_set", "(", ")" ]
78.863636
37
def indent_func(input_): """ Takes either no arguments or an alias label """ if isinstance(input_, six.string_types): # A label was specified lbl = input_ return _indent_decor(lbl) elif isinstance(input_, (bool, tuple)): # Allow individually turning of of this decorator func = input_ return func else: # Use the function name as the label func = input_ lbl = '[' + meta_util_six.get_funcname(func) + ']' return _indent_decor(lbl)(func)
[ "def", "indent_func", "(", "input_", ")", ":", "if", "isinstance", "(", "input_", ",", "six", ".", "string_types", ")", ":", "# A label was specified", "lbl", "=", "input_", "return", "_indent_decor", "(", "lbl", ")", "elif", "isinstance", "(", "input_", ",", "(", "bool", ",", "tuple", ")", ")", ":", "# Allow individually turning of of this decorator", "func", "=", "input_", "return", "func", "else", ":", "# Use the function name as the label", "func", "=", "input_", "lbl", "=", "'['", "+", "meta_util_six", ".", "get_funcname", "(", "func", ")", "+", "']'", "return", "_indent_decor", "(", "lbl", ")", "(", "func", ")" ]
30.823529
11.529412
def get_current_time(self): """ Get current time :return: datetime.time """ hms = [int(self.get_current_controller_value(i)) for i in range(406, 409)] return datetime.time(*hms)
[ "def", "get_current_time", "(", "self", ")", ":", "hms", "=", "[", "int", "(", "self", ".", "get_current_controller_value", "(", "i", ")", ")", "for", "i", "in", "range", "(", "406", ",", "409", ")", "]", "return", "datetime", ".", "time", "(", "*", "hms", ")" ]
27.375
15.875
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'text'", ")", "and", "self", ".", "text", "is", "not", "None", ":", "_dict", "[", "'text'", "]", "=", "self", ".", "text", "return", "_dict" ]
36
14.166667
def add(self, bounds1, label1, bounds2, label2, bin3, label3, data_label): """ Combines signals from multiple instruments within given bounds. Parameters ---------- bounds1 : (min, max) Bounds for selecting data on the axis of label1 Data points with label1 in [min, max) will be considered. label1 : string Data label for bounds1 to act on. bounds2 : (min, max) Bounds for selecting data on the axis of label2 Data points with label1 in [min, max) will be considered. label2 : string Data label for bounds2 to act on. bin3 : (min, max, #bins) Min and max bounds and number of bins for third axis. label3 : string Data label for third axis. data_label : array of strings Data label(s) for data product(s) to be averaged. Returns ------- median : dictionary Dictionary indexed by data label, each value of which is a dictionary with keys 'median', 'count', 'avg_abs_dev', and 'bin' (the values of the bin edges.) """ # TODO Update for 2.7 compatability. if isinstance(data_label, str): data_label = [data_label, ] elif not isinstance(data_label, collections.Sequence): raise ValueError("Please pass data_label as a string or " "collection of strings.") # Modeled after pysat.ssnl.median2D # Make bin boundaries. # y: values at label3 # z: *data_labels biny = np.linspace(bin3[0], bin3[1], bin3[2]+1) numy = len(biny)-1 numz = len(data_label) # Ranges yarr, zarr = map(np.arange, (numy, numz)) # Store data here. ans = [[[collections.deque()] for j in yarr] for k in zarr] # Filter data by bounds and bin it. # Idiom for loading all of the data in an instrument's bounds. for inst in self: for inst in inst: if len(inst.data) != 0: # Select indicies for each piece of data we're interest in. # Not all of this data is in bounds on label3 but we'll # sort this later. min1, max1 = bounds1 min2, max2 = bounds2 data1 = inst.data[label1] data2 = inst.data[label2] in_bounds, = np.where((min1 <= data1) & (data1 < max1) & (min2 <= data2) & (data2 < max2)) # Grab the data in bounds on data1, data2. data_considered = inst.data.iloc[in_bounds] y_indexes = np.digitize(data_considered[label3], biny) - 1 # Iterate over the bins along y for yj in yarr: # Indicies of data in this bin yindex, = np.where(y_indexes == yj) # If there's data in this bin if len(yindex) > 0: # For each data label, add the points. for zk in zarr: ans[zk][yj][0].extend( data_considered.ix[yindex, data_label[zk]].tolist()) # Now for the averaging. # Let's, try .. packing the answers for the 2d function. numx = 1 xarr = np.arange(numx) binx = None # TODO modify output out_2d = _calc_2d_median(ans, data_label, binx, biny, xarr, yarr, zarr, numx, numy, numz) # Transform output output = {} for i, label in enumerate(data_label): median = [r[0] for r in out_2d[label]['median']] count = [r[0] for r in out_2d[label]['count']] dev = [r[0] for r in out_2d[label]['avg_abs_dev']] output[label] = {'median': median, 'count': count, 'avg_abs_dev': dev, 'bin': out_2d[label]['bin_y']} return output
[ "def", "add", "(", "self", ",", "bounds1", ",", "label1", ",", "bounds2", ",", "label2", ",", "bin3", ",", "label3", ",", "data_label", ")", ":", "# TODO Update for 2.7 compatability.", "if", "isinstance", "(", "data_label", ",", "str", ")", ":", "data_label", "=", "[", "data_label", ",", "]", "elif", "not", "isinstance", "(", "data_label", ",", "collections", ".", "Sequence", ")", ":", "raise", "ValueError", "(", "\"Please pass data_label as a string or \"", "\"collection of strings.\"", ")", "# Modeled after pysat.ssnl.median2D", "# Make bin boundaries.", "# y: values at label3", "# z: *data_labels", "biny", "=", "np", ".", "linspace", "(", "bin3", "[", "0", "]", ",", "bin3", "[", "1", "]", ",", "bin3", "[", "2", "]", "+", "1", ")", "numy", "=", "len", "(", "biny", ")", "-", "1", "numz", "=", "len", "(", "data_label", ")", "# Ranges", "yarr", ",", "zarr", "=", "map", "(", "np", ".", "arange", ",", "(", "numy", ",", "numz", ")", ")", "# Store data here.", "ans", "=", "[", "[", "[", "collections", ".", "deque", "(", ")", "]", "for", "j", "in", "yarr", "]", "for", "k", "in", "zarr", "]", "# Filter data by bounds and bin it.", "# Idiom for loading all of the data in an instrument's bounds.", "for", "inst", "in", "self", ":", "for", "inst", "in", "inst", ":", "if", "len", "(", "inst", ".", "data", ")", "!=", "0", ":", "# Select indicies for each piece of data we're interest in.", "# Not all of this data is in bounds on label3 but we'll", "# sort this later.", "min1", ",", "max1", "=", "bounds1", "min2", ",", "max2", "=", "bounds2", "data1", "=", "inst", ".", "data", "[", "label1", "]", "data2", "=", "inst", ".", "data", "[", "label2", "]", "in_bounds", ",", "=", "np", ".", "where", "(", "(", "min1", "<=", "data1", ")", "&", "(", "data1", "<", "max1", ")", "&", "(", "min2", "<=", "data2", ")", "&", "(", "data2", "<", "max2", ")", ")", "# Grab the data in bounds on data1, data2.", "data_considered", "=", "inst", ".", "data", ".", "iloc", "[", "in_bounds", "]", "y_indexes", "=", "np", ".", "digitize", "(", "data_considered", "[", "label3", "]", ",", "biny", ")", "-", "1", "# Iterate over the bins along y", "for", "yj", "in", "yarr", ":", "# Indicies of data in this bin", "yindex", ",", "=", "np", ".", "where", "(", "y_indexes", "==", "yj", ")", "# If there's data in this bin", "if", "len", "(", "yindex", ")", ">", "0", ":", "# For each data label, add the points.", "for", "zk", "in", "zarr", ":", "ans", "[", "zk", "]", "[", "yj", "]", "[", "0", "]", ".", "extend", "(", "data_considered", ".", "ix", "[", "yindex", ",", "data_label", "[", "zk", "]", "]", ".", "tolist", "(", ")", ")", "# Now for the averaging.", "# Let's, try .. packing the answers for the 2d function.", "numx", "=", "1", "xarr", "=", "np", ".", "arange", "(", "numx", ")", "binx", "=", "None", "# TODO modify output", "out_2d", "=", "_calc_2d_median", "(", "ans", ",", "data_label", ",", "binx", ",", "biny", ",", "xarr", ",", "yarr", ",", "zarr", ",", "numx", ",", "numy", ",", "numz", ")", "# Transform output", "output", "=", "{", "}", "for", "i", ",", "label", "in", "enumerate", "(", "data_label", ")", ":", "median", "=", "[", "r", "[", "0", "]", "for", "r", "in", "out_2d", "[", "label", "]", "[", "'median'", "]", "]", "count", "=", "[", "r", "[", "0", "]", "for", "r", "in", "out_2d", "[", "label", "]", "[", "'count'", "]", "]", "dev", "=", "[", "r", "[", "0", "]", "for", "r", "in", "out_2d", "[", "label", "]", "[", "'avg_abs_dev'", "]", "]", "output", "[", "label", "]", "=", "{", "'median'", ":", "median", ",", "'count'", ":", "count", ",", "'avg_abs_dev'", ":", "dev", ",", "'bin'", ":", "out_2d", "[", "label", "]", "[", "'bin_y'", "]", "}", "return", "output" ]
38.25
19.75
def write_connection_file(fname=None, shell_port=0, iopub_port=0, stdin_port=0, hb_port=0, ip=LOCALHOST, key=b''): """Generates a JSON config file, including the selection of random ports. Parameters ---------- fname : unicode The path to the file to write shell_port : int, optional The port to use for ROUTER channel. iopub_port : int, optional The port to use for the SUB channel. stdin_port : int, optional The port to use for the REQ (raw input) channel. hb_port : int, optional The port to use for the hearbeat REP channel. ip : str, optional The ip address the kernel will bind to. key : str, optional The Session key used for HMAC authentication. """ # default to temporary connector file if not fname: fname = tempfile.mktemp('.json') # Find open ports as necessary. ports = [] ports_needed = int(shell_port <= 0) + int(iopub_port <= 0) + \ int(stdin_port <= 0) + int(hb_port <= 0) for i in xrange(ports_needed): sock = socket.socket() sock.bind(('', 0)) ports.append(sock) for i, sock in enumerate(ports): port = sock.getsockname()[1] sock.close() ports[i] = port if shell_port <= 0: shell_port = ports.pop(0) if iopub_port <= 0: iopub_port = ports.pop(0) if stdin_port <= 0: stdin_port = ports.pop(0) if hb_port <= 0: hb_port = ports.pop(0) cfg = dict( shell_port=shell_port, iopub_port=iopub_port, stdin_port=stdin_port, hb_port=hb_port, ) cfg['ip'] = ip cfg['key'] = bytes_to_str(key) with open(fname, 'w') as f: f.write(json.dumps(cfg, indent=2)) return fname, cfg
[ "def", "write_connection_file", "(", "fname", "=", "None", ",", "shell_port", "=", "0", ",", "iopub_port", "=", "0", ",", "stdin_port", "=", "0", ",", "hb_port", "=", "0", ",", "ip", "=", "LOCALHOST", ",", "key", "=", "b''", ")", ":", "# default to temporary connector file", "if", "not", "fname", ":", "fname", "=", "tempfile", ".", "mktemp", "(", "'.json'", ")", "# Find open ports as necessary.", "ports", "=", "[", "]", "ports_needed", "=", "int", "(", "shell_port", "<=", "0", ")", "+", "int", "(", "iopub_port", "<=", "0", ")", "+", "int", "(", "stdin_port", "<=", "0", ")", "+", "int", "(", "hb_port", "<=", "0", ")", "for", "i", "in", "xrange", "(", "ports_needed", ")", ":", "sock", "=", "socket", ".", "socket", "(", ")", "sock", ".", "bind", "(", "(", "''", ",", "0", ")", ")", "ports", ".", "append", "(", "sock", ")", "for", "i", ",", "sock", "in", "enumerate", "(", "ports", ")", ":", "port", "=", "sock", ".", "getsockname", "(", ")", "[", "1", "]", "sock", ".", "close", "(", ")", "ports", "[", "i", "]", "=", "port", "if", "shell_port", "<=", "0", ":", "shell_port", "=", "ports", ".", "pop", "(", "0", ")", "if", "iopub_port", "<=", "0", ":", "iopub_port", "=", "ports", ".", "pop", "(", "0", ")", "if", "stdin_port", "<=", "0", ":", "stdin_port", "=", "ports", ".", "pop", "(", "0", ")", "if", "hb_port", "<=", "0", ":", "hb_port", "=", "ports", ".", "pop", "(", "0", ")", "cfg", "=", "dict", "(", "shell_port", "=", "shell_port", ",", "iopub_port", "=", "iopub_port", ",", "stdin_port", "=", "stdin_port", ",", "hb_port", "=", "hb_port", ",", ")", "cfg", "[", "'ip'", "]", "=", "ip", "cfg", "[", "'key'", "]", "=", "bytes_to_str", "(", "key", ")", "with", "open", "(", "fname", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "json", ".", "dumps", "(", "cfg", ",", "indent", "=", "2", ")", ")", "return", "fname", ",", "cfg" ]
27.469697
17.5
def get_id(id_or_obj): """ Returns the 'id' attribute of 'id_or_obj' if present; if not, returns 'id_or_obj'. """ if isinstance(id_or_obj, six.string_types + (int,)): # It's an ID return id_or_obj try: return id_or_obj.id except AttributeError: return id_or_obj
[ "def", "get_id", "(", "id_or_obj", ")", ":", "if", "isinstance", "(", "id_or_obj", ",", "six", ".", "string_types", "+", "(", "int", ",", ")", ")", ":", "# It's an ID", "return", "id_or_obj", "try", ":", "return", "id_or_obj", ".", "id", "except", "AttributeError", ":", "return", "id_or_obj" ]
25.833333
15.5
def get_data(self, compact=True): ''' Returns data representing current state of the form. While Form.raw_data may contain alien fields and invalid data, this method returns only valid fields that belong to this form only. It's designed to pass somewhere current state of the form (as query string or by other means). ''' data = MultiDict() for field in self.fields: raw_value = field.from_python(self.python_data[field.name]) field.set_raw_value(data, raw_value) if compact: data = MultiDict([(k, v) for k, v in data.items() if v]) return data
[ "def", "get_data", "(", "self", ",", "compact", "=", "True", ")", ":", "data", "=", "MultiDict", "(", ")", "for", "field", "in", "self", ".", "fields", ":", "raw_value", "=", "field", ".", "from_python", "(", "self", ".", "python_data", "[", "field", ".", "name", "]", ")", "field", ".", "set_raw_value", "(", "data", ",", "raw_value", ")", "if", "compact", ":", "data", "=", "MultiDict", "(", "[", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", "if", "v", "]", ")", "return", "data" ]
43.6
23.2
def update_pop(self): """Assigns fitnesses to particles that are within bounds.""" valid_particles = [] invalid_particles = [] for part in self.population: if any(x > 1 or x < -1 for x in part): invalid_particles.append(part) else: valid_particles.append(part) self._params['model_count'] += len(valid_particles) for part in valid_particles: self.update_particle(part) self.assign_fitnesses(valid_particles) for part in valid_particles: if part.fitness > part.best.fitness: part.best = creator.Particle(part) part.best.fitness = part.fitness for part in invalid_particles: self.update_particle(part) self.population[:] = valid_particles + invalid_particles self.population.sort(key=lambda x: x.ident)
[ "def", "update_pop", "(", "self", ")", ":", "valid_particles", "=", "[", "]", "invalid_particles", "=", "[", "]", "for", "part", "in", "self", ".", "population", ":", "if", "any", "(", "x", ">", "1", "or", "x", "<", "-", "1", "for", "x", "in", "part", ")", ":", "invalid_particles", ".", "append", "(", "part", ")", "else", ":", "valid_particles", ".", "append", "(", "part", ")", "self", ".", "_params", "[", "'model_count'", "]", "+=", "len", "(", "valid_particles", ")", "for", "part", "in", "valid_particles", ":", "self", ".", "update_particle", "(", "part", ")", "self", ".", "assign_fitnesses", "(", "valid_particles", ")", "for", "part", "in", "valid_particles", ":", "if", "part", ".", "fitness", ">", "part", ".", "best", ".", "fitness", ":", "part", ".", "best", "=", "creator", ".", "Particle", "(", "part", ")", "part", ".", "best", ".", "fitness", "=", "part", ".", "fitness", "for", "part", "in", "invalid_particles", ":", "self", ".", "update_particle", "(", "part", ")", "self", ".", "population", "[", ":", "]", "=", "valid_particles", "+", "invalid_particles", "self", ".", "population", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", ".", "ident", ")" ]
42.47619
8.952381
def get_parameter(self): """ get the parameter object from the system for this var needs to be backend safe (not passing or storing bundle) """ if not self.is_param: raise ValueError("this var does not point to a parameter") # this is quite expensive, so let's cache the parameter object so we only # have to filter on the first time this is called if self._parameter is None: self._parameter = self._bundle.get_parameter(uniqueid=self.unique_label, check_visible=False, check_default=False) return self._parameter
[ "def", "get_parameter", "(", "self", ")", ":", "if", "not", "self", ".", "is_param", ":", "raise", "ValueError", "(", "\"this var does not point to a parameter\"", ")", "# this is quite expensive, so let's cache the parameter object so we only", "# have to filter on the first time this is called", "if", "self", ".", "_parameter", "is", "None", ":", "self", ".", "_parameter", "=", "self", ".", "_bundle", ".", "get_parameter", "(", "uniqueid", "=", "self", ".", "unique_label", ",", "check_visible", "=", "False", ",", "check_default", "=", "False", ")", "return", "self", ".", "_parameter" ]
39.933333
25.4
def sendcontrol(self, char): '''Helper method that wraps send() with mnemonic access for sending control character to the child (such as Ctrl-C or Ctrl-D). For example, to send Ctrl-G (ASCII 7, bell, '\a'):: child.sendcontrol('g') See also, sendintr() and sendeof(). ''' char = char.lower() a = ord(char) if 97 <= a <= 122: a = a - ord('a') + 1 byte = _byte(a) return self._writeb(byte), byte d = {'@': 0, '`': 0, '[': 27, '{': 27, '\\': 28, '|': 28, ']': 29, '}': 29, '^': 30, '~': 30, '_': 31, '?': 127} if char not in d: return 0, b'' byte = _byte(d[char]) return self._writeb(byte), byte
[ "def", "sendcontrol", "(", "self", ",", "char", ")", ":", "char", "=", "char", ".", "lower", "(", ")", "a", "=", "ord", "(", "char", ")", "if", "97", "<=", "a", "<=", "122", ":", "a", "=", "a", "-", "ord", "(", "'a'", ")", "+", "1", "byte", "=", "_byte", "(", "a", ")", "return", "self", ".", "_writeb", "(", "byte", ")", ",", "byte", "d", "=", "{", "'@'", ":", "0", ",", "'`'", ":", "0", ",", "'['", ":", "27", ",", "'{'", ":", "27", ",", "'\\\\'", ":", "28", ",", "'|'", ":", "28", ",", "']'", ":", "29", ",", "'}'", ":", "29", ",", "'^'", ":", "30", ",", "'~'", ":", "30", ",", "'_'", ":", "31", ",", "'?'", ":", "127", "}", "if", "char", "not", "in", "d", ":", "return", "0", ",", "b''", "byte", "=", "_byte", "(", "d", "[", "char", "]", ")", "return", "self", ".", "_writeb", "(", "byte", ")", ",", "byte" ]
29.518519
17.074074
def get_max_instability(self, min_voltage=None, max_voltage=None): """ The maximum instability along a path for a specific voltage range. Args: min_voltage: The minimum allowable voltage. max_voltage: The maximum allowable voltage. Returns: Maximum decomposition energy of all compounds along the insertion path (a subset of the path can be chosen by the optional arguments) """ data = [] for pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.decomp_e_charge is not None: data.append(pair.decomp_e_charge) if pair.decomp_e_discharge is not None: data.append(pair.decomp_e_discharge) return max(data) if len(data) > 0 else None
[ "def", "get_max_instability", "(", "self", ",", "min_voltage", "=", "None", ",", "max_voltage", "=", "None", ")", ":", "data", "=", "[", "]", "for", "pair", "in", "self", ".", "_select_in_voltage_range", "(", "min_voltage", ",", "max_voltage", ")", ":", "if", "pair", ".", "decomp_e_charge", "is", "not", "None", ":", "data", ".", "append", "(", "pair", ".", "decomp_e_charge", ")", "if", "pair", ".", "decomp_e_discharge", "is", "not", "None", ":", "data", ".", "append", "(", "pair", ".", "decomp_e_discharge", ")", "return", "max", "(", "data", ")", "if", "len", "(", "data", ")", ">", "0", "else", "None" ]
42.157895
21.421053
def storage_command(self, name, method_name=None, command_type=None, oauth=False, generic_update=None, **kwargs): """ Registers an Azure CLI Storage Data Plane command. These commands always include the four parameters which can be used to obtain a storage client: account-name, account-key, connection-string, and sas-token. """ if generic_update: command_name = '{} {}'.format(self.group_name, name) if self.group_name else name self.generic_update_command(name, **kwargs) elif command_type: command_name = self.command(name, method_name, command_type=command_type, **kwargs) else: command_name = self.command(name, method_name, **kwargs) self._register_data_plane_account_arguments(command_name) if oauth: self._register_data_plane_oauth_arguments(command_name)
[ "def", "storage_command", "(", "self", ",", "name", ",", "method_name", "=", "None", ",", "command_type", "=", "None", ",", "oauth", "=", "False", ",", "generic_update", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "generic_update", ":", "command_name", "=", "'{} {}'", ".", "format", "(", "self", ".", "group_name", ",", "name", ")", "if", "self", ".", "group_name", "else", "name", "self", ".", "generic_update_command", "(", "name", ",", "*", "*", "kwargs", ")", "elif", "command_type", ":", "command_name", "=", "self", ".", "command", "(", "name", ",", "method_name", ",", "command_type", "=", "command_type", ",", "*", "*", "kwargs", ")", "else", ":", "command_name", "=", "self", ".", "command", "(", "name", ",", "method_name", ",", "*", "*", "kwargs", ")", "self", ".", "_register_data_plane_account_arguments", "(", "command_name", ")", "if", "oauth", ":", "self", ".", "_register_data_plane_oauth_arguments", "(", "command_name", ")" ]
66.769231
27.230769
def cull_edges(self, stat, threshold=0.5, comparator=ge): """Delete edges whose stat >= ``threshold`` (default 0.5). Optional argument ``comparator`` will replace >= as the test for whether to cull. You can use the name of a stored function. """ return self.cull_portals(stat, threshold, comparator)
[ "def", "cull_edges", "(", "self", ",", "stat", ",", "threshold", "=", "0.5", ",", "comparator", "=", "ge", ")", ":", "return", "self", ".", "cull_portals", "(", "stat", ",", "threshold", ",", "comparator", ")" ]
41.75
22.125
def _get_grammar_errors(self,pos,text,tokens): """ Internal function to get the number of grammar errors in given text pos - part of speech tagged text (list) text - normal text (list) tokens - list of lists of tokenized text """ word_counts = [max(len(t),1) for t in tokens] good_pos_tags = [] min_pos_seq=2 max_pos_seq=4 bad_pos_positions=[] for i in xrange(0, len(text)): pos_seq = [tag[1] for tag in pos[i]] pos_ngrams = util_functions.ngrams(pos_seq, min_pos_seq, max_pos_seq) long_pos_ngrams=[z for z in pos_ngrams if z.count(' ')==(max_pos_seq-1)] bad_pos_tuples=[[z,z+max_pos_seq] for z in xrange(0,len(long_pos_ngrams)) if long_pos_ngrams[z] not in self._good_pos_ngrams] bad_pos_tuples.sort(key=operator.itemgetter(1)) to_delete=[] for m in reversed(xrange(len(bad_pos_tuples)-1)): start, end = bad_pos_tuples[m] for j in xrange(m+1, len(bad_pos_tuples)): lstart, lend = bad_pos_tuples[j] if lstart >= start and lstart <= end: bad_pos_tuples[m][1]=bad_pos_tuples[j][1] to_delete.append(j) fixed_bad_pos_tuples=[bad_pos_tuples[z] for z in xrange(0,len(bad_pos_tuples)) if z not in to_delete] bad_pos_positions.append(fixed_bad_pos_tuples) overlap_ngrams = [z for z in pos_ngrams if z in self._good_pos_ngrams] if (len(pos_ngrams)-len(overlap_ngrams))>0: divisor=len(pos_ngrams)/len(pos_seq) else: divisor=1 if divisor == 0: divisor=1 good_grammar_ratio = (len(pos_ngrams)-len(overlap_ngrams))/divisor good_pos_tags.append(good_grammar_ratio) return good_pos_tags,bad_pos_positions
[ "def", "_get_grammar_errors", "(", "self", ",", "pos", ",", "text", ",", "tokens", ")", ":", "word_counts", "=", "[", "max", "(", "len", "(", "t", ")", ",", "1", ")", "for", "t", "in", "tokens", "]", "good_pos_tags", "=", "[", "]", "min_pos_seq", "=", "2", "max_pos_seq", "=", "4", "bad_pos_positions", "=", "[", "]", "for", "i", "in", "xrange", "(", "0", ",", "len", "(", "text", ")", ")", ":", "pos_seq", "=", "[", "tag", "[", "1", "]", "for", "tag", "in", "pos", "[", "i", "]", "]", "pos_ngrams", "=", "util_functions", ".", "ngrams", "(", "pos_seq", ",", "min_pos_seq", ",", "max_pos_seq", ")", "long_pos_ngrams", "=", "[", "z", "for", "z", "in", "pos_ngrams", "if", "z", ".", "count", "(", "' '", ")", "==", "(", "max_pos_seq", "-", "1", ")", "]", "bad_pos_tuples", "=", "[", "[", "z", ",", "z", "+", "max_pos_seq", "]", "for", "z", "in", "xrange", "(", "0", ",", "len", "(", "long_pos_ngrams", ")", ")", "if", "long_pos_ngrams", "[", "z", "]", "not", "in", "self", ".", "_good_pos_ngrams", "]", "bad_pos_tuples", ".", "sort", "(", "key", "=", "operator", ".", "itemgetter", "(", "1", ")", ")", "to_delete", "=", "[", "]", "for", "m", "in", "reversed", "(", "xrange", "(", "len", "(", "bad_pos_tuples", ")", "-", "1", ")", ")", ":", "start", ",", "end", "=", "bad_pos_tuples", "[", "m", "]", "for", "j", "in", "xrange", "(", "m", "+", "1", ",", "len", "(", "bad_pos_tuples", ")", ")", ":", "lstart", ",", "lend", "=", "bad_pos_tuples", "[", "j", "]", "if", "lstart", ">=", "start", "and", "lstart", "<=", "end", ":", "bad_pos_tuples", "[", "m", "]", "[", "1", "]", "=", "bad_pos_tuples", "[", "j", "]", "[", "1", "]", "to_delete", ".", "append", "(", "j", ")", "fixed_bad_pos_tuples", "=", "[", "bad_pos_tuples", "[", "z", "]", "for", "z", "in", "xrange", "(", "0", ",", "len", "(", "bad_pos_tuples", ")", ")", "if", "z", "not", "in", "to_delete", "]", "bad_pos_positions", ".", "append", "(", "fixed_bad_pos_tuples", ")", "overlap_ngrams", "=", "[", "z", "for", "z", "in", "pos_ngrams", "if", "z", "in", "self", ".", "_good_pos_ngrams", "]", "if", "(", "len", "(", "pos_ngrams", ")", "-", "len", "(", "overlap_ngrams", ")", ")", ">", "0", ":", "divisor", "=", "len", "(", "pos_ngrams", ")", "/", "len", "(", "pos_seq", ")", "else", ":", "divisor", "=", "1", "if", "divisor", "==", "0", ":", "divisor", "=", "1", "good_grammar_ratio", "=", "(", "len", "(", "pos_ngrams", ")", "-", "len", "(", "overlap_ngrams", ")", ")", "/", "divisor", "good_pos_tags", ".", "append", "(", "good_grammar_ratio", ")", "return", "good_pos_tags", ",", "bad_pos_positions" ]
48.820513
20.25641
def resetAndRejoin(self, timeout): """reset and join back Thread Network with a given timeout delay Args: timeout: a timeout interval before rejoin Thread Network Returns: True: successful to reset and rejoin Thread Network False: fail to reset and rejoin the Thread Network """ print '%s call resetAndRejoin' % self.port print timeout try: if self.__sendCommand(WPANCTL_CMD + 'setprop Daemon:AutoAssociateAfterReset false')[0] != 'Fail': time.sleep(0.5) if self.__sendCommand(WPANCTL_CMD + 'reset')[0] != 'Fail': self.isPowerDown = True else: return False else: return False time.sleep(timeout) if self.deviceRole == Thread_Device_Role.SED: self.setPollingRate(self.sedPollingRate) if self.__sendCommand(WPANCTL_CMD + 'attach')[0] != 'Fail': time.sleep(3) else: return False if self.__sendCommand(WPANCTL_CMD + 'setprop Daemon:AutoAssociateAfterReset true')[0] == 'Fail': return False if self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:State')[0]) != 'associated': print '[FAIL] reset and rejoin' return False return True except Exception, e: ModuleHelper.WriteIntoDebugLogger('resetAndRejoin() Error: ' + str(e))
[ "def", "resetAndRejoin", "(", "self", ",", "timeout", ")", ":", "print", "'%s call resetAndRejoin'", "%", "self", ".", "port", "print", "timeout", "try", ":", "if", "self", ".", "__sendCommand", "(", "WPANCTL_CMD", "+", "'setprop Daemon:AutoAssociateAfterReset false'", ")", "[", "0", "]", "!=", "'Fail'", ":", "time", ".", "sleep", "(", "0.5", ")", "if", "self", ".", "__sendCommand", "(", "WPANCTL_CMD", "+", "'reset'", ")", "[", "0", "]", "!=", "'Fail'", ":", "self", ".", "isPowerDown", "=", "True", "else", ":", "return", "False", "else", ":", "return", "False", "time", ".", "sleep", "(", "timeout", ")", "if", "self", ".", "deviceRole", "==", "Thread_Device_Role", ".", "SED", ":", "self", ".", "setPollingRate", "(", "self", ".", "sedPollingRate", ")", "if", "self", ".", "__sendCommand", "(", "WPANCTL_CMD", "+", "'attach'", ")", "[", "0", "]", "!=", "'Fail'", ":", "time", ".", "sleep", "(", "3", ")", "else", ":", "return", "False", "if", "self", ".", "__sendCommand", "(", "WPANCTL_CMD", "+", "'setprop Daemon:AutoAssociateAfterReset true'", ")", "[", "0", "]", "==", "'Fail'", ":", "return", "False", "if", "self", ".", "__stripValue", "(", "self", ".", "__sendCommand", "(", "WPANCTL_CMD", "+", "'getprop -v NCP:State'", ")", "[", "0", "]", ")", "!=", "'associated'", ":", "print", "'[FAIL] reset and rejoin'", "return", "False", "return", "True", "except", "Exception", ",", "e", ":", "ModuleHelper", ".", "WriteIntoDebugLogger", "(", "'resetAndRejoin() Error: '", "+", "str", "(", "e", ")", ")" ]
38
24.075