Observing mode processing mode of numina.
767654
def mode_run_common_obs(args, extra_args):
    """"""

    # Loading observation result if exists
    loaded_obs = []
    sessions = []
    if args.session:
        for obfile in args.obsresult:
            _logger.info("session file from %r", obfile)

            with open(obfile) as fd:
                sess = yaml.load(fd)
                sessions.append(sess['session'])
    else:
        for obfile in args.obsresult:
            _logger.info("Loading observation results from %r", obfile)

            with open(obfile) as fd:
                sess = []
                for doc in yaml.load_all(fd):
                    enabled = doc.get('enabled', True)
                    docid = doc['id']
                    requirements = doc.get('requirements', {})
                    sess.append(dict(id=docid, enabled=enabled,
                                               requirements=requirements))
                    if enabled:
                        _logger.debug("load observation result with id %s", docid)
                    else:
                        _logger.debug("skip observation result with id %s", docid)
                
                    loaded_obs.append(doc)

            sessions.append(sess)
    if args.reqs:
        _logger.info('reading control from %s', args.reqs)
        with open(args.reqs, 'r') as fd:
            loaded_data = yaml.load(fd)
    else:
        _logger.info('no control file')
        loaded_data = {}

    if extra_args.extra_control:
        _logger.info('extra control %s', extra_args.extra_control)
        loaded_data_extra = parse_as_yaml(extra_args.extra_control)
    else:
        loaded_data_extra = None

    control_format = loaded_data.get('version', 1)
    _logger.info('control format version %d', control_format)

    if control_format == 1:
        _backend = process_format_version_1(loaded_obs, loaded_data, loaded_data_extra, args.profilepath)
        datamanager = DataManager(args.basedir, args.datadir, _backend)
        datamanager.workdir_tmpl = "obsid{obsid}_work"
        datamanager.resultdir_tmpl = "obsid{obsid}_results"
        datamanager.serial_format = 'yaml'
        datamanager.result_file = 'result.yaml'
        datamanager.task_file = 'task.yaml'

    elif control_format == 2:
        _backend = process_format_version_2(loaded_obs, loaded_data, loaded_data_extra, args.profilepath)
        datamanager = DataManager(args.basedir, args.datadir, _backend)
    else:
        print('Unsupported format', control_format, 'in', args.reqs)
        sys.exit(1)

    # Start processing
    jobs = []
    for session in sessions:
        for job in session:
            if job['enabled']:
                jobs.append(job)

    for job in jobs:
        # Directories with relevant data
        request = 'reduce'
        request_params = {}

        obid = job['id']

        request_params['oblock_id'] = obid
        request_params["pipeline"] = args.pipe_name
        request_params["instrument_configuration"] = args.insconf

        logger_control = dict(
            default=DEFAULT_RECIPE_LOGGER,
            logfile='processing.log',
            format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
            enabled=True
            )
        request_params['logger_control'] = logger_control

        task = datamanager.backend.new_task(request, request_params)
        task.request = request
        task.request_params = request_params

        task.request_runinfo['runner'] = 'numina'
        task.request_runinfo['runner_version'] = __version__

        _logger.info("procesing OB with id={}".format(obid))
        workenv = datamanager.create_workenv(task)

        task.request_runinfo["results_dir"] = workenv.resultsdir_rel
        task.request_runinfo["work_dir"] = workenv.workdir_rel

        # Roll back to cwd after leaving the context
        with working_directory(workenv.datadir):

            obsres = datamanager.backend.obsres_from_oblock_id(obid, configuration=args.insconf)

            _logger.debug("pipeline from CLI is %r", args.pipe_name)
            pipe_name = args.pipe_name
            obsres.pipeline = pipe_name
            recipe = datamanager.backend.search_recipe_from_ob(obsres)
            _logger.debug('recipe class is %s', recipe.__class__)

            # Enable intermediate results by default
            _logger.debug('enable intermediate results')
            recipe.intermediate_results = True

            # Update runinfo
            _logger.debug('update recipe runinfo')
            recipe.runinfo['runner'] = 'numina'
            recipe.runinfo['runner_version'] = __version__
            recipe.runinfo['task_id'] = task.id
            recipe.runinfo['data_dir'] = workenv.datadir
            recipe.runinfo['work_dir'] = workenv.workdir
            recipe.runinfo['results_dir'] = workenv.resultsdir

            _logger.debug('recipe created')

            try:
                rinput = recipe.build_recipe_input(obsres, datamanager.backend)
            except (ValueError, numina.exceptions.ValidationError) as err:
                _logger.error("During recipe input construction")
                _logger.error("%s", err)
                sys.exit(0)
            _logger.debug('recipe input created')

            # Show the actual inputs
            for key in recipe.requirements():
                v = getattr(rinput, key)
                _logger.debug("recipe requires %r, value is %s", key, v)

            for req in recipe.products().values():
                _logger.debug('recipe provides %s, %s', req.type.__class__.__name__, req.description)

        # Load recipe control and recipe parameters from file
        task.request_runinfo['instrument'] =  obsres.instrument
        task.request_runinfo['mode'] = obsres.mode
        task.request_runinfo['recipe_class'] =  recipe.__class__.__name__
        task.request_runinfo['recipe_fqn'] = fully_qualified_name(recipe.__class__)
        task.request_runinfo['recipe_version'] =  recipe.__version__

        # Copy files
        if args.copy_files:
            _logger.debug('copy files to work directory')
            workenv.sane_work()
            workenv.copyfiles_stage1(obsres)
            workenv.copyfiles_stage2(rinput)
            workenv.adapt_obsres(obsres)

        completed_task = run_recipe(recipe=recipe, task=task, rinput=rinput,
                                    workenv=workenv, logger_control=logger_control)

        datamanager.store_task(completed_task)

    if args.dump_control:
        _logger.debug('dump control status')
        with open('control_dump.yaml', 'w') as fp:
            datamanager.backend.dump(fp)
