Parse web server camera view for camera image names
161294
async def async_get_image_names(self):
        

        cookies = self.get_session_cookie()
        try:
            async with aiohttp.ClientSession(cookies=cookies) as session:
                resp = await session.get(
                    self._base_url
                )
                t = await resp.text()
                match = re.findall('(?:\w|\d|")/(.*?).(?:mjpg|jpg)', t)
                if len(match) == 0:
                    raise XeomaError('Unable to find any camera image names')
                image_names = set(match)
                results = []
                for image_name in image_names:
                    match = re.search(
                        image_name + '\.(?:mjpg|jpg).*?user=(.*?)&', t
                    )
                    if match and len(match.group(1)) > 0:
                        d = base64.b64decode(unquote(match.group(1))) \
                            .decode('ASCII')
                        creds = d.split(':')
                        if len(creds) < 2:
                            raise XeomaError('Error parsing image credentials')
                        results.append((image_name, creds[0], creds[1]))
                    else:
                        results.append((image_name, None, None))
                return results
        except asyncio.TimeoutError as e:
            raise XeomaError("Unable to connect to Xeoma web server")
1032940
def getCameraParams(self):
        '''
        
        '''
        c = self.coeffs['cameraMatrix']
        fx = c[0][0]
        fy = c[1][1]
        cx = c[0][2]
        cy = c[1][2]
        k1, k2, p1, p2, k3 = tuple(self.coeffs['distortionCoeffs'].tolist()[0])
        return fx, fy, cx, cy, k1, k2, k3, p1, p2
1296003
def namer(cls, imageUrl, pageUrl):
        """"""
        imgname = imageUrl.split('/')[-1]
        imgbase = imgname.rsplit('-', 1)[0]
        imgext = imgname.rsplit('.', 1)[1]
        return '%s.%s' % (imgbase, imgext)
730974
def lookup_camera_by_id(self, device_id):
        """"""
        camera = list(filter(
            lambda cam: cam.device_id == device_id, self.cameras))[0]
        if camera:
            return camera
        return None
438416
def get_camera_extended_properties(self):
        """"""
        resource = 'cameras/{}'.format(self.device_id)
        resource_event = self.publish_and_get_event(resource)

        if resource_event is None:
            return None

        self._camera_extended_properties = resource_event.get('properties')
        return self._camera_extended_properties
1166112
def _get_filename(request, item):
        
        if request.keep_image_names:
            filename = OgcImageService.finalize_filename(item['niceName'].replace(' ', '_'))
        else:
            filename = OgcImageService.finalize_filename(
                '_'.join([str(GeopediaService._parse_layer(request.layer)), item['objectPath'].rsplit('/', 1)[-1]]),
                request.image_format
            )

        LOGGER.debug("filename=%s", filename)
        return filename
94099
def user_parse(data):
        """"""
        user_ = data.get('user')
        yield 'id', user_.get('username')
        yield 'username', user_.get('username')
        yield 'first_name', user_.get('first_name')
        yield 'last_name', user_.get('last_name')
        yield 'picture', user_.get('avatar')
        yield 'link', user_.get('resource_url')
184435
def get_default_cam_pos(self):
        
        focal_pt = self.center
        return [np.array(rcParams['camera']['position']) + np.array(focal_pt),
                focal_pt, rcParams['camera']['viewup']]
590694
def _extract_image_urls(arg: Message_T) -> List[str]:
    """"""
    arg_as_msg = Message(arg)
    return [s.data['url'] for s in arg_as_msg
            if s.type == 'image' and 'url' in s.data]
194021
def image_query_record(self, imagename=None):
        """"""

        if imagename:
            with get_image_conn() as conn:
                result = conn.execute("SELECT * FROM image WHERE "
                                      "imagename=?", (imagename,))
                image_list = result.fetchall()
            if not image_list:
                obj_desc = "Image with name: %s" % imagename
                raise exception.SDKObjectNotExistError(obj_desc=obj_desc,
                                                   modID=self._module_id)
        else:
            with get_image_conn() as conn:
                result = conn.execute("SELECT * FROM image")
                image_list = result.fetchall()

        # Map each image record to be a dict, with the key is the field name in
        # image DB
        image_keys_list = ['imagename', 'imageosdistro', 'md5sum',
                      'disk_size_units', 'image_size_in_bytes', 'type',
                      'comments']

        image_result = []
        for item in image_list:
            image_item = dict(zip(image_keys_list, item))
            image_result.append(image_item)
        return image_result
