Record that a variant was successful for a user
    @param experiment_id : A single experiment id
    @param user_id : An identifier for the user
    @param client_id : Bernoulli Client ID
166873
def record_goal_attained(experiment_id, user_id, client_id = None):
    

    if not client_id:
        client_id = os.environ.get('BERNOULLI_CLIENT_ID')

    if not client_id:
        raise Exception("client_id is required")

    try:
        response = requests.post(BASE_URL, data={
            'clientId': client_id,
            'userId': user_id,
            'experimentId': experiment_id,
        })
    except requests.ConnectionError:
        raise Exception("Unable to access services")

    val = response.json()
    if val['status'] != 'ok':
        raise Exception(val['message'])

    return val['value']
283471
def add_experiment(redis, name):
    """"""

    if not ALLOWED_NAMES.match(name):
        raise ExperimentException(name, "Illegal name")
    if redis.exists(EXPERIMENT_REDIS_KEY_TEMPLATE % name):
        raise ExperimentException(name, "Already exists")

    json = dict(creation_date=util.unicode_type(datetime.datetime.now()))
    pipe = redis.pipeline(transaction=True)
    pipe.sadd(ACTIVE_EXPERIMENTS_REDIS_KEY, name)
    pipe.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % name, "metadata", escape.json_encode(json))
    pipe.execute()
    return Experiment(redis, name)
1161734
def persist_experiment(experiment):
    
    from benchbuild.utils.schema import Experiment, Session

    session = Session()

    cfg_exp = experiment.id
    LOG.debug("Using experiment ID stored in config: %s", cfg_exp)
    exps = session.query(Experiment).filter(Experiment.id == cfg_exp)
    desc = str(CFG["experiment_description"])
    name = experiment.name

    if exps.count() == 0:
        newe = Experiment()
        newe.id = cfg_exp
        newe.name = name
        newe.description = desc
        session.add(newe)
        ret = newe
    else:
        exps.update({'name': name, 'description': desc})
        ret = exps.first()

    try:
        session.commit()
    except IntegrityError:
        session.rollback()
        persist_experiment(experiment)

    return (ret, session)
328684
def complete_experiment(self, status):
        
        self.log("Bot player completing experiment. Status: {}".format(status))
        while True:
            url = "{host}/{status}?participant_id={participant_id}".format(
                host=self.host, participant_id=self.participant_id, status=status
            )
            try:
                result = requests.get(url)
                result.raise_for_status()
            except RequestException:
                self.stochastic_sleep()
                continue
            return result
351479
def update_experiment():
    ''''''
    experiment_config = Experiments()
    experiment_dict = experiment_config.get_all_experiments()
    if not experiment_dict:
        return None
    for key in experiment_dict.keys():
        if isinstance(experiment_dict[key], dict):
            if experiment_dict[key].get('status') != 'STOPPED':
                nni_config = Config(experiment_dict[key]['fileName'])
                rest_pid = nni_config.get_config('restServerPid')
                if not detect_process(rest_pid):
                    experiment_config.update_experiment(key, 'status', 'STOPPED')
                    continue
                rest_port = nni_config.get_config('restServerPort')
                startTime, endTime = get_experiment_time(rest_port)
                if startTime:
                    experiment_config.update_experiment(key, 'startTime', startTime)
                if endTime:
                    experiment_config.update_experiment(key, 'endTime', endTime)
                status = get_experiment_status(rest_port)
                if status:
                    experiment_config.update_experiment(key, 'status', status)
12618
def get_experiment_summ_ids( self, coinc_event_id ):
		
		experiment_summ_ids = []
		for row in self:
			if row.coinc_event_id == coinc_event_id:
				experiment_summ_ids.append(row.experiment_summ_id)
		if len(experiment_summ_ids) == 0:
			raise ValueError("'%s' could not be found in the experiment_map table" % coinc_event_id)
		return experiment_summ_ids
532235
private function getWhitelistedVariation(Experiment $experiment, $userId)
    {
        // Check if user is whitelisted for a variation.
        $forcedVariations = $experiment->getForcedVariations();
        if (!is_null($forcedVariations) && isset($forcedVariations[$userId])) {
            $variationKey = $forcedVariations[$userId];
            $variation = $this->_projectConfig->getVariationFromKey($experiment->getKey(), $variationKey);
            if ($variationKey && !empty($variation->getKey())) {
                $this->_logger->log(
                    Logger::INFO,
                    sprintf('User "%s" is forced in variation "%s" of experiment "%s".', $userId, $variationKey, $experiment->getKey())
                );
            } else {
                return null;
            }
            return $variation;
        }
        return null;
    }
576776
def list_experiments
      response =  self.client.execute({
        api_method: self.analytics_experiments.list,
        parameters: {
          accountId: self.config.account_id.to_s,
          profileId: self.config.profile_id.to_s,
          webPropertyId: self.config.web_property_id
        }
      })
      response.data.items.collect(&:to_hash)
    end
772476
def _maybe_init_run(self, experiment_name, run_name):
    
    experiment_id = self._maybe_init_experiment(experiment_name)
    cursor = self._db.cursor()
    cursor.execute(
        """
        SELECT run_id FROM Runs
        WHERE experiment_id = ? AND run_name = ?
        """,
        (experiment_id, run_name))
    row = cursor.fetchone()
    if row:
      return row[0]
    run_id = self._create_id()
    # TODO: track actual run start times
    started_time = 0
    cursor.execute(
        """
        INSERT INTO Runs (
          experiment_id, run_id, run_name, inserted_time, started_time
        ) VALUES (?, ?, ?, ?, ?)
        """,
        (experiment_id, run_id, run_name, time.time(), started_time))
    return run_id
