Manage Morp application services
348531
def cli(ctx, settings, app):
    """"""
    if app is None and settings is None:
        print('Either --app or --settings must be supplied')
    ctx.ensure_object(dict)
    ctx.obj['app'] = app
    ctx.obj['settings'] = settings
990293
def cli(ctx, config, debug):
    """"""
    ctx.obj['config'] = config
    ctx.obj['engine'] = stex.SnakeTeX(config_file=config, debug=debug)
376332
def run():
    

    # List all the possible options, defaults and help
    options = [
        ['resolverlist', 'store',
         'Location of the yaml resolvers list to download (http/https)',
         'https://www.codesam.co.uk/files/dnsyo/list/resolver-list.yml'],
        ['resolverfile', 'store',
         'Location of the local yaml resolvers file',
         '~/.dnsyo-resolvers-list.yaml'],
        ['verbose:v', 'store_true', 'Extended debug info'],
        ['simple:s', 'store_true',
         'Simple output mode (good for UNIX parsing)'],
        ['extended:x', 'store_true',
         'Extended output mode including server addresses'],
        ['threads:t', 'store', 'Number of worker threads to use', 100],
        ['servers:q', 'store',
         'Maximum number of servers to query (or ALL)', 500],
        ['country:c', 'store',
         'Query servers by two letter country code'],
        ['update', 'store_true',
         'Check the list for working servers'],
        ['updateSummary', 'store',
         'Location for the summary status of the update'],
        ['updateDestination', 'store',
         'Destination resolver list for update']
    ]

    # Create an argparse
    p = ArgumentParser(
        usage="%(prog)s [options] domain [type]",
        description="Query lots of DNS servers and colate the results",
        epilog="https://github.com/samarudge/dnsyo"
    )

    # Load the options
    for opt in options:
        # Split them into name and short flag
        if ":" in opt[0]:
            name, flag = opt[0].split(':')
        else:
            name, flag = opt[0], None

        # Set a default
        default = opt[3] if len(opt) > 3 else None

        # Add it to the parser object
        arguments = ['--{0}'.format(name)]
        if flag:
            arguments.append('-{0}'.format(flag))

        p.add_argument(
            *arguments,
            dest=name,
            action=opt[1],
            help=opt[2],
            default=default
        )

    # Add the default positional arguments
    p.add_argument('domain', action="store",
                   help="Domain to query", default=None,
                   nargs="?")
    p.add_argument('type', action="store",
                   help='Record type (A, CNAME, MX, etc.)',
                   default="A", nargs="?")

    opts = p.parse_args()

    # Dirty hack to get around --update not needing domain or record
    if not opts.update and not opts.domain:
        p.error("You must provide a domain!")
        sys.exit(3)

    # Setup logging
    if len(logging.root.handlers) == 0:  # Only if there aren't any loggers
        if opts.verbose:
            # If the verbose option is passed, set debug output
            logging.basicConfig(
                level=logging.DEBUG
            )
        elif opts.simple:
            # If the simple option is passed only output warnings and errors
            logging.basicConfig(
                level=logging.WARNING
            )
        else:
            # Otherwise just info
            logging.basicConfig(
                level=logging.INFO
            )

        logging.debug("Debug logging enabled")

    # Prepare the lookup request
    try:
        lookup = dnsyo(
            listLocation=opts.resolverlist,
            listLocal=opts.resolverfile,
            maxWorkers=opts.threads,
            maxServers=opts.servers,
            country=opts.country
        )
    except AssertionError as e:
        # Some arguments were not valid, show the error and exit
        p.error(e)
        sys.exit(3)

    if opts.update:
        # Do a list update
        if not opts.updateSummary or not opts.updateDestination:
            p.error("Must supply updateSummary and updateDestination!")
            sys.exit(3)

        u = updater.update(lookup, opts.updateSummary, opts.updateDestination)
    else:
        # Do a lookup

        # Update the nameserver list, if needed
        lookup.updateList()

        # Filter the list to only the servers we want
        lookup.prepareList()

        try:
            # Query the servers, display progress if not simple output
            lookup.query(
                domain=opts.domain,
                recordType=opts.type,
                progress=not opts.simple
            )
        except ValueError as e:
            p.error(e)
            sys.exit(3)

        # Output the relevant result format
        if opts.simple:
            lookup.outputSimple()
        else:
            lookup.outputStandard(opts.extended)
675312
def cli(env):
    """"""

    mgr = SoftLayer.ObjectStorageManager(env.client)
    accounts = mgr.list_accounts()
    table = formatting.Table(['id', 'name', 'apiType'])
    table.sortby = 'id'
    api_type = None
    for account in accounts:
        if 'vendorName' in account and account['vendorName'] == 'Swift':
            api_type = 'Swift'
        elif 'Cleversafe' in account['serviceResource']['name']:
            api_type = 'S3'

        table.add_row([
            account['id'],
            account['username'],
            api_type,
        ])

    env.fout(table)
