Create georaster from the web service definition file.
550469
def from_wms(cls, filename, vector, resolution, destination_file=None):
        """"""
        doc = wms_vrt(filename,
                      bounds=vector,
                      resolution=resolution).tostring()
        filename = cls._save_to_destination_file(doc, destination_file)
        return GeoRaster2.open(filename)
301850
def make_tool(uri,                # type: Union[Text, CommentedMap, CommentedSeq]
              loadingContext      # type: LoadingContext
             ):  # type: (...) -> Process
    """"""
    if loadingContext.loader is None:
        raise ValueError("loadingContext must have a loader")
    resolveduri, metadata = loadingContext.loader.resolve_ref(uri)

    processobj = None
    if isinstance(resolveduri, MutableSequence):
        for obj in resolveduri:
            if obj['id'].endswith('#main'):
                processobj = obj
                break
        if not processobj:
            raise WorkflowException(
                u"Tool file contains graph of multiple objects, must specify "
                "one of #%s" % ", #".join(
                    urllib.parse.urldefrag(i["id"])[1] for i in resolveduri
                    if "id" in i))
    elif isinstance(resolveduri, MutableMapping):
        processobj = resolveduri
    else:
        raise Exception("Must resolve to list or dict")

    tool = loadingContext.construct_tool_object(processobj, loadingContext)

    if loadingContext.jobdefaults:
        jobobj = loadingContext.jobdefaults
        for inp in tool.tool["inputs"]:
            if shortname(inp["id"]) in jobobj:
                inp["default"] = jobobj[shortname(inp["id"])]

    return tool
730547
def create(self):
        """"""
        # get json content from POST request
        content = request.environ['wsgi.input'].read(int(request.environ['CONTENT_LENGTH']))
        #content = content.decode('utf8')   mapfile interface don't like unicode strings... bad...

        # load mapfile
        mapfile = Mapfile()
        dict = simplejson.loads(content)
        mapfile.from_dict(dict)

        # create mapfile
        mapname = mapfile.get_name()
        map_pathname = h.gen_mapname()
        mapfile.to_file(os.path.join(config['mapfiles_dir'], map_pathname))

        # create map in db
        map = self._new_map_from_user(c.user, mapname, map_pathname)

        response.status = 201

        href = h.url_for(controller="mapfiles", action="show", id=map.id)
        wmsproxyurl = h.url_for(controller='mapfiles', action='wms_proxy', id=map.id)
        wmsurl = "%s?%s" %(config['mapserver_url'], urlencode({'map':os.path.join(config['mapfiles_dir'], map.filepath)}))
        return {'name': map.name, 'id': map.id, 'href': href, 'wmsurl': wmsurl, 'wmsproxyurl': wmsproxyurl}
504217
def from_geojson(cls, filename):
        """"""
        with open(filename) as fd:
            geometry = json.load(fd)

        if 'type' not in geometry:
            raise TypeError("%s is not a valid geojson." % (filename,))

        return cls(to_shape(geometry), WGS84_CRS)
295280
def from_file(cls, jss, filename):
        
        tree = ElementTree.parse(filename)
        root = tree.getroot()
        return cls(jss, root)
866484
def cli(source_f, raster_f, output, verbose):
    
    with fiona.open(source_f, 'r') as source:
        source_driver = source.driver
        source_crs = source.crs
        sink_schema = source.schema.copy()

        source_geom = source.schema['geometry']
        if source_geom == 'Point':
            sink_schema['geometry'] = '3D Point'
        elif source_geom == 'LineString':
            sink_schema['geometry'] = '3D LineString'
        elif source_geom == '3D Point' or source_geom == '3D LineString':
            pass
        else:
            click.BadParameter("Source geometry type {} not implemented".format(source_geom))

        with rasterio.open(raster_f) as raster:
            if source_crs != raster.crs:
                click.BadParameter("Features and raster have different CRS.")
            if raster.count > 1:
                warnings.warn("Found {0} bands in {1}, expected a single band raster".format(raster.bands, raster_f))
            supported = ['int16', 'int32', 'float32', 'float64']
            if raster.dtypes[0] not in supported:
                warnings.warn("Found {0} type in {1}, expected one of {2}".format(raster.dtypes[0]), raster_f, supported)
            with fiona.open(
                output, 'w',
                driver=source_driver,
                crs=source_crs,
                schema=sink_schema) as sink:

                for feature in source:
                    try:
                        feature_z = drapery.drape(raster, feature)
                        sink.write({
                            'geometry': mapping(feature_z),
                            'properties': feature['properties'],
                        })
                    except Exception:
                        logging.exception("Error processing feature %s:", feature['id'])
