Start a shell sourcing source or using vars as locals
763636
def shell(source=None, vars=None, server=None, port=None):
    """"""
    Wdb.get(server=server, port=port).shell(source=source, vars=vars)
612434
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="DEBUG",
        options_first=False,
        projectName="picaxe"
    )
    arguments, settings, log, dbConn = su.setup()

    startTime = times.get_now_sql_datetime()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/picaxe/picaxe.yaml"
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    if auth:
        from picaxe import picaxe
        client = picaxe(
            log=log,
            settings=settings,
            pathToSettingsFile=pathToSettingsFile
        )
        client.authenticate()

    if md:
        from picaxe import picaxe
        Flickr = picaxe(
            log=log,
            settings=settings
        )
        if not width:
            width = "original"
        mdLink = Flickr.md(
            url=urlOrPhotoid,
            # [75, 100, 150, 240, 320, 500, 640, 800, 1024, 1600, 2048]
            width=width
        )
        print mdLink

    if albums:
        from picaxe import picaxe
        flickr = picaxe(
            log=log,
            settings=settings
        )
        albumList = flickr.list_album_titles()
        for a in albumList:
            print a

    if upload:
        from picaxe import picaxe
        flickr = picaxe(
            log=log,
            settings=settings
        )

        imageType = "photo"
        if screenGrabFlag:
            imageType = "screengrab"
        elif imageFlag:
            imageType = "image"

        album = "inbox"
        if albumFlag:
            album = albumFlag

        photoid = flickr.upload(
            imagePath=imagePath,
            title=titleFlag,
            private=publicFlag,
            tags=tagsFlag,
            description=descFlag,
            imageType=imageType,  # image|screengrab|photo
            album=albumFlag,
            openInBrowser=openFlag
        )
        print photoid

    if grab:

        # for k, v in locals().iteritems():
        #     print k, v
        # return
        try:
            os.remove("/tmp/screengrab.png")
        except:
            pass

        if delayFlag:

            time.sleep(int(delayFlag))

        from subprocess import Popen, PIPE, STDOUT
        cmd = """screencapture -i /tmp/screengrab.png""" % locals()
        p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        stdout, stderr = p.communicate()
        log.debug('output: %(stdout)s' % locals())

        exists = os.path.exists("/tmp/screengrab.png")
        if exists:
            from picaxe import picaxe
            flickr = picaxe(
                log=log,
                settings=settings
            )

            if not albumFlag:
                albumFlag = "screengrabs"

            photoid = flickr.upload(
                imagePath="/tmp/screengrab.png",
                title=titleFlag,
                private=publicFlag,
                tags=tagsFlag,
                description=descFlag,
                imageType="screengrab",  # image|screengrab|photo
                album=albumFlag,
                openInBrowser=openFlag
            )
            mdLink = flickr.md(
                url=photoid,
                # [75, 100, 150, 240, 320, 500, 640, 800, 1024, 1600, 2048]
                width="original"
            )
            print mdLink

    # CALL FUNCTIONS/OBJECTS

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
1231428
function start(object, filename) {
  var port = process.env.PORT || argv.port
  var hostname = argv.host === '0.0.0.0' ? 'localhost' : argv.host

  for (var prop in object) {
    console.log(chalk.gray('  http://' + hostname +  ':' + port + '/') + chalk.cyan(prop))
  }

  console.log(
    '\nYou can now go to ' + chalk.gray('http://' + hostname + ':' + port + '/\n')
  )

  console.log(
    'Enter ' + chalk.cyan('`s`') + ' at any time to create a snapshot of the db\n'
  )

  process.stdin.resume()
  process.stdin.setEncoding('utf8')
  process.stdin.on('data', function (chunk) {
    if (chunk.trim().toLowerCase() === 's') {
      var file = 'db-' + Date.now() + '.json'
      _db.save(object, file)
      console.log('\nSaved snapshot to ' + chalk.cyan(file) + '\n')
    }
  })

  if (filename) {
    var router = jsonServer.router(filename)
  } else {
    var router = jsonServer.router(object)
  }

  var server = jsonServer.create()
  server.use(jsonServer.defaults)
  server.use(router)
  server.listen(port, argv.host)
}
602469
function bin (argv) {
  program.version(pkg.version)
  .usage('[options] <sourceURI> <destURI>')
  .parse(argv)

  var sourceURI = program.args[0]
  var destURI = program.args[1]

  if (!sourceURI || !destURI) {
    program.help()
  }

  shell.mv(sourceURI, destURI, function (err, res, uri) {
    if (!err) {
      debug(res)
    } else {
      console.error(err)
    }
  })
}
398472
function buildSources (path, options) {
  var excludes = options.excludes;
  var sources = [];

  if (options.defaults) {
    sources = options.defaults.concat(sources);
  }

  var environment = getEnvironment(options);

  var basename = nodePath.basename(path);
  var ext = nodePath.extname(basename);

  var pathNoExt = path.slice(0, 0 - ext.length);

  if (!ext) {
    ext = '.json';
  }

  sources.push(pathNoExt + ext);

  if (excludes['env-file'] !== true) {
    sources.push(pathNoExt + '-' + environment + ext);
  }

  if (excludes['local-file'] !== true) {
    sources.push(pathNoExt + '-local' + ext);
  }

  if (excludes['env'] !== true) {
    sources.push(getEnvNodeConfig());
  }

  if (excludes['command-line'] !== true) {
    sources.push(getCommandLineNodeConfig());
  }

  if (options.overrides) {
    sources = sources.concat(options.overrides);
  }

  if (typeof options.sources === 'function') {
    var newSources = options.sources(sources);
    if (newSources != null) {
      sources = newSources;
    }
  }

  return sources;
}
666062
def _init_non_posix(vars):
    """"""
    # set basic install directories
    vars['LIBDEST'] = get_path('stdlib')
    vars['BINLIBDEST'] = get_path('platstdlib')
    vars['INCLUDEPY'] = get_path('include')
    vars['SO'] = '.pyd'
    vars['EXE'] = '.exe'
    vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT
    vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