320883
def serve(self, app, conf):
        

        if self.args.reload:
            try:
                self.watch_and_spawn(conf)
            except ImportError:
                print('The `--reload` option requires `watchdog` to be '
                      'installed.')
                print('   $ pip install watchdog')
        else:
            self._serve(app, conf)
1097811
function() {
    return {
      compose: app.composeCore,
      project: app.name,
      opts: {
        services: ['appserver'],
        app: app
      }
    };
  }
1340039
function gulp(opts) {
  opts = opts || {};

  var failOnError = opts['failOnError'] || false;
  var interimFiles = [];
  var failedValidations = [];

  return Through(
    function (file) {
      interimFiles.push(file.path);
      this.queue(file);
    },
    function () {
      var baseFile = opts.packageFile;

      interimFiles.forEach(function (file) {
        opts.packageFile = file;

        var results = validate(opts);

        if (hasErrors(results)) {
          failedValidations.push(file);
          log(results);
        }
      });

      opts.packageFile = baseFile;

      if (failOnError &&  failedValidations.length) {
        this.emit('error', new PluginError('dep-validate', 'Unable to validate dependencies'));
      } else {
        this.emit('end');
      }
    }
  );
}
453489
def handle_services(changeset):
    """"""
    charms = {}
    for service_name, service in sorted(changeset.bundle['services'].items()):
        # Add the addCharm record if one hasn't been added yet.
        if service['charm'] not in charms:
            record_id = 'addCharm-{}'.format(changeset.next_action())
            changeset.send({
                'id': record_id,
                'method': 'addCharm',
                'args': [service['charm']],
                'requires': [],
            })
            charms[service['charm']] = record_id

        # Add the deploy record for this service.
        record_id = 'deploy-{}'.format(changeset.next_action())
        changeset.send({
            'id': record_id,
            'method': 'deploy',
            'args': [
                '${}'.format(charms[service['charm']]),
                service_name,
                service.get('options', {}),
                service.get('constraints', ''),
                service.get('storage', {}),
            ],
            'requires': [charms[service['charm']]],
        })
        changeset.services_added[service_name] = record_id

        # Expose this service if required.
        if service.get('expose'):
            changeset.send({
                'id': 'expose-{}'.format(changeset.next_action()),
                'method': 'expose',
                'args': ['${}'.format(record_id)],
                'requires': [record_id],
            })

        # Set the annotations for this service.
        if 'annotations' in service:
            changeset.send({
                'id': 'setAnnotations-{}'.format(changeset.next_action()),
                'method': 'setAnnotations',
                'args': [
                    '${}'.format(record_id),
                    'service',
                    service['annotations'],
                ],
                'requires': [record_id],
            })

    return handle_machines
1247527
def prepare_infrastructure():
    """"""
    runner = ForemastRunner()

    runner.write_configs()
    runner.create_app()

    archaius = runner.configs[runner.env]['app']['archaius_enabled']
    eureka = runner.configs[runner.env]['app']['eureka_enabled']
    deploy_type = runner.configs['pipeline']['type']

    if deploy_type not in ['s3', 'datapipeline']:
        runner.create_iam()
        # TODO: Refactor Archaius to be fully featured
        if archaius:
            runner.create_archaius()
        runner.create_secgroups()

    if eureka:
        LOG.info("Eureka Enabled, skipping ELB and DNS setup")
    elif deploy_type == "lambda":
        LOG.info("Lambda Enabled, skipping ELB and DNS setup")
        runner.create_awslambda()
    elif deploy_type == "s3":
        runner.create_s3app()
    elif deploy_type == 'datapipeline':
        runner.create_datapipeline()
    else:
        LOG.info("No Eureka, running ELB and DNS setup")
        runner.create_elb()
        runner.create_dns()

    runner.slack_notify()
    runner.cleanup()
1131940
function (glob, opts) {
    if (opts.ignore) {
      this.map('exclude', opts.ignore, opts);
    }
    if (opts.exclude) {
      this.map('exclude', opts.exclude, opts);
    }
    if (opts.include) {
      this.map('include', opts.include, opts);
    }

    // if not disabled by the user, run the built-ins
    if (!this.disabled('builtins')) {
      if (!this.disabled('npm')) {
        this.use(npm(opts));
      }
      if (!this.disabled('dotfiles')) {
        this.use(dotfiles()(opts));
      }
      if (!this.disabled('gitignore')) {
        this.use(gitignore()(opts));
      }
    }
  }
