Wrapper of zipline run() method. Use the configuration set so far
        to build up the trading environment
495102
def build(self, identity, modules, strategy=constants.DEFAULT_CONFIG):
        '''
        
        '''
        # TODO Catch a problem here
        self.engine = TradingEngine(identity, modules, strategy)
        self.initial_cash = strategy['manager'].get('cash', None)
850365
def run(self):
        
        self.api = self.context.get("cls")(self.context)
        self.context["inst"].append(self)  # Adapters used by strategies

        def on_ws_connect(*args, **kwargs):
            """Callback on connect hook to set is_connected_ws"""
            self.is_connected_ws = True
            self.api.on_ws_connect(*args, **kwargs)

        # Initialize websocket in a thread with channels
        if hasattr(self.api, "on_ws_connect"):
            self.thread = Process(target=self.api.connect_ws, args=(
                on_ws_connect, [
                    SockChannel(channel, res_type, self._generate_result)
                    for channel, res_type in
                    self
                    .context
                    .get("conf")
                    .get("subscriptions")
                    .items()
                ]))
            self.thread.start()
1274659
def run(self, globs=None):
        
        # Without this, the underneath import clashes with the top-level one
        global scoop

        if globs is None:
            globs = globals()

        # import the user module
        if scoop.MAIN_MODULE:
            globs.update(self.setupEnvironment(self))

        # Start the user program
        from scoop import futures

        def futures_startup():
            """Execute the user code.
            Wraps futures._startup (SCOOP initialisation) over the user module.
            Needs """
            return futures._startup(
                functools.partial(
                    runpy.run_path,
                    scoop.MAIN_MODULE,
                    init_globals=globs,
                    run_name="__main__"
                )
            )

        if self.args.profile:
            import cProfile
            # runctx instead of run is required for local function
            try:
                os.makedirs("profile")
            except:
                pass
            cProfile.runctx(
                "futures_startup()",
                globs,
                locals(),
                "./profile/{0}.prof".format(os.getpid())
            )
        else:
            try:
                futures_startup()
            finally:
                # Must reimport (potentially not there after bootstrap)
                import scoop

                # Ensure a communication queue exists (may happend when a
                # connection wasn't established such as cloud-mode wait).
                if scoop._control.execQueue:
                    scoop._control.execQueue.shutdown()
935496
def run():
    
    logging.basicConfig(level=logging.DEBUG)
    load_config.ConfigLoader().load()
    config.debug = True
    print(repr(config.engine.item(sys.argv[1])))
304668
def run(self, **options):
        """"""
        if not self.is_setup:
            self.setup()

        if self.twisted:
            self.run_with_twisted(**options)
        elif self.gunicorn:
            self.run_with_gunicorn(**options)
        else:
            self.run_with_werkzeug(**options)
135072
def run(self, context):
        """"""
        # Don't do something when running non-interactive.
        if not sys.stdout.isatty():
            return

        with local.cwd(context.in_container):
            from benchbuild.projects.gentoo import gentoo
            gentoo.setup_networking()
            gentoo.configure_portage()

            sed_in_chroot = uchroot.uchroot()["/bin/sed"]
            emerge_in_chroot = uchroot.uchroot()["/usr/bin/emerge"]
            has_pkg = uchroot.uchroot()["/usr/bin/qlist", "-I"]

            run.run(sed_in_chroot["-i", '/CC=/d', "/etc/portage/make.conf"])
            run.run(sed_in_chroot["-i", '/CXX=/d', "/etc/portage/make.conf"])

            want_sync = bool(CFG["container"]["strategy"]["polyjit"]["sync"])
            want_upgrade = bool(
                CFG["container"]["strategy"]["polyjit"]["upgrade"])

            packages = \
                CFG["container"]["strategy"]["polyjit"]["packages"].value
            with local.env(MAKEOPTS="-j{0}".format(int(CFG["jobs"]))):
                if want_sync:
                    LOG.debug("Synchronizing portage.")
                    run.run(emerge_in_chroot["--sync"])
                if want_upgrade:
                    LOG.debug("Upgrading world.")
                    run.run(emerge_in_chroot["--autounmask-only=y", "-uUDN",
                                             "--with-bdeps=y", "@world"])
                for pkg in packages:
                    if has_pkg[pkg["name"]] & TF:
                        continue
                    env = pkg["env"]
                    with local.env(**env):
                        run.run(emerge_in_chroot[pkg["name"]])

            gentoo.setup_benchbuild()

        print("Packing new container image.")
        with local.cwd(context.builddir):
            pack_container(context.in_container, context.out_container)