572031
function _fnProcessingDisplay ( oSettings, bShow )
		{
			if ( oSettings.oFeatures.bProcessing )
			{
				var an = oSettings.aanFeatures.r;
				for ( var i=0, iLen=an.length ; i<iLen ; i++ )
				{
					an[i].style.visibility = bShow ? "visible" : "hidden";
				}
			}
		
			$(oSettings.oInstance).trigger('processing', [oSettings, bShow]);
		}
1276553
public void observation(String info) {
        // Parsing obs as JSON would be slower but less fragile than extracting the turn_key using string search.
        String pattern = "\"turn_key\":\"";
        int i = info.indexOf(pattern);
        String turnKey = "";
        if (i != -1) {
            turnKey = info.substring(i + pattern.length(), info.length() - 1);
            turnKey = turnKey.substring(0, turnKey.indexOf("\""));
            // TCPUtils.Log(Level.FINE, "Observation turn key: " + turnKey);
        }
        lock.lock();
        try {
            if (!envState.turnKey.equals(turnKey)) {
                // TCPUtils.Log(Level.FINE,"Update TK: [" + turnKey + "][" + turnKey + "]");
            }
            if (!envState.lastTurnKey.equals(turnKey)) {
                envState.turnKey = turnKey;
            }
            envState.info = info;
            cond.signalAll();
        } finally {
            lock.unlock();
        }
    }
1038436
def _observe(self, api_command):
        """"""
        path = api_command.path
        duration = api_command.observe_duration
        if duration <= 0:
            raise ValueError("Observation duration has to be greater than 0.")
        url = api_command.url(self._host)
        err_callback = api_command.err_callback

        command = (self._base_command('get')
                   + ['-s', str(duration), '-B', str(duration), url])

        kwargs = {
            'stdout': subprocess.PIPE,
            'stderr': subprocess.DEVNULL,
            'universal_newlines': True
        }
        try:
            proc = subprocess.Popen(command, **kwargs)
        except subprocess.CalledProcessError as err:
            raise RequestError(
                'Error executing request: %s'.format(err)) from None

        output = ''
        open_obj = 0
        start = time()

        for data in iter(lambda: proc.stdout.read(1), ''):
            if data == '\n':
                _LOGGER.debug('Observing stopped for %s after %.1fs',
                              path, time() - start)
                err_callback(RequestError("Observing stopped."))
                break

            if data == '{':
                open_obj += 1
            elif data == '}':
                open_obj -= 1

            output += data

            if open_obj == 0:
                api_command.result = _process_output(output)
                output = ''
