Check the app and, if it's compatible with Wallace, freeze its state.
320771
def setup_experiment(debug=True, verbose=False, app=None):
    """"""
    print_header()

    # Verify that the package is usable.
    log("Verifying that directory is compatible with Wallace...")
    if not verify_package(verbose=verbose):
        raise AssertionError(
            "This is not a valid Wallace app. " +
            "Fix the errors and then try running 'wallace verify'.")

    # Verify that the Postgres server is running.
    try:
        psycopg2.connect(database="x", user="postgres", password="nada")
    except psycopg2.OperationalError, e:
        if "could not connect to server" in str(e):
            raise RuntimeError("The Postgres server isn't running.")

    # Load psiTurk configuration.
    config = PsiturkConfig()
    config.load_config()

    # Check that the demo-specific requirements are satisfied.
    try:
        with open("requirements.txt", "r") as f:
            dependencies = f.readlines()
    except:
        dependencies = []

    pkg_resources.require(dependencies)

    # Generate a unique id for this experiment.
    id = "w" + str(uuid.uuid4())[0:28]

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

    log("Running as experiment " + id + "...")

    # Copy this directory into a temporary folder, ignoring .git
    dst = os.path.join(tempfile.mkdtemp(), id)
    to_ignore = shutil.ignore_patterns(
        ".git/*",
        "*.db",
        "snapshots",
        "data",
        "server.log"
    )
    shutil.copytree(os.getcwd(), dst, ignore=to_ignore)

    click.echo(dst)

    # Save the experiment id
    with open(os.path.join(dst, "experiment_id.txt"), "w") as file:
        if app:
            file.write(id_long)
        else:
            file.write(id)

    # 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("snapshots", id + "-code"), "zip", dst)

    # Change directory to the temporary folder.
    cwd = os.getcwd()
    os.chdir(dst)

    # Check directories.
    if not os.path.exists("static/scripts"):
        os.makedirs("static/scripts")
    if not os.path.exists("templates"):
        os.makedirs("templates")
    if not os.path.exists("static/css"):
        os.makedirs("static/css")

    # Rename experiment.py to wallace_experiment.py to aviod psiTurk conflict.
    os.rename(
        os.path.join(dst, "experiment.py"),
        os.path.join(dst, "wallace_experiment.py"))

    # Copy files into this experiment package.
    src = os.path.join(
        os.path.dirname(os.path.realpath(__file__)),
        "custom.py")
    shutil.copy(src, os.path.join(dst, "custom.py"))

    heroku_files = [
        "Procfile",
        "requirements.txt",
        "psiturkapp.py",
        "worker.py",
        "clock.py",
    ]

    for filename in heroku_files:
        src = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            "heroku",
            filename)
        shutil.copy(src, os.path.join(dst, filename))

    clock_on = config.getboolean('Server Parameters', 'clock_on')

    # If the clock process has been disabled, overwrite the Procfile.
    if not clock_on:
        src = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            "heroku",
            "Procfile_no_clock")
        shutil.copy(src, os.path.join(dst, "Procfile"))

    frontend_files = [
        "static/css/wallace.css",
        "static/scripts/wallace.js",
        "static/scripts/reqwest.min.js",
        "templates/error_wallace.html",
        "templates/launch.html",
        "templates/complete.html",
        "static/robots.txt"
    ]

    for filename in frontend_files:
        src = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            "frontend",
            filename)
        shutil.copy(src, os.path.join(dst, filename))

    time.sleep(0.25)

    os.chdir(cwd)

    return (id, dst)
1260443
def _freeze(self, final_text):
        """"""
        text = to_unicode(final_text)
        self._last_frame = self._compose_out(text, mode="last")

        # Should be stopped here, otherwise prints after
        # self._freeze call will mess up the spinner
        self.stop()
        sys.stdout.write(self._last_frame)
1017941
def cancel_if_pending(self):
        
        if self.state == tds_base.TDS_IDLE:
            return
        if not self.in_cancel:
            self.put_cancel()
        self.process_cancel()