208381
def run(self):
        """"""
        # Launch the broker(s)
        for hostname, nb_brokers in self.broker_hosts:
            for ind in range(nb_brokers):
                if self.externalHostname in utils.localHostnames:
                    self.brokers.append(localBroker(
                        debug=self.debug,
                        nice=self.nice,
                        backend=self.backend,
                    ))
                else:
                    self.brokers.append(remoteBroker(
                        hostname=hostname,
                        pythonExecutable=self.python_executable,
                        debug=self.debug,
                        nice=self.nice,
                        backend=self.backend,
                        rsh=self.rsh,
                        ssh_executable=self.ssh_executable,
                    ))

        # Share connection information between brokers
        if self.b > 1:
            for broker in self.brokers:
                # Only send data of other brokers to a given broker
                connect_data = [
                    BrokerInfo(
                        x.getHost(),
                        *x.getPorts(),
                        externalHostname=x.getHost()
                    )
                    for x in self.brokers
                    if x is not broker
                ]
                broker.sendConnect(connect_data)

        # Launch the workers
        shells = []
        origin_launched = False
        for hostname, nb_workers in self.worker_hosts:
            self.workers.append(self.LAUNCH_HOST_CLASS(hostname, self.rsh,
                                                       self.ssh_executable))
            total_workers_host = min(nb_workers, self.workersLeft)

            self.setWorkerInfo(hostname, total_workers_host, not origin_launched)
            origin_launched = True
            self.workersLeft -= total_workers_host

            # Launch every workers at the same time
            scoop.logger.debug(
                "{0}: Launching '{1}'".format(
                    hostname,
                    self.workers[-1].getCommand(),
                )
            )
            shells.append(self.workers[-1].launch(
                (self.brokers[0].brokerPort,
                 self.brokers[0].infoPort)
                    if self.tunnel else None,
            ))
            if self.workersLeft <= 0:
                # We've launched every worker we needed, so let's exit the loop
                break
        rootProcess = shells[0][0]

        # Wait for the root program
        try:
            if self.workers[0].isLocal():
                self.errors = self.workers[0].subprocesses[0].wait()
            else:
                self.errors = rootProcess.wait()
        except KeyboardInterrupt:
            pass
        scoop.logger.info('Root process is done.')
        return self.errors
1202592
def run(cls, routes, *args, **kwargs): # pragma: no cover
    

    app = init(cls, routes, *args, **kwargs)

    HOST = os.getenv('HOST', '0.0.0.0')
    PORT = int(os.getenv('PORT', 8000))

    aiohttp.web.run_app(app, port=PORT, host=HOST)
203155
def run_example(example_name, environ):
    
    mod = EXAMPLE_MODULES[example_name]

    register_calendar("YAHOO", get_calendar("NYSE"), force=True)

    return run_algorithm(
        initialize=getattr(mod, 'initialize', None),
        handle_data=getattr(mod, 'handle_data', None),
        before_trading_start=getattr(mod, 'before_trading_start', None),
        analyze=getattr(mod, 'analyze', None),
        bundle='test',
        environ=environ,
        # Provide a default capital base, but allow the test to override.
        **merge({'capital_base': 1e7}, mod._test_args())
    )
506488
public void run() throws Exception {
        if (ranges == null) {
            throw new ModelsIllegalargumentException("No ranges have been defined for the parameter space.", this);
        }

        createSwarm();
        double[] previous = null;
        while( iterationStep <= maxIterations ) {
            updateSwarm();

            if (printStep()) {
                System.out.println(prefix + " - ITER: " + iterationStep + " global best: " + globalBest + " - for positions: "
                        + Arrays.toString(globalBestLocations));
            }

            if (function.hasConverged(globalBest, globalBestLocations, previous)) {
                break;
            }
            previous = globalBestLocations.clone();
        }
    }
166518
def run(self):
        
        with open('src/lsqfit/__init__.py', 'a') as lsfile:
            lsfile.write("\n__version__ = '%s'\n" % LSQFIT_VERSION)
        _build_py.run(self)
680528
def setup(app: Application,
          tracer: Tracer, *,
          skip_routes: Optional[AbstractRoute] = None,
          tracer_key: str = APP_AIOZIPKIN_KEY,
          request_key: str = REQUEST_AIOZIPKIN_KEY) -> Application:
    
    app[tracer_key] = tracer
    m = middleware_maker(skip_routes=skip_routes,
                         tracer_key=tracer_key,
                         request_key=request_key)
    app.middlewares.append(m)

    # register cleanup signal to close zipkin transport connections
    async def close_aiozipkin(app: Application) -> None:
        await app[tracer_key].close()

    app.on_cleanup.append(close_aiozipkin)

    return app