936165
function iconShellHelper(shellScriptPath, icoSrc, dest) {
  return new Promise((resolve, reject) => {
    if (isWindows()) {
      reject(new Error('OSX or Linux is required'));
      return;
    }

    shell.exec(
      `"${shellScriptPath}" "${icoSrc}" "${dest}"`,
      { silent: true },
      (exitCode, stdOut, stdError) => {
        if (exitCode) {
          // eslint-disable-next-line prefer-promise-reject-errors
          reject({
            stdOut,
            stdError,
          });
          return;
        }

        resolve(dest);
      },
    );
  });
}
94505
def shellinit(cli):
        """"""
        output = 'eval echo "Initializing Waybills"'
        if which('docker') is None:
            raise ValueError("Unable to find program 'docker'.  Please make sure it is installed and setup properly")
        for waybill in cli.get_waybills():
            output += ' && source {0}'.format(waybill)
        return output
231098
def main(arguments=None):
    

    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName=False
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    if os.path.isfile(pathToYaml):
        from fundamentals.mysql import yaml_to_database
        # PARSE YAML FILE CONTENTS AND ADD TO DATABASE
        yaml2db = yaml_to_database(
            log=log,
            settings=settings,
            dbConn=dbConn
        )
        yaml2db.add_yaml_file_content_to_database(
            filepath=pathToYaml,
            deleteFile=deleteFlag
        )
        basename = os.path.basename(pathToYaml)
        print "Content of %(basename)s added to database" % locals()

    else:
        from fundamentals.mysql import yaml_to_database
        yaml2db = yaml_to_database(
            log=log,
            settings=settings,
            dbConn=dbConn,
            pathToInputDir=pathToYaml,
            deleteFiles=deleteFlag
        )
        yaml2db.ingest()
        print "Content of %(pathToYaml)s directory added to database" % locals()

    return