180178
def _peek(tokens, n=0):
    """"""
    return tokens.peek(n=n, skip=_is_comment, drop=True)
516213
void startScanSFeaturesAt(List seq, int pos) {	
	sFeatures.clear();
	sFeatureIdx = 0;
	
	Observation obsr = (Observation)seq.get(pos);
	    
	// scan over all context predicates
	for (int i = 0; i < obsr.cps.length; i++) {
	    Element elem = (Element)dict.dict.get(new Integer(obsr.cps[i]));
	    if (elem == null) {
		continue;
	    }
	    
	    if (!(elem.isScanned)) {
		// scan all labels for state feature
		Iterator it = elem.lbCntFidxes.keySet().iterator();
		while (it.hasNext()) {
		    Integer label = (Integer)it.next();
		    CountFeatureIdx cntFidx = (CountFeatureIdx)elem.lbCntFidxes.get(label);

		    if (cntFidx.fidx >= 0) {
			Feature sF = new Feature();
			sF.sFeature1Init(label.intValue(), obsr.cps[i]);
			sF.idx = cntFidx.fidx;
			
			elem.cpFeatures.add(sF);
		    }	    
		}		
		
		elem.isScanned = true;
	    }
	    
	    for (int j = 0; j < elem.cpFeatures.size(); j++) {
		sFeatures.add(elem.cpFeatures.get(j));
	    }
	}		
    }
132319
public boolean process( List<AssociatedTriple> observations , TrifocalTensor solution ) {

		if( observations.size() < 7 )
			throw new IllegalArgumentException(
					"At least 7 correspondences must be provided. Found "+observations.size());

		// compute normalization to reduce numerical errors
		LowLevelMultiViewOps.computeNormalization(observations, N1, N2, N3);

		// compute solution in normalized pixel coordinates
		createLinearSystem(observations);

		// solve for the trifocal tensor
		solveLinearSystem();

		// enforce geometric constraints to improve solution
		extractEpipoles.setTensor(solutionN);
		extractEpipoles.extractEpipoles(e2,e3);
		enforce.process(e2,e3,A);
		enforce.extractSolution(solutionN);

		// undo normalization
		removeNormalization(solution);

		return true;
	}
287136
def nobs(self):
        
        self.control_data.nobs = self.observation_data.shape[0]
        return self.control_data.nobs
