def test_bundle_serie_of_should_build_max_bundles(): bundler = bundle_series_of(references=['A', 'B']) result_bundles = list( bundler( cart(item(reference='A', quantity=3), item(reference='B', quantity=2)))) assert result_bundles == [Bundle(size=2)] * 2 + [Bundle(size=1)]
def get_bundles_from(yml): bundles = list() for bundle in yml.get('roles', list()): b = Bundle('role', bundle) bundles.append(b) for bundle in yml.get('dependencies', list()): if bundle.get('role', None): b = Bundle('role', bundle) bundles.append(b) return bundles
def _process_requests(self): if self.mode != Server.Modes.PROCESSING: raise ValueError(f"not ready to process: in state {self.mode}") elif self._bundles: raise ValueError("bundles already exist; can't process") self._bundles = [Bundle() for _ in range(self.SERVER_COUNT)] rsa_priv_keys = [k.export_key() for k in self._keys] # sequentially process up prev_up = list(self._id_map.values()) # initial is direct from client: final is terminal's decrypted for b, pk in zip(self._bundles, rsa_priv_keys): b.load_up(prev_up) prev_up = b.send_up(pk) terminal_raws = prev_up prev_down = self._terminal_process(terminal_raws) for b in reversed(self._bundles): # go in the opposite direction now b.load_down(prev_down) prev_down = b.send_down() self._responses = {id: resp for id, resp in zip(self._id_map.keys(), prev_down)} self.mode = Server.Modes.DISTRIBUTING
def dumps(self): out = str(self) for tid in self.global_history.buckets: hit_list = self.global_history.buckets[tid].head bundle = Bundle() prev = None while hit_list != None: print("[", hit_list.value.ns, "] [", hit_list.value.tid, "]", hit_list.value.name) if prev != None: # for testing purposes, ensure this is true assert prev.ns < hit_list.value.ns prev = hit_list.value bundle.push(hit_list.value) hit_list = hit_list.next out += str(bundle) if self.file: try: with open(self.file, "w") as fd: fd.write(out) except IOError as e: print(e) print(out) else: print(out)
def get_watchkit_paths(root_bundle_path): """ collect sub-bundles of this bundle that have watchkit """ # typical structure: # # app_bundle # ... # some_directory # watchkit_extension <-- this is the watchkit bundle # Info.plist # watchkit_bundle <-- this is the part that runs on the Watch # Info.plist <-- WKWatchKitApp=True # watchkit_paths = [] for path, _, _ in os.walk(root_bundle_path): if path == root_bundle_path: continue try: bundle = Bundle(path) except NotMatched: # this directory is not a bundle continue if bundle.info.get('WKWatchKitApp') is True: # get the *containing* bundle watchkit_paths.append(dirname(path)) return watchkit_paths
def view(): logger = Logger(mongo) global bundle bundle = Bundle(mongo) if current_user.ID != admin_id: flash(f'This account is not authorised to view logs!','danger') return redirect(url_for('log')) else: form = ViewForm() if request.method == 'POST': log_list = logger.get_log(form.i_field.data, form.b_field.data, form.p_field.data) user_json = logger.get_user(form.i_field.data) if user_json: user = User(user_json) if log_list == []: return render_template('view.html', form=form, no_log="Currently no existing Logs to view", user=user) else: return render_template('view.html', form=form, log_list=log_list, user=user) else: flash(f'User does not Exist!','danger') return redirect(url_for('view')) return render_template('view.html', form=form)
def register(self, name, *args, **kwargs): """Register a bundle with the given name. There are two possible ways to call this: - With a single ``Bundle`` instance argument: register('jquery', jquery_bundle) - With one or multiple arguments, automatically creating a new bundle inline: register('all.js', jquery_bundle, 'common.js', output='packed.js') """ if len(args) == 0: raise TypeError('at least two arguments are required') else: if len(args) == 1 and not kwargs and isinstance(args[0], Bundle): bundle = args[0] else: bundle = Bundle(*args, **kwargs) if name in self._named_bundles: if self._named_bundles[name] == bundle: pass # ignore else: raise RegisterError( 'Another bundle is already registered ' + 'as "%s": %s' % (name, self._named_bundles[name])) else: self._named_bundles[name] = bundle bundle.env = self # take ownership return bundle
def register(name, *args, **kwargs): """Register a bundle with the given name. There are two possible ways to call this: - With a single ``Bundle`` instance argument: register('jquery', jquery_bundle) - With one or multiple arguments, automatically creating a new bundle inline: register('all.js', jquery_bundle, 'common.js', output='packed.js') """ if len(args) == 0: raise TypeError('at least two arguments are required') else: if len(args) == 1 and not kwargs and isinstance(args[0], Bundle): bundle = args[0] else: bundle = Bundle(*args, **kwargs) global _REGISTRY if name in _REGISTRY: if _REGISTRY[name] == bundle: pass # ignore else: raise RegistryError('Another bundle is already registered '+ 'as "%s": %s' % (name, _REGISTRY[name])) else: _REGISTRY[name] = bundle
def main(): i = Invoice() data = i.get_processed_data() b = Bundle() # Create separate files split by sender IBAN for send_iban in settings.SENDER_IBAN: content = b.generate(data, send_iban) b.save_to_disk(send_iban, content)
def addTrxnTransfer(self, workTangle, sendNode, recNode, transAmount=5): tips = workTangle.find_tips() tipObjs = [] for tip in tips: tipObjs.append(workTangle.bundleObjects.get(tip)) value_bundle = Bundle(workTangle.find_tips(), tipObjs, sendNode) # add value transition in Bundle value_bundle.add_value_tx(sendNode, recNode, transAmount) workTangle.add_tx(value_bundle)
def __init__(self): super(App, self).__init__() self.bundle = Bundle() self.app = urwid.MainLoop( self.bundle.output, unhandled_input=self.bundle.globle_input_listener) self.signal_flash = True self.app.set_alarm_in(1, self.update_datetime) self.app.set_alarm_in(0.5, self.post_list_status_tracker) self.app.run()
def to_bundle(self, prefix=''): """ Turns an object into a serialized bundle. Args: prefix: The prefix to prepend to the keys corresponding to the instance variable names Returns: A serialized bundle that can be unbundled into the same object. """ bnd = Bundle() metacount = 0 bnd.set_value(prefix + '.type', self.__class__.__name__) for key, val in self.__dict__.iteritems(): if isinstance(val, Bundleable): # take care of nested bundleables bnd.assimilate(val.to_bundle(prefix='%s.%s' % (prefix, key))) arg_type = val.__module__ + '.' + val.__class__.__name__ meta = BundleableMetadata(key, arg_type, '%s.%s' % (prefix, key)) bnd.assimilate( meta.to_bundle('%s.meta.%d' % (prefix, metacount))) metacount += 1 elif isinstance(val, list): # take care of a list if val: if isinstance(val[0], Bundleable): # list of bundleables bnd.assimilate( self.encode_list(val, prefix='%s.%s' % (prefix, key))) arg_type = val[0].__module__ + '.' + val[ 0].__class__.__name__ meta = ListMetadata(key, arg_type, '%s.%s' % (prefix, key), len(val)) bnd.assimilate( meta.to_bundle('%s.meta.%d' % (prefix, metacount))) metacount += 1 else: # list of primitives - anything that can be converted to/from a string for i, obj in enumerate(val): bnd.set_value('%s.%s.%d' % (prefix, key, i), obj) #TODO the line below only works if val is not empty meta = ListMetadata( key, 'prim.' + str(type(val[0]).__name__), '%s.%s' % (prefix, key), len(val)) bnd.assimilate( meta.to_bundle('%s.meta.%d' % (prefix, metacount))) metacount += 1 else: # empty list bnd.set_value('%s.%s' % (prefix, key), val) else: bnd.set_value(prefix + "." + key, self.__dict__[key]) return bnd
def wildcard_bundle(): return Bundle( '*.common.name', 'e8a7fcfbe48df21daede665d78984dec', KEY, CSR, CRT, '0000000', expiry=EXPIRY, authority=dict(digicert=dict(order_id=1298368)), timestamp=TIMESTAMP)
def addTrxn(self, workTangle, workNode): tips = workTangle.find_tips() tipObjs = [] for tip in tips: tipObjs.append(workTangle.bundleObjects.get(tip)) genBundle = Bundle(tips, tipObjs, workNode) # Generate basic bundle metaTrxn = Trxn(genBundle) genBundle.addTrxn(metaTrxn) # Add non-value trxn workTangle.add_tx( genBundle) # Record bundle with transaction in tangle and do PoW
class ViewForm(FlaskForm): b_field = SelectField("Bundle: ", choices=Bundle(Mongo()).get_bundle_names(), default=1) p_field = SelectField("Project: ", choices=[("Project", "Project")], default=1) i_field = SelectField("ID: ", choices=[("ID", "ID")], default=1) submit = SubmitField('Submit')
def register(self, name, *args, **kwargs): """Register a :class:`Bundle` with the given ``name``. This can be called in multiple ways: - With a single :class:`Bundle` instance:: env.register('jquery', jquery_bundle) - With a dictionary, registering multiple bundles at once: bundles = {'js': js_bundle, 'css': css_bundle} env.register(bundles) .. note:: This is a convenient way to use a :doc:`loader <loaders>`: env.register(YAMLLoader('assets.yaml').load_bundles()) - With many arguments, creating a new bundle on the fly:: env.register('all_js', jquery_bundle, 'common.js', filters='rjsmin', output='packed.js') """ # Register a dict if isinstance(name, dict) and not args and not kwargs: for name, bundle in name.items(): self.register(name, bundle) return if len(args) == 0: raise TypeError('at least two arguments are required') else: if len(args) == 1 and not kwargs and isinstance(args[0], Bundle): bundle = args[0] else: bundle = Bundle(*args, **kwargs) if name in self._named_bundles: if self._named_bundles[name] == bundle: pass # ignore else: raise RegisterError( 'Another bundle is already registered ' + 'as "%s": %s' % (name, self._named_bundles[name])) else: self._named_bundles[name] = bundle bundle.env = self # take ownership return bundle
def test_json_roundtrip(bundle): json = bundle.to_obj() common_name, modhash, key, csr, crt, bug, sans, expiry, authority, destinations, timestamp = Bundle.from_obj(json) bundle2 = Bundle( common_name, modhash, key, csr, crt, bug, sans=sans, expiry=expiry, authority=authority, destinations=destinations, timestamp=timestamp) assert bundle == bundle2
def __init__(self): # One trxn with a bundle to start as genesis, random selection with replacement allows for growing tangle # ==> URTS # TGraph key {key: [trnxObject]} self.genBundle = Bundle(None,None, None) # Setup genesis Bundle self.genBundle.addTrxn(self.genBundle) self.tGraph = {'genesis_trxn': [None]} self.bundleObjects = {'genesis_trxn': self.genBundle} # No data to start self.tData = {} # Five nodes for example self.tLedger = {} self.netNodes = [] self.tValues = {}
def load(tracks_path, cameras_path): bundle = Bundle() bundle.K = K # Read cameras camera_data = np.loadtxt(open(cameras_path)) for row in camera_data: P = row.reshape((3, 4)) bundle.add_camera(Camera(P[:, :3], P[:, 3])) # Read tracks for i, line in enumerate(open(tracks_path)): tokens = line.strip().split() assert len(tokens) % 3 == 0, 'Error at line %d:\n %s' % (i, line) vs = np.array(map(int, tokens)).reshape((-1, 3)) bundle.add_track(Track(list(vs[:, 0].astype(int)), vs[:, 1:])) return bundle
class LogForm(FlaskForm): b_field = SelectField("Bundle: ", choices=Bundle(Mongo()).get_bundle_names(), default=1) p_field = SelectField("Project: ", choices=[("Project","Project")], default=1) i_field = SelectField("ID: ", choices=[("ID","ID")], default=1) log_text = TextAreaField('log_text', validators=[DataRequired(), Length(min=10, max=1000)]) log_time = StringField('log_time', validators=[DataRequired(), Length(min=1, max=5)]) submit = SubmitField('Submit')
def add_projects(): bundle = Bundle(mongo) if current_user.ID != admin_id: flash(f'This account is not authorised to add Projects!','danger') return redirect(url_for('log')) else: f = 0 form = AddProjectForm() bundle_lst = bundle.get_bundle_list() project_lst = bundle.get_project_list() ID_lst = bundle.get_ID_list() if request.method == 'POST': f = bundle.add_project(form.bundle_text.data, form.project_text.data, form.ID_text.data) if f == -1: flash(f'Already Exists!','danger') redirect(url_for('add_projects')) elif f == 1: flash(f'Successfully Added!','success') redirect(url_for('add_projects')) return render_template('add_projects.html', form=form, bundle_lst=bundle_lst, project_lst=project_lst, ID_lst=ID_lst )
def execute(self): status = 201 modhash, key, csr = pki.create_modhash_key_and_csr( self.args.common_name, public_exponent=CFG.key.public_exponent, key_size=CFG.key.key_size, key=self.args.key, csr=self.args.csr, oids=self.cfg.csr.oids, sans=self.args.sans) crt, expiry, authority = self.authority.create_certificate( self.args.organization_name, self.args.common_name, self.args.validity_years, csr, self.args.bug, sans=sorted(list(self.args.sans)), repeat_delta=self.args.repeat_delta, whois_check=self.args.whois_check) bundle = Bundle( self.args.common_name, modhash, key, csr, crt, self.args.bug, sans=sorted(list(self.args.sans)), expiry=expiry, authority=authority) bundle.to_disk() if self.args.destinations: note = 'bug ' + self.args.bug for name, dests in self.args.destinations.items(): bundle = self.destinations[name].install_certificates(note, [bundle], dests)[0] json = self.transform([bundle]) return json, status
def test_pricing_bundle_two_items(): assert price_bundles([Bundle(size=2)]) == Price(15.2)
app.config['SECRET_KEY'] = SECRET_KEY #initialize login manager login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' #initialize Mongo class mongo = Mongo() user_coll = mongo.get_user_coll() #initialize Mongo class bundle = Bundle(mongo) #load current user @login_manager.user_loader def load_user(user_id): user_json = user_coll.find_one({'_id': ObjectId(user_id)}) return User(user_json) #Daily Log page @app.route("/", methods=['GET', 'POST']) @app.route("/log", methods=['GET', 'POST']) @login_required def log():
from celery import VERSION from bundle import Bundle series = "{}.{}".format(*VERSION[:2]) defaults = { "version": series, "author": "Celery Project", "author_email": "*****@*****.**", "url": "http://celeryproject.org", "license": "BSD" } bundles = [ Bundle("celery-with-redis", "Bundle that installs the dependencies for Celery and Redis", requires=["celery>=%s,<3.0" % (series, ), "redis>=2.4.4"], **defaults), ] def main(): for bundle in bundles: bundle.bump_if_exists() print(bundle.render_readme()) if __name__ == "__main__": main()
def test_bundle_optimisation(): optimized_bundles = optimize_bundles([Bundle(size=5), Bundle(size=3)]) assert optimized_bundles == [Bundle(size=4), Bundle(size=4)]
def test_pricing_bundle_one_item(): assert price_bundles([Bundle(size=1)]) == Price(8)
def encode_list(item_list, prefix=''): bnd = Bundle() for i, item in enumerate(item_list): bnd.assimilate(item.to_bundle('%s.%d' % (prefix, i))) return bnd
brushdir = config.ask("Brushes directory", "brushes") brushmask = config.ask("Brush files mask", "*.gbr;*.gih;*.png") patdir = config.ask("Patterns directory", "patterns") patmask = config.ask("Pattern files mask", "*.pat") presetsdir = config.ask("Presets directory", "paintoppresets") presetmask = config.ask("Preset files mask", "*.kpp") skip_bad = config.ask("Skip presets with broken references", default=False, config_option="Skip bad presets") skip_unused_brushes = config.ask("Skip unused brushes", default=False) autopopulate = config.ask("Automatically add resources from directory", default=None, config_option="Auto add resources") if autopopulate is not None: autopopulate = autopopulate.split(";") autopopulate = map(expanduser, autopopulate) autopopulate = sum(map(glob, autopopulate), []) preview = config.ask("Preview", "preview.png") bundle = Bundle() bundle.prepare(brushdir, brushmask, presetsdir, presetmask, patdir, patmask) ok = bundle.check(skip_bad=skip_bad, resourcedir=autopopulate, skip_unused_brushes=skip_unused_brushes) if not ok: print( "Bundle contains references to resources outside the bundle. You probably need to put required resources to the bundle itself." ) bundle.create(zipname, meta, preview)
def test_pricing_bundle_three_items(): assert price_bundles([Bundle(size=3)]) == Price(21.6)