1246868
def main(arguments=None):
    

    # SETUP VARIABLES
    # MAKE SURE HEALPIX SMALL ENOUGH TO MATCH FOOTPRINTS CORRECTLY
    nside = 1024
    pi = (4 * math.atan(1.0))
    DEG_TO_RAD_FACTOR = pi / 180.0
    RAD_TO_DEG_FACTOR = 180.0 / pi
    tileSide = 5.46

    i = 0
    outputList = []
    rsyncContent = []
    obscodes = {"02": "T05", "01": "T08"}

    # SETUP THE COMMAND-LINE UTIL SETTINGS
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName=False
    )
    arguments, settings, log, dbConn = su.setup()

    # UNPACK REMAINING CL ARGUMENTS USING `EXEC` TO SETUP THE VARIABLE NAMES
    # AUTOMATICALLY
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    dbSettings = {
        'host': '127.0.0.1',
        'user': 'dryx',
        'tunnel': {
            'remote ip': 'starbase.mp.qub.ac.uk',
            'remote datbase host': 'dormammu',
            'remote user': 'dry',
            'port': 5003
        },
        'password': 'dryxPass',
        'db': 'atlas_moving_objects'
    }

    # SETUP DATABASE CONNECTIONS
    dbConn = database(
        log=log,
        dbSettings=dbSettings
    ).connect()

    # GRAB THE EXPOSURE LISTING
    for expPrefix, obscode in obscodes.iteritems():
        exposureList = []
        mjds = []
        sqlQuery = "select * from atlas_exposures where expname like '%(expPrefix)s%%'" % locals(
        )
        connected = 0
        while connected == 0:
            try:
                rows = readquery(
                    log=log,
                    sqlQuery=sqlQuery,
                    dbConn=dbConn,
                    quiet=False
                )
                connected = 1
            except:
                # SETUP DATABASE CONNECTIONS
                dbConn = database(
                    log=log,
                    dbSettings=dbSettings
                ).connect()
                print "Can't connect to DB - try again"
                time.sleep(2)

        t = len(rows)

        print "There are %(t)s '%(expPrefix)s' exposures to check - hang tight" % locals()

        for row in rows:
            row["mjd"] = row["mjd"] + row["exp_time"] / (2. * 60 * 60 * 24)
            exposureList.append(row)
            mjds.append(row["mjd"])

        results = []

        batchSize = 500
        total = len(mjds[1:])
        batches = int(total / batchSize)

        start = 0
        end = 0
        theseBatches = []
        for i in range(batches + 1):
            end = end + batchSize
            start = i * batchSize
            thisBatch = mjds[start:end]
            theseBatches.append(thisBatch)

        i = 0
        totalLen = len(theseBatches)
        index = 0
        for batch in theseBatches:
            i += 1

            if index > 1:
                # Cursor up one line and clear line
                sys.stdout.write("\x1b[1A\x1b[2K")
            print "Requesting batch %(i)04d/%(totalLen)s from JPL" % locals()
            index += 1

            eph = jpl_horizons_ephemeris(
                log=log,
                objectId=[ssobject],
                mjd=batch,
                obscode=obscode,
                verbose=False
            )

            for b in batch:
                match = 0
                # print b
                for row in eph:
                    if math.floor(row["mjd"] * 10000 + 0.01) == math.floor(b * 10000 + 0.01):
                        match = 1
                        results.append(row)
                if match == 0:
                    for row in eph:
                        if math.floor(row["mjd"] * 10000) == math.floor(b * 10000):
                            match = 1
                            results.append(row)
                if match == 0:
                    results.append(None)
                    this = math.floor(b * 10000 + 0.01)
                    print "MJD %(b)s (%(this)s) is missing" % locals()
                    for row in eph:
                        print math.floor(row["mjd"] * 10000 + 0.00001)
                    print ""

        print "Finding the exopsures containing the SS object"

        for e, r in zip(exposureList, results):
            # CALCULATE SEPARATION IN ARCSEC
            if not r:
                continue

            calculator = separations(
                log=log,
                ra1=r["ra_deg"],
                dec1=r["dec_deg"],
                ra2=e["raDeg"],
                dec2=e["decDeg"],
            )
            angularSeparation, north, east = calculator.get()
            sep = float(angularSeparation) / 3600.
            if sep < 5.:

                # THE SKY-LOCATION AS A HEALPIXEL ID
                pinpoint = hp.ang2pix(nside, theta=r["ra_deg"], phi=r[
                                      "dec_deg"], lonlat=True)

                decCorners = (e["decDeg"] - tileSide / 2,
                              e["decDeg"] + tileSide / 2)
                corners = []
                for d in decCorners:
                    if d > 90.:
                        d = 180. - d
                    elif d < -90.:
                        d = -180 - d
                    raCorners = (e["raDeg"] - (tileSide / 2) / np.cos(d * DEG_TO_RAD_FACTOR),
                                 e["raDeg"] + (tileSide / 2) / np.cos(d * DEG_TO_RAD_FACTOR))
                    for rc in raCorners:
                        if rc > 360.:
                            rc = 720. - rc
                        elif rc < 0.:
                            rc = 360. + rc
                        corners.append(hp.ang2vec(rc, d, lonlat=True))

                # NEAR THE POLES RETURN SQUARE INTO TRIANGE - ALMOST DEGENERATE
                pole = False
                for d in decCorners:
                    if d > 87.0 or d < -87.0:
                        pole = True

                if pole == True:
                    corners = corners[1:]
                else:
                    # FLIP CORNERS 3 & 4 SO HEALPY UNDERSTANDS POLYGON SHAPE
                    corners = [corners[0], corners[1],
                               corners[3], corners[2]]

                # RETURN HEALPIXELS IN EXPOSURE AREA
                expPixels = hp.query_polygon(nside, np.array(
                    corners))
                if pinpoint in expPixels:
                    outputList.append(
                        {"obs": e["expname"],
                         "mjd": e["mjd"],
                         "raDeg": r["ra_deg"],
                         "decDeg": r["dec_deg"],
                         "mag": r["apparent_mag"],
                         "sep": sep
                         })
                    thisMjd = int(math.floor(e["mjd"]))
                    expname = e["expname"]
                    ssobject_ = ssobject.replace(" ", "_")
                    raStr = r["ra_deg"]
                    decStr = r["dec_deg"]
                    rsyncContent.append(
                        "rsync -av dyoung@atlas-base-adm01.ifa.hawaii.edu:/atlas/red/%(expPrefix)sa/%(thisMjd)s/%(expname)s.fits.fz %(ssobject_)s_atlas_exposures/" % locals())
                    rsyncContent.append(
                        "touch %(ssobject_)s_atlas_exposures/%(expname)s.location" % locals())
                    rsyncContent.append(
                        'echo "_RAJ2000,_DEJ2000,OBJECT\n%(raStr)s,%(decStr)s,%(ssobject)s" > %(ssobject_)s_atlas_exposures/%(expname)s.location' % locals())

    dataSet = list_of_dictionaries(
        log=log,
        listOfDictionaries=outputList,
        # use re.compile('^[0-9]{4}-[0-9]{2}-[0-9]{2}T') for mysql
        reDatetime=False
    )

    ssobject = ssobject.replace(" ", "_")
    csvData = dataSet.csv(
        filepath="./%(ssobject)s_atlas_exposure_matches.csv" % locals())

    rsyncContent = ("\n").join(rsyncContent)
    pathToWriteFile = "./%(ssobject)s_atlas_exposure_rsync.sh" % locals()
    try:
        log.debug("attempting to open the file %s" % (pathToWriteFile,))
        writeFile = codecs.open(pathToWriteFile, encoding='utf-8', mode='w')
    except IOError, e:
        message = 'could not open the file %s' % (pathToWriteFile,)
        log.critical(message)
        raise IOError(message)
    writeFile.write(rsyncContent)
    writeFile.close()

    return