1106356
def handle(self, *args, **options):  # NoQA
        

        # Load the settings
        self.require_settings(args, options)

        # Load your AWS credentials from ~/.aws/credentials
        self.load_credentials()

        #Get the Django settings file
        self.get_django_settings_file()

        # Make sure the necessary IAM execution roles are available
        self.zappa.create_iam_roles()

        # Create the Lambda Zip
        self.create_package()

        # Upload it to S3
        try:
            zip_arn = self.zappa.upload_to_s3(
                self.zip_path, self.s3_bucket_name)
        except (KeyboardInterrupt, SystemExit):
            raise

        # Register the Lambda function with that zip as the source
        # You'll also need to define the path to your lambda_handler code.
        lambda_arn = self.zappa.create_lambda_function(bucket=self.s3_bucket_name,
                                                       s3_key=self.zip_path,
                                                       function_name=self.lambda_name,
                                                       handler='handler.lambda_handler',
                                                       vpc_config=self.vpc_config,
                                                       memory_size=self.memory_size,
                                                       timeout=self.timeout)

        # Create and configure the API Gateway
        api_id = self.zappa.create_api_gateway_routes(
            lambda_arn, self.lambda_name)

        # Deploy the API!
        endpoint_url = self.zappa.deploy_api_gateway(api_id, self.api_stage)

        # Finally, delete the local copy our zip package
        if self.zappa_settings[self.api_stage].get('delete_zip', True):
            os.remove(self.zip_path)

        #Remove the local settings
        self.remove_s3_local_settings()
        # Remove the uploaded zip from S3, because it is now registered..
        self.zappa.remove_from_s3(self.zip_path, self.s3_bucket_name)

        if self.zappa_settings[self.api_stage].get('touch', True):
            requests.get(endpoint_url)

        print("Your Zappa deployment is live!: " + endpoint_url)

        events = self.zappa_settings[self.api_stage].get('events')

        if options['unschedule'] and events:
            self.zappa.unschedule_events(lambda_arn, self.lambda_name, events)
        elif options['unschedule'] and not events:
            print("No Events to Unschedule")

        if options['schedule'] and events:
            self.zappa.schedule_events(lambda_arn, self.lambda_name, events)
        elif options['schedule'] and not events:
            print("No Events to Schedule")
227597
def _run(self, line):
        ''' 

        '''
        line = self._setup('RUN', line)
        self.install += line
969558
def _run(self):
        
        tup = self.read_tuple()
        self._current_tups = [tup]
        if self.is_heartbeat(tup):
            self.send_message({"command": "sync"})
        elif self.is_tick(tup):
            self.process_tick(tup)
            if self.auto_ack:
                self.ack(tup)
        else:
            self.process(tup)
            if self.auto_ack:
                self.ack(tup)
        # Reset _current_tups so that we don't accidentally fail the wrong
        # Tuples if a successive call to read_tuple fails.
        # This is not done in `finally` clause because we want the current
        # Tuples to fail when there is an exception.
        self._current_tups = []
339357
def zipline_magic(line, cell=None):
    
    load_extensions(
        default=True,
        extensions=[],
        strict=True,
        environ=os.environ,
    )
    try:
        return run.main(
            # put our overrides at the start of the parameter list so that
            # users may pass values with higher precedence
            [
                '--algotext', cell,
                '--output', os.devnull,  # don't write the results by default
            ] + ([
                # these options are set when running in line magic mode
                # set a non None algo text to use the ipython user_ns
                '--algotext', '',
                '--local-namespace',
            ] if cell is None else []) + line.split(),
            '%s%%zipline' % ((cell or '') and '%'),
            # don't use system exit and propogate errors to the caller
            standalone_mode=False,
        )
    except SystemExit as e:
        # https://github.com/mitsuhiko/click/pull/533
        # even in standalone_mode=False `--help` really wants to kill us ;_;
        if e.code:
            raise ValueError('main returned non-zero status code: %d' % e.code)
567878
def run_config(self, project, run=None, entity=None):
        
        query = gql('''
        query Model($name: String!, $entity: String!, $run: String!) {
            model(name: $name, entityName: $entity) {
                bucket(name: $run) {
                    config
                    commit
                    patch
                    files(names: ["wandb-metadata.json"]) {
                        edges {
                            node {
                                url
                            }
                        }
                    }
                }
            }
        }
        ''')

        response = self.gql(query, variable_values={
            'name': project, 'run': run, 'entity': entity
        })
        if response['model'] == None:
            raise ValueError("Run {}/{}/{} not found".format(entity, project, run) )
        run = response['model']['bucket']
        commit = run['commit']
        patch = run['patch']
        config = json.loads(run['config'] or '{}')
        if len(run['files']['edges']) > 0:
            url = run['files']['edges'][0]['node']['url']
            res = requests.get(url)
            res.raise_for_status()
            metadata = res.json()
        else:
            metadata = {}
        return (commit, config, patch, metadata)