442053
def parse(self, ssos_result_filename_or_lines, mpc_observations=None):
        
        table_reader = ascii.get_reader(Reader=ascii.Basic)
        table_reader.inconsistent_handler = self._skip_missing_data
        table_reader.header.splitter.delimiter = '\t'
        table_reader.data.splitter.delimiter = '\t'
        ssos_table = table_reader.read(ssos_result_filename_or_lines)

        dbimage_list = storage.list_dbimages(dbimages=storage.DBIMAGES)
        logger.debug("Comparing to {} observations in dbimages: {}".format(len(dbimage_list), storage.DBIMAGES))
        sources = []
        observations = []
        source_readings = []

        if mpc_observations is not None and isinstance(mpc_observations[0], mpc.Observation):
            orbit = Orbfit(mpc_observations)
        else:
            from mp_ephem import horizons
            start_time = Time(min(ssos_table['MJD']), format='mjd')
            stop_time = Time(max(ssos_table['MJD']), format='mjd')
            step_size = 5.0 * units.hour
            orbit = horizons.Body(self.provisional_name, start_time, stop_time, step_size)

        warnings.filterwarnings('ignore')
        logger.info("Loading {} observations\n".format(len(ssos_table)))
        expnums_examined = []
        for row in ssos_table:
            # Trim down to OSSOS-specific images

            logger.debug("Checking row: {}".format(row))
            if (row['Filter'] not in parameters.OSSOS_FILTERS) or row['Image_target'].startswith('WP'):
                logger.debug("Failed filter / target name check")
                continue

            # check if a dbimages object exists
            # For CFHT/MegaCam strip off the trailing character to get the exposure number.
            ftype = row['Image'][-1]
            expnum = row['Image'][:-1]
            if str(expnum) not in dbimage_list:
                logger.debug("Expnum: {} Failed dbimage list check".format(expnum))
                continue
            logger.debug("Expnum: {} Passed dbimage list check".format(expnum))
            # The file extension is the ccd number + 1 , or the first extension.
            ccd = int(row['Ext'])-1
            if 39 < ccd < 0 or ccd < 0:
                ccd = None
            x = row['X'] * units.pix
            y = row['Y'] * units.pix
            ra = row['Object_RA'] * units.degree
            dec = row['Object_Dec'] * units.degree
            ssois_coordinate = SkyCoord(ra, dec)
            mjd = row['MJD'] * units.day

            # if not 0 < x.value < 2060 or not 0 < y.value < 4700:
            #    continue

            obs_date = Time(mjd, format='mjd', scale='utc')
            logger.info("Calling predict")
            orbit.predict(obs_date)
            logger.info("Done calling predict")
            if orbit.dra > 4 * units.arcminute or orbit.ddec > 4.0 * units.arcminute:
                print "Skipping entry as orbit uncertainty at date {} is large.".format(obs_date)
                continue
            if expnum in expnums_examined:
                logger.debug("Already checked this exposure.")
                continue
            expnums_examined.append(expnum)

            logger.debug(("SSOIS Prediction: exposure:{} ext:{} "
                          "ra:{} dec:{} x:{} y:{}").format(expnum, ccd, ra, dec, x, y))

            logger.debug(("Orbfit Prediction: "
                          "ra:{} dec:{} ").format(orbit.coordinate.ra.to(units.degree),
                                                  orbit.coordinate.dec.to(units.degree)))
            logger.info("Building Observation")
            observation = SSOSParser.build_source_reading(expnum, ccd, ftype=ftype)
            observation.mjd = mjd
            from_input_file = observation.rawname in self.input_rawnames
            # compare to input observation list.
            previous = False
            mpc_observation = None
            if from_input_file:
                for mpc_observation in mpc_observations:
                    try:
                        if mpc_observation.comment.frame.strip() == observation.rawname:
                            # only skip previous obseravtions if not discovery.
                            previous = not mpc_observation.discovery
                            break
                    except Exception as e:
                        logger.debug(str(e))
                        pass
                    mpc_observation = None

            # skip previously measured observations if requested.
            if self.skip_previous and ( previous or observation.rawname in self.null_observations):
                continue

            logger.info('built observation {}'.format(observation))
            observations.append(observation)
            null_observation = observation.rawname in self.null_observations

            ddec = orbit.ddec + abs(orbit.coordinate.dec - ssois_coordinate.dec)
            dra = orbit.dra + abs(orbit.coordinate.ra - ssois_coordinate.ra)

            logger.info(" Building SourceReading .... \n")
            source_reading = astrom.SourceReading(x=x, y=y, x0=x, y0=y,
                                                  ra=orbit.coordinate.ra.to(units.degree).value,
                                                  dec=orbit.coordinate.dec.to(units.degree).value,
                                                  xref=x, yref=y, obs=observation,
                                                  ssos=True, from_input_file=from_input_file,
                                                  dx=dra, dy=ddec, pa=orbit.pa,
                                                  null_observation=null_observation)
            source_reading.mpc_observation = mpc_observation
            source_readings.append(source_reading)
            logger.info("Source Reading Built")

        # build our array of SourceReading objects
        sources.append(source_readings)

        warnings.filterwarnings('once')

        return SSOSData(observations, sources, self.provisional_name)