41569
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=True,
        projectName="sloancone",
        tunnel=False
    )
    arguments, settings, log, dbConn = su.setup()

    # tab completion for raw_input
    readline.set_completer_delims(' \t\n;')
    readline.parse_and_bind("tab: complete")
    readline.set_completer(tab_complete)

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    # set options interactively if user requests
    if "interactiveFlag" in locals() and interactiveFlag:

        # load previous settings
        moduleDirectory = os.path.dirname(__file__) + "/resources"
        pathToPickleFile = "%(moduleDirectory)s/previousSettings.p" % locals()
        try:
            with open(pathToPickleFile):
                pass
            previousSettingsExist = True
        except:
            previousSettingsExist = False
        previousSettings = {}
        if previousSettingsExist:
            previousSettings = pickle.load(open(pathToPickleFile, "rb"))

        # x-raw-input
        # x-boolean-raw-input
        # x-raw-input-with-default-value-from-previous-settings

        # save the most recently used requests
        pickleMeObjects = []
        pickleMe = {}
        theseLocals = locals()
        for k in pickleMeObjects:
            pickleMe[k] = theseLocals[k]
        pickle.dump(pickleMe, open(pathToPickleFile, "wb"))

    # CALL FUNCTIONS/OBJECTS

    # call the worker function
    if search:
        cs = cone_search(
            log=log,
            ra=ra,
            dec=dec,
            searchRadius=float(arcsecRadius),
            nearest=nearestFlag,
            outputFormat=outputFormat,
            galaxyType=galaxyType
        )
        results = cs.get()
        print results

    # covered = True | False | 999 (i.e. not sure)
    if covered:
        check = check_coverage(
            log=log,
            ra=ra,
            dec=dec
        ).get()
        print check

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
782666
def source_zsh(args, stdin=None):
    """"""
    args = list(args)
    new_args = ['zsh', '--sourcer=source']
    new_args.extend(args)
    return source_foreign(new_args, stdin=stdin)