1266537
def doExperiment(numObjects,
                 featuresPerObject,
                 objectWidth,
                 numFeatures,
                 featureDistribution,
                 useTrace,
                 noiseFactor,
                 moduleNoiseFactor,
                 numModules,
                 thresholds,
                 inverseReadoutResolution,
                 enlargeModuleFactor,
                 bumpOverlapMethod,
                 seed1,
                 seed2):
  
  if not os.path.exists("traces"):
    os.makedirs("traces")

  if seed1 != -1:
    np.random.seed(seed1)

  if seed2 != -1:
    random.seed(seed2)

  features = [str(i) for i in xrange(numFeatures)]
  objects = generateObjects(numObjects, featuresPerObject, objectWidth,
                            numFeatures, featureDistribution)

  locationConfigs = []
  scale = 40.0

  if thresholds == -1:
    thresholds = int(math.ceil(numModules*0.8))
  elif thresholds == 0:
    thresholds = numModules
  perModRange = float(60.0 / float(numModules))
  for i in xrange(numModules):
    orientation = (float(i) * perModRange) + (perModRange / 2.0)

    locationConfigs.append({
        "scale": scale,
        "orientation": np.radians(orientation),
        "activationThreshold": 8,
        "initialPermanence": 1.0,
        "connectedPermanence": 0.5,
        "learningThreshold": 8,
        "sampleSize": 10,
        "permanenceIncrement": 0.1,
        "permanenceDecrement": 0.0,
        "inverseReadoutResolution": inverseReadoutResolution,
        "enlargeModuleFactor": enlargeModuleFactor,
        "bumpOverlapMethod": bumpOverlapMethod,
    })

  l4Overrides = {
    "initialPermanence": 1.0,
    "activationThreshold": thresholds,
    "reducedBasalThreshold": thresholds,
    "minThreshold": numModules,
    "sampleSize": numModules,
    "cellsPerColumn": 16,
  }

  column = PIUNCorticalColumn(locationConfigs, L4Overrides=l4Overrides,
                              bumpType="gaussian2")
  exp = PIUNExperiment(column, featureNames=features,
                       numActiveMinicolumns=10,
                       noiseFactor=noiseFactor,
                       moduleNoiseFactor=moduleNoiseFactor)

  for objectDescription in objects:
    exp.learnObject(objectDescription)

  convergence = collections.defaultdict(int)
  try:
    if useTrace:
      filename = os.path.join(
        SCRIPT_DIR,
        "traces/{}-resolution-{}-modules-{}-objects-{}-feats.html".format(
          inverseReadoutResolution, numModules, numObjects, numFeatures)
      )
      traceFileOut = io.open(filename, "w", encoding="utf8")
      traceHandle = trace(traceFileOut, exp, includeSynapses=True)
      print "Logging to", filename

    for objectDescription in objects:
      steps = exp.inferObjectWithRandomMovements(objectDescription)
      convergence[steps] += 1
      if steps is None:
        print 'Failed to infer object "{}"'.format(objectDescription["name"])
  finally:
    if useTrace:
      traceHandle.__exit__()
      traceFileOut.close()

  for step, num in sorted(convergence.iteritems()):
    print "{}: {}".format(step, num)

  result = {
    "convergence": convergence,
  }

  return result
644642
def compute_vis_noise(msname, sefd, spw_id=0):
    """"""
    from pyrap.tables import table

    tab = table(msname)
    spwtab = table(msname + "/SPECTRAL_WINDOW")

    freq0 = spwtab.getcol("CHAN_FREQ")[spw_id, 0]
    wavelength = 300e+6/freq0
    bw = spwtab.getcol("CHAN_WIDTH")[spw_id, 0]
    dt = tab.getcol("EXPOSURE", 0, 1)[0]
    dtf = (tab.getcol("TIME", tab.nrows()-1, 1)-tab.getcol("TIME", 0, 1))[0]

    # close tables properly, else the calls below will hang waiting for a lock...
    tab.close()
    spwtab.close()

    print(">>> %s freq %.2f MHz (lambda=%.2fm), bandwidth %.2g kHz, %.2fs integrations, %.2fh synthesis"%(msname, freq0*1e-6, wavelength, bw*1e-3, dt, dtf/3600))
    noise = sefd/math.sqrt(abs(2*bw*dt))
    print(">>> SEFD of %.2f Jy gives per-visibility noise of %.2f mJy"%(sefd, noise*1000))

    return noise
891589
@Override
	public void process(GrayF32 intensityImage, @Nullable QueueCorner localMin, @Nullable QueueCorner localMax) {

		if( localMin != null )
			localMin.reset();
		if( localMax != null )
			localMax.reset();

		// the defines the region that can be processed
		int endX = intensityImage.width - border;
		int endY = intensityImage.height - border;

		int step = configuration.radius+1;

		search.initialize(configuration,intensityImage,localMin,localMax);

		// Compute number of y iterations
		int range = endY-border;
		int N = range/step;
		if( range > N*step )
			N += 1;

		BoofConcurrency.loopFor(0,N, iterY -> {

			NonMaxBlock.Search search;
			QueueCorner threadMin=null,threadMax=null;

			// get work space for this thread
			synchronized (lock) {
				if( searches.isEmpty() ) {
					search = this.search.newInstance();
				} else {
					search = searches.remove( searches.size()-1 );
				}
				if( search.isDetectMinimums() ) {
					threadMin = pop();
				}
				if( search.isDetectMaximums() ) {
					threadMax = pop();
				}
			}
			search.initialize(configuration,intensityImage,threadMin,threadMax);

			// search for local peaks along this block row
			int y = border + iterY*step;
			int y1 = y + step;
			if( y1 > endY) y1 = endY;

			for(int x = border; x < endX; x += step ) {
				int x1 = x + step;
				if( x1 > endX) x1 = endX;
				search.searchBlock(x,y,x1,y1);
			}

			// Save the results and recycle thread working space
			synchronized (lock) {
				saveResults(localMin, threadMin);
				saveResults(localMax, threadMax);

				searches.add(search);
				if( threadMin != null )
					cornerLists.add(threadMin);
				if( threadMax != null )
					cornerLists.add(threadMax);
			}
		});
	}