945949
function setupSystemD (name, options, callback) {
  options.stdOut = (options.logDir && `${options.logDir}/${name}-out.log`) || null
  options.stdErr = (options.logDir && `${options.logDir}/${name}-err.log`) || null

  const filepath = `/etc/systemd/system/${name}.service`

  const script = systemdTemplate(options)

  if (options.dryRun) {
    console.log(script)
    return
  }

  console.log(`Installing service on: ${filepath}`)
  fs.exists(filepath, exists => {
    if(!exists) {
      fs.writeFile(filepath,script, err => {
        if (err) {
          callback(err)
          return
        }

        fs.chmod(filepath,'755', err => {
          if (err) {
            callback(err)
            return
          }

          let cmd = 'systemctl daemon-reload'
          console.log('Running %s...', cmd)
          exec(cmd, err => {
            callback(err, 'SystemD service registered succesfully')
          })
        })
      })
    } else {
      callback('Service already exists, please uninstall first')
    }
  })
}
521902
def cli(ctx, project_dir):
    """"""

    exit_code = SCons(project_dir).sim()
    ctx.exit(exit_code)
370249
function(required, done) {
        if (arguments.length < 1 || required) {
          grunt.log.writeln('\nnpm install...');
          // Run npm install in project's directory
          grunt.util.spawn({cmd: 'npm', args: ['install'],
                            opts: {cwd: init.destpath, stdio: 'inherit'}},
              function(error, result, code) {
                if (done) {
                  done();
                }
              });
        } else if (done) {
          done();
        }
      }
592879
def managepy(cmd, extra=None):
    """"""

    extra = extra.split() if extra else []
    run_django_cli(['invoke', cmd] + extra)
1094645
def cli(obj, expired=None, info=None):
    """"""
    client = obj['client']
    client.housekeeping(expired_delete_hours=expired, info_delete_hours=info)