1242544
def create_from_dict(cls, src_dict, roi_skydir=None, rescale=False):
        
        src_dict = copy.deepcopy(src_dict)
        src_dict.setdefault('SpatialModel', 'PointSource')
        src_dict.setdefault('Spectrum_Filename', None)
        src_dict.setdefault('SpectrumType', 'PowerLaw')
        src_dict['SpatialType'] = get_spatial_type(src_dict['SpatialModel'])

        spectrum_type = src_dict['SpectrumType']
        spatial_type = src_dict['SpatialType']

        spectral_pars = src_dict.pop('spectral_pars', {})
        spatial_pars = src_dict.pop('spatial_pars', {})

        if not spectral_pars:
            spectral_pars = extract_pars_from_dict(spectrum_type, src_dict)
            norm_par_name = get_function_norm_par_name(spectrum_type)
            if norm_par_name is not None:
                spectral_pars[norm_par_name].setdefault('free', True)

        if not spatial_pars:
            spatial_pars = extract_pars_from_dict(spatial_type, src_dict)
            for k in ['RA', 'DEC', 'Prefactor']:
                if k in spatial_pars:
                    del spatial_pars[k]

        spectral_pars = create_pars_from_dict(spectrum_type, spectral_pars,
                                              rescale)
        spatial_pars = create_pars_from_dict(spatial_type, spatial_pars,
                                             False)

        if 'file' in src_dict:
            src_dict['Spectrum_Filename'] = src_dict.pop('file')

        if spectrum_type == 'DMFitFunction' and src_dict['Spectrum_Filename'] is None:
            src_dict['Spectrum_Filename'] = os.path.join('$FERMIPY_DATA_DIR',
                                                         'gammamc_dif.dat')

        src_dict['spectral_pars'] = cast_pars_dict(spectral_pars)
        src_dict['spatial_pars'] = cast_pars_dict(spatial_pars)

        if 'name' in src_dict:
            name = src_dict['name']
            src_dict['Source_Name'] = src_dict.pop('name')
        elif 'Source_Name' in src_dict:
            name = src_dict['Source_Name']
        else:
            raise Exception('Source name undefined.')

        skydir = wcs_utils.get_target_skydir(src_dict, roi_skydir)

        src_dict['RAJ2000'] = skydir.ra.deg
        src_dict['DEJ2000'] = skydir.dec.deg

        radec = np.array([skydir.ra.deg, skydir.dec.deg])

        return cls(name, src_dict, radec=radec)
1153047
def wwln_to_geopandas(file):
    """"""
    tmp = pd.read_csv(file, parse_dates=True, header=None,
                      names=['date', 'time', 'lat', 'lon', 'err', '#sta'])
    list_dts = [gen_datetime(dvals, tvals)
                for dvals, tvals in zip(tmp['date'], tmp['time'])]
    points = [[Point(tmp.lat[row], tmp.lon[row]), dt]
              for row, dt in zip(tmp.index, list_dts)]
    df = gpd.GeoDataFrame(points, columns=['geometry', 'dt'])
    return df
757530
def create_from_source(cls, name, config, **kwargs):
        """"""

        coordsys = kwargs.pop('coordsys', 'CEL')

        roi = cls(config, src_radius=None, src_roiwidth=None,
                  srcname=name, **kwargs)
        src = roi.get_source_by_name(name)

        return cls.create_from_position(src.skydir, config,
                                        coordsys=coordsys, **kwargs)
290107
def CreateGrrUser(self, username=None, user_type=None, password=None):
    """"""

    if not username:
      raise ValueError("Username can't be empty.")

    args = user_management_pb2.ApiCreateGrrUserArgs(username=username)

    if user_type is not None:
      args.user_type = user_type

    if password is not None:
      args.password = password

    data = self._context.SendRequest("CreateGrrUser", args)
    return GrrUser(data=data, context=self._context)
647
def _raster_opener(cls, filename, *args, **kwargs):
        """"""
        with rasterio.Env(**cls.get_gdal_env(filename)):
            try:
                return rasterio.open(filename, *args, **kwargs)
            except (rasterio.errors.RasterioIOError, rasterio._err.CPLE_BaseError) as e:
                raise GeoRaster2IOError(e)
1237731
def to_geojson(self, filename):
        """"""
        with open(filename, 'w') as fd:
            json.dump(self.to_record(WGS84_CRS), fd)
552807
def fromsoap(args):
    
    p = OptionParser(fromsoap.__doc__)
    p.add_option("--type", default="nucleotide_match",
                 help="GFF feature type [default: %default]")
    p.add_option("--source", default="soap",
                help="GFF source qualifier [default: %default]")
    p.set_fixchrnames(orgn="maize")
    p.set_outfile()
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    soapfile, = args
    pad0 = len(str(sum(1 for line in open(soapfile))))

    fw = must_open(opts.outfile, "w")
    fp = must_open(soapfile)
    for idx, line in enumerate(fp):
        if opts.fix_chr_name:
            from jcvi.utils.cbook import fixChromName
            line = fixChromName(line, orgn=opts.fix_chr_name)

        atoms = line.strip().split("\t")
        attributes = "ID=match{0};Name={1}".format(str(idx).zfill(pad0), atoms[0])
        start, end = int(atoms[8]), int(atoms[5]) + int(atoms[8]) - 1
        seqid = atoms[7]

        print("\t".join(str(x) for x in (seqid, opts.source, opts.type, \
            start, end, ".", atoms[6], ".", attributes)), file=fw)