621993
def freeze(obj):
    '''
    
    '''
    if isinstance(obj, dict):
        return ImmutableDict(obj)
    if isinstance(obj, list):
        return ImmutableList(obj)
    if isinstance(obj, set):
        return ImmutableSet(obj)
    return obj
1305564
function onupgrade(to){
    if (transport && to.name != transport.name) {
      debug('"%s" works - aborting "%s"', to.name, transport.name);
      freezeTransport();
    }
  }
649439
private void checkUnready() {
    if (!allReady()) {
      log.debug(String.format("%s - Components not ready, pausing components", NetworkManager.this));
      data.remove(currentContext.address(), new Handler<AsyncResult<String>>() {
        @Override
        public void handle(AsyncResult<String> result) {
          if (result.failed()) {
            log.error(result.cause());
          }
        }
      });
    }
  }
574783
public synchronized void statusMachine(final String status, final DeviceState state) throws DevFailed {
        if (status != null) {
            logger.debug("Changing status to: {}", status);
            this.status = status;
            if (setStatusMethod != null) {
                try {
                    setStatusMethod.invoke(businessObject, status);
                } catch (final IllegalArgumentException e) {
                    throw DevFailedUtils.newDevFailed(e);
                } catch (final IllegalAccessException e) {
                    throw DevFailedUtils.newDevFailed(e);
                } catch (final InvocationTargetException e) {
                    if (e.getCause() instanceof DevFailed) {
                        throw (DevFailed) e.getCause();
                    } else {
                        throw DevFailedUtils.newDevFailed(e.getCause());
                    }
                }
            }
        }
    }
831465
def freeze(self):
        '''
        
        '''
        remote_path = os.path.join(self.venv, 'requirements.txt')
        run('{} freeze > {}'.format(self.pip(), remote_path))
        get(remote_path, self.requirements)
949350
def isLocked(self):
        '''
        
        '''

        self.__checkTransport()
        lockScreenRE = re.compile('mShowingLockscreen=(true|false)')
        dwp = self.shell('dumpsys window policy')
        m = lockScreenRE.search(dwp)
        if m:
            return m.group(1) == 'true'
        dreamingLockscreenRE = re.compile('mDreamingLockscreen=(true|false)')
        m = dreamingLockscreenRE.search(dwp)
        if m:
            return m.group(1) == 'true'
        raise RuntimeError("Couldn't determine screen lock state")
6659
public void pause() {
        if (hasState(TICKING) && !hasState(PAUSED)) {
            if (DBG) Log.v(TAG, "pause. " + mEntries.size());
            mContentView.animate().cancel();
            addState(PAUSED);
            cancel(-1);
        }
    }
1306452
function freeze(self) {
    var anything = self;
    if (anything.aclEntries) {
        anything.aclEntries = Object.freeze(anything.aclEntries);
    }
    if (anything.createdDate) {
        anything.createdDate = Object.freeze(new Date(+anything.createdDate));
    }
    if (anything.modifiedDate) {
        anything.modifiedDate = Object.freeze(new Date(+anything.modifiedDate));
    }
    return Object.freeze(anything);
}
124923
public void blockTillTerminated() {
    while (!runState.compareAndSet(State.IDLE, State.REMOVED)) {
      // wait and retry
      LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
      if (Thread.currentThread().isInterrupted()) {
        runState.set(State.REMOVED);
        return;
      }
    }
  }