55714
def build_vars(path=None):
        """"""
        init_vars = {
            "__name__": "__main__",
            "__package__": None,
            "reload": reload,
        }
        if path is not None:
            init_vars["__file__"] = fixpath(path)
        # put reserved_vars in for auto-completion purposes
        for var in reserved_vars:
            init_vars[var] = None
        return init_vars
738772
def from_env_vars(self) -> None:
        """"""
        for key, value in os.environ.items():
            if key.startswith('KUYRUK_'):
                key = key[7:]
                if hasattr(Config, key):
                    try:
                        value = ast.literal_eval(value)
                    except (ValueError, SyntaxError):
                        pass

                    self._setattr(key, value)
500921
function createLocalEnv(args) {
    var vars = localVars();

    (args || []).forEach(function(val, key) {
        if(val !== undefined) {
            vars.set(parseInt(key, 10) + 1, val);
        }
    });

    return vars;
}
102001
def shell(no_ipython):
    """"""
    banner = "Interactive Werkzeug Shell"
    namespace = make_shell()
    if not no_ipython:
        try:
            try:
                from IPython.frontend.terminal.embed import InteractiveShellEmbed

                sh = InteractiveShellEmbed.instance(banner1=banner)
            except ImportError:
                from IPython.Shell import IPShellEmbed

                sh = IPShellEmbed(banner=banner)
        except ImportError:
            pass
        else:
            sh(local_ns=namespace)
            return
    from code import interact

    interact(banner, local=namespace)
1201081
def source_bash(args, stdin=None):
    """"""
    args = list(args)
    new_args = ['bash', '--sourcer=source']
    new_args.extend(args)
    return source_foreign(new_args, stdin=stdin)