1353113
private void parseImagesAndInternalLinks(SpanManager sm,
			List<Span> linkSpans, List<Link> links)
	{

		sm.manageList(linkSpans);

		int pos = -1;
		Stack<Integer> linkOpenTags = new Stack<Integer>();
		while ((pos = sm.indexOf("[[", pos + 1)) != -1)
		{
			linkOpenTags.push(pos);
		}

		Span lastLinkSpan = new Span(sm.length() + 1, sm.length() + 1);
		Link.type linkType = Link.type.INTERNAL;

		while (!linkOpenTags.empty())
		{
			int linkStartTag = linkOpenTags.pop();
			int linkEndTag = sm.indexOf("]]", linkStartTag);
			if (linkEndTag == -1)
			{
				continue;
			}

			int linkOptionTag = sm.indexOf("|", linkStartTag, linkEndTag);

			int linkTextStart;
			String linkTarget;

			if (linkOptionTag != -1)
			{
				linkTextStart = linkOptionTag + 1;
				linkTarget = sm.substring(new Span(linkStartTag + 2,
						linkOptionTag).trim(sm));
			}
			else
			{
				linkTextStart = linkStartTag + 2;
				linkTarget = sm
						.substring(new Span(linkStartTag + 2, linkEndTag)
								.trim(sm));
			}

			// is is a regular link ?
			if (linkTarget.indexOf(lineSeparator) != -1)
			{
				continue;
			}
			linkTarget = encodeWikistyle(linkTarget);

			// so it is a Link or image!!!
			List<String> parameters;

			String namespace = getLinkNameSpace(linkTarget);
			if (namespace != null)
			{
				if (imageIdentifers.indexOf(namespace) != -1)
				{
					if (linkOptionTag != -1)
					{
						int temp;
						while ((temp = sm.indexOf("|", linkTextStart,
								linkEndTag)) != -1)
						{
							linkTextStart = temp + 1;
						}

						parameters = tokenize(sm, linkOptionTag + 1,
								linkEndTag, "|");

						// maybe there is an external link at the end of the
						// image description...
						if (sm.charAt(linkEndTag + 2) == ']'
								&& sm.indexOf("[", linkTextStart, linkEndTag) != -1)
						{
							linkEndTag++;
						}
					}
					else
					{
						parameters = null;
					}
					linkType = Link.type.IMAGE;
				}
				else
				{
					//Link has namespace but is not image
					linkType = Link.type.UNKNOWN;
					parameters = null;
				}
			}
			else
			{
				if (linkType == Link.type.INTERNAL
						&& lastLinkSpan.hits(new Span(linkStartTag,
								linkEndTag + 2)))
				{
					continue;
				}
				parameters = null;
				linkType = Link.type.INTERNAL;
			}

			Span posSpan = new Span(linkTextStart, linkEndTag).trim(sm);
			linkSpans.add(posSpan);

			Link l = new Link(null, posSpan, linkTarget, linkType, parameters);
			links.add(l);

			if (calculateSrcSpans)
			{
				l.setSrcSpan(new SrcSpan(sm.getSrcPos(linkStartTag), sm
						.getSrcPos(linkEndTag + 2)));
			}

			sm.delete(posSpan.getEnd(), linkEndTag + 2);
			sm.delete(linkStartTag, posSpan.getStart());

			// removing line separators in link text
			int lsinlink;
			while ((lsinlink = sm.indexOf(lineSeparator, posSpan)) != -1)
			{
				sm.replace(lsinlink, lsinlink + lineSeparator.length(), " ");
			}

			lastLinkSpan = posSpan;
		}
	}
