code stringlengths 1 18.2k |
|---|
def _load_referenced_schema_from_properties(val, a_scheme, a_property): """ :return: updated scheme """ scheme = copy.copy(a_scheme) if _value_properties_are_referenced(val): ref_schema_uri = val['properties']['$ref'] sub_schema = load_ref_schema(ref_schema_uri) ## dereference the sub schema sub_schema_copy_level_0 = c... |
sub_schema_copy_level_1, prop_1) raise SalesKingException("too much nesting in the schemes") if _value_is_required(val_0): # remove required sub_schema_copy_level_0['properties'][prop_0]['required'] = False # hack to bypass text format valitation to string if _value_is_type_text(val_0): log.debug("patched text to strin... |
def import_schema_to_json(name, store_it=False): """ loads the given schema name from the local filesystem and puts it into a store if it is not in there yet :param name: :param store_it: if set to True, stores the contents :return: """ schema_file = u"%s.json" % name file_path = os.path.join(SCHEMA_ROOT, schema_file) ... |
def load_schema(name): """ loads the schema by name :param name name of the model """ schema = import_schema_to_json(name) #salesking specific swap #//set link relation as key name to make it easier to call these for item in schema['links']: #//set link relation as key name to make it easier to call these # foreach($sc... |
(_value_properties_are_referenced(value))): schema = _load_referenced_schema_from_properties(value, schema, prop) if is_type_array and _value_is_default_any(value) and _value_has_items_key(value): schema = _load_referenced_schemes_from_list(value['items'], value, schema, prop) if _value_is_required(value): # remove req... |
def paths(self): """All the entries of sys.path, possibly restricted by --path""" if not self.select_paths: return sys.path result = [] match_any = set() for path in sys.path: path = os.path.normcase(os.path.abspath(path)) for match in self.select_paths: match = os.path.normcase(os.path.abspath(match)) if '*' in match:... |
def plugged_usbs(multiple=True) -> map or dict: """ Gets the plugged-in USB Flash drives (pen-drives). If multiple is true, it returns a map, and a dict otherwise. If multiple is false, this method will raise a :class:`.NoUSBFound` if no USB is found. """ class FindPenDrives(object): # From https://github.com/pyusb/pyu... |
'reader' not in product: return True return False def get_pendrive(pen: usb.Device) -> dict: manufacturer = pen.manufacturer.strip() or str(pen.idVendor) model = pen.product.strip() or str(pen.idProduct) serial_number = pen.serial_number.strip() hid = Naming.hid(manufacturer, serial_number, model) return { '_id': hid, ... |
def reduce_base(amount: int, base: int) -> tuple: """ Compute the reduced base of the given parameters :param amount: the amount value :param base: current base value :return: tuple containing computed (amount, base) """ if amount == 0: return 0, 0 next_amount = amount next_base = base next_amount_is_integer = True whi... |
def from_inline(cls: Type[InputSourceType], tx_version: int, inline: str) -> InputSourceType: """ Return Transaction instance from inline string format :param tx_version: Version number of the document :param inline: Inline string format :return: """ if tx_version == 2: data = InputSource.re_inline.match(inline) if dat... |
def inline(self, tx_version: int) -> str: """ Return an inline string format of the document :param tx_version: Version number of the document :return: """ if tx_version == 2: return "{0}:{1}:{2}".format(self.source, self.origin_id, self.index) else: return "{0}:{1}:{2}:{3}:{4}".format(self.amount, self.base, self.sour... |
def from_inline(cls: Type[OutputSourceType], inline: str) -> OutputSourceType: """ Return OutputSource instance from inline string format :param inline: Inline string format :return: """ data = OutputSource.re_inline.match(inline) if data is None: raise MalformedDocumentError("Inline output") amount = int(data.group(1)... |
def inline(self) -> str: """ Return an inline string format of the document :return: """ return "{0}:{1}:{2}".format(self.amount, self.base, pypeg2.compose(self.condition, output.Condition)) |
def condition_from_text(text) -> Condition: """ Return a Condition instance with PEG grammar from text :param text: PEG parsable string :return: """ try: condition = pypeg2.parse(text, output.Condition) except SyntaxError: # Invalid conditions are possible, see https://github.com/duniter/duniter/issues/1156 # In such a... |
def from_parameter(cls: Type[SIGParameterType], parameter: str) -> Optional[SIGParameterType]: """ Return a SIGParameter instance from an index parameter :param parameter: Index parameter :return: """ sig = SIGParameter.re_sig.match(parameter) if sig: return cls(int(sig.group(1))) return None |
def from_parameter(cls: Type[XHXParameterType], parameter: str) -> Optional[XHXParameterType]: """ Return a XHXParameter instance from an index parameter :param parameter: Index parameter :return: """ xhx = XHXParameter.re_xhx.match(parameter) if xhx: return cls(int(xhx.group(1))) return None |
def from_parameter(cls: Type[UnlockParameterType], parameter: str) -> Optional[Union[SIGParameter, XHXParameter]]: """ Return UnlockParameter instance from parameter string :param parameter: Parameter string :return: """ sig_param = SIGParameter.from_parameter(parameter) if sig_param: return sig_param else: xhx_param =... |
def from_inline(cls: Type[UnlockType], inline: str) -> UnlockType: """ Return an Unlock instance from inline string format :param inline: Inline string format :return: """ data = Unlock.re_inline.match(inline) if data is None: raise MalformedDocumentError("Inline input") index = int(data.group(1)) parameters_str = data... |
def inline(self) -> str: """ Return inline string format of the instance :return: """ return "{0}:{1}".format(self.index, ' '.join([str(p) for p in self.parameters])) |
def from_bma_history(cls: Type[TransactionType], currency: str, tx_data: Dict) -> TransactionType: """ Get the transaction instance from json :param currency: the currency of the tx :param tx_data: json data of the transaction :return: """ tx_data = tx_data.copy() tx_data["currency"] = currency for data_list in ('issue... |
def from_compact(cls: Type[TransactionType], currency: str, compact: str) -> TransactionType: """ Return Transaction instance from compact string format :param currency: Name of the currency :param compact: Compact format string :return: """ lines = compact.splitlines(True) n = 0 header_data = Transaction.re_header.mat... |
1 for i in range(0, unlocks_num): unlock = Unlock.from_inline(lines[n]) unlocks.append(unlock) n += 1 for i in range(0, outputs_num): output_source = OutputSource.from_inline(lines[n]) outputs.append(output_source) n += 1 comment = "" if has_comment == 1: data = Transaction.re_compact_comment.match(lines[n]) if data: c... |
def from_signed_raw(cls: Type[TransactionType], raw: str) -> TransactionType: """ Return a Transaction instance from a raw string format :param raw: Raw string format :return: """ lines = raw.splitlines(True) n = 0 version = int(Transaction.parse_field("Version", lines[n])) n += 1 Transaction.parse_field("Type", lines[... |
Transaction.re_outputs.match(lines[n]) is None: unlock = Unlock.from_inline(lines[n]) unlocks.append(unlock) n += 1 if Transaction.re_outputs.match(lines[n]) is not None: n += 1 while not Transaction.re_comment.match(lines[n]): _output = OutputSource.from_inline(lines[n]) outputs.append(_output) n += 1 comment = Transa... |
def raw(self) -> str: """ Return raw string format from the instance :return: """ doc = """Version: {0} Type: Transaction Currency: {1} """.format(self.version, self.currency) if self.version >= 3: doc += "Blockstamp: {0}\n".format(self.blockstamp) doc += "Locktime: {0}\n".format(self.locktime) doc += "Issuers:\n" for ... |
def compact(self) -> str: """ Return a transaction in its compact format from the instance :return: """ """TX:VERSION:NB_ISSUERS:NB_INPUTS:NB_UNLOCKS:NB_OUTPUTS:HAS_COMMENT:LOCKTIME PUBLIC_KEY:INDEX ... INDEX:SOURCE:FINGERPRINT:AMOUNT ... PUBLIC_KEY:AMOUNT ... COMMENT """ doc = "TX:{0}:{1}:{2}:{3}:{4}:{5}:{6}\n".format... |
def is_simple(tx: Transaction) -> bool: """ Filter a transaction and checks if it is a basic one A simple transaction is a tx which has only one issuer and two outputs maximum. The unlocks must be done with simple "SIG" functions, and the outputs must be simple SIG conditions. :param tx: the transaction to check :retur... |
def retry(self, retries, task_f, check_f=bool, wait_f=None): """ Try a function up to n times. Raise an exception if it does not pass in time :param retries int: The number of times to retry :param task_f func: The function to be run and observed :param func()bool check_f: a function to check if task_f is complete :par... |
def check_assert(self, cmd, retries=1, pollrate=60, on_retry=None): """ Run a command, logging (using gather) and raise an exception if the return code of the command indicates failure. Try the command multiple times if requested. :param cmd <string|list>: A shell command :param retries int: The number of times to try ... |
Final result = {} in {} tries.".format(result, try_num)) assertion.success( result, "Error running [{}] {}.\n{}". format(pushd.Dir.getcwd(), cmd, stderr)) return stdout, stderr |
def gather(self, cmd): """ Runs a command and returns rc,stdout,stderr as a tuple. If called while the `Dir` context manager is in effect, guarantees that the process is executed in that directory, even if it is no longer the current directory of the process (i.e. it is thread-safe). :param cmd: The command and argumen... |
def json_serial(obj): """ Custom JSON serializer for objects not serializable by default. """ if isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() raise TypeError('Type {} not serializable.'.format(type(obj))) |
def next_version(ctx: click.Context, _, value): """ Prints next version (according to Gitversion run) then exits """ if not value or ctx.resilient_parsing: return config.QUIET.default = True CTX.repo = epab.utils.Repo() print(epab.utils.get_next_version()) sys.exit(0) |
def train_weather_predictor( location='Portland, OR', years=range(2013, 2016,), delays=(1, 2, 3), inputs=('Min Temperature', 'Max Temperature', 'Min Sea Level Pressure', u'Max Sea Level Pressure', 'WindDirDegrees',), outputs=(u'Max TemperatureF',), N_hidden=6, epochs=30, use_cache=False, verbosity=2, ): """Train a neur... |
ST" alternatively an airport code like "PDX or LAX" delays (list of int): sample delays to use for the input tapped delay line. Positive and negative values are treated the same as sample counts into the past. default: [1, 2, 3], in z-transform notation: z^-1 + z^-2 + z^-3 years (int or list of int): list of 4-digit ye... |
inputs=inputs, outputs=outputs, verbosity=verbosity) nn = util.ann_from_ds(ds, N_hidden=N_hidden, verbosity=verbosity) trainer = util.build_trainer(nn, ds=ds, verbosity=verbosity) trainer.trainEpochs(epochs) columns = [] for delay in delays: columns += [inp + "[-{}]".format(delay) for inp in inputs] columns += list(out... |
def oneday_weather_forecast( location='Portland, OR', inputs=('Min Temperature', 'Mean Temperature', 'Max Temperature', 'Max Humidity', 'Mean Humidity', 'Min Humidity', 'Max Sea Level Pressure', 'Mean Sea Level Pressure', 'Min Sea Level Pressure', 'Wind Direction'), outputs=('Min Temperature', 'Mean Temperature', 'Max ... |
= update_dict(yesterday, {'date': df.index[-2].date()}) today = dict(zip(outputs, nn.activate(trainer.ds['input'][-1]))) forecast['today'] = update_dict(today, {'date': df.index[-1].date()}) ds = util.input_dataset_from_dataframe(df[-max(delays):], delays=delays, inputs=inputs, normalize=False, verbosity=0) tomorrow = ... |
def run_competition(builders=[], task=BalanceTask(), Optimizer=HillClimber, rounds=3, max_eval=20, N_hidden=3, verbosity=0): """ pybrain buildNetwork builds a subtly different network structhan build_ann... so compete them! Arguments: task (Task): task to compete at Optimizer (class): pybrain.Optimizer class to instant... |
range(rounds): heat = [] # FIXME: shuffle the order of the builders to keep things fair # (like switching sides of the tennis court) for builder in builders: try: competitor = builder(task.outdim, N_hidden, task.indim, verbosity=verbosity) except NetworkError: competitor = builder(task.outdim, N_hidden, task.indim) # T... |
speedi = np.argmax(means[0]), np.argmin(means[1]) print('And the winner for performance is ... Algorithm #{} (0-offset array index [{}])'.format(perfi+1, perfi)) print('And the winner for speed is ... Algorithm #{} (0-offset array index [{}])'.format(speedi+1, speedi)) return results, means |
def environ(context): """Retrieves the environment for a particular SETSHELL context""" if 'BASEDIRSETSHELL' not in os.environ: # It seems that we are in a hostile environment # try to source the Idiap-wide shell idiap_source = "/idiap/resource/software/initfiles/shrc" if os.path.exists(idiap_source): logger.debug("Sou... |
os.environ['BASEDIRSETSHELL'] dosetshell = '%s/setshell/bin/dosetshell' % BASEDIRSETSHELL command = [dosetshell, '-s', 'sh', context] # First things first, we get the path to the temp file created by dosetshell try: logger.debug("Executing: '%s'", ' '.join(command)) p = subprocess.Popen(command, stdout = subprocess.PIP... |
raise OSError("Error executing '%s': %s (%d)" % (' '.join(command2), e.strerror, e.errno)) new_environ = dict(os.environ) for line in p2.stdout: line = str_(line) (key, _, value) = line.partition("=") new_environ[key.strip()] = value.strip() try: p2.communicate() except KeyboardInterrupt: # the user CTRL-C'ed os.kill(p... |
def sexec(context, command, error_on_nonzero=True): """Executes a command within a particular Idiap SETSHELL context""" import six if isinstance(context, six.string_types): E = environ(context) else: E = context try: logger.debug("Executing: '%s'", ' '.join(command)) p = subprocess.Popen(command, stdout=subprocess.PIPE... |
def get_dates_in_period(start=None, top=None, step=1, step_dict={}): """Return a list of dates from the `start` to `top`.""" delta = relativedelta(**step_dict) if step_dict else timedelta(days=step) start = start or datetime.today() top = top or start + delta dates = [] current = start while current <= top: dates.appen... |
def localize_date(date, city): """ Localize date into city Date: datetime City: timezone city definitio. Example: 'Asia/Qatar', 'America/New York'.. """ local = pytz.timezone(city) local_dt = local.localize(date, is_dst=None) return local_dt |
def get_month_from_date_str(date_str, lang=DEFAULT_DATE_LANG): """Find the month name for the given locale, in the given string. Returns a tuple ``(number_of_month, abbr_name)``. """ date_str = date_str.lower() with calendar.different_locale(LOCALES[lang]): month_abbrs = list(calendar.month_abbr) for seq, abbr in enume... |
def replace_month_abbr_with_num(date_str, lang=DEFAULT_DATE_LANG): """Replace month strings occurrences with month number.""" num, abbr = get_month_from_date_str(date_str, lang) return re.sub(abbr, str(num), date_str, flags=re.IGNORECASE) |
def translate_month_abbr( date_str, source_lang=DEFAULT_DATE_LANG, target_lang=DEFAULT_DATE_LANG): """Translate the month abbreviation from one locale to another.""" month_num, month_abbr = get_month_from_date_str(date_str, source_lang) with calendar.different_locale(LOCALES[target_lang]): translated_abbr = calendar.mo... |
def merge_datetime(date, time='', date_format='%d/%m/%Y', time_format='%H:%M'): """Create ``datetime`` object from date and time strings.""" day = datetime.strptime(date, date_format) if time: time = datetime.strptime(time, time_format) time = datetime.time(time) day = datetime.date(day) day = datetime.combine(day, tim... |
def display_list(prefix, l, color): """ Prints a file list to terminal, allows colouring output. """ for itm in l: print colored(prefix + itm['path'], color) |
def pfx_path(path): """ Prefix a path with the OS path separator if it is not already """ if path[0] != os.path.sep: return os.path.sep + path else: return path |
def file_put_contents(path, data): """ Put passed contents into file located at 'path' """ with open(path, 'w') as f: f.write(data); f.flush() |
def file_or_default(path, default, function = None): """ Return a default value if a file does not exist """ try: result = file_get_contents(path) if function != None: return function(result) return result except IOError as e: if e.errno == errno.ENOENT: return default raise |
def make_dirs_if_dont_exist(path): """ Create directories in path if they do not exist """ if path[-1] not in ['/']: path += '/' path = os.path.dirname(path) if path != '': try: os.makedirs(path) except OSError: pass |
def cpjoin(*args): """ custom path join """ rooted = True if args[0].startswith('/') else False def deslash(a): return a[1:] if a.startswith('/') else a newargs = [deslash(arg) for arg in args] path = os.path.join(*newargs) if rooted: path = os.path.sep + path return path |
def get_single_file_info(f_path, int_path): """ Gets the creates and last change times for a single file, f_path is the path to the file on disk, int_path is an internal path relative to a root directory. """ return { 'path' : force_unicode(int_path), 'created' : os.path.getctime(f_path), 'last_mod' : os.path.getmtime(... |
def hash_file(file_path, block_size = 65536): """ Hashes a file with sha256 """ sha = hashlib.sha256() with open(file_path, 'rb') as h_file: file_buffer = h_file.read(block_size) while len(file_buffer) > 0: sha.update(file_buffer) file_buffer = h_file.read(block_size) return sha.hexdigest() |
def get_file_list(path): """ Recursively lists all files in a file system below 'path'. """ f_list = [] def recur_dir(path, newpath = os.path.sep): files = os.listdir(path) for fle in files: f_path = cpjoin(path, fle) if os.path.isdir(f_path): recur_dir(f_path, cpjoin(newpath, fle)) elif os.path.isfile(f_path): f_list.... |
def find_manifest_changes(new_file_state, old_file_state): """ Find what has changed between two sets of files """ prev_state_dict = copy.deepcopy(old_file_state) changed_files = {} # Find files which are new on the server for itm in new_file_state: if itm['path'] in prev_state_dict: d_itm = prev_state_dict.pop(itm['pa... |
def shasha(msg): """SHA256(SHA256(msg)) -> HASH object""" res = hashlib.sha256(hashlib.sha256(msg).digest()) return res |
def ripesha(msg): """RIPEMD160(SHA256(msg)) -> HASH object""" ripe = hashlib.new('ripemd160') ripe.update(hashlib.sha256(msg).digest()) return ripe |
def privkey_to_wif(rawkey, compressed=True, net=BC): """Convert privkey bytes to Wallet Import Format (WIF).""" # See https://en.bitcoin.it/wiki/Wallet_import_format. k = net.wifprefix + rawkey if compressed: k += b'\x01' chksum = shasha(k).digest()[:4] key = k + chksum b58key = b58encode(key) return b58key |
def wif_to_privkey(wif, compressed=True, net=BC): """Convert Wallet Import Format (WIF) to privkey bytes.""" key = b58decode(wif) version, raw, check = key[0:1], key[1:-4], key[-4:] assert version == net.wifprefix, "unexpected version byte" check_compare = shasha(version + raw).digest()[:4] assert check_compare == chec... |
def is_archive(filename): '''returns boolean of whether this filename looks like an archive''' for archive in archive_formats: if filename.endswith(archive_formats[archive]['suffix']): return True return False |
def archive_basename(filename): '''returns the basename (name without extension) of a recognized archive file''' for archive in archive_formats: if filename.endswith(archive_formats[archive]['suffix']): return filename.rstrip('.' + archive_formats[archive]['suffix']) return False |
def unarchive(filename,output_dir='.'): '''unpacks the given archive into ``output_dir``''' if not os.path.exists(output_dir): os.makedirs(output_dir) for archive in archive_formats: if filename.endswith(archive_formats[archive]['suffix']): return subprocess.call(archive_formats[archive]['command'](output_dir,filename)... |
def flatten(nested_list): '''converts a list-of-lists to a single flat list''' return_list = [] for i in nested_list: if isinstance(i,list): return_list += flatten(i) else: return_list.append(i) return return_list |
def run(command,products=None,working_directory='.',force_local=False,stderr=True,quiet=False): '''wrapper to run external programs :command: list containing command and parameters (formatted the same as subprocess; must contain only strings) :products: string or list of files that are the products of this command if a... |
isinstance(products,basestring): products = [products] if all([os.path.exists(x) for x in products]): return False command = flatten(command) command = [str(x) for x in command] quiet_option = False if quiet==False else True with nl.notify('Running %s...' % command[0],level=nl.level.debug,quiet=quiet_option): out = Non... |
def log(fname,msg): ''' generic logging function ''' with open(fname,'a') as f: f.write(datetime.datetime.now().strftime('%m-%d-%Y %H:%M:\n') + msg + '\n') |
def hash(filename): '''returns string of MD5 hash of given filename''' buffer_size = 10*1024*1024 m = hashlib.md5() with open(filename) as f: buff = f.read(buffer_size) while len(buff)>0: m.update(buff) buff = f.read(buffer_size) dig = m.digest() return ''.join(['%x' % ord(x) for x in dig]) |
def hash_str(string): '''returns string of MD5 hash of given string''' m = hashlib.md5() m.update(string) dig = m.digest() return ''.join(['%x' % ord(x) for x in dig]) |
def find(file): '''tries to find ``file`` using OS-specific searches and some guessing''' # Try MacOS Spotlight: mdfind = which('mdfind') if mdfind: out = run([mdfind,'-name',file],stderr=None,quiet=None) if out.return_code==0 and out.output: for fname in out.output.split('\n'): if os.path.basename(fname)==file: return... |
def universal_read(fname): '''Will open and read a file with universal line endings, trying to decode whatever format it's in (e.g., utf8 or utf16)''' with open(fname,'rU') as f: data = f.read() enc_guess = chardet.detect(data) return data.decode(enc_guess['encoding']) |
def strip_rows(array,invalid=None): '''takes a ``list`` of ``list``s and removes corresponding indices containing the invalid value (default ``None``). ''' array = np.array(array) none_indices = np.where(np.any(np.equal(array,invalid),axis=0)) return tuple(np.delete(array,none_indices,axis=1)) |
def numberize(string): '''Turns a string into a number (``int`` or ``float``) if it's only a number (ignoring spaces), otherwise returns the string. For example, ``"5 "`` becomes ``5`` and ``"2 ton"`` remains ``"2 ton"``''' if not isinstance(string,basestring): return string just_int = r'^\s*[-+]?\d+\s*$' just_float = ... |
def check_packet(self): '''is there a valid packet (from another thread) for this app/instance?''' if not os.path.exists(self.packet_file()): # No packet file, we're good return True else: # There's already a file, but is it still running? try: with open(self.packet_file()) as f: packet = json.loads(f.read()) if time.t... |
def get_hexagram(method='THREE COIN'): """ Return one or two hexagrams using any of a variety of divination methods. The ``NAIVE`` method simply returns a uniformally random ``int`` between ``1`` and ``64``. All other methods return a 2-tuple where the first value represents the starting hexagram and the second represe... |
a `tuple` will be returned. tuple: A 2-tuple of form ``(int, int)`` where the first value is key of the starting hexagram and the second is that of the 'moving-to' hexagram. Raises: ValueError if ``method`` is invalid Examples: The function being used alone: :: >>> get_hexagram(method='THREE COIN') # doctest: +SKIP # M... |
... ) # doctest: +SKIP Confining moving to Augmenting """ if method == 'THREE COIN': weights = [('MOVING YANG', 2), ('MOVING YIN', 2), ('STATIC YANG', 6), ('STATIC YIN', 6)] elif method == 'YARROW': weights = [('MOVING YANG', 8), ('MOVING YIN', 2), ('STATIC YANG', 11), ('STATIC YIN', 17)] elif method == 'NAIVE': return... |
def get_supported_resources(netid): """ Returns list of Supported resources """ url = _netid_supported_url(netid) response = get_resource(url) return _json_to_supported(response) |
def _json_to_supported(response_body): """ Returns a list of Supported objects """ data = json.loads(response_body) supported = [] for supported_data in data.get("supportedList", []): supported.append(Supported().from_json( supported_data)) return supported |
def add_arguments(parser): """Adds stock arguments to argparse parsers from scripts that submit grid jobs.""" default_log_path = os.path.realpath('logs') parser.add_argument('--log-dir', metavar='LOG', type=str, dest='logdir', default=default_log_path, help='Base directory used for logging (defaults to "%(default)s")')... |
qsub') parser.add_argument('--no-cwd', default=True, action='store_false', dest='cwd', help='Do not change to the current directory when starting the grid job') parser.add_argument('--dry-run', default=False, action='store_true', dest='dryrun', help='Does not really submit anything, just print what would do instead') p... |
def create_manager(arguments): """A simple wrapper to JobManager() that places the statefile on the correct path by default""" if arguments.statefile is None: arguments.statefile = os.path.join(os.path.dirname(arguments.logdir), 'submitted.db') arguments.statefile = os.path.realpath(arguments.statefile) return manager.... |
def submit(jman, command, arguments, deps=[], array=None): """An easy submission option for grid-enabled scripts. Create the log directories using random hash codes. Use the arguments as parsed by the main script.""" logdir = os.path.join(os.path.realpath(arguments.logdir), tools.random_logdir()) jobname = os.path.spli... |
def add_to_dict(self, text): """ Generate word n-tuple and next word probability dict """ n = self.n sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?|!)\s', text) # '' is a special symbol for the start of a sentence like pymarkovchain uses for sentence in sentences: sentence = sentence.replace('"','') # re... |
this to represent probabilities for word in self.word_dict: wordsum = 0 for nextword in self.word_dict[word]: wordsum += self.word_dict[word][nextword].count if wordsum != 0: for nextword in self.word_dict[word]: self.word_dict[word][nextword].prob = self.word_dict[word][nextword].count / wordsum |
def next_word(self, previous_words): """The next word that is generated by the Markov Chain depends on a tuple of the previous words from the Chain""" # The previous words may never have appeared in order in the corpus used to # generate the word_dict. Consequently, we want to try to find the previous # words in orde, ... |
for k, v in frequencies.items()] p, w = zip(*inv) return np.random.choice(w,1,p)[0] |
def get_transaction_document(current_block: dict, source: dict, from_pubkey: str, to_pubkey: str) -> Transaction: """ Return a Transaction document :param current_block: Current block infos :param source: Source to send :param from_pubkey: Public key of the issuer :param to_pubkey: Public key of the receiver :return: T... |
async def main(): """ Main code """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) # Get the node summary infos to test the connection response = await client(bma.node.summary) print(response) # prompt hidden user entry salt = getpass.getpass("Enter your passphrase (salt): ") # pr... |
document transaction = get_transaction_document(current_block, source, pubkey_from, pubkey_to) # sign document transaction.sign([key]) # send the Transaction document to the node response = await client(bma.tx.process, transaction.signed_raw()) if response.status == 200: print(await response.text()) else: print("Error ... |
def check_type(obj: Any, candidate_type: Any, reltype: str = 'invariant') -> bool: """Tell wether a value correspond to a type, optionally specifying the type as contravariant or covariant. Args: obj (Any): The value to check. candidate_type (Any): The type to check the object against. reltype (:obj:`str`, optional): V... |
['covariant']: return issubclass(obj.__class__, candidate_type) if type(candidate_type) == type and reltype in ['contravariant']: return issubclass(candidate_type, obj.__class__) # Any accepts everything if type(candidate_type) == type(Any): return True # Union, at least one match in __args__ if type(candidate_type) ==... |
matches the type in __args__ if type(candidate_type) == type(List) and \ (list in candidate_type.__bases__ or set in candidate_type.__bases__): if not hasattr(obj, '__len__'): return False return all(check_type(o, candidate_type.__args__[0], reltype) for o in obj) # TypeVar, this is tricky if type(candidate_type) == Ty... |
def check_args(func): """A decorator that performs type checking using type hints at runtime:: @check_args def fun(a: int): print(f'fun is being called with parameter {a}') # this will raise a TypeError describing the issue without the function being called fun('not an int') """ @wraps(func) def check(*args, **kwargs):... |
find one, at most, detecting what else # is missing is tricky if not impossible if not found_errors: raise DetailedTypeError([IssueDescription(None, None, None, None, str(te))]) raise DetailedTypeError(found_errors) for name, value in binding.arguments.items(): if not check_type(value, sig.parameters[name].annotation):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.