def T2tt(self): # model name self.modelname = "T2tt" # decay chain self.label= "pp #rightarrow #tilde{t} #bar{_{_{ }}#tilde{t}_{_{ }}}, #tilde{t} #rightarrow t #tilde{#chi}^{0}_{1}"; # scan range to plot self.Xmin = 150 self.Xmax = 1200 self.Ymin = 0 self.Ymax = 700 self.Zmin = 0.001 self.Zmax = 100 #self.Zmin = 0.1 #self.Zmax = 10 # produce sparticle self.sParticle = "m_{#kern[0.7]{#tilde{t}}} [GeV]" # LSP self.LSP = "m_{#tilde{#chi}_{1}^{0}} [GeV]" # diagonal position: mLSP = mgluino - 2mtop mW = 75 self.diagX = array('d',[0,20000]) self.diagY = array('d',[-mW, 20000-mW]) # turn off diagonal lines self.diagOn = True #self.mT, self.dM = 172.5, 6.25 self.mT, self.dM = 175, 25 self.mTopDiagOn = True
def setStyleCOLZ(self): # set z axis self.histo.GetZaxis().SetLabelFont(42) self.histo.GetZaxis().SetTitleFont(42) self.histo.GetZaxis().SetLabelSize(0.035) self.histo.GetZaxis().SetTitleSize(0.035) self.histo.SetMinimum(self.model.Zmin) self.histo.SetMaximum(self.model.Zmax) # define the palette for z axis NRGBs = 5 NCont = 255 stops = array("d",[0.00, 0.34, 0.61, 0.84, 1.00]) red= array("d",[0.50, 0.50, 1.00, 1.00, 1.00]) green = array("d",[ 0.50, 1.00, 1.00, 0.60, 0.50]) blue = array("d",[1.00, 1.00, 0.50, 0.40, 0.50]) rt.TColor.CreateGradientColorTable(NRGBs, stops, red, green, blue, NCont) rt.gStyle.SetNumberContours(NCont) self.c.cd() self.histo.Draw("colz") rt.gPad.Update() palette = self.histo.GetListOfFunctions().FindObject("palette") palette.SetX1NDC(1.-0.18) palette.SetY1NDC(0.14) palette.SetX2NDC(1.-0.13) palette.SetY2NDC(1.-0.08) palette.SetLabelFont(42) palette.SetLabelSize(0.035)
def makeROCFromHisto(hsig,hbkg,LtoR): nbins = hsig.GetNbinsX(); binsize = hsig.GetBinWidth(1); lowedge = hsig.GetBinLowEdge(1); #print "lowedge: ",lowedge hsigIntegral = hsig.Integral(); hbkgIntegral = hbkg.Integral(); xval = array('d', []) yval = array('d', []) ctr = 0; for i in range(1,nbins+1): effBkg = 0; effSig = 0; if LtoR: effBkg = hbkg.Integral( i, nbins )/hbkgIntegral; else: effBkg = hbkg.Integral( 1, i )/hbkgIntegral; if LtoR: effSig = hsig.Integral( i, nbins )/hsigIntegral; else: effSig = hsig.Integral( 1, i )/hsigIntegral; #print "cut: ",(lowedge+(i-1)*binsize),"effBkg: ", effBkg, ", effSig: ", effSig; xval.append( effSig ); yval.append( 1-effBkg ); ctr = ctr + 1; #print nbins, "and ", ctr tg = ROOT.TGraph( nbins, xval, yval ); return tg;
def T6ttWW(self): # model name self.modelname = "T6ttWW" # decay chain self.label= "pp #rightarrow #tilde{b}_{1}#tilde{b}_{1}*, #tilde{b}_{1}#rightarrow tW#tilde{#chi}^{0}_{1} "; # scan range to plot self.Xmin = 287.5 self.Xmax = 912.5 self.Ymin = 62.5 self.Ymax = 1112.5 self.Zmin = 0.01 self.Zmax = 10 # produce sparticle self.sParticle = "m_{#tilde{b}} (GeV)" # LSP self.LSP = "m_{#tilde{#chi}^{#pm}_{1}} (GeV)" # diagonal position: msbottom = mXpm mT = 0 self.diagX = array('d',[0,20000]) self.diagY = array('d',[-mT, 20000-mT]) self.diagText = 'm_{#tilde{b}} = m_{#tilde{#chi}^{#pm}_{1}}' self.diagAngle = 35.5 self.diagTextX = 0.2 self.diagTextY = 0.38 # turn off diagonal lines self.diagOn = True self.fixMass = 'm_{#tilde{#chi}^{0}_{1}} = 50 GeV'
def markEvenlySpacedPoints( x, y,interval): number=1 nextline=0 x=smoothListGaussian(x) y=smoothListGaussian(y) evenlySpacedXArray=array('d',[]) evenlySpacedYArray=array('d',[]) markcount=0 skipcount=1 for xval in x: if number == 1 or number==nextline: markcount += 1 #print "number: ", number, "-", x[number],"-",y[number] evenlySpacedXArray.append(x[number]) evenlySpacedYArray.append(y[number]) ## update sql table #try: #c=conn.cursor() #c.execute('update tblMeasurement set i_evenSpacePoint=1 where i_measurementID=%d' % row_list[number]) #conn.commit() #except sqlite.OperationalError, msg: #logger.error( "A SQL error occurred: %s", msg) nextline=int(number+int(pow(skipcount,1.25))) skipcount += 1 #print "X: ", xval, " Y:", y[number], " MARK" #print "X: ", xval, " Y:", y[number] number +=1 return evenlySpacedXArray, evenlySpacedYArray
def set_palette(name="palette", ncontours=999): """Set a color palette from a given RGB list stops, red, green and blue should all be lists of the same length see set_decent_colors for an example""" if name == "gray" or name == "grayscale": stops = [0.00, 0.34, 0.61, 0.84, 1.00] red = [1.00, 0.84, 0.61, 0.34, 0.00] green = [1.00, 0.84, 0.61, 0.34, 0.00] blue = [1.00, 0.84, 0.61, 0.34, 0.00] elif name=="signal": stops = [0.00, 0.34, 0.61, 0.84, 1.00] red = [1.00, 0.90, 0.60, 0.40, 0.20] green = [0.00, 0.00, 0.00, 0.00, 0.00] blue = [0.00, 0.00, 0.00, 0.00, 0.00] # elif name == "whatever": # (define more palettes) else: # default palette, looks cool stops = [0.00, 0.34, 0.61, 0.84, 1.00] red = [0.00, 0.00, 0.87, 1.00, 0.51] green = [0.00, 0.81, 1.00, 0.20, 0.00] blue = [0.51, 1.00, 0.12, 0.00, 0.00] s = array('d', stops) r = array('d', red) g = array('d', green) b = array('d', blue) npoints = len(s) TColor.CreateGradientColorTable(npoints, s, r, g, b, ncontours) gStyle.SetNumberContours(ncontours)
def _zip2crx(self, zipPath, keyPath, crxPath): """ :param zipPath: path to .zip file :param keyPath: path to .pem file :param crxPath: path to .crx file to be created """ # Sign the zip file with the private key in PEM format signature = subprocess.Popen( ["openssl", "sha1", "-sign", keyPath, zipPath], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ).communicate()[0] # Convert the PEM key to DER (and extract the public form) for inclusion in the CRX header derkey = subprocess.Popen( ["openssl", "rsa", "-pubout", "-inform", "PEM", "-outform", "DER", "-in", keyPath], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ).communicate()[0] out = open(crxPath, "wb") out.write("Cr24") # Extension file magic number header = array("L") if struct.calcsize("L") == 4 else array("I") header.append(2) # Version 2 header.append(len(derkey)) header.append(len(signature)) header.tofile(out) out.write(derkey) out.write(signature) out.write(open(zipPath, "rb").read())
def createStreams(self): self.buffer32 = array('i') # array of long self.buffer16 = array('h') # array of signed short self.buffer8 = array('b') # array of signed byte. Call it a big string self.Allocated32 = 0 # Size buffer32 should be self.Allocated16 = 0 # Size buffer16 should be self.Allocated8 = 0 # Size buffer8 should be
def synchrony(s1, s2, t, winLen, freq, overlap=.1) : """ FUNC: synchrony DESCR: phase synchrony implementation """ #print "utils.synchrony(s1(", len(s1), ",), s2(", len(s2), "), t(", len(t),"),", winLen, freq, overlap, ")" # Compute phase difference #print "utils.synchrony(): doing hilbert_phaser(s1)" p1 = hilbert_phaser(s1) #print "utils.synchrony(): doing hilbert_phaser(s2)" p2 = hilbert_phaser(s2) pdiff = p1 - p2 sync = [] time = [] nWin = int(winLen * freq) nOverlap = int(overlap * freq) #print "utils.synchrony(): doing ", len(arange(0, len(pdiff), nWin - nOverlap)), " pdiffs" for i in arange(0, len(pdiff), nWin - nOverlap): sWin = pdiff[i:i + nWin] if len(sWin) < 3 : continue s = 1. / (1 + std(sWin)) #print "utils.synchrony(): [", i, ", ", i+nWin, "]: appending value s=", s try : sync.append(s) except : print 'sWin:', sWin sys.exit() if t is not None : time.append(t[i] + winLen / 2.) return array(sync), array(time)
def TChiWH(self): # model name self.modelname = "TChiWH" # decay chain self.label= "pp #rightarrow #tilde{#chi}^{#pm}_{1}#tilde{#chi}^{0}_{2}; #tilde{#chi}^{#pm}_{1} #rightarrow W^{#pm}#tilde{#chi}^{0}_{1}, #tilde{#chi}^{0}_{2} #rightarrow H#tilde{#chi}^{0}_{1}" #self.masslabel = "m_{#tilde{#chi}^{0}_{2}}-m_{#tilde{#chi}^{0}_{1}}=130 GeV" self.masslabel = "" # plot boundary. The top 1/4 of the y axis is taken by the legend self.Xmin = 125 self.Xmax = 300 self.Ymin = 0 self.Ymax = 275 self.Zmax = 5 self.Zmin = 0.1 # produce sparticle self.sParticle = "m_{#tilde{#chi}^{#pm}_{1}} = m_{#tilde{#chi}^{0}_{2}} [GeV]" # LSP self.LSP = "m_{#tilde{#chi}^{0}_{1}} [GeV]" # diagonal position: mLSP = mSbotton - 150 self.diagX = array('d',[0,20000,self.Xmin]) self.diagY = array('d',[-125, 20000-125,self.Xmax]) #self.divX = 407 self.divX = 409 self.divY = 408 self.optX = True self.optY = True
def T1tttt(self): # model name self.modelname = "T1tttt" # decay chain self.label= "pp #rightarrow #tilde{g}#tilde{g}, #tilde{g} #rightarrow t#bar{t}#tilde{#chi}^{0}_{1}" self.masslabel = "" # scan range to plot self.Xmin = 600 self.Xmax = 1950 self.Ymin = 0 self.Ymax = 1800 self.Zmax = 2 self.Zmin = 1.e-3 # produce sparticle self.sParticle = "m_{#tilde{g}} [GeV]" # LSP self.LSP = "m_{#tilde{#chi}^{0}_{1}} [GeV]" # diagonal position: mLSP = mgluino - 2mtop mW = 225 self.diagX = array('d',[0,20000,self.Xmin]) self.diagY = array('d',[-mW, 20000-mW,self.Xmax]) self.divX = 408 self.divY = 408 self.optX = True self.optY = True
def T2ttGluino(self): # model name self.modelname = "T2ttGluino" # decay chain self.label= "pp #rightarrow #tilde{g}#tilde{g}, #tilde{g} #rightarrow t#tilde{t} #rightarrow t#tilde{#chi}^{0}_{1}+invisible" self.masslabel = "m_{#tilde{t}} #approx m_{#tilde{#chi}^{0}_{1}}" # plot boundary. The top 1/4 of the y axis is taken by the legend self.Xmin = 100 self.Xmax = 900 self.Ymin = 0 self.Ymax = 700 self.Zmax = 200 self.Zmin = 1.e-3 # produce sparticle self.sParticle = "m_{#tilde{g}} [GeV]" # LSP self.LSP = "m_{#tilde{#chi}^{0}_{1}} [GeV]" # diagonal position: mLSP = mgluino - 2mtop self.diagX = array('d',[0,20000,self.Xmin]) self.diagY = array('d',[-75, 20000-75,self.Xmax]) self.diagXtop = array('d',[0,20000,self.Xmin]) self.diagYtop = array('d',[-175, 20000-175,self.Xmax]) #self.fillXtop = array('d',[0,20000,20000,0]) #self.fillYtop = array('d',[-175-25, 20000-175-25,20000-175+25,-175+25]) #self.divX = 407 self.divX = 409 self.divY = 408 self.optX = True self.optY = True
def T2bw(self): # model name self.modelname = "T2bw" # decay chain self.label= "pp #rightarrow #tilde{t}#tilde{t}, #tilde{t} #rightarrow b#tilde{#chi}^{#pm}_{1}" self.masslabel = "m_{#tilde{#chi}^{#pm}_{1}}-m_{#tilde{#chi}^{0}_{1}} = 5 GeV" # plot boundary. The top 1/4 of the y axis is taken by the legend self.Xmin = 150 self.Xmax = 900 self.Ymin = 0 self.Ymax = 600 self.Zmax = 10 self.Zmin = 1.e-3 # produce sparticle self.sParticle = "m_{#tilde{t}} [GeV]" # LSP self.LSP = "m_{#tilde{#chi}^{0}_{1}} [GeV]" # diagonal position: mLSP = mgluino - 2mtop self.diagX = array('d',[0,20000,self.Xmin]) self.diagY = array('d',[-100, 20000-100,self.Xmax]) #self.divX = 407 self.divX = 409 self.divY = 408 self.optX = True self.optY = True
def T1x0p00y0p50(self): # model name self.modelname = "T1x0p50y0p00" # decay chain self.label= "pp #rightarrow #tilde{g}#tilde{g}, #tilde{g} #rightarrow tb#tilde{#chi}^{#pm}_{1} / tt#tilde{#chi}^{0}_{1} (x=0,y=#frac{1}{2})" self.masslabel = "m_{#tilde{#chi}^{#pm}_{1}}-m_{#tilde{#chi}^{0}_{1}} = 5 GeV" # scan range to plot self.Xmin = 600 self.Xmax = 1950 self.Ymin = 0 self.Ymax = 1800 self.Zmax = 2 self.Zmin = 1.e-3 # produce sparticle self.sParticle = "m_{#tilde{g}} [GeV]" # LSP self.LSP = "m_{#tilde{#chi}^{0}_{1}} [GeV]" # diagonal position: mLSP = mgluino - 2mtop mW = 225 self.diagX = array('d',[0,20000,self.Xmin]) self.diagY = array('d',[-mW, 20000-mW,self.Xmax]) self.divX = 408 self.divY = 408 self.optX = True self.optY = True
def T2bH(self): # model name self.modelname = "T2bH" # decay chain self.label= "pp #rightarrow #tilde{b}#tilde{b}, #tilde{b} #rightarrow b#tilde{#chi}^{0}_{2} #rightarrow bH#tilde{#chi}^{0}_{1}" self.masslabel = "m_{#tilde{#chi}^{0}_{2}}-m_{#tilde{#chi}^{0}_{1}}=130 GeV" # plot boundary. The top 1/4 of the y axis is taken by the legend self.Xmin = 250 self.Xmax = 600 self.Ymin = 0 self.Ymax = 450 self.Zmax = 10 self.Zmin = 0.2 # produce sparticle self.sParticle = "m_{#tilde{b}} [GeV]" # LSP self.LSP = "m_{#tilde{#chi}^{0}_{1}} [GeV]" # diagonal position: mLSP = mSbotton - 150 self.diagX = array('d',[0,20000,self.Xmin]) self.diagY = array('d',[-150, 20000-150,self.Xmax]) #self.divX = 407 self.divX = 409 self.divY = 408 self.optX = True self.optY = True
def __init__(self, url, ip, domain, target, useragent): self.url = url self.ip = ip self.domain = domain self.target = target self.useragent = useragent self.logdir = '' self.alexa = False self.abuse_ch_ransomware_domains = False self.abuse_ch_ransomware_ips = False self.abuse_ch_ransomware_urls = False self.abuse_ch_feodo = False self.xforce = False self.VT = False self.bluecoat = False self.bluecoatcategory = '' self.talos = False self.taloscategory = '' self.fortiguard = False self.fortiguardcategory = '' self.targetdomainentropy = 'N/A' self.country = 'N/A' self.http_data = array('i') self.https_data = array('i')
def parse(cls, txt): name, ext = os.path.splitext(txt) with open(name + '_tmp' + ext, 'wb') as binOut: count = 0 with open(txt, 'r') as txtIn: for line in txtIn: line = line.rstrip('\n') arr = array('B') arr.append(len(line)) arr.tofile(binOut) binOut.write(bytearray(line, 'utf-8')) arr = array('B') arr.append(0) arr.tofile(binOut) count += 1 with open(name + '_bin' + ext, 'wb') as binOut: arr = array('B') arr.append(count) arr.append(0) arr.tofile(binOut) with open(name + '_tmp' + ext, 'rb') as binIn: while True: chunk = binIn.read(1024) if chunk: binOut.write(chunk) else: break os.remove(name + '_tmp' + ext)
def __init__(self,n,elts=[]): self._known = array('I',range(n)) self._index = array('I',range(n)) self._size = 0 self._iter = 0 for elt in elts: self.add(elt)
def testTCP(self): eth = ethernet() eth.dst = '\xca\xfe\xde\xad\xbe\xef' eth.src = '\xca\xfe\xde\xad\xd0\xd0' eth.type = ethernet.IP_TYPE ipstr = '\x45\x00\x00\x34\x1c\x1b\x40\x00\x40\x06\x34\xdf\xab\x40\x4a\x31\xac\x18\x48\x40' iparr = array('B',ipstr) tcpstr = '\x03\x20\x08\x01\xd2\x9d\x61\x67\x57\x37\xc3\x0f\x80\x10\x7e\x82\xf2\x6e\x00\x00\x01\x01\x08\x0a\xf3\xb5\x9c\x36\x18\xa2\x1a\x06' tcparr = array('B',tcpstr) tcph = ethernet(array('B', eth.tostring()) + iparr + tcparr).find('tcp') assert(tcph) assert(tcph.parsed) assert(tcph.srcport == 800) assert(tcph.dstport == 2049) assert(tcph.seq == 0xd29d6167) assert(tcph.ack == 0x5737c30f) assert(tcph.off == 8) assert(tcph.res == 0) assert(not tcph.flags & tcp.CWR) assert(not tcph.flags & tcp.ECN) assert(not tcph.flags & tcp.URG) assert(tcph.flags & tcp.ACK) assert(not tcph.flags & tcp.PUSH) assert(not tcph.flags & tcp.RST) assert(not tcph.flags & tcp.SYN) assert(not tcph.flags & tcp.FIN) assert(tcph.win == 32386) assert(tcph.csum == 0xf26e) assert(tcph.checksum() == tcph.csum) assert(len(tcph.options) == 3) assert(tcph.options[0].type == tcp_opt.NOP) assert(tcph.options[1].type == tcp_opt.NOP) assert(tcph.options[2].type == tcp_opt.TSOPT) assert(tcph.options[2].val[0] == 4088765494)
def testGetAccumulate(self): group = self.WIN.Get_group() size = group.Get_size() group.Free() for array in arrayimpl.ArrayTypes: for typecode in arrayimpl.TypeMap: for count in range(self.COUNT_MIN, 10): for rank in range(size): ones = array([1]*count, typecode) sbuf = array(range(count), typecode) rbuf = array(-1, typecode, count+1) gbuf = array(-1, typecode, count+1) for op in (MPI.SUM, MPI.PROD, MPI.MAX, MPI.MIN, MPI.REPLACE, MPI.NO_OP): self.WIN.Lock(rank) self.WIN.Put(ones.as_mpi(), rank) self.WIN.Flush(rank) r = self.WIN.Rget_accumulate(sbuf.as_mpi(), rbuf.as_mpi_c(count), rank, op=op) r.Wait() self.WIN.Flush(rank) r = self.WIN.Rget(gbuf.as_mpi_c(count), rank) r.Wait() self.WIN.Unlock(rank) # for i in range(count): self.assertEqual(sbuf[i], i) self.assertEqual(rbuf[i], 1) self.assertEqual(gbuf[i], op(1, i)) self.assertEqual(rbuf[-1], -1) self.assertEqual(gbuf[-1], -1)
def __new__(cls, data): """docstring for __init__""" newme = array.__new__(cls, 'i', range(len(data))) newme._index = array('i', newme) newme._prio = array('d', data) newme.heapify() return newme
def read_subimage(self, rows, cols, bands=[]): ''' Reads arbitrary rows, columns, and bands from the image. Arguments: `rows` (list of ints): Indices of rows to read. `cols` (list of ints): Indices of columns to read. `bands` (list of ints): Optional list of bands to read. If not specified, all bands are read. Returns: :class:`numpy.ndarray` An `MxNxL` array, where `M` = len(`rows`), `N` = len(`cols`), and `L` = len(bands) (or # of image bands if `bands` == None). ''' return self.parent.read_subimage(list(array(rows) + self.row_offset), list(array(cols) + self.col_offset), bands)
def Interpolate2DHist(hist, epsilon=5, smooth=0, diagonal_offset=0): """interpolate a TH2""" x = array('d',[]) y = array('d',[]) z = array('d',[]) # fill arrays for xbin in range(1, hist.GetNbinsX()+1): for ybin in range(1, hist.GetNbinsY()+1): if hist.GetBinContent(xbin, ybin) > 0.0: x.append(hist.GetXaxis().GetBinCenter(xbin)) y.append(hist.GetYaxis().GetBinCenter(ybin)) z.append(root.TMath.Log(hist.GetBinContent(xbin, ybin))) # interpolate using scipy bin_width = float(hist.GetBinWidth(1)) mgMin = hist.GetXaxis().GetBinCenter(1) mgMax = hist.GetXaxis().GetBinCenter(hist.GetNbinsX()) mchiMin = hist.GetYaxis().GetBinCenter(1) mchiMax = hist.GetYaxis().GetBinCenter(hist.GetNbinsY()) myX = np.linspace(mgMin, mgMax,int((mgMax-mgMin)/bin_width+1)) myY = np.linspace(mchiMin, mchiMax, int((mchiMax-mchiMin)/bin_width+1)) myXI, myYI = np.meshgrid(myX,myY) rbf = Rbf(x, y, z,function='multiquadric', epsilon=epsilon, smooth=smooth) myZI = rbf(myXI, myYI) # reset hist for xbin in range(1, hist.GetNbinsX()+1): for ybin in range(1, hist.GetNbinsY()+1): xLow = hist.GetXaxis().GetBinCenter(xbin) yLow = hist.GetYaxis().GetBinCenter(ybin) if xLow >= yLow + diagonal_offset - 3.0*bin_width: hist.SetBinContent(xbin, ybin, root.TMath.Exp(myZI[ybin-1][xbin-1])) return hist
def interpolate2D(hist, epsilon=1, smooth=0): x = array('d', []) y = array('d', []) z = array('d', []) binWidth = float(hist.GetBinWidth(1)) for i in range(1, hist.GetNbinsX() + 1): for j in range(1, hist.GetNbinsY() + 1): if hist.GetBinContent(i, j) > 0.: x.append(hist.GetXaxis().GetBinLowEdge(i)) y.append(hist.GetYaxis().GetBinLowEdge(j)) z.append(rt.TMath.Log(hist.GetBinContent(i, j))) #z.append(hist.GetBinContent(i,j)) mgMin = hist.GetXaxis().GetBinLowEdge(1) mgMax = hist.GetXaxis().GetBinUpEdge(hist.GetNbinsX()) mchiMin = hist.GetYaxis().GetBinLowEdge(1) mchiMax = hist.GetYaxis().GetBinUpEdge(hist.GetNbinsY()) myX = np.linspace(mgMin, mgMax, int((mgMax - mgMin) / binWidth + 1)) myY = np.linspace(mchiMin, mchiMax, int((mchiMax - mchiMin) / binWidth + 1)) myXI, myYI = np.meshgrid(myX, myY) rbf = Rbf(x, y, z, function='multiquadric', epsilon=epsilon, smooth=smooth) myZI = rbf(myXI, myYI) for i in range(1, hist.GetNbinsX() + 1): for j in range(1, hist.GetNbinsY() + 1): xLow = hist.GetXaxis().GetBinLowEdge(i) yLow = hist.GetYaxis().GetBinLowEdge(j) if xLow >= yLow + diagonalOffset: hist.SetBinContent(i, j, rt.TMath.Exp(myZI[j - 1][i - 1])) return hist
def tile_image(im, nrows, ncols): ''' Break an image into nrows x ncols tiles. USAGE: tiles = tile_image(im, nrows, ncols) ARGUMENTS: im The SpyFile to tile. nrows Number of tiles in the veritical direction. ncols Number of tiles in the horizontal direction. RETURN VALUE: tiles A list of lists of SubImage objects. tiles contains nrows lists, each of which contains ncols SubImage objects. ''' from numpy.oldnumeric import array, Int from io.spyfile import SubImage x = (array(range(nrows + 1)) * float(im.nrows) / nrows).astype(Int) y = (array(range(ncols + 1)) * float(im.ncols) / ncols).astype(Int) x[-1] = im.nrows y[-1] = im.ncols tiles = [] for r in range(len(x) - 1): row = [] for c in range(len(y) - 1): si = SubImage(im, [x[r], x[r + 1]], [y[c], y[c + 1]]) row.append(si) tiles.append(row) return tiles
def T5qqqqVV(self): # model name self.modelname = "T5qqqqVV" # decay chain self.label= "pp #rightarrow #tilde{g}#tilde{g}, #tilde{g} #rightarrow q#bar{q}'W/Z#tilde{#chi}^{0}_{1}"; # scan range to plot self.Xmin = 587.5 self.Xmax = 1312.5 self.Ymin = -12.5 self.Ymax = 1412.5 self.Zmin = 0.01 self.Zmax = 50 # produce sparticle self.sParticle = "m_{#tilde{g}} (GeV)" # LSP self.LSP = "m_{#tilde{#chi}_{1}^{0}} (GeV)" # diagonal position: mLSP = mgluino - 2mtop mT = 0 self.diagX = array('d',[0,20000]) self.diagY = array('d',[-mT, 20000-mT]) self.diagText = 'm_{#tilde{g}} = m_{#tilde{#chi}^{0}_{1}}' self.diagAngle = 29.01 self.diagTextX = 0.2 self.diagTextY = 0.53 # turn off diagonal lines self.diagOn = True self.fixMass = 'm_{#tilde{#chi}^{#pm}_{1}} = 0.5 (m_{#tilde{g}} + m_{#tilde{#chi}^{0}_{1}})'
def T5ttttdeg(self): # model name self.modelname = "T5ttttdeg" # decay chain self.label= "pp #rightarrow #tilde{g}#tilde{g}, #tilde{g} #rightarrow #tilde{t}_{1}t, #tilde{t}_{1} #rightarrow t#tilde{#chi}^{0}_{1}"; # scan range to plot self.Xmin = 587.5 self.Xmax = 1312.5 self.Ymin = -12.5 self.Ymax = 1362.5 self.Zmin = 0.01 self.Zmax = 50 # produce sparticle self.sParticle = "m_{#tilde{g}} (GeV)" # LSP self.LSP = "m_{#tilde{#chi}_{1}^{0}} (GeV)" # diagonal position: mLSP = mgluino - 2m(W+b) mT = 85 self.diagX = array('d',[0,20000]) self.diagY = array('d',[-mT, 20000-mT]) self.diagText = 'm_{#tilde{g}} - m_{#tilde{#chi}^{0}_{1}} = m_{W} + m_{b}' self.diagAngle = 29.5 self.diagTextX = 0.2 self.diagTextY = 0.49 # turn off diagonal lines self.diagOn = True self.fixMass = 'm_{#tilde{t}_{1}} = m_{#tilde{#chi}^{0}_{1}} + 20 GeV'
def CombineTGraphs(g1, g2, name, title): if g1.GetN()==0 and g2.GetN()==0: g = root.TGraph(0) elif g1.GetN()==0: g = g2.Clone() elif g2.GetN()==0: g = g1.Clone() else: g_x = array('d') g_y = array('d') for i in reversed(xrange(g1.GetN())): g_x.append(g1.GetX()[i]) g_y.append(g1.GetY()[i]) # append bogus value to join the other contour "off the screen" g_x.append(150) g_y.append(-12.5) g_x.append(175) g_y.append(-12.5) g_x.append(200) g_y.append(-12.5) for i in reversed(xrange(g2.GetN())): g_x.append(g2.GetX()[i]) g_y.append(g2.GetY()[i]) n = g1.GetN()+g2.GetN()+3 g = root.TGraph(n, g_x, g_y) g.SetName(name) g.SetTitle(title) g.SetLineColor(root.kBlack) g.SetLineWidth(3) return g
def T1tttt(self): # model name self.modelname = "T1tttt" # decay chain self.label= "pp #rightarrow #tilde{g}#tilde{g}, #tilde{g} #rightarrow t#bar{t}#tilde{#chi}^{0}_{1}"; # scan range to plot self.Xmin = 687.5 self.Xmax = 1712.5 self.Ymin = -12.5 self.Ymax = 1712.5 self.Zmin = 0.01 self.Zmax = 50 # produce sparticle self.sParticle = "m_{#tilde{g}} (GeV)" # LSP self.LSP = "m_{#tilde{#chi}_{1}^{0}} (GeV)" # diagonal position: mLSP = mgluino - 2m(W+b) mT = 170 self.diagX = array('d',[0,20000]) self.diagY = array('d',[-mT, 20000-mT]) self.diagText = 'm_{#tilde{g}} - m_{#tilde{#chi}^{0}_{1}} = 2 (m_{W} + m_{b})' self.diagAngle = 34.6 self.diagTextX = 0.2 self.diagTextY = 0.47 # turn off diagonal lines self.diagOn = True self.fixMass = ''
def read_subregion(self, row_bounds, col_bounds, bands=None): ''' Reads a contiguous rectangular sub-region from the image. Arguments: `row_bounds` (2-tuple of ints): (a, b) -> Rows a through b-1 will be read. `col_bounds` (2-tuple of ints): (a, b) -> Columnss a through b-1 will be read. `bands` (list of ints): Optional list of bands to read. If not specified, all bands are read. Returns: :class:`numpy.ndarray` An `MxNxL` array. ''' return self.parent.read_subimage( list(array(row_bounds) + self.row_offset), list(array( col_bounds) + self.col_offset), bands)
myfile = TFile(outFileName, 'RECREATE') NewTree1 = ROOT.TTree('UdeATree', 'Converteed Tree') #Declares a the branches of the first 4 Jets, 2 electrons, 2 Muons, and 3 leafs for the Missing Energy Jet1 = ROOT.TLorentzVector(0, 0, 0, 0) Jet2 = ROOT.TLorentzVector(0, 0, 0, 0) Jet3 = ROOT.TLorentzVector(0, 0, 0, 0) Jet4 = ROOT.TLorentzVector(0, 0, 0, 0) Elec1 = ROOT.TLorentzVector(0, 0, 0, 0) Elec2 = ROOT.TLorentzVector(0, 0, 0, 0) Muon1 = ROOT.TLorentzVector(0, 0, 0, 0) Muon2 = ROOT.TLorentzVector(0, 0, 0, 0) METNRGT = array('f', [0]) METPhi = array('f', [0]) METEta = array('f', [0]) b_Jet1 = array('f', [0]) b_Jet2 = array('f', [0]) b_Jet3 = array('f', [0]) b_Jet4 = array('f', [0]) Tau_Jet1 = array('f', [0]) Tau_Jet2 = array('f', [0]) Tau_Jet3 = array('f', [0]) Tau_Jet4 = array('f', [0]) NewTree1.Branch('Jet1', Jet1) NewTree1.Branch('Jet2', Jet2)
from array import * intArray = array('i', []) intLength = eval(input("Enter length of array")) for i in range(intLength): intValue = eval(input("Enter the value:")) intArray.append(intValue) for i in range(len(intArray)): print(intArray[i])
CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "Preliminary" CMS_lumi.lumi_sqrtS = "13 TeV" # used with iPeriod = 0, e.g. for simulation-only plots (default is an empty string) iPos = 11 if( iPos==0 ): CMS_lumi.relPosX = 0.12 iPeriod=4 #ROOT.gSystem.Load(options.inPath+"/PDFs/HWWLVJRooPdfs_cxx.so") rt.gStyle.SetOptFit(1) massBins =[1, 3, 6, 10, 16, 23, 31, 40, 50, 61, 74, 88, 103, 119, 137, 156, 176, 197, 220, 244, 270, 296, 325, 354, 386, 419, 453, 489, 526, 565, 606, 649, 693, 740, 788, 838, 890, 955, 1000, 1058, #944 to 955! 1118, 1181, 1246, 1313, 1383, 1455, 1530, 1607, 1687, 1770, 1856, 1945, 2037, 2132, 2231, 2332, 2438, 2546, 2659, 2775, 2895, 3019, 3147, 3279, 3416, 3558, 3704, 3854, 4010, 4171, 4337, 4509, 4686, 4869, 5058, 5253, 5455, 5663, 5877, 6099, 6328, 6564, 6808] xbins = array('d',massBins) outdir = "/mnt/t3nfs01/data01/shome/dschafer/AnalysisOutput/figures/bkgfit/ReReco2016/" fileIN = rt.TFile.Open("/mnt/t3nfs01/data01/shome/dschafer/ExoDiBosonAnalysis/results/ReRecoData_VVdijet.root") alphas = [8.34260e-01,2.26698,1.53339,1.17580,2.99999,2.2626,0.663441,0.800000] #WWHP,WWLP,WZHP,WZLP,ZZHP,ZZLP,VVHP (forBulkZZ),VVLP(forBulkZZ) sigfracs = [4.58877e-01,3.00000e-01,2.94266e-07,1.64950e-02,0.867402,0.278371,6.42551e-01,5.00000e-01] #WWHP,WWLP,WZHP,WZLP,ZZHP,ZZLP,VVHP (forBulkZZ),VVLP(forBulkZZ) gsigmas = [7.27898e+01,1.06220e+02,49.3526,6.92449e+02,1.04783e+02,127.174,6.78921e+01,7.40979e+03] #WWHP,WWLP,WZHP,WZLP,ZZHP,ZZLP,VVHP (forBulkZZ),VVLP(forBulkZZ) means = [2.03797e+03,2.03398e+03,2045.73,2.01137e+03,2.05889e+03,2071.45,2.02521e+03,2.00000e+03] #WWHP,WWLP,WZHP,WZLP,ZZHP,ZZLP,VVHP (forBulkZZ),VVLP(forBulkZZ) signs = [1.28383e+02,2.01148e+00,32.3031,1.34384e+02,8.63245e+01,131.438,1.33056e+02,1.30000e+02] #WWHP,WWLP,WZHP,WZLP,ZZHP,ZZLP,VVHP (forBulkZZ),VVLP(forBulkZZ) sigmas = [5.73275e+01,6.08280e+01,67.4016,8.25785e+01,6.54552e+01,59.7554,1.03704e+02,1.00000e+02] #WWHP,WWLP,WZHP,WZLP,ZZHP,ZZLP,VVHP (forBulkZZ),VVLP(forBulkZZ) # signalrate = [1.68221,1.95172,3.38452,2.95105,1.26099,0.928928,3.00421,2.86817]#8TeV signalrate = [9.41966,15.6241,29.0534,34.6518,26.9728,24.441] #2016 exp expected signalrate for signal with 0.01pb xSec in each category (#WWHP,WWLP,WZHP,WZLP,ZZHP,ZZLP) scaleToExcluded = [2.,2.,0.9,0.9,0.8,0.8]#2016 exp
from array import * vals = array('i', [5, 9, 8, 4, 2]) print(vals.buffer_info()) # in buffer_info output we get two values one is address and one is size vals.reverse() print(vals) for i in range(len(vals)): print(vals[i]) # create new array newArr = array(vals.typecode, (j * j for j in vals)) # here typecode is used for to know the type of values and after that it will take one value and one by one # assigned in array # if we want to print square of the values just use * for i in newArr: print(i)
from array import * arr = array('i', [int(input()), int(input()), int(input())]) arr = sorted(arr) for i in arr: print(i)
def test_assign_object_with_special_methods(self): from array import array class Num(object): def __float__(self): return 5.25 def __int__(self): return 7 class NotNum(object): pass class Silly(object): def __float__(self): return None def __int__(self): return None class OldNum: def __float__(self): return 6.25 def __int__(self): return 8 class OldNotNum: pass class OldSilly: def __float__(self): return None def __int__(self): return None for tc in 'bBhHiIlL': a = array(tc, [0]) raises(TypeError, a.__setitem__, 0, 1.0) a[0] = 1 a[0] = Num() assert a[0] == 7 raises(TypeError, a.__setitem__, NotNum()) a[0] = OldNum() assert a[0] == 8 raises(TypeError, a.__setitem__, OldNotNum()) raises(TypeError, a.__setitem__, Silly()) raises(TypeError, a.__setitem__, OldSilly()) for tc in 'fd': a = array(tc, [0]) a[0] = 1.0 a[0] = 1 a[0] = Num() assert a[0] == 5.25 raises(TypeError, a.__setitem__, NotNum()) a[0] = OldNum() assert a[0] == 6.25 raises(TypeError, a.__setitem__, OldNotNum()) raises(TypeError, a.__setitem__, Silly()) raises(TypeError, a.__setitem__, OldSilly()) a = array('c', 'hi') a[0] = 'b' assert a[0] == 'b' a = array('u', u'hi') a[0] = u'b' assert a[0] == u'b'
'''6: Write a Python program to convert an array to an array of machine values and return the bytes representation. Expected Output: Original array: A1: array('i', [1, 2, 3, 4, 5, 6]) Array of bytes: b'010000000200000003000000040000000500000006000000''' from array import * A1 = array('i', [1, 2, 3, 4, 5, 6]) print(A1.tobytes())
from array import * li = array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9]) print(li) l = len(li) for i in range(l): print(li[i])
def make_var_hist(name, nbins, xarray): h = ROOT.TH1F(name, name, nbins, xarray) return h main_dir = "/home/software/users/napadula/" plot_dir = main_dir + "plots/" root_dir = main_dir + "rootfiles/" ofile = "InvMass_ptbins_" + args.energy + "_" + args.system + "_" + args.trailer + ".root" png = args.system + args.energy + args.trailer + ".png" nbins = 8 pt_low = [3, 4, 5, 6, 7, 8, 10, 12] pt_high = [4, 5, 6, 7, 8, 10, 12, 15] pt_mid = [3.5, 4.5, 5.5, 6.5, 7.5, 9, 11, 13.5] pt_edge = array('d', [3, 4, 5, 6, 7, 8, 10, 12, 15]) root_filename = root_dir + ofile rootfile = ROOT.TFile.Open(root_filename, "READ") branch_names = [ 'inv_mass', 'pt_cand', 'pt_prong0', 'pt_prong1', 'dca', 'cos_t_star', 'imp_par_prod', 'cos_p' ] cut_names = [ 'pt_prong0', 'pt_prong1', 'dca', 'cos_t_star', 'imp_par_prod', 'cos_p' ] cut_type = ['greater', 'greater', 'less', 'abs', 'less', 'greater'] cut_value = [[0.7, 0.7, 0.03, 0.8, -0.0002, 0.9], [0.7, 0.7, 0.03, 0.8, -0.0002, 0.9], [0.7, 0.7, 0.03, 0.8, -0.00005, 0.85],
# remove the first occurence of a specified element from an array from array import * a = array('i', [1, 3, 5, 3, 7, 3, 9]) ele = 3 ''' for i in a: if ele==i: del i ''' b = array('i', []) for i in a: if i != 3: b.append(i) print "after removing all the occurence:" for i in b: print i ''' afer removing all the occurence: 1 5 7 9 '''
from array import * arr = array('i', [1, 2, 3], [5, 6, 7]) array([], datatype) linspace(0, 15, 16) #divided into 16 parts,(default 50 parts) gap is same. logspace(1, 40, 5) #print('%2f' %arr[4])10^1,10^40 and 5 parts arange(1, 15, 2) #stpes(1,3,5...) zeros(5, int) #all zeros(default float) ones(5, int) #all ones(default float) print(arr)
from array import * vals = array('i', [1, 2, 3, 4, -5, 9, 10]) print(vals)
Arrays can used the u code to create an array of Strings but will be deprecated""" """ Arrays in Python are strong typed. A type is required in order to create Type code C Type Python Type Minimum size (bytes) 'b' signed char int 1 'B' unsigned char int 1 'u' Py_UNICODE Unicode character 2 'h' signed short int 2 'H' unsigned short int 2 'i' signed int int 2 'I' unsigned int int 2 'l' signed long int 4 'L' unsigned long int 4 'q' signed long long int 8 'Q' unsigned long long int 8 'f' float float 4 'd' double float 8 u will be deprecated in 3.3 """ """Generate an Array of Integer""" a = array('i', [12, 3040, 120033]) print(a) """array.typecode property that displays the typecode character used to create the array.""" print(a.typecode) """array.buffer_info() Return a tuple (address, length) giving the current memory address and the length in elements of the buffer used to hold array’s contents. The size of the memory buffer in bytes can be computed as array.buffer_info()[1] * array.itemsize. This is occasionally useful when working with low-level (and inherently unsafe) I/O interfaces that require memory addresses, such as certain ioctl() operations. The returned numbers are valid as long as the array exists and no length-changing operations are applied to it.""" print(a.buffer_info())
""" Write a Python program to insert a new item before the second element in an existing array. """ from array import * array_test = array('i', [1, 3, 5, 7, 9]) print(f"Original array: {array_test}") print("Insert new value 4 before 3:") array_test.insert(1, 4) print("New array: " + str(array_test))
from array import * arr=array('i',[]) n=int(input("enter size of array : ")) for i in range(n): temp=int(input()) arr.insert(i,temp) print("array is : ") print(arr) print("after converting array in list form : ") arr=list(arr) print(arr)
def append_value_end_array(self): array_num = array('i', [1, 3, 5, 7, 9]) print("Original array: " + str(array_num)) print("Append 11 at the end of the array:") array_num.append(11) print("New array: " + str(array_num))
from array import * arr= array('i',[2,3,4,5]) for i in range(len(arr)): print(arr[i]+5)
from array import * a = array('i', [1, 2, 3, 4]) print("ARRAY ELEMENTS ARE") for i in a: print(i) print(a[0]) print(a[3])
hinput1 = hist1 hinput2 = hist2 if options.buildFakeRate: # in this case the input TH2 have eta on x axis and offset/slope on the other one # this is needed only for muons, for electrons I save directly the smoothed FR (PR) neta = hist1.GetNbinsX() etabins = [ hist1.GetXaxis().GetBinLowEdge(i) for i in range(1, 2 + neta) ] #etamin = hist1.GetXaxis().GetBinLowEdge(1) #etamax = hist1.GetXaxis().GetBinLowEdge(1+neta) #hFR1 = ROOT.TH2D(hist1.GetName()+"_FRorPR","",195,26,65,neta,etamin,etamax) #hFR2 = ROOT.TH2D(hist2.GetName()+"_FRorPR","",195,26,65,neta,etamin,etamax) hFR1 = ROOT.TH2D(hist1.GetName() + "_FRorPR", "", 195, 26, 65, neta, array('d', etabins)) hFR2 = ROOT.TH2D(hist2.GetName() + "_FRorPR", "", 195, 26, 65, neta, array('d', etabins)) for ix in range(1, 1 + hFR1.GetNbinsX()): for iy in range(1, 1 + hFR1.GetNbinsY()): fr1 = hist1.GetBinContent(iy, 1) + hist1.GetBinContent( iy, 2) * hFR1.GetXaxis().GetBinCenter(ix) hFR1.SetBinContent(ix, iy, fr1) fr2 = hist2.GetBinContent(iy, 1) + hist2.GetBinContent( iy, 2) * hFR2.GetXaxis().GetBinCenter(ix) hFR2.SetBinContent(ix, iy, fr2) hinput1 = hFR1 hinput2 = hFR2 if options.roll1Dto2D: # TO DO
tempSocket.connect((serverName, serverPort)) sutIP = tempSocket.getsockname()[0] tempSocket.close() print("Local IP Address: " + str(sutIP)) print("SUT Port Number: " + str(sutport)) sutIPHexContainer = split(sutIP, '.') # Convert IP address to number then to hex sutIPNum = int(sutIPHexContainer[0]) * 256**3 + int(sutIPHexContainer[1]) * 256**2 + int(sutIPHexContainer[2]) * 256 + int(sutIPHexContainer[3]) sutIPHex = '0x{0:08X}'.format(sutIPNum) print(sutIPHex) sutPortHex = '0x{0:04X}'.format(sutport) print("Sending IP Address in hex: " + str(sutIPHex) + " and port in hex: " + str(sutPortHex)) # Construct Packet bitArray = array('l') first16Bits = 0x8164 bitArray.append(first16Bits) second16Bits = 0x0107 bitArray.append(second16Bits) # Add cookie to packet clientCookie = 0x023F bitArray.append(clientCookie) bitArray.append(clientCookie) # Add IP to packet sutIPHex1 = '0x' + sutIPHex[2:6] sutIPHex2 = '0x' + sutIPHex[6:len(sutIPHex)] bitArray.append(int(sutIPHex1, 16)) bitArray.append(int(sutIPHex2, 16))
# array of samples signal_samples = signal[1] signal_samples = signal_samples.astype(np.int64) filename2 = filename + ".detection.txt" vad_file = open(filename2, 'w') # frame size: 25ms (400 samples) # overlapping 15ms (240 samples) N = 400 # frame number (starts from 1) frame_no = 0 # voice-active decision for each frame vad_decision = array('d') energy = 0 # initial value of threshold for i in range(0, len(noise[1]), 160): x = noise_samples[i:i + N] if len(x) < N: break frame_no += 1 # energy detector # calculate energy of a frame energy += sum(np.square(x) / N)
from array import * array1 = array('i', [10, 20, 30, 40, 50]) for x in array1: print(x) # 访问数组元素 print(array1[0]) # 插入操作 array1.insert(1, 60) for x in array1: print(x) # 删除 array1.remove(60) for x in array1: print(x) # 查找/搜索 print(array1.index(50)) # 更新 array1[2] = 1000 print(array1[2]) for x in array1: print(x) # ===== 二维数组 ===== T = [[11, 12, 5, 2], [15, 6, 10], [10, 8, 12, 5], [12, 15, 8, 6]] print(T[0])
def __mode_EHV(self, data, allrange, _ar_labels, _ar_units, _ec, _xc, _yc, _graphs_joined=1): #allrange, units = _rescale_range(allrange) #allrange, units = _rescale_range(allrange, _ar_units, _ec, _xc, _yc) allrange, units = uti_plot_com.rescale_range(allrange, _ar_units, _ec, _xc, _yc) #e0, e1, ne, x0, x1, nx, y0, y1, ny = allrange e0, e1, ne, x0, x1, nx, y0, y1, ny, ec, xc, yc = allrange #e = np.linspace(e0, e1, ne) #x = np.linspace(x0, x1, nx) #y = np.linspace(y0, y1, ny) #ie = np.where(data.sum(axis=1)==data.sum(axis=1).max())[0][0] #ix = np.where(abs(x)==abs(x).min())[0][0] #iy = np.where(abs(y)==abs(y).min())[0][0] range_e = e0, e1, ne range_x = x0, x1, nx range_y = y0, y1, ny ie = 0 if ne > 1: if ec > e1: ie = ne - 1 elif ec > e0: eStep = (e1 - e0) / (ne - 1) if eStep > 0: ie = int(round((ec - e0) / eStep)) ix = 0 if nx > 1: if xc > x1: ix = nx - 1 elif xc > x0: xStep = (x1 - x0) / (nx - 1) if xStep > 0: ix = int(round((xc - x0) / xStep)) iy = 0 if ny > 1: if yc > y1: iy = ny - 1 elif yc > y0: yStep = (y1 - y0) / (ny - 1) if yStep > 0: iy = int(round((yc - y0) / yStep)) #label2D = ("Horizontal Position, ["+units[1]+"]", "Vertical Position, ["+units[2]+"]") label2D = (_ar_labels[1] + ' [' + units[1] + ']', _ar_labels[2] + ' [' + units[2] + ']') #label1E = ("Energy, ["+units[0]+"]","Ph/s/0.1%BW/mm^2") label1E = (_ar_labels[0] + ' [' + units[0] + ']', _ar_labels[3] + ' [' + units[3] + ']') #label1H = ("Horizontal Position, ["+units[1]+"]","Ph/s/0.1%BW/mm^2") label1H = (_ar_labels[1] + ' [' + units[1] + ']', _ar_labels[3] + ' [' + units[3] + ']') #label1V = ("Vertical Position, ["+units[2]+"]","Ph/s/0.1%BW/mm^2") label1V = (_ar_labels[2] + ' [' + units[2] + ']', _ar_labels[3] + ' [' + units[3] + ']') arCutXY = array('d', [0] * nx * ny) perY = ne * nx i = 0 for iiy in range(ny): perY_iiy = perY * iiy for iix in range(nx): arCutXY[i] = data[ie + ne * iix + perY_iiy] i += 1 arCutE = array('d', [0] * ne) perX_ix = ne * ix perY_iy = perY * iy for iie in range(ne): arCutE[iie] = data[iie + perX_ix + perY_iy] arCutX = array('d', [0] * nx) for iix in range(nx): arCutX[iix] = data[ie + ne * iix + perY_iy] arCutY = array('d', [0] * ny) for iiy in range(ny): arCutY[iiy] = data[ie + perX_ix + perY * iiy] #fig = _pl.figure(figsize=(8,8)) #_plot_2D(data[:,:,ie], range_x, range_y, label2D, fig, 221) #_plot_1D(data[ix,iy,:],range_e,label1E,fig,224) #_plot_1D(data[ie,:,iy],range_x,label1H,fig,222) #_plot_1D(data[:,ix,ie],range_y,label1V,fig,223) fig = None if _graphs_joined: fig = self._pl.figure(figsize=(12, 5)) self._plot_2D(arCutXY, range_x, range_y, label2D, fig, 221) #showing graphs in one figure self._plot_1D(arCutE, range_e, label1E, fig, 222) self._plot_1D(arCutX, range_x, label1X, fig, 223) self._plot_1D(arCutY, range_y, label1Y, fig, 224) else: self.uti_plot2d(arCutXY, range_x, range_y, label2D) self.uti_plot1d(arCutE, range_e, label1E) self.uti_plot1d(arCutX, range_x, label1X) self.uti_plot1d(arCutY, range_y, label1Y) return self._maybe_savefig(fig)
from array import * arr = array('i', []) # creates an empty array length = int(input("enter the no of students")) for i in range(length): n = int(input("enter the marks of students")) arr.append(n) for maria in arr: print(maria)
pivot = a[e] for j in range(s, e): if a[j] <= pivot: a[i], a[j] = a[j], a[i] i += 1 a[i], a[e] = a[e], a[i] return i def sort(a, s, e): if (s < e): p = divide(a, s, e) sort(a, s, p - 1) sort(a, p + 1, e) from array import * n = int(input("Enter number of elements : ")) val = array('i', []) print("Enter elements : ") for i in range(n): x = int(input()) val.append(x) print("Array before sorting :") for i in val: print(i, end=" ") print() sort(val, 0, n - 1) for i in val: print(i, end=" ")
def uti_plot2d1d(self, data, x_range, y_range, xc, yc, labels, _graphs_joined=True): x0 = x_range[0] x1 = x_range[1] nx = x_range[2] #y0 = x_range[0]; y1 = y_range[1]; ny = y_range[2] y0 = y_range[0] y1 = y_range[1] ny = y_range[2] #OC090714 label2D = labels[0] label1H = labels[1] label1V = labels[2] fig = None if _graphs_joined: #fig = _pl.figure(figsize=(12,5)) fig = self._pl.figure(figsize=(15, 5.3)) self._plot_2D(data, x_range, y_range, label2D, fig, 131) #showing graphs in one panel else: self.uti_plot2d(data, x_range, y_range, label2D) xStep = 0 if nx > 1: xStep = (x1 - x0) / (nx - 1) yStep = 0 if ny > 1: yStep = (y1 - y0) / (ny - 1) inperpOrd = 1 #interpolation order to use (1 to 3) #_plot_1D(data[iy,:],range_x,label1H,fig,132) arCutX = array('d', [0] * nx) xx = x0 for ix in range(nx): arCutX[ix] = uti_math.interp_2d(xx, yc, x0, xStep, nx, y0, yStep, ny, data, inperpOrd, 1, 0) xx += xStep if _graphs_joined: self._plot_1D(arCutX, x_range, label1H, fig, 132) #OC150814 else: self.uti_plot1d(arCutX, x_range, label1H) #_plot_1D(data[:,ix],range_y,label1V,fig,133) arCutY = array('d', [0] * ny) yy = y0 for iy in range(ny): #arCutY[iy] = _interp_2d(xc, yy, x0, xStep, nx, y0, yStep, ny, data, inperpOrd, 1, 0) arCutY[iy] = uti_math.interp_2d(xc, yy, x0, xStep, nx, y0, yStep, ny, data, inperpOrd, 1, 0) yy += yStep if _graphs_joined: self._plot_1D(arCutY, y_range, label1V, fig, 133) else: self.uti_plot1d(arCutY, y_range, label1V) if _graphs_joined: self._pl.tight_layout() #OC081115 return self._maybe_savefig(fig)
import random from array import * tablica = array('d') for i in range(10): tablica.append(random.uniform(-5, 5)) file = open("result.txt", "w") file.write(str(tablica)) file.close()
def _plot_2D(self, ar2d, x_range, y_range, labels, fig, typ=111): #totLen = int(x_range[2]*y_range[2]) #lenAr2d = len(ar2d) #if lenAr2d > totLen: ar2d = np.array(ar2d[0:totLen]) #elif lenAr2d < totLen: # auxAr = array('d', [0]*lenAr2d) # for i in range(lenAr2d): auxAr[i] = ar2d[i] # ar2d = np.array(auxAr) #if isinstance(ar2d,(list,array)): ar2d = np.array(ar2d) #ar2d = ar2d.reshape(y_range[2],x_range[2]) isDataAr = False #OC30052020 if isinstance(ar2d, (list, array)): isFlat = True if isinstance(ar2d[0], (list, array)): isFlat = False if ((x_range is None) or (y_range is None)): if isFlat: raise Exception( 'Mesh / grid description for 2D plot is not provided') if x_range is None: nx = len(ar2d[0]) x_range = [0, nx - 1, nx] if y_range is None: ny = len(ar2d) y_range = [0, ny - 1, ny] if isFlat: totLen = int(x_range[2] * y_range[2]) lenAr2d = len(ar2d) if lenAr2d > totLen: ar2d = np.array(ar2d[0:totLen]) elif lenAr2d < totLen: auxAr = array('d', [0] * lenAr2d) for i in range(lenAr2d): auxAr[i] = ar2d[i] ar2d = np.array(auxAr) ar2d = np.array(ar2d) ar2d = ar2d.reshape(y_range[2], x_range[2]) isDataAr = True else: #Perhaps this is not necessary? Image will be displayed in standard way then (with pixel row number starting from top) nx = 0 ny = 0 if (x_range is None): nx, ny = ar2d.size x_range = [0, nx - 1, nx] if (y_range is None): if (ny == 0): nx, ny = ar2d.size y_range = [0, ny - 1, ny] ax = fig.add_subplot(typ) #x = np.linspace(x_range[0],x_range[1],x_range[2]) #y = np.linspace(y_range[0],y_range[1],y_range[2]) x = np.linspace( x_range[0], x_range[1], x_range[2]) if x_range is not None else None #OC30052020 y = np.linspace(y_range[0], y_range[1], y_range[2]) if y_range is not None else None #ax.pcolormesh(x,y,ar2d,cmap=self._pl.cm.Greys_r) #OC150814 if isDataAr: ax.pcolormesh(x, y, ar2d, cmap=self._pl.cm.Greys_r) #OC30052020 else: ax.imshow( ar2d, cmap=self._pl.cm.Greys_r) #OC30052020 (assuming PIL.Image) #ax.set_xlim(x[0],x[-1]) #ax.set_ylim(y[0],y[-1]) if x is not None: ax.set_xlim(x[0], x[-1]) #OC30052020 if y is not None: ax.set_ylim(y[0], y[-1]) ax.set_xlabel(labels[0]) ax.set_ylabel(labels[1]) if (len(labels) > 2): ax.set_title(labels[2])
from array import * x=array('i',[1,2,3,4,1,5,1,6,2,3,1,5,10,25,5,2,221,2,3,4,1,5,1,6,2,3,1,5,10,3,1,5,10,25,5,2,2]) s=int(input('enter the number whose occurence is to be counted: ')) print(s,' occurs ',x.count(s),' times in the array')
""" Write a Python program to append a new item to the end of the array. """ from array import * array_num = array('i', [1, 3, 5, 7, 9]) print("Original array: " + str(array_num)) print("Append 11 at the end of the array:") array_num.append(11) print("New array: " + str(array_num))