291747
function handleImageData(handler, xref, res, image) {
    if (image instanceof JpegStream && image.isNativelyDecodable(xref, res)) {
      // For natively supported jpegs send them to the main thread for decoding.
      var dict = image.dict;
      var colorSpace = dict.get('ColorSpace', 'CS');
      colorSpace = ColorSpace.parse(colorSpace, xref, res);
      var numComps = colorSpace.numComps;
      var decodePromise = handler.sendWithPromise('JpegDecode',
                                                  [image.getIR(), numComps]);
      return decodePromise.then(function (message) {
        var data = message.data;
        return new Stream(data, 0, data.length, image.dict);
      });
    } else {
      return Promise.resolve(image);
    }
  }
877131
def view_for_image_named(image_name):
    """"""

    image = resource.get_image(image_name)

    if not image:
        return None

    return ImageView(pygame.Rect(0, 0, 0, 0), image)
112843
def imgaccount
      params = {
        :method => WebPurify::Constants.methods[:imgaccount]
      }
      parsed = WebPurify::Request.query(image_request_base, @query_base, params)
      return parsed[:remaining].to_i
    end
35462
function(data){
        var _retinaObject;
        var _data = [];
        var _retinaImageList = [];
        var _retinaSliceList =[];
        var _regex = new RegExp('background-image:[\\s]*url\\(["\']?(?!http[s]?|/)[^;]*?(slice[\\w\\d\\s!./\\-\\_@]*\\.[\\w?#]+)["\']?\\)[^;}]*;?', 'ig');
        var _rregex = new RegExp('.*(slice\\/[\\w\\d\\s!./\\-\\_@]*)\\.([\\w?#]+)["\']?\\)[^;}]*;?', 'ig');
        RegExp.escape = function (s) {
            return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
        };
        _data = data.match(_regex);
        if(_data !== null){
            for(var i=0;i<_data.length;i++){
                var _slice = _data[i];
                var _retinaSlice = _slice.replace(_rregex,"$1")+"@2x."+_slice.replace(_rregex,"$2");
                var _retinaSlicePath = _rootPath +"/"+_retinaSlice;
                if(fileExists(_retinaSlicePath)){
                    var _regexClassNameString = '(\\.?[^}]*?)\\s?{\\s?[^}]*?' + RegExp.escape(_slice);
                    var _regexClassName = new RegExp(_regexClassNameString, 'ig');
                    var _classNameResult = data.match(_regexClassName);
                    var _className = _classNameResult[0].replace(_regexClassName, '$1');
                    var _retinaItem = new Object();
                    _retinaImageList.push(_retinaSlicePath);
                    _retinaItem.className = _className;
                    _retinaSliceList[_retinaSlicePath] = _retinaItem;
                }
            }
        }
        _retinaObject = {
            slice:_retinaImageList,
            slicekey:_retinaSliceList
        }
        return _retinaObject;
    }
133751
def doorient(self):
        
        assert self.cal1Dfn.is_file(
        ), 'please specify filename for each camera under [cam]/cal1Dname: in .ini file  {}'.format(self.cal1Dfn)

        with h5py.File(self.cal1Dfn, 'r') as f:
            az = f['az'][()]
            el = f['el'][()]
            ra = f['ra'][()]
            dec = f['dec'][()]

        assert az.ndim == el.ndim == 2
        assert az.shape == el.shape

        if self.transpose:
            logging.debug(
                'tranposing cam #{} az/el/ra/dec data. '.format(self.name))
            az = az.T
            el = el.T
            ra = ra.T
            dec = dec.T
        if self.fliplr:
            logging.debug(
                'flipping horizontally cam #{} az/el/ra/dec data.'.format(self.name))
            az = np.fliplr(az)
            el = np.fliplr(el)
            ra = np.fliplr(ra)
            dec = np.fliplr(dec)
        if self.flipud:
            logging.debug(
                'flipping vertically cam #{} az/el/ra/dec data.'.format(self.name))
            az = np.flipud(az)
            el = np.flipud(el)
            ra = np.flipud(ra)
            dec = np.flipud(dec)
        if self.rotccw != 0:
            logging.debug(
                'rotating cam #{} az/el/ra/dec data.'.format(self.name))
            az = np.rot90(az, self.rotccw)
            el = np.rot90(el, self.rotccw)
            ra = np.rot90(ra, self.rotccw)
            dec = np.rot90(dec, self.rotccw)

        self.az = az
        self.el = el
        self.ra = ra
        self.dec = dec