1086771
def setup_app(command, conf, vars):
    """"""
    load_environment(conf.global_conf, conf.local_conf)

    # Merge and minify JavaScript code
    input_file = config['js_tmpl']
    public_dir = config['pylons.paths']['static_files']
    output_file = os.path.join(public_dir, 'js', 'Studio', 'studio-all.js')
    _merge_js(input_file, public_dir, output_file)
    log.info('JavaScript successfully merged and minified in ' + output_file)

    # Load the models
    from studio.model import meta
    meta.metadata.bind = meta.engine

    filename = os.path.split(conf.filename)[-1]
    if filename == 'test.ini':
        # Permanently drop any existing tables
        log.info("Dropping existing tables...")
        meta.metadata.drop_all(checkfirst=True)

    # Create the tables if they aren't there already
    meta.metadata.create_all(checkfirst=True)

    # Create permissions
    # datastores permissions
    perm_create_update_datastores = model.Permission()
    perm_create_update_datastores.name = 'create_update_datastores'
    meta.Session.add(perm_create_update_datastores)
    perm_view_datastores = model.Permission()
    perm_view_datastores.name = 'view_datastores'
    meta.Session.add(perm_view_datastores)
    # datasources permissions
    perm_view_datasources = model.Permission()
    perm_view_datasources.name = 'view_datasources'
    meta.Session.add(perm_view_datasources)
    perm_create_datasources = model.Permission()
    perm_create_datasources.name = 'create_datasources'
    meta.Session.add(perm_create_datasources)
    # mapfiles permissions
    perm_create_update_mapfiles = model.Permission()
    perm_create_update_mapfiles.name = 'create_update_mapfiles'
    meta.Session.add(perm_create_update_mapfiles)
    perm_view_mapfiles = model.Permission()
    perm_view_mapfiles.name = 'view_mapfiles'
    meta.Session.add(perm_view_mapfiles)
    # layertemplates permissions
    perm_create_update_layertemplates = model.Permission()
    perm_create_update_layertemplates.name = 'create_update_layertemplates'
    meta.Session.add(perm_create_update_layertemplates)
    perm_view_layertemplates = model.Permission()
    perm_view_layertemplates.name = 'view_layertemplates'
    meta.Session.add(perm_view_layertemplates)

    # Create group admin
    admin_gp = model.Group()
    admin_gp.name = 'admin'
    admin_gp.permissions.append(perm_create_update_datastores)
    admin_gp.permissions.append(perm_view_datastores)
    admin_gp.permissions.append(perm_view_datasources)
    admin_gp.permissions.append(perm_create_datasources)
    admin_gp.permissions.append(perm_create_update_mapfiles)
    admin_gp.permissions.append(perm_view_mapfiles)
    admin_gp.permissions.append(perm_create_update_layertemplates)
    admin_gp.permissions.append(perm_view_layertemplates)
    meta.Session.add(admin_gp)

    # Create group enduser
    enduser_gp = model.Group()
    enduser_gp.name = 'enduser'
    enduser_gp.permissions.append(perm_view_datastores)
    enduser_gp.permissions.append(perm_view_datasources)
    enduser_gp.permissions.append(perm_create_update_mapfiles)
    enduser_gp.permissions.append(perm_view_mapfiles)
    enduser_gp.permissions.append(perm_create_update_layertemplates)
    enduser_gp.permissions.append(perm_view_layertemplates)
    meta.Session.add(enduser_gp)

    # Create user admin
    admin = model.User()
    admin.name = 'Admin'
    admin.login = 'admin'
    admin.password = config['admin_password']
    admin.groups.append(admin_gp)
    meta.Session.add(admin)

    if filename == 'test.ini':
        # create enduser user for test purpose only
        enduser = model.User()
        enduser.name = 'Test User'
        enduser.login = 'enduser'
        enduser.password = 'password'
        enduser.groups.append(enduser_gp)
        meta.Session.add(enduser)

    mfdir = config['mapfiles_dir']
    if not os.path.exists(mfdir):
        os.makedirs(mfdir, 0755)

    if 'default_datastore_postgis' in config:
        # Create default datastore
        datastore = model.DataStore('default (postgis)', 'postgis', config['default_datastore_postgis'])
        meta.Session.add(datastore)
        meta.Session.flush()

    if 'default_datastore_dir' in config:
        # Create default datastore
        datastore = model.DataStore('default (directory)', 'directory', config['default_datastore_dir'])
        meta.Session.add(datastore)
        meta.Session.flush()

        # Create dummy mapfile
        mapfile = create_default_mapfile()
        dict = mapfile.to_dict()
        ds = DataStore(datastore.ogrstring)
        dsources = ds.get_datasources()
        palette = QualitativePalette(len(dsources)).get_palette()
        for dss in dsources:
            if dss.type == 'RASTER':
                print "adding %s datasource"%dss.name
                l = _make_mapfile_layer(datastore.id,dss)
                if 'projection' in l:
                    dict['projection'] = l['projection']
                dict['layers'].append(l)
        for dss in dsources:
            if dss.type == 'POLYGON':
                print "adding %s datasource"%dss.name
                color = palette.pop(0)
                l = _make_mapfile_layer(datastore.id,dss)
                if 'projection' in l:
                    dict['projection'] = l['projection']
                l['classes'][0]['styles'][0]['color']=color
                dict['layers'].append(l)
        for dss in dsources:
            if dss.type == 'LINE':
                print "adding %s datasource"%dss.name
                color = palette.pop(0)
                l = _make_mapfile_layer(datastore.id,dss)
                if 'projection' in l:
                    dict['projection'] = l['projection']
                l['classes'][0]['styles'][0]['color']=color
                dict['layers'].append(l)
        for dss in dsources:
            if dss.type == 'POINT':
                print "adding %s datasource"%dss.name
                color = palette.pop(0)
                l = _make_mapfile_layer(datastore.id,dss)
                if 'projection' in l:
                    dict['projection'] = l['projection']
                l['classes'][0]['styles'][0]['color']=color
                dict['layers'].append(l)
        if 'projection' not in dict:
            dict['projection']="init=epsg:4326"
        mapfile.from_dict(dict)
        mapfile.to_file(os.path.join(config['mapfiles_dir'], 'dummy_mapfile.map'))

        # Create dummy_mapfile in db, owned by user 'admin'
        map = model.Map('dummy_mapfile', 'dummy_mapfile.map', 1)
        model.meta.Session.add(map)

    # Commit the new objects into the database
    meta.Session.commit()

    log.info("Data successfully set up")
825929
function Management(options) {
  /* eslint-disable */
  assert.check(
    options,
    { type: 'object', message: 'options parameter is not valid' },
    {
      domain: { type: 'string', message: 'domain option is required' },
      token: { type: 'string', message: 'token option is required' },
      _sendTelemetry: {
        optional: true,
        type: 'boolean',
        message: '_sendTelemetry option is not valid'
      },
      _telemetryInfo: {
        optional: true,
        type: 'object',
        message: '_telemetryInfo option is not valid'
      }
    }
  );
  /* eslint-enable */

  this.baseOptions = options;

  this.baseOptions.headers = { Authorization: 'Bearer ' + this.baseOptions.token };

  this.request = new RequestBuilder(this.baseOptions);
  this.baseOptions.rootUrl = urljoin('https://' + this.baseOptions.domain, 'api', 'v2');
}