def password_generator(choice: int, size=10) -> str: """function generates passwords. It can generate password from three lists and every list is being used for one of the options. It uses SystemRandom beacuse it is safer method.""" osrand = SystemRandom() password = '' if choice == 1: print( "Option one: weak password. Two words randomly chosen from the list." ) password = ''.join([ word_list[osrand.randint(1, len(word_list))], word_list[osrand.randint(1, len(word_list))] ]) elif choice == 2: print( "Option two: randomly chosen numbers and lowercase letters.\n" "Password will have ", size, " caracters. (default is 10)") password = ''.join([ char_lowercase_digits[int(osrand.random() * len(char_lowercase_digits))] for elem in range(0, size) ]) elif choice == 3: print( "Option three: randomly chosen from all printable caracters.\n" "Password will have ", size, " caracters. (default is 10)") password = ''.join([ char_printable[int(osrand.random() * len(char_printable))] for elem in range(0, size) ]) return password
def generate_random(len): try: random = SystemRandom() random.random() except NotImplementedError: # pragma: no cover random = Random() return md5(str(random.random()))[0:len]
def randomer(self): for i in range(128): rand = SystemRandom() probability = rand.random() if self.bloombits[i] == 1: bit = (probability <= (1 - 0.5 * self.f)) if bit == 1: self.b1[i] = 1 else: self.b1[i] = 0 else: bit = (probability <= 0.5 * self.f) if bit == 1: self.b1[i] = 1 else: self.b1[i] = 0 for i in range(128): rand = SystemRandom() probability = rand.random() if self.b1[i] == 1: bit = (probability <= self.q) if bit == 1: self.result[i] = 1 else: self.result[i] = 0 else: bit = (probability <= self.p) if bit == 1: self.result[i] = 1 else: self.result[i] = 0 return self.result
def randomer(self): for i in range(128): if i >= self.s and i <= self.e: rand = SystemRandom() probability = rand.random() if self.bloombits[i] == 1: bit = probability < 1 - 0.5 * self.p if bit == 1: self.b1[i] = 1 else: self.b1[i] = 0 else: bit = probability < 0.5 * self.p if bit == 1: self.b1[i] = 1 else: self.b1[i] = 0 for i in range(128): if i >= self.s and i <= self.e: rand = SystemRandom() probability = rand.random() if self.bloombits[i] == 1: bit = probability < 1 - 0.5 * self.p if bit == 1: self.b2[i] = 1 else: self.b2[i] = 0 else: bit = probability < 0.5 * self.p if bit == 1: self.b2[i] = 1 else: self.b2[i] = 0 for i in range(128): rand = SystemRandom() probability = rand.random() if self.b1[i] == 1 and self.b2[i] == 1: self.result[i] = 1 if self.b1[i] == 0 and self.b2[i] == 0: self.result[i] = 0 if self.b1[i] == 1 and self.b2[i] == 0: bit = probability < self.q if bit == 1: self.result[i] = 1 else: self.result[i] = 0 if self.b1[i] == 0 and self.b2[i] == 1: bit = probability < self.q if bit == 1: self.result[i] = 1 else: self.result[i] = 0 return self.result
def main(args): r = SystemRandom() try: try: _min = int(args[1]) _max = int(args[2]) except: _min = 0 _max = int(args[1]) except: _min = 0 _max = 10 try: if args[0] == 'simple': l = list(string.letters + string.digits) r.shuffle(l) return ''.join(l[0:_max]) if args[0] == 'strong': l = list(string.letters + string.digits + string.punctuation) r.shuffle(l) return ''.join(l[0:_max]) if args[0] == 'integer': return r.randint(_min, _max) return r.uniform(_min, _max) except: return r.random()
def directionsGenerator(steps): ''' generate unity steps in random directions ''' from random import SystemRandom from numpy import exp, pi s = SystemRandom() for i in xrange(steps): yield exp(s.random()*pi*2j)
def rand_ortho1(n): r = SystemRandom() pos = [r.random() for x in range(n)] s = sum(pos) v = array(pos,dtype=float)-(s/float(n)) norm = sqrt(sum(v*v)) return v/norm
def rand_ortho1(n): r = SystemRandom() pos = [r.random() for x in range(n)] s = sum(pos) v = array(pos, dtype=float) - (s / float(n)) norm = sqrt(sum(v * v)) return v / norm
def get_session(self): """ get current session associated with this request. if no current session, create a new session """ if self.__session: return self.__session if "SESSIONID" in self.cookie: self.__sid = self.cookie["SESSIONID"].value else: rand = SystemRandom() rand_num = rand.random() self.__sid = md5.new(repr(rand_num)).hexdigest() self.__new_session_hook() if not os.path.exists("/tmp/.session"): os.mkdir("/tmp/.session") self.__session_file = shelve.open( "/tmp/.session/yagra_session_db", writeback=True) if self.__sid not in self.__session_file: self.__session_file[self.__sid] = {} self.__session = self.__session_file[self.__sid] return self.__session
def rand_ortho1(n): from random import SystemRandom r = SystemRandom() pos = [r.random() for x in xrange(n)] s = sum(pos) v = array(pos,dtype=float)-(s/len(pos)) norm = sqrt(sum(v*v)) return v/norm
def rand_ortho1(n): from random import SystemRandom r = SystemRandom() pos = [r.random() for x in xrange(n)] s = sum(pos) v = array(pos, dtype=float) - (s / len(pos)) norm = sqrt(sum(v * v)) return v / norm
def __call__(self): p = self.prob_one rand = SystemRandom() r = 0 for i in range(self.num_bits): bit = rand.random() < p r |= (bit << i) # using bool as int return r
def __call__(self): p = self.prob_one rand = SystemRandom() r = 0 for i in xrange(self.num_bits): bit = rand.random() < p r |= (bit << i) # using bool as int return r
def sys_random_test(): print("sys random:") no_of_digits = 3 for i in range(0, 10): sys_random = SystemRandom() num = sys_random.random() multiplicant = 10**no_of_digits num = int(num * multiplicant) print(_digit_average(num, no_of_digits))
class MainPage(Page): def __init__(self, a, b): super(MainPage, self).__init__(a, b); self.random = SystemRandom(); def get(self): id = str(self.random.random())[2:] self.nocache() self.redirect("/me?browser=" + id)
def randomer(self): for i in range(self.len_data): rand = SystemRandom() probability = rand.random() bit = probability < math.exp(self.eplison1 / 2) / (1 + math.exp(self.eplison1 / 2)) if bit == 1: self.result[i] = self.data[i] else: self.result[i] = 1 - self.data[i] return self.result
def binarioSeguidoDeReal(string): if (len(string) == 8): secure_random = SystemRandom() randomfloat = secure_random.random() return [string, float(f'{randint(0,99) + round(randomfloat, 2)}')] else: raise Exception('Número menor ou maior que o permitido') #print(binarioSeguidoDeReal('11001100'))
def randomize(graph, nodeProbability, edgeProbability): rng = SystemRandom() nodes, edges = graph goalNodes = len(nodes) + rng.randint( 0, int(len(nodes) * (1 - nodeProbability))) goalEdges = len(edges) + rng.randint( 0, int(len(edges) * (1 - edgeProbability))) resultNodes = [ node for node in nodes if rng.random() <= nodeProbability + nodeDegreeWeight(node, nodes, edges) ] validOriginalEdges = [edge for edge in edges if any((node for node in resultNodes if edge.nodeA == node.name)) \ and any((node for node in resultNodes if edge.nodeB == node.name))] edgeProbability = edgeProbability * len(edges) / len(validOriginalEdges) resultEdges = [ edge for edge in validOriginalEdges if rng.random() <= edgeProbability ] latitudeDist = getDistribution([node.latitude for node in nodes]) longitudeDist = getDistribution([node.longitude for node in nodes]) numOutEdgesDist = getDistribution([ len([edge for edge in edges if edge.nodeA == node.name]) for node in nodes ]) pathLengthDist = getDistribution(list( map(lambda edge: haversine(edge[0].longitude, edge[0].latitude, edge[1].longitude, edge[1].latitude), \ map(lambda edge: getNodeObjectsForEdge(edge, nodes), edges)))) anyFakes, resultNodes, resultEdges = createFakeNodes( goalNodes, resultNodes, resultEdges, latitudeDist, longitudeDist, numOutEdgesDist, pathLengthDist) resultEdges = ensureGoalEdgesNoSingletons(goalEdges, resultNodes, resultEdges, pathLengthDist) if anyFakes: resultNodes, resultEdges = renameGraph(resultNodes, resultEdges) return (resultNodes, resultEdges)
def randomer(self): i = 0 t = 0 for k in self.item_k: if self.pb_vector[i] == 0: for j in range(0, k): self.result[t] = self.data[t] t = t + 1 elif self.pb_vector[i] == 1: for j in range(0, k): rand = SystemRandom() probability = rand.random() bit = probability < math.exp( self.eplison1 / 2) / (1 + math.exp(self.eplison1 / 2)) if bit == 1: self.result[t] = self.data[t] else: self.result[t] = 1 - self.data[t] t = t + 1 elif self.pb_vector[i] == 2: vector_t = [] for tmp in range(t, t + k): if self.data[tmp] == 1: j = tmp else: vector_t.append(tmp) rand = SystemRandom() probability = rand.random() bit = probability < math.exp( self.eplison2) / (k - 1 + math.exp(self.eplison2)) if bit == 1: j = j else: tmp1 = random.randint(0, k - 2) j = vector_t[tmp1] self.result[j] = 1 t = t + k i = i + 1 return self.result
def rand_ortho1(n): from random import SystemRandom r = SystemRandom() pos = [r.random() for x in xrange(n)] s = sum(pos) # Note: returning only positive values (if we had only negative values # an exception such as: # inf X:\grandalf\grandalf\layouts.py:784: RuntimeWarning: divide by zero encountered in double_scalars # sfactor = 1.0/max(y.max(),x.max()) # Could be found (randomly happening in test-layouts:test_splines). v = abs(array(pos,dtype=float)-(s/len(pos))) norm = sqrt(sum(v*v)) return v/norm
def rand_ortho1(n): from random import SystemRandom r = SystemRandom() pos = [r.random() for x in xrange(n)] s = sum(pos) # Note: returning only positive values (if we had only negative values # an exception such as: # inf X:\grandalf\grandalf\layouts.py:784: RuntimeWarning: divide by zero encountered in double_scalars # sfactor = 1.0/max(y.max(),x.max()) # Could be found (randomly happening in test-layouts:test_splines). v = abs(array(pos, dtype=float) - (s / len(pos))) norm = sqrt(sum(v * v)) return v / norm
def secureRandom(prob, num): if not isinstance(num, list): return None rand = SystemRandom() randValue = rand.random() if randValue < (prob * p): #print 'set 1', randValue num[2] = '1\n' elif (randValue > (prob * p)) and (randValue < (1 - prob)): #print 'set 0', randValue num[2] = '0\n' elif randValue > (1 - prob): #print 'stay unchange', randValue pass else: print 'It can not happen!' return randValue
def make_randomized_subset(opt): """Make a subset dataset for fraction of the bib-ids""" bib_ids = {} fraction = opt.subset_fraction r = SystemRandom() # a non-reporoducible random generator logging.warning("Writing subset charge and browse to %s..." % opt.subset_charge_and_browse ) cab_fh = gzip.open( opt.subset_charge_and_browse, 'w') cab_fh.write("# CHARGE AND BROWSE COUNTS\n") cab_fh.write("# (randomized subset data, item_id=0)\n") fake_bib_ids = set() for (bib_id,charges,browses) in CULChargeAndBrowse(opt.charge_and_browse): if (r.random()<=fraction): # generate fake bib_id that we haven't used before, record and dump data fake_bib_id = 1234567 while (fake_bib_id in fake_bib_ids): fake_bib_id = r.randint(1,10000000) bib_ids[bib_id] = fake_bib_id fake_bib_ids.add(fake_bib_id) # write, just use 0 for item_id as we don't use that at all cab_fh.write("%d\t%d\t%d\t%d\n" % (0,fake_bib_id,charges,browses) ) cab_fh.close() logging.warning("Writing subset circ trans to %s..." % opt.subset_circ_trans ) ct_fh = gzip.open( opt.subset_circ_trans, 'w') ct_fh.write("# CIRCULATION TRANSACTIONS\n") ct_fh.write("# (randomized subset data, trans_id=0, item_id=0)\n") for (bib_id,date) in CULCircTrans(opt.circ_trans): # select subset based on whether the bib_id was picked before if (bib_id in bib_ids): fake_bib_id = bib_ids[bib_id] # an just for belt-and-brances, randomise the date by a year or so fake_dt = datetime.datetime.combine(date,datetime.time.min) + datetime.timedelta(days=r.randint(-400,400)) fake_date = fake_dt.date().strftime('%d-%b-%y').upper() # write, use 0 for trans_id and item_id as we don't use these at all ct_fh.write(" %d\t%d\t%d\t%s\n" % (0,0,fake_bib_id,fake_date) ) ct_fh.close() logging.info("Done subset")
def randomWalk(N1, N2): from random import SystemRandom s = SystemRandom() positions = [0] n1 = 0 n2 = 0 # the steps are in units of 1/N1 * N1*N2, resp. 1/N2 * N1*N2 to make sure # we don't accumulate round-off errors in the summation while (n1 < N1 or n2 < N2): if s.random() >= 0.5: if n1 < N1: n1 += 1 positions.append(positions[-1]+N2) # else: # does not really change the statistics # positions.append(positions[-1]) else: if n2 < N2: n2 += 1 positions.append(positions[-1]-N1) # else: # does not really change the statistics # positions.append(positions[-1]) # returning to stepsize 1/N1, resp. 1/N2 return [float(p)/(N1*N2) for p in positions]
class RNG(object): """Provide a random number generator which can constantly generate random numbers as required by various gaming jurisdictions. """ def __init__(self, hz=100): self._rng = SystemRandom() self._cur = self._rng.random() self.is_cycling = False self.hz = hz def cycle(self): self.rng_thread = threading.Thread(target=rng_cycle, args=(self,)) self.is_cycling = True self.rng_thread.start() def stop_cycle(self): self.is_cycling = False self.rng_thread.join() def choice(self, seq): """Return a random item from a given sequence""" r = math.floor(self._rng.random() * len(seq)) return seq[r] def randint(self, a, b): """Return a random integer between a and b""" return math.floor((self._rng.random() * (b-a)) + a) def chi_square(self, n=1000000, k=1000): """Perform a chi-square goodness of fit test on the RNG. Args: k: Number of evenly-spaced ranges to categorize samples into. n: Number of samples. Returns: Pearson's cumulative test statistic, X^2, calculated as the sum of: observations in a category minus expected observations in that category, squared, divided by the expected observations in that category, for every category. You'll want to compare the resulting number against a chi-squared distribution table for the required p-value and k-1 degrees of freedom. The critical value for 95% confidence (p=0.05) at the default k=1000 is approximately 1074. """ if self.is_cycling: self.stop_cycle() self.is_cycling = True U = [(i/k, (i+1)/k) for i in range(k)] N = [self._rng.random() for i in range(n)] x = 0 for i in U: u = 0 for j in N: if i[0] < j <=i[1]: u += 1 x += (u - (n/k))**2 / (n/k) if self.is_cycling: self.cycle() return x
def decorator(cb, metrics, now=None): next_run = func(cb, metrics, now=now) how_often = cb._periodic_spacing jitter = how_often * (random.random() * max_percent_jitter) return next_run + jitter
def __init__(self): from random import random, Random, SystemRandom init = SystemRandom() self.rng = Random(init.random())
def _rnd_passwd(): r = SystemRandom() m = md5() m.update(str(r.random())) return m.hexdigest()
import datetime import dateutil.parser import errno import json import os import pytz import re import string import girder import girder.events try: from random import SystemRandom random = SystemRandom() random.random() # potentially raises NotImplementedError except NotImplementedError: # pragma: no cover girder.logprint.warning( 'WARNING: using non-cryptographically secure PRNG.') import random def parseTimestamp(x, naive=True): """ Parse a datetime string using the python-dateutil package. If no timezone information is included, assume UTC. If timezone information is included, convert to UTC. If naive is True (the default), drop the timezone information such that a naive datetime is returned.
hittables: List[Hittable] = [ Sphere(Vec3(0, 0, -1), 0.5), Sphere(Vec3(0, -100.5, -1), 100) ] world: HittableList = HittableList(hittables) for j in range(height - 1, -1, -1): for i in range(width): print("Tracing on row %s, col %s" % (j, i)) print("antialiasing...", end="") accumulator: Vec3 = Vec3(0, 0, 0) for sample in range(sampling_size): # In this instance, instead of u and v being mere ratios to # our distance from the edges, they feature a random "jitter" # which we use to sample the pixels around our current pixel. # In this sense, the current pixel is a combination of its # surroundings. u: float = float(i + random.random()) / float(width) v: float = float(j + random.random()) / float(height) r: Ray = cam.get_ray(u, v) accumulator += color(r, world) accumulator /= float(sampling_size) print("done") accumulator *= 255.9 accumulator.map(int) ppm.set_pixel((height - 1) - j, i, accumulator) ppm.write(_derive_ppm_filename())
def generateEDMRSIndex(self): currentTime = time.time() if os.path.isfile('EDMRStree.json'): self.label1.setText('已經產生過該索引') return print("Generating EDMRS index...") if not os.path.isfile('basic_secret_EDMRS.bin'): self.createBasicSecret('basic_secret_EDMRS') if not os.path.isfile('plaintree.json'): self.generateTreeIndex() f = open('basic_secret_EDMRS.bin', "rb") cipherdata = f.read() f.close() cipherdata = cipherdata.decode() cipher = cipherdata.split('\n') S = cipher[0] index1 = int(cipher[1]) index2 = int(cipher[2]) M1 = make_spd_matrix(self.m + self.m_p, random_state=index1) M2 = make_spd_matrix(self.m + self.m_p, random_state=index2) cryptogen = SystemRandom() f = open(f"plaintree.json", "r") str1 = f.read() n = self.end - self.start + 1 Nodes = [] SecureNodes = [] AllNodes = json.loads(str1) for Node in AllNodes: print(f"Processing Node {Node['ID']}") securenode = SecureTreeNode(Node['ID'], Node['FID']) securenode.PL = Node['PL'] securenode.PR = Node['PR'] Du = np.array(Node['D']) phantom = np.random.rand(self.m_p) Du = np.append(Du, phantom) Du_1 = np.zeros(self.m + self.m_p) Du_2 = np.zeros(self.m + self.m_p) for i in range(self.m + self.m_p): if S[i] == '0': Du_1[i] = Du[i] Du_2[i] = Du[i] else: Du_1[i] = cryptogen.random() Du_2[i] = Du[i] - Du_1[i] Iu_1 = M1.dot(Du_1) Iu_2 = M2.dot(Du_2) Iu = list(Iu_1) + list(Iu_2) print(Iu_1) securenode.Iu = Iu SecureNodes.append(securenode) used_time = time.time() - currentTime self.label2.setText(f'花費時間:{used_time}秒') f = open(f"EDMRStree.json", "w") f.write(json.dumps(SecureNodes, cls=TreeNodeEncoder)) f.close()
from random import SystemRandom crypto = SystemRandom() print(crypto.random())
def f(_): b = SystemRandom() x = b.random() * 2 - 1 y = b.random() * 2 - 1 return 1 if x ** 2 + y ** 2 < 1 else 0
beats = {'R': 'P', 'P': 'S', 'S': 'R'} # value beats key cedes = {'R': 'S', 'P': 'R', 'S': 'P'} # key beats value rng = SystemRandom() cracked = None elif input == "R": rockCount += 1 input_seq.append(input) elif input == "P": paperCount += 1 input_seq.append(input) elif input == "S": scissorsCount += 1 input_seq.append(input) if not cracked: if rng.random() > 0.8: cracked = beats[output_seq[-1]] # choose output if cracked: output = cracked elif rng.random() > 0.6: output = choice(actions) else: if rockCount > paperCount and rockCount > scissorsCount: output = beats['R'] elif paperCount > scissorsCount: output = beats['P'] else: output = beats['S'] output_seq.append(output)
try: opts, args = getopt.gnu_getopt(sys.argv[1:], "h", ['help', 'pass='******'-h', '--help'): usage() elif opt == '--pass': password = val if not password: d = Dialog('TurnKey Linux - First boot configuration') password = d.get_password( "Observium Password", "Enter new password for the Observium 'admin' account.") random = SystemRandom() salt = hashlib.sha1(str(random.random())).hexdigest()[:8] hash = crypt.crypt(password, "$1$" + salt + "$") m = MySQL() m.execute( 'UPDATE observium.users SET password=\"%s\" WHERE username=\"admin\";' % hash) if __name__ == "__main__": main()
# record input if input == "": # initialize rockCount = paperCount = scissorsCount = 0 input_seq, output_seq = [], [] rng = SystemRandom() actions = ('R', 'P', 'S') # dict of moves such that value beats key beats = {actions[i]: actions[(i + 1) % 3] for i in xrange(3)} model = hmm.GaussianHMM(2, 'full') elif input == 'R': rockCount += 1 input_seq.append(input) elif input == 'P': paperCount += 1 input_seq.append(input) elif input == 'S': scissorsCount += 1 input_seq.append(input) # choose output if len(input_seq) <= 10: if rng.random() >= 0.95: output = choice(actions) else: model.fit([input_seq]) z2 = model.predict(input_seq) print "z2 = %s" % (z2,) output = choice(actions) output_seq.append(output)
class PositionerSetup(Screen): @staticmethod def satposition2metric(position): if position > 1800: position = 3600 - position orientation = "west" else: orientation = "east" return position, orientation @staticmethod def orbital2metric(position, orientation): if orientation == "west": position = 360 - position if orientation == "south": position = - position return position @staticmethod def longitude2orbital(position): if position >= 180: return 360 - position, "west" else: return position, "east" @staticmethod def latitude2orbital(position): if position >= 0: return position, "north" else: return -position, "south" UPDATE_INTERVAL = 50 # milliseconds STATUS_MSG_TIMEOUT = 2 # seconds LOG_SIZE = 16 * 1024 # log buffer size def __init__(self, session, feid): self.session = session Screen.__init__(self, session) self.feid = feid self.oldref = None log.open(self.LOG_SIZE) if config.Nims[self.feid].configMode.value == 'advanced': self.advanced = True self.advancedconfig = config.Nims[self.feid].advanced self.advancedsats = self.advancedconfig.sat self.availablesats = map(lambda x: x[0], nimmanager.getRotorSatListForNim(self.feid)) else: self.advanced = False cur = { } if not self.openFrontend(): self.oldref = session.nav.getCurrentlyPlayingServiceReference() service = session.nav.getCurrentService() feInfo = service and service.frontendInfo() if feInfo: cur = feInfo.getTransponderData(True) del feInfo del service session.nav.stopService() # try to disable foreground service if not self.openFrontend(): if session.pipshown: # try to disable pip service = self.session.pip.pipservice feInfo = service and service.frontendInfo() if feInfo: cur = feInfo.getTransponderData(True) del feInfo del service from Screens.InfoBar import InfoBar InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP() if not self.openFrontend(): self.frontend = None # in normal case this should not happen if hasattr(self, 'raw_channel'): del self.raw_channel self.frontendStatus = { } self.diseqc = Diseqc(self.frontend) # True means we dont like that the normal sec stuff sends commands to the rotor! self.tuner = Tuner(self.frontend, ignore_rotor = True) tp = ( cur.get("frequency", 0) / 1000, cur.get("symbol_rate", 0) / 1000, cur.get("polarization", eDVBFrontendParametersSatellite.Polarisation_Horizontal), cur.get("fec_inner", eDVBFrontendParametersSatellite.FEC_Auto), cur.get("inversion", eDVBFrontendParametersSatellite.Inversion_Unknown), cur.get("orbital_position", 0), cur.get("system", eDVBFrontendParametersSatellite.System_DVB_S), cur.get("modulation", eDVBFrontendParametersSatellite.Modulation_QPSK), cur.get("rolloff", eDVBFrontendParametersSatellite.RollOff_alpha_0_35), cur.get("pilot", eDVBFrontendParametersSatellite.Pilot_Unknown)) self.tuner.tune(tp) self.isMoving = False self.stopOnLock = False self.red = Button("") self["key_red"] = self.red self.green = Button("") self["key_green"] = self.green self.yellow = Button("") self["key_yellow"] = self.yellow self.blue = Button("") self["key_blue"] = self.blue self.list = [] self["list"] = ConfigList(self.list) self["snr_db"] = TunerInfo(TunerInfo.SNR_DB, statusDict = self.frontendStatus) self["snr_percentage"] = TunerInfo(TunerInfo.SNR_PERCENTAGE, statusDict = self.frontendStatus) self["ber_value"] = TunerInfo(TunerInfo.BER_VALUE, statusDict = self.frontendStatus) self["snr_bar"] = TunerInfo(TunerInfo.SNR_BAR, statusDict = self.frontendStatus) self["ber_bar"] = TunerInfo(TunerInfo.BER_BAR, statusDict = self.frontendStatus) self["lock_state"] = TunerInfo(TunerInfo.LOCK_STATE, statusDict = self.frontendStatus) self["frequency_value"] = Label("") self["symbolrate_value"] = Label("") self["fec_value"] = Label("") self["polarisation"] = Label("") self["status_bar"] = Label("") self.statusMsgTimeoutTicks = 0 self.statusMsgBlinking = False self.statusMsgBlinkCount = 0 self.statusMsgBlinkRate = 500 / self.UPDATE_INTERVAL # milliseconds self.tuningChangedTo(tp) self["actions"] = NumberActionMap(["DirectionActions", "OkCancelActions", "ColorActions", "TimerEditActions", "InputActions"], { "ok": self.keyOK, "cancel": self.keyCancel, "up": self.keyUp, "down": self.keyDown, "left": self.keyLeft, "right": self.keyRight, "red": self.redKey, "green": self.greenKey, "yellow": self.yellowKey, "blue": self.blueKey, "log": self.showLog, "1": self.keyNumberGlobal, "2": self.keyNumberGlobal, "3": self.keyNumberGlobal, "4": self.keyNumberGlobal, "5": self.keyNumberGlobal, "6": self.keyNumberGlobal, "7": self.keyNumberGlobal, "8": self.keyNumberGlobal, "9": self.keyNumberGlobal, "0": self.keyNumberGlobal }, -1) self.updateColors("tune") self.statusTimer = eTimer() self.statusTimer.callback.append(self.updateStatus) self.collectingStatistics = False self.statusTimer.start(self.UPDATE_INTERVAL, True) self.dataAvailable = Event() self.onClose.append(self.__onClose) self.createConfig() self.createSetup() def __onClose(self): self.statusTimer.stop() log.close() self.session.nav.playService(self.oldref) def restartPrevService(self, yesno): if yesno: if self.frontend: self.frontend = None del self.raw_channel else: self.oldref=None self.close(None) def keyCancel(self): if self.oldref: self.session.openWithCallback(self.restartPrevService, MessageBox, _("Zap back to service before positioner setup?"), MessageBox.TYPE_YESNO) else: self.restartPrevService(False) def openFrontend(self): res_mgr = eDVBResourceManager.getInstance() if res_mgr: self.raw_channel = res_mgr.allocateRawChannel(self.feid) if self.raw_channel: self.frontend = self.raw_channel.getFrontend() if self.frontend: return True else: print "getFrontend failed" else: print "getRawChannel failed" else: print "getResourceManager instance failed" return False def setLNB(self, lnb): try: self.sitelon = lnb.longitude.float self.longitudeOrientation = lnb.longitudeOrientation.value self.sitelat = lnb.latitude.float self.latitudeOrientation = lnb.latitudeOrientation.value self.tuningstepsize = lnb.tuningstepsize.float self.rotorPositions = lnb.rotorPositions.value self.turningspeedH = lnb.turningspeedH.float self.turningspeedV = lnb.turningspeedV.float except: # some reasonable defaults from NimManager self.sitelon = 5.1 self.longitudeOrientation = 'east' self.sitelat = 50.767 self.latitudeOrientation = 'north' self.tuningstepsize = 0.36 self.rotorPositions = 99 self.turningspeedH = 2.3 self.turningspeedV = 1.7 self.sitelat = PositionerSetup.orbital2metric(self.sitelat, self.latitudeOrientation) self.sitelon = PositionerSetup.orbital2metric(self.sitelon, self.longitudeOrientation) def getLNBfromConfig(self, orb_pos): lnb = None if orb_pos in self.availablesats: lnbnum = int(self.advancedsats[orb_pos].lnb.value) if not lnbnum: for allsats in range(3601, 3607): lnbnum = int(self.advancedsats[allsats].lnb.value) if lnbnum: break if lnbnum: self.printMsg(_("Using LNB %d") % lnbnum) lnb = self.advancedconfig.lnb[lnbnum] if not lnb: self.logMsg(_("Warning: no LNB; using factory defaults."), timeout = 4) return lnb def createConfig(self): rotorposition = 1 orb_pos = 0 self.printMsg(_("Using tuner %s") % chr(0x41 + self.feid)) if not self.advanced: self.printMsg(_("Configuration mode: %s") % _("simple")) nim = config.Nims[self.feid] self.sitelon = nim.longitude.float self.longitudeOrientation = nim.longitudeOrientation.value self.sitelat = nim.latitude.float self.latitudeOrientation = nim.latitudeOrientation.value self.sitelat = PositionerSetup.orbital2metric(self.sitelat, self.latitudeOrientation) self.sitelon = PositionerSetup.orbital2metric(self.sitelon, self.longitudeOrientation) self.tuningstepsize = nim.tuningstepsize.float self.rotorPositions = nim.rotorPositions.value self.turningspeedH = nim.turningspeedH.float self.turningspeedV = nim.turningspeedV.float else: # it is advanced self.printMsg(_("Configuration mode: %s") % _("advanced")) fe_data = { } self.frontend.getFrontendData(fe_data) self.frontend.getTransponderData(fe_data, True) orb_pos = fe_data.get("orbital_position", None) if orb_pos in self.availablesats: rotorposition = int(self.advancedsats[orb_pos].rotorposition.value) self.setLNB(self.getLNBfromConfig(orb_pos)) self.positioner_tune = ConfigNothing() self.positioner_move = ConfigNothing() self.positioner_finemove = ConfigNothing() self.positioner_limits = ConfigNothing() self.positioner_storage = ConfigInteger(default = rotorposition, limits = (1, self.rotorPositions)) self.allocatedIndices = [] m = PositionerSetup.satposition2metric(orb_pos) self.orbitalposition = ConfigFloat(default = [int(m[0] / 10), m[0] % 10], limits = [(0,180),(0,9)]) self.orientation = ConfigSelection([("east", _("East")), ("west", _("West"))], m[1]) def createSetup(self): self.list.append((_("Tune and focus"), self.positioner_tune, "tune")) self.list.append((_("Movement"), self.positioner_move, "move")) self.list.append((_("Fine movement"), self.positioner_finemove, "finemove")) self.list.append((_("Set limits"), self.positioner_limits, "limits")) self.list.append((_("Memory index"), self.positioner_storage, "storage")) self.list.append((_("Goto"), self.orbitalposition, "goto")) self.list.append((" ", self.orientation, "goto")) self["list"].l.setList(self.list) def keyOK(self): pass def getCurrentConfigPath(self): return self["list"].getCurrent()[2] def keyUp(self): if not self.isMoving: self["list"].instance.moveSelection(self["list"].instance.moveUp) self.updateColors(self.getCurrentConfigPath()) def keyDown(self): if not self.isMoving: self["list"].instance.moveSelection(self["list"].instance.moveDown) self.updateColors(self.getCurrentConfigPath()) def keyNumberGlobal(self, number): self["list"].handleKey(KEY_0 + number) def keyLeft(self): self["list"].handleKey(KEY_LEFT) def keyRight(self): self["list"].handleKey(KEY_RIGHT) def updateColors(self, entry): if entry == "tune": self.red.setText(_("Tune")) self.green.setText(_("Auto focus")) self.yellow.setText(_("Calibrate")) self.blue.setText(_("Calculate")) elif entry == "move": if self.isMoving: self.red.setText(_("Stop")) self.green.setText(_("Stop")) self.yellow.setText(_("Stop")) self.blue.setText(_("Stop")) else: self.red.setText(_("Move west")) self.green.setText(_("Search west")) self.yellow.setText(_("Search east")) self.blue.setText(_("Move east")) elif entry == "finemove": self.red.setText("") self.green.setText(_("Step west")) self.yellow.setText(_("Step east")) self.blue.setText("") elif entry == "limits": self.red.setText(_("Limits off")) self.green.setText(_("Limit west")) self.yellow.setText(_("Limit east")) self.blue.setText(_("Limits on")) elif entry == "storage": self.red.setText("") self.green.setText(_("Store position")) self.yellow.setText(_("Goto position")) if self.advanced: self.blue.setText(_("Allocate")) else: self.blue.setText("") elif entry == "goto": self.red.setText("") self.green.setText(_("Goto 0")) self.yellow.setText(_("Goto X")) self.blue.setText("") else: self.red.setText("") self.green.setText("") self.yellow.setText("") self.blue.setText("") def printMsg(self, msg): print msg print>>log, msg def stopMoving(self): self.printMsg(_("Stop")) self.diseqccommand("stop") self.isMoving = False self.stopOnLock = False self.statusMsg(_("Stopped"), timeout = self.STATUS_MSG_TIMEOUT) def redKey(self): entry = self.getCurrentConfigPath() if entry == "move": if self.isMoving: self.stopMoving() else: self.printMsg(_("Move west")) self.diseqccommand("moveWest", 0) self.isMoving = True self.statusMsg(_("Moving west ..."), blinking = True) self.updateColors("move") elif entry == "limits": self.printMsg(_("Limits off")) self.diseqccommand("limitOff") self.statusMsg(_("Limits cancelled"), timeout = self.STATUS_MSG_TIMEOUT) elif entry == "tune": fe_data = { } self.frontend.getFrontendData(fe_data) self.frontend.getTransponderData(fe_data, True) feparm = self.tuner.lastparm.getDVBS() fe_data["orbital_position"] = feparm.orbital_position self.statusTimer.stop() self.session.openWithCallback(self.tune, TunerScreen, self.feid, fe_data) def greenKey(self): entry = self.getCurrentConfigPath() if entry == "tune": # Auto focus self.printMsg(_("Auto focus")) print>>log, (_("Site latitude") + " : %5.1f %s") % PositionerSetup.latitude2orbital(self.sitelat) print>>log, (_("Site longitude") + " : %5.1f %s") % PositionerSetup.longitude2orbital(self.sitelon) Thread(target = self.autofocus).start() elif entry == "move": if self.isMoving: self.stopMoving() else: self.printMsg(_("Search west")) self.isMoving = True self.stopOnLock = True self.diseqccommand("moveWest", 0) self.statusMsg(_("Searching west ..."), blinking = True) self.updateColors("move") elif entry == "finemove": self.printMsg(_("Step west")) self.diseqccommand("moveWest", 0xFF) # one step self.statusMsg(_("Stepped west"), timeout = self.STATUS_MSG_TIMEOUT) elif entry == "storage": self.printMsg(_("Store at index")) index = int(self.positioner_storage.value) self.diseqccommand("store", index) self.statusMsg((_("Position stored at index") + " %2d") % index, timeout = self.STATUS_MSG_TIMEOUT) elif entry == "limits": self.printMsg(_("Limit west")) self.diseqccommand("limitWest") self.statusMsg(_("West limit set"), timeout = self.STATUS_MSG_TIMEOUT) elif entry == "goto": self.printMsg(_("Goto 0")) self.diseqccommand("moveTo", 0) self.statusMsg(_("Moved to position 0"), timeout = self.STATUS_MSG_TIMEOUT) def yellowKey(self): entry = self.getCurrentConfigPath() if entry == "move": if self.isMoving: self.stopMoving() else: self.printMsg(_("Move east")) self.isMoving = True self.stopOnLock = True self.diseqccommand("moveEast", 0) self.statusMsg(_("Searching east ..."), blinking = True) self.updateColors("move") elif entry == "finemove": self.printMsg(_("Step east")) self.diseqccommand("moveEast", 0xFF) # one step self.statusMsg(_("Stepped east"), timeout = self.STATUS_MSG_TIMEOUT) elif entry == "storage": self.printMsg(_("Goto index position")) index = int(self.positioner_storage.value) self.diseqccommand("moveTo", index) self.statusMsg((_("Moved to position at index") + " %2d") % index, timeout = self.STATUS_MSG_TIMEOUT) elif entry == "limits": self.printMsg(_("Limit east")) self.diseqccommand("limitEast") self.statusMsg(_("East limit set"), timeout = self.STATUS_MSG_TIMEOUT) elif entry == "goto": self.printMsg(_("Move to position X")) satlon = self.orbitalposition.float position = "%5.1f %s" % (satlon, self.orientation.value) print>>log, (_("Satellite longitude:") + " %s") % position satlon = PositionerSetup.orbital2metric(satlon, self.orientation.value) self.statusMsg((_("Moving to position") + " %s") % position, timeout = self.STATUS_MSG_TIMEOUT) self.gotoX(satlon) elif entry == "tune": # Start USALS calibration self.printMsg(_("USALS calibration")) print>>log, (_("Site latitude") + " : %5.1f %s") % PositionerSetup.latitude2orbital(self.sitelat) print>>log, (_("Site longitude") + " : %5.1f %s") % PositionerSetup.longitude2orbital(self.sitelon) Thread(target = self.gotoXcalibration).start() def blueKey(self): entry = self.getCurrentConfigPath() if entry == "move": if self.isMoving: self.stopMoving() else: self.printMsg(_("Move east")) self.diseqccommand("moveEast", 0) self.isMoving = True self.statusMsg(_("Moving east ..."), blinking = True) self.updateColors("move") elif entry == "limits": self.printMsg(_("Limits on")) self.diseqccommand("limitOn") self.statusMsg(_("Limits enabled"), timeout = self.STATUS_MSG_TIMEOUT) elif entry == "tune": # Start (re-)calculate self.session.openWithCallback(self.recalcConfirmed, MessageBox, _("This will (re-)calculate all positions of your rotor and may remove previously memorised positions and fine-tuning!\nAre you sure?"), MessageBox.TYPE_YESNO, default = False, timeout = 10) elif entry == "storage": if self.advanced: self.printMsg(_("Allocate unused memory index")) while True: if not len(self.allocatedIndices): for sat in self.availablesats: current_index = int(self.advancedsats[sat].rotorposition.value) if current_index not in self.allocatedIndices: self.allocatedIndices.append(current_index) if len(self.allocatedIndices) == self.rotorPositions: self.statusMsg(_("No free index available"), timeout = self.STATUS_MSG_TIMEOUT) break index = 1 if len(self.allocatedIndices): for i in sorted(self.allocatedIndices): if i != index: break index += 1 if index <= self.rotorPositions: self.positioner_storage.value = index self["list"].invalidateCurrent() self.allocatedIndices.append(index) self.statusMsg((_("Index allocated:") + " %2d") % index, timeout = self.STATUS_MSG_TIMEOUT) break else: self.allocatedIndices = [] def recalcConfirmed(self, yesno): if yesno: self.printMsg(_("Calculate all positions")) print>>log, (_("Site latitude") + " : %5.1f %s") % PositionerSetup.latitude2orbital(self.sitelat) print>>log, (_("Site longitude") + " : %5.1f %s") % PositionerSetup.longitude2orbital(self.sitelon) lon = self.sitelon if lon >= 180: lon -= 360 if lon < -30: # americas, make unsigned binary west positive polarity lon = -lon lon = int(round(lon)) & 0xFF lat = int(round(self.sitelat)) & 0xFF index = int(self.positioner_storage.value) & 0xFF self.diseqccommand("calc", (((index << 8) | lon) << 8) | lat) self.statusMsg(_("Calculation complete"), timeout = self.STATUS_MSG_TIMEOUT) def showLog(self): self.session.open(PositionerSetupLog) def diseqccommand(self, cmd, param = 0): print>>log, "Diseqc(%s, %X)" % (cmd, param) self.diseqc.command(cmd, param) self.tuner.retune() def tune(self, transponder): # re-start the update timer self.statusTimer.start(self.UPDATE_INTERVAL, True) if transponder is not None: self.tuner.tune(transponder) self.tuningChangedTo(transponder) feparm = self.tuner.lastparm.getDVBS() orb_pos = feparm.orbital_position m = PositionerSetup.satposition2metric(orb_pos) self.orbitalposition.value = [int(m[0] / 10), m[0] % 10] self.orientation.value = m[1] if self.advanced: if orb_pos in self.availablesats: rotorposition = int(self.advancedsats[orb_pos].rotorposition.value) self.positioner_storage.value = rotorposition self.allocatedIndices = [] self.setLNB(self.getLNBfromConfig(orb_pos)) def isLocked(self): return self.frontendStatus.get("tuner_locked", 0) == 1 def statusMsg(self, msg, blinking = False, timeout = 0): # timeout in seconds self.statusMsgBlinking = blinking if not blinking: self["status_bar"].visible = True self["status_bar"].setText(msg) self.statusMsgTimeoutTicks = (timeout * 1000 + self.UPDATE_INTERVAL / 2) / self.UPDATE_INTERVAL def updateStatus(self): self.statusTimer.start(self.UPDATE_INTERVAL, True) if self.frontend: self.frontend.getFrontendStatus(self.frontendStatus) self["snr_db"].update() self["snr_percentage"].update() self["ber_value"].update() self["snr_bar"].update() self["ber_bar"].update() self["lock_state"].update() if self.statusMsgBlinking: self.statusMsgBlinkCount += 1 if self.statusMsgBlinkCount == self.statusMsgBlinkRate: self.statusMsgBlinkCount = 0 self["status_bar"].visible = not self["status_bar"].visible if self.statusMsgTimeoutTicks > 0: self.statusMsgTimeoutTicks -= 1 if self.statusMsgTimeoutTicks == 0: self["status_bar"].setText("") self.statusMsgBlinking = False self["status_bar"].visible = True if self.isLocked() and self.isMoving and self.stopOnLock: self.stopMoving() self.updateColors(self.getCurrentConfigPath()) if self.collectingStatistics: self.low_rate_adapter_count += 1 if self.low_rate_adapter_count == self.MAX_LOW_RATE_ADAPTER_COUNT: self.low_rate_adapter_count = 0 self.snr_percentage += self["snr_percentage"].getValue(TunerInfo.SNR) self.lock_count += self["lock_state"].getValue(TunerInfo.LOCK) self.stat_count += 1 if self.stat_count == self.max_count: self.collectingStatistics = False count = float(self.stat_count) self.lock_count /= count self.snr_percentage *= 100.0 / 0x10000 / count self.dataAvailable.set() def tuningChangedTo(self, tp): def setLowRateAdapterCount(symbolrate): # change the measurement time and update interval in case of low symbol rate, # since more time is needed for the front end in that case. # It is an heuristic determination without any pretence. For symbol rates # of 5000 the interval is multiplied by 3 until 15000 which is seen # as a high symbol rate. Linear interpolation elsewhere. return max(int(round((3 - 1) * (symbolrate - 15000) / (5000 - 15000) + 1)), 1) self.symbolrate = tp[1] self.polarisation = tp[2] self.MAX_LOW_RATE_ADAPTER_COUNT = setLowRateAdapterCount(self.symbolrate) transponderdata = ConvertToHumanReadable(self.tuner.getTransponderData(), "DVB-S") self["frequency_value"].setText(str(transponderdata.get("frequency"))) self["symbolrate_value"].setText(str(transponderdata.get("symbol_rate"))) self["fec_value"].setText(str(transponderdata.get("fec_inner"))) self["polarisation"].setText(str(transponderdata.get("polarization"))) @staticmethod def rotorCmd2Step(rotorCmd, stepsize): return round(float(rotorCmd & 0xFFF) / 0x10 / stepsize) * (1 - ((rotorCmd & 0x1000) >> 11)) @staticmethod def gotoXcalc(satlon, sitelat, sitelon): def azimuth2Rotorcode(angle): gotoXtable = (0x00, 0x02, 0x03, 0x05, 0x06, 0x08, 0x0A, 0x0B, 0x0D, 0x0E) a = int(round(abs(angle) * 10.0)) return ((a / 10) << 4) + gotoXtable[a % 10] satHourAngle = rotor_calc.calcSatHourangle(satlon, sitelat, sitelon) if sitelat >= 0: # Northern Hemisphere rotorCmd = azimuth2Rotorcode(180 - satHourAngle) if satHourAngle <= 180: # the east rotorCmd |= 0xE000 else: # west rotorCmd |= 0xD000 else: # Southern Hemisphere if satHourAngle <= 180: # the east rotorCmd = azimuth2Rotorcode(satHourAngle) | 0xD000 else: # west rotorCmd = azimuth2Rotorcode(360 - satHourAngle) | 0xE000 return rotorCmd def gotoX(self, satlon): rotorCmd = PositionerSetup.gotoXcalc(satlon, self.sitelat, self.sitelon) self.diseqccommand("gotoX", rotorCmd) x = PositionerSetup.rotorCmd2Step(rotorCmd, self.tuningstepsize) print>>log, (_("Rotor step position:") + " %4d") % x return x def getTurningspeed(self): if self.polarisation == eDVBFrontendParametersSatellite.Polarisation_Horizontal: turningspeed = self.turningspeedH else: turningspeed = self.turningspeedV return max(turningspeed, 0.1) TURNING_START_STOP_DELAY = 1.600 # seconds MAX_SEARCH_ANGLE = 12.0 # degrees MAX_FOCUS_ANGLE = 6.0 # degrees LOCK_LIMIT = 0.1 # ratio MEASURING_TIME = 2.500 # seconds def measure(self, time = MEASURING_TIME): # time in seconds self.snr_percentage = 0.0 self.lock_count = 0.0 self.stat_count = 0 self.low_rate_adapter_count = 0 self.max_count = max(int((time * 1000 + self.UPDATE_INTERVAL / 2)/ self.UPDATE_INTERVAL), 1) self.collectingStatistics = True self.dataAvailable.clear() self.dataAvailable.wait() def logMsg(self, msg, timeout = 0): self.statusMsg(msg, timeout = timeout) self.printMsg(msg) def sync(self): self.lock_count = 0.0 n = 0 while self.lock_count < (1 - self.LOCK_LIMIT) and n < 5: self.measure(time = 0.500) n += 1 if self.lock_count < (1 - self.LOCK_LIMIT): return False return True randomGenerator = None def randomBool(self): if self.randomGenerator is None: self.randomGenerator = SystemRandom() return self.randomGenerator.random() >= 0.5 def gotoXcalibration(self): def move(x): z = self.gotoX(x + satlon) time = int(abs(x - prev_pos) / turningspeed + 2 * self.TURNING_START_STOP_DELAY) sleep(time * self.MAX_LOW_RATE_ADAPTER_COUNT) return z def reportlevels(pos, level, lock): print>>log, (_("Signal quality") + " %5.1f" + chr(176) + " : %6.2f") % (pos, level) print>>log, (_("Lock ratio") + " %5.1f" + chr(176) + " : %6.2f") % (pos, lock) def optimise(readings): xi = readings.keys() yi = map(lambda (x, y) : x, readings.values()) x0 = sum(map(mul, xi, yi)) / sum(yi) xm = xi[yi.index(max(yi))] return x0, xm def toGeopos(x): if x < 0: return _("W") else: return _("E") def toGeoposEx(x): if x < 0: return _("west") else: return _("east") self.logMsg(_("GotoX calibration")) satlon = self.orbitalposition.float print>>log, (_("Satellite longitude:") + " %5.1f" + chr(176) + " %s") % (satlon, self.orientation.value) satlon = PositionerSetup.orbital2metric(satlon, self.orientation.value) prev_pos = 0.0 # previous relative position w.r.t. satlon turningspeed = self.getTurningspeed() x = 0.0 # relative position w.r.t. satlon dir = 1 if self.randomBool(): dir = -dir while abs(x) < self.MAX_SEARCH_ANGLE: if self.sync(): break x += (1.0 * dir) # one degree east/west self.statusMsg((_("Searching") + " " + toGeoposEx(dir) + " %2d" + chr(176)) % abs(x), blinking = True) move(x) prev_pos = x else: x = 0.0 dir = -dir while abs(x) < self.MAX_SEARCH_ANGLE: x += (1.0 * dir) # one degree east/west self.statusMsg((_("Searching") + " " + toGeoposEx(dir) + " %2d" + chr(176)) % abs(x), blinking = True) move(x) prev_pos = x if self.sync(): break else: msg = _("Cannot find any signal ..., aborting !") self.printMsg(msg) self.statusMsg("") self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 5) return x = round(x / self.tuningstepsize) * self.tuningstepsize move(x) prev_pos = x measurements = {} self.measure() print>>log, (_("Initial signal quality") + " %5.1f" + chr(176) + ": %6.2f") % (x, self.snr_percentage) print>>log, (_("Initial lock ratio") + " %5.1f" + chr(176) + ": %6.2f") % (x, self.lock_count) measurements[x] = (self.snr_percentage, self.lock_count) start_pos = x x = 0.0 dir = 1 if self.randomBool(): dir = -dir while x < self.MAX_FOCUS_ANGLE: x += self.tuningstepsize * dir # one step east/west self.statusMsg((_("Moving") + " " + toGeoposEx(dir) + " %5.1f" + chr(176)) % abs(x + start_pos), blinking = True) move(x + start_pos) prev_pos = x + start_pos self.measure() measurements[x + start_pos] = (self.snr_percentage, self.lock_count) reportlevels(x + start_pos, self.snr_percentage, self.lock_count) if self.lock_count < self.LOCK_LIMIT: break else: msg = _("Cannot determine") + " " + toGeoposEx(dir) + " " + _("limit ..., aborting !") self.printMsg(msg) self.statusMsg("") self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 5) return x = 0.0 dir = -dir self.statusMsg((_("Moving") + " " + toGeoposEx(dir) + " %5.1f" + chr(176)) % abs(start_pos), blinking = True) move(start_pos) prev_pos = start_pos if not self.sync(): msg = _("Sync failure moving back to origin !") self.printMsg(msg) self.statusMsg("") self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 5) return while abs(x) < self.MAX_FOCUS_ANGLE: x += self.tuningstepsize * dir # one step west/east self.statusMsg((_("Moving") + " " + toGeoposEx(dir) + " %5.1f" + chr(176)) % abs(x + start_pos), blinking = True) move(x + start_pos) prev_pos = x + start_pos self.measure() measurements[x + start_pos] = (self.snr_percentage, self.lock_count) reportlevels(x + start_pos, self.snr_percentage, self.lock_count) if self.lock_count < self.LOCK_LIMIT: break else: msg = _("Cannot determine") + " " + toGeoposEx(dir) + " " + _("limit ..., aborting !") self.printMsg(msg) self.statusMsg("") self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 5) return (x0, xm) = optimise(measurements) x = move(x0) if satlon > 180: satlon -= 360 x0 += satlon xm += satlon print>>log, (_("Weighted position") + " : %5.1f" + chr(176) + " %s") % (abs(x0), toGeopos(x0)) print>>log, (_("Strongest position") + " : %5.1f" + chr(176) + " %s") % (abs(xm), toGeopos(xm)) self.logMsg((_("Final position at") + " %5.1f" + chr(176) + " %s / %d; " + _("offset is") + " %4.1f" + chr(176)) % (abs(x0), toGeopos(x0), x, x0 - satlon), timeout = 10) def autofocus(self): def move(x): if x > 0: self.diseqccommand("moveEast", (-x) & 0xFF) elif x < 0: self.diseqccommand("moveWest", x & 0xFF) if x != 0: time = int(abs(x) * self.tuningstepsize / turningspeed + 2 * self.TURNING_START_STOP_DELAY) sleep(time * self.MAX_LOW_RATE_ADAPTER_COUNT) def reportlevels(pos, level, lock): print>>log, (_("Signal quality") + " [%2d] : %6.2f") % (pos, level) print>>log, (_("Lock ratio") + " [%2d] : %6.2f") % (pos, lock) def optimise(readings): xi = readings.keys() yi = map(lambda (x, y) : x, readings.values()) x0 = int(round(sum(map(mul, xi, yi)) / sum(yi))) xm = xi[yi.index(max(yi))] return x0, xm def toGeoposEx(x): if x < 0: return _("west") else: return _("east") self.logMsg(_("Auto focus commencing ...")) turningspeed = self.getTurningspeed() measurements = {} maxsteps = max(min(round(self.MAX_FOCUS_ANGLE / self.tuningstepsize), 0x1F), 3) self.measure() print>>log, (_("Initial signal quality:") + " %6.2f") % self.snr_percentage print>>log, (_("Initial lock ratio") + " : %6.2f") % self.lock_count if self.lock_count < 1 - self.LOCK_LIMIT: msg = _("There is no signal to lock on !") self.printMsg(msg) self.statusMsg("") self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 5) return print>>log, _("Signal OK, proceeding") x = 0 dir = 1 if self.randomBool(): dir = -dir measurements[x] = (self.snr_percentage, self.lock_count) nsteps = 0 while nsteps < maxsteps: x += dir self.statusMsg((_("Moving") + " " + toGeoposEx(dir) + " %2d") % abs(x), blinking = True) move(dir) # one step self.measure() measurements[x] = (self.snr_percentage, self.lock_count) reportlevels(x, self.snr_percentage, self.lock_count) if self.lock_count < self.LOCK_LIMIT: break nsteps += 1 else: msg = _("Cannot determine") + " " + toGeoposEx(dir) + " " + _("limit ..., aborting !") self.printMsg(msg) self.statusMsg("") self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 5) return dir = -dir self.statusMsg(_("Moving") + " " + toGeoposEx(dir) + " 0", blinking = True) move(-x) if not self.sync(): msg = _("Sync failure moving back to origin !") self.printMsg(msg) self.statusMsg("") self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 5) return x = 0 nsteps = 0 while nsteps < maxsteps: x += dir self.statusMsg((_("Moving") + " " + toGeoposEx(dir) + " %2d") % abs(x), blinking = True) move(dir) # one step self.measure() measurements[x] = (self.snr_percentage, self.lock_count) reportlevels(x, self.snr_percentage, self.lock_count) if self.lock_count < self.LOCK_LIMIT: break nsteps += 1 else: msg = _("Cannot determine") + " " + toGeoposEx(dir) + " " + _("limit ..., aborting !") self.printMsg(msg) self.statusMsg("") self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 5) return (x0, xm) = optimise(measurements) print>>log, (_("Weighted position") + " : %2d") % x0 print>>log, (_("Strongest position") + " : %2d") % xm self.logMsg((_("Final position at index") + " %2d (%5.1f" + chr(176) + ")") % (x0, x0 * self.tuningstepsize), timeout = 6) move(x0 - x)
## The default pseudo-random number generator of the random module was ## designed with the focus on modelling and simulation, not on security. ## So, you shouldn't generate sensitive information such as passwords, ## secure tokens, session keys and similar things by using random. ## The SystemRandom class of the random module offers a suitable way to overcome this security ## problem. The methods of this class use an alternate random number generator, ## which uses tools provided by the operating system (such as /dev/urandom ## on Unix or CryptGenRandom on Windows. ## One can also use "secret' module on Python 3.6+ import random random_number = random.random() print("Rando Number using random function of random module(not a secure way)", random_number) print("Secure way of generating random number") from random import SystemRandom crypto = SystemRandom() print( "Create random float number >=0 and <1 using random function of \ SystemRandom class: ", crypto.random()) print("Generate a list of random numbers")
# record input if input == "": # initialize rockCount = paperCount = scissorsCount = 0 input_seq, output_seq = [], [] rng = SystemRandom() actions = ('R', 'P', 'S') beats = {'R': 'P', 'P': 'S', 'S': 'R'} # value beats key cedes = {'R': 'S', 'P': 'R', 'S': 'P'} # key beats value rng = SystemRandom() elif input == "R": rockCount += 1 input_seq.append(input) elif input == "P": paperCount += 1 input_seq.append(input) elif input == "S": scissorsCount += 1 input_seq.append(input) # choose output if rng.random() > 0.1: output = choice(actions) else: if rockCount > paperCount and rockCount > scissorsCount: output = beats['R'] elif paperCount > scissorsCount: output = beats['P'] else: output = beats['S'] output_seq.append(output)
def get_random(): crypto = SystemRandom() return crypto.random()
def password_generator( size=8, symbols=True, numeric=True, alpha_lower=True, alpha_upper=True, exclude_similar=True, exclude_ambiguous=True ): """Password generation with a given length.""" # Defining alphabets for different characher types alphabet_lower = 'abcdefghjkmnpqrstuvwxyz' alphabet_upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ' digits = '23456789' special_chars = '!#$%&*+-=?@^_' cryptogen = SystemRandom() # Joining alphabets in set character_set = '' if not exclude_similar: alphabet_lower += 'ilo' alphabet_upper += 'IO' digits += '01' special_chars += '|' if not exclude_ambiguous and symbols: special_chars += '{}[]()/\\\'\"`~,;:.<>' if symbols: character_set += special_chars if numeric: character_set += digits if alpha_lower: character_set += alphabet_lower if alpha_upper: character_set += alphabet_upper # Get random characters from char set for password password_symbols = ''.join( cryptogen.choice(character_set) for i in range(size - 4) ) # Get one character from each type, # lowercase and uppercase latin, number, special symbol password_symbols += cryptogen.choice(alphabet_lower) password_symbols += cryptogen.choice(alphabet_upper) password_symbols += cryptogen.choice(digits) password_symbols += cryptogen.choice(special_chars) # Converting taken symbols of password from string to list password_symbols = list(map(str, password_symbols)) # Mixing symbols in list with Fisher-Yates algorithm for i in range(len(password_symbols) - 1, 0, -1): j = math.floor(cryptogen.random() * (i + 1)) temp = password_symbols[j] password_symbols[j] = password_symbols[i] password_symbols[i] = temp # Converting back to string and return password_symbols = ''.join(password_symbols) return password_symbols
def GenTrapdoor_E(self): currentTime = time.time() if not os.path.isfile('dataowner/EDMRStree.json' ) or not os.path.isfile('dataowner/idf.json'): self.txtContent.setPlainText('相關的索引檔尚未建立,請聯絡資料庫擁有者') return if not os.path.isfile('dataowner/basic_secret_EDMRS.bin'): self.txtContent.setPlainText('請先向資料庫擁有者取得金鑰!') return print('Generate Trapdoor for EDMRS') f = open('dataowner/idf.json', 'r') str1 = f.read() IDF_p = json.loads(str1) raw_search = self.txtKeyword.text() try: search = raw_search.split('->')[0] filename = raw_search.split('->')[1] except: search = raw_search filename = 'trapdoor' vector = self.getplainSearchVector(search) Q = np.zeros(self.m + self.m_p) Q_1 = np.zeros(self.m + self.m_p) Q_2 = np.zeros(self.m + self.m_p) cryptogen = SystemRandom() f = open('dataowner/basic_secret_EDMRS.bin', "rb") cipherdata = f.read() f.close() cipherdata = cipherdata.decode() cipher = cipherdata.split('\n') S = cipher[0] index1 = int(cipher[1]) index2 = int(cipher[2]) print(cipher) M1 = make_spd_matrix(self.m + self.m_p, random_state=index1) M2 = make_spd_matrix(self.m + self.m_p, random_state=index2) M1_inv = np.linalg.inv(M1) M2_inv = np.linalg.inv(M2) for i in range(len(vector)): if vector[i] != 0: Q[i] = IDF_p[i] q = math.sqrt(np.sum(np.power(Q, 2))) Q = Q / q # Set half of m_p as 1 Q[np.random.choice(self.m_p, int(self.m_p / 2), replace=False) + self.m] = 1 for i in range(self.m): if S[i] == '1': Q_1[i] = Q[i] Q_2[i] = Q[i] else: Q_1[i] = cryptogen.random() Q_2[i] = Q[i] - Q_1[i] TD_1 = M1_inv.dot(Q_1) TD_2 = M2_inv.dot(Q_2) TD = list(TD_1) + list(TD_2) used_time = time.time() - currentTime print(f'花費時間:{used_time}秒') self.txtContent.setPlainText('trapdoor已建立成功') f = open(f"trapdoor/EDMRS/{filename}.json", "w") f.write(json.dumps(TD)) f.close()
import dateutil.parser import errno import json import os import pytz import re import string import six import girder import girder.events try: from random import SystemRandom random = SystemRandom() random.random() # potentially raises NotImplementedError except NotImplementedError: girder.logprint.warning( 'WARNING: using non-cryptographically secure PRNG.') import random def parseTimestamp(x, naive=True): """ Parse a datetime string using the python-dateutil package. If no timezone information is included, assume UTC. If timezone information is included, convert to UTC. If naive is True (the default), drop the timezone information such that a naive datetime is returned.
# import memcache import mysql.connector from flask import Flask, render_template, request, redirect, Markup, sessions, session from flask import flash, request, session, abort, url_for #from flask.ext.hashing import Hashing import re import hashlib from pymongo import MongoClient from random import SystemRandom import os import subprocess # mc = memcache.Client(['db-cache.ielwjl.cfg.use1.cache.amazonaws.com:11211'], debug = 1) application = Flask(__name__) cryptogen = SystemRandom() application.secret_key = str(cryptogen.random()) app = application #hashing = Hashing(application) ## Connection details for SQL Connections # cnx = mysql.connector.connect(user='******', password='******', # host='ravish.cg5bqgnmovqh.us-west-2.rds.amazonaws.com', # database='Ravish_secure') # cursor = cnx.cursor(buffered=True) client = MongoClient('ds115918.mlab.com:15918') print("DB Connected Successfully") db = client['ravish'] db.authenticate('ravish33', 'ravish293') collection = db.secure
def main(): try: opts, args = getopt.gnu_getopt(sys.argv[1:], "h", ['help', 'pass='******'-h', '--help'): usage() elif opt == '--pass': password = val if not password: d = Dialog('TurnKey Linux - First boot configuration') password = d.get_password( "Observium Password", "Enter new password for the Observium 'admin' account.") random = SystemRandom() salt = hashlib.sha1(str(random.random())).hexdigest()[:8] hash = crypt.crypt(password, "$1$" + salt + "$") m = MySQL() m.execute('UPDATE observium.users SET password=\"%s\" WHERE username=\"admin\";' % hash) if __name__ == "__main__": main()
from random import SystemRandom a = SystemRandom() print(a.random())