650378
function(terria, viewer) {
  GlobeOrMap.call(this, terria);

  /**
   * Gets or sets the Cesium {@link Viewer} instance.
   * @type {Viewer}
   */
  this.viewer = viewer;

  /**
   * Gets or sets the Cesium {@link Scene} instance.
   * @type {Scene}
   */
  this.scene = viewer.scene;

  /**
   * Gets or sets whether the viewer has stopped rendering since startup or last set to false.
   * @type {Boolean}
   */
  this.stoppedRendering = false;

  /**
   * Gets or sets whether to output info to the console when starting and stopping rendering loop.
   * @type {Boolean}
   */
  this.verboseRendering = false;

  /**
   * Gets or sets whether this viewer _can_ show a splitter.
   * @type {Boolean}
   */
  this.canShowSplitter = true;

  /**
   * Gets the {@link DataSourceDisplay} used to render a {@link DataSource}.
   * @type {DataSourceDisplay}
   */
  this.dataSourceDisplay = undefined;

  this._lastClockTime = new JulianDate(0, 0.0);
  this._lastCameraViewMatrix = new Matrix4();
  this._lastCameraMoveTime = 0;

  this._selectionIndicator = new CesiumSelectionIndicator(this);

  this._removePostRenderListener = this.scene.postRender.addEventListener(
    postRender.bind(undefined, this)
  );
  this._removeInfoBoxCloseListener = undefined;
  this._boundNotifyRepaintRequired = this.notifyRepaintRequired.bind(this);

  this._pauseMapInteractionCount = 0;

  this.scene.imagerySplitPosition = this.terria.splitPosition;

  this.supportsPolylinesOnTerrain = this.scene.context.depthTexture;

  // Handle left click by picking objects from the map.
  viewer.screenSpaceEventHandler.setInputAction(
    function(e) {
      this.pickFromScreenPosition(e.position);
    }.bind(this),
    ScreenSpaceEventType.LEFT_CLICK
  );

  // Force a repaint when the mouse moves or the window changes size.
  var canvas = this.viewer.canvas;
  canvas.addEventListener("mousemove", this._boundNotifyRepaintRequired, false);
  canvas.addEventListener("mousedown", this._boundNotifyRepaintRequired, false);
  canvas.addEventListener("mouseup", this._boundNotifyRepaintRequired, false);
  canvas.addEventListener(
    "touchstart",
    this._boundNotifyRepaintRequired,
    false
  );
  canvas.addEventListener("touchend", this._boundNotifyRepaintRequired, false);
  canvas.addEventListener("touchmove", this._boundNotifyRepaintRequired, false);

  if (defined(window.PointerEvent)) {
    canvas.addEventListener(
      "pointerdown",
      this._boundNotifyRepaintRequired,
      false
    );
    canvas.addEventListener(
      "pointerup",
      this._boundNotifyRepaintRequired,
      false
    );
    canvas.addEventListener(
      "pointermove",
      this._boundNotifyRepaintRequired,
      false
    );
  }

  // Detect available wheel event
  this._wheelEvent = undefined;
  if ("onwheel" in canvas) {
    // spec event type
    this._wheelEvent = "wheel";
  } else if (defined(document.onmousewheel)) {
    // legacy event type
    this._wheelEvent = "mousewheel";
  } else {
    // older Firefox
    this._wheelEvent = "DOMMouseScroll";
  }

  canvas.addEventListener(
    this._wheelEvent,
    this._boundNotifyRepaintRequired,
    false
  );

  window.addEventListener("resize", this._boundNotifyRepaintRequired, false);

  // Force a repaint when the feature info box is closed.  Cesium can't close its info box
  // when the clock is not ticking, for reasons that are not clear.
  if (defined(this.viewer.infoBox)) {
    this._removeInfoBoxCloseListener = this.viewer.infoBox.viewModel.closeClicked.addEventListener(
      this._boundNotifyRepaintRequired
    );
  }

  if (defined(this.viewer._clockViewModel)) {
    var clock = this.viewer._clockViewModel;
    this._shouldAnimateSubscription = knockout
      .getObservable(clock, "shouldAnimate")
      .subscribe(this._boundNotifyRepaintRequired);
    this._currentTimeSubscription = knockout
      .getObservable(clock, "currentTime")
      .subscribe(this._boundNotifyRepaintRequired);
  }

  if (defined(this.viewer.timeline)) {
    this.viewer.timeline.addEventListener(
      "settime",
      this._boundNotifyRepaintRequired,
      false
    );
  }

  this._selectedFeatureSubscription = knockout
    .getObservable(this.terria, "selectedFeature")
    .subscribe(function() {
      selectFeature(this);
    }, this);

  this._splitterPositionSubscription = knockout
    .getObservable(this.terria, "splitPosition")
    .subscribe(function() {
      if (this.scene) {
        this.scene.imagerySplitPosition = this.terria.splitPosition;
        this.notifyRepaintRequired();
      }
    }, this);

  this._showSplitterSubscription = knockout
    .getObservable(terria, "showSplitter")
    .subscribe(function() {
      this.updateAllItemsForSplitter();
    }, this);

  // Hacky way to force a repaint when an async load request completes
  var that = this;
  this._originalLoadWithXhr = loadWithXhr.load;
  loadWithXhr.load = function(
    url,
    responseType,
    method,
    data,
    headers,
    deferred,
    overrideMimeType,
    preferText,
    timeout
  ) {
    deferred.promise.always(that._boundNotifyRepaintRequired);
    that._originalLoadWithXhr(
      url,
      responseType,
      method,
      data,
      headers,
      deferred,
      overrideMimeType,
      preferText,
      timeout
    );
  };

  // Hacky way to force a repaint when a web worker sends something back.
  this._originalScheduleTask = TaskProcessor.prototype.scheduleTask;
  TaskProcessor.prototype.scheduleTask = function(
    parameters,
    transferableObjects
  ) {
    var result = that._originalScheduleTask.call(
      this,
      parameters,
      transferableObjects
    );

    if (!defined(this._originalWorkerMessageSinkRepaint)) {
      this._originalWorkerMessageSinkRepaint = this._worker.onmessage;

      var taskProcessor = this;
      this._worker.onmessage = function(event) {
        taskProcessor._originalWorkerMessageSinkRepaint(event);

        if (that.isDestroyed()) {
          taskProcessor._worker.onmessage =
            taskProcessor._originalWorkerMessageSinkRepaint;
          taskProcessor._originalWorkerMessageSinkRepaint = undefined;
        } else {
          that.notifyRepaintRequired();
        }
      };
    }

    return result;
  };

  this.eventHelper = new EventHelper();

  // If the render loop crashes, inform the user and then switch to 2D.
  this.eventHelper.add(
    this.scene.renderError,
    function(scene, error) {
      this.terria.error.raiseEvent(
        new TerriaError({
          sender: this,
          title: "Error rendering in 3D",
          message:
            "\
<p>An error occurred while rendering in 3D.  This probably indicates a bug in " +
            terria.appName +
            " or an incompatibility with your system \
or web browser.  We'll now switch you to 2D so that you can continue your work.  We would appreciate it if you report this \
error by sending an email to <a href=\"mailto:" +
            terria.supportEmail +
            '">' +
            terria.supportEmail +
            "</a> with the \
technical details below.  Thank you!</p><pre>" +
            formatError(error) +
            "</pre>"
        })
      );

      this.terria.viewerMode = ViewerMode.Leaflet;
    },
    this
  );

  this.eventHelper.add(
    this.scene.globe.tileLoadProgressEvent,
    this.updateTilesLoadingCount.bind(this)
  );

  selectFeature(this);
}
1225725
protected void detectOctave( II integral , int skip , int ...featureSize ) {

		int w = integral.width/skip;
		int h = integral.height/skip;

		// resize the output intensity image taking in account subsampling
		for( int i = 0; i < intensity.length; i++ ) {
			intensity[i].reshape(w,h);
		}

		// compute feature intensity in each level
		for( int i = 0; i < featureSize.length; i++ ) {
			GIntegralImageFeatureIntensity.hessian(integral,skip,featureSize[i],intensity[spaceIndex]);

			spaceIndex++;
			if( spaceIndex >= 3 )
				spaceIndex = 0;

			// find maximum in scale space
			if( i >= 2 ) {
				findLocalScaleSpaceMax(featureSize,i-1,skip);
			}
		}
	}
