content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
from cfn_kong_provider import KongProvider request_schema = { "type": "object", "required": ["AdminURL", "ACL"], "properties": { "AdminURL": { "type": "string", "pattern": "^https?://.+", "description": "of kong admin port"}, "JWT": { "type": "object", "required": ["PrivateKeyParameterName"], "properties": { "Issuer": { "type": "string", "default": "admin", "description": "iss attribute of the JWT token" }, "PrivateKeyParameterName": { "type": "string", "description": "containing the RSA key in PEM encoding to sign the JWT token with" } } }, "ACL": { "type": "object", "required": ["consumer", "group"], "properties": { "consumer": { "type": "object", "required": ["id"], "properties": { "id": { "type": "string", "description": "of the consumer" } } }, "group": { "type": "string" } } } } } provider = KongACLProvider()
[ 6738, 269, 22184, 62, 74, 506, 62, 15234, 1304, 1330, 9071, 29495, 198, 198, 25927, 62, 15952, 2611, 796, 1391, 198, 220, 220, 220, 366, 4906, 1298, 366, 15252, 1600, 198, 220, 220, 220, 366, 35827, 1298, 14631, 46787, 21886, 1600, 36...
1.656784
877
#!/usr/bin/env python import rospy import cv2 import time from person_detection import PersonDetection from pose_estimation import PoseEstimation from camera_reader import CameraStreamer from persons import Persons # color constants RED_COLOR = (0, 0, 255) BLUE_COLOR = (255, 0, 0) WHITE_COLOR = (255, 255, 255) DEFAULT_POINTS = {'1', '2', '3', '4', '5', '6', '7'} if __name__ == "__main__": rospy.init_node("human_wave_detection", anonymous=True) instance = WaveDetector() try: instance.process() except KeyboardInterrupt: rospy.logwarn("Shutting done ...") finally: rospy.loginfo("Exiting ...")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 686, 2777, 88, 198, 11748, 269, 85, 17, 198, 11748, 640, 198, 6738, 1048, 62, 15255, 3213, 1330, 7755, 11242, 3213, 198, 6738, 12705, 62, 395, 18991, 1330, 37557, 22362, 18...
2.606426
249
import numpy as np import os from numpy.linalg import inv from numpy.linalg import det list1=["like_3x2pt_LSST_Y10_area=1.800000e+04_dmo","like_3x2pt_WFIRST_area=2.000000e+03_dmo","like_3x2pt_WFIRST_area=1.800000e+04_dmo"] FOMDE=np.array([1.0,1.0,1.0]) i=0 FOMDE[i] print FOMDE[i] for name in list1: i=0 filen=name print filen d1 = np.genfromtxt(filen,skip_header=7800000) #d1.shape cov=np.cov(d1[:,:],rowvar=False) covDE=cov[np.ix_([3,4],[3,4])] FM=inv(cov) FOMDE[i]=(np.power(det(inv(covDE)),1./2)) print FOMDE[i] i=i+1
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 6738, 299, 32152, 13, 75, 1292, 70, 1330, 800, 198, 6738, 299, 32152, 13, 75, 1292, 70, 1330, 1062, 198, 198, 4868, 16, 28, 14692, 2339, 62, 18, 87, 17, 457, 62, 6561, 2257, 6...
1.806962
316
from flask_restplus import Api from .parallel_templates import template api = Api( title='C99 Parallel Template Api', version='1.0', description="""Provides a set of parallel programming templates for easy parallelization.""" ) # Adding template resource namesace to the API api.add_namespace(template.api)
[ 6738, 42903, 62, 2118, 9541, 1330, 5949, 72, 198, 6738, 764, 1845, 29363, 62, 11498, 17041, 1330, 11055, 628, 198, 15042, 796, 5949, 72, 7, 198, 220, 220, 220, 3670, 11639, 34, 2079, 42945, 37350, 5949, 72, 3256, 198, 220, 220, 220, ...
3.27
100
#!@WHICHPYTHON@ import string, sys #------------------ Alphabet ------------------- class Alphabet(object): """Biological alphabet class. This defines the set of symbols from which various objects can be built, e.g. sequences and motifs. The symbol set is immutable and accessed as a tuple. symstr: symbols in alphabet as either a tuple or string """ def __init__(self, symstr): """Construct an alphabet from a string or tuple of characters. Lower case characters will be converted to upper case. Example: >>> alpha = sequence.Alphabet('ACGTttga') >>> alpha.getSymbols() will construct the DNA alphabet and output: ('A', 'C', 'G', 'T') """ symlst = [] for s in [str(sym).upper()[0] for sym in symstr]: if not s in symlst: symlst.append(s) self.symbols = tuple(symlst) def getSymbols(self): """Retrieve a tuple with all symbols, immutable membership and order""" return self.symbols def isValidSymbol(self, sym): """Check if the symbol is a member of alphabet""" return any([s==sym for s in self.symbols]) def getIndex(self, sym): """Retrieve the index of the symbol (immutable)""" for idx in range (len(self.symbols)): if self.symbols[idx] == sym: return idx raise RuntimeError("Symbol " + sym + " does not exist in alphabet") def isValidString(self, symstr): """Check if the string contains only symbols that belong to the alphabet""" found = True for sym in symstr: if self.isValidSymbol(sym) == False: return False return True def getLen(self): """Retrieve the number of symbols in (the length of) the alphabet""" return len(self.symbols) # pre-defined alphabets that can be specified by their name predefAlphabets = [ ("DNA" , Alphabet('ACGT')), ("RNA" , Alphabet('ACGU')), ("Extended DNA" , Alphabet('ACGTYRN')), ("Protein" , Alphabet('ACDEFGHIKLMNPQRSTVWY')), ("Extended Protein" , Alphabet('ACDEFGHIKLMNPQRSTVWYX')), ("TM Labels" , Alphabet('MIO')) ] def getAlphabet(name): """Retrieve a pre-defined alphabet by name. Currently, "Protein", "DNA", "RNA", "Extended DNA", "Extended Protein" and "TM Labels" are available. Example: >>> alpha = sequence.getAlphabet('Protein') >>> alpha.getSymbols() will retrieve the 20 amino acid alphabet and output the tuple: ('A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y') """ for (xname, xalpha) in predefAlphabets: if xname == name: return xalpha return None #------------------ Sequence ------------------- class Sequence(object): """Biological sequence class. Sequence data is immutable. data: the sequence data as a tuple or string alpha: the alphabet from which symbols are taken name: the sequence name, if any info: can contain additional sequence information apart from the name """ def __init__(self, sequence, alpha = None, name = "", seqinfo = ""): """Create a sequence with sequence data. Specifying the alphabet is optional, so is the name and info. Example: >>> myseq = sequence.Sequence('MVSAKKVPAIAMSFGVSF') will create a sequence with name "", and assign one of the predefined alphabets on basis of what symbols were used. >>> myseq.getAlphabet().getSymbols() will most likely output the standard protein alphabet: ('A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y') """ if type(sequence) is str: self.data = tuple(sequence.upper()) elif type(sequence) is tuple: self.data = sequence elif type(sequence) is list: self.data = tuple([s.upper() for s in sequence]) else: raise RuntimeError("Sequence data is not specified correctly: must be string or tuple") # Resolve choice of alphabet validAlphabet = False if alpha == None: # Alphabet is not set, attempt to set it automatically... for (xname, xalpha) in predefAlphabets: # Iterate through each predefined alphabet, in order if xalpha.isValidString( self.data ): # This alphabet works, go with it self.alpha = alpha = xalpha validAlphabet = True break self.name = name self.info = seqinfo if validAlphabet == False: # we were either unsuccessful above or the alphabet was specified so test it if type(alpha) is str: # check if name is a predefined alphabet for (xname, xalpha) in predefAlphabets: # Iterate through each predefined alphabet, check for name if (xname == alpha): alpha = xalpha break if type(alpha) is Alphabet: # the alphabet is specified if alpha.isValidString(self.data) == False: raise RuntimeError("Invalid alphabet specified: "+"".join(alpha.getSymbols())+" is not compatible with sequence '"+"".join(self.data)+"'") else: self.alpha = alpha else: raise RuntimeError("Could not identify alphabet from sequence") #basic getters and setters for the class def getName(self): """Get the name of the sequence""" return self.name def getInfo(self): """Get additional info of the sequence (e.g. from the defline in a FASTA file)""" return self.info def getAlphabet(self): """Retrieve the alphabet that is assigned to this sequence""" return self.alpha def setName(self, name): """Change the name of the sequence""" self.name = name def setAlphabet(self, alpha): """Set the alphabet, throws an exception if it is not compatible with the sequence data""" if type(alpha) is Alphabet: if alpha.isValid( sequence ) == False: raise RuntimeError( "Invalid alphabet specified" ) #sequence functions def getSequence(self): """Retrieve the sequence data (a tuple of symbols)""" return self.data def getString(self): """Retrieve the sequence data as a string (copy of actual data)""" return "".join(self.data) def getLen(self): """Get the length of the sequence (number of symbols)""" return len(self.data) def getSite(self, position, length = 1): """Retrieve a site in the sequence of desired length. Note that positions go from 0 to length-1, and that if the requested site extends beyond those the method throws an exception. """ if position >= 0 and position <= self.getLen() - length: if length == 1: return self.data[position] else: return self.data[position:position+length] else: raise RuntimeError( "Attempt to access invalid position in sequence "+self.getName() ) def nice(self): """ A short description of the sequence """ print self.getName(), ":", self.getLen() def readStrings(filename): """ Read one or more lines of text from a file--for example an alignment. Return as a list of strings. filename: name of file """ txtlist = [] f = open(filename) for line in f.readlines(): txtlist.extend(line.split()) return txtlist def readFASTA(filename, alpha = None): """ Read one or more sequences from a file in FASTA format. filename: name of file to load sequences from alpha: alphabet that is used (if left unspecified, an attempt is made to identify the alphabet for each individual sequence) """ seqlist = [] seqname = None seqinfo = None seqdata = [] fh = open(filename) thisline = fh.readline() while (thisline): if (thisline[0] == '>'): # new sequence if (seqname): # take care of the data that is already in the buffer before processing the new sequence try: seqnew = Sequence(seqdata, alpha, seqname, seqinfo) seqlist.append(seqnew) except RuntimeError, e: print >> sys.stderr, "Warning: "+seqname+" is invalid (ignored): ", e seqinfo = thisline[1:-1] # everything on the defline is "info" seqname = seqinfo.split()[0] # up to first space seqdata = [] else: # pull out the sequence data cleanline = thisline.split() for line in cleanline: seqdata.extend(tuple(line.strip('*'))) # sometimes a line ends with an asterisk in FASTA files thisline = fh.readline() if (seqname): try: seqnew = Sequence(seqdata, alpha, seqname, seqinfo) seqlist.append(seqnew) except RuntimeError, e: print >> sys.stderr, "Warning: " + seqname + " is invalid (ignored): ", e else: raise RuntimeError("No sequences on FASTA format found in this file") fh.close() return seqlist def _writeOneFASTA(sequence, filehandle): """Write one sequence in FASTA format to an already open file""" filehandle.write(">" + sequence.getName()+"\n") data = sequence.getSequence() lines = ( sequence.getLen() - 1) / 60 + 1 for i in range(lines): #note: python lets us get the last line (var length) free #lineofseq = data[i*60 : (i+1)*60] + "\n" lineofseq = "".join(data[i*60 : (i+1)*60]) + "\n" filehandle.write(lineofseq) def writeFASTA(sequence, filename): """Write a list (or a single) of sequences to a file in the FASTA format""" fh = open(filename, "w") if isinstance(sequence, Sequence): _writeOneFASTA(sequence, fh) else: for seq in sequence: if isinstance(seq, Sequence): _writeOneFASTA(seq, fh) else: print >> sys.stderr, "Warning: could not write " + seq.getName() + " (ignored)." fh.flush() fh.close() #------------------ Distrib ------------------- class Distrib(object): """Class for storing a multinomial probability distribution over the symbols in an alphabet""" def count(self, syms = None ): """Count an observation of a symbol""" if syms == None: syms = self.alpha.getSymbols() for sym in syms: idx = self.alpha.getIndex( sym ) self.cnt[idx] += 1.0 self.tot += 1 def reset(self): """Reset the distribution, that is, restart counting.""" self.tot = 0 self.cnt = [0.0 for _ in range( self.alpha.getLen() )] def getFreq(self, sym = None): """Determine the probability distribution from the current counts. The order in which probabilities are given follow the order of the symbols in the alphabet.""" if self.tot > 0: if sym == None: freq = tuple([ y / self.tot for y in self.cnt ]) return freq else: idx = self.alpha.getIndex( sym ) return self.cnt[idx] / self.tot return None def pretty(self): """Retrieve the probabilites for all symbols and return as a pretty table (a list of text strings)""" table = ["".join(["%4s " % s for s in self.alpha.getSymbols()])] table.append("".join(["%3.2f " % y for y in Distrib.getFreq(self)])) return table def getSymbols(self): """Get the symbols in the alphabet in the same order as probabilities are given.""" return self.alpha.getSymbols() def getAlphabet(self): """Get the alphabet over which the distribution is defined.""" return self.alpha #------------------ Motif (and subclasses) ------------------- class Motif(object): """ Sequence motif class--defining a pattern that can be searched in sequences. This class is not intended for direct use. Instead use and develop sub-classes (see below). """ def getLen(self): """Get the length of the motif""" return self.len def getAlphabet(self): """Get the alphabet that is used in the motif""" return self.alpha def isAlphabet(self, seqstr): """Check if the sequence can be processed by this motif""" mystr = seqstr if type(seqstr) is Sequence: mystr = seqstr.getString() return self.getAlphabet().isValidString(mystr) import re class RegExp(Motif): """A motif class that defines the pattern in terms of a regular expression""" def match(self, seq): """Find matches to the motif in a specified sequence. The method is a generator, hence subsequent hits can be retrieved using next(). The returned result is a tuple (position, match-sequence, score), where score is always 1.0 since a regular expression is either true or false (not returned). """ myseq = seq if not type(seq) is Sequence: myseq = Sequence(seq, self.alpha) mystr = myseq.getString() if not Motif.isAlphabet(self, mystr): raise RuntimeError("Motif alphabet is not valid for sequence " + myseq.getName()) for m in re.finditer(self.pattern, mystr): yield (m.start(), m.group(), 1.0) import math class PWM(Motif): """This motif subclass defines a pattern in terms of a position weight matrix. An alphabet must be provided. A pseudo-count to be added to each count is optional. A uniform background distribution is used by default. """ def setFromAlignment(self, aligned, pseudo_count = 0.0): """Set the probabilities in the PWM from an alignment. The alignment is a list of equal-length strings (see readStrings), OR a list of Sequence. """ self.cols = -1 seqs = [] # Below we create a list of Sequence from the alignment, # while doing some error checking, and figure out the number of columns for s in aligned: # probably a text string, so we make a nameless sequence from it if not type(s) is Sequence: s=Sequence(s, Motif.getAlphabet(self)) else: # it was a sequence, so we check that the alphabet in # this motif will be able to process it if not Motif.isAlphabet(self, s): raise RuntimeError("Motif alphabet is not valid for sequence " + s.getName()) if self.cols == -1: self.cols = s.getLen() elif self.cols != s.getLen(): raise RuntimeError("Sequences in alignment are not of equal length") seqs.append(s) # The line below initializes the list of Distrib (one for each column of the alignment) self.counts = [Distrib(Motif.getAlphabet(self), pseudo_count) for _ in range(self.cols)] # Next, we do the counting, column by column for c in range( self.cols ): # iterate through columns for s in seqs: # iterate through rows # determine the index of the symbol we find at this position (row, column c) self.counts[c].count(s.getSite(c)) def setBackground(self, distrib): """Set the background distribution""" if not distrib.getAlphabet() == Motif.getAlphabet(self): raise RuntimeError("Incompatible alphabets") self.background = distrib def getFreq(self): """Get the probabilities for all positions in the PWM (a list of Distribs)""" return [y.getFreq() for y in self.counts] def pretty(self): """Retrieve the probabilites for all positions in the PWM as a pretty table (a list of text strings)""" #table = ["".join(["%8s " % s for s in self.alpha.getSymbols()])] table = [] for row in PWM.getFreq(self): table.append("".join(["%8.6f " % y for y in row])) return table def logoddsPretty(self, bkg): """Retrieve the (base-2) log-odds for all positions in the PWM as a pretty table (a list of text strings)""" table = [] for row in PWM.getFreq(self): #table.append("".join(["%8.6f " % (math.log((row[i]+1e-6)/bkg[i])/math.log(2)) for i in range(len(row))])) table.append("".join(["%8.6f " % (math.log((row[i])/bkg[i])/math.log(2)) for i in range(len(row))])) #table.append("".join(["%8.6f " % row[i] for i in range(len(row))])) return table def consensus_sequence(self): """ Get the consensus sequence corresponding to a PWM. Consensus sequence is the letter in each column with the highest probability. """ consensus = "" alphabet = Motif.getAlphabet(self).getSymbols() for pos in range(self.cols): best_letter = alphabet[0] best_p = self.counts[pos].getFreq(best_letter) for letter in alphabet[1:]: p = self.counts[pos].getFreq(letter) if p > best_p: best_p = p best_letter = letter consensus += best_letter return consensus def consensus(self): """ Get the consensus corresponding to a PWM. Consensus at each column of motif is a list of characters with non-zero probabilities. """ consensus = [] for pos in range(self.cols): matches = [] for letter in Motif.getAlphabet(self).getSymbols(): p = self.counts[pos].getFreq(letter) if p > 0: matches += letter consensus.append(matches) return consensus def getScore(self, seq, start): """Score this particular list of symbols using the PFM (background needs to be set separately)""" sum = 0.0 seqdata = seq.getSequence()[start : start+self.cols] for pos in range(len(seqdata)): q = self.counts[pos].getFreq(seqdata[pos]) if q == 0: q = 0.0001 # to avoid log(0) == -Infinity logodds = math.log(q / self.background.getFreq(seqdata[pos])) sum += logodds return sum def match(self, seq, _LOG0 = -10): """Find matches to the motif in a specified sequence. The method is a generator, hence subsequent hits can be retrieved using next(). The returned result is a tuple (position, match-sequence, score). The optional parameter _LOG0 specifies a lower bound on reported logodds scores. """ myseq = seq if not type(seq) is Sequence: myseq = Sequence(seq, self.alpha) if not Motif.isAlphabet(self, myseq): raise RuntimeError("Motif alphabet is not valid for sequence " + myseq.getName()) for pos in range(myseq.getLen() - self.cols): score = PWM.getScore(self, myseq, pos) if score > _LOG0: yield (pos, "".join(myseq.getSite(pos, self.cols)), score) #------------------ Main method ------------------- # Executed if you run this file from the operating system prompt, e.g. # > python sequence.py if __name__=='__main__': alpha = getAlphabet('Extended DNA') #seqs = readFASTA('pos.fasta') seqs = [] aln = readStrings('tmp0') #regexp = RegExp(alpha, '[AG]G.[DE]TT[AS].') pwm = PWM(alpha) pwm.setFromAlignment(aln) for row in pwm.pretty(): print row for s in seqs: print s.getName(), s.getLen(), s.getAlphabet().getSymbols() for m in regexp.match( s ): print "pos: %d pat: %s %4.2f" % (m[0], m[1], m[2]) for m in pwm.match( s ): print "pos: %d pat: %s %4.2f" % (m[0], m[1], m[2])
[ 2, 0, 31, 12418, 2149, 14082, 56, 4221, 1340, 31, 198, 198, 11748, 4731, 11, 25064, 198, 198, 2, 1783, 438, 45695, 34400, 6329, 198, 198, 4871, 45695, 7, 15252, 2599, 198, 197, 37811, 33, 15071, 24830, 1398, 13, 220, 198, 197, 1212,...
2.764899
6,410
import arcade import yaml from gamemanager import GameManager def load_config(): """ Load config data from config.yaml """ with open("config.yaml", 'r') as stream: try: return yaml.safe_load(stream) except yaml.YAMLError as exc: print(exc) def main(): """ Main method """ # load config GAME_CONFIG = load_config() # load game window = GameManager(GAME_CONFIG) window.setup() arcade.run() if __name__ == "__main__": main()
[ 11748, 27210, 198, 11748, 331, 43695, 198, 198, 6738, 9106, 8463, 3536, 1330, 3776, 13511, 198, 198, 4299, 3440, 62, 11250, 33529, 198, 220, 220, 220, 37227, 8778, 4566, 1366, 422, 4566, 13, 88, 43695, 37227, 628, 220, 220, 220, 351, ...
2.386047
215
ff = open("ath") biggest="" amt=0 for line in ff: row = line.split("\t") if int(row[3]) > amt: biggest=row[0] amt = int(row[3]) print "new biggest", biggest, "with amount", amt
[ 487, 796, 1280, 7203, 776, 4943, 198, 198, 14261, 3495, 33151, 198, 321, 83, 28, 15, 198, 1640, 1627, 287, 31246, 25, 198, 197, 808, 796, 1627, 13, 35312, 7203, 59, 83, 4943, 198, 197, 361, 493, 7, 808, 58, 18, 12962, 1875, 716, ...
2.202381
84
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import sys from colors import cyan, green, red, yellow from pants.base.config import Config from pants.option import custom_types from pants.option.errors import ParseError migrations = { ('backends', 'packages'): ('DEFAULT', 'backend_packages'), ('backends', 'plugins'): ('DEFAULT', 'plugins'), ('DEFAULT', 'bootstrap_buildfiles'): ('goals', 'bootstrap_buildfiles'), ('jvm', 'missing_deps_target_whitelist'): ('compile.java', 'missing_deps_whitelist'), ('java-compile', 'partition_size_hint'): ('compile.java', 'partition_size_hint'), ('java-compile', 'javac_args'): ('compile.java', 'args'), ('java-compile', 'jvm_args'): ('compile.java', 'jvm_options'), ('java-compile', 'confs'): ('compile.java', 'confs'), ('java-compile', 'locally_changed_targets_heuristic_limit'): ('compile.java', 'changed_targets_heuristic_limit'), ('java-compile', 'warning_args'): ('compile.java', 'warning_args'), ('java-compile', 'no_warning_args'): ('compile.java', 'no_warning_args'), ('java-compile', 'use_nailgun'): ('compile.java', 'use_nailgun'), ('scala-compile', 'partition_size_hint'): ('compile.scala', 'partition_size_hint'), ('scala-compile', 'jvm_args'): ('compile.scala', 'jvm_options'), ('scala-compile', 'confs'): ('compile.scala', 'confs'), ('scala-compile', 'locally_changed_targets_heuristic_limit'): ('compile.scala', 'changed_targets_heuristic_limit'), ('scala-compile', 'warning_args'): ('compile.scala', 'warning_args'), ('scala-compile', 'no_warning_args'): ('compile.scala', 'no_warning_args'), ('scala-compile', 'runtime-deps'): ('compile.scala', 'runtime-deps'), ('scala-compile', 'use_nailgun'): ('compile.scala', 'use_nailgun'), ('scala-compile', 'args'): ('compile.scala', 'args'), ('javadoc-gen', 'include_codegen'): ('gen.javadoc', 'include_codegen'), ('scaladoc-gen', 'include_codegen'): ('gen.scaladoc', 'include_codegen'), ('nailgun', 'autokill'): ('DEFAULT', 'kill_nailguns'), ('jvm-run', 'jvm_args'): ('run.jvm', 'jvm_options'), ('benchmark-run', 'jvm_args'): ('bench', 'jvm_options'), ('specs-run', 'jvm_args'): ('test.specs', 'jvm_options'), ('junit-run', 'jvm_args'): ('test.junit', 'jvm_options'), ('scala-repl', 'jvm_args'): ('repl.scala', 'jvm_options'), ('ivy-resolve', 'jvm_args'): ('resolve.ivy', 'jvm_options'), ('jvm-run', 'confs'): ('run.jvm', 'confs'), ('benchmark-run', 'confs'): ('bench', 'confs'), ('specs-run', 'confs'): ('test.specs', 'confs'), ('junit-run', 'confs'): ('test.junit', 'confs'), ('scala-repl', 'confs'): ('repl.scala', 'confs'), ('ivy-resolve', 'confs'): ('resolve.ivy', 'confs'), ('scala-repl', 'args'): ('repl.scala', 'args'), ('checkstyle', 'bootstrap-tools'): ('compile.checkstyle', 'bootstrap_tools'), ('checkstyle', 'configuration'): ('compile.checkstyle', 'configuration'), ('checkstyle', 'properties'): ('compile.checkstyle', 'properties'), ('scalastyle', 'config'): ('compile.scalastyle', 'config'), ('scalastyle', 'excludes'): ('compile.scalastyle', 'excludes'), # These must now be defined for each JvmTask subtask, so we temporarily put them # in the DEFAULT section as a convenience. # These will soon move into a subsystem, which will fix this. ('jvm', 'debug_config'): ('DEFAULT', 'debug_config'), ('jvm', 'debug_port'): ('DEFAULT', 'debug_port'), ('scala-compile', 'scalac-plugins'): ('compile.scala', 'plugins'), ('scala-compile', 'scalac-plugin-args'): ('compile.scala', 'plugin_args'), ('markdown-to-html', 'extensions'): ('markdown', 'extensions'), ('markdown-to-html', 'code-style'): ('markdown', 'code_style'), # Note: This assumes that ConfluencePublish is registered as the only task in a # goal called 'confluence'. Adjust if this is not the case in your pants.ini. ('confluence-publish', 'url'): ('confluence', 'url'), # JVM tool migrations. ('antlr-gen', 'javadeps'): ('gen.antlr', 'antlr3'), ('antlr4-gen', 'javadeps'): ('gen.antlr', 'antlr4'), ('scrooge-gen', 'bootstrap-tools'): ('gen.scrooge', 'scrooge'), ('thrift-linter', 'bootstrap-tools'): ('thrift-linter', 'scrooge_linter'), ('wire-gen', 'bootstrap-tools'): ('gen.wire', 'wire_compiler'), ('benchmark-run', 'bootstrap-tools'): ('bench', 'benchmark_tool'), ('benchmark-run', 'agent-bootstrap-tools'): ('bench', 'benchmark_agent'), ('compile.checkstyle', 'bootstrap-tools'): ('compile.checkstyle', 'checkstyle'), ('ivy-resolve', 'bootstrap-tools'): ('resolve.ivy', 'xalan'), ('jar-tool', 'bootstrap-tools'): ('DEFAULT', 'jar-tool'), ('junit-run', 'junit-bootstrap-tools'): ('test.junit', 'junit'), ('junit-run', 'emma-bootstrap-tools'): ('test.junit', 'emma'), ('junit-run', 'cobertura-bootstrap-tools'): ('test.junit', 'cobertura'), ('java-compile', 'jmake-bootstrap-tools'): ('compile.java', 'jmake'), ('java-compile', 'compiler-bootstrap-tools'): ('compile.java', 'java_compiler'), # Note: compile-bootstrap-tools is not a typo. ('scala-compile', 'compile-bootstrap-tools'): ('compile.scala', 'scalac'), ('scala-compile', 'zinc-bootstrap-tools'): ('compile.scala', 'zinc'), ('scala-compile', 'scalac-plugin-bootstrap-tools'): ('compile.scala', 'plugin_jars'), ('scala-repl', 'bootstrap-tools'): ('repl.scala', 'scala_repl'), ('specs-run', 'bootstrap-tools'): ('test.specs', 'specs'), # Artifact cache spec migration. ('dx-tool', 'read_artifact_caches'): ('dex', 'read_artifact_caches'), ('thrift-gen', 'read_artifact_caches'): ('gen.thrift', 'read_artifact_caches'), ('ivy-resolve', 'read_artifact_caches'): ('resolve.ivy', 'read_artifact_caches'), ('java-compile', 'read_artifact_caches'): ('compile.java', 'read_artifact_caches'), ('scala-compile', 'read_artifact_caches'): ('compile.scala', 'read_artifact_caches'), ('dx-tool', 'write_artifact_caches'): ('dex', 'write_artifact_caches'), ('thrift-gen', 'write_artifact_caches'): ('gen.thrift', 'write_artifact_caches'), ('ivy-resolve', 'write_artifact_caches'): ('resolve.ivy', 'write_artifact_caches'), ('java-compile', 'write_artifact_caches'): ('compile.java', 'write_artifact_caches'), ('scala-compile', 'write_artifact_caches'): ('compile.scala', 'write_artifact_caches'), ('protobuf-gen', 'version'): ('gen.protoc', 'version'), ('protobuf-gen', 'supportdir'): ('gen.protoc', 'supportdir'), ('protobuf-gen', 'plugins'): ('gen.protoc', 'plugins'), ('protobuf-gen', 'javadeps'): ('gen.protoc', 'javadeps'), ('protobuf-gen', 'pythondeps'): ('gen.protoc', 'pythondeps'), ('thrift-gen', 'strict'): ('gen.thrift', 'strict'), ('thrift-gen', 'supportdir'): ('gen.thrift', 'supportdir'), ('thrift-gen', 'version'): ('gen.thrift', 'version'), ('thrift-gen', 'java'): ('gen.thrift', 'java'), ('thrift-gen', 'python'): ('gen.thrift', 'python'), ('backend', 'python-path'): ('DEFAULT', 'pythonpath'), ('python-ipython', 'entry-point'): ('repl.py', 'ipython_entry_point'), ('python-ipython', 'requirements'): ('repl.py', 'ipython_requirements'), ('jar-publish', 'restrict_push_branches'): ('publish.jar', 'restrict_push_branches'), ('jar-publish', 'ivy_jvmargs'): ('publish.jar', 'jvm_options'), ('jar-publish', 'repos'): ('publish.jar', 'repos'), ('jar-publish', 'publish_extras'): ('publish.jar', 'publish_extras'), ('publish', 'individual_plugins'): ('publish.jar', 'individual_plugins'), ('publish', 'ivy_settings'): ('publish.jar', 'ivy_settings'), ('publish', 'jvm_options'): ('publish.jar', 'jvm_options'), ('publish', 'publish_extras'): ('publish.jar', 'publish_extras'), ('publish', 'push_postscript'): ('publish.jar', 'push_postscript'), ('publish', 'repos'): ('publish.jar', 'repos'), ('publish', 'restrict_push_branches'): ('publish.jar', 'restrict_push_branches'), # Three changes are pertinent to migrate 'ide' to both idea and & eclipse. I tried to capture # that in notes ('ide', 'python_source_paths'): ('idea', 'python_source_paths'), ('ide', 'python_lib_paths'): ('idea', 'python_lib_paths'), ('ide', 'python_test_paths'): ('idea', 'python_test_paths'), ('ide', 'extra_jvm_source_paths'): ('idea', 'extra_jvm_source_paths'), ('ide', 'extra_jvm_test_paths'): ('idea', 'extra_jvm_test_paths'), ('ide', 'debug_port'): ('idea', 'debug_port'), ('reporting', 'reports_template_dir'): ('reporting', 'template_dir'), ('DEFAULT', 'stats_upload_url'): ('run-tracker', 'stats_upload_url'), ('DEFAULT', 'stats_upload_timeout'): ('run-tracker', 'stats_upload_timeout'), ('DEFAULT', 'num_foreground_workers'): ('run-tracker', 'num_foreground_workers'), ('DEFAULT', 'num_background_workers'): ('run-tracker', 'num_background_workers'), # These changes migrate all possible scoped configuration of --ng-daemons to --use-nailgun leaf # options. ('DEFAULT', 'ng_daemons'): ('DEFAULT', 'use_nailgun'), # NB: binary.binary -> binary is a leaf scope ('binary', 'ng_daemons'): ('binary', 'use_nailgun'), ('binary.dex', 'ng_daemons'): ('binary.dex', 'use_nailgun'), ('binary.dup', 'ng_daemons'): ('binary.dup', 'use_nailgun'), # NB: bundle.bundle -> bundle is a leaf scope ('bundle', 'ng_daemons'): ('bundle', 'use_nailgun'), ('bundle.dup', 'ng_daemons'): ('bundle.dup', 'use_nailgun'), ('compile', 'ng_daemons'): None, # Intermediate scope - note only, no direct migration path ('compile.scalastyle', 'ng_daemons'): ('compile.scalastyle', 'use_nailgun'), ('compile.scala', 'ng_daemons'): ('compile.scala', 'use_nailgun'), ('compile.apt', 'ng_daemons'): ('compile.apt', 'use_nailgun'), ('compile.java', 'ng_daemons'): ('compile.java', 'use_nailgun'), ('compile.checkstyle', 'ng_daemons'): ('compile.checkstyle', 'use_nailgun'), ('detect-duplicates', 'ng_daemons'): ('detect-duplicates', 'use_nailgun'), ('gen', 'ng_daemons'): None, # Intermediate scope - note only, no direct migration path ('gen.antlr', 'ng_daemons'): ('gen.antlr', 'use_nailgun'), ('gen.jaxb', 'ng_daemons'): ('gen.jaxb', 'use_nailgun'), ('gen.scrooge', 'ng_daemons'): ('gen.scrooge', 'use_nailgun'), ('imports', 'ng_daemons'): None, # Intermediate scope - note only, no direct migration path ('imports.ivy-imports', 'ng_daemons'): ('imports.ivy-imports', 'use_nailgun'), ('jar', 'ng_daemons'): ('jar', 'use_nailgun'), ('publish', 'ng_daemons'): ('publish', 'use_nailgun'), ('resolve', 'ng_daemons'): None, # Intermediate scope - note only, no direct migration path ('resolve.ivy', 'ng_daemons'): ('resolve.ivy', 'use_nailgun'), ('thrift-linter', 'ng_daemons'): ('thrift-linter', 'use_nailgun'), # Migration of the scrooge contrib module to the new options system. ('java-thrift-library', 'compiler'): ('DEFAULT', 'thrift_default_compiler'), ('java-thrift-library', 'language'): ('DEFAULT', 'thrift_default_language'), ('java-thrift-library', 'rpc_style'): ('DEFAULT', 'thrift_default_rpc_style'), ('scrooge-gen', 'jvm_args'): ('gen.scrooge', 'jvm_options'), ('scrooge-gen', 'jvm_options'): ('gen.scrooge', 'jvm_options'), ('scrooge-gen', 'strict'): ('gen.scrooge', 'strict'), ('scrooge-gen', 'verbose'): ('gen.scrooge', 'verbose'), ('thrift-linter', 'strict'): ('thrift-linter', 'strict_default'), # NB: For the following two options, see the notes below. ('scrooge-gen', 'scala'): ('gen.scrooge', 'service_deps'), ('scrooge-gen', 'java'): ('gen.scrooge', 'service_deps'), # jar-tool subsystem. ('jar-tool', 'bootstrap-tools'): ('jar-tool', 'jar-tool'), ('jar-tool', 'jvm_args'): ('jar-tool', 'jvm_options'), # Technically 'indices' and 'indexes' are both acceptable plural forms of 'index'. However # usage has led to the former being used primarily for mathematical indices and the latter # for book indexes, database indexes and the like. ('python-repos', 'indices'): ('python-repos', 'indexes'), ('ragel-gen', 'supportdir'): ('gen.ragel', 'supportdir'), ('ragel-gen', 'version'): ('gen.ragel', 'version'), ('prepare-resources', 'confs'): ('resources.prepare', 'confs'), ('compile.scala', 'runtime-deps'): ('scala-platform', 'runtime'), ('compile.scala', 'scalac'): ('scala-platform', 'scalac'), ('DEFAULT', 'thrift_default_compiler'): ('thrift-defaults', 'compiler'), ('DEFAULT', 'thrift_default_language'): ('thrift-defaults', 'language'), ('DEFAULT', 'thrift_default_rpc_style'): ('thrift-defaults', 'rpc_style'), ('python-setup', 'egg_cache_dir'): ('python_setup', 'resolver_cache_dir'), ('DEFAULT', 'python_chroot_requirements_ttl'): ('python-setup', 'resolver_cache_ttl'), ('DEFAULT', 'pants_support_baseurls'): ('binaries', 'baseurls'), ('DEFAULT', 'pants_support_fetch_timeout_secs'): ('binaries', 'fetch_timeout_secs'), ('gen.thrift', 'supportdir'): ('thrift-binary', 'supportdir'), ('gen.thrift', 'version'): ('thrift-binary', 'version'), ('gen.thrift', 'java'): None, # Notes only one to many migration: see notes below. ('gen.thrift', 'python'): None, # Notes only pure deletion migration: see notes below. ('compile.zinc-java', 'enabled'): ('compile.java', 'use-jmake'), ('compile.scala', 'args'): ('compile.zinc', 'args'), ('compile.cpp-compile', 'cc_options'): ('compile.cpp', 'cc_options'), ('compile.cpp-compile', 'cc_extensions'): ('compile.cpp', 'cc_extensions'), ('test.junit', 'coverage_html_open'): ('test.junit', 'coverage_open'), } ng_daemons_note = ('The global "ng_daemons" option has been replaced by a "use_nailgun" option ' 'local to each task that can use a nailgun. A default can no longer be ' 'specified at intermediate scopes; ie: "compile" when the option is present in ' '"compile.apt", "compile.checkstyle", "compile.java", "compile.scala" and ' '"compile.scalastyle". You must over-ride in each nailgun task section that ' 'should not use the default "use_nailgun" value of sTrue. You can possibly ' 'limit the number of overrides by inverting the default with a DEFAULT section ' 'value of False.') scrooge_gen_deps_note = ('The scrooge-gen per-language config fields have been refactored into ' 'two options: one for service deps, and one for structs deps.') notes = { ('jvm', 'missing_deps_target_whitelist'): 'This should be split into compile.java or ' 'compile.scala', ('jvm', 'debug_port'): 'For now must be defined for each JvmTask subtask separately. Will soon ' 'move to a subsystem, which will fix this requirement.', ('jvm', 'debug_args'): 'For now must be defined for each JvmTask subtask separately. Will soon ' 'move to a subsystem, which will fix this requirement.', ('java-compile', 'javac_args'): 'Source, target, and bootclasspath args should be specified in ' 'the jvm-platform subsystem. Other args can be placed in args: ' 'and prefixed with -C, or also be included in the jvm-platform ' 'args.', ('java-compile', 'source'): 'source and target args should be defined using the jvm-platform ' 'subsystem, rathern than as arguments to java-compile.', ('java-compile', 'target'): 'source and target args should be defined using the jvm-platform ' 'subsystem, rathern than as arguments to java-compile.', ('jar-tool', 'bootstrap_tools'): 'Each JarTask sub-task can define this in its own section. or ' 'this can be defined for everyone in the DEFAULT section.', ('ivy-resolve', 'jvm_args'): 'If needed, this should be repeated in resolve.ivy, ' 'bootstrap.bootstrap-jvm-tools and imports.ivy-imports ' '(as jvm_options). Easiest way to do this is to define ' 'ivy_jvm_options in DEFAULT and then interpolate it: ' 'jvm_options: %(ivy_jvm_options)s', ('protobuf-gen', 'version'): 'The behavior of the "version" and "javadeps" parameters ' 'have changed.\n ' 'The old behavior to was to append the "version" paraemter to the ' 'target name \'protobuf-\' as the default for "javadeps". Now ' '"javadeps" defaults to the value \'protobuf-java\'.', ('protobuf-gen', 'plugins'): 'The behavior of the "plugins" parameter has changed. ' 'The old behavior was to unconditionally append "_protobuf" to the ' 'end of the plugin name. This will not work for plugins that have ' 'a name that does not end in "_protobuf".', ('thrift-gen', 'verbose'): 'This flag is no longer supported. Use -ldebug instead.', ('ide', 'python_source_path'): 'python_source_path now must be specified separately for idea and ' 'eclipse goals.', ('ide', 'python_lib_paths'): 'python_lib_path now must be specified separately for idea and ' 'eclipse goals.', ('ide', 'python_test_paths'): 'python_test_path now must be specified separately for idea and ' 'eclipse goals.', ('ide', 'extra_jvm_source_paths'): 'extra_jvm_source_paths now must be specified separately for ' 'idea and eclipse goals.', ('ide', 'extra_jvm_test_paths'): 'extra_jvm_test_paths now must be specified separately for ' 'idea and eclipse goals.', ('ide', 'debug_port'): 'debug_port now must be specified separately for idea and eclipse ' 'goals. Also, IDE goals now use their own debug setting and do not ' 'inherit from jvm configuration.', ('tasks', 'build_invalidator'): 'This is no longer configurable. The default will be used.', ('compile', 'ng_daemons'): ng_daemons_note, ('gen', 'ng_daemons'): ng_daemons_note, ('imports', 'ng_daemons'): ng_daemons_note, ('resolve', 'ng_daemons'): ng_daemons_note, ('scrooge-gen', 'scala'): scrooge_gen_deps_note, ('scrooge-gen', 'java'): scrooge_gen_deps_note, ('gen.thrift', 'version'): 'You can either set the apache thrift compiler version globally for ' 'java and python using the [thrift-binary] scope or else you can ' 'configure the languages separately using the ' '[thrift-binary.gen.thrift] scope to control the version used for ' 'java.', ('gen.thrift', 'java'): 'The java configuration has migrated from a single dict with 3 keys to ' '3 options.\n' 'The "gen" key has migrated to the `gen_options` option and the value ' 'should just be the option portion of the thrift --gen argument. For ' 'example, if you had `"gen": "java:hashcode"` as your java dict entry ' 'you\'d now use the top-level option `gen_options: hashcode`.\n' 'The "deps.structs" nested key has migrated to the `deps` option and the ' 'value remains the same.\n' 'The "deps.service" nested key as migrated to the `service_deps` option ' 'and the value remains the same, but is now optional if service deps are ' 'the same as non-service deps.', ('gen.thrift', 'python'): 'The python configuration for gen.thrift has never been used and ' 'should be removed.', ('resolve.ivy', 'automatic_excludes'): 'Enabled by default.', ('imports.ivy-imports', 'automatic_excludes'): 'Enabled by default.', ('compile.zinc-java', 'enabled'): 'The enabled flag has moved from "enable zinc for java" ' 'to "disable jmake for java", more precisely, instead of ' '--compile-zinc-java-enabled, use --no-compile-java-use-jmake', ('compile.scala', 'args'): 'ALL `compile.scala` options have moved to `compile.zinc`.', ('compile.cpp-compile', 'cc_options'): 'Value used to be a string, is now a list.', ('compile.cpp-compile', 'cc_extensions'): 'Value used to be a string (but default was a list), ' 'is now a list. Values also now include the dot, e.g.,' 'it\'s now .cpp, not cpp.', ('test.junit', 'coverage_console'): 'Option no longer exists. Coverage always written to stdout.', ('test.junit', 'coverage_html'): 'Option no longer exists. Coverage always written to html file.', ('test.junit', 'coverage_xml'): 'Option no longer exists. Coverage always written to xml file.', } if __name__ == '__main__': if len(sys.argv) > 2: print('Usage: migrate_config.py [path to pants.ini file]', file=sys.stderr) sys.exit(1) elif len(sys.argv) > 1: path = sys.argv[1] else: path = './pants.ini' check_config_file(path)
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 1946, 41689, 1628, 20420, 357, 3826, 27342, 9865, 3843, 20673, 13, 9132, 737, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 3826, 38559, 24290, 737, 198, 198, 6738, 1...
2.436634
8,877
# SPDX-License-Identifier: GPL-2.0 # Copyright (c) 2017, Heinrich Schuchardt <xypron.glpk@gmx.de> # Test efi API implementation import pytest import u_boot_utils @pytest.mark.buildconfigspec('cmd_bootefi_selftest') def test_efi_selftest(u_boot_console): """Test the UEFI implementation :param u_boot_console: U-Boot console This function executes all selftests that are not marked as on request. """ u_boot_console.run_command(cmd='setenv efi_selftest') u_boot_console.run_command(cmd='bootefi selftest', wait_for_prompt=False) m = u_boot_console.p.expect(['Summary: 0 failures', 'Press any key']) if m != 0: raise Exception('Failures occurred during the EFI selftest') u_boot_console.run_command(cmd='', wait_for_echo=False, wait_for_prompt=False); m = u_boot_console.p.expect(['resetting', 'U-Boot']) if m != 0: raise Exception('Reset failed during the EFI selftest') u_boot_console.restart_uboot(); @pytest.mark.buildconfigspec('cmd_bootefi_selftest') @pytest.mark.buildconfigspec('of_control') @pytest.mark.notbuildconfigspec('generate_acpi_table') @pytest.mark.buildconfigspec('cmd_bootefi_selftest') @pytest.mark.buildconfigspec('cmd_bootefi_selftest') def test_efi_selftest_text_input(u_boot_console): """Test the EFI_SIMPLE_TEXT_INPUT_PROTOCOL :param u_boot_console: U-Boot console This function calls the text input EFI selftest. """ u_boot_console.run_command(cmd='setenv efi_selftest text input') output = u_boot_console.run_command(cmd='bootefi selftest', wait_for_prompt=False) m = u_boot_console.p.expect(['To terminate type \'x\'']) if m != 0: raise Exception('No prompt for \'text input\' test') u_boot_console.drain_console() u_boot_console.p.timeout = 500 # EOT u_boot_console.run_command(cmd=chr(4), wait_for_echo=False, send_nl=False, wait_for_prompt=False) m = u_boot_console.p.expect( ['Unicode char 4 \(unknown\), scan code 0 \(Null\)']) if m != 0: raise Exception('EOT failed in \'text input\' test') u_boot_console.drain_console() # BS u_boot_console.run_command(cmd=chr(8), wait_for_echo=False, send_nl=False, wait_for_prompt=False) m = u_boot_console.p.expect( ['Unicode char 8 \(BS\), scan code 0 \(Null\)']) if m != 0: raise Exception('BS failed in \'text input\' test') u_boot_console.drain_console() # TAB u_boot_console.run_command(cmd=chr(9), wait_for_echo=False, send_nl=False, wait_for_prompt=False) m = u_boot_console.p.expect( ['Unicode char 9 \(TAB\), scan code 0 \(Null\)']) if m != 0: raise Exception('BS failed in \'text input\' test') u_boot_console.drain_console() # a u_boot_console.run_command(cmd='a', wait_for_echo=False, send_nl=False, wait_for_prompt=False) m = u_boot_console.p.expect( ['Unicode char 97 \(\'a\'\), scan code 0 \(Null\)']) if m != 0: raise Exception('\'a\' failed in \'text input\' test') u_boot_console.drain_console() # UP escape sequence u_boot_console.run_command(cmd=chr(27) + '[A', wait_for_echo=False, send_nl=False, wait_for_prompt=False) m = u_boot_console.p.expect( ['Unicode char 0 \(Null\), scan code 1 \(Up\)']) if m != 0: raise Exception('UP failed in \'text input\' test') u_boot_console.drain_console() # Euro sign u_boot_console.run_command(cmd='\xe2\x82\xac', wait_for_echo=False, send_nl=False, wait_for_prompt=False) m = u_boot_console.p.expect(['Unicode char 8364 \(\'']) if m != 0: raise Exception('Euro sign failed in \'text input\' test') u_boot_console.drain_console() u_boot_console.run_command(cmd='x', wait_for_echo=False, send_nl=False, wait_for_prompt=False) m = u_boot_console.p.expect(['Summary: 0 failures', 'Press any key']) if m != 0: raise Exception('Failures occurred during the EFI selftest') u_boot_console.restart_uboot(); @pytest.mark.buildconfigspec('cmd_bootefi_selftest') def test_efi_selftest_text_input_ex(u_boot_console): """Test the EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL :param u_boot_console: U-Boot console This function calls the extended text input EFI selftest. """ u_boot_console.run_command(cmd='setenv efi_selftest extended text input') output = u_boot_console.run_command(cmd='bootefi selftest', wait_for_prompt=False) m = u_boot_console.p.expect(['To terminate type \'CTRL\+x\'']) if m != 0: raise Exception('No prompt for \'text input\' test') u_boot_console.drain_console() u_boot_console.p.timeout = 500 # EOT u_boot_console.run_command(cmd=chr(4), wait_for_echo=False, send_nl=False, wait_for_prompt=False) m = u_boot_console.p.expect( ['Unicode char 100 \\(\'d\'\\), scan code 0 \\(CTRL\\+Null\\)']) if m != 0: raise Exception('EOT failed in \'text input\' test') u_boot_console.drain_console() # BS u_boot_console.run_command(cmd=chr(8), wait_for_echo=False, send_nl=False, wait_for_prompt=False) m = u_boot_console.p.expect( ['Unicode char 8 \(BS\), scan code 0 \(\+Null\)']) if m != 0: raise Exception('BS failed in \'text input\' test') u_boot_console.drain_console() # TAB u_boot_console.run_command(cmd=chr(9), wait_for_echo=False, send_nl=False, wait_for_prompt=False) m = u_boot_console.p.expect( ['Unicode char 9 \(TAB\), scan code 0 \(\+Null\)']) if m != 0: raise Exception('TAB failed in \'text input\' test') u_boot_console.drain_console() # a u_boot_console.run_command(cmd='a', wait_for_echo=False, send_nl=False, wait_for_prompt=False) m = u_boot_console.p.expect( ['Unicode char 97 \(\'a\'\), scan code 0 \(Null\)']) if m != 0: raise Exception('\'a\' failed in \'text input\' test') u_boot_console.drain_console() # UP escape sequence u_boot_console.run_command(cmd=chr(27) + '[A', wait_for_echo=False, send_nl=False, wait_for_prompt=False) m = u_boot_console.p.expect( ['Unicode char 0 \(Null\), scan code 1 \(\+Up\)']) if m != 0: raise Exception('UP failed in \'text input\' test') u_boot_console.drain_console() # Euro sign u_boot_console.run_command(cmd='\xe2\x82\xac', wait_for_echo=False, send_nl=False, wait_for_prompt=False) m = u_boot_console.p.expect(['Unicode char 8364 \(\'']) if m != 0: raise Exception('Euro sign failed in \'text input\' test') u_boot_console.drain_console() # SHIFT+ALT+FN 5 u_boot_console.run_command(cmd='\x1b\x5b\x31\x35\x3b\x34\x7e', wait_for_echo=False, send_nl=False, wait_for_prompt=False) m = u_boot_console.p.expect( ['Unicode char 0 \(Null\), scan code 15 \(SHIFT\+ALT\+FN 5\)']) if m != 0: raise Exception('SHIFT+ALT+FN 5 failed in \'text input\' test') u_boot_console.drain_console() u_boot_console.run_command(cmd=chr(24), wait_for_echo=False, send_nl=False, wait_for_prompt=False) m = u_boot_console.p.expect(['Summary: 0 failures', 'Press any key']) if m != 0: raise Exception('Failures occurred during the EFI selftest') u_boot_console.restart_uboot();
[ 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 38644, 12, 17, 13, 15, 198, 2, 15069, 357, 66, 8, 2177, 11, 26431, 7527, 3059, 794, 446, 83, 1279, 5431, 31186, 13, 4743, 79, 74, 31, 70, 36802, 13, 2934, 29, 198, 198, 2, 6208, 30...
2.432528
2,816
# -*- coding: utf-8 -*- """ @author: Yi Zhang. Department of Aerodynamics Faculty of Aerospace Engineering TU Delft, Delft, Netherlands """ import sys if './' not in sys.path: sys.path.append('./') from objects.CSCG._3d.forms.standard._3s.discretize.main import _3dCSCG_Discretize from objects.CSCG._3d.forms.standard.base.main import _3dCSCG_Standard_Form from objects.CSCG._3d.forms.standard._3s.special import _3Form_Special from objects.CSCG._3d.forms.standard._3s.reconstruct import _3dCSCG_SF3_Reconstruct from objects.CSCG._3d.forms.standard._3s.inheriting.private import _3dCSCG_S3F_Private from objects.CSCG._3d.forms.standard._3s.visualize.main import _3dCSCG_S3F_VISUALIZE class _3dCSCG_3Form(_3dCSCG_S3F_Private, _3dCSCG_Standard_Form): """Standard 3-form. :param mesh: :param space: :param is_hybrid: :param orientation: :param numbering_parameters: :param name: """ @property @property @property @property if __name__ == '__main__': # mpiexec -n 4 python objects/CSCG/_3d/forms/standard/_3s/main.py from objects.CSCG._3d.master import MeshGenerator, SpaceInvoker, FormCaller, ExactSolutionSelector mesh = MeshGenerator('cuboid')([3,3,3]) space = SpaceInvoker('polynomials')([('Lobatto',3), ('Lobatto',3), ('Lobatto',3)]) FC = FormCaller(mesh, space) # es = ExactSolutionSelector(mesh)('icpsNS:sincosRD') f3 = FC('3-f', is_hybrid=False) import numpy as np scalar = FC('scalar', func) f3.TW.func.body = scalar f3.TW.current_time = 0 f3.TW.do.push_all_to_instant() f3.do.discretize() f3.visualize(x=1) # from tools.CSCG.partial_dofs import PartialDofs # # pd = PartialDofs(f3)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 198, 31, 9800, 25, 26463, 19439, 13, 198, 220, 220, 220, 220, 220, 220, 220, 220, 2732, 286, 15781, 44124, 198, 220, 220, 220, 220, 220, 220, 220, 220, 3...
2.29882
763
import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) logging.getLogger("pyrogram").setLevel(logging.WARNING) import os from config import Config from pyrogram import Client if __name__ == "__main__" : plugins = dict( root="plugins" ) app = Client( "Telegraph-Bot", bot_token=Config.BOT_TOKEN, api_id=Config.API_ID, api_hash=Config.API_HASH, workers=75, plugins=plugins ) app.run()
[ 11748, 18931, 198, 6404, 2667, 13, 35487, 16934, 7, 5715, 28, 6404, 2667, 13, 30531, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 5794, 11639, 4, 7, 292, 310, 524, 8, 82...
2.183521
267
# Copyright (c) 2006-2008 Alexander Burtsev # See LICENSE for details """AMI tests @author: U{Alexander Burtsev<mailto:eburus@gmail.com>} $Id: test_ami.py 24 2008-02-18 12:22:42Z burus $ """ from twisted.trial import unittest from twisted.internet.protocol import FileWrapper from twisted.test.test_protocols import StringIOWithoutClosing as SIOWC from twisted.fats.ami import AMIClient, AMI from twisted.fats.errors import AMIFailure, LoginFailed, NoSuchChannel FAILURE = 0 SUCCESS = 1 RESPONSE_MAP = { 'Login': {FAILURE: 'Asterisk Call Manager/1.0' 'Response: Error' 'Message: Authentication failed', SUCCESS: 'Asterisk Call Manager/1.0' 'Response: Success' 'Message: Authentication accepted'}, 'Ping': {FAILURE: 'Response: Pong', SUCCESS: 'Response: Pong'}, 'AbsoluteTimeout': {FAILURE: 'Response: Error' 'Message: No such channel', SUCCESS: 'Response: Success' 'Message: Timeout Set'}, 'ChangeMonitor': {FAILURE: 'Response: Error' 'Message: No such channel', SUCCESS: 'Response: Success' 'Message: Stopped monitoring channel'}, } """ '': {FAILURE:, SUCCESS:}, '': {FAILURE:, SUCCESS:}, '': {FAILURE:, SUCCESS:}, '': {FAILURE:, SUCCESS:}, '': {FAILURE:, SUCCESS:}, '': {FAILURE:, SUCCESS:}, '': {FAILURE:, SUCCESS:}, '': {FAILURE:, SUCCESS:}, '': {FAILURE:, SUCCESS:}, '': {FAILURE:, SUCCESS:}, '': {FAILURE:, SUCCESS:}, '': {FAILURE:, SUCCESS:}, """
[ 2, 15069, 357, 66, 8, 4793, 12, 11528, 10009, 347, 3325, 325, 85, 198, 2, 4091, 38559, 24290, 329, 3307, 198, 198, 37811, 43870, 5254, 198, 31, 9800, 25, 471, 90, 38708, 347, 3325, 325, 85, 27, 4529, 1462, 25, 1765, 31891, 31, 148...
1.854776
1,026
from mytest import * from mytest.annotationTest import spamrun @spamrun if __name__ == '__main__': fuc(1,2)
[ 198, 6738, 616, 9288, 1330, 1635, 198, 198, 6738, 616, 9288, 13, 1236, 14221, 14402, 1330, 18084, 5143, 198, 198, 31, 2777, 321, 5143, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 277, 1229, ...
2.4375
48
#!/usr/bin/env python2 # coding: utf-8 import yaml from argparse import ArgumentParser from sys import stdout, stderr from java_source_parser import make_model if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 11748, 331, 43695, 198, 6738, 1822, 29572, 1330, 45751, 46677, 198, 6738, 25064, 1330, 14367, 448, 11, 336, 1082, 81, 198, 6738, 20129, ...
2.873239
71
import numpy as np import matplotlib.pyplot as plt teste()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 628, 198, 198, 9288, 68, 3419, 198 ]
2.695652
23
#!/usr/bin/python # coding: UTF-8 # musicdata service to read from SPOP # Written by: Ron Ritchey import threading, logging, queue, time, sys, telnetlib, json, getopt from . import musicdata if __name__ == '__main__': logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', filename='musicdata_spop.log', level=logging.DEBUG) logging.getLogger().addHandler(logging.StreamHandler()) try: opts, args = getopt.getopt(sys.argv[1:],"hs:p:w:",["server=","port=","pwd="]) except getopt.GetoptError: print('musicdata_spop.py -s <server> -p <port> -w <password>') sys.exit(2) # Set defaults server = 'localhost' port = 6602 pwd= '' for opt, arg in opts: if opt == '-h': print('musicdata_spop.py -s <server> -p <port> -w <password>') sys.exit() elif opt in ("-s", "--server"): server = arg elif opt in ("-p", "--port"): port = arg elif opt in ("-w", "--pwd"): pwd = arg import sys q = queue.Queue() mds = musicdata_spop(q, server, port, pwd) try: start = time.time() while True: if start+120 < time.time(): break; try: item = q.get(timeout=1000) print("+++++++++") for k,v in item.items(): print("[{0}] '{1}' type {2}".format(k,v,type(v))) print("+++++++++") print() q.task_done() except queue.Empty: pass except KeyboardInterrupt: print('') pass print("Exiting...")
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 19617, 25, 41002, 12, 23, 198, 198, 2, 2647, 7890, 2139, 284, 1100, 422, 6226, 3185, 198, 2, 22503, 416, 25, 6575, 371, 270, 2395, 88, 628, 198, 11748, 4704, 278, 11, 18931, 11, 16834,...
2.282178
606
#!/bin/env python # -*-coding:utf-8 -* # pylint: disable=missing-module-docstring # pylint: disable=wrong-import-position # pylint: disable=unused-import # flake8: noqa import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname( __file__), '../src/tribud'))) import model
[ 2, 48443, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 66, 7656, 25, 40477, 12, 23, 532, 9, 198, 2, 279, 2645, 600, 25, 15560, 28, 45688, 12, 21412, 12, 15390, 8841, 198, 2, 279, 2645, 600, 25, 15560, 28, 36460, 12, 11748, 12, ...
2.435484
124
import argparse import os import sys import numpy as np import tensorflow as tf from matplotlib import pyplot as plt from PIL import Image from urllib.request import urlretrieve import depth_prediction.models as models from main import utils import glob import logging logger = utils.get_logger(name=__name__) DEFAULT_MODEL_PATH = "../resources/models/depth_prediction/NYU_" \ "ResNet-UpProj.npy" DEFAULT_IMAGES_PATH = "../resources/demo/image.jpg" DEFAULT_BATCH_SIZE = 16 DEFAULT_LOG_FILE = "deeplens_depth_maps.log" IS_DEBUG = False """ author: Adam Dziedzic ady@uchicago.edu based on: https://github.com/iro-cp/FCRN-DepthPrediction """ def show_figure(img): """ Plot the image as a figure. :param img: the input image """ fig = plt.figure() input_img = plt.imshow(img, interpolation='nearest') fig.colorbar(input_img) plt.show() def process_images(images_path, width, height): """ Process the image (e.g. resize). :param images_path: the path to the directory with images :param width: the width of the image expected by the model :param height: the height of the image expected by the model :return: the processed and resized images (the resized image can be used to plot is as an original input to the model) """ processed_imgs = [] resized_imgs = [] for image_path in images_path: img = Image.open(image_path) resized_img = img.resize([width, height], Image.ANTIALIAS) resized_imgs.append(resized_img) processed_img = np.array(resized_img).astype('float32') processed_imgs.append(processed_img) if logger.level == logging.DEBUG: for image in resized_imgs: show_figure(image) return processed_imgs, resized_imgs def main(model_path=DEFAULT_MODEL_PATH, images_path=DEFAULT_IMAGES_PATH): """ Main and self-contained method to predict the images. :param model_path: the path to the pre-trained model parameters :param images_path: the path to the directory with images or a single image path """ predictor = Predictor(model_path) predicted_depths, resized_imgs = predictor.predict_depth( images_path=images_path) # Plot result fig = plt.figure() columns = 2 rows = len(resized_imgs) logger.debug("number of processed images:" + str(rows)) for counter in range(rows): first_index = 2 * counter + 1 ax1 = fig.add_subplot(rows, columns, first_index) input_img = plt.imshow(resized_imgs[counter], interpolation='nearest') fig.colorbar(input_img) ax1.title.set_text("resized input image " + str(counter)) second_index = 2 * counter + 2 ax2 = fig.add_subplot(rows, columns, second_index) prediction_img = plt.imshow(predicted_depths[counter], interpolation='nearest') fig.colorbar(prediction_img) ax2.title.set_text("depth map " + str(counter)) fig.tight_layout() img_folder = images_path[:images_path.rfind("/")] depth_folder = img_folder + "/image_depths/" if not os.path.exists(depth_folder): os.makedirs(depth_folder) fig.savefig(depth_folder + "/image_depths.png") plt.show(block=True) plt.close(fig) if __name__ == '__main__': # Parse arguments parser = argparse.ArgumentParser() parser.add_argument('-m', '--model_path', default=DEFAULT_MODEL_PATH, help='Converted parameters for the model') parser.add_argument('-i', '--image_path', default=DEFAULT_IMAGES_PATH, help='Image path or directory of images to predict ' 'their depth maps') parser.add_argument("-l", "--log_file", default=DEFAULT_LOG_FILE, help="The name of the log file.") parser.add_argument("-b", "--batch_size", default=DEFAULT_BATCH_SIZE, type=int, help="the batch size for inference") parser.add_argument("-g", "--is_debug", default=IS_DEBUG, type=bool, help="is it the debug mode execution") args = parser.parse_args(args=sys.argv[1:]) log_file = args.log_file IS_DEBUG = args.is_debug utils.set_up_logging(log_file=log_file, is_debug=args.is_debug) logger = utils.get_logger(name=__name__) if IS_DEBUG: logger.setLevel(logging.DEBUG) logger.debug("current working directory: " + os.getcwd()) # predict the depth maps main(model_path=args.model_path, images_path=args.image_path)
[ 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, 198, 6738, 350, 4146, 1330, 7412, 198...
2.452355
1,868
""" Kafka schema """ from . import serializer from . import avro from . import registry __version__:str = '1.0.0.rc1' __author__: str ='Brandon Bluemner'
[ 37811, 46906, 32815, 198, 37811, 198, 6738, 764, 1330, 11389, 7509, 198, 6738, 764, 1330, 1196, 305, 198, 6738, 764, 1330, 20478, 628, 198, 834, 9641, 834, 25, 2536, 796, 705, 16, 13, 15, 13, 15, 13, 6015, 16, 6, 198, 834, 9800, 8...
2.854545
55
""" Create a vocabulary wrapper. Original code: https://github.com/yalesong/pvse/blob/master/vocab.py """ from collections import Counter import json import os import pickle import fire from nltk.tokenize import word_tokenize from pycocotools.coco import COCO ANNOTATIONS = { 'mrw': ['mrw-v1.0.json'], 'tgif': ['tgif-v1.0.tsv'], 'coco': ['annotations/captions_train2014.json', 'annotations/captions_val2014.json'], } class Vocabulary(object): """Simple vocabulary wrapper.""" def build_vocab(data_path, data_name, jsons, threshold): """Build a simple vocabulary wrapper.""" counter = Counter() for path in jsons[data_name]: full_path = os.path.join(os.path.join(data_path, data_name), path) if data_name == 'tgif': captions = from_tgif_tsv(full_path) elif data_name == 'mrw': captions = from_mrw_json(full_path) elif data_name == 'coco': captions = from_coco_json(full_path) else: captions = from_txt(full_path) for caption in captions: tokens = word_tokenize(caption.lower()) counter.update(tokens) # Discard if the occurrence of the word is less than min_word_cnt. words = [word for word, cnt in counter.items() if cnt >= threshold] print('Vocabulary size: {}'.format(len(words))) # Create a vocab wrapper and add some special tokens. vocab = Vocabulary() vocab.add_word('<pad>') vocab.add_word('<start>') vocab.add_word('<end>') vocab.add_word('<unk>') # Add words to the vocabulary. for word in words: vocab.add_word(word) return vocab if __name__ == '__main__': fire.Fire(main)
[ 37811, 13610, 257, 25818, 29908, 13, 198, 198, 20556, 2438, 25, 198, 5450, 1378, 12567, 13, 785, 14, 88, 2040, 506, 14, 79, 85, 325, 14, 2436, 672, 14, 9866, 14, 18893, 397, 13, 9078, 198, 37811, 198, 198, 6738, 17268, 1330, 15034, ...
2.353825
732
import torch import torch.nn as nn import torch.nn.functional as F from network.vgg import VggNet from network.resnet import ResNet from util.config import config as cfg
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 3127, 13, 85, 1130, 1330, 569, 1130, 7934, 198, 6738, 3127, 13, 411, 3262, 1330, 1874, 7934, 198, 6738, 7736, 13, ...
3.411765
51
import numpy as np import torch from sklearn.utils import resample import torch.multiprocessing torch.multiprocessing.set_sharing_strategy('file_system')
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 1341, 35720, 13, 26791, 1330, 581, 1403, 198, 11748, 28034, 13, 16680, 541, 305, 919, 278, 198, 13165, 354, 13, 16680, 541, 305, 919, 278, 13, 2617, 62, 21987, 62, 2536, 433...
3.156863
51
k = 128 input_size = 320 # number of input bits upper_bound_gates = 11000 # path to the cbmc compiler cbmc_path = "data/CBMC-GC-2/bin/" default_output = "cbmc_parser/gate_files/default_output/" # on Windows it has to be the address of the "Hyper-V Virtual Ethernet Adapter #2" if you use docker test_server_ip = 'localhost' test_server_port = 8448
[ 74, 796, 13108, 198, 15414, 62, 7857, 796, 20959, 220, 1303, 1271, 286, 5128, 10340, 198, 45828, 62, 7784, 62, 70, 689, 796, 1367, 830, 198, 198, 2, 3108, 284, 262, 269, 20475, 66, 17050, 198, 66, 20475, 66, 62, 6978, 796, 366, 78...
2.900826
121
from flask import Flask, render_template, jsonify from extractor import extractorv1 import functools import os import sqlalchemy as sql import pandas as pd import datetime import pickle from app import predictions import time while True: now = datetime.datetime.now() hour = now.hour minute = now.minute second = now.second if hour == 1 and minute == 1 and second == 1: predictions("available_bike_stands") time.sleep((24*60*60) - 1)
[ 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 11, 33918, 1958, 198, 6738, 7925, 273, 1330, 7925, 273, 85, 16, 198, 11748, 1257, 310, 10141, 198, 11748, 28686, 198, 11748, 44161, 282, 26599, 355, 44161, 198, 11748, 19798, 292, 355, 279,...
2.727778
180
# -*- coding: utf-8 -*- """ Created on Tue Aug 4 14:27:23 2020 @author: MBelobraydic """ import argparse import sys import pandas as pd import json from dbf900_main_bytes import yield_blocks, parse_record from dbf900_layouts_bytes import dbf900_layout from dbf900_formats_bytes import pic_yyyymmdd, pic_numeric, pic_any if __name__ == '__main__': main() print('WorkingFileForTesting.py complete.')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 30030, 2447, 220, 604, 1478, 25, 1983, 25, 1954, 12131, 198, 198, 31, 9800, 25, 10771, 417, 672, 2433, 67, 291, 198, 37811, 198, 11748, 1822, 2...
2.656051
157
#!/usr/bin/env python from django.core.management import call_command from boot_django import boot_django boot_django() call_command("makemigrations", "formulaic")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 1330, 869, 62, 21812, 198, 6738, 6297, 62, 28241, 14208, 1330, 6297, 62, 28241, 14208, 198, 198, 18769, 62, 28241, 14208, 3419, 198, 13345, ...
3.018182
55
import numpy as np from scipy import integrate import matplotlib.pyplot as plt from UTILS.Calculus import Calculus from UTILS.SetAxisLimit import SetAxisLimit from UTILS.Tools import Tools from UTILS.Errors import Errors import sys # Theoretical background https://arxiv.org/abs/1401.5176 # Mocak, Meakin, Viallet, Arnett, 2014, Compressible Hydrodynamic Mean-Field # # Equations in Spherical Geometry and their Application to Turbulent Stellar # # Convection Data #
[ 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 1330, 19386, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 19255, 45484, 13, 9771, 17576, 1330, 2199, 17576, 198, 6738, 19255, 45484, 13, 7248, 31554, 27...
3.263889
144
"""Disassembler of Python byte code into mnemonics.""" import sys import types from opcode import * from opcode import __all__ as _opcodes_all __all__ = ["dis","disassemble","distb","disco"] + _opcodes_all del _opcodes_all def dis(x=None): """Disassemble classes, methods, functions, or code. With no argument, disassemble the last traceback. """ if x is None: distb() return if type(x) is types.InstanceType: x = x.__class__ if hasattr(x, 'im_func'): x = x.im_func if hasattr(x, 'func_code'): x = x.func_code if hasattr(x, '__dict__'): items = x.__dict__.items() items.sort() for name, x1 in items: if type(x1) in (types.MethodType, types.FunctionType, types.CodeType, types.ClassType): print "Disassembly of %s:" % name try: dis(x1) except TypeError, msg: print "Sorry:", msg print elif hasattr(x, 'co_code'): disassemble(x) elif isinstance(x, str): disassemble_string(x) else: raise TypeError, \ "don't know how to disassemble %s objects" % \ type(x).__name__ def distb(tb=None): """Disassemble a traceback (default: last traceback).""" if tb is None: try: tb = sys.last_traceback except AttributeError: raise RuntimeError, "no last traceback to disassemble" while tb.tb_next: tb = tb.tb_next disassemble(tb.tb_frame.f_code, tb.tb_lasti) def disassemble(co, lasti=-1): """Disassemble a code object.""" code = co.co_code byte_increments = [ord(c) for c in co.co_lnotab[0::2]] line_increments = [ord(c) for c in co.co_lnotab[1::2]] table_length = len(byte_increments) # == len(line_increments) lineno = co.co_firstlineno table_index = 0 while (table_index < table_length and byte_increments[table_index] == 0): lineno += line_increments[table_index] table_index += 1 addr = 0 line_incr = 0 labels = findlabels(code) n = len(code) i = 0 extended_arg = 0 free = None while i < n: c = code[i] op = ord(c) if i >= addr: lineno += line_incr while table_index < table_length: addr += byte_increments[table_index] line_incr = line_increments[table_index] table_index += 1 if line_incr: break else: addr = sys.maxint if i > 0: print print "%3d"%lineno, else: print ' ', if i == lasti: print '-->', else: print ' ', if i in labels: print '>>', else: print ' ', print `i`.rjust(4), print opname[op].ljust(20), i = i+1 if op >= HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg extended_arg = 0 i = i+2 if op == EXTENDED_ARG: extended_arg = oparg*65536L print `oparg`.rjust(5), if op in hasconst: print '(' + `co.co_consts[oparg]` + ')', elif op in hasname: print '(' + co.co_names[oparg] + ')', elif op in hasjrel: print '(to ' + `i + oparg` + ')', elif op in haslocal: print '(' + co.co_varnames[oparg] + ')', elif op in hascompare: print '(' + cmp_op[oparg] + ')', elif op in hasfree: if free is None: free = co.co_cellvars + co.co_freevars print '(' + free[oparg] + ')', print disco = disassemble # XXX For backwards compatibility def findlabels(code): """Detect all offsets in a byte code which are jump targets. Return the list of offsets. """ labels = [] n = len(code) i = 0 while i < n: c = code[i] op = ord(c) i = i+1 if op >= HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 label = -1 if op in hasjrel: label = i+oparg elif op in hasjabs: label = oparg if label >= 0: if label not in labels: labels.append(label) return labels def _test(): """Simple test program to disassemble a file.""" if sys.argv[1:]: if sys.argv[2:]: sys.stderr.write("usage: python dis.py [-|file]\n") sys.exit(2) fn = sys.argv[1] if not fn or fn == "-": fn = None else: fn = None if fn is None: f = sys.stdin else: f = open(fn) source = f.read() if fn is not None: f.close() else: fn = "<stdin>" code = compile(source, fn, "exec") dis(code) if __name__ == "__main__": _test()
[ 37811, 7279, 34455, 1754, 286, 11361, 18022, 2438, 656, 285, 77, 7966, 873, 526, 15931, 198, 198, 11748, 25064, 198, 11748, 3858, 198, 198, 6738, 1034, 8189, 1330, 1635, 198, 6738, 1034, 8189, 1330, 11593, 439, 834, 355, 4808, 404, 4014...
1.845302
2,799
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RSplancs(RPackage): """Spatial and Space-Time Point Pattern Analysis""" homepage = "https://cloud.r-project.org/package=splancs" url = "https://cloud.r-project.org/src/contrib/splancs_2.01-40.tar.gz" list_url = "https://cloud.r-project.org/src/contrib/Archive/splancs" version('2.01-40', sha256='79744381ebc4a361740a36dca3c9fca9ae015cfe0bd585b7856a664a3da74363') depends_on('r@2.10:', type=('build', 'run')) depends_on('r-sp@0.9:', type=('build', 'run'))
[ 2, 15069, 2211, 12, 1238, 1828, 13914, 45036, 3549, 2351, 4765, 11, 11419, 290, 584, 198, 2, 1338, 441, 4935, 34152, 13, 4091, 262, 1353, 12, 5715, 27975, 38162, 9947, 2393, 329, 3307, 13, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, ...
2.472414
290
# Copyright 2020 Mobvoi Inc. (authors: Fangjun Kuang) # Xiaomi Corp. (author: Haowen Qiu) # # See ../../../LICENSE for clarification regarding multiple authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import List from typing import Tuple from typing import Union import torch import k2 import _k2 from .fsa import Fsa # put index_select here instead of in `autograd.py` to break circular import def index_select(src: torch.Tensor, index: torch.Tensor, default_value: float = 0) -> torch.Tensor: '''Returns a new tensor which indexes the input tensor along dimension 0 using the entries in `index`. If the entry in `index` is -1, then the corresponding entry in the returned tensor is 0. Caution: `index.dtype == torch.int32` and `index.ndim == 1`. Args: src: The input tensor. Either 1-D or 2-D with dtype `torch.int32`, `torch.int64`, `torch.float32`, or `torch.float64`. index: 1-D tensor of dtype `torch.int32` containing the indexes. If an entry is -1, the corresponding entry in the returned value is 0. The elements of `index` should be in the range `[-1..src.shape[0]-1]`. default_value: Used only when `src` is a 1-D tensor. It sets ans[i] to default_value if index[i] is -1. Returns: A tensor with shape ``(index.numel(), *src.shape[1:])`` and dtype the same as `src`, e.g. if `src.ndim == 1`, `ans.shape` would be `(index.shape[0],)`; if `src.ndim == 2`, `ans.shape` would be `(index.shape[0], src.shape[1])`. Will satisfy `ans[i] == src[index[i]]` if `src.ndim == 1`, or `ans[i, j] == src[index[i], j]` if `src.ndim == 2`, except for entries where `index[i] == -1` which will be zero. ''' ans = _IndexSelectFunction.apply(src, index, default_value) return ans def index_add(index: torch.Tensor, value: torch.Tensor, in_out: torch.Tensor) -> None: '''It implements in_out[index[i]] += value[i]. Caution: It has similar semantics with `torch.Tensor.index_add_` except that: - `index.dtype == torch.int32` - `-1 <= index[i] < in_out.shape[0]` - `index[i] == -1` is ignored. - `index` has to be a 1-D **contiguous** tensor. Caution: `in_out` is modified **in-place**. Caution: This functions does NOT support autograd. Args: index: A 1-D **contiguous** tensor with dtype `torch.int32`. Must satisfy `-1 <= index[i] < in_out.shape[0]` value: A 1-D or 2-D tensor with dtype `torch.int32`, `torch.float32`, or `torch.float64`. Must satisfy `index.shape[0] == value.shape[0]` in_out: A 1-D or 2-D tensor with the same dtype as `value`. It satisfies `in_out.shape[1] == value.shape[1]` if it is a 2-D tensor. Returns: Return None. ''' _k2.index_add(index, value, in_out) def index_fsa(src: Fsa, indexes: torch.Tensor) -> Fsa: '''Select a list of FSAs from `src` with a 1-D tensor. Args: src: An FsaVec. indexes: A 1-D `torch.Tensor` of dtype `torch.int32` containing the ids of FSAs to select. Returns: Return an FsaVec containing only those FSAs specified by `indexes`. ''' # TODO: export it to k2 ragged_arc, value_indexes = _k2.index(src.arcs, axis=0, indexes=indexes, need_value_indexes=True) out_fsa = Fsa(ragged_arc) for name, value in src.named_tensor_attr(): if isinstance(value, torch.Tensor): setattr(out_fsa, name, k2.ops.index_select(value, value_indexes)) else: assert isinstance(value, k2.RaggedTensor) assert value.dtype == torch.int32 ragged_value, _ = value.index(value_indexes, axis=0, need_value_indexes=False) setattr(out_fsa, name, ragged_value) for name, value in src.named_non_tensor_attr(): setattr(out_fsa, name, value) return out_fsa def cat(srcs: List[Fsa]) -> Fsa: '''Concatenate a list of FsaVec into a single FsaVec. Caution: Only common tensor attributes are kept in the output FsaVec. For non-tensor attributes, only one copy is kept in the output FsaVec. We choose the first copy of the FsaVec that has the lowest index in `srcs`. Args: srcs: A list of FsaVec. Each element MUST be an FsaVec. Returns: Return a single FsaVec concatenated from the input FsaVecs. ''' for src in srcs: assert len(src.shape) == 3, f'Expect an FsaVec. Given: {src.shape}' src_ragged_arcs = [fsa.arcs for fsa in srcs] ans_ragged_arcs = _k2.cat(src_ragged_arcs, axis=0) out_fsa = Fsa(ans_ragged_arcs) common_tensor_attributes = ( set(dict(src.named_tensor_attr()).keys()) for src in srcs) common_tensor_attributes = set.intersection( *list(common_tensor_attributes)) for name in common_tensor_attributes: # We assume that the type of the attributes among # FsaVecs are the same if they share the same name. values = [getattr(src, name) for src in srcs] if isinstance(values[0], torch.Tensor): # NOTE: We assume the shape of elements in values # differ only in shape[0]. value = torch.cat(values) else: assert isinstance(values[0], k2.RaggedTensor) value = k2.ragged.cat(values, axis=0) setattr(out_fsa, name, value) for src in srcs: for name, value in src.named_non_tensor_attr(): if not hasattr(out_fsa, name): setattr(out_fsa, name, value) return out_fsa def compose_arc_maps(step1_arc_map: torch.Tensor, step2_arc_map: torch.Tensor) -> torch.Tensor: '''Compose arc maps from two Fsa operations. It implements: - ans_arc_map[i] = step1_arc_map[step2_arc_map[i]] if step2_arc_map[i] is not -1 - ans_arc_map[i] = -1 if step2_arc_map[i] is -1 for i in 0 to `step2_arc_map.numel() - 1`. Args: step1_arc_map: A 1-D tensor with dtype torch.int32 from the first Fsa operation. step2_arc_map: A 1-D tensor with dtype torch.int32 from the second Fsa operation. Returns: Return a 1-D tensor with dtype torch.int32. It has the same number of elements as step2_arc_map. That is, ans_arc_map.shape == step2_arc_map.shape. ''' assert step1_arc_map.ndim == 1 assert step1_arc_map.dtype == torch.int32 assert step2_arc_map.ndim == 1 assert step2_arc_map.dtype == torch.int32 return _k2.index_select(step1_arc_map, step2_arc_map, default_value=-1)
[ 2, 15069, 220, 220, 220, 220, 220, 12131, 220, 16540, 13038, 72, 3457, 13, 220, 220, 220, 220, 220, 220, 220, 357, 41617, 25, 24468, 29741, 12554, 648, 8, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.228351
3,372
from django.contrib import admin from back.models.node import * @admin.register(Node) # @admin.register(Sensor) # class SensorAdmin(admin.ModelAdmin): # search_fields = ['node__uid', 'description'] # list_display = ['node', 'pin', 'sensor_type', # 'description', 'created', 'modified'] # list_filter = ['node__owner', 'sensor_type'] @admin.register(SensorLocation) @admin.register(SensorType)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 6738, 736, 13, 27530, 13, 17440, 1330, 1635, 628, 198, 198, 31, 28482, 13, 30238, 7, 19667, 8, 628, 198, 2, 2488, 28482, 13, 30238, 7, 47864, 8, 198, 2, 1398, 35367, 46787, ...
2.685185
162
import errno import mock from chroma_agent.lib import node_admin from chroma_agent.lib.shell import AgentShell from iml_common.test.command_capture_testcase import ( CommandCaptureTestCase, CommandCaptureCommand, )
[ 11748, 11454, 3919, 198, 11748, 15290, 198, 6738, 15358, 64, 62, 25781, 13, 8019, 1330, 10139, 62, 28482, 198, 6738, 15358, 64, 62, 25781, 13, 8019, 13, 29149, 1330, 15906, 23248, 198, 6738, 545, 75, 62, 11321, 13, 9288, 13, 21812, 62...
3.246377
69
import pygame from queue import PriorityQueue """ Path Finding - Buscador de caminhos com A* É um programa em python desenvolvido durante a disciplina de Inteligência Artificial da Faculdade de Tecnologia da Unicamp pelos alunos: 1. Kevin Barrios 2. Larissa Benevides 3. Matheus Alves 4. Matheus Bruder 5. Miguel Amaral O Objetivo deste programa é simular visualmente cada uma das decisões tomadas em uma busca utilizando o algoritmo A*. Além disso, utilizamos tanto de heurísticas admissíveis, como heurísticas inadmissíveis para poder comparar os resultados. """ # ----------------------------------------------------------------------- # CONFIGURAÇÕES GERAIS # ----------------------------------------------------------------------- # Cada estado de um Nó é representado por uma cor: ESTADOS = { 'vazio': (255, 255, 255), # Branco 'fechado': (0, 53, 73), # Vermelho 'aberto': (64, 208, 231), # Verde 'inicio': (39, 161, 23), # Azul 'fim': (255, 0, 0), # Amarelo 'obstaculo': (128, 128, 128), # Preto 'caminho': (252, 255, 72), # Verde Claro } # Dimensões: LARGURA = 1600 ALTURA = 800 JANELA = pygame.display.set_mode((LARGURA, ALTURA)) # Tamanho da janela pygame.display.set_caption( 'Path Finding - Buscador de caminhos com A*') # Título da janela # Definições para escrita de texto na tela do jogo: pygame.font.init() font_titulo = pygame.font.Font(pygame.font.get_default_font(), 30) font = pygame.font.Font(pygame.font.get_default_font(), 12) font_aviso = pygame.font.Font(pygame.font.get_default_font(), 15) COR_FONTE = (255, 255, 255) # Definição dos títulos textuais dentro da tela: cabecalho_arvore_busca = font_titulo.render('Árvore de Busca', True, COR_FONTE) cabecalho_lista_abertos = font_titulo.render( 'Lista de nós abertos', True, COR_FONTE) cabecalho_lista_fechados = font_titulo.render( 'Lista de nós fechados', True, COR_FONTE) # Deslocamento dos textos na tela: deslocamento_y_abertos = 90 deslocamento_x_abertos = 1250 deslocamento_y_fechados = 440 deslocamento_x_fechados = 1250 deslocamento_y_arvore = 90 deslocamento_x_arvore = 900 # ----------------------------------------------------------------------- # CLASSE PARA CADA UM DOS NÓS DISPOSTOS NA TELA # ----------------------------------------------------------------------- class Ponto: """ Classe utilizada para gerar cada um dos 'quadradinhos' ou 'nós' do grafo. """ # Construtor: # Getters: # Setters: # Métodos para checagem de estados de cada nó: # Outros Métodos: def desenhar(self, janela): ''' Desenha um quadrado na janela (pygame window) passada por parâmetro. Parâmetros: janela (pygame window): janela do pygame. Observação: O ponto (0, 0) fica localizado no vértice superior esquerdo. Logo, aumentar o Y significa ir para baixo e aumentar o X ir para a direita. ''' pygame.draw.rect(janela, self.estado, (self.x, self.y, self.largura, self.largura)) def atualizar_pontos_vizinhos(self, matriz): ''' Atualizar a lista com todos os pontos próximos ao ponto em questão, verificando se o ponto existe e se não é um obstáculo. Parâmetro: matrix (list): lista de listas. ''' self.vizinhos = [] # O ponto de baixo existe? Ele é um obstaculo?: if self.linha < self.qtd_linhas - 1 \ and not matriz[self.linha + 1][self.coluna].is_obstaculo(): self.vizinhos.append(matriz[self.linha + 1][self.coluna]) # O ponto de cima existe? Ele é um obstaculo?: if self.linha > 0 \ and not matriz[self.linha - 1][self.coluna].is_obstaculo(): self.vizinhos.append(matriz[self.linha - 1][self.coluna]) # O ponto da direita existe? Ele é um obstaculo?: if self.coluna < self.qtd_linhas - 1 \ and not matriz[self.linha][self.coluna + 1].is_obstaculo(): self.vizinhos.append(matriz[self.linha][self.coluna + 1]) # O ponto da esquerda existe? Ele é um obstaculo?: if self.coluna > 0 \ and not matriz[self.linha][self.coluna - 1].is_obstaculo(): self.vizinhos.append(matriz[self.linha][self.coluna - 1]) # ----------------------------------------------------------------------- # HEURÍSTICAS # ----------------------------------------------------------------------- def manhattan(p1, p2): # -> Admissível ''' Heurística 01: Manhattan. Será utilizada a distância de Manhattan como uma das heurísticas adimissíveis. Parâmetros: p1 (Ponto): ponto inicial, de onde quer sair. p2 (Ponto): ponto final, para onde quer ir. Retorno: int: distância 'Manhattan' entre p1 e p2. ''' x1, y1 = p1 x2, y2 = p2 return abs(x1 - x2) + abs(y1 - y2) def chebyshev(p1, p2): # -> Admissível ''' Heurística 02: Chebyshev. Retona a maior entre as diferenças de X e Y de dois pontos. Parâmetros: p1 (Ponto): ponto inicial, de onde quer sair. p2 (Ponto): ponto final, para onde quer ir. Retorno: int: distância 'Chebyshev' entre p1 e p2. ''' x1, y1 = p1 x2, y2 = p2 return max(abs(x1 - x2), abs(y1 - y2)) def heuristica_inadmissivel(p1, p2): # -> Inadmissível ''' Heurística 03: Multiplica a distância de manhattan pela distância de chebyshev. Parâmetros: p1 (Ponto): ponto inicial, de onde quer sair. p2 (Ponto): ponto final, para onde quer ir. Retorno: int: distância "inventada" entre p1 e p2. ''' return manhattan(p1, p2) * chebyshev(p1, p2) # ----------------------------------------------------------------------- # Buscador de Caminhos com A* # ----------------------------------------------------------------------- def busca_A_estrela(redesenhar_tela, matriz, pos_inicio, pos_fim): ''' Função central do projeto. É aqui que o algoritmo A* é definido, todas as estruturas de dados são modificadas e a melhor decisão é tomada com base em uma determinada função de avaliação. F(n) = g(n) + h(n) Parâmetros: redesenhar_tela (function): função que atualiza a tela. matriz (list): lista de listas. pos_inicio (Ponto): ponto inicial, do qual parte-se. pos_fim (Ponto): ponto final, no qual pretende-se chegar. ''' contador = 0 caminho = {} global deslocamento_y_abertos, deslocamento_x_abertos, deslocamento_x_fechados, deslocamento_y_fechados # Estrutura de dados dos nós abertos e fechados: fila = PriorityQueue() # Retorna sempre o menor elemento da fila fila.put((0, contador, pos_inicio)) lista_abertos = {pos_inicio} lista_fechados = set() # Parâmetros para função de avaliação: g = {ponto: float("inf") for linha in matriz for ponto in linha} g[pos_inicio] = 0 f = {ponto: float("inf") for linha in matriz for ponto in linha} iterador = 0 while not fila.empty(): iterador += 1 # Encerra o jogo ao clicar no botão de sair: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() atual = fila.get()[2] atual.set_g(g[atual]) # Valor de 'g' para cada nó # Solução encontrada? Desenha o melhor caminho: if atual == pos_fim: lista_abertos.remove(pos_fim) lista_fechados.add(pos_fim) print(f"ITERACAO {iterador:2}: ") printar_listas(lista_abertos, lista_fechados) print('========= ARVORE DE BUSCA =========') print(f'CUSTO REAL = {pos_fim.get_g()}') # Enviar listas por parametros desenhar_melhor_caminho(caminho, pos_fim, redesenhar_tela) pos_fim.set_fim() pos_inicio.set_inicio() for ponto in lista_abertos: # Exibe o nó aberto na tela do jogo: if deslocamento_x_abertos > LARGURA - 50: deslocamento_x_abertos = 1250 deslocamento_y_abertos += 20 JANELA.blit(font.render(str(ponto) + ',', True, COR_FONTE), dest=(deslocamento_x_abertos, deslocamento_y_abertos)) deslocamento_x_abertos += 55 for ponto in lista_fechados: # Exibe o nó fechado na tela do jogo: if deslocamento_x_fechados > LARGURA - 50: deslocamento_x_fechados = 1250 deslocamento_y_fechados += 20 JANELA.blit(font.render(str(ponto) + ',', True, COR_FONTE), dest=(deslocamento_x_fechados, deslocamento_y_fechados)) deslocamento_x_fechados += 55 return True # Caso contrário: for ponto_vizinho in atual.vizinhos: temp_g = g[atual] + 1 if temp_g < g[ponto_vizinho]: caminho[ponto_vizinho] = atual g[ponto_vizinho] = temp_g # Atualiza valor de f para tomar decisão: f[ponto_vizinho] = temp_g + ponto_vizinho.get_heuristica() # Alteração de estado - Nó aberto: if ponto_vizinho not in lista_abertos \ and ponto_vizinho not in lista_fechados: contador += 1 fila.put((f[ponto_vizinho], contador, ponto_vizinho)) lista_abertos.add(ponto_vizinho) ponto_vizinho.set_aberto() redesenhar_tela() # Alteração de estado - Nó fechado: lista_abertos.remove(atual) lista_fechados.add(atual) atual.set_fechado() print(f"ITERACAO {iterador:2}:") printar_listas(lista_abertos, lista_fechados) return False # ----------------------------------------------------------------------- # ESTRUTURA DE DADOS # ----------------------------------------------------------------------- def criar_matriz(qtd_linhas, largura): ''' Criar uma matriz, ou seja, uma lista de listas para guardar cada um dos pontos criados. Parâmetros: qtd_linhas (int): número de linhas. largura (int): tamanho da janela. Retorno: list: lista de listas, a matriz. ''' matriz = [] margem = largura // qtd_linhas # Espaço entre os nós dentro do jogo for linha in range(qtd_linhas): matriz.append([]) for coluna in range(qtd_linhas): # Criação de um novo nó: ponto = Ponto(linha=linha, coluna=coluna, largura=margem, qtd_linhas=qtd_linhas) matriz[linha].append(ponto) return matriz # ----------------------------------------------------------------------- # FUNÇÕES AUXILIARES # ----------------------------------------------------------------------- def desenhar_grade(janela, qtd_linhas, largura): ''' Desenha as linhas que delimitam cada um dos pontos (nós) do grafo. Isto é, aqui é gerada a representação visual da estrutura de dados, ou melhor, da matriz. Parâmetros: janela (pygame window): janela do pygame. qtd_linhas (int): número de linhas. largura (int): tamanho da janela. ''' COR_LINHAS = (128, 128, 128) margem = largura // qtd_linhas # Espaço entre os nós dentro do jogo # Desenha as linhas horizontais: for linha in range(qtd_linhas): pygame.draw.line(janela, COR_LINHAS, (0, linha * margem), (largura, linha * margem)) # Desenha as linhas verticais: for coluna in range(qtd_linhas): pygame.draw.line(janela, COR_LINHAS, (coluna * margem, 0), (coluna * margem, largura)) def redesenhar_tela(janela, matriz, qtd_linhas, largura): ''' Redesenha, isto é, limpa a tela e redenha tudo novamente com os estados atuais. Parâmetros: janela (pygame window): janela do pygame. matriz (list): lista de listas. qtd_linhas (int): número de linhas. largura (int): tamanho da janela. ''' janela.blit(cabecalho_arvore_busca, dest=(900, 50)) janela.blit(cabecalho_lista_abertos, dest=(1250, 50)) janela.blit(cabecalho_lista_fechados, dest=(1250, 400)) janela.blit(font_aviso.render( 'Aperte a tecla "f5" para reiniciar o jogo', False, (0, 255, 0)), dest=(1300, 25)) for linha in matriz: for ponto in linha: # Desenha cada nó de cada uma das linhas: ponto.desenhar(janela) desenhar_grade(janela, qtd_linhas, largura) pygame.display.update() def get_mouse_pos(mouse_pos, qtd_linhas, largura): ''' Retorna a posição em que o mouse estava quando houve o clique. Parâmetros: mouse_pos (tuple): posição do mouse [x, y] no momento do clique. qtd_linhas (int): número de linhas. largura (int): tamanho da janela. Retorno: tuple: posição x, y do mouse quando houver clique. ''' margem = largura // qtd_linhas # Espaço entre os nós dentro do jogo x, y = mouse_pos linha = x // margem coluna = y // margem return linha, coluna def desenhar_melhor_caminho(caminho, atual, redesenhar_tela): ''' Desenha na tela o melhor caminho após o algoritmo ter encontrado uma solução. Somente será o melhor caminho caso a heurística escolhida seja admissível. Parâmetros: caminho(dict): dicionário com todos o nós do melhor caminho. atual(Point): ponto atual, o destino. redesenhar_tela(function): função que redesenha a tela. ''' global deslocamento_y_arvore, deslocamento_x_arvore print('CAMINHO ESCOLHIDO:') print(f'Ponto: {atual.get_posicao()} G: {atual.get_g()} H: {atual.get_heuristica()} | F = {atual.get_g() + atual.get_heuristica()}', end=" ") JANELA.blit(font.render( str(f'Ponto: {atual.get_posicao()} G: {atual.get_g()} H: {atual.get_heuristica()} | F = {atual.get_g() + atual.get_heuristica()}'), True, COR_FONTE), dest=(deslocamento_x_arvore, 90)) print() while atual in caminho: atual.set_caminho() atual = caminho[atual] redesenhar_tela() deslocamento_y_arvore += 20 JANELA.blit(font.render( str(f'Ponto: {atual.get_posicao()} G: {atual.get_g()} H: {atual.get_heuristica()} | F = {atual.get_g() + atual.get_heuristica()}'), True, COR_FONTE), dest=(deslocamento_x_arvore, deslocamento_y_arvore)) print( f'Ponto: {atual.get_posicao()} G: {atual.get_g()} H: {atual.get_heuristica()} | F = {atual.get_g() + atual.get_heuristica()}') redesenhar_tela() # ----------------------------------------------------------------------- # FUNÇÃO PRINCIPAL # ----------------------------------------------------------------------- # ----------------------------------------------------------------------- # INICIA O JOGO # ----------------------------------------------------------------------- main(janela=JANELA, largura=LARGURA)
[ 11748, 12972, 6057, 201, 198, 6738, 16834, 1330, 34416, 34991, 201, 198, 201, 198, 37811, 201, 198, 15235, 27063, 532, 5869, 66, 7079, 390, 269, 5669, 71, 418, 401, 317, 9, 201, 198, 38351, 23781, 1430, 64, 795, 21015, 748, 268, 10396...
2.050433
7,614
#!/usr/bin/env python3 # -"- encoding: utf-8 -"- import re import pickle from tgen.data import DA from tgen.tfclassif import Reranker from tgen.logf import log_info from tgen.futil import file_stream, read_das # ---- # BEGIN code copied over from e2e-cleaning -- TODO dependency? # ---- REALIZATIONS = { 'area': { 'city centre': [ '(?:city|town) cent(?:re|er)', 'cent(?:re|er) of (?:the )?(?:city|town)', 'in the cent(?:re|er)', ], 'riverside': [ 'riverside', '(?:near|by|at|close to|along|on|off|beside) the river', ], }, 'eat_type': { 'coffee shop': [ 'coffee[- ]+shop', 'caf[eé]', 'coffee', ], 'pub': [ 'pub', ], 'restaurant': [ 'restaurant', ], }, 'family_friendly': { 'no': [ r'(?:isn\'t|not|non|no)[ -]+(?:\w+ ){0,2}(?:child|children|family|kids|kid)[ -]+(?:friendly|orien(?:ta)?ted)', '(?:child|children|family|kids|kid)[ -]+unfriendly', 'adults?[ -]+only', 'only for adults', '(?:no|not) (?:kids|children|famil(?:y|ies))', '(?:not|no)(?: good| suitable| friendly| orien(?:ta)?ted| open(?:ed))? (?:at|for|to|with)(?: the)? (?:kids|children|family|families|all age)', '(?:kids?|child(?:ren)?|famil(?:y|ies)) (?:are|is)(?:n\'t| not) (?:welcome|allowed|accepted)', r'(?:does not|doesn\'t) (?:welcome|allow|accept) (?:\w+ ){0,2}(?:kids?|child(?:ren)?|famil(?:y|ies)|all age)', 'adult (?:establishment|venue|place|establish)', ], 'yes': [ 'for (?:kids|children|family|families)', 'family place', 'place to bring the(?: whole)? family', '(?:friendly|suitable|good|orien(?:ta)?ted|open(?:ed)) (?:at|with|to|for)(?: the)(?:kids?|child(?:ren)?|famil(?:y|ies)?|all age)', '(?:child|children|family|kids|kid)[ -]+(?:friendly|orien(?:ta)?ted)', '(?:kids?|child(?:ren)?|famil(?:y|ies)) (?:are|is) (?:welcome|allowed|accepted)', r'(?:welcomes?|allows?|accepts?) (?:\w+ ){0,2}(?:kids?|child(?:ren)?|famil(?:y|ies)|all age)', ], }, 'food': { 'Chinese': ['Chinese', 'Chines'], 'English': ['English', 'British'], 'Fast food': ['Fast food'], 'French': ['French'], 'Indian': ['Indian'], 'Italian': ['Italian'], 'Japanese': ['Japanese'], }, 'name': [ 'Alimentum', 'Aromi', 'Bibimbap House', 'Blue Spice', 'Browns Cambridge', 'Clowns', 'Cocum', 'Cotto', 'Fitzbillies', 'Giraffe', 'Green Man', 'Loch Fyne', 'Midsummer House', 'Strada', 'Taste of Cambridge', 'The Cambridge Blue', 'The Cricketers', 'The Dumpling Tree', 'The Eagle', 'The Golden Curry', 'The Golden Palace', 'The Mill', 'The Olive Grove', 'The Phoenix', 'The Plough', 'The Punter', 'The Rice Boat', 'The Twenty Two', 'The Vaults', 'The Waterman', 'The Wrestlers', 'Travellers Rest Beefeater', 'Wildwood', 'Zizzi', 'X-name', ], 'near': [ 'All Bar One', 'Avalon', 'Burger King', 'Café Adriatic', 'Café Brazil', 'Café Rouge', 'Café Sicilia', 'Clare Hall', 'Crowne Plaza Hotel', 'Express by Holiday Inn', 'Rainbow Vegetarian Café', 'Raja Indian Cuisine', 'Ranch', 'The Bakers', 'The Portland Arms', 'The Rice Boat', 'The Six Bells', 'The Sorrento', 'Yippee Noodle Bar', 'X-near', ], 'price_range': { "cheap": [ "(?:inexpensive|cheap)(?:ly)?", "low[- ]+price[ds]?", "affordabl[ey]", r"prices?(?: range)?(?: \w+){0,3} low", ], "less than £20": [ "(?:inexpensive|cheap)(?:ly)?", "affordabl[ey]", "(?:less than|under) £? *20", "moderately priced", "low[- ]+price[ds]?", r"prices?(?: range)?(?: \w+){0,3} low", ], "more than £30": [ "(?:more than|over) £? *30", "high[- ]+price[ds]?", "expensive", "not cheap", r"prices?(?: range)?(?: \w+){0,3} high", ], "high": [ "high[- ]+price[ds]?", "expensive", r"prices?(?: range)?(?: \w+){0,3} high", ], "moderate": [ "(?:moderate|reasonable|ok|average)(?:ly)?[- ]+price[ds]?", "not cheap", "affordable", "mid[- ]+(?:range[- ]+)price[ds]?", r"prices?(?: range)?(?: \w+){0,3} (?:ok|average|moderate|reasonable)", ], "£20-25": [ "£? *20 *(?:[-–]*|to) *25", "(?:moderate|reasonable|ok|average)(?:ly)?[- ]+price[ds]?", r"prices?(?: range)?(?: \w+){0,3} (?:ok|average|moderate|reasonable)", "affordable", ] }, 'rating': { "1 out of 5": [ "(?:1|one)(?:(?: out)? of (?:5|five)(?: stars?)?|[- ]+stars?)", r"(?:rat(?:ings?|e[ds]?)|reviews?|standards?|quality)(?: \w+){0,2} (?:as )?(?:low|bad|poor)(?:(?: \w+){0,3} (?:1|one)(?:(?: out)? of (?:5|five)|[- ]+stars?))?", r"(?:low|bad|poor|(?:not|doesn't|isn't)(?: \w+){0,2} (:?good|well))(?:ly)?(?:[ -]+\w+){0,2}[ -]+(?:rat(?:ings?|ed)|reviews?|standards?|quality)(?:(?: \w+){0,3} (?:1|one)(?:(?: out)? of (?:5|five)(?: stars?)?|[- ]+stars?))?", ], "3 out of 5": [ "(?:3|three)(?:(?: out)? of (?:5|five)(?: stars?)?|[- ]+stars?)", r"(?:rat(?:ings?|e[ds]?)|reviews?|standards?|quality)(?: \w+){0,2} (?:as )?average(?:(?: \w+){0,3} (?:3|three)(?:(?: out)? of (?:5|five)|[- ]+stars?))?", r"(?:average|(?<!very )(?:good|well))(?:ly)?(?:[ -]+\w+){0,2}[ -]+(?:rat(?:ings?|ed)|reviews?|standards?|quality)(?:(?: \w+){0,3} (?:3|three)(?:(?: out)? of (?:5|five)(?: stars?)?|[- ]+stars?))?", ], "5 out of 5": [ "(?:5|five)(?:(?: out)? of (?:5|five)(?: stars?)?|[- ]+stars?)", r"(?:rat(?:ings?|e[ds]?)|reviews?|standards?|quality)(?: \w+){0,2} (?:as )?high(?:(?: \w+){0,3} (?:5|five)(?:(?: out)? of (?:5|five)|[- ]+stars?))?", r"(?:high|excellent|very good|great)(?:ly)?(?:[ -]+\w+){0,2}[ -]+(?:rat(?:ings?|ed)|reviews?|standards?|quality)(?:(?: \w+){0,3} (?:5|five)(?:(?: out)? of (?:5|five)(?: stars?)?|[- ]+stars?))?", ], "high": [ "(?:5|five)(?:(?: out)? of (?:5|five)(?: stars?)?|[- ]+stars?)", r"(?:rat(?:ings?|e[ds]?)|reviews?|standards?|quality)(?: \w+){0,2} (?:as )?high", r"(?:high|excellent|very good|great|well)(?:ly)?(?:[ -]+\w+){0,2}[ -]+(?:rat(?:ings?|ed)|reviews?|standards?|quality)", ], "average": [ "(?:3|three)(?:(?: out)? of (?:5|five)(?: stars?)?|[- ]+stars?)", r"(?:rat(?:ings?|e[ds]?)|reviews?|standards?|quality)(?: \w+){0,2} (?:as )?average", r"(?:average|(?<!very )(?:good|well))(?:ly)?(?:[ -]+\w+){0,2}[ -]+(?:rat(?:ings?|ed)|reviews?|standards?|quality)", ], "low": [ "(?:1|one)(?:(?: out)? of (?:5|five)(?: stars?)?|[- ]+stars?)", r"(?:rat(?:ings?|e[ds]?)|reviews?|standards?|quality)(?: \w+){0,2} (?:as )?(?:low|bad|poor)", r"(?:low|bad|poor|(?:not|doesn't|isn't)(?: \w+){0,2} (?:well|good))(?:ly)?(?:[ -]+\w+){0,2}[ -]+(?:rat(?:ings?|ed)|reviews?|standards?|quality)", ], }, } def compile_patterns(patterns): """Compile a list of patterns into one big option regex. Note that all of them will match whole words only.""" # pad intent patterns with \b (word boundary), unless they contain '^'/'$' (start/end) return re.compile('|'.join([((r'\b' if not pat.startswith('^') else '') + pat + (r'\b' if not pat.endswith('$') else '')) for pat in patterns]), re.I | re.UNICODE) # store "proper" capitalization of the values CAPITALIZE = {} # compile realization patterns for slot in REALIZATIONS.keys(): if isinstance(REALIZATIONS[slot], list): CAPITALIZE[slot] = {val.lower(): val for val in REALIZATIONS[slot]} REALIZATIONS[slot] = compile_patterns(REALIZATIONS[slot]) else: CAPITALIZE[slot] = {val.lower(): val for val in REALIZATIONS[slot].keys()} for value in REALIZATIONS[slot].keys(): REALIZATIONS[slot][value] = compile_patterns(REALIZATIONS[slot][value]) class Match(object): """Realization pattern match in the system output""" def reclassify_mr(ref, gold_mr=DA()): """Classify the MR given a text. Can use a gold-standard MR to make the classification more precise (in case of ambiguity, goes with the gold-standard value). Returns a dict-based MR format for the system output MR and the gold-standard MR.""" # convert MR to dict for comparing & checking against mr_dict = {} for dai in gold_mr.dais: mr_dict[dai.slot] = mr_dict.get(dai.slot, {}) val = CAPITALIZE[dai.slot][dai.value.lower()] mr_dict[dai.slot][val] = mr_dict[dai.slot].get(val, 0) + 1 # create MR dict representation of the output text # first, collect all value matches matches = [] for slot in REALIZATIONS.keys(): # verbatim slot if not isinstance(REALIZATIONS[slot], dict): matches.extend([Match(slot, CAPITALIZE[slot][match.group(0).lower()], match) for match in REALIZATIONS[slot].finditer(ref)]) # slot with variable realizations else: # collect all matches for all values for value in REALIZATIONS[slot].keys(): matches.extend([Match(slot, CAPITALIZE[slot][value.lower()], match) for match in REALIZATIONS[slot][value].finditer(ref)]) # then filter out those that are substrings/duplicates (let only one value match, # preferrably the one indicated by the true MR -- check with the MR dict) filt_matches = [] for match in matches: skip = False for other_match in matches: if match is other_match: continue if (match.is_substring(other_match) or (match.is_same_string(other_match) and (other_match.value in mr_dict.get(other_match.slot, {}).keys() or other_match in filt_matches))): skip = True break if not skip: filt_matches.append(match) # now put it all into a dict out_dict = {} for match in filt_matches: out_dict[match.slot] = out_dict.get(match.slot, {}) out_dict[match.slot][match.value] = out_dict[match.slot].get(value, 0) + 1 return DA.parse_dict(out_dict) # ---- # END code copied over from e2e-cleaning # ----
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 26793, 21004, 25, 3384, 69, 12, 23, 532, 26793, 198, 198, 11748, 302, 198, 11748, 2298, 293, 198, 6738, 256, 5235, 13, 7890, 1330, 17051, 198, 6738, 256, 5235, 13, 27110,...
1.949983
5,758
import os import setupmeta
[ 11748, 28686, 198, 198, 11748, 9058, 28961, 628 ]
3.625
8
# -*- coding: utf-8 -*- """ Created on Fri Feb 8 10:22:45 2019 @author: mangelon """ import numpy as np import pandas as pd from scipy.optimize import newton def price(yield_to_mat, redemption, rate, freq, maturity_dt, settlement_dt, dcc="30/360 US", eom=False): """ Returns the price given the yield to maturity maturity date, the face value at maturity, the interest rate paid with frequency freq """ # calculate the number of payments on the basis of 365 days years freq_lbl = str(int(12/freq)) + 'M' Ncoupons = int(np.floor((maturity_dt - settlement_dt) / np.timedelta64(365,'D') * freq) + 1) dt = pd.date_range(end=maturity_dt, periods=Ncoupons+1, freq=freq_lbl) dtws = dt.insert(1, pd.to_datetime(settlement_dt)) cf = coupon_factor(dt, dcc, eom) DSCcf = coupon_factor(dtws[1:3],dcc) Ecf = coupon_factor(dt[0:2],dcc) Acf = Ecf - DSCcf k = np.arange(1, Ncoupons+1) if np.isscalar(yield_to_mat): xx = 100 * rate*cf / (1 + yield_to_mat*cf)**(k-1 + DSCcf/Ecf) p = redemption / (1 + yield_to_mat/freq)**(Ncoupons-1 + DSCcf/Ecf) \ + np.sum(xx) - 100 * rate/freq * Acf/Ecf p = np.asscalar(p) else: p = np.empty_like(yield_to_mat) for ix in range(yield_to_mat.size): xx = 100 * rate*cf / (1 + yield_to_mat[ix]*cf)**(k-1 + DSCcf/Ecf) p[ix] = redemption / (1 + yield_to_mat[ix]/freq)**(Ncoupons-1 + DSCcf/Ecf) \ + np.sum(xx) - 100 * rate/freq * Acf/Ecf return p def ytm(p, redemption, rate, freq, maturity_dt, settlement_dt, ytm_guess=None, dcc="30/360 US", eom=False): """ Returns the yield to maturity. """ if ytm_guess is None: ytm_guess = rate if np.isscalar(p): yy = newton(func, ytm_guess) else: yy = np.empty_like(p) for ix in range(p.size): yy[ix] = newton(func, ytm_guess, args=(ix,)) return yy def dv01(x, redemption, rate, freq, maturity_dt, settlement_dt, dcc="30/360 US", eom=False, x_is_yield=True, step=0.5): """ Returns the numerically computed local DV01 for 1 bp move in the yield at the given price. Calculations done symmetrically at +/- bps step on the yield given or at +/- step of the price given. """ if x_is_yield is False: yy1 = ytm(x + step, redemption, rate, freq, maturity_dt, settlement_dt, dcc, eom) yy2 = ytm(x - step, redemption, rate, freq, maturity_dt, settlement_dt, dcc, eom) res = 2*step / (yy1 - yy2) / 10000 else: p1 = price(x + step/10000, redemption, rate, freq, maturity_dt, settlement_dt, dcc, eom) p2 = price(x - step/10000, redemption, rate, freq, maturity_dt, settlement_dt, dcc, eom) res = (p1 - p2) / 2 / step return res def coupon_factor(dt, dcc, eom=False): """ Returns the coupon factors of periods between dates according to the daycount convention. """ eom_date = dt.is_month_end Y = dt.year.values Y2 = Y[1:] Y1 = Y[:-1] M = dt.month.values M2 = M[1:] M1 = M[:-1] D = dt.day.values D2 = D[1:] D1 = D[:-1] if dcc == "30/360 US": # to be verified, not exactly accurate 100% D2[(eom & (M1==2 & eom_date[:-1])) & (M2==2 & eom_date[1:])] = 30 D1[eom & (M1==2 & eom_date[:-1])] = 30 D2[(D2==31) & ((D1==30) | (D1==31))] = 30 D1[D1==31] = 30 cf = (360*(Y2-Y1) + 30*(M2-M1) + (D2-D1)) / 360 else: raise NotImplementedError() return cf
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 19480, 3158, 220, 807, 838, 25, 1828, 25, 2231, 13130, 198, 198, 31, 9800, 25, 582, 25280, 261, 198, 37811, 198, 11748, 299, 32152, 355, 45941, ...
2.023516
1,786
from ctypes import Structure, c_double, c_int, c_ubyte from . import constants SCALE_INFO_ARRAY = c_gsfScaleInfo * constants.GSF_MAX_PING_ARRAY_SUBRECORDS
[ 6738, 269, 19199, 1330, 32522, 11, 269, 62, 23352, 11, 269, 62, 600, 11, 269, 62, 549, 88, 660, 198, 198, 6738, 764, 1330, 38491, 628, 198, 198, 6173, 21358, 62, 10778, 62, 1503, 30631, 796, 269, 62, 14542, 69, 29990, 12360, 1635, ...
2.580645
62
import numpy as np import matplotlib.pyplot as plt import CoolProp, scipy.optimize backend = 'HEOS' fluid = 'R125' kwargs = dict(lw = 2) print('Ideal') ICT = IdealCurveTracer(backend, fluid, p0 = 1e5, T0 = 900) T, p = ICT.trace() plt.plot(T, p, '-', label = 'Ideal Curve', **kwargs) print('Boyle') BCT = BoyleCurveTracer(backend, fluid, p0 = 1e5, T0 = 800) T, p = BCT.trace() plt.plot(T, p, '-', label = 'Boyle Curve', **kwargs) print('Joule Inversion') JIT = JouleInversionCurveTracer(backend, fluid, p0 = 1e5, T0 = 1800) T, p = JIT.trace() plt.plot(T, p, '-', label = 'Joule Inversion Curve', **kwargs) print('Joule-Thomson') JTCT = JouleThomsonCurveTracer(backend, fluid, p0 = 1e5, T0 = 1800) T, p = JTCT.trace() plt.plot(T, p, '-', label = 'Joule-Thomson Curve', **kwargs) print('Saturation Curve') Tt = ICT.AS.keyed_output(CoolProp.iT_triple) Tc = ICT.AS.keyed_output(CoolProp.iT_critical) Ts = np.linspace(Tt, Tc - 1.e-6) ps = CoolProp.CoolProp.PropsSI('P','T',Ts,'Q',0,backend + '::' + fluid) plt.plot(Ts, ps, '-', label = 'Saturation Curve', **kwargs) plt.yscale('log') plt.xscale('log') plt.xlabel('T (K)') plt.ylabel('p (Pa)') plt.legend(loc = 'best') plt.savefig('IdealCurves.png') plt.show()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 15226, 24331, 11, 629, 541, 88, 13, 40085, 1096, 628, 628, 628, 198, 198, 1891, 437, 796, 705, 13909, 2640, 6, 198, 35522, 312, ...
2.188849
556
# -*- coding: utf-8 -*- """ Practical Algorthns Problem set: 5.1 - Working with Data Structures 2d and 3a """ from timeit import default_timer as timer import sys N = 1_000_000 # 2d """ Create a list of a million elements, populated with the first million natural numbers. Using a for loop, (so no direct formulas or other exotic approaches like using a map*), calculate the sum of all the elements of the list. """ mylist = [] start = timer() for i in range(N): mylist.append(i+1) end = timer() print("Time taken to create list = ", end-start) sum = 0 start = timer() for i in range(N): sum += mylist[i] end = timer() print("Time taken to compute sum = ", end-start) print("sum = ", sum) print("size of list = ", sys.getsizeof(mylist), "\n\n") # 3a """ Repeat problem 2d, using arrays instead of lists """ import array as arr myarray = arr.array('i', [0] * N) start = timer() for i in range(N): myarray[i] = i+1 end = timer() print("Time taken to create array = ", end-start) sum = 0 start = timer() for i in range(N): sum += myarray[i] end = timer() print("Time taken to compute sum = ", end-start) print("sum = ", sum) print("size of array = ", sys.getsizeof(myarray))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 47, 36112, 978, 70, 1506, 5907, 198, 40781, 900, 25, 642, 13, 16, 532, 14594, 351, 6060, 32112, 942, 198, 198, 17, 67, 290, 513, 64, 198, 198, 37811, 198...
2.835681
426
from __future__ import print_function, division, absolute_import import time from robust_serial import write_order, Order, write_i8, write_i16, read_i8, read_order from robust_serial.utils import open_serial_port if __name__ == '__main__': try: serial_file = open_serial_port(baudrate=115200, timeout=None) except Exception as e: raise e is_connected = False # Initialize communication with Arduino while not is_connected: print("Waiting for arduino...") write_order(serial_file, Order.HELLO) bytes_array = bytearray(serial_file.read(1)) if not bytes_array: time.sleep(2) continue byte = bytes_array[0] if byte in [Order.HELLO.value, Order.ALREADY_CONNECTED.value]: is_connected = True print("Connected to Arduino") motor_speed = -56 # Equivalent to write_i8(serial_file, Order.MOTOR.value) write_order(serial_file, Order.MOTOR) write_i8(serial_file, motor_speed) write_order(serial_file, Order.SERVO) write_i16(serial_file, 120) for _ in range(10): order = read_order(serial_file) print("Ordered received: {:?}", order)
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 11, 7297, 11, 4112, 62, 11748, 198, 198, 11748, 640, 198, 198, 6738, 12373, 62, 46911, 1330, 3551, 62, 2875, 11, 8284, 11, 3551, 62, 72, 23, 11, 3551, 62, 72, 1433, 11, 1100, 62, 72, ...
2.427126
494
# Generated by Django 2.2.8 on 2020-01-16 18:52 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import pyuploadcare.dj.models
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 23, 319, 12131, 12, 486, 12, 1433, 1248, 25, 4309, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 142...
3.065574
61
#!/usr/bin/env python #coding=utf-8 import cv2 import numpy as np import matplotlib.pyplot as plt root = "/home/li/bag/0824/02" if __name__ == '__main__': x_data = [] y1_data = [] y2_data = [] offset_data = [] # read_csv() # show_image() imu_data = load_imu() imu_x_data = imu_data[:,0] imu_x_data = np.divide(imu_x_data,100) imu_x_data = np.floor(imu_x_data) #print(imu_x_data) imu_y_data = imu_data[:,3] # plt.plot(imu_x_data,imu_y_data) # plt.show() platform_data = load_platform() pt_x_data = platform_data[:,0] pt_x_data = np.divide(pt_x_data,100) pt_x_data = np.floor(pt_x_data) #print(pt_x_data) pt_y_data = platform_data[:,1] pt_y_data = np.subtract(pt_y_data,360) pt_y_data = np.abs(pt_y_data) # get join cit = np.nditer(imu_x_data, flags=["c_index"]) while not cit.finished: #print("value:", cit[0], "index:<{}>".format(cit.index)) print(cit.index," ",cit[0]) imu_idx = cit.index imu_val = cit[0] #print("imu_y_data:",imu_y_data[imu_idx]) pt_index_array = np.where(pt_x_data == imu_val) #print(type(pt_index_array)) if len(pt_index_array) > 0: pt_indexs = pt_index_array[0] if pt_indexs.size > 0: #print(type(pt_indexs)) #print(pt_indexs[0]) pt_val = pt_y_data[pt_indexs[0]] #print("pt_y_data:",pt_val) offset = abs(imu_y_data[imu_idx] - pt_val) print(imu_val,offset) x_data.append(imu_val) y1_data.append(imu_y_data[imu_idx]) y2_data.append(pt_val) offset_data.append(offset) cit.iternext() #plt # plt.plot(x_data,y1_data,'s-',color="r",label="imu") # plt.plot(x_data,y2_data,'o-',color="g",label="hk") plt.plot(x_data,y1_data,color="r",label="imu") plt.plot(x_data,y2_data,color="g",label="hk") plt.plot(x_data,offset_data,color="b",label="offset") plt.xlabel("timestamp") plt.ylabel("angle") plt.legend() plt.show() # for x in np.nditer(imu_x_data): # #print("imu:",x) # index_array = np.where(pt_x_data == x) # print(type(index_array)) # if len(index_array) > 0: # result = index_array[0] # if result.size > 0: # x_data.append(x) # print(type(result)) # print(result.shape) # print(result) # print(result[0])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 66, 7656, 28, 40477, 12, 23, 198, 11748, 269, 85, 17, 220, 220, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 15763, ...
1.766074
1,462
import os import sys import numpy as np if __name__ == '__main__': if len(sys.argv) < 2 or sys.argv[1] not in ('p1', 'p2'): print('you done did it wrong') exit() filename = os.path.join(sys.argv[0].split('/', 1)[0], 'input.txt') lines = get_input(filename) part = sys.argv[1:] if 'p1' in part: main_p1(lines) if 'p2' in part: main_p2(lines)
[ 11748, 28686, 198, 11748, 25064, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 611, 18896, 7, 17597, 13, 853, 85, 8, 1279, 362, 393, 25064, 13, 853, ...
2.046154
195
""" switchboard.helpers ~~~~~~~~~~~~~~~~ :copyright: (c) 2015 Kyle Adams. :license: Apache License 2.0, see LICENSE for more details. """ from webob import Request class MockRequest(Request): """ A mock request object which stores a user instance and the ip address. """
[ 37811, 198, 31943, 3526, 13, 16794, 364, 198, 27156, 198, 198, 25, 22163, 4766, 25, 357, 66, 8, 1853, 14316, 12620, 13, 198, 25, 43085, 25, 24843, 13789, 362, 13, 15, 11, 766, 38559, 24290, 329, 517, 3307, 13, 198, 37811, 198, 198, ...
3.258427
89
import os, sys import unittest, time import pdb from testconfig import this_trick, tests_dir from WorkflowCommon import * def suite(): """Create test suite from WorkflowCommonTestCase unit test class and return""" return unittest.TestLoader().loadTestsFromTestCase(WorkflowCommonTestCase)
[ 11748, 28686, 11, 25064, 198, 11748, 555, 715, 395, 11, 640, 198, 11748, 279, 9945, 198, 6738, 1332, 11250, 1330, 428, 62, 2213, 624, 11, 5254, 62, 15908, 198, 6738, 5521, 11125, 17227, 1330, 1635, 198, 198, 4299, 18389, 33529, 198, 2...
3.465116
86
#!/usr/bin/env python import logging import os import subprocess import sys from setuptools import setup from distutils.extension import Extension logging.basicConfig() log = logging.getLogger() # Parse the version from the fiona module. with open('rasterio/__init__.py') as f: for line in f: if line.find("__version__") >= 0: version = line.split("=")[1].strip() version = version.strip('"') version = version.strip("'") continue with open('VERSION.txt', 'w') as f: f.write(version) # Use Cython if available. try: from Cython.Build import cythonize except ImportError: cythonize = None # By default we'll try to get options via gdal-config. On systems without, # options will need to be set in setup.cfg or on the setup command line. include_dirs = [] library_dirs = [] libraries = [] extra_link_args = [] try: import numpy include_dirs.append(numpy.get_include()) except ImportError: log.critical("Numpy and its headers are required to run setup(). Exiting.") sys.exit(1) try: gdal_config = "gdal-config" with open("gdal-config.txt", "w") as gcfg: subprocess.call([gdal_config, "--cflags"], stdout=gcfg) subprocess.call([gdal_config, "--libs"], stdout=gcfg) with open("gdal-config.txt", "r") as gcfg: cflags = gcfg.readline().strip() libs = gcfg.readline().strip() for item in cflags.split(): if item.startswith("-I"): include_dirs.extend(item[2:].split(":")) for item in libs.split(): if item.startswith("-L"): library_dirs.extend(item[2:].split(":")) elif item.startswith("-l"): libraries.append(item[2:]) else: # e.g. -framework GDAL extra_link_args.append(item) except Exception as e: log.warning("Failed to get options via gdal-config: %s", str(e)) ext_options = dict( include_dirs=include_dirs, library_dirs=library_dirs, libraries=libraries, extra_link_args=extra_link_args) # When building from a repo, Cython is required. if os.path.exists("MANIFEST.in") and "clean" not in sys.argv: log.info("MANIFEST.in found, presume a repo, cythonizing...") if not cythonize: log.critical( "Cython.Build.cythonize not found. " "Cython is required to build from a repo.") sys.exit(1) ext_modules = cythonize([ Extension( 'rasterio._base', ['rasterio/_base.pyx'], **ext_options), Extension( 'rasterio._io', ['rasterio/_io.pyx'], **ext_options), Extension( 'rasterio._copy', ['rasterio/_copy.pyx'], **ext_options), Extension( 'rasterio._features', ['rasterio/_features.pyx'], **ext_options), Extension( 'rasterio._drivers', ['rasterio/_drivers.pyx'], **ext_options), Extension( 'rasterio._warp', ['rasterio/_warp.pyx'], **ext_options), Extension( 'rasterio._err', ['rasterio/_err.pyx'], **ext_options), Extension( 'rasterio._example', ['rasterio/_example.pyx'], **ext_options), ]) # If there's no manifest template, as in an sdist, we just specify .c files. else: ext_modules = [ Extension( 'rasterio._base', ['rasterio/_base.c'], **ext_options), Extension( 'rasterio._io', ['rasterio/_io.c'], **ext_options), Extension( 'rasterio._copy', ['rasterio/_copy.c'], **ext_options), Extension( 'rasterio._features', ['rasterio/_features.c'], **ext_options), Extension( 'rasterio._drivers', ['rasterio/_drivers.c'], **ext_options), Extension( 'rasterio._warp', ['rasterio/_warp.cpp'], **ext_options), Extension( 'rasterio._err', ['rasterio/_err.c'], **ext_options), Extension( 'rasterio._example', ['rasterio/_example.c'], **ext_options), ] with open('README.rst') as f: readme = f.read() # Runtime requirements. inst_reqs = [ 'affine>=1.0', 'click', 'Numpy>=1.7', 'setuptools' ] if sys.version_info < (3, 4): inst_reqs.append('enum34') setup(name='rasterio', version=version, description=( "Fast and direct raster I/O for Python programmers who use Numpy"), long_description=readme, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Programming Language :: C', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Multimedia :: Graphics :: Graphics Conversion', 'Topic :: Scientific/Engineering :: GIS' ], keywords='raster gdal', author='Sean Gillies', author_email='sean@mapbox.com', url='https://github.com/mapbox/rasterio', license='BSD', package_dir={'': '.'}, packages=['rasterio', 'rasterio.rio'], entry_points=''' [console_scripts] rio=rasterio.rio.main:cli ''', include_package_data=True, ext_modules=ext_modules, zip_safe=False, install_requires=inst_reqs )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 850, 14681, 198, 11748, 25064, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 6738, 1233, 26791, 13, 2302, 3004, 1330, 27995, 198, 198, ...
2.240212
2,452
"""UUID utilities.""" from __future__ import annotations from typing import Callable from uuid import UUID, uuid4 def uuid(_uuid: Callable[[], UUID] = uuid4) -> str: """Generate unique id in UUID4 format. See Also: For now this is provided by :func:`uuid.uuid4`. """ return str(_uuid())
[ 37811, 52, 27586, 20081, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 19720, 1330, 4889, 540, 198, 6738, 334, 27112, 1330, 471, 27586, 11, 334, 27112, 19, 628, 198, 4299, 334, 27112, 28264, 12303, 312, 25, 4889...
2.669492
118
# -*- coding: utf8 -*- """ This is part of shot detector. Produced by w495 at 2017.05.04 04:18:27 """ from __future__ import absolute_import, division, print_function import logging from .base_stat_swfilter import BaseSWFilter class DebugSWFilter(BaseSWFilter): """ ... """ __logger = logging.getLogger(__name__) def aggregate_windows(self, window_seq, if_index=None, true_factor=1, true_summand=0, false_factor=1, false_summand=0, **kwargs): """ :param window_seq: :param if_index: :param true_factor: :param true_summand: :param false_factor: :param false_summand: :param kwargs: :return: """ for window in window_seq: for win_index, win_item in enumerate(window): if if_index == win_index: yield true_factor * win_item + true_summand else: yield false_factor * win_item + false_summand
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 23, 532, 9, 12, 198, 37811, 198, 220, 220, 220, 770, 318, 636, 286, 2823, 31029, 13, 198, 220, 220, 220, 21522, 771, 416, 266, 33781, 379, 2177, 13, 2713, 13, 3023, 8702, 25, 1507, 25, 1983, ...
1.803008
665
# -*- coding: utf-8 -*- """ Created on Thu Feb 16 23:11:56 2017 @author: Flamingo """ import pandas as pd import numpy as np import datetime import copy import sys sys.path.append('../TOOLS') from IJCAI2017_TOOL import * #%% readin shop data HOLI = pd.read_csv('../additional/HOLI.csv') HOLI = HOLI.set_index(['DATE'],drop = True) HOLI_TAB = HOLI.transpose() HOLI_TAB.columns = [str((datetime.datetime.strptime('20150626','%Y%m%d') + datetime.timedelta(days=x)).date()) for x in range( HOLI_TAB.shape[1])] #%% readin shop data PAYNW = pd.read_csv('../data/user_pay_new.csv') VIENW = pd.read_csv('../data/user_view_new.csv') PAYNW_SHOP_DATE = PAYNW.groupby(['SHOP_ID','DATE'],as_index = False).sum() PAYNW_SHOP_DATE = PAYNW_SHOP_DATE[['SHOP_ID','DATE','Num_post']] #PAYNW_TAB_FIX = pd.read_csv('FillOctober.csv') #PAYNW_TAB_FIX['DATE'] = [ (lambda x:str(datetime.datetime.strptime('2015/06/26','%Y/%m/%d').date() ) ) (x) for x in PAYNW_TAB_FIX['DATE']] # #PAYNW_SHOP_DATE = pd.concat([PAYNW_SHOP_DATE ,PAYNW_TAB_FIX],axis = 0) # # #PAYNW_SHOP_DATE = PAYNW_SHOP_DATE.drop_duplicates(subset = ['SHOP_ID','DATE'], keep = 'last') #PAYNW_SHOP_DATE = PAYNW_SHOP_DATE.sort_values(by = ['SHOP_ID','DATE']) PAYNW_SHOP_DATE.reset_index(level=0) PAYNW_TAB = pd.pivot_table(PAYNW_SHOP_DATE, values=['Num_post'], index=['SHOP_ID'],columns=['DATE'], aggfunc=np.sum) #PAYNW_TAB = pd.pivot_table(PAYNW, values=['Num_post'], index=['SHOP_ID'],columns=['DATE'], aggfunc=np.sum) PAYNW_TAB = pd.concat( [PAYNW_TAB[PAYNW_TAB.columns[0:169:1]], pd.DataFrame({'A':[np.nan],},index=np.arange(1,2001)),PAYNW_TAB[PAYNW_TAB.columns[169::1]] ], axis = 1) PAYNW_TAB.columns = [str((datetime.datetime.strptime('20150626','%Y%m%d') + datetime.timedelta(days=x)).date()) for x in range( PAYNW_TAB.shape[1])] PAYNW_TAB['2015-12-12'] = PAYNW_TAB['2015-12-13'] PAYNW_TAB_T = PAYNW_TAB.transpose() #%% shop_related_features SHOP_INFO = pd.read_csv("../external/SHOP_FEATURES_0221.csv",low_memory=False) SHOP_SC = ['SC00'] SHOP_SD = map(lambda x:'SD'+ str(x).zfill(2), np.arange(5)) SHOP_SE = map(lambda x:'SE'+ str(x).zfill(2), np.arange(1)) SHOP_SF = map(lambda x:'SF'+ str(x).zfill(2), np.arange(1)) SHOP_SG = map(lambda x:'SG'+ str(x).zfill(2), np.arange(4)) SHOP_SH = map(lambda x:'SH'+ str(x).zfill(2), np.arange(2)) SHOP_SI = [(lambda x:('SI'+ str(x).zfill(2))) (x) for x in range(10)] SHOP_SJ = map(lambda x:'SJ'+ str(x).zfill(2), np.arange(15)) SHOP_columns = SHOP_SC + SHOP_SD + SHOP_SE + SHOP_SF + SHOP_SG + SHOP_SH + SHOP_SI + SHOP_SJ #%% TRN_N = 21 TST_N = 14 TST_PAD_N = 14 + 4 end_date = datetime.datetime.strptime('2016-10-31','%Y-%m-%d') day_N = 494 date_list = [str((end_date- datetime.timedelta(days=x)).date()) for x in range(day_N)] date_list.reverse() #%% TRAIN = pd.DataFrame() train_date_zip = zip(date_list[0:day_N-(TRN_N+TST_N)+1],date_list[TRN_N-1:day_N-TST_N+1],date_list[TRN_N:day_N-TST_N+2], date_list[TRN_N+TST_N-1:day_N]) train_date_zip_df = pd.DataFrame(train_date_zip) train_date_zip_df.columns = ['TRN_STA','TRN_END','TST_STA','TST_END'] for TRN_STA,TRN_END,TST_STA,TST_END in train_date_zip: TRAIN_temp = PAYNW_TAB.loc[:,TRN_STA:TST_END] TRAIN_temp.columns = np.arange(TRAIN_temp.shape[1]) TRAIN_temp.reset_index(level=0, inplace=True) TRAIN_temp.loc[:,'TRN_STA'] = str(TRN_STA) TRAIN_temp.loc[:,'TRN_END'] = str(TRN_END) TRAIN_temp.loc[:,'TST_STA'] = str(TST_STA) TRAIN_temp.loc[:,'TST_END'] = str(TST_END) TRAIN = pd.concat( [TRAIN,TRAIN_temp],) #%% TRAIN = TRAIN.reset_index(np.arange(len(TRAIN)),drop = True) TRAIN_TRN_C = map(lambda x:'SA'+ str(x).zfill(2), np.arange(TRN_N)) TRAIN_TST_C = map(lambda x:'SB'+ str(x).zfill(2), np.arange(TST_N)) TRAIN.columns = ['SHOP_ID'] + TRAIN_TRN_C + TRAIN_TST_C + ['TRN_STA','TRN_END','TST_STA','TST_END'] #%% #TEST= pd.DataFrame() #TRN_END = datetime.datetime.strptime('2016-10-31','%Y-%m-%d') #TRN_STA = (TRN_END - datetime.timedelta(days=(TRN_N-1)) ) #TST_STA = (TRN_END + datetime.timedelta(days=(1)) ) #TST_END = (TRN_END + datetime.timedelta(days=(TST_N)) ) #test_date_zip = zip([str(TRN_STA.date())],[str(TRN_END.date())],[str(TST_STA.date())], [str(TST_END.date()) ]) #TEST = PAYNW_TAB.loc[:,str(TRN_STA.date()):str(TRN_END.date())] #TEST.reset_index(level=0, inplace=True) #end_date = datetime.datetime.strptime('2016-10-31','%Y-%m-%d') #TEST.loc[:,'TRN_STA'] = str(TRN_STA.date()) #TEST.loc[:,'TRN_END'] = str(TRN_END.date()) #TEST.loc[:,'TST_STA'] = str(TST_STA.date()) #TEST.loc[:,'TST_END'] = str(TST_END.date()) #TEST_TRN_C = map(lambda x:'SA'+ str(x).zfill(2), np.arange(TRN_N)) #TEST.columns = ['SHOP_ID'] + TEST_TRN_C + ['TRN_STA','TRN_END','TST_STA','TST_END'] TEST = pd.read_csv('../dataclean/TEST_cor_0313.csv') #%% result_fix = pd.read_csv('../generateXY_table/sub_011_last6weeks_removenan_m105.csv',header=None,names =['SHOP_ID'] + range(14)) result_fmed = pd.DataFrame() result_fmed['SHOP_ID'] = result_fix['SHOP_ID'] result_fmed['VALUE'] = result_fix.loc[:,np.arange(0,14)].median(axis = 1) result_fmed.to_csv('0215_fix.csv',index = False) TRAIN_OK = TRAIN[TRAIN.loc[:,TRAIN_TST_C].isnull().sum(axis = 1)==0] TRAIN_OK = TRAIN_OK[TRAIN_OK.loc[:,TRAIN_TRN_C].isnull().sum(axis = 1)<=(TRN_N-21)] TRAIN_OK = pd.merge(TRAIN_OK ,result_fmed,on='SHOP_ID',how = 'left') TEST = pd.merge(TEST ,result_fmed,on='SHOP_ID',how = 'left') TRAIN_OK = pd.merge(TRAIN_OK ,SHOP_INFO,on='SHOP_ID',how = 'left') TEST = pd.merge(TEST ,SHOP_INFO,on='SHOP_ID',how = 'left') TRAIN_OK['DT'] = pd.to_datetime(TRAIN_OK['TRN_STA']) - pd.to_datetime(TRAIN_OK['SH00']) TRAIN_OK.loc[:,'DT'] = [(lambda x:(x.days)) (x) for x in TRAIN_OK.loc[:,'DT']] TRAIN_OK = TRAIN_OK[TRAIN_OK['DT'] >7] #%% TRAIN_OK[TRAIN_TRN_C + TRAIN_TST_C] = np.log(TRAIN_OK[TRAIN_TRN_C + TRAIN_TST_C]).div(np.log(TRAIN_OK['VALUE']),axis=0 ) TEST[TEST_TRN_C] = np.log(TEST[TEST_TRN_C]).div( np.log( TEST['VALUE']),axis=0) #%% HOLI_TRN_CA = [(lambda x:('NC'+ str(x).zfill(2))) (x) for x in range(TRN_N)] HOLI_TST_CA = [(lambda x:('ND'+ str(x).zfill(2))) (x) for x in range(-2,TST_PAD_N-2)] HOLI_TRN = pd.DataFrame() date_all = copy.deepcopy(train_date_zip) date_all.append(test_date_zip[0]) date_all_df = pd.DataFrame(date_all) date_all_df.columns = ['TRN_STA','TRN_END','TST_STA','TST_END'] for TRN_STA,TRN_END,TST_STA,TST_END in date_all: tt1 = HOLI_TAB.loc[:,TRN_STA:TRN_END] tt1.columns = HOLI_TRN_CA tst_sta = str((datetime.datetime.strptime(TST_STA,'%Y-%m-%d') + datetime.timedelta(-2)).date()) tst_end = str((datetime.datetime.strptime(TST_END,'%Y-%m-%d') + datetime.timedelta(2)).date()) tt2 = HOLI_TAB.loc[:,tst_sta :tst_end ] tt2.columns = HOLI_TST_CA tt3 = pd.concat([tt1,tt2],axis=1) HOLI_TRN = pd.concat([HOLI_TRN,tt3]) HOLI_TRN = HOLI_TRN.reset_index(np.arange(len(HOLI_TRN)),drop = True) HOLI_TRN = HOLI_TRN.join(date_all_df) #%% TRAIN_OK = pd.merge(TRAIN_OK ,HOLI_TRN,on=['TRN_STA','TRN_END','TST_STA','TST_END'],how = 'left') TEST = pd.merge(TEST ,HOLI_TRN,on=['TRN_STA','TRN_END','TST_STA','TST_END'],how = 'left') #%% HOLI_RATIO = [(lambda x:('NE'+ str(x).zfill(2))) (x) for x in range(1)] TRAIN_OK = Add_work_ratio(TRAIN_OK,HOLI_TRN_CA,HOLI_RATIO) TEST = Add_work_ratio(TEST,HOLI_TRN_CA,HOLI_RATIO) #%% PRECIP = pd.read_csv('../external/PRECIP.csv') PRECIP_TAB = pd.pivot_table(PRECIP, values=['Precip'], index=['CITY_EN'],columns=['DATE']) PRECIP_TAB.columns = [str((datetime.datetime.strptime('20150501','%Y%m%d') + datetime.timedelta(days=x)).date()) for x in range( PRECIP_TAB.shape[1])] PRECIP_TRN_C = [(lambda x:('RA'+ str(x).zfill(2))) (x) for x in range(TRN_N)] PRECIP_TST_C = [(lambda x:('RB'+ str(x).zfill(2))) (x) for x in range(TST_N)] PRECIP_TRN = pd.DataFrame() for TRN_STA,TRN_END,TST_STA,TST_END in date_all: tt1 = PRECIP_TAB.loc[:,TRN_STA:TRN_END ] tt2 = PRECIP_TAB.loc[:,TST_STA:TST_END ] tt3 = pd.concat([tt1,tt2],axis=1) tt3.reset_index(level=0, inplace=True) tt3.columns = ['CITY_EN'] + PRECIP_TRN_C + PRECIP_TST_C tt3.loc[:,'TRN_STA'] = TRN_STA tt3.loc[:,'TRN_END'] = TRN_END tt3.loc[:,'TST_STA'] = TST_STA tt3.loc[:,'TST_END'] = TST_END PRECIP_TRN = pd.concat([PRECIP_TRN,tt3],axis = 0) PRECIP_TRN = PRECIP_TRN.reset_index(np.arange(len(PRECIP_TRN)),drop = True) TRAIN_OK = pd.merge(TRAIN_OK ,PRECIP_TRN,on=['CITY_EN','TRN_STA','TRN_END','TST_STA','TST_END'],how = 'left') TEST = pd.merge(TEST ,PRECIP_TRN,on=['CITY_EN','TRN_STA','TRN_END','TST_STA','TST_END'],how = 'left') #%% WEATHER = pd.read_csv('../external/WEATHER_extract.csv') WEATHER_TAB = pd.pivot_table(WEATHER, values=['RC','RE','RG','RI'], index=['CITY_EN'],columns=['DATE']) WEATHER_TAB.columns = Const_Datestr3('RC_', '2015-06-26','2016-11-20') + Const_Datestr3('RE_', '2015-06-26','2016-11-20') \ +Const_Datestr3('RG_', '2015-06-26','2016-11-20')+Const_Datestr3('RI_', '2015-06-26','2016-11-20') WEARC_TRN_C = [(lambda x:('RC'+ str(x).zfill(2))) (x) for x in range(TRN_N)] WEARE_TRN_C = [(lambda x:('RE'+ str(x).zfill(2))) (x) for x in range(TRN_N)] WEARG_TRN_C = [(lambda x:('RG'+ str(x).zfill(2))) (x) for x in range(TRN_N)] WEARI_TRN_C = [(lambda x:('RI'+ str(x).zfill(2))) (x) for x in range(TRN_N)] WEARD_TST_C = [(lambda x:('RD'+ str(x).zfill(2))) (x) for x in range(TST_N)] WEARF_TST_C = [(lambda x:('RF'+ str(x).zfill(2))) (x) for x in range(TST_N)] WEARH_TST_C = [(lambda x:('RH'+ str(x).zfill(2))) (x) for x in range(TST_N)] WEARJ_TST_C = [(lambda x:('RJ'+ str(x).zfill(2))) (x) for x in range(TST_N)] weather_output_columns = (WEARC_TRN_C + WEARE_TRN_C + WEARG_TRN_C + WEARI_TRN_C \ + WEARD_TST_C + WEARF_TST_C + WEARH_TST_C + WEARJ_TST_C ) WEATHER_ALL = pd.DataFrame() for TRN_STA,TRN_END,TST_STA,TST_END in date_all: weather_input_columns = (Const_Datestr3('RC_', TRN_STA,TRN_END) + Const_Datestr3('RE_', TRN_STA,TRN_END) \ + Const_Datestr3('RG_', TRN_STA,TRN_END) + Const_Datestr3('RI_', TRN_STA,TRN_END) \ + Const_Datestr3('RC_', TST_STA,TST_END) + Const_Datestr3('RE_', TST_STA,TST_END) \ + Const_Datestr3('RG_', TST_STA,TST_END)+Const_Datestr3('RI_', TST_STA,TST_END) ) tt = WEATHER_TAB[ weather_input_columns] tt.columns = weather_output_columns tt.reset_index(level=0, inplace=True) tt.loc[:,'TRN_STA'] = TRN_STA tt.loc[:,'TRN_END'] = TRN_END tt.loc[:,'TST_STA'] = TST_STA tt.loc[:,'TST_END'] = TST_END WEATHER_ALL = pd.concat([WEATHER_ALL,tt],axis = 0) TRAIN_OK = pd.merge(TRAIN_OK ,WEATHER_ALL,on=['CITY_EN','TRN_STA','TRN_END','TST_STA','TST_END'],how = 'left') TEST = pd.merge(TEST ,WEATHER_ALL,on=['CITY_EN','TRN_STA','TRN_END','TST_STA','TST_END'],how = 'left') #%% readin movie index #MOVIE_A = [(lambda x:('NAA'+ str(x).zfill(2))) (x) for x in range(TST_N)] #MOVIE_B = [(lambda x:('NAB'+ str(x).zfill(2))) (x) for x in range(TST_N)] #MOVIE_C = [(lambda x:('NAC'+ str(x).zfill(2))) (x) for x in range(TST_N)] #MOVIE_D = [(lambda x:('NAD'+ str(x).zfill(2))) (x) for x in range(TST_N)] #MOVIE_E = [(lambda x:('NAE'+ str(x).zfill(2))) (x) for x in range(TST_N)] # #MOVIE_columns = MOVIE_A + MOVIE_B + MOVIE_C + MOVIE_D + MOVIE_E # #MOV_IND = pd.read_csv('../external/MOV_INDEX.csv') #MOV_IND = MOV_IND[['DATE','Num','RAT_d3','RAT_w1','RAT_w3','RAT_w5']] #MOV_IND.set_index(keys = ['DATE'],drop = True,inplace = True) #MOV_TAB = MOV_IND.transpose() # # #MOV_TST = pd.DataFrame() #for TRN_STA,TRN_END,TST_STA,TST_END in date_all: # tt = MOV_TAB.loc[:,TST_STA:TST_END] # tt3 = tt.stack().to_frame().T # tt3.columns = MOVIE_columns # tt3.loc[:,'TST_STA'] = TST_STA # tt3.loc[:,'TST_END'] = TST_END # MOV_TST = pd.concat([MOV_TST,tt3]) #TRAIN_OK = pd.merge(TRAIN_OK , MOV_TST,on=['TST_STA','TST_END'],how = 'left') #TEST = pd.merge(TEST , MOV_TST,on=['TST_STA','TST_END'],how = 'left') #%% readin regional data # ALL_FEATURE_LIST = (TRAIN_TRN_C + SHOP_columns + HOLI_TRN_CA + HOLI_TST_CA + HOLI_RATIO + PRECIP_TRN_C +PRECIP_TST_C + weather_output_columns ) X = TRAIN_OK[ALL_FEATURE_LIST] Y = TRAIN_OK[TRAIN_TST_C] X_test = TEST[ALL_FEATURE_LIST] #Xout1 = X[Y[Y<0.25].sum(axis = 1) < 1] #Yout1 = Y[Y[Y<0.25].sum(axis = 1) < 1] # #Xout2 = Xout1[Yout1[Yout1>1.6].sum(axis = 1) < 1] #Yout2 = Yout1[Yout1[Yout1>1.6].sum(axis = 1) < 1] #Xout2.to_csv('../XY/0226_X_clean.csv', index = False) #Yout2.to_csv('../XY/0226_Y_clean.csv', index = False) #X_test.to_csv('../XY/0226_Xtest_clean.csv', index = False) X.to_csv('../XY/0313_X.csv', index = False) Y.to_csv('../XY/0313_Y.csv', index = False) X_test.to_csv('../XY/0313_Xtest.csv', index = False)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 26223, 3158, 1467, 2242, 25, 1157, 25, 3980, 2177, 198, 198, 31, 9800, 25, 1610, 3723, 78, 198, 37811, 628, 198, 11748, 19798, 292, 355, 279, 6...
1.902205
6,667
import unittest from pony.orm import * from pony.orm.tests.testutils import * from pony.orm.tests import setup_database, teardown_database db = Database() if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 6738, 26902, 13, 579, 1330, 1635, 198, 6738, 26902, 13, 579, 13, 41989, 13, 9288, 26791, 1330, 1635, 198, 6738, 26902, 13, 579, 13, 41989, 1330, 9058, 62, 48806, 11, 573, 446, 593, 62, 48806, 198, 198...
2.915493
71
""" An IPython FileContentsManager that uses Postgres for checkpoints. """ from __future__ import unicode_literals from .api_utils import ( _decode_unknown_from_base64, outside_root_to_404, reads_base64, to_b64, writes_base64, ) from .managerbase import PostgresManagerMixin from .query import ( delete_remote_checkpoints, delete_single_remote_checkpoint, get_remote_checkpoint, list_remote_checkpoints, move_remote_checkpoints, purge_remote_checkpoints, save_remote_checkpoint, ) from .utils.ipycompat import Checkpoints, GenericCheckpointsMixin class PostgresCheckpoints(PostgresManagerMixin, GenericCheckpointsMixin, Checkpoints): """ A Checkpoints implementation that saves checkpoints to a remote database. """ @outside_root_to_404 def create_notebook_checkpoint(self, nb, path): """Create a checkpoint of the current state of a notebook Returns a checkpoint_id for the new checkpoint. """ b64_content = writes_base64(nb) with self.engine.begin() as db: return save_remote_checkpoint( db, self.user_id, path, b64_content, self.crypto.encrypt, self.max_file_size_bytes, ) @outside_root_to_404 def create_file_checkpoint(self, content, format, path): """Create a checkpoint of the current state of a file Returns a checkpoint_id for the new checkpoint. """ try: b64_content = to_b64(content, format) except ValueError as e: self.do_400(str(e)) with self.engine.begin() as db: return save_remote_checkpoint( db, self.user_id, path, b64_content, self.crypto.encrypt, self.max_file_size_bytes, ) @outside_root_to_404 def delete_checkpoint(self, checkpoint_id, path): """delete a checkpoint for a file""" with self.engine.begin() as db: return delete_single_remote_checkpoint( db, self.user_id, path, checkpoint_id, ) def get_checkpoint_content(self, checkpoint_id, path): """Get the content of a checkpoint.""" with self.engine.begin() as db: return get_remote_checkpoint( db, self.user_id, path, checkpoint_id, self.crypto.decrypt, )['content'] @outside_root_to_404 @outside_root_to_404 @outside_root_to_404 def list_checkpoints(self, path): """Return a list of checkpoints for a given file""" with self.engine.begin() as db: return list_remote_checkpoints(db, self.user_id, path) @outside_root_to_404 def rename_all_checkpoints(self, old_path, new_path): """Rename all checkpoints for old_path to new_path.""" with self.engine.begin() as db: return move_remote_checkpoints( db, self.user_id, old_path, new_path, ) @outside_root_to_404 def delete_all_checkpoints(self, path): """Delete all checkpoints for the given path.""" with self.engine.begin() as db: delete_remote_checkpoints(db, self.user_id, path) def purge_db(self): """ Purge all database records for the current user. """ with self.engine.begin() as db: purge_remote_checkpoints(db, self.user_id)
[ 37811, 198, 2025, 6101, 7535, 9220, 15842, 13511, 326, 3544, 2947, 34239, 329, 36628, 13, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 764, 15042, 62, 26791, 1330, 357, 198, 220, 220, 220,...
2.127672
1,731
__all__ = ['BinaryCmdEncoder'] import struct from tron import Misc from .CommandEncoder import CommandEncoder
[ 834, 439, 834, 796, 37250, 33, 3219, 40109, 27195, 12342, 20520, 198, 198, 11748, 2878, 198, 198, 6738, 491, 261, 1330, 29882, 198, 198, 6738, 764, 21575, 27195, 12342, 1330, 9455, 27195, 12342, 628 ]
3.352941
34
#!/bin/env python
[ 2, 48443, 8800, 14, 24330, 21015, 198 ]
2.571429
7
from datetime import datetime from peewee import AutoField from peewee import DateTimeField from peewee import ForeignKeyField from peewee import TextField from peewee import IntegerField from bot.models.base import Base from bot.models.user import User
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 613, 413, 1453, 1330, 11160, 15878, 198, 6738, 613, 413, 1453, 1330, 7536, 7575, 15878, 198, 6738, 613, 413, 1453, 1330, 8708, 9218, 15878, 198, 6738, 613, 413, 1453, 1330, 8255, 15878...
3.724638
69
import pyeapi from pprint import pprint import argparse if __name__ == '__main__': main()
[ 11748, 279, 5948, 15042, 198, 6738, 279, 4798, 1330, 279, 4798, 198, 11748, 1822, 29572, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ]
2.823529
34
@iso_register("US-SC") class SouthCarolina(UnitedStates): """South Carolina""" FIXED_HOLIDAYS = UnitedStates.FIXED_HOLIDAYS + ((5, 10, "Confederate Memorial Day"),) include_thanksgiving_friday = True include_christmas_eve = True include_boxing_day = True include_columbus_day = False
[ 31, 26786, 62, 30238, 7203, 2937, 12, 6173, 4943, 198, 4871, 2520, 9914, 47196, 7, 17013, 42237, 2599, 198, 197, 37811, 14942, 5913, 37811, 198, 197, 47084, 1961, 62, 39, 3535, 2389, 4792, 50, 796, 1578, 42237, 13, 47084, 1961, 62, 39...
2.861386
101
import unittest import requests as req from app.config.config import HOST from app.api.base.base_name import * if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 11748, 7007, 355, 43089, 198, 6738, 598, 13, 11250, 13, 11250, 1330, 367, 10892, 198, 6738, 598, 13, 15042, 13, 8692, 13, 8692, 62, 3672, 1330, 1635, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, ...
2.890909
55
import pickle import argparse import json from copy import deepcopy import numpy as np import grr.GIF_network as gfn from grr.Tools import check_dict_fields #%% PARSE COMMANDLINE ARGUMENTS parser = argparse.ArgumentParser() parser.add_argument( '--mods', type=str, required=True, help='Pickled neuron models.' ) parser.add_argument( '--prefix', type=str, required=True, help='Path to save GIF_network models.', ) parser.add_argument( '--opts', type=str, required=True, help='Path to opts JSON file.' ) parser.add_argument( '-r', '--replicates', default=1, type=int, help='No. of randomized models to generate.', ) parser.add_argument( '--seed', type=int, default=42, help='Random seed (default 42).' ) parser.add_argument( '-v', '--verbose', action='store_true', help='Print information about progress.', ) args = parser.parse_args() # Parse JSON opts file. with open(args.opts, 'r') as f: opts = json.load(f) f.close() # Ensure JSON object contains required fields. required_fields = { 'dt': None, 'no_principal_neurons': None, 'output_model_suffixes': {'base': None, 'noIA': None, 'fixedIA': None}, } check_dict_fields(opts, required_fields) #%% LOAD GIF MODELS if args.verbose: print('Loading mPFC models from {}'.format(args.mods)) with open(args.mods, 'rb') as f: principal_cell_gifs = pickle.load(f) f.close() # SET RANDOM SEED np.random.seed(args.seed) # GENERATE MODELS def save_model(model, type, number): """Save GIFnet model to a pickle file. `model` is saved to `<prefix>_<number>_<typesuffix>` according to args and opts. Arguments --------- model : GIFnet Model to save. type : str in {`base`, `noIA`, `fixedIA`} Type of model being saved. Used to get correct filename suffix. number : int Number of model being saved. Used as filename infix. """ fname = '_'.join( [args.prefix, str(number), opts['output_model_suffixes'][type]] ) if args.verbose: print('Saving {} GIFnet model to {}'.format(type, fname)) with open(fname, 'wb') as f: pickle.dump(model, f) f.close() for i in range(args.replicates): if args.verbose: print( 'Assembling GIFnet model set {} of {}.'.format( i + 1, args.replicates ) ) subsample_gifnet = gfn.GIFnet( name='Subsample GIFs', ser_mod=np.random.choice( deepcopy(principal_cell_gifs), opts['no_principal_neurons'] ), gaba_mod=None, propagation_delay=None, gaba_kernel=None, gaba_reversal=None, connectivity_matrix=[], dt=opts['dt'], ) # Clear cached interpolated filters to save disk space. subsample_gifnet.clear_interpolated_filters() # Save base model to disk. save_model(subsample_gifnet, 'base', i) if args.verbose: print('Finished! Exiting.')
[ 11748, 2298, 293, 198, 11748, 1822, 29572, 198, 11748, 33918, 198, 6738, 4866, 1330, 2769, 30073, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 1036, 81, 13, 38, 5064, 62, 27349, 355, 308, 22184, 198, 6738, 1036, 81, 13, 3...
2.36996
1,265
""" Script to upload secrets to AWS SSM Parameter Store and tag them appropriately This script will read your secret value from the clipboard automagically """ import click import pyperclip from colorama import init, Fore from upside.enforcer.upload.util import upload_secret, secret_key_pattern from upside.enforcer.util.auth import session from upside.enforcer.util.secret import Secret init(autoreset=True) @click.command() @click.option('--profile', default=None, help='aws profile') @click.option('--region', default=None, help='aws region name') @click.option( '--fq_secret_key', prompt='Fully Qualified Secret Key [/secret_directory/secret_name]', callback=secret_key_pattern_check, help='Fully qualified secret e.g /secret_directory/secret_name') @click.option('--secret_value', prompt='Copy your secret value to the clipboard then press enter', default='', show_default=False, hide_input=False) @click.option('-k', '--kms_key_id', default=None, help='alias of the AWS KMS Parameter Store Key used to encrypt secrets') @click.option('-f', '--force', flag_value=True, help='skip confirmation prompt')
[ 37811, 198, 7391, 284, 9516, 13141, 284, 30865, 6723, 44, 25139, 2357, 9363, 290, 7621, 606, 20431, 198, 1212, 4226, 481, 1100, 534, 3200, 1988, 422, 262, 47999, 3557, 39066, 198, 37811, 198, 198, 11748, 3904, 198, 11748, 12972, 525, 15...
3.424242
330
from django.conf.urls import url from core.views import MediaUploadView, MediaHierarchyView urlpatterns = [ url(r'^$', MediaUploadView.as_view(), name='media_upload'), url(r'^files/$', MediaHierarchyView.as_view(), name='media_view'), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 6738, 4755, 13, 33571, 1330, 6343, 41592, 7680, 11, 6343, 39, 959, 9282, 7680, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 19016, 7, 81, 6, 61, 3, 3256, 6...
2.806818
88
import random from app.generator.utils import * from PIL import Image, ImageColor, ImageFont, ImageDraw, ImageFilter from app.utils import image_utils # 旋转函数 def random_rotate(img): ''' ______________ | / /| | / / | |/________/__| 旋转可能有两种情况,一种是矩形,一种是平行四边形, 但是传入的points,就是4个顶点, ''' w, h = img.size center = (w // 2, h // 2) degree = random.uniform(-30, 30) # 随机旋转0-8度 print("旋转度数:%f" % degree) return img.rotate(degree, center=center, expand=1) # 因为英文、数字、符号等ascii可见字符宽度短,所以要计算一下他的实际宽度,便于做样本的时候的宽度过宽
[ 11748, 4738, 198, 6738, 598, 13, 8612, 1352, 13, 26791, 1330, 1635, 198, 6738, 350, 4146, 1330, 7412, 11, 7412, 10258, 11, 7412, 23252, 11, 7412, 25302, 11, 7412, 22417, 198, 6738, 598, 13, 26791, 1330, 2939, 62, 26791, 628, 198, 2, ...
1.347032
438
import random myList = randomListGenerator() output = min(myList) print(myList) print(output)
[ 11748, 4738, 220, 628, 198, 198, 1820, 8053, 796, 4738, 8053, 8645, 1352, 3419, 198, 22915, 796, 949, 7, 1820, 8053, 8, 198, 4798, 7, 1820, 8053, 8, 198, 4798, 7, 22915, 8 ]
2.939394
33
import cv2 import numpy as np import torch from torchvision import transforms from torch import nn from torch.nn import init import torch.nn.functional as F import functools import math import warnings def image_float_to_uint8(img): """ Convert a float image (0.0-1.0) to uint8 (0-255) """ vmin = np.min(img) vmax = np.max(img) if vmax - vmin < 1e-10: vmax += 1e-10 img = (img - vmin) / (vmax - vmin) img *= 255.0 return img.astype(np.uint8) def cmap(img, color_map=cv2.COLORMAP_HOT): """ Apply 'HOT' color to a float image """ return cv2.applyColorMap(image_float_to_uint8(img), color_map) def batched_index_select_nd(t, inds): """ Index select on dim 1 of a n-dimensional batched tensor. :param t (batch, n, ...) :param inds (batch, k) :return (batch, k, ...) """ return t.gather( 1, inds[(...,) + (None,) * (len(t.shape) - 2)].expand(-1, -1, *t.shape[2:]) ) def batched_index_select_nd_last(t, inds): """ Index select on dim -1 of a >=2D multi-batched tensor. inds assumed to have all batch dimensions except one data dimension 'n' :param t (batch..., n, m) :param inds (batch..., k) :return (batch..., n, k) """ dummy = inds.unsqueeze(-2).expand(*inds.shape[:-1], t.size(-2), inds.size(-1)) out = t.gather(-1, dummy) return out def repeat_interleave(input, repeats, dim=0): """ Repeat interleave along axis 0 torch.repeat_interleave is currently very slow https://github.com/pytorch/pytorch/issues/31980 """ output = input.unsqueeze(1).expand(-1, repeats, *input.shape[1:]) return output.reshape(-1, *input.shape[1:]) def homogeneous(points): """ Concat 1 to each point :param points (..., 3) :return (..., 4) """ return F.pad(points, (0, 1), "constant", 1.0) def gen_grid(*args, ij_indexing=False): """ Generete len(args)-dimensional grid. Each arg should be (lo, hi, sz) so that in that dimension points are taken at linspace(lo, hi, sz). Example: gen_grid((0,1,10), (-1,1,20)) :return (prod_i args_i[2], len(args)), len(args)-dimensional grid points """ return torch.from_numpy( np.vstack( np.meshgrid( *(np.linspace(lo, hi, sz, dtype=np.float32) for lo, hi, sz in args), indexing="ij" if ij_indexing else "xy" ) ) .reshape(len(args), -1) .T ) def unproj_map(width, height, f, c=None, device="cpu"): """ Get camera unprojection map for given image size. [y,x] of output tensor will contain unit vector of camera ray of that pixel. :param width image width :param height image height :param f focal length, either a number or tensor [fx, fy] :param c principal point, optional, either None or tensor [fx, fy] if not specified uses center of image :return unproj map (height, width, 3) """ if c is None: c = [width * 0.5, height * 0.5] else: c = c.squeeze() if isinstance(f, float): f = [f, f] elif len(f.shape) == 0: f = f[None].expand(2) elif len(f.shape) == 1: f = f.expand(2) Y, X = torch.meshgrid( torch.arange(height, dtype=torch.float32) - float(c[1]), torch.arange(width, dtype=torch.float32) - float(c[0]), ) X = X.to(device=device) / float(f[0]) Y = Y.to(device=device) / float(f[1]) Z = torch.ones_like(X) unproj = torch.stack((X, -Y, -Z), dim=-1) unproj /= torch.norm(unproj, dim=-1).unsqueeze(-1) return unproj def coord_from_blender(dtype=torch.float32, device="cpu"): """ Blender to standard coordinate system transform. Standard coordinate system is: x right y up z out (out=screen to face) Blender coordinate system is: x right y in z up :return (4, 4) """ return torch.tensor( [[1, 0, 0, 0], [0, 0, 1, 0], [0, -1, 0, 0], [0, 0, 0, 1]], dtype=dtype, device=device, ) def coord_to_blender(dtype=torch.float32, device="cpu"): """ Standard to Blender coordinate system transform. Standard coordinate system is: x right y up z out (out=screen to face) Blender coordinate system is: x right y in z up :return (4, 4) """ return torch.tensor( [[1, 0, 0, 0], [0, 0, -1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], dtype=dtype, device=device, ) def look_at(origin, target, world_up=np.array([0, 1, 0], dtype=np.float32)): """ Get 4x4 camera to world space matrix, for camera looking at target """ back = origin - target back /= np.linalg.norm(back) right = np.cross(world_up, back) right /= np.linalg.norm(right) up = np.cross(back, right) cam_to_world = np.empty((4, 4), dtype=np.float32) cam_to_world[:3, 0] = right cam_to_world[:3, 1] = up cam_to_world[:3, 2] = back cam_to_world[:3, 3] = origin cam_to_world[3, :] = [0, 0, 0, 1] return cam_to_world def get_cuda(gpu_id): """ Get a torch.device for GPU gpu_id. If GPU not available, returns CPU device. """ return ( torch.device("cuda:%d" % gpu_id) if torch.cuda.is_available() else torch.device("cpu") ) def masked_sample(masks, num_pix, prop_inside, thresh=0.5): """ :return (num_pix, 3) """ num_inside = int(num_pix * prop_inside + 0.5) num_outside = num_pix - num_inside inside = (masks >= thresh).nonzero(as_tuple=False) outside = (masks < thresh).nonzero(as_tuple=False) pix_inside = inside[torch.randint(0, inside.shape[0], (num_inside,))] pix_outside = outside[torch.randint(0, outside.shape[0], (num_outside,))] pix = torch.cat((pix_inside, pix_outside)) return pix def bbox_sample(bboxes, num_pix, window_x = 8, window_y = 8, use_windows = False): """ :return (num_pix, 3) """ if use_windows: image_ids = torch.randint(bboxes.shape[0], (1,)) pix_bboxes = bboxes[image_ids] if pix_bboxes[:, 2] - window_x * 2 > pix_bboxes[:, 0]: start_x = torch.randint(int(pix_bboxes[:, 0]), int(pix_bboxes[:, 2] - window_x), (1,)) else: start_x = pix_bboxes[:, 0] if pix_bboxes[:, 3] - window_y * 2 > pix_bboxes[:, 1]: start_y = torch.randint(int(pix_bboxes[:, 1]), int(pix_bboxes[:, 3] - window_y), (1,)) else: start_y = pix_bboxes[:, 1] x, y = torch.meshgrid(torch.arange(int(start_x), int(start_x + window_x * 2), 2), torch.arange(int(start_y), int(start_y + window_y * 2), 2)) pix = torch.stack((y.long(), x.long())).T.reshape((num_pix, 2)) pix = torch.column_stack((image_ids.expand(num_pix), pix)) else: image_ids = torch.randint(0, bboxes.shape[0], (num_pix,)) pix_bboxes = bboxes[image_ids] x = ( torch.rand(num_pix) * (pix_bboxes[:, 2] + 1 - pix_bboxes[:, 0]) + pix_bboxes[:, 0] ).long() y = ( torch.rand(num_pix) * (pix_bboxes[:, 3] + 1 - pix_bboxes[:, 1]) + pix_bboxes[:, 1] ).long() pix = torch.stack((image_ids, y, x), dim=-1) return pix def gen_rays(poses, width, height, focal, z_near, z_far, c=None, ndc=False): """ Generate camera rays :return (B, H, W, 8) """ num_images = poses.shape[0] device = poses.device cam_unproj_map = ( unproj_map(width, height, focal.squeeze(), c=c, device=device) .unsqueeze(0) .repeat(num_images, 1, 1, 1) ) cam_centers = poses[:, None, None, :3, 3].expand(-1, height, width, -1) cam_raydir = torch.matmul( poses[:, None, None, :3, :3], cam_unproj_map.unsqueeze(-1) )[:, :, :, :, 0] if ndc: if not (z_near == 0 and z_far == 1): warnings.warn( "dataset z near and z_far not compatible with NDC, setting them to 0, 1 NOW" ) z_near, z_far = 0.0, 1.0 cam_centers, cam_raydir = ndc_rays( width, height, focal, 1.0, cam_centers, cam_raydir ) cam_nears = ( torch.tensor(z_near, device=device) .view(1, 1, 1, 1) .expand(num_images, height, width, -1) ) cam_fars = ( torch.tensor(z_far, device=device) .view(1, 1, 1, 1) .expand(num_images, height, width, -1) ) return torch.cat( (cam_centers, cam_raydir, cam_nears, cam_fars), dim=-1 ) # (B, H, W, 8) def pose_spherical(theta, phi, radius): """ Spherical rendering poses, from NeRF """ c2w = trans_t(radius) c2w = rot_phi(phi / 180.0 * np.pi) @ c2w c2w = rot_theta(theta / 180.0 * np.pi) @ c2w c2w = ( torch.tensor( [[-1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], dtype=torch.float32, ) @ c2w ) return c2w def get_norm_layer(norm_type="instance", group_norm_groups=32): """Return a normalization layer Parameters: norm_type (str) -- the name of the normalization layer: batch | instance | none For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev). For InstanceNorm, we do not use learnable affine parameters. We do not track running statistics. """ if norm_type == "batch": norm_layer = functools.partial( nn.BatchNorm2d, affine=True, track_running_stats=True ) elif norm_type == "instance": norm_layer = functools.partial( nn.InstanceNorm2d, affine=False, track_running_stats=False ) elif norm_type == "group": norm_layer = functools.partial(nn.GroupNorm, group_norm_groups) elif norm_type == "none": norm_layer = None else: raise NotImplementedError("normalization layer [%s] is not found" % norm_type) return norm_layer def same_pad_conv2d(t, padding_type="reflect", kernel_size=3, stride=1, layer=None): """ Perform SAME padding on tensor, given kernel size/stride of conv operator assumes kernel/stride are equal in all dimensions. Use before conv called. Dilation not supported. :param t image tensor input (B, C, H, W) :param padding_type padding type constant | reflect | replicate | circular constant is 0-pad. :param kernel_size kernel size of conv :param stride stride of conv :param layer optionally, pass conv layer to automatically get kernel_size and stride (overrides these) """ if layer is not None: if isinstance(layer, nn.Sequential): layer = next(layer.children()) kernel_size = layer.kernel_size[0] stride = layer.stride[0] return F.pad( t, calc_same_pad_conv2d(t.shape, kernel_size, stride), mode=padding_type ) def same_unpad_deconv2d(t, kernel_size=3, stride=1, layer=None): """ Perform SAME unpad on tensor, given kernel/stride of deconv operator. Use after deconv called. Dilation not supported. """ if layer is not None: if isinstance(layer, nn.Sequential): layer = next(layer.children()) kernel_size = layer.kernel_size[0] stride = layer.stride[0] h_scaled = (t.shape[-2] - 1) * stride w_scaled = (t.shape[-1] - 1) * stride pad_left, pad_right, pad_top, pad_bottom = calc_same_pad_conv2d( (h_scaled, w_scaled), kernel_size, stride ) if pad_right == 0: pad_right = -10000 if pad_bottom == 0: pad_bottom = -10000 return t[..., pad_top:-pad_bottom, pad_left:-pad_right] def psnr(pred, target): """ Compute PSNR of two tensors in decibels. pred/target should be of same size or broadcastable """ mse = ((pred - target) ** 2).mean() psnr = -10 * math.log10(mse) return psnr def quat_to_rot(q): """ Quaternion to rotation matrix """ batch_size, _ = q.shape q = F.normalize(q, dim=1) R = torch.ones((batch_size, 3, 3), device=q.device) qr = q[:, 0] qi = q[:, 1] qj = q[:, 2] qk = q[:, 3] R[:, 0, 0] = 1 - 2 * (qj ** 2 + qk ** 2) R[:, 0, 1] = 2 * (qj * qi - qk * qr) R[:, 0, 2] = 2 * (qi * qk + qr * qj) R[:, 1, 0] = 2 * (qj * qi + qk * qr) R[:, 1, 1] = 1 - 2 * (qi ** 2 + qk ** 2) R[:, 1, 2] = 2 * (qj * qk - qi * qr) R[:, 2, 0] = 2 * (qk * qi - qj * qr) R[:, 2, 1] = 2 * (qj * qk + qi * qr) R[:, 2, 2] = 1 - 2 * (qi ** 2 + qj ** 2) return R def rot_to_quat(R): """ Rotation matrix to quaternion """ batch_size, _, _ = R.shape q = torch.ones((batch_size, 4), device=R.device) R00 = R[:, 0, 0] R01 = R[:, 0, 1] R02 = R[:, 0, 2] R10 = R[:, 1, 0] R11 = R[:, 1, 1] R12 = R[:, 1, 2] R20 = R[:, 2, 0] R21 = R[:, 2, 1] R22 = R[:, 2, 2] q[:, 0] = torch.sqrt(1.0 + R00 + R11 + R22) / 2 q[:, 1] = (R21 - R12) / (4 * q[:, 0]) q[:, 2] = (R02 - R20) / (4 * q[:, 0]) q[:, 3] = (R10 - R01) / (4 * q[:, 0]) return q def get_module(net): """ Shorthand for either net.module (if net is instance of DataParallel) or net """ if isinstance(net, torch.nn.DataParallel): return net.module else: return net
[ 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 28034, 10178, 1330, 31408, 198, 6738, 28034, 1330, 299, 77, 198, 6738, 28034, 13, 20471, 1330, 2315, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376...
2.12512
6,250
# -*- coding: utf-8 """Module for testing reading charactersitic lines. This file is part of project TESPy (github.com/oemof/tespy). It's copyrighted by the contributors recorded in the version control history of the file, available from its original location tests/test_tools/test_characteristics.py SPDX-License-Identifier: MIT """ import json import os import shutil import numpy as np from pkg_resources import resource_filename from tespy.tools.characteristics import CharLine from tespy.tools.characteristics import CharMap from tespy.tools.characteristics import load_custom_char from tespy.tools.characteristics import load_default_char from tespy.tools.helpers import extend_basic_path def test_custom_CharLine_import(): """Test importing a custom characteristc lines.""" # we need to write some data to the path first, using defaults data_path = resource_filename('tespy.data', 'char_lines.json') path = extend_basic_path('data') tmp_path = extend_basic_path('tmp_dir_for_testing') if os.path.exists(path): for f in os.listdir(path): shutil.copy(src=path + '/' + f, dst=tmp_path) with open(data_path) as f: raw_data = json.loads(f.read()) data = raw_data['heat exchanger']['kA_char2'] with open(os.path.join(path, 'char_lines.json'), 'w') as outfile: json.dump(data, outfile) char_original = load_default_char('heat exchanger', 'kA_char2', 'EVAPORATING FLUID', CharLine) char_custom = load_custom_char('EVAPORATING FLUID', CharLine) shutil.rmtree(path, ignore_errors=True) if os.path.exists(tmp_path): path = extend_basic_path('data') for f in os.listdir(tmp_path): shutil.copy(src=tmp_path + '/' + f, dst=path) shutil.rmtree(tmp_path, ignore_errors=True) x_cond = np.array_equal(char_original.x, char_custom.x) y_cond = np.array_equal(char_original.y, char_custom.y) msg = ('The x values from the custom characteristic line ' + str(char_custom.x) + ' must be identical to the x values from ' 'the default characteristic line ' + str(char_original.x) + ' ' 'as these have been duplicated before load.') assert x_cond is True, msg msg = ('The y values from the custom characteristic line ' + str(char_custom.y) + ' must be identical to the y values from ' 'the default characteristic line ' + str(char_original.y) + ' ' 'as these have been duplicated before load.') assert y_cond is True, msg def test_custom_CharMap_import(): """Test importing a custom characteristc map.""" # we need to write some data to the path first, using defaults data_path = resource_filename('tespy.data', 'char_maps.json') path = extend_basic_path('data') tmp_path = extend_basic_path('tmp_dir_for_testing') if os.path.exists(path): for f in os.listdir(path): shutil.copy(src=path + '/' + f, dst=tmp_path) with open(data_path) as f: raw_data = json.loads(f.read()) data = raw_data['compressor']['char_map_pr'] with open(os.path.join(path, 'char_maps.json'), 'w') as outfile: json.dump(data, outfile) char_original = load_default_char( 'compressor', 'char_map_pr', 'DEFAULT', CharMap) char_custom = load_custom_char('DEFAULT', CharMap) x_cond = np.array_equal(char_original.x, char_custom.x) y_cond = np.array_equal(char_original.y, char_custom.y) z_cond = np.array_equal(char_original.z, char_custom.z) shutil.rmtree(path, ignore_errors=True) if os.path.exists(tmp_path): path = extend_basic_path('data') for f in os.listdir(tmp_path): shutil.copy(src=tmp_path + '/' + f, dst=path) shutil.rmtree(tmp_path, ignore_errors=True) msg = ('The x values from the custom characteristic line ' + str(char_custom.x) + ' must be identical to the x values from ' 'the default characteristic line ' + str(char_original.x) + ' ' 'as these have been duplicated before load.') assert x_cond is True, msg msg = ('The y values from the custom characteristic line ' + str(char_custom.y) + ' must be identical to the y values from ' 'the default characteristic line ' + str(char_original.y) + ' ' 'as these have been duplicated before load.') assert y_cond is True, msg msg = ('The z values from the custom characteristic line ' + str(char_custom.z) + ' must be identical to the z values from ' 'the default characteristic line ' + str(char_original.z) + ' ' 'as these have been duplicated before load.') assert z_cond is True, msg def test_CharLine_evaluation(): """Test the characteristc line evaluation.""" # create a characteristc line with values of y=(x-2)^2 line = CharLine(x=[0, 1, 2, 3, 4], y=[4, 1, 0, 1, 4]) # test evaluation at given x value (x=3, y=1) x = 3 y = line.evaluate(x) msg = ('The evaluation of x=' + str(x) + ' must be 1.0, but is ' + str(y) + '.') assert y == 1.0, msg # test evaluation at x=0.5 to force interpolation, result: y=2.5 x = 0.5 y = line.evaluate(x) msg = ('The evaluation of x=' + str(x) + ' must be 2.5, but is ' + str(y) + '.') assert y == 2.5, msg # test evaluation at x=-1 to check lower limits, result: y=4 x = -1 y = line.evaluate(x) msg = ('The evaluation of x=' + str(x) + ' must be 4, but is ' + str(y) + '.') assert y == 4.0, msg # test evaluation at x=5 to check upper limits, result: y=4 x = 5 y = line.evaluate(x) msg = ('The evaluation of x=' + str(x) + ' must be 4, but is ' + str(y) + '.') assert y == 4.0, msg def test_CharLine_extrapolation(): """Test the characteristc line with extrapolation.""" # create a characteristc line with values of y=(x-2)^2 line = CharLine(x=[0, 1, 2, 3, 4], y=[4, 1, 0, 1, 4], extrapolate=True) # test evaluation at x=-1 to check lower limits, result: y=7 x = -1 y = line.evaluate(x) msg = ('The evaluation of x=' + str(x) + ' must be 7, but is ' + str(y) + '.') assert y == 7.0, msg # test evaluation at x=5 to check upper limits, result: y=7 x = 5 y = line.evaluate(x) msg = ('The evaluation of x=' + str(x) + ' must be 7, but is ' + str(y) + '.') assert y == 7.0, msg def test_CharMap_evaluation(): """Test the characteristc map evaluation.""" # create a characteristc line with values of y=(x-2)^2 x = [1, 2, 3] y = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) z = y ** 0.5 map = CharMap(x=x, y=y, z=z) # test evaluation at x=2 and y=3, result: z1=1.73, z2=9 x = 2 y = 3 z = map.evaluate(x=x, y=y) msg = ('The evaluation of x=' + str(x) + ' and y=' + str(y) + ' for z ' 'must be 1.73, but is ' + str(round(z, 2)) + '.') assert round(z, 2) == 1.73, msg # test evaluation at x=0 and y=0 for lower value range limit, # result: z=1 x = 0 y = 0 z = map.evaluate(x=x, y=y) msg = ('The evaluation of x=' + str(x) + ' and y=' + str(y) + ' for z ' 'must be 1.0, but is ' + str(round(z, 1)) + '.') assert round(z, 1) == 1.0, msg # test evaluation at x=4 and y=6 for upper value range limit, # result: z=2.24 x = 4 y = 6 z = map.evaluate(x=x, y=y) msg = ('The evaluation of x=' + str(x) + ' and y=' + str(y) + ' for z ' 'must be 2.24, but is ' + str(round(z, 2)) + '.') assert round(z, 2) == 2.24, msg # check, if bound errors go through map.get_domain_errors(x, y, 'Componentlabel')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 26796, 329, 4856, 3555, 3435, 16233, 3951, 13, 198, 198, 1212, 2393, 318, 636, 286, 1628, 309, 1546, 20519, 357, 12567, 13, 785, 14, 78, 368, 1659, 14, 4879, 9078, 737, ...
2.426471
3,196
import paho.mqtt.client as mqtt import uuid import ssl import json from typing import Dict, List # pip install paho-mqtt TOPIC = 'myTopic' QOS = 2 # 0, 1 or 2 # read about qos here: https://www.hivemq.com/blog/mqtt-essentials-part-6-mqtt-quality-of-service-levels/ # and here: https://www.rabbitmq.com/mqtt.html#features # The callback for when the client receives a CONNACK response from the server. # The callback for when a PUBLISH message is received from the server. n_clients = 2 clients: List[mqtt.Client] = [] for i in range(n_clients): print(f'Creating mqtt client {i+1}') clients.append(get_client(i+1)) for client in clients: client.loop_start() infoInput = 'Hit enter with no inputs to stop..' stringInput = input(infoInput) while len(stringInput) > 0: for client in clients: payload = {'msg': f'Hello Mqtt World! From client {str(client._client_id.decode("utf-8"))}'} info: mqtt.MQTTMessageInfo = client.publish(TOPIC, json.dumps(payload), qos=QOS, retain=True) info.wait_for_publish() print(f'published successfully on topic: {TOPIC}') stringInput = input(infoInput) for client in clients: print(f'Stopping mqtt client {str(client._client_id.decode("utf-8"))}') client.loop_stop(force=True) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. # client.loop_forever()
[ 11748, 279, 17108, 13, 76, 80, 926, 13, 16366, 355, 285, 80, 926, 198, 11748, 334, 27112, 198, 11748, 264, 6649, 198, 11748, 33918, 198, 6738, 19720, 1330, 360, 713, 11, 7343, 198, 198, 2, 7347, 2721, 279, 17108, 12, 76, 80, 926, ...
2.763401
541
# # @component { # "kind" : "viz", # "language" : "py", # "description" : "Plots grayscale images", # "permissions": "public", # "properties": [ # { "name": "Number to plot" , "field": "count", "kind": "integer", "min": 1, "max": 1000, "required": true, "default": 9 }, # { "name": "Number of columns" , "field": "numcols", "kind": "integer", "min": 1, "max": 10, "required": true, "default": 3 } # ], # "inputs": ["X:img[]", "y:string[]"], # "outputs": ["X:img[]", "y:string[]"], # "dependencies": ["matplotlib"], # "readme" : "", # "license" : "", # "links": ["https://machinelearningmastery.com/how-to-develop-a-cnn-from-scratch-for-fashion-mnist-clothing-classification/"] # } import matplotlib.pyplot as plt
[ 2, 220, 201, 198, 2, 2488, 42895, 1391, 201, 198, 2, 197, 1, 11031, 1, 1058, 366, 85, 528, 1600, 201, 198, 2, 197, 1, 16129, 1, 1058, 366, 9078, 1600, 201, 198, 2, 197, 1, 11213, 1, 1058, 366, 3646, 1747, 1036, 592, 38765, 426...
2.380645
310
# Generated by Django 3.2.4 on 2021-06-13 02:53 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 19, 319, 33448, 12, 3312, 12, 1485, 7816, 25, 4310, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
"""User support functions and definitions.""" import dataclasses import typing from . import mongo, core @dataclasses.dataclass class User(core.ModelBase): """Representation of authenticated user.""" email: str is_admin: bool = False roles: typing.List = dataclasses.field(default_factory=list) def get_user(email: str): """Return user instance from db. If ne create new one.""" return mongo.MongoUsers.get_user(email)
[ 37811, 12982, 1104, 5499, 290, 17336, 526, 15931, 198, 11748, 4818, 330, 28958, 198, 11748, 19720, 198, 198, 6738, 764, 1330, 285, 25162, 11, 4755, 628, 198, 31, 19608, 330, 28958, 13, 19608, 330, 31172, 198, 4871, 11787, 7, 7295, 13, ...
3.075342
146
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.python.framework.ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import gc import numpy as np import os import threading import weakref from tensorflow.core.framework import attr_value_pb2 from tensorflow.core.protobuf import config_pb2 from tensorflow.python.autograph.core import ag_ctx from tensorflow.python.client import session from tensorflow.python.compat import compat as forward_compat from tensorflow.python.eager import backprop from tensorflow.python.eager import context from tensorflow.python.eager import def_function from tensorflow.python.eager import function as eager_function from tensorflow.python.eager import wrap_function from tensorflow.python.framework import composite_tensor from tensorflow.python.framework import constant_op from tensorflow.python.framework import device as pydev from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import function from tensorflow.python.framework import indexed_slices from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_spec from tensorflow.python.framework import tensor_util from tensorflow.python.framework import test_ops from tensorflow.python.framework import test_util from tensorflow.python.framework import type_spec from tensorflow.python.framework import versions from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import resources from tensorflow.python.ops import special_math_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables import tensorflow.python.ops.gradients # pylint: disable=unused-import from tensorflow.python.platform import googletest from tensorflow.python.util import compat @test_util.run_all_in_graph_and_eager_modes # NOTE(skyewm): these cases test the private Graph._create_op_from_tf_operation # method. Arguably we should only test the public APIs that depend on this # method. However, this logic is complex and tricky, and it can be difficult to # ascertain if we have adequate coverage (e.g. a graph may run successfully if # the control flow context isn't set properly, but a more complicated use case # that might not be obvious to test will fail). Thus we instead explicitly test # the low-level behavior. ops.NotDifferentiable("FloatOutput") @ops.RegisterGradient("CopyOp") @ops.RegisterGradient("copy_override") @ops.RegisterStatistics("a", "flops") class _TupleTensor(composite_tensor.CompositeTensor): """`Tensor`-like `tuple`-like for custom `Tensor` conversion masquerading.""" @property class _MyTuple(object): """Pretend user-side class for `ConvertToCompositeTensorTest .""" ops.register_tensor_conversion_function( _MyTuple, conversion_func=lambda x, *_, **__: _TupleTensor(x)) if __name__ == "__main__": googletest.main()
[ 2, 15069, 1853, 383, 309, 22854, 37535, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, ...
3.577096
1,109
#!/usr/bin/env python3 import os, sys import getpass import tempfile import subprocess """ Install Snakemake This script runs the necessary commands to install Snakemake. """ if __name__=="__main__": install_snakemake_the_slightly_easier_way()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 28686, 11, 25064, 198, 11748, 651, 6603, 198, 11748, 20218, 7753, 198, 11748, 850, 14681, 198, 198, 37811, 198, 15798, 16705, 15883, 198, 198, 1212, 4226, 4539, 262, 3306, 972...
2.747475
99
#!/usr/bin/env python import sys from cdrouter import CDRouter from cdrouter.highlights import Highlight if len(sys.argv) < 3: print('usage: <base_url> <token>') sys.exit(1) base = sys.argv[1] token = sys.argv[2] c = CDRouter(base, token=token) for r in c.results.iter_list(sort=['-id']): for tr in c.tests.iter_list(r.id): try: logs = c.tests.list_log(tr.id, tr.seq, filter=['proto=DHCP', 'info~*offer'], limit='100000') except: continue if len(logs.lines) == 0: continue r.starred = True r = c.results.edit(r) print('{}: starred'.format(r.id)) tr.flagged = True tr = c.tests.edit(tr) print('{}: {}: flagged'.format(r.id, tr.name)) for log in logs.lines: c.highlights.create(tr.id, tr.seq, Highlight(line=str(log.line), color='red')) print('{}: {}: line {}: highlighted red'.format(r.id, tr.name, log.line))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 25064, 198, 198, 6738, 22927, 472, 353, 1330, 6458, 49, 39605, 198, 6738, 22927, 472, 353, 13, 8929, 8091, 1330, 3334, 2971, 198, 198, 361, 18896, 7, 17597, 13, 853, 85, ...
2.005976
502
from my_devices import device_list from my_functions import napalm_connect if __name__ == "__main__": connection = [] for device in device_list: conn = napalm_connect(device) connection.append(conn) for conn in connection: print(conn) conn.load_merge_candidate(filename="{}-loopbacks".format(conn.hostname)) print("Difference in device{}".format(conn.hostname)) diff = conn.compare_config() print(diff) if diff: conn.commit_config() print("Difference in device after commiting{}".format(conn.hostname)) print(conn.compare_config()) conn.close()
[ 6738, 616, 62, 42034, 1330, 3335, 62, 4868, 198, 6738, 616, 62, 12543, 2733, 1330, 25422, 38182, 62, 8443, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 4637, 796, 17635, 198, 220, 220, 220, ...
2.400722
277
#! /usr/bin/env python3 import sys DIRECTIONS = [(0, -1), (-1, 0), (1, 0), (0, 1)] if __name__ == '__main__': if len(sys.argv) != 2: sys.exit('Usage: %s (1|2)' % sys.argv[0]) if sys.argv[1] == '1': print(run_1(sys.stdin.read())) elif sys.argv[1] == '2': print(run_2(sys.stdin.read())) else: sys.exit('Unknown action: %s' % sys.argv[1])
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 25064, 198, 198, 17931, 23988, 11053, 796, 47527, 15, 11, 532, 16, 828, 13841, 16, 11, 657, 828, 357, 16, 11, 657, 828, 357, 15, 11, 352, 15437, 628, 628, 628, 628, ...
1.882075
212
# flake8: noqa from catalyst.core.callback import * from catalyst.core.callbacks import * from .confusion_matrix import ConfusionMatrixCallback from .inference import InferCallback from .meter import MeterMetricsCallback from .metrics import ( AccuracyCallback, AUCCallback, ClasswiseIouCallback, ClasswiseJaccardCallback, DiceCallback, F1ScoreCallback, IouCallback, JaccardCallback, MapKCallback, MulticlassDiceMetricCallback, PrecisionRecallF1ScoreCallback, ) from .mixup import MixupCallback from .scheduler import LRFinder from catalyst.contrib.dl.callbacks import * # isort:skip
[ 2, 781, 539, 23, 25, 645, 20402, 198, 198, 6738, 31357, 13, 7295, 13, 47423, 1330, 1635, 198, 6738, 31357, 13, 7295, 13, 13345, 10146, 1330, 1635, 198, 198, 6738, 764, 10414, 4241, 62, 6759, 8609, 1330, 7326, 4241, 46912, 47258, 198, ...
2.995261
211
import time class Deadline: """It is convenient to use this class instead of timeout variable if the timeout variable is accessed multiple times inside a function. """ @property @property @property
[ 11748, 640, 628, 198, 4871, 35954, 25, 198, 220, 220, 220, 37227, 1026, 318, 11282, 284, 779, 428, 1398, 2427, 286, 26827, 7885, 611, 262, 198, 220, 220, 220, 26827, 7885, 318, 17535, 3294, 1661, 2641, 257, 2163, 13, 198, 220, 220, ...
3.603175
63
import time import cv2 import numpy as np from tqdm import tqdm data = np.load('pts.npz') src_pts = data['src_pts'] dst_pts = data['dst_pts'] num_tests = 100000 start = time.time() for _ in tqdm(range(num_tests)): H, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0) elapsed_time = time.time() - start print('average time per image pair: {} seconds'.format(elapsed_time / num_tests))
[ 11748, 640, 198, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 7890, 796, 45941, 13, 2220, 10786, 457, 82, 13, 37659, 89, 11537, 198, 10677, 62, 457, 82, 796,...
2.376471
170
from queue import Queue from typing import TYPE_CHECKING, Any, Dict, Type, Union, Optional import pytest from nonebug.base import BaseApp, Context from .model import Api, Send, Model from .fake import make_fake_bot, make_fake_adapter if TYPE_CHECKING: from nonebot.adapters import Bot, Event, Adapter, Message, MessageSegment
[ 6738, 16834, 1330, 4670, 518, 198, 6738, 19720, 1330, 41876, 62, 50084, 2751, 11, 4377, 11, 360, 713, 11, 5994, 11, 4479, 11, 32233, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 4844, 25456, 13, 8692, 1330, 7308, 4677, 11, 30532, 198...
3.294118
102
from cursor import device from cursor import path from cursor import filter import json import random from alive_progress import alive_bar if __name__ == "__main__": # recordings = data.DataDirHandler().recordings() # _loader = loader.Loader(directory=recordings, limit_files=1) # pc = _loader.all_paths() categories = ["broccoli"] pc_all = path.PathCollection() for cat in categories: # cat = "all" fname = f"{cat}.json" data = json.load(open(fname)) print(f"done loading {fname}") file_to_paths(pc_all, data, categories.index(cat) + 1) # sorter = filter.Sorter(param=filter.Sorter.POINT_COUNT, reverse=True) # pc_all.sort(sorter) # rs = pc_all[0] entropy_filter = filter.EntropyMinFilter(1.5, 1.5) point_filter1 = filter.MinPointCountFilter(100) point_filter2 = filter.MaxPointCountFilter(30) # pc_all.filter(point_filter1) # pc_all.filter(point_filter2) pc_all.clean() # pc_all.filter(entropy_filter) pc = path.PathCollection() rows = 3 for i in range(rows * rows): # p = pc_all.random().copy() p = pc_all.random() split1 = random.uniform(0, 0.5) split2 = random.uniform(0.5, 1.0) end1 = int(len(p) * split1) end2 = int(len(p) * split2) p1 = path.Path(p.vertices[:end1]) p2 = path.Path(p.vertices[end1:end2]) p3 = path.Path(p.vertices[end2:]) p1.pen_select = (((i % 3) + 1) % 3) + 1 p2.pen_select = (((i % 3) + 2) % 3) + 1 p3.pen_select = (((i % 3) + 3) % 3) + 1 p1.is_polygon = True p2.is_polygon = True p3.is_polygon = True x = (i % rows) + 1 y = (int(i / rows)) + 1 center = p1.centeroid() p1.translate(-center[0], -center[1]) pc1 = path.PathCollection() pc1.add(p1) pc1.fit((280, 280)) p1 = pc1[0] p1.translate(300 * x, 300 * y) center = p2.centeroid() p2.translate(-center[0], -center[1]) pc2 = path.PathCollection() pc2.add(p2) pc2.fit((280, 280)) p2 = pc2[0] p2.translate(300 * x, 300 * y) center = p3.centeroid() p3.translate(-center[0], -center[1]) pc3 = path.PathCollection() pc3.add(p3) pc3.fit((280, 280)) p3 = pc3[0] p3.translate(300 * x, 300 * y) pc.add(p1) pc.add(p2) pc.add(p3) # rs2.translate(i * 1, i * 1) # pc.add(rs2) # pc.scale(10, 10) # make_filled_polygon(pc) device.SimpleExportWrapper().ex( pc, device.PlotterType.HP_7595A_A3, device.PaperSize.LANDSCAPE_A3, 25, "genuary22_18_three_colors", f"split_path_{pc.hash()}", )
[ 6738, 23493, 1330, 3335, 198, 6738, 23493, 1330, 3108, 198, 6738, 23493, 1330, 8106, 198, 198, 11748, 33918, 198, 11748, 4738, 198, 6738, 6776, 62, 33723, 1330, 6776, 62, 5657, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, ...
1.970381
1,418
# # Copyright (c) 2019 ISP RAS (http://www.ispras.ru) # Ivannikov Institute for System Programming of the Russian Academy of Sciences # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import json from django.http import HttpResponse from django.template import loader from django.urls import reverse from django.utils.translation import ugettext as _ from rest_framework import exceptions from rest_framework.generics import ( get_object_or_404, RetrieveAPIView, CreateAPIView, DestroyAPIView, UpdateAPIView, GenericAPIView ) from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from bridge.vars import DECISION_STATUS, LOG_FILE from bridge.utils import logger, BridgeException, ArchiveFileContent from bridge.access import ServicePermission, ViewJobPermission from bridge.CustomViews import TemplateAPIRetrieveView from tools.profiling import LoggedCallMixin from jobs.models import Decision from reports.models import Report, ReportComponent, OriginalSources, CoverageArchive, ReportAttr, CompareDecisionsInfo from jobs.utils import JobAccess, DecisionAccess from reports.comparison import FillComparisonCache, ComparisonData from reports.coverage import GetCoverageData, ReportCoverageStatistics from reports.serializers import OriginalSourcesSerializer, PatchReportAttrSerializer from reports.source import GetSource from reports.UploadReport import UploadReports
[ 2, 198, 2, 15069, 357, 66, 8, 13130, 33086, 371, 1921, 357, 4023, 1378, 2503, 13, 271, 1050, 292, 13, 622, 8, 198, 2, 16975, 1236, 1134, 709, 5136, 329, 4482, 30297, 286, 262, 3394, 8581, 286, 13473, 198, 2, 198, 2, 49962, 739, ...
3.905138
506
#!/usr/bin/env python3 import sys import os sys.path.append("../lib/") sys.path.append("../io_path/") from datetime import datetime import subprocess import psutil import signal import ibofos import ibofos_constant import cli import json_parser import spdk_rpc import TEST import TEST_LOG import TEST_DEBUGGING ###################################################################################### isIbofExecuted = False ######################################################################################
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 25064, 198, 11748, 28686, 198, 198, 17597, 13, 6978, 13, 33295, 7203, 40720, 8019, 14, 4943, 198, 17597, 13, 6978, 13, 33295, 7203, 40720, 952, 62, 6978, 14, 4943, 198,...
3.984496
129
import hug @hug.cli() @hug.get('/')
[ 11748, 16225, 198, 198, 31, 71, 1018, 13, 44506, 3419, 198, 31, 71, 1018, 13, 1136, 10786, 14, 11537, 628 ]
1.9
20
from core import messages from core.weexceptions import FatalException from mako import template from core.config import sessions_path, sessions_ext from core.loggers import log, dlog, stream_handler from core.module import Status import os import yaml import glob import logging import urllib.parse import atexit import ast import pprint print_filters = ( 'debug', 'channel', 'proxy' ) set_filters = ( 'debug', 'channel', 'proxy' )
[ 6738, 4755, 1330, 6218, 198, 6738, 4755, 13, 732, 1069, 11755, 1330, 41815, 16922, 198, 6738, 285, 25496, 1330, 11055, 198, 6738, 4755, 13, 11250, 1330, 10991, 62, 6978, 11, 10991, 62, 2302, 198, 6738, 4755, 13, 6404, 5355, 1330, 2604, ...
3.08
150
"""Celery tasks for stories""" from datetime import timedelta from pathlib import Path import re from celery import shared_task from celery.schedules import crontab from celery.task import periodic_task from celery.utils.log import get_task_logger from django.core.cache import cache from django.db.models import F, Q from django.utils import timezone from apps.issues.models import current_issue from apps.photo.tasks import upload_imagefile_to_desken from .models import Story logger = get_task_logger(__name__) # cron timing UPDATE_SEARCH = timedelta(hours=1) DEVALUE_HOTNESS = timedelta(hours=1) PERSIST_STORY_VISITS = timedelta(minutes=10) @periodic_task(run_every=UPDATE_SEARCH, ignore_result=True) def update_search_task(): """Update database search index for newly modified stories.""" qs = Story.objects.filter( Q(search_vector=None) | Q(modified__gt=timezone.now() - UPDATE_SEARCH * 1.5) ) qs.update_search_vector() return qs.count() @periodic_task(run_every=crontab(hour=6, minute=0)) def archive_stale_stories(days=14): """Archive prodsys content that has not been touched for a while.""" STALE_LIMIT = timezone.timedelta(days) stale_stories = Story.objects.filter( modified__lt=timezone.now() - STALE_LIMIT, publication_status__lt=Story.STATUS_PUBLISHED, ) if stale_stories: count = stale_stories.update(publication_status=Story.STATUS_PRIVATE) logger.info(f'archived {count} stories') else: logger.info('no stale stories') @shared_task @periodic_task(run_every=PERSIST_STORY_VISITS, ignore_result=True) def save_visits_task(): """Persist visit counts to database and reset cache.""" cache_keys = cache.keys(f'{Story.VISIT_KEY_PREFIX}*') for key in cache_keys: val = int(cache.get(key)) pk = int(key.replace(Story.VISIT_KEY_PREFIX, '')) Story.objects.filter(pk=pk).update( hit_count=F('hit_count') + val, hot_count=F('hot_count') + 100 * val, ) logger.info(f'Story {pk} was visited {val} times') cache.delete(key) return len(cache_keys) @periodic_task(run_every=DEVALUE_HOTNESS, ignore_result=True) def devalue_hotness_task(chill_percentage=1): """Decrease the hotness rating of all stories.""" factor = (100 - chill_percentage) / 100.0 logger.info(f'decreasing hotness by {factor}%') Story.objects.devalue_hotness(factor) return chill_percentage
[ 37811, 34, 417, 1924, 8861, 329, 3923, 37811, 198, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 6738, 3108, 8019, 1330, 10644, 198, 11748, 302, 198, 198, 6738, 18725, 1924, 1330, 4888, 62, 35943, 198, 6738, 18725, 1924, 13, 1416, 704...
2.551335
974
import os import sys import gi gi.require_version('Gtk', '3.0') gi.require_version('GtkSource', '3.0') from gi.repository import Gtk, GtkSource, GLib, Gio MENU_XML = """ <?xml version="1.0" encoding="UTF-8"?> <interface> <menu id="menubar"> <submenu> <attribute name="label" translatable="yes">ファイル</attribute> <section> <item> <attribute name="action">win.open</attribute> <attribute name="label" translatable="yes">開く</attribute> <attribute name="icon">document-open</attribute> </item> <item> <attribute name="action">win.save</attribute> <attribute name="label" translatable="yes">上書き保存</attribute> <attribute name="icon">document-save</attribute> </item> <item> <attribute name="action">win.save_as</attribute> <attribute name="label" translatable="yes">名前を付けて保存</attribute> <attribute name="icon">document-save-as</attribute> </item> <item> <attribute name="action">win.quit</attribute> <attribute name="label" translatable="yes">終了</attribute> <attribute name="icon">application-exit</attribute> </item> </section> </submenu> </menu> </interface> """ # self.activate() # self.add_main_option("open", ord("o"), GLib.OptionFlags.NONE, # GLib.OptionArg.NONE, "Open file", None) # def do_command_line(self, command_line): # options = command_line.get_options_dict() # # if options.contains("open"): # print("Open file!") # # self.activate() # return 0 if __name__ == "__main__": app = Application() app.run(sys.argv)
[ 11748, 28686, 198, 11748, 25064, 198, 198, 11748, 308, 72, 198, 12397, 13, 46115, 62, 9641, 10786, 38, 30488, 3256, 705, 18, 13, 15, 11537, 198, 12397, 13, 46115, 62, 9641, 10786, 38, 30488, 7416, 3256, 705, 18, 13, 15, 11537, 198, ...
2.179874
795
from Bio import SeqIO from Bio.Seq import Seq import random import math ########################################################### ################### SDU ################### ########################################################### ########################################################### ################### RSDU ################## ########################################################### #### DICTIONARIES #### CpCpos1 = {'P': 1.0} CpGpos1 = {'R': 0.6666666666666666} CpUpos1 = {'L': 0.6666666666666666} CpApos1 = {'Q': 1.0, 'H': 1.0} GpCpos1 = {'A': 1.0} GpGpos1 = {'G': 1.0} GpUpos1 = {'V': 1.0} GpApos1 = {'D': 1.0, 'E': 1.0} UpCpos1 = {'S': 0.6666666666666666} UpGpos1 = {'C': 1.0, 'W': 1.0} UpUpos1 = {'F': 1.0, 'L': 0.3333333333333333} UpApos1 = {'Y': 1.0} ApCpos1 = {'T': 1.0} ApGpos1 = {'S': 0.3333333333333333, 'R': 0.3333333333333333} ApUpos1 = {'M': 1.0, 'I': 1.0} ApApos1 = {'N': 1.0, 'K': 1.0} CpCpos2 = {'S': 0.16666666666666666, 'P': 0.25, 'T': 0.25, 'A': 0.25} CpGpos2 = {'S': 0.16666666666666666, 'P': 0.25, 'T': 0.25, 'A': 0.25} CpUpos2 = {'S': 0.16666666666666666, 'P': 0.25, 'T': 0.25, 'A': 0.25} CpApos2 = {'S': 0.16666666666666666, 'P': 0.25, 'T': 0.25, 'A': 0.25} GpCpos2 = {'C': 0.5, 'S': 0.16666666666666666, 'G': 0.25, 'R': 0.16666666666666666} GpGpos2 = {'G': 0.25, 'R': 0.3333333333333333, 'W': 1.0} GpUpos2 = {'C': 0.5, 'S': 0.16666666666666666, 'G': 0.25, 'R': 0.16666666666666666} GpApos2 = {'G': 0.25, 'R': 0.3333333333333333} UpCpos2 = {'F': 0.5, 'I': 0.3333333333333333, 'L': 0.16666666666666666, 'V': 0.25} UpGpos2 = {'M': 1.0, 'L': 0.3333333333333333, 'V': 0.25} UpUpos2 = {'F': 0.5, 'I': 0.3333333333333333, 'L': 0.16666666666666666, 'V': 0.25} UpApos2 = {'I': 0.3333333333333333, 'L': 0.3333333333333333, 'V': 0.25} ApCpos2 = {'D': 0.5, 'N': 0.5, 'H': 0.5, 'Y': 0.5} ApGpos2 = {'Q': 0.5, 'K': 0.5, 'E': 0.5} ApUpos2 = {'D': 0.5, 'N': 0.5, 'H': 0.5, 'Y': 0.5} ApApos2 = {'Q': 0.5, 'K': 0.5, 'E': 0.5} CpCbridge = {'CQ': 0.5, 'CP': 0.5, 'CL': 0.3333333333333333, 'CH': 0.5, 'CR': 0.3333333333333333, 'DQ': 0.5, 'DP': 0.5, 'DL': 0.3333333333333333, 'DH': 0.5, 'DR': 0.3333333333333333, 'SQ': 0.3333333333333333, 'SP': 0.3333333333333333, 'SL': 0.2222222222222222, 'SH': 0.3333333333333333, 'SR': 0.2222222222222222, 'NQ': 0.5, 'NP': 0.5, 'NL': 0.3333333333333333, 'NH': 0.5, 'NR': 0.3333333333333333, 'PQ': 0.25, 'PP': 0.25, 'PL': 0.16666666666666666, 'PH': 0.25, 'PR': 0.16666666666666666, 'TQ': 0.25, 'TP': 0.25, 'TL': 0.16666666666666666, 'TH': 0.25, 'TR': 0.16666666666666666, 'FQ': 0.5, 'FP': 0.5, 'FL': 0.3333333333333333, 'FH': 0.5, 'FR': 0.3333333333333333, 'AQ': 0.25, 'AP': 0.25, 'AL': 0.16666666666666666, 'AH': 0.25, 'AR': 0.16666666666666666, 'GQ': 0.25, 'GP': 0.25, 'GL': 0.16666666666666666, 'GH': 0.25, 'GR': 0.16666666666666666, 'IQ': 0.3333333333333333, 'IP': 0.3333333333333333, 'IL': 0.2222222222222222, 'IH': 0.3333333333333333, 'IR': 0.2222222222222222, 'LQ': 0.16666666666666666, 'LP': 0.16666666666666666, 'LL': 0.1111111111111111, 'LH': 0.16666666666666666, 'LR': 0.1111111111111111, 'HQ': 0.5, 'HP': 0.5, 'HL': 0.3333333333333333, 'HH': 0.5, 'HR': 0.3333333333333333, 'RQ': 0.16666666666666666, 'RP': 0.16666666666666666, 'RL': 0.1111111111111111, 'RH': 0.16666666666666666, 'RR': 0.1111111111111111, 'VQ': 0.25, 'VP': 0.25, 'VL': 0.16666666666666666, 'VH': 0.25, 'VR': 0.16666666666666666, 'YQ': 0.5, 'YP': 0.5, 'YL': 0.3333333333333333, 'YH': 0.5, 'YR': 0.3333333333333333} CpGbridge = {'CD': 0.5, 'CA': 0.5, 'CG': 0.5, 'CV': 0.5, 'CE': 0.5, 'DD': 0.5, 'DA': 0.5, 'DG': 0.5, 'DV': 0.5, 'DE': 0.5, 'SD': 0.3333333333333333, 'SA': 0.3333333333333333, 'SG': 0.3333333333333333, 'SV': 0.3333333333333333, 'SE': 0.3333333333333333, 'ND': 0.5, 'NA': 0.5, 'NG': 0.5, 'NV': 0.5, 'NE': 0.5, 'PD': 0.25, 'PA': 0.25, 'PG': 0.25, 'PV': 0.25, 'PE': 0.25, 'TD': 0.25, 'TA': 0.25, 'TG': 0.25, 'TV': 0.25, 'TE': 0.25, 'FD': 0.5, 'FA': 0.5, 'FG': 0.5, 'FV': 0.5, 'FE': 0.5, 'AD': 0.25, 'AA': 0.25, 'AG': 0.25, 'AV': 0.25, 'AE': 0.25, 'GD': 0.25, 'GA': 0.25, 'GG': 0.25, 'GV': 0.25, 'GE': 0.25, 'ID': 0.3333333333333333, 'IA': 0.3333333333333333, 'IG': 0.3333333333333333, 'IV': 0.3333333333333333, 'IE': 0.3333333333333333, 'LD': 0.16666666666666666, 'LA': 0.16666666666666666, 'LG': 0.16666666666666666, 'LV': 0.16666666666666666, 'LE': 0.16666666666666666, 'HD': 0.5, 'HA': 0.5, 'HG': 0.5, 'HV': 0.5, 'HE': 0.5, 'RD': 0.16666666666666666, 'RA': 0.16666666666666666, 'RG': 0.16666666666666666, 'RV': 0.16666666666666666, 'RE': 0.16666666666666666, 'VD': 0.25, 'VA': 0.25, 'VG': 0.25, 'VV': 0.25, 'VE': 0.25, 'YD': 0.5, 'YA': 0.5, 'YG': 0.5, 'YV': 0.5, 'YE': 0.5} CpUbridge = {'CC': 0.5, 'CS': 0.3333333333333333, 'CF': 0.5, 'CL': 0.16666666666666666, 'CW': 0.5, 'CY': 0.5, 'DC': 0.5, 'DS': 0.3333333333333333, 'DF': 0.5, 'DL': 0.16666666666666666, 'DW': 0.5, 'DY': 0.5, 'SC': 0.3333333333333333, 'SS': 0.2222222222222222, 'SF': 0.3333333333333333, 'SL': 0.1111111111111111, 'SW': 0.3333333333333333, 'SY': 0.3333333333333333, 'NC': 0.5, 'NS': 0.3333333333333333, 'NF': 0.5, 'NL': 0.16666666666666666, 'NW': 0.5, 'NY': 0.5, 'PC': 0.25, 'PS': 0.16666666666666666, 'PF': 0.25, 'PL': 0.08333333333333333, 'PW': 0.25, 'PY': 0.25, 'TC': 0.25, 'TS': 0.16666666666666666, 'TF': 0.25, 'TL': 0.08333333333333333, 'TW': 0.25, 'TY': 0.25, 'FC': 0.5, 'FS': 0.3333333333333333, 'FF': 0.5, 'FL': 0.16666666666666666, 'FW': 0.5, 'FY': 0.5, 'AC': 0.25, 'AS': 0.16666666666666666, 'AF': 0.25, 'AL': 0.08333333333333333, 'AW': 0.25, 'AY': 0.25, 'GC': 0.25, 'GS': 0.16666666666666666, 'GF': 0.25, 'GL': 0.08333333333333333, 'GW': 0.25, 'GY': 0.25, 'IC': 0.3333333333333333, 'IS': 0.2222222222222222, 'IF': 0.3333333333333333, 'IL': 0.1111111111111111, 'IW': 0.3333333333333333, 'IY': 0.3333333333333333, 'LC': 0.16666666666666666, 'LS': 0.1111111111111111, 'LF': 0.16666666666666666, 'LL': 0.05555555555555555, 'LW': 0.16666666666666666, 'LY': 0.16666666666666666, 'HC': 0.5, 'HS': 0.3333333333333333, 'HF': 0.5, 'HL': 0.16666666666666666, 'HW': 0.5, 'HY': 0.5, 'RC': 0.16666666666666666, 'RS': 0.1111111111111111, 'RF': 0.16666666666666666, 'RL': 0.05555555555555555, 'RW': 0.16666666666666666, 'RY': 0.16666666666666666, 'VC': 0.25, 'VS': 0.16666666666666666, 'VF': 0.25, 'VL': 0.08333333333333333, 'VW': 0.25, 'VY': 0.25, 'YC': 0.5, 'YS': 0.3333333333333333, 'YF': 0.5, 'YL': 0.16666666666666666, 'YW': 0.5, 'YY': 0.5} CpAbridge = {'CS': 0.16666666666666666, 'CM': 0.5, 'CN': 0.5, 'CK': 0.5, 'CT': 0.5, 'CI': 0.5, 'CR': 0.16666666666666666, 'DS': 0.16666666666666666, 'DM': 0.5, 'DN': 0.5, 'DK': 0.5, 'DT': 0.5, 'DI': 0.5, 'DR': 0.16666666666666666, 'SS': 0.1111111111111111, 'SM': 0.3333333333333333, 'SN': 0.3333333333333333, 'SK': 0.3333333333333333, 'ST': 0.3333333333333333, 'SI': 0.3333333333333333, 'SR': 0.1111111111111111, 'NS': 0.16666666666666666, 'NM': 0.5, 'NN': 0.5, 'NK': 0.5, 'NT': 0.5, 'NI': 0.5, 'NR': 0.16666666666666666, 'PS': 0.08333333333333333, 'PM': 0.25, 'PN': 0.25, 'PK': 0.25, 'PT': 0.25, 'PI': 0.25, 'PR': 0.08333333333333333, 'TS': 0.08333333333333333, 'TM': 0.25, 'TN': 0.25, 'TK': 0.25, 'TT': 0.25, 'TI': 0.25, 'TR': 0.08333333333333333, 'FS': 0.16666666666666666, 'FM': 0.5, 'FN': 0.5, 'FK': 0.5, 'FT': 0.5, 'FI': 0.5, 'FR': 0.16666666666666666, 'AS': 0.08333333333333333, 'AM': 0.25, 'AN': 0.25, 'AK': 0.25, 'AT': 0.25, 'AI': 0.25, 'AR': 0.08333333333333333, 'GS': 0.08333333333333333, 'GM': 0.25, 'GN': 0.25, 'GK': 0.25, 'GT': 0.25, 'GI': 0.25, 'GR': 0.08333333333333333, 'IS': 0.1111111111111111, 'IM': 0.3333333333333333, 'IN': 0.3333333333333333, 'IK': 0.3333333333333333, 'IT': 0.3333333333333333, 'II': 0.3333333333333333, 'IR': 0.1111111111111111, 'LS': 0.05555555555555555, 'LM': 0.16666666666666666, 'LN': 0.16666666666666666, 'LK': 0.16666666666666666, 'LT': 0.16666666666666666, 'LI': 0.16666666666666666, 'LR': 0.05555555555555555, 'HS': 0.16666666666666666, 'HM': 0.5, 'HN': 0.5, 'HK': 0.5, 'HT': 0.5, 'HI': 0.5, 'HR': 0.16666666666666666, 'RS': 0.05555555555555555, 'RM': 0.16666666666666666, 'RN': 0.16666666666666666, 'RK': 0.16666666666666666, 'RT': 0.16666666666666666, 'RI': 0.16666666666666666, 'RR': 0.05555555555555555, 'VS': 0.08333333333333333, 'VM': 0.25, 'VN': 0.25, 'VK': 0.25, 'VT': 0.25, 'VI': 0.25, 'VR': 0.08333333333333333, 'YS': 0.16666666666666666, 'YM': 0.5, 'YN': 0.5, 'YK': 0.5, 'YT': 0.5, 'YI': 0.5, 'YR': 0.16666666666666666} GpCbridge = {'SQ': 0.16666666666666666, 'SP': 0.16666666666666666, 'SL': 0.1111111111111111, 'SH': 0.16666666666666666, 'SR': 0.1111111111111111, 'QQ': 0.5, 'QP': 0.5, 'QL': 0.3333333333333333, 'QH': 0.5, 'QR': 0.3333333333333333, 'MQ': 1.0, 'MP': 1.0, 'ML': 0.6666666666666666, 'MH': 1.0, 'MR': 0.6666666666666666, 'PQ': 0.25, 'PP': 0.25, 'PL': 0.16666666666666666, 'PH': 0.25, 'PR': 0.16666666666666666, 'KQ': 0.5, 'KP': 0.5, 'KL': 0.3333333333333333, 'KH': 0.5, 'KR': 0.3333333333333333, 'TQ': 0.25, 'TP': 0.25, 'TL': 0.16666666666666666, 'TH': 0.25, 'TR': 0.16666666666666666, 'AQ': 0.25, 'AP': 0.25, 'AL': 0.16666666666666666, 'AH': 0.25, 'AR': 0.16666666666666666, 'GQ': 0.25, 'GP': 0.25, 'GL': 0.16666666666666666, 'GH': 0.25, 'GR': 0.16666666666666666, 'LQ': 0.3333333333333333, 'LP': 0.3333333333333333, 'LL': 0.2222222222222222, 'LH': 0.3333333333333333, 'LR': 0.2222222222222222, 'RQ': 0.3333333333333333, 'RP': 0.3333333333333333, 'RL': 0.2222222222222222, 'RH': 0.3333333333333333, 'RR': 0.2222222222222222, 'WQ': 1.0, 'WP': 1.0, 'WL': 0.6666666666666666, 'WH': 1.0, 'WR': 0.6666666666666666, 'VQ': 0.25, 'VP': 0.25, 'VL': 0.16666666666666666, 'VH': 0.25, 'VR': 0.16666666666666666, 'EQ': 0.5, 'EP': 0.5, 'EL': 0.3333333333333333, 'EH': 0.5, 'ER': 0.3333333333333333} GpGbridge = {'SD': 0.16666666666666666, 'SA': 0.16666666666666666, 'SG': 0.16666666666666666, 'SV': 0.16666666666666666, 'SE': 0.16666666666666666, 'QD': 0.5, 'QA': 0.5, 'QG': 0.5, 'QV': 0.5, 'QE': 0.5, 'MD': 1.0, 'MA': 1.0, 'MG': 1.0, 'MV': 1.0, 'ME': 1.0, 'PD': 0.25, 'PA': 0.25, 'PG': 0.25, 'PV': 0.25, 'PE': 0.25, 'KD': 0.5, 'KA': 0.5, 'KG': 0.5, 'KV': 0.5, 'KE': 0.5, 'TD': 0.25, 'TA': 0.25, 'TG': 0.25, 'TV': 0.25, 'TE': 0.25, 'AD': 0.25, 'AA': 0.25, 'AG': 0.25, 'AV': 0.25, 'AE': 0.25, 'GD': 0.25, 'GA': 0.25, 'GG': 0.25, 'GV': 0.25, 'GE': 0.25, 'LD': 0.3333333333333333, 'LA': 0.3333333333333333, 'LG': 0.3333333333333333, 'LV': 0.3333333333333333, 'LE': 0.3333333333333333, 'RD': 0.3333333333333333, 'RA': 0.3333333333333333, 'RG': 0.3333333333333333, 'RV': 0.3333333333333333, 'RE': 0.3333333333333333, 'WD': 1.0, 'WA': 1.0, 'WG': 1.0, 'WV': 1.0, 'WE': 1.0, 'VD': 0.25, 'VA': 0.25, 'VG': 0.25, 'VV': 0.25, 'VE': 0.25, 'ED': 0.5, 'EA': 0.5, 'EG': 0.5, 'EV': 0.5, 'EE': 0.5} GpUbridge = {'SC': 0.16666666666666666, 'SS': 0.1111111111111111, 'SF': 0.16666666666666666, 'SL': 0.05555555555555555, 'SW': 0.16666666666666666, 'SY': 0.16666666666666666, 'QC': 0.5, 'QS': 0.3333333333333333, 'QF': 0.5, 'QL': 0.16666666666666666, 'QW': 0.5, 'QY': 0.5, 'MC': 1.0, 'MS': 0.6666666666666666, 'MF': 1.0, 'ML': 0.3333333333333333, 'MW': 1.0, 'MY': 1.0, 'PC': 0.25, 'PS': 0.16666666666666666, 'PF': 0.25, 'PL': 0.08333333333333333, 'PW': 0.25, 'PY': 0.25, 'KC': 0.5, 'KS': 0.3333333333333333, 'KF': 0.5, 'KL': 0.16666666666666666, 'KW': 0.5, 'KY': 0.5, 'TC': 0.25, 'TS': 0.16666666666666666, 'TF': 0.25, 'TL': 0.08333333333333333, 'TW': 0.25, 'TY': 0.25, 'AC': 0.25, 'AS': 0.16666666666666666, 'AF': 0.25, 'AL': 0.08333333333333333, 'AW': 0.25, 'AY': 0.25, 'GC': 0.25, 'GS': 0.16666666666666666, 'GF': 0.25, 'GL': 0.08333333333333333, 'GW': 0.25, 'GY': 0.25, 'LC': 0.3333333333333333, 'LS': 0.2222222222222222, 'LF': 0.3333333333333333, 'LL': 0.1111111111111111, 'LW': 0.3333333333333333, 'LY': 0.3333333333333333, 'RC': 0.3333333333333333, 'RS': 0.2222222222222222, 'RF': 0.3333333333333333, 'RL': 0.1111111111111111, 'RW': 0.3333333333333333, 'RY': 0.3333333333333333, 'WC': 1.0, 'WS': 0.6666666666666666, 'WF': 1.0, 'WL': 0.3333333333333333, 'WW': 1.0, 'WY': 1.0, 'VC': 0.25, 'VS': 0.16666666666666666, 'VF': 0.25, 'VL': 0.08333333333333333, 'VW': 0.25, 'VY': 0.25, 'EC': 0.5, 'ES': 0.3333333333333333, 'EF': 0.5, 'EL': 0.16666666666666666, 'EW': 0.5, 'EY': 0.5} GpAbridge = {'SS': 0.05555555555555555, 'SM': 0.16666666666666666, 'SN': 0.16666666666666666, 'SK': 0.16666666666666666, 'ST': 0.16666666666666666, 'SI': 0.16666666666666666, 'SR': 0.05555555555555555, 'QS': 0.16666666666666666, 'QM': 0.5, 'QN': 0.5, 'QK': 0.5, 'QT': 0.5, 'QI': 0.5, 'QR': 0.16666666666666666, 'MS': 0.3333333333333333, 'MM': 1.0, 'MN': 1.0, 'MK': 1.0, 'MT': 1.0, 'MI': 1.0, 'MR': 0.3333333333333333, 'PS': 0.08333333333333333, 'PM': 0.25, 'PN': 0.25, 'PK': 0.25, 'PT': 0.25, 'PI': 0.25, 'PR': 0.08333333333333333, 'KS': 0.16666666666666666, 'KM': 0.5, 'KN': 0.5, 'KK': 0.5, 'KT': 0.5, 'KI': 0.5, 'KR': 0.16666666666666666, 'TS': 0.08333333333333333, 'TM': 0.25, 'TN': 0.25, 'TK': 0.25, 'TT': 0.25, 'TI': 0.25, 'TR': 0.08333333333333333, 'AS': 0.08333333333333333, 'AM': 0.25, 'AN': 0.25, 'AK': 0.25, 'AT': 0.25, 'AI': 0.25, 'AR': 0.08333333333333333, 'GS': 0.08333333333333333, 'GM': 0.25, 'GN': 0.25, 'GK': 0.25, 'GT': 0.25, 'GI': 0.25, 'GR': 0.08333333333333333, 'LS': 0.1111111111111111, 'LM': 0.3333333333333333, 'LN': 0.3333333333333333, 'LK': 0.3333333333333333, 'LT': 0.3333333333333333, 'LI': 0.3333333333333333, 'LR': 0.1111111111111111, 'RS': 0.1111111111111111, 'RM': 0.3333333333333333, 'RN': 0.3333333333333333, 'RK': 0.3333333333333333, 'RT': 0.3333333333333333, 'RI': 0.3333333333333333, 'RR': 0.1111111111111111, 'WS': 0.3333333333333333, 'WM': 1.0, 'WN': 1.0, 'WK': 1.0, 'WT': 1.0, 'WI': 1.0, 'WR': 0.3333333333333333, 'VS': 0.08333333333333333, 'VM': 0.25, 'VN': 0.25, 'VK': 0.25, 'VT': 0.25, 'VI': 0.25, 'VR': 0.08333333333333333, 'ES': 0.16666666666666666, 'EM': 0.5, 'EN': 0.5, 'EK': 0.5, 'ET': 0.5, 'EI': 0.5, 'ER': 0.16666666666666666} UpCbridge = {'CQ': 0.5, 'CP': 0.5, 'CL': 0.3333333333333333, 'CH': 0.5, 'CR': 0.3333333333333333, 'DQ': 0.5, 'DP': 0.5, 'DL': 0.3333333333333333, 'DH': 0.5, 'DR': 0.3333333333333333, 'SQ': 0.3333333333333333, 'SP': 0.3333333333333333, 'SL': 0.2222222222222222, 'SH': 0.3333333333333333, 'SR': 0.2222222222222222, 'NQ': 0.5, 'NP': 0.5, 'NL': 0.3333333333333333, 'NH': 0.5, 'NR': 0.3333333333333333, 'PQ': 0.25, 'PP': 0.25, 'PL': 0.16666666666666666, 'PH': 0.25, 'PR': 0.16666666666666666, 'TQ': 0.25, 'TP': 0.25, 'TL': 0.16666666666666666, 'TH': 0.25, 'TR': 0.16666666666666666, 'FQ': 0.5, 'FP': 0.5, 'FL': 0.3333333333333333, 'FH': 0.5, 'FR': 0.3333333333333333, 'AQ': 0.25, 'AP': 0.25, 'AL': 0.16666666666666666, 'AH': 0.25, 'AR': 0.16666666666666666, 'GQ': 0.25, 'GP': 0.25, 'GL': 0.16666666666666666, 'GH': 0.25, 'GR': 0.16666666666666666, 'IQ': 0.3333333333333333, 'IP': 0.3333333333333333, 'IL': 0.2222222222222222, 'IH': 0.3333333333333333, 'IR': 0.2222222222222222, 'LQ': 0.16666666666666666, 'LP': 0.16666666666666666, 'LL': 0.1111111111111111, 'LH': 0.16666666666666666, 'LR': 0.1111111111111111, 'HQ': 0.5, 'HP': 0.5, 'HL': 0.3333333333333333, 'HH': 0.5, 'HR': 0.3333333333333333, 'RQ': 0.16666666666666666, 'RP': 0.16666666666666666, 'RL': 0.1111111111111111, 'RH': 0.16666666666666666, 'RR': 0.1111111111111111, 'VQ': 0.25, 'VP': 0.25, 'VL': 0.16666666666666666, 'VH': 0.25, 'VR': 0.16666666666666666, 'YQ': 0.5, 'YP': 0.5, 'YL': 0.3333333333333333, 'YH': 0.5, 'YR': 0.3333333333333333} UpGbridge = {'CD': 0.5, 'CA': 0.5, 'CG': 0.5, 'CV': 0.5, 'CE': 0.5, 'DD': 0.5, 'DA': 0.5, 'DG': 0.5, 'DV': 0.5, 'DE': 0.5, 'SD': 0.3333333333333333, 'SA': 0.3333333333333333, 'SG': 0.3333333333333333, 'SV': 0.3333333333333333, 'SE': 0.3333333333333333, 'ND': 0.5, 'NA': 0.5, 'NG': 0.5, 'NV': 0.5, 'NE': 0.5, 'PD': 0.25, 'PA': 0.25, 'PG': 0.25, 'PV': 0.25, 'PE': 0.25, 'TD': 0.25, 'TA': 0.25, 'TG': 0.25, 'TV': 0.25, 'TE': 0.25, 'FD': 0.5, 'FA': 0.5, 'FG': 0.5, 'FV': 0.5, 'FE': 0.5, 'AD': 0.25, 'AA': 0.25, 'AG': 0.25, 'AV': 0.25, 'AE': 0.25, 'GD': 0.25, 'GA': 0.25, 'GG': 0.25, 'GV': 0.25, 'GE': 0.25, 'ID': 0.3333333333333333, 'IA': 0.3333333333333333, 'IG': 0.3333333333333333, 'IV': 0.3333333333333333, 'IE': 0.3333333333333333, 'LD': 0.16666666666666666, 'LA': 0.16666666666666666, 'LG': 0.16666666666666666, 'LV': 0.16666666666666666, 'LE': 0.16666666666666666, 'HD': 0.5, 'HA': 0.5, 'HG': 0.5, 'HV': 0.5, 'HE': 0.5, 'RD': 0.16666666666666666, 'RA': 0.16666666666666666, 'RG': 0.16666666666666666, 'RV': 0.16666666666666666, 'RE': 0.16666666666666666, 'VD': 0.25, 'VA': 0.25, 'VG': 0.25, 'VV': 0.25, 'VE': 0.25, 'YD': 0.5, 'YA': 0.5, 'YG': 0.5, 'YV': 0.5, 'YE': 0.5} UpUbridge = {'CC': 0.5, 'CS': 0.3333333333333333, 'CF': 0.5, 'CL': 0.16666666666666666, 'CW': 0.5, 'CY': 0.5, 'DC': 0.5, 'DS': 0.3333333333333333, 'DF': 0.5, 'DL': 0.16666666666666666, 'DW': 0.5, 'DY': 0.5, 'SC': 0.3333333333333333, 'SS': 0.2222222222222222, 'SF': 0.3333333333333333, 'SL': 0.1111111111111111, 'SW': 0.3333333333333333, 'SY': 0.3333333333333333, 'NC': 0.5, 'NS': 0.3333333333333333, 'NF': 0.5, 'NL': 0.16666666666666666, 'NW': 0.5, 'NY': 0.5, 'PC': 0.25, 'PS': 0.16666666666666666, 'PF': 0.25, 'PL': 0.08333333333333333, 'PW': 0.25, 'PY': 0.25, 'TC': 0.25, 'TS': 0.16666666666666666, 'TF': 0.25, 'TL': 0.08333333333333333, 'TW': 0.25, 'TY': 0.25, 'FC': 0.5, 'FS': 0.3333333333333333, 'FF': 0.5, 'FL': 0.16666666666666666, 'FW': 0.5, 'FY': 0.5, 'AC': 0.25, 'AS': 0.16666666666666666, 'AF': 0.25, 'AL': 0.08333333333333333, 'AW': 0.25, 'AY': 0.25, 'GC': 0.25, 'GS': 0.16666666666666666, 'GF': 0.25, 'GL': 0.08333333333333333, 'GW': 0.25, 'GY': 0.25, 'IC': 0.3333333333333333, 'IS': 0.2222222222222222, 'IF': 0.3333333333333333, 'IL': 0.1111111111111111, 'IW': 0.3333333333333333, 'IY': 0.3333333333333333, 'LC': 0.16666666666666666, 'LS': 0.1111111111111111, 'LF': 0.16666666666666666, 'LL': 0.05555555555555555, 'LW': 0.16666666666666666, 'LY': 0.16666666666666666, 'HC': 0.5, 'HS': 0.3333333333333333, 'HF': 0.5, 'HL': 0.16666666666666666, 'HW': 0.5, 'HY': 0.5, 'RC': 0.16666666666666666, 'RS': 0.1111111111111111, 'RF': 0.16666666666666666, 'RL': 0.05555555555555555, 'RW': 0.16666666666666666, 'RY': 0.16666666666666666, 'VC': 0.25, 'VS': 0.16666666666666666, 'VF': 0.25, 'VL': 0.08333333333333333, 'VW': 0.25, 'VY': 0.25, 'YC': 0.5, 'YS': 0.3333333333333333, 'YF': 0.5, 'YL': 0.16666666666666666, 'YW': 0.5, 'YY': 0.5} UpAbridge = {'CS': 0.16666666666666666, 'CM': 0.5, 'CN': 0.5, 'CK': 0.5, 'CT': 0.5, 'CI': 0.5, 'CR': 0.16666666666666666, 'DS': 0.16666666666666666, 'DM': 0.5, 'DN': 0.5, 'DK': 0.5, 'DT': 0.5, 'DI': 0.5, 'DR': 0.16666666666666666, 'SS': 0.1111111111111111, 'SM': 0.3333333333333333, 'SN': 0.3333333333333333, 'SK': 0.3333333333333333, 'ST': 0.3333333333333333, 'SI': 0.3333333333333333, 'SR': 0.1111111111111111, 'NS': 0.16666666666666666, 'NM': 0.5, 'NN': 0.5, 'NK': 0.5, 'NT': 0.5, 'NI': 0.5, 'NR': 0.16666666666666666, 'PS': 0.08333333333333333, 'PM': 0.25, 'PN': 0.25, 'PK': 0.25, 'PT': 0.25, 'PI': 0.25, 'PR': 0.08333333333333333, 'TS': 0.08333333333333333, 'TM': 0.25, 'TN': 0.25, 'TK': 0.25, 'TT': 0.25, 'TI': 0.25, 'TR': 0.08333333333333333, 'FS': 0.16666666666666666, 'FM': 0.5, 'FN': 0.5, 'FK': 0.5, 'FT': 0.5, 'FI': 0.5, 'FR': 0.16666666666666666, 'AS': 0.08333333333333333, 'AM': 0.25, 'AN': 0.25, 'AK': 0.25, 'AT': 0.25, 'AI': 0.25, 'AR': 0.08333333333333333, 'GS': 0.08333333333333333, 'GM': 0.25, 'GN': 0.25, 'GK': 0.25, 'GT': 0.25, 'GI': 0.25, 'GR': 0.08333333333333333, 'IS': 0.1111111111111111, 'IM': 0.3333333333333333, 'IN': 0.3333333333333333, 'IK': 0.3333333333333333, 'IT': 0.3333333333333333, 'II': 0.3333333333333333, 'IR': 0.1111111111111111, 'LS': 0.05555555555555555, 'LM': 0.16666666666666666, 'LN': 0.16666666666666666, 'LK': 0.16666666666666666, 'LT': 0.16666666666666666, 'LI': 0.16666666666666666, 'LR': 0.05555555555555555, 'HS': 0.16666666666666666, 'HM': 0.5, 'HN': 0.5, 'HK': 0.5, 'HT': 0.5, 'HI': 0.5, 'HR': 0.16666666666666666, 'RS': 0.05555555555555555, 'RM': 0.16666666666666666, 'RN': 0.16666666666666666, 'RK': 0.16666666666666666, 'RT': 0.16666666666666666, 'RI': 0.16666666666666666, 'RR': 0.05555555555555555, 'VS': 0.08333333333333333, 'VM': 0.25, 'VN': 0.25, 'VK': 0.25, 'VT': 0.25, 'VI': 0.25, 'VR': 0.08333333333333333, 'YS': 0.16666666666666666, 'YM': 0.5, 'YN': 0.5, 'YK': 0.5, 'YT': 0.5, 'YI': 0.5, 'YR': 0.16666666666666666} ApCbridge = {'SQ': 0.16666666666666666, 'SP': 0.16666666666666666, 'SL': 0.1111111111111111, 'SH': 0.16666666666666666, 'SR': 0.1111111111111111, 'QQ': 0.5, 'QP': 0.5, 'QL': 0.3333333333333333, 'QH': 0.5, 'QR': 0.3333333333333333, 'PQ': 0.25, 'PP': 0.25, 'PL': 0.16666666666666666, 'PH': 0.25, 'PR': 0.16666666666666666, 'KQ': 0.5, 'KP': 0.5, 'KL': 0.3333333333333333, 'KH': 0.5, 'KR': 0.3333333333333333, 'TQ': 0.25, 'TP': 0.25, 'TL': 0.16666666666666666, 'TH': 0.25, 'TR': 0.16666666666666666, 'AQ': 0.25, 'AP': 0.25, 'AL': 0.16666666666666666, 'AH': 0.25, 'AR': 0.16666666666666666, 'GQ': 0.25, 'GP': 0.25, 'GL': 0.16666666666666666, 'GH': 0.25, 'GR': 0.16666666666666666, 'IQ': 0.3333333333333333, 'IP': 0.3333333333333333, 'IL': 0.2222222222222222, 'IH': 0.3333333333333333, 'IR': 0.2222222222222222, 'LQ': 0.3333333333333333, 'LP': 0.3333333333333333, 'LL': 0.2222222222222222, 'LH': 0.3333333333333333, 'LR': 0.2222222222222222, 'RQ': 0.3333333333333333, 'RP': 0.3333333333333333, 'RL': 0.2222222222222222, 'RH': 0.3333333333333333, 'RR': 0.2222222222222222, 'VQ': 0.25, 'VP': 0.25, 'VL': 0.16666666666666666, 'VH': 0.25, 'VR': 0.16666666666666666, 'EQ': 0.5, 'EP': 0.5, 'EL': 0.3333333333333333, 'EH': 0.5, 'ER': 0.3333333333333333} ApGbridge = {'SD': 0.16666666666666666, 'SA': 0.16666666666666666, 'SG': 0.16666666666666666, 'SV': 0.16666666666666666, 'SE': 0.16666666666666666, 'QD': 0.5, 'QA': 0.5, 'QG': 0.5, 'QV': 0.5, 'QE': 0.5, 'PD': 0.25, 'PA': 0.25, 'PG': 0.25, 'PV': 0.25, 'PE': 0.25, 'KD': 0.5, 'KA': 0.5, 'KG': 0.5, 'KV': 0.5, 'KE': 0.5, 'TD': 0.25, 'TA': 0.25, 'TG': 0.25, 'TV': 0.25, 'TE': 0.25, 'AD': 0.25, 'AA': 0.25, 'AG': 0.25, 'AV': 0.25, 'AE': 0.25, 'GD': 0.25, 'GA': 0.25, 'GG': 0.25, 'GV': 0.25, 'GE': 0.25, 'ID': 0.3333333333333333, 'IA': 0.3333333333333333, 'IG': 0.3333333333333333, 'IV': 0.3333333333333333, 'IE': 0.3333333333333333, 'LD': 0.3333333333333333, 'LA': 0.3333333333333333, 'LG': 0.3333333333333333, 'LV': 0.3333333333333333, 'LE': 0.3333333333333333, 'RD': 0.3333333333333333, 'RA': 0.3333333333333333, 'RG': 0.3333333333333333, 'RV': 0.3333333333333333, 'RE': 0.3333333333333333, 'VD': 0.25, 'VA': 0.25, 'VG': 0.25, 'VV': 0.25, 'VE': 0.25, 'ED': 0.5, 'EA': 0.5, 'EG': 0.5, 'EV': 0.5, 'EE': 0.5} ApUbridge = {'SC': 0.16666666666666666, 'SS': 0.1111111111111111, 'SF': 0.16666666666666666, 'SL': 0.05555555555555555, 'SW': 0.16666666666666666, 'SY': 0.16666666666666666, 'QC': 0.5, 'QS': 0.3333333333333333, 'QF': 0.5, 'QL': 0.16666666666666666, 'QW': 0.5, 'QY': 0.5, 'PC': 0.25, 'PS': 0.16666666666666666, 'PF': 0.25, 'PL': 0.08333333333333333, 'PW': 0.25, 'PY': 0.25, 'KC': 0.5, 'KS': 0.3333333333333333, 'KF': 0.5, 'KL': 0.16666666666666666, 'KW': 0.5, 'KY': 0.5, 'TC': 0.25, 'TS': 0.16666666666666666, 'TF': 0.25, 'TL': 0.08333333333333333, 'TW': 0.25, 'TY': 0.25, 'AC': 0.25, 'AS': 0.16666666666666666, 'AF': 0.25, 'AL': 0.08333333333333333, 'AW': 0.25, 'AY': 0.25, 'GC': 0.25, 'GS': 0.16666666666666666, 'GF': 0.25, 'GL': 0.08333333333333333, 'GW': 0.25, 'GY': 0.25, 'IC': 0.3333333333333333, 'IS': 0.2222222222222222, 'IF': 0.3333333333333333, 'IL': 0.1111111111111111, 'IW': 0.3333333333333333, 'IY': 0.3333333333333333, 'LC': 0.3333333333333333, 'LS': 0.2222222222222222, 'LF': 0.3333333333333333, 'LL': 0.1111111111111111, 'LW': 0.3333333333333333, 'LY': 0.3333333333333333, 'RC': 0.3333333333333333, 'RS': 0.2222222222222222, 'RF': 0.3333333333333333, 'RL': 0.1111111111111111, 'RW': 0.3333333333333333, 'RY': 0.3333333333333333, 'VC': 0.25, 'VS': 0.16666666666666666, 'VF': 0.25, 'VL': 0.08333333333333333, 'VW': 0.25, 'VY': 0.25, 'EC': 0.5, 'ES': 0.3333333333333333, 'EF': 0.5, 'EL': 0.16666666666666666, 'EW': 0.5, 'EY': 0.5} ApAbridge = {'SS': 0.05555555555555555, 'SM': 0.16666666666666666, 'SN': 0.16666666666666666, 'SK': 0.16666666666666666, 'ST': 0.16666666666666666, 'SI': 0.16666666666666666, 'SR': 0.05555555555555555, 'QS': 0.16666666666666666, 'QM': 0.5, 'QN': 0.5, 'QK': 0.5, 'QT': 0.5, 'QI': 0.5, 'QR': 0.16666666666666666, 'PS': 0.08333333333333333, 'PM': 0.25, 'PN': 0.25, 'PK': 0.25, 'PT': 0.25, 'PI': 0.25, 'PR': 0.08333333333333333, 'KS': 0.16666666666666666, 'KM': 0.5, 'KN': 0.5, 'KK': 0.5, 'KT': 0.5, 'KI': 0.5, 'KR': 0.16666666666666666, 'TS': 0.08333333333333333, 'TM': 0.25, 'TN': 0.25, 'TK': 0.25, 'TT': 0.25, 'TI': 0.25, 'TR': 0.08333333333333333, 'AS': 0.08333333333333333, 'AM': 0.25, 'AN': 0.25, 'AK': 0.25, 'AT': 0.25, 'AI': 0.25, 'AR': 0.08333333333333333, 'GS': 0.08333333333333333, 'GM': 0.25, 'GN': 0.25, 'GK': 0.25, 'GT': 0.25, 'GI': 0.25, 'GR': 0.08333333333333333, 'IS': 0.1111111111111111, 'IM': 0.3333333333333333, 'IN': 0.3333333333333333, 'IK': 0.3333333333333333, 'IT': 0.3333333333333333, 'II': 0.3333333333333333, 'IR': 0.1111111111111111, 'LS': 0.1111111111111111, 'LM': 0.3333333333333333, 'LN': 0.3333333333333333, 'LK': 0.3333333333333333, 'LT': 0.3333333333333333, 'LI': 0.3333333333333333, 'LR': 0.1111111111111111, 'RS': 0.1111111111111111, 'RM': 0.3333333333333333, 'RN': 0.3333333333333333, 'RK': 0.3333333333333333, 'RT': 0.3333333333333333, 'RI': 0.3333333333333333, 'RR': 0.1111111111111111, 'VS': 0.08333333333333333, 'VM': 0.25, 'VN': 0.25, 'VK': 0.25, 'VT': 0.25, 'VI': 0.25, 'VR': 0.08333333333333333, 'ES': 0.16666666666666666, 'EM': 0.5, 'EN': 0.5, 'EK': 0.5, 'ET': 0.5, 'EI': 0.5, 'ER': 0.16666666666666666} syco = { "C": ["TGT", "TGC"], "D": ["GAT", "GAC"], "S": ["TCT", "TCG", "TCA", "TCC", "AGC", "AGT"], "Q": ["CAA", "CAG"], "M": ["ATG"], "N": ["AAC", "AAT"], "P": ["CCT", "CCG", "CCA", "CCC"], "K": ["AAG", "AAA"], "T": ["ACC", "ACA", "ACG", "ACT"], "F": ["TTT", "TTC"], "A": ["GCA", "GCC", "GCG", "GCT"], "G": ["GGT", "GGG", "GGA", "GGC"], "I": ["ATC", "ATA", "ATT"], "L": ["TTA", "TTG", "CTC", "CTT", "CTG", "CTA"], "H": ["CAT", "CAC"], "R": ["CGA", "CGC", "CGG", "CGT", "AGG", "AGA"], "W": ["TGG"], "V": ["GTA", "GTC", "GTG", "GTT"], "E": ["GAG", "GAA"], "Y": ["TAT", "TAC"]} ################################### #### LISTS #### #non-informative dinucleotide positions that will be excluded noninfo = ['CpCpos1', 'CpApos1', 'GpCpos1', 'GpGpos1', 'GpUpos1', 'GpApos1', 'UpGpos1', 'UpApos1', 'ApCpos1', 'ApUpos1', 'ApApos1'] ############################ #dinucl should be a list like: ['CpC', 'CpG', 'CpU', 'CpA', 'GpC', 'GpG', 'GpU', 'GpA', 'UpC', 'UpG', 'UpU', 'UpA', 'ApC', 'ApG', 'ApU', 'ApA'] #position should also be a list: ['pos1', 'pos2', 'bridge'] ########################## #dinucl should be a list like: ['CpC', 'CpG', 'CpU', 'CpA', 'GpC', 'GpG', 'GpU', 'GpA', 'UpC', 'UpG', 'UpU', 'UpA', 'ApC', 'ApG', 'ApU', 'ApA'] #position should also be a list: ['pos1', 'pos2', 'bridge'] ########################## #### TABLE #### ##########################
[ 6738, 16024, 1330, 1001, 80, 9399, 198, 6738, 16024, 13, 4653, 80, 1330, 1001, 80, 198, 11748, 4738, 198, 11748, 10688, 628, 198, 29113, 14468, 7804, 21017, 198, 14468, 21017, 220, 220, 220, 220, 220, 220, 220, 220, 9834, 52, 220, 220...
2.085448
13,002
import string # convert text in lyrics to lower case and removes all punctuations # e.g !"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ with open("lyricsData.txt","x",encoding="UTF-8") as new: with open("lyrics.txt","r") as lines: for line in lines: line = line.lower() # convert words to lower case words = line.split() strip = str.maketrans("","",string.punctuation) stripped = [w.translate(strip) for w in words] # remove all punctuations # save lower case stripped words to new file new.writelines(" ".join(stripped)) new.writelines("\n")
[ 11748, 4731, 198, 198, 2, 10385, 2420, 287, 15844, 284, 2793, 1339, 290, 20694, 477, 21025, 6055, 198, 2, 304, 13, 70, 220, 2474, 29953, 4, 5, 43054, 3419, 9, 10, 12095, 19571, 25, 26, 27, 14804, 30, 31, 58, 6852, 60, 61, 62, 63...
2.291367
278
import os from unittest import TestCase from pathlib import Path import PIL import torch import clip import numpy as np from clip_mania.core.executor import ModelExecutor from clip_mania.utils.data.preprocess import DatasetProcessor
[ 11748, 28686, 198, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 350, 4146, 198, 198, 11748, 28034, 198, 11748, 10651, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 106...
3.380282
71
import click from popper import __version__ as popper_version from popper.cli import pass_context, log @click.command('version', short_help='Show version of Popper and exit.') @pass_context def cli(ctx): """Displays version of Popper and exit. """ # Args: # ctx(Popper.cli.context): For process inter-command communication # context is used.For reference visit # https://click.palletsprojects.com/en/7.x/commands/#nested-handling-and-contexts . # Returns: # None log.info(f'Popper version {popper_version}')
[ 11748, 3904, 198, 198, 6738, 745, 2848, 1330, 11593, 9641, 834, 355, 745, 2848, 62, 9641, 198, 6738, 745, 2848, 13, 44506, 1330, 1208, 62, 22866, 11, 2604, 628, 198, 31, 12976, 13, 21812, 10786, 9641, 3256, 1790, 62, 16794, 11639, 153...
2.701422
211
# Copyright 2017 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import collections import ddt import mock from neutronclient.common import exceptions as n_exc from oslo_config import cfg as oslo_cfg from oslo_serialization import jsonutils from oslo_utils import uuidutils from os_vif.objects import vif as osv_vif from kuryr_kubernetes import constants from kuryr_kubernetes.controller.drivers import nested_vlan_vif from kuryr_kubernetes.controller.drivers import neutron_vif from kuryr_kubernetes.controller.drivers import vif_pool from kuryr_kubernetes import exceptions from kuryr_kubernetes import os_vif_util as ovu from kuryr_kubernetes.tests import base as test_base from kuryr_kubernetes.tests.unit import kuryr_fixtures as k_fix @ddt.ddt @ddt.ddt @ddt.ddt
[ 2, 15069, 2177, 2297, 10983, 11, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, ...
3.235589
399
import os import platform from pathlib import Path ROOT = os.path.abspath(os.path.dirname(__file__)) def find_platform_location(dir_type): """ Attempt to find and create operating system data folders """ if platform.system() == "Linux": home_dir = os.path.expanduser("~") if dir_type == "config": xdg_dir = os.environ.get("XDG_CONFIG_HOME") or os.path.join(home_dir, ".config") elif dir_type == "data": xdg_dir = os.environ.get("XDG_DATA_HOME") or os.path.join(home_dir, ".local/share") ev3sim_dir = os.path.join(xdg_dir, "ev3sim") Path(ev3sim_dir).mkdir(parents=True, exist_ok=True) return ev3sim_dir return None def find_abs(filepath, allowed_areas=None): """ Attempt to find a reference file, from this list of appropriate places specified. allowed_areas can contain: - package: search from root level of package - package/path: search from path in package - workspace: search from workspace - workspace/path: search from path in workspace - local|path: search from current execution context (can be an absolute path or relative one) areas leftmost will be considered first. this defaults to local, then package. """ from ev3sim.simulation.loader import StateHandler if allowed_areas is None: allowed_areas = ["workspace", "local", "package"] workspace_missing = False if StateHandler.WORKSPACE_FOLDER: WORKSPACE = os.path.abspath(StateHandler.WORKSPACE_FOLDER) for area in allowed_areas: if area.startswith("workspace"): if not os.path.exists(WORKSPACE): workspace_missing = True break else: WORKSPACE = "" for area in allowed_areas: if area == "package": path = os.path.join(ROOT, filepath) elif area.startswith("package"): path = os.path.join(ROOT, area[8:], filepath) elif area == "workspace": if not WORKSPACE: continue path = os.path.join(WORKSPACE, filepath) elif area.startswith("workspace"): if not WORKSPACE: continue path = os.path.join(WORKSPACE, area[10:], filepath) elif area.startswith("platform"): if area.startswith("platform/config"): pl = find_platform_location("config") if pl is None: continue path = os.path.join(pl, area[16:], filepath) elif area.startswith("platform/data"): pl = find_platform_location("data") if pl is None: continue path = os.path.join(pl, area[14:], filepath) elif area == "local": path = filepath elif area.startswith("local"): path = os.path.join(area[6:], filepath) else: raise ValueError(f"Unknown file area {area}") if os.path.isdir(path) or os.path.isfile(path): return path if workspace_missing: # We got problems with workspace from user_config. import yaml from ev3sim.visual.manager import ScreenObjectManager from ev3sim.search_locations import config_locations ScreenObjectManager.instance.forceCloseError( "Your workspace location is incorrect. This could be a bug in the system, or you renaming some folders. Click the Fix button if you want ev3sim to attempt to fix this.", ("Fix", fix), ) raise WorkspaceError() raise ValueError(f"File not found: {filepath}")
[ 11748, 28686, 198, 11748, 3859, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 13252, 2394, 796, 28686, 13, 6978, 13, 397, 2777, 776, 7, 418, 13, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 4008, 628, 198, 198, 4299, 1064, 62, 24254, 6...
2.259191
1,632
import attr from pyspark import StorageLevel from geo_pyspark.core.jvm.abstract import JvmObject from geo_pyspark.register.java_libs import GeoSparkLib from geo_pyspark.utils.decorators import require @attr.s
[ 11748, 708, 81, 198, 6738, 279, 893, 20928, 1330, 20514, 4971, 198, 198, 6738, 40087, 62, 79, 893, 20928, 13, 7295, 13, 73, 14761, 13, 397, 8709, 1330, 449, 14761, 10267, 198, 6738, 40087, 62, 79, 893, 20928, 13, 30238, 13, 12355, 6...
2.944444
72
# MIT License # # Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020 # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the # Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from __future__ import absolute_import, division, print_function, unicode_literals import logging import unittest import importlib import numpy as np import tensorflow as tf from tests.utils import TestBase, master_seed object_detection_spec = importlib.util.find_spec("object_detection") object_detection_found = object_detection_spec is not None logger = logging.getLogger(__name__) @unittest.skipIf( not object_detection_found, reason="Skip unittests if object detection module is not found because of pre-trained model.", ) @unittest.skipIf( tf.__version__[0] == "2" or (tf.__version__[0] == "1" and tf.__version__.split(".")[1] != "15"), reason="Skip unittests if not TensorFlow v1.15 because of pre-trained model.", ) class TestTensorFlowFasterRCNN(TestBase): """ This class tests the TensorFlowFasterRCNN object detector. """ @classmethod if __name__ == "__main__": unittest.main()
[ 2, 17168, 13789, 198, 2, 198, 2, 15069, 357, 34, 8, 383, 1215, 690, 36098, 3851, 436, 1108, 16984, 3524, 357, 7227, 8, 46665, 12131, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257...
3.399015
609
""" A IceController Module """ from masonite.controllers import Controller from masonite.request import Request from app.Ice import Ice
[ 37811, 317, 6663, 22130, 19937, 37227, 198, 198, 6738, 285, 888, 578, 13, 3642, 36667, 1330, 22741, 198, 6738, 285, 888, 578, 13, 25927, 1330, 19390, 198, 6738, 598, 13, 23709, 1330, 6663, 198 ]
4.029412
34
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class TaskInformation(Model): """Information about a task running on a compute node. :param task_url: The URL of the task. :type task_url: str :param job_id: The id of the job to which the task belongs. :type job_id: str :param task_id: The id of the task. :type task_id: str :param subtask_id: The id of the subtask if the task is a multi-instance task. :type subtask_id: int :param task_state: The current state of the task. Possible values include: 'active', 'preparing', 'running', 'completed' :type task_state: str or :class:`TaskState <azure.batch.models.TaskState>` :param execution_info: Information about the execution of the task. :type execution_info: :class:`TaskExecutionInformation <azure.batch.models.TaskExecutionInformation>` """ _validation = { 'task_state': {'required': True}, } _attribute_map = { 'task_url': {'key': 'taskUrl', 'type': 'str'}, 'job_id': {'key': 'jobId', 'type': 'str'}, 'task_id': {'key': 'taskId', 'type': 'str'}, 'subtask_id': {'key': 'subtaskId', 'type': 'int'}, 'task_state': {'key': 'taskState', 'type': 'TaskState'}, 'execution_info': {'key': 'executionInfo', 'type': 'TaskExecutionInformation'}, }
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 16529, 35937, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 198, 2, 5964, 1321...
2.988411
604
#! /usr/bin/env python3 import re with open('input/day5') as input: polymer = list(map(lambda x: x.strip(), input.readlines()))[0] x = polymer x = react(x) print("Part 1: %d" % len(x)) shortest = len(polymer) begin = ord('a') for i in range(26): x = polymer lower, upper = chr(begin + i), chr(begin + i).upper() removed = x.replace(lower, '') removed = removed.replace(upper, '') reacted = react(removed) length = len(reacted) print("%s/%s: %d" % (lower, upper, length)) if length < shortest: shortest = length print("Part 2: %d" % shortest)
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 302, 198, 198, 4480, 1280, 10786, 15414, 14, 820, 20, 11537, 355, 5128, 25, 198, 197, 35428, 647, 796, 1351, 7, 8899, 7, 50033, 2124, 25, 2124, 13, 36311, 22784, 5128, ...
2.488889
225
import os # comment char _COMMENT_CHAR = '#' def read_list_from_file(fn: str, items_per_line=None, separator=None, comment_char=_COMMENT_CHAR): """ Read a list from given file Note: list file is organized by lines, comments are started with _COMMENT_CHAR :param fn: file name :param items_per_line: number of items per line :param separator: separator. Using space char when None :param comment_char: char indicating comment :return: """ # check parameters assert os.path.exists(fn), "{} does not exist".format(fn) assert (items_per_line is None) or (items_per_line > 0) # store result result = [] # read file with open(fn, 'r') as f: # handle lines while True: line = f.readline() if not line: break line = line.strip() if line.startswith(comment_char): continue result.append(get_items(line)) # return result return result
[ 11748, 28686, 628, 198, 2, 2912, 1149, 198, 62, 9858, 10979, 62, 38019, 796, 705, 2, 6, 628, 198, 4299, 1100, 62, 4868, 62, 6738, 62, 7753, 7, 22184, 25, 965, 11, 3709, 62, 525, 62, 1370, 28, 14202, 11, 2880, 1352, 28, 14202, 11...
2.404762
420
from . import ( social_media, code_hosting, code_packaging, website_analytics, outputs, email, forums, forum_categories, example ) __all__ = ['social_media', 'code_hosting', 'code_packaging', 'website_analytics', 'outputs', 'email', 'forums', 'forum_categories', 'example']
[ 6738, 764, 1330, 357, 198, 220, 220, 220, 1919, 62, 11431, 11, 198, 220, 220, 220, 2438, 62, 4774, 278, 11, 198, 220, 220, 220, 2438, 62, 8002, 3039, 11, 198, 220, 220, 220, 3052, 62, 38200, 14094, 11, 198, 220, 220, 220, 23862, ...
2.296552
145
from qubiter.SEO_writer import * import qubiter.utilities_gen as utg from shutil import copyfile class CodaSEO_writer(SEO_writer): """ This class is a child of class `SEO_writer`. The constructor of this class accepts as input the paths to a pair of well-formed initial English and Picture files. The class makes copies of those 2 initial files and opens the copies, called the final English and Picture files, in the append mode. Thereafter, the user can write to those final files using methods that this class inherits from its parent SEO_writer. Coda SEO writer means tail-end SEO writer, which accurately describes what this class does. Attributes ---------- fin_eng_path : str path to final English file that starts life as a verbatim copy of the initial English file and is thereafter appended to. fin_pic_path : str path to final Picture file that starts life as a verbatim copy of the initial Picture file and is thereafter appended to. """ def __init__(self, init_file_prefix, fin_file_prefix, num_bits, ZL=True, fin_emb=None): """ Parameters ---------- init_file_prefix : str fin_file_prefix : str num_bits : int ZL : bool fin_emb : CktEmbedder circuit embedder for the writer of the final English and Picture files Returns ------- """ assert init_file_prefix != fin_file_prefix,\ "intial and final file prefixes can't be the same." ZL_str = 'ZL' if ZL else 'ZF' init_eng_path = eng_path(init_file_prefix) fin_eng_path = eng_path(fin_file_prefix) self.fin_eng_path = fin_eng_path init_pic_path = pic_path(init_file_prefix) fin_pic_path = pic_path(fin_file_prefix) self.fin_pic_path = fin_pic_path # copying files try: copyfile(utg.preface(init_eng_path), utg.preface(fin_eng_path)) except: assert False, 'Could not copy file\n' + init_eng_path try: copyfile(utg.preface(init_pic_path), utg.preface(fin_pic_path)) except: assert False, 'Could not copy file\n' + init_pic_path # opening copies of files try: fin_eng_out = open(utg.preface(fin_eng_path), 'a') except: assert False, 'Could not open file\n' + fin_eng_path try: fin_pic_out = open(utg.preface(fin_pic_path), 'a') except: assert False, 'Could not open file\n' + fin_pic_path emb = CktEmbedder(num_bits, num_bits) if fin_emb: emb = fin_emb SEO_writer.__init__(self, fin_file_prefix, emb, ZL=ZL, english_out=fin_eng_out, picture_out=fin_pic_out) def write_xy_measurements(self, bit_pos_to_xy_str, write_notas=True): """ This method will append to the final English and Picture files a SEO of rotations, one rotation at each key of the input dictionary `bit_pos_to_xy_str`. That input dictionary `bit_pos_to_xy_str` maps qubit positions (int) to xy str values that are: either 'X' or 'Y'. Let sigx, sigy and sigz be the Pauli matrices. When key=b and value='X', a rotation exp(i*sigy*pi/4) is applied to qubit b. This rotation is chosen because it diagonalizes sigx, according to the equation: exp(-i*sigy*pi/4)*sigz*exp(i*sigy*pi/4) = sigx. When key=b and value='Y', a rotation exp(-i*sigx*pi/4) is applied to qubit b. This rotation is chosen because it diagonalizes sigy, according to the equation: exp(i*sigx*pi/4)*sigz*exp(-i*sigx*pi/4) = sigy. These rotations are applied in order to convert an X or Y qubit measurement into the standard Z measurements which are along the eigenvectors of sigz. There is no need to apply any rotations when Z is measured because the operating qubit basis is already the eigenvectors of sigz. Parameters ---------- bit_pos_to_xy_str : dict[int, str] write_notas : bool whether to write a NOTA before each rotation explaining it Returns ------- None """ for bit_pos, xy_str in bit_pos_to_xy_str.items(): if xy_str == 'X': if write_notas: self.write_NOTA("change |0_X>, |1_X> to |0>, |1>") # exp(-i*sigy*pi/4)*sigz*exp(i*sigy*pi/4) = sigx self.write_Ry(bit_pos, np.pi/4) elif xy_str == 'Y': if write_notas: self.write_NOTA("change |0_Y>, |1_Y> to |0>, |1>") # exp(i*sigx*pi/4)*sigz*exp(-i*sigx*pi/4) = sigy self.write_Rx(bit_pos, -np.pi/4) else: assert False, "Unsupported qbit measurement. '" + \ xy_str + "' Should be either 'X' or 'Y'" if __name__ == "__main__": main()
[ 6738, 627, 2545, 263, 13, 50, 4720, 62, 16002, 1330, 1635, 198, 11748, 627, 2545, 263, 13, 315, 2410, 62, 5235, 355, 3384, 70, 198, 6738, 4423, 346, 1330, 4866, 7753, 628, 198, 4871, 327, 11329, 50, 4720, 62, 16002, 7, 50, 4720, 6...
2.139095
2,430
from pprint import pprint from string import Template from decoderGenerator import getDecodeTree, getSwitch opCodes = { "00 000000": ("", "NOP", []), "00 001000": ("", "LD ${N}, SP", []), "00 RR 0001": ("", "LD ${R}, ${N}", []), "00 RR 1001": ("", "ADD HL, ${R}", []), "00 0r 0 010": ("", "LD ${R}, A", []), "00 0r 1 010": ("", "LD A, ${R}", []), "00 RR 0 011": ("", "INC ${R}", []), "00 RR 1 011": ("", "DEC ${R}", []), "00 DDD 10 0": ("", "INC ${D}", []), "00 DDD 10 1": ("", "DEC ${D}", []), "00 DDD 110": ("", "LD ${D}, ${N}", []), "00 00 d 111": ("", "RdCA", []), "00 01 d 111": ("", "RdA", []), "00 010000": ("", "STOP", []), "00 011 000": ("", "JR ${N}", []), "00 1FF 000": ("", "JR ${F}, ${N}", []), "00 100 010": ("", "LDI HL, A", []), "00 101 010": ("", "LDI A, HL", []), "00 100 010": ("", "LDD HL, A", []), "00 111 010": ("", "LDD A, HL", []), "00 100111": ("", "DAA", []), "00 101111": ("", "CPL", []), "00 110111": ("", "SCF", []), "00 111111": ("", "CCF", []), "01 DDD DDD": ("", "LD ${D}, ${D2}", []), "01 110 110": ("", "HALT", []), "10 AAA DDD": ("", "${ALU} A, ${D2}", []), "11 AAA 110": ("", "${ALU} A, ${N}", []), "11 RR0 0 01": ("", "POP ${R}", []), "11 RR0 1 01": ("", "PUSH ${R}", []), "11 NNN 111": ("", "RST ${RST}", []), "110 FF 000": ("", "RET ${F}", []), "110 01001": ("", "RET", []), "110 11001": ("", "RETI", []), "110 FF 010": ("", "JP ${F}, ${N}", []), "110 00011": ("", "JP ${N}", []), "110 FF 100": ("", "CALL ${F}, ${N}", []), "110 01101": ("", "CALL ${N}", []), "111 01000": ("", "ADD SP, ${N}", []), "111 11000": ("", "LD HL, SP+${N}", []), "111 00000": ("", "LD FF00 + ${N}, A", []), "111 10000": ("", "LD A, FF00 + ${N}", []), "111 0 0010": ("", "LD C, A", []), "111 1 0010": ("", "LD A, C", []), "111 0 1010": ("", "LD ${N}, A", []), "111 1 1010": ("", "LD A, ${N}", []), "111 01001": ("", "JP HL", []), # Also known as "LD PC, HL" "111 11001": ("", "LD SP, HL", []), "111 10011": ("", "DI", []), "111 11011": ("", "EI", []), "1100 1011": ("", "MB", []), # Multiple byte command } branches = set("01") wildcard = "XDFRArNd" ignore = " ," decodeTree = getDecodeTree(opCodes, wildcard, ignore) print getSwitch(genDisassemble, "/*Default*/", decodeTree, 0)
[ 6738, 279, 4798, 1330, 279, 4798, 198, 6738, 4731, 1330, 37350, 198, 6738, 875, 12342, 8645, 1352, 1330, 651, 10707, 1098, 27660, 11, 651, 38978, 198, 198, 404, 34, 4147, 796, 1391, 198, 220, 220, 220, 366, 405, 41853, 1298, 5855, 160...
2.091854
1,154
import os import sys import pygame import time from pygame.locals import * CAPTION = "Rescue Xiaomeng" SCREEN_SIZE = (800, 600) pygame.init() pygame.display.set_caption(CAPTION) screen = pygame.display.set_mode(SCREEN_SIZE) xm = People() xm.show() run()
[ 11748, 28686, 198, 11748, 25064, 198, 11748, 12972, 6057, 198, 11748, 640, 198, 6738, 12972, 6057, 13, 17946, 874, 1330, 1635, 198, 198, 33177, 24131, 796, 366, 49, 3798, 518, 22450, 296, 1516, 1, 198, 6173, 2200, 1677, 62, 33489, 796, ...
2.529412
102