745828
def show_observee(self, user_id, observee_id):
        
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - user_id
        """ID"""
        path["user_id"] = user_id

        # REQUIRED - PATH - observee_id
        """ID"""
        path["observee_id"] = observee_id

        self.logger.debug("GET /api/v1/users/{user_id}/observees/{observee_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/users/{user_id}/observees/{observee_id}".format(**path), data=data, params=params, single_item=True)
488641
public function getVariationFromId($experimentKey, $variationId)
    {
        if (isset($this->_variationIdMap[$experimentKey])
            && isset($this->_variationIdMap[$experimentKey][$variationId])
        ) {
            return $this->_variationIdMap[$experimentKey][$variationId];
        }

        $this->_logger->log(
            Logger::ERROR,
            sprintf(
                'No variation ID "%s" defined in datafile for experiment "%s".',
                $variationId,
                $experimentKey
            )
        );
        $this->_errorHandler->handleError(new InvalidVariationException('Provided variation is not in datafile.'));
        return new Variation();
    }
98941
def run_experiment(self):
        
        data=self.data
        options=self.options
        result=self.result

        command = open(self.options.experiment_script).read()
        result["experiment_script"]=command
        t0=time.time()
        exec(command)   #creates variable result
        t1=time.time()
        print(("Elapsed time for running the experiment is %.2f seconds" % (t1-t0)))
        self.result=result
        return self.result
1043508
def setup_experiment(log, debug=True, verbose=False, app=None, exp_config=None):
    

    # Verify that the Postgres server is running.
    try:
        db.check_connection()
    except Exception:
        log("There was a problem connecting to the Postgres database!")
        raise

    # Check that the demo-specific requirements are satisfied.
    try:
        with open("requirements.txt", "r") as f:
            dependencies = [r for r in f.readlines() if r[:3] != "-e "]
    except (OSError, IOError):
        dependencies = []
    pkg_resources.require(dependencies)

    # Generate a unique id for this experiment.
    from dallinger.experiment import Experiment

    generated_uid = public_id = Experiment.make_uuid(app)

    # If the user provided an app name, use it everywhere that's user-facing.
    if app:
        public_id = str(app)

    log("Experiment id is " + public_id + "")

    # Load and update the config
    config = get_config()
    if not config.ready:
        config.load()  #
    if exp_config:
        config.extend(exp_config)
    config.extend({"id": six.text_type(generated_uid)})

    temp_dir = assemble_experiment_temp_dir(config)
    log("Deployment temp directory: {}".format(temp_dir), chevrons=False)

    # Zip up the temporary directory and place it in the cwd.
    if not debug:
        log("Freezing the experiment package...")
        shutil.make_archive(
            os.path.join(os.getcwd(), "snapshots", public_id + "-code"), "zip", temp_dir
        )

    return (public_id, temp_dir)
180586
def seed_pathology_for(local_patient_id:)
      patient = Patient.find_by(local_patient_id: local_patient_id)
      pathology_patient = Pathology.cast_patient(patient)
      seed_pathology_requests_for(patient: pathology_patient)
      seed_pathology_observations_for(patient: pathology_patient)
    end
816970
def download_experiment(self, experiment_id):
        
        req = self.query_records_no_auth('experiment',
                                         query='download/'+experiment_id)
        if req.status_code == 404:
            print "Sorry, no experiment matching id # " + experiment_id
            print "Please double check the code you obtained on the\
                http://psiturk.org/ee"
        else:
            # Check if folder with same name already exists.
            expinfo = req.json()
            gitr = requests.get(expinfo['git_url']).json()
            if os.path.exists('./'+gitr['name']):
                print "*"*20
                print "Sorry, you already have a file or folder named\
                    "+gitr['name']+". Please rename or delete it before trying\
                    to download this experiment.  You can do this by typing `rm\
                    -rf " + gitr['name'] + "`"
                print "*"*20
                return
            if "clone_url" in gitr:
                git.Git().clone(gitr["clone_url"])
                print "="*20
                print "Downloading..."
                print "Name: " + expinfo['name']
                print "Downloads: " + str(expinfo['downloads'])
                print "Keywords: " + expinfo['keywords']
                print "psiTurk Version: " +\
                    str(expinfo['psiturk_version_string'])
                print "URL: http://psiturk.org/ee/"+experiment_id
                print "\n"
                print "Experiment downloaded into the `" + gitr['name'] + "`\
                    folder of the current directory"
                print "Type 'cd " + gitr['name'] + "` then run the `psiturk`\
                    command."
                print "="*20
            else:
                print "Sorry, experiment not located on github.  You might\
                    contact the author of this experiment.  Experiment NOT\
                    downloaded."
            return
342099
def update_experiment_profile(args, key, value):
    ''''''
    nni_config = Config(get_config_filename(args))
    rest_port = nni_config.get_config('restServerPort')
    running, _ = check_rest_server_quick(rest_port)
    if running:
        response = rest_get(experiment_url(rest_port), REST_TIME_OUT)
        if response and check_response(response):
            experiment_profile = json.loads(response.text)
            experiment_profile['params'][key] = value
            response = rest_put(experiment_url(rest_port)+get_query_type(key), json.dumps(experiment_profile), REST_TIME_OUT)
            if response and check_response(response):
                return response
    else:
        print_error('Restful server is not running...')
    return None
355976
def get_experiment_from_key(self, experiment_key):
    

    experiment = self.experiment_key_map.get(experiment_key)

    if experiment:
      return experiment

    self.logger.error('Experiment key "%s" is not in datafile.' % experiment_key)
    self.error_handler.handle_error(exceptions.InvalidExperimentException(enums.Errors.INVALID_EXPERIMENT_KEY_ERROR))
    return None