941534
def freeze(config, urls_file=None):
    """"""
    if urls_file:
        app = make_app(config=config, URLS_FILE=urls_file)
    else:
        app = make_app(config=config)
    app.logger.info('freezing app to directory: %s' % app.config['FREEZER_DESTINATION'])
    freezer = Freezer(app)


    #@freezer.register_generator
    #def index_page():
    #    for (dirpath, dirnames, filenames) in os.walk(app.config['DATA_PATH'], topdown=True):
    #        start = len(os.path.commonprefix((app.config['DATA_PATH'], dirpath)))
    #        relative_path = dirpath[start+1:]
    #        for dirname in dirnames:
    #            yield ('page.index_page', {'uri': os.path.join(relative_path, dirname)})

    #@freezer.register_generator
    #def page_uri():
    #    # uri_index will be used so just avoid showing a warning
    #    return [
    #            ('public.page_uri', {'uri': ''}),
    #            ]
    @freezer.register_generator
    def uri_index():
        def cleanup_url(url):
            url = url.strip()
            if url.startswith('/'):
                if url.endswith('/index.html'):
                    return url
                elif url.endswith('/'):
                    url = url.strip('/')
                    if len(url) == 0:
                        return ('public.index', {})
                    return ('public.uri_index', {'uri': url})

        try:
            result = db.execute(text(fetch_query_string('select_paths_to_freeze.sql'))).fetchall()
        except (DatabaseError, StatementError) as err:
            app.logger.error("DatabaseError: %s", err)
            return []
        urls = filter(None, map(lambda x:cleanup_url(x[0]), result))

        urls_file = app.config.get('URLS_FILE', None)
        if urls_file:
            urls_file = urls_file if urls_file[0] == os.sep else os.path.join(os.getcwd(), urls_file)
            f = open(urls_file, 'r')
            urls.extend(filter(None, map(cleanup_url, f.readlines())))
            f.close()

        return urls


    @freezer.register_generator
    def send_root_file():
        root_folder = app.config.get('ROOT_FOLDER', None)
        if root_folder and os.path.isdir( root_folder ):
            for (dirpath, dirnames, filenames) in os.walk(root_folder, topdown=True):
                start = len(os.path.commonprefix((root_folder, dirpath)))
                relative_path = dirpath[start+1:]
                for filename in filenames:
                    yield ('send_root_file', {
                            'filename': os.path.join(relative_path, filename)
                            })

    @freezer.register_generator
    def send_media_file():
        media_folder = app.config.get('MEDIA_FOLDER', None)
        media_path = app.config.get('MEDIA_PATH', '/media/')
        freeze_all_files = app.config.get('MEDIA_FREEZE_ALL', False)
        if media_folder and freeze_all_files and os.path.isdir( media_folder ) and media_path[0] == '/':
            for (dirpath, dirnames, filenames) in os.walk(media_folder, topdown=True):
                start = len(os.path.commonprefix((media_folder, dirpath)))
                relative_path = dirpath[start+1:]
                for filename in filenames:
                    yield ('send_media_file', {
                            'filename': os.path.join(relative_path, filename)
                            })

    @freezer.register_generator
    def send_theme_file():
        theme_static_folder = app.config.get('THEME_STATIC_FOLDER', None)
        theme_static_path = app.config.get('THEME_STATIC_PATH', '/theme/')
        if theme_static_folder and os.path.isdir( theme_static_folder ) and theme_static_path[0] == '/':
            for (dirpath, dirnames, filenames) in os.walk(theme_static_folder, topdown=True):
                start = len(os.path.commonprefix((theme_static_folder, dirpath)))
                relative_path = dirpath[start+1:]
                for filename in filenames:
                    yield ('send_theme_file', {
                            'filename': os.path.join(relative_path, filename)
                            })


    freezer.freeze()
449293
def is_ready(self, key):
        """"""
        if self.pending_callbacks is None or key not in self.pending_callbacks:
            raise UnknownKeyError("key %r is not pending" % (key,))
        return key in self.results
105616
def _lock(self):
        """"""
        if not self.locked:
            try:
                self.device.cu.lock()
                self.locked = True
            except JnprLockError as jle:
                raise LockError(py23_compat.text_type(jle))
1221413
def should_register(self, app):
        
        if self.only_if is None:
            return True
        elif callable(self.only_if):
            return self.only_if(app)
        return bool(self.only_if)
293588
def start_app(app_id, is_finished=False):
    
    state = constant.STATE_APP_RUNNING if is_finished else constant.STATE_APP_STARTING
    app_update_state(app_id, state)