523272
function processOtherSpecifier() {
                    const leftBrace = sourceCode.getFirstToken(node, 1)
                    const rightBrace = sourceCode.getLastToken(
                        node,
                        hasSemi ? 3 : 2
                    )
                    setOffsetToToken(leftBrace, 0, importToken)
                    processNodeList(node.specifiers, leftBrace, rightBrace, 1)
                    tokens.push(
                        sourceCode.getLastToken(node, hasSemi ? 2 : 1), // from
                        sourceCode.getLastToken(node, hasSemi ? 1 : 0) // "foo"
                    )
                }
722497
def __analizar_observaciones(self, ret):
        ""
        self.Observaciones = [obs["codigoDescripcion"] for obs in ret.get('arrayObservaciones', [])]
        self.Obs = '\n'.join(["%(codigo)s: %(descripcion)s" % obs for obs in self.Observaciones])
535278
def observe(self, dataset, kind, components=None, distance=1.0, l3=0.0, **kwargs):
        

        meshes = self.meshes
        if kind=='lp':
            def sv(p, p0, w):
                # Subsidiary variable:
                return (p0-p)/(w/2)

            def lorentzian(sv):
                return 1-1./(1+sv**2)

            def gaussian(sv):
                return 1-np.exp(-np.log(2)*sv**2)

            profile_func = kwargs.get('profile_func')
            profile_rest = kwargs.get('profile_rest')
            profile_sv = kwargs.get('profile_sv')
            wavelengths = kwargs.get('wavelengths')
            if profile_func == 'gaussian':
                func = gaussian
            elif profile_func == 'lorentzian':
                func = lorentzian
            else:
                raise NotImplementedError("profile_func='{}' not supported".format(profile_func))

            visibilities = meshes.get_column_flat('visibilities', components)

            abs_intensities = meshes.get_column_flat('abs_intensities:{}'.format(dataset), components)
            # mus here will be from the tnormals of the triangle and will not
            # be weighted by the visibility of the triangle
            mus = meshes.get_column_flat('mus', components)
            areas = meshes.get_column_flat('areas_si', components)
            ldint = meshes.get_column_flat('ldint:{}'.format(dataset), components)

            rvs = (meshes.get_column_flat("rvs:{}".format(dataset), components)*u.solRad/u.d).to(u.m/u.s).value
            dls = rvs*profile_rest/c.c.si.value

            line = func(sv(wavelengths, profile_rest, profile_sv))
            lines = np.array([np.interp(wavelengths, wavelengths+dl, line) for dl in dls])
            if not np.any(visibilities):
                avg_line = np.full_like(wavelengths, np.nan)
            else:
                avg_line = np.average(lines, axis=0, weights=abs_intensities*areas*mus*ldint*visibilities)

            return {'flux_densities': avg_line}


        elif kind=='rv':
            visibilities = meshes.get_column_flat('visibilities', components)

            if np.all(visibilities==0):
                # then no triangles are visible, so we should return nan
                return {'rv': np.nan}

            rvs = meshes.get_column_flat("rvs:{}".format(dataset), components)
            abs_intensities = meshes.get_column_flat('abs_intensities:{}'.format(dataset), components)
            # mus here will be from the tnormals of the triangle and will not
            # be weighted by the visibility of the triangle
            mus = meshes.get_column_flat('mus', components)
            areas = meshes.get_column_flat('areas_si', components)
            ldint = meshes.get_column_flat('ldint:{}'.format(dataset), components)
            # NOTE: don't need ptfarea because its a float (same for all
            # elements, regardless of component)

            # NOTE: the intensities are already projected but are per unit area
            # so we need to multiply by the /projected/ area of each triangle (thus the extra mu)
            return {'rv': np.average(rvs, weights=abs_intensities*areas*mus*ldint*visibilities)}

        elif kind=='lc':
            visibilities = meshes.get_column_flat('visibilities')

            if np.all(visibilities==0):
                # then no triangles are visible, so we should return nan -
                # probably shouldn't ever happen for lcs
                return {'flux': np.nan}

            intensities = meshes.get_column_flat("intensities:{}".format(dataset), components)
            mus = meshes.get_column_flat('mus', components)
            areas = meshes.get_column_flat('areas_si', components)
            ldint = meshes.get_column_flat('ldint:{}'.format(dataset), components)

            # assume that all bodies are using the same passband and therefore
            # will have the same ptfarea.  If this assumption is ever a problem -
            # then we will need to build a flat column based on the component
            # of each element so that ptfarea is an array with the same shape
            # as those above
            if isinstance(self.bodies[0], Envelope):
                # for envelopes, we'll make the same assumption and just grab
                # that value stored in the first "half"
                ptfarea = self.bodies[0]._halves[0].get_ptfarea(dataset)
            else:
                ptfarea = self.bodies[0].get_ptfarea(dataset)

            # intens_proj is the intensity in the direction of the observer per unit surface area of the triangle
            # areas is the area of each triangle
            # areas*mus is the area of each triangle projected in the direction of the observer
            # visibilities is 0 for hidden, 0.5 for partial, 1.0 for visible
            # areas*mus*visibilities is the visibile projected area of each triangle (ie half the area for a partially-visible triangle)
            # so, intens_proj*areas*mus*visibilities is the intensity in the direction of the observer per the observed projected area of that triangle
            # and the sum of these values is the observed flux

            # note that the intensities are already projected but are per unit area
            # so we need to multiply by the /projected/ area of each triangle (thus the extra mu)

            return {'flux': np.sum(intensities*areas*mus*visibilities)*ptfarea/(distance**2)+l3}

        else:
            raise NotImplementedError("observe for dataset with kind '{}' not implemented".format(kind))