720951
def create(self, *args, **kwargs):
        """"""
        resource = super(JsonServerResource, self).create(*args, **kwargs)

        return ResourceResult(
            body=resource,
            status=get_http_status_code_value(http.client.CREATED),
            location="{}/{}".format(request.url, resource.get_id())
        )
581260
def create_environ(self, req, payload):
        """"""
        ws_req = req.copy()

        del ws_req.controller_info

        ws_req.environ.pop("wsgi.input", None)
        ws_req.body_kwargs = payload.body

        ws_req.environ["REQUEST_METHOD"] = payload.method
        ws_req.method = payload.method

        ws_req.environ["PATH_INFO"] = payload.path
        ws_req.path = payload.path

        ws_req.environ["WS_PAYLOAD"] = payload
        ws_req.environ["WS_ORIGINAL"] = req

        ws_req.payload = payload
        ws_req.parent = req
        return {"WS_REQUEST": ws_req}
1066928
def load(filename, drop=False):
    '''
    
    '''
    if filename.startswith('http'):
        log.info('Downloading GeoZones bundle: %s', filename)
        filename, _ = urlretrieve(filename, tmp.path('geozones.tar.xz'))

    log.info('Extracting GeoZones bundle')
    with contextlib.closing(lzma.LZMAFile(filename)) as xz:
        with tarfile.open(fileobj=xz) as f:
            f.extractall(tmp.root)

    log.info('Loading GeoZones levels')

    if drop:
        log.info('Dropping existing levels')
        GeoLevel.drop_collection()

    log.info('Loading levels.msgpack')
    levels_filepath = tmp.path('levels.msgpack')
    with open(levels_filepath) as fp:
        unpacker = msgpack.Unpacker(fp, encoding=str('utf-8'))
        for i, level in enumerate(unpacker, start=1):
            GeoLevel.objects(id=level['id']).modify(
                upsert=True,
                set__name=level['label'],
                set__parents=[level_ref(p) for p in level['parents']],
                set__admin_level=level.get('admin_level')
            )
    os.remove(levels_filepath)
    log.info('Loaded {total} levels'.format(total=i))

    if drop:
        log.info('Dropping existing spatial zones')
        GeoZone.drop_collection()

    log.info('Loading zones.msgpack')
    zones_filepath = tmp.path('zones.msgpack')
    with open(zones_filepath) as fp:
        unpacker = msgpack.Unpacker(fp, encoding=str('utf-8'))
        unpacker.next()  # Skip headers.
        for i, geozone in enumerate(unpacker):
            params = {
                'slug': slugify.slugify(geozone['name'], separator='-'),
                'level': geozone['level'],
                'code': geozone['code'],
                'name': geozone['name'],
                'keys': geozone.get('keys'),
                'parents': geozone.get('parents', []),
                'ancestors': geozone.get('ancestors', []),
                'successors': geozone.get('successors', []),
                'validity': geozone.get('validity'),
                'population': geozone.get('population'),
                'dbpedia': geozone.get('dbpedia'),
                'flag': geozone.get('flag'),
                'blazon': geozone.get('blazon'),
                'wikipedia': geozone.get('wikipedia'),
                'area': geozone.get('area'),
            }
            if geozone.get('geom') and (
                geozone['geom']['type'] != 'GeometryCollection' or
                    geozone['geom']['geometries']):
                params['geom'] = geozone['geom']
            try:
                GeoZone.objects(id=geozone['_id']).modify(upsert=True, **{
                    'set__{0}'.format(k): v for k, v in params.items()
                })
            except errors.ValidationError as e:
                log.warning('Validation error (%s) for %s with %s',
                            e, geozone['_id'], params)
                continue
    os.remove(zones_filepath)
    log.info('Loaded {total} zones'.format(total=i))

    shutil.rmtree(tmp.path('translations'))
375373
def setup_geoserver(options):
    """"""
    fast = options.get('fast', False)
    download_dir = path('downloaded')
    if not download_dir.exists():
        download_dir.makedirs()

    geoserver_dir = path('geoserver')
    geoserver_bin = path('geoserver_ext/target/geoserver.war')

    if not geoserver_bin.exists():
        geoserver_bin = download_dir / os.path.basename(ROGUE_GEOSERVER_URL)
        grab(ROGUE_GEOSERVER_URL, geoserver_bin, "geoserver binary")

    jetty_runner = download_dir / os.path.basename(JETTY_RUNNER_URL)
    grab(JETTY_RUNNER_URL, jetty_runner, "jetty runner")

    data_dir = download_dir / os.path.basename(DATA_DIR_URL)
    grab(DATA_DIR_URL, data_dir, "data dir")

    if not geoserver_dir.exists():
        geoserver_dir.makedirs()

        webapp_dir = geoserver_dir
        if not webapp_dir:
            webapp_dir.makedirs()

        print 'extracting geoserver'
        z = zipfile.ZipFile(geoserver_bin, "r")
        z.extractall(webapp_dir)

        # Set the geonode auth config to dev port 8000
        sh("perl -pi.back -e 's/localhost/localhost:8000/g;' geoserver/data/security/auth/geonodeAuthProvider/config.xml")