def read_sensor(sensor_pin): # Read sensor data humidity, temperature = read_retry(DHT22, sensor_pin) if humidity is None and temperature is None: trace("Failed to get reading on sensor: " + str(sensor_pin), ERROR) return (temperature, humidity)
def get_recipe(recipe, refresh): client = trace(get_client) notestore = trace(client.get_note_store) # Get the note metadata without a body or resources. This result contains # the body hash used for caching. partial = tracen('Evernote.note_store.getNote', notestore.getNote, recipe, False, False, False, False) # Check the cache for this note. key = '%s%s_%s' % (vmenu.app.config['CACHE_PREFIX'], binascii.hexlify(partial.contentHash), vmenu.app.config['RECIPE_IMAGES']) content = cache.get(key) if content is None or refresh: if refresh: logging.info('Explicitly refreshing %s', key); else: logging.info('Cache miss for %s', key) full = tracen('Evernote.note_store.getNote', notestore.getNote, recipe, True, False, False, False) content = strip_tags(full.content.decode('utf-8')) def process(): url_prefix = trace(get_url_prefix) if full.resources is not None and vmenu.app.config['RECIPE_IMAGES']: for resource in full.resources: content = trace(update_resource, url_prefix, content, resource) trace(process) # Cache the content. The key is the MD5 hash of the server stored content # but the stored value in this cache has stripped out tags. cache.set(key, content, timeout=vmenu.app.config['CACHE_TIMEOUT']) return { "content": content }
def find_nodes_to_add_edges(this_tg, inkml_obj): if len(inkml_obj.objects) == 1: return [] elif len(inkml_obj.objects) <= 3: return [i.id for i in inkml_obj.objects if i.id != this_tg.id] this_tg_tr = trace() for t in inkml_obj.get_traces_in_object(this_tg.id): this_tg_tr.x.extend(t.x) this_tg_tr.y.extend(t.y) this_tg_tr.calculate_centroids() this_tg_tr.id = "this" dist = {} for tg in range(len(inkml_obj.objects)): if inkml_obj.objects[tg].id != this_tg.id: other_tg_tr = trace() for t in inkml_obj.get_traces_in_object(inkml_obj.objects[tg].id): other_tg_tr.x.extend(t.x) other_tg_tr.y.extend(t.y) other_tg_tr.calculate_centroids() other_tg_tr.id = "Other" # if this_tg_tr.bb_center_x <= other_tg_tr.bb_center_x: this_dist = this_tg_tr.get_distance_bb_center(other_tg_tr) dist[inkml_obj.objects[tg].id] = this_dist dist = sorted(dist.items(), key=lambda x: x[1]) if len(dist) >= 2: return [dist[0][0], dist[1][0]] elif len(dist) == 1: return [dist[0][0]] return []
def get_features(obj1_traces, obj2_traces): tr1 = trace() for tr in obj1_traces: tr1.x.extend(tr.x) tr1.y.extend(tr.y) tr1.calculate_centroids() tr1.id = 'O1' tr2 = trace() for tr in obj2_traces: tr2.x.extend(tr.x) tr2.y.extend(tr.y) tr2.calculate_centroids() tr2.id = 'O2' features = [] features.append(get_vertical_bb_distance(tr1, tr2)) features.append(get_hor_bb_distance(tr1, tr2)) features.extend(feature_corner_angle_with_center(tr1, tr2)) features.append(get_angle_between_bb(tr1, tr2)) features.append(get_distance_between_bb_center(tr1, tr2)) features.extend(get_offsets([tr1, tr2])) features.extend(feature_PSC(tr1, tr2)) # traces = [] # for tr in [tr1, tr2]: # traces.append(tr.x) # traces.append(tr.y) # # traces_dense = sfe.add_points_lin(traces) # # histogram_of_points = sfe.get_histogram_of_points(traces_dense, 5) # features.extend(histogram_of_points) return features
def measure(): # Read data from sensors measurements = [] for sensor in get_sensors(): if sensor["type"] == "DHT22": temp, humidity = dht22.read_sensor(sensor["id"]) if temp != None: measurements.append({ "field": sensor["temperature"], "value": temp }) if humidity != None: measurements.append({ "field": sensor["humidity"], "value": humidity }) elif sensor["type"] == "DS18B20": temp = ds18b20.read_sensor(get_config("DS18B20_sensor_path"), sensor["id"]) if temp != None: measurements.append({ "field": sensor["temperature"], "value": temp }) else: trace("Unknown sensor type: " + str(sensor), ERROR) return measurements
def process_notes(): url_prefix = trace(get_url_prefix) for n in notes: result = { 'guid': n.guid, 'title': n.title, 'thumbnail': trace(get_thumbnail, url_prefix, n.guid) } results.append(result)
def sub_by_rotor(self, rotor_num, num): """ substitute the number by one rotor""" trace(num, '>') assert num in self.alphabet num += self.shift[rotor_num] num = num % self.alpha_len num = self.rotors[rotor_num][num] num -= self.shift[rotor_num] num = num % self.alpha_len trace(num, '>') return num
def configure(self): # could be more orthogonal : conf_file = conf_3.py ''' the enigma gets it's attributes from the conf file ''' import conf_3 # maybe more efficiant: for att in enigma.attributes: # self.att = conf_3.att() self.rotors = conf_3.rotors() self.shift = conf_3.shift() trace(self.shift) self.plugboard = conf_3.plugboard() self.calculate_extra_attributes()
def configure(self): # could be more orthogonal : conf_file = conf.py ''' the enigma gets it's attributes from the conf file ''' # AUR: importing in non-global scope is frowned upon, and I # agree it usually just confuses things import conf # maybe more efficiant: for att in enigma.attributes: # self.att = conf.att() self.rotors = conf.rotors() self.shift = conf.shift() trace(self.shift) self.plugboard = conf.plugboard() self.calculate_extra_attributes()
def log(measurements): # Logging if(not has_config("logging")): trace("no logging", INFO) return logging = get_config("logging") if "trace" in logging: trace(measurements, logging["trace"]["level"]) if "thingspeak" in logging: post_thingspeak_channel_update(measurements, logging["thingspeak"]["channel_key"])
def ray_fan_Y_single(lens, Hx=0, Hy=0, wave=0, **options): num_pts = 50 ys = [] py = np.linspace(-1,1,num_pts) yp,up = paraxial_trace_HP(lens,Hx=Hx,Hy=Hy,Px=0,Py=0,wave=wave) for pt in py: raytrace = trace(lens,Hx=Hx,Hy=Hy,Px=0,Py=pt,wave=wave) raytrace.run() ys.append(raytrace.y[-1] - yp[-1]) raytrace = trace(lens,Hx=Hx,Hy=Hy,Px=0,Py=0,wave=wave).run() ys = [y-raytrace.y[-1]+yp[-1] for y in ys] # remove distortion return py, ys
def spot_diagram_standard(lens, pupil_distribution, Hx, Hy, airy=False): fig, ax = plt.subplots() colors = ['r+','gx','b*','cd','mv','yh'] geo = [] for idw, wave in enumerate(lens.wavelengths_list): xs = [] ys = [] for Px,Py in pupil_distribution.points: raytrace = trace(lens,Hx,Hy,Px,Py,wave=idw).run() xs.append(raytrace.x[-1]) ys.append(raytrace.y[-1]) ax.plot(xs,ys,colors[idw%6],label='%.1f nm'%wave) geo.append(spot_geometric_radius(xs,ys)) rad_str = 'Wave: %.1f nm, RMS Radius: %.3f mm, Geo. Radius: %.3f mm'%(wave,spot_rms(xs,ys),geo[-1]) print(rad_str) if airy: theta = np.linspace(0,2*np.pi,100) r = 1.22*lens.wavelengths_list[lens.prim_wave]/1e6*lens.FNO() x = r*np.cos(theta) y = r*np.sin(theta) ax.plot(x,y,'k') box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) plt.xlabel('Image Plane X (%s)'%lens.length_unit) plt.ylabel('Image Plane Y (%s)'%lens.length_unit) plt.title('%s, Spot Diagram: Hx=%.1f, Hy=%.1f'%(lens.name.title(),Hx, Hy)) plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) ax.set_aspect('equal', adjustable='box') plt.show()
def generer(self): if self.trois_D : p1 = Point(0,0,0) p2 = Point(1,0,0) p3 = Point(1,1,0) p4 = Point(0,1,0) base = Facette([p1, p2, p3, p4]) self.terrain = Paysage(base) else : p1 = Point(0,0) p2 = Point(1,0) base = Facette([p1, p2]) self.terrain = Paysage(base) for i in range(self.nb_iter): self.terrain.itere(self.puiss, self.fraction) X, Y, Z = trace(self.terrain) self.ui.matplotlib.axes.clear() if len(Z) < 1 : #2D self.axes2D = self.figure2D.add_subplot(111) self.ui.matplotlib.axes.plot(X,Y,'r-') self.ui.matplotlib.axes.hold(True) self.ui.matplotlib.draw() else : #3D self.axes2D = None self.axes3D = self.figure3D.gca(projection='3d') #self.axes = self.figure.add_subplot(111, projection='3d') self.axes3D.set_axis_off() self.axes3D.plot_surface(X, Y, Z, cmap=cm.ocean) #ou terrain show() self.ui.matplotlib.draw()
def mtf_geometric_single(lens, v0, Hx=0, Hy=0, wave=0, N=300): # define pupil distribution for raytrace dist = distribution(type_='rectangular', num_pts=500) # raytrace xs = [] ys = [] for Px,Py in dist.points: raytrace = trace(lens,Hx,Hy,Px,Py,wave).run() xs.append(raytrace.x[-1]) ys.append(raytrace.y[-1]) # find line spread function by integrating along x using histogram rad_geo = spot_geometric_radius(xs, ys) dx = 2*rad_geo/N bins = np.arange(-rad_geo,rad_geo,dx) A, x = np.histogram(xs, bins) v = np.linspace(0,v0,len(A)) # x is bin edges, use the upper edge of bin x = x[1:] # calculate MTF at different cycles/mm denom = np.sum(A*dx) MTF = np.zeros_like(v) for k in range(len(v)): numC = np.sum(A * np.cos(2*np.pi*v[k]*x) * dx) numS = np.sum(A * np.sin(2*np.pi*v[k]*x) * dx) Ac = numC/denom As = numS/denom MTF[k] = np.sqrt(Ac**2 + As**2) return v,MTF
def get_tags(refresh): key = vmenu.app.config['CACHE_PREFIX'] + 'tags' tags = cache.get(key) if tags is None or refresh: if refresh: logging.info('Explicitly refreshing %s', key); else: logging.info('Cache miss for %s', key) client = trace(get_client) notestore = trace(client.get_note_store) notebook = trace(get_notebook, notestore, vmenu.app.config['NOTEBOOK']) tags = tracen('Evernote.note_store.listTagsByNotebook', notestore.listTagsByNotebook, notebook.guid) tags = sorted(tags, key = lambda Tag: Tag.name) cache.set(key, tags, timeout=vmenu.app.config['CACHE_TIMEOUT']) return tags
def thingspeak_post_request(endpoint, param_dict): #performs a GET request on the given URL with the params in URL-encoded form #returns response payload or False if the response was not positive url = "https://api.thingspeak.com/" + endpoint trace("POST: " + url + " Params:" + str(param_dict), INFO) try: request = urllib2.Request(url, urllib.urlencode(param_dict)) response = urllib2.urlopen(request) data = response.read() trace("Response: " + data, INFO) return data except urllib2.URLError as e: trace("Negative response from Thingspeak: " + e.reason, WARN) except: trace("Connection to Thingspeak failed", ERROR) trace(str(sys.exc_info()), WARN) return False
def __init__(self, keymap, verbose=0, invalid_cls=None, character_cls=None): self.verbose = verbose from pyrepl.keymap import compile_keymap, parse_keys self.keymap = keymap self.invalid_cls = invalid_cls self.character_cls = character_cls d = {} for keyspec, command in keymap: keyseq = tuple(parse_keys(keyspec)) d[keyseq] = command if verbose: trace('[input] keymap: {}', pprint.pformat(d)) self.k = self.ck = compile_keymap(d, ()) self.results = deque() self.stack = []
def spot_diagram_standard_single(lens, pupil_distribution, Hx, Hy, wave=0, **options): xs = [] ys = [] for Px,Py in pupil_distribution.points: raytrace = trace(lens,Hx,Hy,Px,Py,wave).run() xs.append(raytrace.x[-1]) ys.append(raytrace.y[-1]) return xs, ys
def get_tags(refresh): key = vmenu.app.config['CACHE_PREFIX'] + 'tags' tags = cache.get(key) if tags is None or refresh: if refresh: logging.info('Explicitly refreshing %s', key) else: logging.info('Cache miss for %s', key) client = trace(get_client) notestore = trace(client.get_note_store) notebook = trace(get_notebook, notestore, vmenu.app.config['NOTEBOOK']) tags = tracen('Evernote.note_store.listTagsByNotebook', notestore.listTagsByNotebook, notebook.guid) tags = sorted(tags, key=lambda Tag: Tag.name) cache.set(key, tags, timeout=vmenu.app.config['CACHE_TIMEOUT']) return tags
def sub_by_rotor(self, rotor_num, num): """ substitute the number by one rotor""" trace(num, '>') assert num in self.alphabet # AUR: You're doing all these rotations all the time, and your code is full of # increment-then-%... Maybe the codebase would be clearer if you used a # "modular number" class? # # Something like: # >>> a = ModNum(16, 5) # >>> a # 5mod16 # >>> a + 1 # 6mod16 # >>> a = a + a + a + a # >>> a # 4mod16 # # or maybe the less magical: # >>> a = Rotor(6, 5) # >>> a # <Rotor 6> # >>> a.value # 5 # >>> a.increase() # >>> a.value # 0 # >>> a.decrease() # >>> a.value # 5 # # In general, a very good thought technique when programming is asking "what are my # core concepts?" and making those easy to "speak in" without needing to do # bookkeeping. num += self.shift[rotor_num] num = num % self.alpha_len num = self.rotors[rotor_num][num] num -= self.shift[rotor_num] num = num % self.alpha_len trace(num, '>') return num
def read_sensor(sensor_path, sensor_id): # Read value of a temperature sensor_id lines = read_temperature_raw(sensor_path, sensor_id) remaining_retry = 10 while lines[0].strip()[-3:] != "YES": time.sleep(0.2) lines = read_temperature_raw(sensor_path, sensor_id) if remaining_retry == 0: trace("Sensor: " + str(sensor_id) + "read failed giving up", ERROR) return 0.0 else: trace("Sensor: " + str(sensor_id) + "read failed retry", WARN) remaining_retry = remaining_retry - 1 temp_output = lines[1].find("t=") if temp_output != -1: temp_string = lines[1].strip()[temp_output + 2:] temp_centigrade = float(temp_string) / 1000.0 return temp_centigrade
def get_recipes(tag, refresh): key = vmenu.app.config['CACHE_PREFIX'] + 'recipes-' + tag results = cache.get(key) if results is None or refresh: if refresh: logging.info('Explicitly refreshing %s', key) else: logging.info('Cache miss for %s', key) client = trace(get_client) notestore = trace(client.get_note_store) notebook = trace(get_notebook, notestore, vmenu.app.config['NOTEBOOK']) tag_guids = [tag] filter = NoteFilter(notebookGuid=notebook.guid, tagGuids=tag_guids) offset = 0 max_notes = 500 result_spec = NotesMetadataResultSpec(includeTitle=True) notes_result = tracen('Evernote.note_store.findNotesMetadata', notestore.findNotesMetadata, filter, offset, max_notes, result_spec) notes = sorted(notes_result.notes, key=lambda NoteMetadata: NoteMetadata.title) results = [] def process_notes(): url_prefix = trace(get_url_prefix) for n in notes: result = { 'guid': n.guid, 'title': n.title, 'thumbnail': trace(get_thumbnail, url_prefix, n.guid) } results.append(result) trace(process_notes) cache.set(key, results, timeout=vmenu.app.config['CACHE_TIMEOUT']) return results
def pipe(img_path, colors_num=16, blur=True, max_pieces_size=0): img = cv2.imread(img_path) img = img_blur(img) img = img_quantize(img, 7) cols, rows, _ = img.shape svg = SVGBuilder() svg.create_canvas(width=rows, height=cols) outlines = trace(img) draw_outlines(svg, outlines)
def ray_fan_X_single(lens, Hx=0, Hy=0, wave=0, **options): num_pts = 25 xs = [] px = np.linspace(0,1,num_pts) yp,up = paraxial_trace_HP(lens,Hx=Hx,Hy=Hy,Px=0,Py=0,wave=wave) for pt in px: raytrace = trace(lens,Hx=Hx,Hy=Hy,Px=pt,Py=0,wave=wave) raytrace.run() xs.append(raytrace.x[-1] - yp[-1]) xs = [x-xs[0] for x in xs] # remove distortion return px, xs
def get_recipe(recipe, refresh): client = trace(get_client) notestore = trace(client.get_note_store) # Get the note metadata without a body or resources. This result contains # the body hash used for caching. partial = tracen('Evernote.note_store.getNote', notestore.getNote, recipe, False, False, False, False) # Check the cache for this note. key = '%s%s_%s' % (vmenu.app.config['CACHE_PREFIX'], binascii.hexlify(partial.contentHash), vmenu.app.config['RECIPE_IMAGES']) content = cache.get(key) if content is None or refresh: if refresh: logging.info('Explicitly refreshing %s', key) else: logging.info('Cache miss for %s', key) full = tracen('Evernote.note_store.getNote', notestore.getNote, recipe, True, False, False, False) content = strip_tags(full.content.decode('utf-8')) def process(): url_prefix = trace(get_url_prefix) if full.resources is not None and vmenu.app.config['RECIPE_IMAGES']: for resource in full.resources: content = trace(update_resource, url_prefix, content, resource) trace(process) # Cache the content. The key is the MD5 hash of the server stored content # but the stored value in this cache has stripped out tags. cache.set(key, content, timeout=vmenu.app.config['CACHE_TIMEOUT']) return {"content": content}
def get_recipes(tag, refresh): key = vmenu.app.config['CACHE_PREFIX'] + 'recipes-' + tag results = cache.get(key) if results is None or refresh: if refresh: logging.info('Explicitly refreshing %s', key); else: logging.info('Cache miss for %s', key) client = trace(get_client) notestore = trace(client.get_note_store) notebook = trace(get_notebook, notestore, vmenu.app.config['NOTEBOOK']) tag_guids = [tag] filter = NoteFilter(notebookGuid=notebook.guid, tagGuids=tag_guids) offset = 0 max_notes = 500 result_spec = NotesMetadataResultSpec(includeTitle=True) notes_result = tracen('Evernote.note_store.findNotesMetadata', notestore.findNotesMetadata, filter, offset, max_notes, result_spec) notes = sorted(notes_result.notes, key = lambda NoteMetadata: NoteMetadata.title) results = [] def process_notes(): url_prefix = trace(get_url_prefix) for n in notes: result = { 'guid': n.guid, 'title': n.title, 'thumbnail': trace(get_thumbnail, url_prefix, n.guid) } results.append(result) trace(process_notes) cache.set(key, results, timeout=vmenu.app.config['CACHE_TIMEOUT']) return results
def quadraticNumSolutions(a, b, c, base): if b == 0: return 1 print(f"Finding Tr(ac / b^2)") poly = baseToPoly(base) ac = polyMult(a, c, poly) print(f"ac = {ac}") #bSqr = polyMult(b,2,poly) bInv = computeFieldInverse(base, b) print(f"bInv = {bInv}") bInvSq = polyPowmod(bInv, 2, 1, poly) print(f"bInvSq = {bInvSq}") tr = trace(polyMult(ac, bInvSq, poly), base) print(f"Tr = {tr}") if (tr == 0): return 2 return 0
def get_traces(root): """ Extract traces from a inkml file. """ trace_objs = [] for trac in root.findall('{http://www.w3.org/2003/InkML}trace'): this_trace = trace() this_trace.id = trac.get('id') data = trac.text.rstrip().lstrip() xy = data.split(',') for one in xy: one_xy = one.rstrip().lstrip().split(' ') this_trace.x.append(float(one_xy[0])) this_trace.y.append(float(one_xy[1])) this_trace.calculate_centroids() trace_objs.append(this_trace) return trace_objs
def spline3(x, y, new_x, boundary, boundary_type='second_derivative', sort=True): if boundary_type not in ('derivative', 'second_derivative'): print('boundary_type can noly be "derivative" or "second_derivative!"') return if len(boundary) != 2: print('The length of boundary can only be 2!') return if not (isinstance(new_x,list) or isinstance(new_x,tuple)): try: new_x = [new_x] except: print('The type of new_x is illegal! new_x should be a list or tuple!') return if sort: my_dict = dict(zip(x,y)) x = sorted(x) y = [my_dict[i] for i in x] x = np.array(x) y = np.array(y) n = len(x) boundary = np.array(boundary) #每个区间长度 h = x[1:] - x[:-1] #miu为三对角矩阵的下次对角,lamb为上次对角, d为三对角方程右边的y向量 miu = h[:-1]/(h[:-1]+h[1:]) lamb = h[1:]/(h[1:]+h[:-1]) d = 6* ((y[2:]-y[1:-1])/(x[2:]-x[1:-1]) - (y[1:-1]-y[:-2])/(x[1:-1]-x[:-2])) / (h[:-1]+h[1:]) #根据边界条件的不同调整miu, lamb, d的两侧 if boundary_type == 'derivative': lamb = np.insert(lamb, 0, 1) miu = np.append(miu, 1) d = np.insert(d,[0,len(d)],[6*((y[1]-y[0])/(x[1]-x[0])-boundary[0])/h[0], 6*(boundary[1]-(y[-1]-y[-2])/(x[-1]-x[-2]))/h[-1]]) else: lamb = np.insert(lamb, 0, 0) miu = np.append(miu, 0) d = np.insert(d, [0,len(d)], [2*boundary[0], 2*boundary[1]]) #求解三对角方程得到中间量M M = trace(np.array([2]*n), lamb, miu, d) #预测 new_y = [predict(x,y,h,M,e) for e in new_x] return new_y
def push(self, evt): trace("[input] pushed {!r}", evt.data) key = evt.data d = self.k.get(key) if isinstance(d, dict): trace("[input] transition") self.stack.append(key) self.k = d else: if d is None: trace("[input] invalid") if self.stack or len(key) > 1 or unicodedata.category( key) == 'C': self.results.append((self.invalid_cls, self.stack + [key])) else: # small optimization: self.k[key] = self.character_cls self.results.append((self.character_cls, [key])) else: trace("[input] matched {}", d) self.results.append((d, self.stack + [key])) self.stack = [] self.k = self.ck
def distortion_single(lens, type_='f_tan_theta', wave=0, **options): if lens.t[0] < 1e10: raise ValueError('Distortion plot requires lens having infinite object.') num_pts = 25 Hys = np.linspace(0,1,num_pts) yf = np.array(lens.y_field_list()) max_f = max(yf) if type_ == 'f_tan_theta': yp = lens.f2()*np.tan(Hys*np.deg2rad(max_f)) elif type_ == 'f_theta': yp = lens.f2()*Hys*np.deg2rad(max_f) else: raise ValueError('Invalid distortion type selected.') yr = [] for Hy in Hys: raytrace = trace(lens,Hx=0,Hy=Hy,Px=0,Py=0,wave=wave).run() yr.append(raytrace.y[-1]) dist = [100*(x-y)/y for x,y in zip(yr,yp)] return dist, Hys
def dft_attack(seq_s, fun_f, fun_g): n = fun_f.degree() field = GF(2 ** n, name = 'gamma', modulus = fun_f) gamma = field.gen() seq_b_iv = [] for i in range(n): seq_b_iv.append(trace(gamma ** i)) seq_b_generator = lfsr(seq_b_iv, fun_f) seq_b = [] for i in range(2 ** n - 1): seq_b.append(seq_b_generator.next()) # print 'seq_b', seq_b seq_a = [] seq_b_doubled = seq_b * 2 # for ease of programming for i in range(2 ** n - 1): seq_a.append(GF(2)(fun_g(seq_b_doubled[i : (i + n)]))) fun_p = bma(seq_a) if len(seq_s) < fun_p.degree(): os.stderr.write("algorithm failed\n") os.exit(-1) # 2 coset_leaders = coset(2 ** n - 1) for k in coset_leaders: # coset() is changed? if 1 == gcd(k, 2 ** n - 1) and k is not 1: break # k_inverse = field(k).pth_power(-1) # not right? for i in range(2 ** n - 1): if (i * k) % (2 ** n - 1) == 1: k_inverse = i break #print 'k_inverse', k_inverse # 3 # print 'seq_a', seq_a # print type(seq_a[0]) (A_k, S_k) = dft(seq_s, seq_a) # print 'A_k', A_k # online phase # 1 # print 'seq_s', seq_s # two dft computations are combined now # print 'S_k', S_k # 2 # print 'k', k # print 'k_inverse', k_inverse # k_inverse = 13 gamma_tau = (S_k[k] * (A_k[k] ** (-1))) ** (k_inverse) # print gamma_tau # 3 result_u = [] for i in range(n): result_u.append(trace(gamma_tau * (gamma_tau.parent().gen() ** i))) return result_u
def log(*args): trace.trace('cppblocks.compiler', *args)
# set I/O ptext_path = sys.argv[1] etext_path = os.path.join("%s.encripted.txt" % ptext_path) f_ptext = file(ptext_path) ptext = f_ptext.read() f_etext = file(etext_path, 'w') enigma_1 = core.enigma() enigma_1.configure() # AUR: Unless this is somehow overridden later, it wouldn't work, as # argv[2] is a string and those are immutable, and you mutate the # shift state all the time. # Aren't there errors when doing shift[i] += 1? enigma_1.shift = shift_user = sys.argv[2] # protector if ptext[-1] == '\n': ptext = ptext[:-1] # calling the enigma function from the core, using the parameters from the conf, passing the result to the output file. for char in ptext: assert(char != '\n') # for some reason, the last char in the file is <CR>, but it doen't appear in a text editor assert(int(char) in enigma_1.alphabet) p_num = int(char) trace(p_num, '>>>>>>>>>>>') e_num = enigma_1.click(p_num) trace(e_num, '>>>>>>>>>>>') # e_char = chr(e_num) e_char = str(e_num) f_etext.write(e_char)
import draw import trace ##points = int(raw_input('Points? ')) ##outer = int(raw_input('Outer Radius? ')) ##inner = int(raw_input('Inner Radius? ')) ##x = int(raw_input('Origin (x)? ')) ##y = int(raw_input('Origin (y)? ')) ##output = str(raw_input('Output? ')) #draw.drawstar(points, outer, inner, x, y, output) #draw.drawfunction('x^2', -2, 2) trace.trace()
def log(*args): trace.trace('cppblocks.expr.scanner', *args)
isa = sys.argv[2] approx_dir = os.environ.get('APPROXGEM5') apps_dir = approx_dir + '/workloads/' + isa + '/apps/' + app_name app_prefix = apps_dir + '/' + app_name raw_outcomes_path = approx_dir + '/gem5/outputs/x86/' raw_trace_file = app_prefix + '_clean_dump_parsed_merged.txt' pruning_db_file = app_prefix + '_pruning_database.txt' raw_outcomes_file = raw_outcomes_path + app_name + '.outcomes_raw' mem_bounds_file = app_prefix + '_mem_bounds.txt' dependent_stores_file = app_prefix + '_dependent_stores.txt' app_trace = trace(raw_trace_file) mem_bounds = [ int(i) for i in open(mem_bounds_file).read().splitlines()[1].split() ] mem_bit_start = max(mem_bounds) raw_outcomes_list = open(raw_outcomes_file).read().splitlines() pruning_db = [ pc_info(None, None, None, in_string=i) for i in open(pruning_db_file).read().splitlines()[1:] ] pilot_db_map = {i.pilot: i for i in pruning_db}
def decorated_function(*args, **kwargs): logging.info(request.path) return trace(f, *args, **kwargs)
shapes = open('./maps/' + map + '/shapes', 'r') lights = open('./maps/' + map + '/lights', 'r') shapedat = "" for id, shape in enumerate(shapes.read()[:-1].split('\n')): line = shape.split(' ') base = './textures/' + line[0] + '/' path = base + 'texture.png' x = [] if path in lookup: x = lookup[path] else: x = trace(path) x = [[point[0] + int(line[1]), point[1] + int(line[2])] for point in x] x = flatten(x) lookup[path] = x if len(x) == 0: continue data = struct.pack('B', 0) # pack data += struct.pack('i', id) # pack data += struct.pack('h', len(x)) ## offset x and y data += struct.pack('i', int(line[1])) data += struct.pack('i', int(line[2]))
def _ray_OPL(self, Px, Py, C, R): '''OPL from object to reference sphere''' raytrace = trace(self.lens, self.Hx, self.Hy, Px, Py, self.wave).run() return sum(raytrace.OPL) - self._OPL_XPtoImg(raytrace.ray_list[-1], C, R)
import random from trace import trace char_nam = int(argv[2]) trace(char_num) path = argv[1] trace(path) file_1 = file(path, 'w') for i in xrange(char_num): file_1.write(random.randint(0,3)
def process(): url_prefix = trace(get_url_prefix) if full.resources is not None and vmenu.app.config['RECIPE_IMAGES']: for resource in full.resources: content = trace(update_resource, url_prefix, content, resource)
f.write(str(n)+"\n") f.close() for im_slice in image_slices: im_slice = str(im_slice) #lo,up,bk = define_aperture.define_aperture("t"+im_slice+"_"+file_name,coo,i) sigma,bk = define_aperture.define_aperture("t"+im_slice+"_"+file_name,coo,i) #print sigma,bk # if len(coo) > 1: # sigma = sigma /2 ### Trace along the brigthest star (coo[0]) signal_trace = trace.trace("t"+im_slice+"_"+file_name,coo[0][0],bk) dist = [] for k in range(len(coo)): dist.append(abs(median(signal_trace)-coo[k][0])) for k in range(len(dist)): if dist[k] == min(dist): signal_trace = signal_trace + (coo[0][0]-coo[k][0]) break print "t"+im_slice+"_"+file_name ### Make trace plot #plt.clf() plt.figure(figsize=(17.25,6)) image = pyfits.getdata("t"+im_slice+"_"+file_name)
def simulate(tb, max_pi_events=-1, trace_list=[], trace_mode="none"): ''' Breadth first simulation ''' if trace_mode == "event": traceevent = True traceon = True elif trace_mode == "end" or trace_mode == "none": traceevent = False traceon = False else: # trace_mode == "tick" traceevent = False traceon = True verbose = goptions['verbose'] statson = goptions['stats'] osclimit = goptions['osclimit'] nostrobe = goptions['nostrobe'] # ensure that all gates in the top level netlist have their verbose # attribute set, if it exists if verbose: for g in tb.gatelist: if hasattr(g, "verbose"): g.verbose = True sticky_result = True netlist = tb.netlist if not len(tb.events): print "Error - no events to simulate" return (None, 0, None, None, 0) elif max_pi_events < 0: max_pi_events = len(tb.events) + 1 tr = trace.trace(trace_list, tb) if verbose: print tr.log_header() # supply nets start simulation with their correct values, but need to # add their fanout to the eval list for the first pass through the # simulation. Also resolve all nets based on 'X' starting values in # drivers eval_list = [] for n in [n for n in tb.get_nets(regexp='', hier=True)]: n.resolve() # # add all (simulatable) gates to the evaluation list for the first pass through - this seems to work better # # for gate level netlists though not for predominantly transistor level ones! eval_list = [[ g.simulate for g in tb.get_gates(regexp='', hier=True) if hasattr(g, 'simulate') ]] total_passes = 0 total_fails = 0 stats = { "Rotations": [], "Wheel lengths": [], "Net Evals": [], "Gate Evals": [], } pi_count = -1 s = time.time() for (events, po_events) in tb.events[:max_pi_events]: pi_count += 1 loop_counter = 0 if statson: stats["Wheel lengths"] = [] stats["Gate Evals"] = [] stats["Net Evals"] = [] else: stats = None event_wheel = [events] while event_wheel: loop_counter += 1 net_evals = 0 # and add fanout of nets to the evaluation list if traceevent: result = tr.log_changes(pi_count)[0] if verbose and result: print result # first update all nets drivers based on the event_wheel contents, resolve the net # and add the fanout events to the evaluation list. while event_wheel: for (n, state, driverpin) in event_wheel.pop(): # some nets may enter the event_wheel more than once so only resolve those # where a change could take place if driverpin.state != state: driverpin.state = state net_evals += 1 eval_list.append(n.resolve()) if statson: stats["Wheel lengths"].append(len(event_wheel)) stats["Gate Evals"].append(len(eval_list)) stats["Net Evals"].append(net_evals) stats["Rotations"] = [loop_counter + 1] event_wheel = [e() for ee in eval_list for e in ee] eval_list = [] if loop_counter > osclimit: print "* Oscillations detected, bailing out of simulation tick", pi_count break if not nostrobe or traceon: (result, passes, fails) = tr.log_changes(pi_count, po_events, nostrobe, \ stats=stats, traceon=traceon) total_passes += passes total_fails += fails if result and verbose: print result if goptions['stoponfail'] and fails > 0: break e = time.time() if trace_mode == "end": result = tr.log_changes(pi_count, None, nostrobe, stats=None, traceon=True, force=True)[0] if verbose: print result if verbose: print tr.log_footer() return (tr, pi_count + 1, total_passes, total_fails, (e - s))
<anItem hi="there" now="again">2</anItem> </root>""" doc2 = """<?xml version="1.0"?><one><two>Three</two><two/></one>""" if __name__ == "__main__" : #from xml.dom.ext.reader import Sax2 from xml.dom.minidom import parseString from trace import trace #reader = Sax2.Reader() #doc1 = reader.fromString(doc) doc2 = parseString(doc) #doc = reader.fromSt("DnD.xml") #expr = Compile("/d_n_d_players/player/../../d_n_d_players/player/character") expr = Compile("/root/*") #expr = Compile(" 2 + 5 * 3") #for n in range(1) : # if n % 100 == 0 : # print ".", # for i in expr(doc, Environment()) : # Print (i) # print # #pass result = expr(trace(doc2), Environment()) print repr(result) for r in result: print repr(r) #expr(test_doc, Environment())
def log(*args): trace.trace('cppblocks.expr.eval', *args)
def dft(sequence, reference=None): if None == reference: N = len(sequence) seq_a = list(sequence) else: N = len(reference) seq_a = list(reference) seq_a_target = list(sequence) fun_p = bma(seq_a * 2) # turn sequence as periodic L = fun_p.degree() # assert 2 * L <= len(seq_a) # selection of parameters # fine smallest n, s.t. N | (2^n - 1) n = 1 while 0 != (2 ** n - 1) % N: # this means N cannot be even number n += 1 # print n # define the extension field TheExtensionField = GF(2 ** n, "beta") beta = TheExtensionField.gen() fun_f = TheExtensionField.polynomial() TheExtensionPolynomialRing = TheExtensionField["Y"] # print fun_f # construct a new m-seq {b_t} seq_b_iv = [] for i in range(n): seq_b_iv.append((beta ** i).trace()) seq_b_generator = lfsr(seq_b_iv, fun_f) seq_b = [] for i in range(2 ** len(seq_b_iv) - 1): seq_b.append(seq_b_generator.next()) # print seq_b_iv # print seq_b # let alpha be an element in GF(2^n) with order N alpha = beta ** ((2 ** n - 1) / N) # print alpha, alpha ** N # procedure # step 1. compute coset I = coset(N) # print I # step 2. fun_p_extended = TheExtensionPolynomialRing(fun_p) # print fun_p_extended spectra_A = [None] * N spectra_A_target = [None] * N for k in I: if fun_p_extended(alpha ** k) != 0: spectra_A[k] = 0 if reference: spectra_A_target[k] = 0 continue # print 'k', k, fun_p_extended(alpha ** k) # sub-routine for computing A_k # 1. get coset size m = I[k] # print k, m, n # 2. k-decimation sequence seq_c = [] if m == n: for t in range(2 * m): seq_c.append(seq_b[(t * k) % (2 ** n - 1)]) elif m < n: for t in range(2 * m): seq_c.append(trace(alpha ** (k * t), m)) else: import sys sys.stderr.write("should never happen?\n") sys.exit(-1) # print seq_b # print seq_c fun_p_k = bma(seq_c) # print fun_p # print fun_p_k # print fun_p / fun_p_k matrix_M_ele = [] for i in range(m): for ele in range(i, m + i): matrix_M_ele.append(seq_c[ele]) matrix_M = matrix(GF(2), m, m, matrix_M_ele) # print 'matrix_M' # print matrix_M # 3. contruct a filter fun_q = fun_p.parent()(fun_p / fun_p_k) # print fun_q # print type(fun_q) # 4. compute the time convolution seq_v_generator = convolution(seq_a, fun_q) seq_v = [] for i in range(m): seq_v.append(seq_v_generator.next()) if reference: seq_v_target_generator = convolution(seq_a_target, fun_q) seq_v_target = [] for i in range(m): seq_v_target.append(seq_v_target_generator.next()) # 4.5 solve linear equations to get x_i matrix_x = matrix_M.inverse() * matrix(GF(2), m, 1, seq_v) # print 'matrix_x' # print matrix_x if reference: matrix_x_target = matrix_M.inverse() * matrix(GF(2), m, 1, seq_v_target) # print 'matrix_x_target' # print matrix_x_target # 5. compute A_k = V * T V = 0 for i in range(m): if 1 == matrix_x[i][0]: V += alpha ** (i * k) if reference: V_target = 0 for i in range(m): if 1 == matrix_x_target[i][0]: V_target += alpha ** (i * k) fun_q_extended = TheExtensionPolynomialRing(fun_q) # print fun_q_extended T = fun_q_extended(alpha ** k) ** (-1) # print T # print type(T) A_k = V * T # print A_k spectra_A[k] = A_k if reference: A_k_target = V_target * T spectra_A_target[k] = A_k_target # print spectra_A # print spectra_A_target # to compute the A_k where k is not coset leader for i in I: for j in range(1, I[i]): spectra_A[(i * (2 ** j)) % N] = spectra_A[i] ** (2 ** j) if reference: spectra_A_target[(i * (2 ** j)) % N] = spectra_A_target[i] ** (2 ** j) # print alpha ** 6 if None == reference: return spectra_A else: return spectra_A, spectra_A_target
def log(*args): trace.trace('cppblocks.filefinder', *args)