938054
void estimateTranslation( DMatrixRMaj R , List<AssociatedPair> points , Vector3D_F64 T )
	{
		final int N = points.size();
		W.reshape(N*2,3);
		y.reshape(N*2,1);
		Wty.reshape(3,1);

		DMatrix3x3 Rtmp = new DMatrix3x3();
		ConvertDMatrixStruct.convert(R,Rtmp);

		int indexY = 0,indexW = 0;
		for (int i = 0; i < N; i++) {
			AssociatedPair p = points.get(i);

			// rotate into camera frame
			double u1 = Rtmp.a11*p.p1.x + Rtmp.a12*p.p1.y;
			double u2 = Rtmp.a21*p.p1.x + Rtmp.a22*p.p1.y;
			double u3 = Rtmp.a31*p.p1.x + Rtmp.a32*p.p1.y;

			W.data[indexW++] = 1;
			W.data[indexW++] = 0;
			W.data[indexW++] = -p.p2.x;
			W.data[indexW++] = 0;
			W.data[indexW++] = 1;
			W.data[indexW++] = -p.p2.y;

			y.data[indexY++] = p.p2.x*u3 - u1;
			y.data[indexY++] = p.p2.y*u3 - u2;
		}

		//======= Compute Pseudo Inverse
		// WW = inv(W^T*W)
		CommonOps_DDRM.multTransA(W,W,WW);
		CommonOps_DDRM.invert(WW);

		// W^T*y
		CommonOps_DDRM.multTransA(W,y,Wty);

		// translation = inv(W^T*W)*W^T*y
		W.reshape(3,1);
		CommonOps_DDRM.mult(WW,Wty,W);

		T.x = W.data[0];
		T.y = W.data[1];
		T.z = W.data[2];
	}