text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.server.remotetask;

import com.facebook.presto.execution.StateMachine;
import com.facebook.presto.execution.TaskId;
import com.facebook.presto.execution.TaskInfo;
import com.facebook.presto.execution.TaskStatus;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import io.airlift.concurrent.SetThreadName;
import io.airlift.http.client.FullJsonResponseHandler;
import io.airlift.http.client.HttpClient;
import io.airlift.http.client.HttpUriBuilder;
import io.airlift.http.client.Request;
import io.airlift.json.JsonCodec;
import io.airlift.log.Logger;
import io.airlift.units.Duration;

import javax.annotation.concurrent.GuardedBy;

import java.net.URI;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

import static com.google.common.net.HttpHeaders.CONTENT_TYPE;
import static com.google.common.net.MediaType.JSON_UTF_8;
import static io.airlift.http.client.FullJsonResponseHandler.createFullJsonResponseHandler;
import static io.airlift.http.client.HttpUriBuilder.uriBuilderFrom;
import static io.airlift.http.client.Request.Builder.prepareGet;
import static io.airlift.units.Duration.nanosSince;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

public class TaskInfoFetcher
        implements SimpleHttpResponseCallback<TaskInfo>
{
    private static final Logger log = Logger.get(TaskInfoFetcher.class);

    private final TaskId taskId;
    private final Consumer<Throwable> onFail;
    private final StateMachine<TaskInfo> taskInfo;
    private final JsonCodec<TaskInfo> taskInfoCodec;

    private final long updateIntervalMillis;
    private final AtomicLong lastUpdateNanos = new AtomicLong();
    private final ScheduledExecutorService updateScheduledExecutor;

    private final Executor executor;
    private final HttpClient httpClient;
    private final RequestErrorTracker errorTracker;

    @GuardedBy("this")
    private final AtomicLong currentRequestStartNanos = new AtomicLong();

    @GuardedBy("this")
    private final AtomicReference<TaskStatus> taskStatusDone = new AtomicReference();

    @GuardedBy("this")
    private final AtomicBoolean lastRequest = new AtomicBoolean();

    private final RemoteTaskStats stats;

    @GuardedBy("this")
    private boolean running;

    @GuardedBy("this")
    private ScheduledFuture<?> scheduledFuture;

    @GuardedBy("this")
    private ListenableFuture<FullJsonResponseHandler.JsonResponse<TaskInfo>> future;

    public TaskInfoFetcher(
            Consumer<Throwable> onFail,
            TaskInfo initialTask,
            HttpClient httpClient,
            Duration updateInterval,
            JsonCodec<TaskInfo> taskInfoCodec,
            Duration minErrorDuration,
            Executor executor,
            ScheduledExecutorService updateScheduledExecutor,
            ScheduledExecutorService errorScheduledExecutor,
            RemoteTaskStats stats)
    {
        requireNonNull(initialTask, "initialTask is null");
        requireNonNull(minErrorDuration, "minErrorDuration is null");
        requireNonNull(errorScheduledExecutor, "errorScheduledExecutor is null");

        this.taskId = initialTask.getTaskStatus().getTaskId();
        this.onFail = requireNonNull(onFail, "onFail is null");
        this.taskInfo = new StateMachine<>("task " + taskId, executor, initialTask);
        this.taskInfoCodec = requireNonNull(taskInfoCodec, "taskInfoCodec is null");

        this.updateIntervalMillis = requireNonNull(updateInterval, "updateInterval is null").toMillis();
        this.updateScheduledExecutor = requireNonNull(updateScheduledExecutor, "updateScheduledExecutor is null");
        this.errorTracker = new RequestErrorTracker(taskId, initialTask.getTaskStatus().getSelf(), minErrorDuration, errorScheduledExecutor, "getting info for task");

        this.executor = requireNonNull(executor, "executor is null");
        this.httpClient = requireNonNull(httpClient, "httpClient is null");
        this.stats = requireNonNull(stats, "stats is null");
    }

    public TaskInfo getTaskInfo()
    {
        return taskInfo.get();
    }

    public synchronized void start()
    {
        if (running) {
            // already running
            return;
        }
        running = true;
        scheduleUpdate();
    }

    public synchronized void taskStatusDone(TaskStatus taskStatus)
    {
        taskStatusDone.set(taskStatus);
    }

    private synchronized void stop()
    {
        running = false;
        if (future != null) {
            future.cancel(true);
            future = null;
        }
        scheduledFuture.cancel(true);
    }

    private synchronized void scheduleUpdate()
    {
        scheduledFuture = updateScheduledExecutor.scheduleWithFixedDelay(() -> {
            synchronized (this) {
                // if the previous request still running, don't schedule a new request
                if (future != null && !future.isDone()) {
                    return;
                }
            }
            if (nanosSince(lastUpdateNanos.get()).toMillis() >= updateIntervalMillis) {
                sendNextRequest();
            }
        }, 0, 100, MILLISECONDS);
    }

    private synchronized void sendNextRequest()
    {
        TaskStatus taskStatus = getTaskInfo().getTaskStatus();

        if (!running) {
            return;
        }

        // we already have the final task info
        if (isDone(getTaskInfo())) {
            stop();
            return;
        }

        // if we have an outstanding request
        if (future != null && !future.isDone()) {
            return;
        }

        if (taskStatusDone.get() != null) {
            lastRequest.set(true);
        }

        // if throttled due to error, asynchronously wait for timeout and try again
        ListenableFuture<?> errorRateLimit = errorTracker.acquireRequestPermit();
        if (!errorRateLimit.isDone()) {
            errorRateLimit.addListener(this::sendNextRequest, executor);
            return;
        }

        HttpUriBuilder httpUriBuilder = uriBuilderFrom(taskStatus.getSelf());
        // if this is the last request, don't summarize, get the complete taskInfo
        URI uri = lastRequest.get() ? httpUriBuilder.build() : httpUriBuilder.addParameter("summarize").build();

        Request request = prepareGet()
                .setUri(uri)
                .setHeader(CONTENT_TYPE, JSON_UTF_8.toString())
                .build();

        errorTracker.startRequest();
        future = httpClient.executeAsync(request, createFullJsonResponseHandler(taskInfoCodec));
        currentRequestStartNanos.set(System.nanoTime());
        Futures.addCallback(future, new SimpleHttpResponseHandler<>(this, request.getUri(), stats), executor);
    }

    synchronized void updateTaskInfo(TaskInfo newValue)
    {
        taskInfo.setIf(newValue, oldValue -> {
            TaskStatus oldTaskStatus = oldValue.getTaskStatus();
            TaskStatus newTaskStatus = newValue.getTaskStatus();
            if (oldTaskStatus.getState().isDone()) {
                // never update if the task has reached a terminal state
                return false;
            }
            // don't update to an older version (same version is ok)
            return newTaskStatus.getVersion() >= oldTaskStatus.getVersion();
        });
    }

    @Override
    public void success(TaskInfo newValue)
    {
        try (SetThreadName ignored = new SetThreadName("TaskInfoFetcher-%s", taskId)) {
            lastUpdateNanos.set(System.nanoTime());
            updateStats(currentRequestStartNanos.get());

            errorTracker.requestSucceeded();
            updateTaskInfo(newValue);

            // if taskStatus is done, and the newValue that we got is also done,
            // we have the final task info so we can stop
            if (lastRequest.get() && !newValue.getTaskStatus().getState().isDone()) {
                log.error("%s taskStatus done but taskInfo is not", taskId);

                // Since the task is already done, update the task status
                updateTaskInfo(taskInfo.get().withTaskStatus(taskStatusDone.get()));
            }

            if (lastRequest.get()) {
                stop();
            }
        }
    }

    @Override
    public void failed(Throwable cause)
    {
        try (SetThreadName ignored = new SetThreadName("TaskInfoFetcher-%s", taskId)) {
            lastUpdateNanos.set(System.nanoTime());
            updateStats(currentRequestStartNanos.get());

            try {
                // if task not already done, record error
                if (!isDone(getTaskInfo())) {
                    errorTracker.requestFailed(cause);
                }
            }
            catch (Error e) {
                // if task status is already done, ignore this failure, update the task status and stop fetching
                if (taskStatusDone.get() != null) {
                    updateTaskInfo(taskInfo.get().withTaskStatus(taskStatusDone.get()));
                    stop();
                }
                onFail.accept(e);
                throw e;
            }
            catch (RuntimeException e) {
                onFail.accept(e);
            }
        }
    }

    @Override
    public void fatal(Throwable cause)
    {
        try (SetThreadName ignored = new SetThreadName("TaskInfoFetcher-%s", taskId)) {
            // if task status is already done, ignore this failure, update the task status and stop fetching
            if (taskStatusDone.get() != null) {
                updateTaskInfo(taskInfo.get().withTaskStatus(taskStatusDone.get()));
                stop();
            }
            updateStats(currentRequestStartNanos.get());
            onFail.accept(cause);
        }
    }

    private void updateStats(long currentRequestStartNanos)
    {
        stats.infoRoundTripMillis(nanosSince(currentRequestStartNanos).toMillis());
    }

    private static boolean isDone(TaskInfo taskInfo)
    {
        return taskInfo.getTaskStatus().getState().isDone();
    }
}


text:
@interface BNRDatePickerViewController ()
@property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;

@end

@implementation BNRDatePickerViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.datePicker.date = self.item.dateCreated;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

//    self.item.dateCreated = self.datePicker.date;
}

@end

redpajama_set_name: RedPajamaGithub


text:
.. _datasets:

Datasets Overview
#################

.. sidebar:: Contributing datasets to MNE-Python

    Do not hesitate to contact MNE-Python developers on the
    `MNE mailing list <http://mail.nmr.mgh.harvard.edu/mailman/listinfo/mne_analysis>`_
    to discuss the possibility of adding more publicly available datasets.

All the dataset fetchers are available in :mod:`mne.datasets`. To download any of the datasets,
use the ``data_path`` (fetches full dataset) or the ``load_data`` (fetches dataset partially) functions.

All fetchers will check the default download location first to see if the dataset
is already on your computer, and only download it if necessary. The default
download location is also configurable; see the documentation of any of the
``data_path`` functions for more information.

.. contents:: Available datasets
   :local:
   :depth: 2

.. _sample-dataset:

Sample
======
:func:`mne.datasets.sample.data_path`

These data were acquired with the Neuromag
Vectorview system at MGH/HMS/MIT Athinoula A. Martinos Center Biomedical
Imaging. EEG data from a 60-channel electrode cap was acquired simultaneously with
the MEG. The original MRI data set was acquired with a Siemens 1.5 T
Sonata scanner using an MPRAGE sequence.

.. note:: These data are provided solely for the purpose of getting familiar
          with the MNE software. The data should not be used to evaluate the
          performance of the MEG or MRI system employed.

In this experiment, checkerboard patterns were presented to the subject
into the left and right visual field, interspersed by tones to the
left or right ear. The interval between the stimuli was 750 ms. Occasionally
a smiley face was presented at the center of the visual field.
The subject was asked to press a key with the right index finger
as soon as possible after the appearance of the face.

.. table:: Trigger codes for the sample data set.

    =========  =====  ==========================================
    Name              Contents
    =========  =====  ==========================================
    LA         1      Response to left-ear auditory stimulus
    RA         2      Response to right-ear auditory stimulus
    LV         3      Response to left visual field stimulus
    RV         4      Response to right visual field stimulus
    smiley     5      Response to the smiley face
    button     32     Response triggered by the button press
    =========  =====  ==========================================

Contents of the data set
^^^^^^^^^^^^^^^^^^^^^^^^

The sample data set contains two main directories: ``MEG/sample`` (the MEG/EEG
data) and ``subjects/sample`` (the MRI reconstructions).
In addition to subject ``sample``, the MRI surface reconstructions from another
subject, morph, are provided to demonstrate morphing capabilities.

.. table:: Contents of the MEG/sample directory.

    ========================  =====================================================================
    File                      Contents
    ========================  =====================================================================
    sample/audvis_raw.fif     The raw MEG/EEG data
    audvis.ave                A template script for off-line averaging
    auvis.cov                 A template script for the computation of a noise-covariance matrix
    ========================  =====================================================================

.. table:: Overview of the contents of the subjects/sample directory.

    =======================  ======================================================================
    File / directory         Contents
    =======================  ======================================================================
    bem                      Directory for the forward modelling data
    bem/watershed            BEM surface segmentation data computed with the watershed algorithm
    bem/inner_skull.surf     Inner skull surface for BEM
    bem/outer_skull.surf     Outer skull surface for BEM
    bem/outer_skin.surf      Skin surface for BEM
    sample-head.fif          Skin surface in fif format for mne_analyze visualizations
    surf                     Surface reconstructions
    mri/T1                   The T1-weighted MRI data employed in visualizations
    =======================  ======================================================================

The following preprocessing steps have been already accomplished
in the sample data set:

- The MRI surface reconstructions have
  been computed using the FreeSurfer software.

- The BEM surfaces have been created with the watershed algorithm,
  see :ref:`bem_watershed_algorithm`.

The **sample** dataset is distributed with :ref:`fsaverage` for convenience.

Brainstorm
==========
Dataset fetchers for three Brainstorm tutorials are available. Users must agree to the
license terms of these datasets before downloading them. These files are recorded in a CTF 275 system
and are provided in native CTF format (.ds files).

Auditory
^^^^^^^^
:func:`mne.datasets.brainstorm.bst_raw.data_path`.

Details about the data can be found at the Brainstorm `auditory dataset tutorial`_.

.. topic:: Examples

    * :ref:`tut-brainstorm-auditory`: Partially replicates the original Brainstorm tutorial.

Resting state
^^^^^^^^^^^^^
:func:`mne.datasets.brainstorm.bst_resting.data_path`

Details can be found at the Brainstorm `resting state dataset tutorial`_.

.. topic:: Examples

    * :ref:`ex-envelope-correlation`

Median nerve
^^^^^^^^^^^^
:func:`mne.datasets.brainstorm.bst_raw.data_path`

Details can be found at the Brainstorm `median nerve dataset tutorial`_.

.. topic:: Examples

    * :ref:`ex-brainstorm-raw`

SPM faces
=========
:func:`mne.datasets.spm_face.data_path`

The `SPM faces dataset`_ contains EEG, MEG and fMRI recordings on face perception.

.. topic:: Examples

    * :ref:`ex-spm-faces` Full pipeline including artifact removal, epochs averaging, forward model computation and source reconstruction using dSPM on the contrast: "faces - scrambled".

EEGBCI motor imagery
====================
:func:`mne.datasets.eegbci.load_data`

The EEGBCI dataset is documented in :footcite:`SchalkEtAl2004`. The data set is
available at PhysioNet :footcite:`GoldbergerEtAl2000`. The dataset contains
64-channel EEG recordings from 109 subjects and 14 runs on each subject in EDF+
format. The recordings were made using the BCI2000 system. To load a subject,
do::

    from mne.io import concatenate_raws, read_raw_edf
    from mne.datasets import eegbci
    raw_fnames = eegbci.load_data(subject, runs)
    raws = [read_raw_edf(f, preload=True) for f in raw_fnames]
    raw = concatenate_raws(raws)

.. topic:: Examples

    * :ref:`ex-decoding-csp-eeg`

.. _somato-dataset:

Somatosensory
=============
:func:`mne.datasets.somato.data_path`

This dataset contains somatosensory data with event-related synchronizations
(ERS) and desynchronizations (ERD).

.. topic:: Examples

    * :ref:`tut-sensors-time-freq`
    * :ref:`ex-inverse-source-power`
    * :ref:`ex-time-freq-global-field-power`

Multimodal
==========
:func:`mne.datasets.multimodal.data_path`

This dataset contains a single subject recorded at Otaniemi (Aalto University)
with auditory, visual, and somatosensory stimuli.

.. topic:: Examples

    * :ref:`ex-io-ave-fiff`

.. _fnirs-motor-dataset:

fNIRS motor
===========
:func:`mne.datasets.fnirs_motor.data_path`

This dataset contains a single subject recorded at Macquarie University.
It has optodes placed over the motor cortex. There are three conditions:

- tapping the left thumb to fingers
- tapping the right thumb to fingers
- a control where nothing happens

The tapping lasts 5 seconds, and there are 30 trials of each condition.

.. topic:: Examples

    * :ref:`tut-fnirs-processing`

High frequency SEF
==================
:func:`mne.datasets.hf_sef.data_path()`

This dataset contains somatosensory evoked fields (median nerve stimulation)
with thousands of epochs. It was recorded with an Elekta TRIUX MEG device at
a sampling frequency of 3 kHz. The dataset is suitable for investigating
high-frequency somatosensory responses. Data from two subjects are included
with MRI images in DICOM format and FreeSurfer reconstructions.

.. topic:: Examples

    * :ref:`high-frequency SEF responses <ex-hf-sef-data>`.

Visual 92 object categories
===========================
:func:`mne.datasets.visual_92_categories.data_path`.

This dataset is recorded using a 306-channel Neuromag vectorview system.

Experiment consisted in the visual presentation of 92 images of human, animal
and inanimate objects either natural or artificial :footcite:`CichyEtAl2014`.
Given the high number of conditions this dataset is well adapted to an approach
based on Representational Similarity Analysis (RSA).

.. topic:: Examples

    * :ref:`Representational Similarity Analysis (RSA) <ex-rsa-noplot>`: Partially replicates the results from :footcite:`CichyEtAl2014`.

mTRF Dataset
============
:func:`mne.datasets.mtrf.data_path`.

This dataset contains 128 channel EEG as well as natural speech stimulus features,
which is also available `here <https://sourceforge.net/projects/aespa/files/>`_.

The experiment consisted of subjects listening to natural speech.
The dataset contains several feature representations of the speech stimulus,
suitable for using to fit continuous regression models of neural activity.
More details and a description of the package can be found in
:footcite:`CrosseEtAl2016`.

.. topic:: Examples

    * :ref:`Receptive Field Estimation and Prediction <ex-receptive-field-mtrf>`: Partially replicates the results from :footcite:`CrosseEtAl2016`.

.. _kiloword-dataset:

Kiloword dataset
================
:func:`mne.datasets.kiloword.data_path`.

This dataset consists of averaged EEG data from 75 subjects performing a
lexical decision task on 960 English words :footcite:`DufauEtAl2015`. The words
are richly annotated, and can be used for e.g. multiple regression estimation
of EEG correlates of printed word processing.

4D Neuroimaging / BTi dataset
=============================
:func:`mne.datasets.phantom_4dbti.data_path`.

This dataset was obtained with a phantom on a 4D Neuroimaging / BTi system at
the MEG center in La Timone hospital in Marseille.

.. topic:: Examples

    * :ref:`tut_phantom_4Dbti`

OPM
===
:func:`mne.datasets.opm.data_path`

OPM data acquired using an Elekta DACQ, simply piping the data into Elekta
magnetometer channels. The FIF files thus appear to come from a TRIUX system
that is only acquiring a small number of magnetometer channels instead of the
whole array.

The OPM ``coil_type`` is custom, requiring a custom ``coil_def.dat``.
The new ``coil_type`` is 9999.

OPM co-registration differs a bit from the typical SQUID-MEG workflow.
No ``-trans.fif`` file is needed for the OPMs, the FIF files include proper
sensor locations in MRI coordinates and no digitization of RPA/LPA/Nasion.
Thus the MEG<->Head coordinate transform is taken to be an identity matrix
(i.e., everything is in MRI coordinates), even though this mis-identifies
the head coordinate frame (which is defined by the relationship of the
LPA, RPA, and Nasion).

Triggers include:

* Median nerve stimulation: trigger value 257.
* Magnetic trigger (in OPM measurement only): trigger value 260.
  1 second before the median nerve stimulation, a magnetic trigger is piped into the MSR.
  This was to be able to check the synchronization between OPMs retrospectively, as each
  sensor runs on an independent clock. Synchronization turned out to be satisfactory.

.. topic:: Examples

    * :ref:`ex-opm-somatosensory`
    * :ref:`ex-opm-resting-state`

The Sleep PolySomnoGraphic Database
===================================
:func:`mne.datasets.sleep_physionet.age.fetch_data`
:func:`mne.datasets.sleep_physionet.temazepam.fetch_data`

The sleep PhysioNet database contains 197 whole-night PolySomnoGraphic sleep
recordings, containing EEG, EOG, chin EMG, and event markers. Some records also
contain respiration and body temperature. Corresponding hypnograms (sleep
patterns) were manually scored by well-trained technicians according to the
Rechtschaffen and Kales manual, and are also available. If you use these
data please cite :footcite:`KempEtAl2000` and :footcite:`GoldbergerEtAl2000`.

.. topic:: Examples

    * :ref:`tut-sleep-stage-classif`

Miscellaneous Datasets
======================
These datasets are used for specific purposes in the documentation and in
general are not useful for separate analyses.

.. _fsaverage:

fsaverage
^^^^^^^^^
:func:`mne.datasets.fetch_fsaverage`

For convenience, we provide a function to separately download and extract the
(or update an existing) fsaverage subject.

.. topic:: Examples

    :ref:`tut-eeg-fsaverage-source-modeling`

ECoG Dataset
^^^^^^^^^^^^
:func:`mne.datasets.misc.data_path`. Data exists at ``/ecog/sample_ecog.mat``.

This dataset contains a sample Electrocorticography (ECoG) dataset. It includes
a single grid of electrodes placed over the temporal lobe during an auditory
listening task. This dataset is primarily used to demonstrate visualization
functions in MNE and does not contain useful metadata for analysis.

.. topic:: Examples

    * :ref:`How to convert 3D electrode positions to a 2D image.
      <ex-electrode-pos-2d>`: Demonstrates
      how to project a 3D electrode location onto a 2D image, a common procedure
      in electrocorticography.

.. _limo-dataset:

LIMO Dataset
^^^^^^^^^^^^
:func:`mne.datasets.limo.load_data`.

In the original LIMO experiment (see :footcite:`RousseletEtAl2010`), participants
performed a
two-alternative forced choice task, discriminating between two face stimuli.
Subjects discriminated the same two faces during the whole experiment.
The critical manipulation consisted of the level of noise added to the
face-stimuli during the task, making the faces more or less discernible to the
observer.

The presented faces varied across a noise-signal (or phase-coherence) continuum
spanning from 0 to 100% in increasing steps of 10%. In other words, faces with
high phase-coherence (e.g., 90%) were easy to identify, while faces with low
phase-coherence (e.g., 10%) were hard to identify and by extension hard to
discriminate.

.. topic:: Examples

    * :ref:`Single trial linear regression analysis with the LIMO dataset
      <ex-limo-data>`: Explores data from a single subject of the LIMO dataset
      and demonstrates how to fit a single trial linear regression using the
      information contained in the metadata of the individual datasets.

References
==========

.. footbibliography::

.. LINKS

.. _auditory dataset tutorial: https://neuroimage.usc.edu/brainstorm/DatasetAuditory
.. _resting state dataset tutorial: https://neuroimage.usc.edu/brainstorm/DatasetResting
.. _median nerve dataset tutorial: https://neuroimage.usc.edu/brainstorm/DatasetMedianNerveCtf
.. _SPM faces dataset: https://www.fil.ion.ucl.ac.uk/spm/data/mmfaces/

Reference channel noise MEG data set
====================================
:func:`mne.datasets.refmeg_noise.data_path`.

This dataset was obtained with a 4D Neuroimaging / BTi system at
the University Clinic - Erlangen, Germany. There are powerful bursts of
external magnetic noise throughout the recording, which make it a good
example for automatic noise removal techniques.

.. topic:: Examples

    * :ref:`ex-megnoise_processing`


text:
<link rel="import" href="../../components/polymer/polymer.html">

<polymer-element name="users-page" attributes="userId">
  <template>

This is the users page

You've selected the user: {{userId}}

    <core-icon icon="face"></core-icon>

    <paper-fab icon="send" on-click="{{goToNextPage}}">

    </paper-fab>
  </template>

</polymer-element>


text:
package de.douglas.maven.plugin.rpmsystemd.rpm;

public class DirectoryConfiguration {

    private String directory;
    private String user;
    private String group;

    public String getDirectory() {
        return directory;
    }

    public void setDirectory(String directory) {
        this.directory = directory;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getGroup() {
        return group;
    }

    public void setGroup(String group) {
        this.group = group;
    }
}


text:
/*
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     (1) Redistributions of source code must retain the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer.
 *
 *     (2) Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *
 *     (3) Neither the name of the copyright holder nor the names of
 *     its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written
 *     permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#pragma once

#ifdef HAVE_CONFIG_H
    #include "ac_config.h"
#endif
#include <pthread.h>
#include <stdlib.h>

#ifdef __APPLE__
    #include <libkern/OSAtomic.h>
#endif

class MutexGuard {
public:
        MutexGuard()
        {
		if (pthread_mutex_init(&mutex_, NULL))
			abort();
        };

        ~MutexGuard()
        {
                pthread_mutex_destroy(&mutex_);
        };

        int enter(void)
        {
                return pthread_mutex_lock(&mutex_);
        };

        int try_enter(void)
        {
                return pthread_mutex_trylock(&mutex_);
        };

        void leave(void)
        {
                pthread_mutex_unlock(&mutex_);
        };

private:
        pthread_mutex_t mutex_;
};

#ifdef __linux__

class SpinlockGuard {
public:
        SpinlockGuard()
        {
		if (pthread_spin_init(&spinlock_, PTHREAD_PROCESS_PRIVATE))
			abort();
        };

        ~SpinlockGuard()
        {
		pthread_spin_destroy(&spinlock_);
        };

        int enter(void)
        {
		return pthread_spin_lock(&spinlock_);
        };

        int try_enter(void)
        {
		return pthread_spin_trylock(&spinlock_);
        };

        void leave(void)
        {
		pthread_spin_unlock(&spinlock_);
        };

private:
	pthread_spinlock_t spin_lock_;
};

#elif defined __APPLE__

class SpinlockGuard {
public:
        SpinlockGuard()
        {
		spinlock_ = OS_SPINLOCK_INIT;
        };

        ~SpinlockGuard()
        {
        };

        int enter(void)
        {
		OSSpinLockLock(&spinlock_);
		return 0;
        };

        int try_enter(void)
        {
		return (OSSpinLockTry(&spinlock_) ? 0 : 1);
        };

        void leave(void)
        {
		OSSpinLockUnlock(&spinlock_);
        };

private:
	OSSpinLock spinlock_;
};

#endif


text:
// ****************************************************************************
// <copyright file="IMessageBoxService.cs" company="Pedro Lamas">
// Copyright © Pedro Lamas 2011
// </copyright>
// ****************************************************************************
// <author>Pedro Lamas</author>
// <email>pedrolamas@gmail.com</email>
// <date>17-11-2011</date>
// <project>Cimbalino.Phone.Toolkit</project>
// <web>http://www.pedrolamas.com</web>
// <license>
// See license.txt in this solution or http://www.pedrolamas.com/license_MIT.txt
// </license>
// ****************************************************************************

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;

namespace Cimbalino.Phone.Toolkit.Services
{
    /// <summary>
    /// Represents a service capable of showing message boxes.
    /// </summary>
    public interface IMessageBoxService
    {
        /// <summary>
        /// Displays a message box that contains the specified text and an OK button.
        /// </summary>
        /// <param name="text">The message to display.</param>
        void Show(string text);

        /// <summary>
        /// Displays a message box that contains the specified text, title bar caption, and an OK button.
        /// </summary>
        /// <param name="text">The message to display.</param>
        /// <param name="caption">The title of the message box.</param>
        void Show(string text, string caption);

        /// <summary>
        /// Displays a message box that contains the specified text, title bar caption, and response buttons.
        /// </summary>
        /// <param name="text">The message to display.</param>
        /// <param name="caption">The title of the message box.</param>
        /// <param name="button">A value that indicates the button or buttons to display.</param>
        /// <returns>A value that indicates the user's response to the message.</returns>
        MessageBoxResult Show(string text, string caption, MessageBoxButton button);

        /// <summary>
        /// Displays a message box that contains the specified text, title bar caption, and response buttons.
        /// </summary>
        /// <param name="text">The message to display.</param>
        /// <param name="caption">The title of the message box.</param>
        /// <param name="buttons">The captions for message box buttons. The maximum number of buttons is two.</param>
        /// <param name="selectedButton">The <see cref="Action{Int32}"/> to be called once the operation is finished.</param>
        void Show(string text, string caption, IEnumerable<string> buttons, Action<int> selectedButton);

        /// <summary>
        /// Displays a message box that contains the specified text, title bar caption, and response buttons.
        /// </summary>
        /// <param name="text">The message to display.</param>
        /// <param name="caption">The title of the message box.</param>
        /// <param name="buttons">The captions for message box buttons. The maximum number of buttons is two.</param>
        /// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns>
        Task<int> ShowAsync(string text, string caption, IEnumerable<string> buttons);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="Encoding">
    <file url="file://$PROJECT_DIR$" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/api-gateway" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/common" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/config-client-service" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/config-server" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/eureka-service" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/gateway-service" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/monitoring-service" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/order-service" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/qrcode-service" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/ribbon-service" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/ucenter-service" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/zipkin-client" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/zipkin-server" charset="UTF-8" />
  </component>
</project>


text:
import { assertEquals, assertRejects } from '../deps/asserts.ts'
import { readAll, readerFromStreamReader } from '../deps/stream.ts'
import { dirname, basename, join } from '../deps/path.ts'
import { BIDSFileDeno, UnicodeDecodeError } from './deno.ts'
import { requestReadPermission } from '../setup/requestPermissions.ts'
import { FileIgnoreRulesDeno } from './ignore.ts'

await requestReadPermission()

// Use this file for testing file behavior
const testUrl = import.meta.url
const testPath = testUrl.slice('file://'.length)
const testDir = dirname(testPath)
const testFilename = basename(testPath)
const ignore = new FileIgnoreRulesDeno([])

Deno.test('Deno implementation of BIDSFile', async t => {
  await t.step('implements basic file properties', () => {
    const file = new BIDSFileDeno(testDir, testFilename, ignore)
    assertEquals(join(testDir, file.path), testPath)
  })
  await t.step('implements correct file size', async () => {
    const { size } = await Deno.stat(testPath)
    const file = new BIDSFileDeno(testDir, testFilename, ignore)
    assertEquals(await file.size, size)
  })
  await t.step('can be read as ReadableStream', async () => {
    const file = new BIDSFileDeno(testDir, testFilename, ignore)
    const stream = file.stream
    const streamReader = stream.getReader()
    const denoReader = readerFromStreamReader(streamReader)
    const fileBuffer = await readAll(denoReader)
    assertEquals(await file.size, fileBuffer.length)
  })
  await t.step('can be read with .text() method', async () => {
    const file = new BIDSFileDeno(testDir, testFilename, ignore)
    const text = await file.text()
    assertEquals(await file.size, text.length)
  })
  await t.step(
    'throws UnicodeDecodeError when reading a UTF-16 file with text() method',
    async () => {
      // BOM is invalid in JSON but shows up often from certain tools, so abstract handling it
      const bomDir = join(testPath, '..', '..', 'tests')
      const bomFilename = 'bom-utf16.tsv'
      const file = new BIDSFileDeno(bomDir, bomFilename, ignore)
      await assertRejects(async () => file.text(), UnicodeDecodeError)
  })
  await t.step(
    'strips BOM characters when reading UTF-8 via .text()',
    async () => {
      // BOM is invalid in JSON but shows up often from certain tools, so abstract handling it
      const bomDir = join(testPath, '..', '..', 'tests')
      const bomFilename = 'bom-utf8.json'
      const file = new BIDSFileDeno(bomDir, bomFilename, ignore)
      const text = await file.text()
      assertEquals(text, '{\n  "example": "JSON for test suite"\n}\n')
    },
  )
})


text:
function shake(div) {
    var interval = 80; var dist = 8; var times = 4; div.css('position', 'relative');
    for (var i = 0; i < times + 1; i++) div.animate({ left: ((i % 2 == 0 ? dist : dist * -1)) }, interval);
    div.animate({ left: 0 }, interval);
}


text:
id: 587d7b8f367417b2b2512b61
title: Use the map Method to Extract Data from an Array
challengeType: 1
---

## Description

So far we have learned to use pure functions to avoid side effects in a program. Also, we have seen the value in having a function only depend on its input arguments.
This is only the beginning. As its name suggests, functional programming is centered around a theory of functions.
It would make sense to be able to pass them as arguments to other functions, and return a function from another function. Functions are considered First Class Objects in JavaScript, which means they can be used like any other object. They can be saved in variables, stored in an object, or passed as function arguments.
Let's start with some simple array functions, which are methods on the array object prototype. In this exercise we are looking at Array.prototype.map(), or more simply map.
Remember that the map method is a way to iterate over each item in an array. It creates a new array (without changing the original one) after applying a callback function to every element.

## Instructions

The watchList array holds objects with information on several movies. Use map to pull the title and rating from watchList and save the new array in the rating variable. The code in the editor currently uses a for loop to do this, replace the loop functionality with your map expression.

## Tests

```yml
tests:
  - text: The <code>watchList</code> variable should not change.
    testString: assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron", 'The <code>watchList</code> variable should not change.');
  - text: Your code should not use a <code>for</code> loop.
    testString: assert(!code.match(/for\s*?\(.+?\)/g), 'Your code should not use a <code>for</code> loop.');
  - text: Your code should use the <code>map</code> method.
    testString: assert(code.match(/\.map/g), 'Your code should use the <code>map</code> method.');
  - text: <code>rating</code> should equal <code>[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]</code>.
    testString: assert(JSON.stringify(rating) === JSON.stringify([{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]), '<code>rating</code> should equal <code>[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]</code>.');

```

## Challenge Seed

```js
// the global variable
var watchList = [
                 {
                   "Title": "Inception",
                   "Year": "2010",
                   "Rated": "PG-13",
                   "Released": "16 Jul 2010",
                   "Runtime": "148 min",
                   "Genre": "Action, Adventure, Crime",
                   "Director": "Christopher Nolan",
                   "Writer": "Christopher Nolan",
                   "Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
                   "Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
                   "Language": "English, Japanese, French",
                   "Country": "USA, UK",
                   "Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.8",
                   "imdbVotes": "1,446,708",
                   "imdbID": "tt1375666",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "Interstellar",
                   "Year": "2014",
                   "Rated": "PG-13",
                   "Released": "07 Nov 2014",
                   "Runtime": "169 min",
                   "Genre": "Adventure, Drama, Sci-Fi",
                   "Director": "Christopher Nolan",
                   "Writer": "Jonathan Nolan, Christopher Nolan",
                   "Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
                   "Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
                   "Language": "English",
                   "Country": "USA, UK",
                   "Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.6",
                   "imdbVotes": "910,366",
                   "imdbID": "tt0816692",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "The Dark Knight",
                   "Year": "2008",
                   "Rated": "PG-13",
                   "Released": "18 Jul 2008",
                   "Runtime": "152 min",
                   "Genre": "Action, Adventure, Crime",
                   "Director": "Christopher Nolan",
                   "Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
                   "Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
                   "Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
                   "Language": "English, Mandarin",
                   "Country": "USA, UK",
                   "Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
                   "Metascore": "82",
                   "imdbRating": "9.0",
                   "imdbVotes": "1,652,832",
                   "imdbID": "tt0468569",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "Batman Begins",
                   "Year": "2005",
                   "Rated": "PG-13",
                   "Released": "15 Jun 2005",
                   "Runtime": "140 min",
                   "Genre": "Action, Adventure",
                   "Director": "Christopher Nolan",
                   "Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
                   "Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
                   "Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
                   "Language": "English, Urdu, Mandarin",
                   "Country": "USA, UK",
                   "Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
                   "Metascore": "70",
                   "imdbRating": "8.3",
                   "imdbVotes": "972,584",
                   "imdbID": "tt0372784",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "Avatar",
                   "Year": "2009",
                   "Rated": "PG-13",
                   "Released": "18 Dec 2009",
                   "Runtime": "162 min",
                   "Genre": "Action, Adventure, Fantasy",
                   "Director": "James Cameron",
                   "Writer": "James Cameron",
                   "Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
                   "Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
                   "Language": "English, Spanish",
                   "Country": "USA, UK",
                   "Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
                   "Metascore": "83",
                   "imdbRating": "7.9",
                   "imdbVotes": "876,575",
                   "imdbID": "tt0499549",
                   "Type": "movie",
                   "Response": "True"
                }
];

// Add your code below this line

var rating = [];
for(var i=0; i < watchList.length; i++){
  rating.push({title: watchList[i]["Title"],  rating: watchList[i]["imdbRating"]});
}

// Add your code above this line

console.log(JSON.stringify(rating));
```

## Solution

```js
// the global variable
var watchList = [
                 {
                   "Title": "Inception",
                   "Year": "2010",
                   "Rated": "PG-13",
                   "Released": "16 Jul 2010",
                   "Runtime": "148 min",
                   "Genre": "Action, Adventure, Crime",
                   "Director": "Christopher Nolan",
                   "Writer": "Christopher Nolan",
                   "Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
                   "Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
                   "Language": "English, Japanese, French",
                   "Country": "USA, UK",
                   "Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.8",
                   "imdbVotes": "1,446,708",
                   "imdbID": "tt1375666",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "Interstellar",
                   "Year": "2014",
                   "Rated": "PG-13",
                   "Released": "07 Nov 2014",
                   "Runtime": "169 min",
                   "Genre": "Adventure, Drama, Sci-Fi",
                   "Director": "Christopher Nolan",
                   "Writer": "Jonathan Nolan, Christopher Nolan",
                   "Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
                   "Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
                   "Language": "English",
                   "Country": "USA, UK",
                   "Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.6",
                   "imdbVotes": "910,366",
                   "imdbID": "tt0816692",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "The Dark Knight",
                   "Year": "2008",
                   "Rated": "PG-13",
                   "Released": "18 Jul 2008",
                   "Runtime": "152 min",
                   "Genre": "Action, Adventure, Crime",
                   "Director": "Christopher Nolan",
                   "Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
                   "Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
                   "Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
                   "Language": "English, Mandarin",
                   "Country": "USA, UK",
                   "Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
                   "Metascore": "82",
                   "imdbRating": "9.0",
                   "imdbVotes": "1,652,832",
                   "imdbID": "tt0468569",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "Batman Begins",
                   "Year": "2005",
                   "Rated": "PG-13",
                   "Released": "15 Jun 2005",
                   "Runtime": "140 min",
                   "Genre": "Action, Adventure",
                   "Director": "Christopher Nolan",
                   "Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
                   "Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
                   "Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
                   "Language": "English, Urdu, Mandarin",
                   "Country": "USA, UK",
                   "Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
                   "Metascore": "70",
                   "imdbRating": "8.3",
                   "imdbVotes": "972,584",
                   "imdbID": "tt0372784",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "Avatar",
                   "Year": "2009",
                   "Rated": "PG-13",
                   "Released": "18 Dec 2009",
                   "Runtime": "162 min",
                   "Genre": "Action, Adventure, Fantasy",
                   "Director": "James Cameron",
                   "Writer": "James Cameron",
                   "Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
                   "Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
                   "Language": "English, Spanish",
                   "Country": "USA, UK",
                   "Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
                   "Metascore": "83",
                   "imdbRating": "7.9",
                   "imdbVotes": "876,575",
                   "imdbID": "tt0499549",
                   "Type": "movie",
                   "Response": "True"
                }
];

var rating = watchList.map(function(movie) {
  return {
    title: movie["Title"],
    rating: movie["imdbRating"]
  }
});
```


text:
<?php
namespace ChristianBudde\Part\model\user;
use ChristianBudde\Part\controller\ajax\TypeHandlerGenerator;
use ChristianBudde\Part\controller\json\JSONObjectSerializable;
use Iterator;

/**
 * Created by JetBrains PhpStorm.
 * User: budde
 * Date: 22/07/12
 * Time: 14:26
 */
interface UserLibrary extends Iterator, JSONObjectSerializable, TypeHandlerGenerator
{
    /**
     * @abstract
     * Will list all users
     * @return User[]
     */
    public function listUsers();

    /**
     * @abstract
     * Will delete user. The user must be instance in library.
     * @param User $user
     * @return bool
     */
    public function deleteUser(User $user);

    /**
     * @abstract
     * Will create a user, the username must be unique
     * The created instance can be deleted and will be in list
     * from listUsers.
     * @param string $username
     * @param string $password
     * @param string $mail
     * @param User $parent
     * @return User | bool FALSE on failure else instance of User
     */
    public function createUser($username,$password,$mail,User $parent=null);

    /**
     * @abstract
     * @return User | null User logged in else null if no user is logged in.
     */
    public function getUserLoggedIn();

    /**
     * @abstract
     * @param string $username
     * @return User | null User if username is found, else null
     */
    public function getUser($username);

    /**
     * @abstract
     *
     * Parameter must be an instance provided from Library.
     * @param User $user
     * @return User | null Will return User if the user provided has parent, else null.
     */
    public function getParent(User $user);

    /**
     * @abstract
     * Input must be instance of User and an instance provided by the library.
     * @param User $user
     * @return User[] Array containing all children (and children's children) as User instances. Empty array on no children or input not valid.
     */
    public function getChildren(User $user);

    /**
     * Returns the current user settings token.
     * If no user is logged in, the token will be null.
     *
     * @return string
     */
    public function getUserSessionToken();

    /**
     * Will compare the tokens. If no user is logged in all tokens are equally valid. I.e. valid.
     * @param string $token
     * @return string
     */
    public function verifyUserSessionToken($token);

}


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

/*=============================================================================
	TranslucentRendering.h: Translucent rendering definitions.
=============================================================================*/

#pragma once

/**
* Translucent draw policy factory.
* Creates the policies needed for rendering a mesh based on its material
*/
class FTranslucencyDrawingPolicyFactory
{
public:
	enum { bAllowSimpleElements = true };
	struct ContextType
	{
		const FProjectedShadowInfo* TranslucentSelfShadow;
		ETranslucencyPassType TranslucenyPassType;
		bool bSceneColorCopyIsUpToDate;
		bool bPostAA;

		ContextType(const FProjectedShadowInfo* InTranslucentSelfShadow = NULL, ETranslucencyPassType InTranslucenyPassType = TPT_NonSeparateTransluceny, bool bPostAAIn = false)
			: TranslucentSelfShadow(InTranslucentSelfShadow)
			, TranslucenyPassType(InTranslucenyPassType)
			, bSceneColorCopyIsUpToDate(false)
			, bPostAA(bPostAAIn)
		{}
	};

	/**
	* Render a dynamic mesh using a translucent draw policy
	* @return true if the mesh rendered
	*/
	static bool DrawDynamicMesh(
		FRHICommandList& RHICmdList,
		const FViewInfo& View,
		ContextType DrawingContext,
		const FMeshBatch& Mesh,
		bool bBackFace,
		bool bPreFog,
		const FPrimitiveSceneProxy* PrimitiveSceneProxy,
		FHitProxyId HitProxyId
		);

	/**
	* Render a dynamic mesh using a translucent draw policy
	* @return true if the mesh rendered
	*/
	static bool DrawStaticMesh(
		FRHICommandList& RHICmdList,
		const FViewInfo& View,
		ContextType DrawingContext,
		const FStaticMesh& StaticMesh,
		const uint64& BatchElementMask,
		bool bPreFog,
		const FPrimitiveSceneProxy* PrimitiveSceneProxy,
		FHitProxyId HitProxyId
		);

	/**
	* Resolves the scene color target and copies it for use as a source texture.
	*/
	static void CopySceneColor(FRHICommandList& RHICmdList, const FViewInfo& View, const FPrimitiveSceneProxy* PrimitiveSceneProxy);

private:
	/**
	* Render a dynamic or static mesh using a translucent draw policy
	* @return true if the mesh rendered
	*/
	static bool DrawMesh(
		FRHICommandList& RHICmdList,
		const FViewInfo& View,
		ContextType DrawingContext,
		const FMeshBatch& Mesh,
		const uint64& BatchElementMask,
		bool bBackFace,
		float DitheredLODTransitionValue,
		bool bPreFog,
		const FPrimitiveSceneProxy* PrimitiveSceneProxy,
		FHitProxyId HitProxyId
		);

};

/**
* Translucent draw policy factory.
* Creates the policies needed for rendering a mesh based on its material
*/
class FTranslucencyForwardShadingDrawingPolicyFactory
{
public:
	enum { bAllowSimpleElements = true };
	struct ContextType
	{
	};

	/**
	* Render a dynamic mesh using a translucent draw policy
	* @return true if the mesh rendered
	*/
	static bool DrawDynamicMesh(
		FRHICommandList& RHICmdList,
		const FViewInfo& View,
		ContextType DrawingContext,
		const FMeshBatch& Mesh,
		bool bBackFace,
		bool bPreFog,
		const FPrimitiveSceneProxy* PrimitiveSceneProxy,
		FHitProxyId HitProxyId
		);

	/**
	* Render a dynamic mesh using a translucent draw policy
	* @return true if the mesh rendered
	*/
	static bool DrawStaticMesh(
		FRHICommandList& RHICmdList,
		const FViewInfo& View,
		ContextType DrawingContext,
		const FStaticMesh& StaticMesh,
		bool bPreFog,
		const FPrimitiveSceneProxy* PrimitiveSceneProxy,
		FHitProxyId HitProxyId
		);
};

/** Represents a subregion of a volume texture. */
struct FVolumeBounds
{
	int32 MinX, MinY, MinZ;
	int32 MaxX, MaxY, MaxZ;

	FVolumeBounds() :
		MinX(0),
		MinY(0),
		MinZ(0),
		MaxX(0),
		MaxY(0),
		MaxZ(0)
	{}

	FVolumeBounds(int32 Max) :
		MinX(0),
		MinY(0),
		MinZ(0),
		MaxX(Max),
		MaxY(Max),
		MaxZ(Max)
	{}

	bool IsValid() const
	{
		return MaxX > MinX && MaxY > MinY && MaxZ > MinZ;
	}
};

/** Vertex shader used to write to a range of slices of a 3d volume texture. */
class FWriteToSliceVS : public FGlobalShader
{
	DECLARE_SHADER_TYPE(FWriteToSliceVS,Global);
public:

	static bool ShouldCache(EShaderPlatform Platform)
	{
		return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4);
	}

	FWriteToSliceVS(const ShaderMetaType::CompiledShaderInitializerType& Initializer):
		FGlobalShader(Initializer)
	{
		UVScaleBias.Bind(Initializer.ParameterMap, TEXT("UVScaleBias"));
	}

	FWriteToSliceVS() {}

	void SetParameters(FRHICommandList& RHICmdList, const FVolumeBounds& VolumeBounds, uint32 VolumeResolution)
	{
		const float InvVolumeResolution = 1.0f / VolumeResolution;
		SetShaderValue(RHICmdList, GetVertexShader(), UVScaleBias, FVector4(
			(VolumeBounds.MaxX - VolumeBounds.MinX) * InvVolumeResolution,
			(VolumeBounds.MaxY - VolumeBounds.MinY) * InvVolumeResolution,
			VolumeBounds.MinX * InvVolumeResolution,
			VolumeBounds.MinY * InvVolumeResolution));
	}

	virtual bool Serialize(FArchive& Ar) override
	{
		bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
		Ar << UVScaleBias;
		return bShaderHasOutdatedParameters;
	}

private:
	FShaderParameter UVScaleBias;
};

/** Geometry shader used to write to a range of slices of a 3d volume texture. */
class FWriteToSliceGS : public FGlobalShader
{
	DECLARE_SHADER_TYPE(FWriteToSliceGS,Global);
public:

	static bool ShouldCache(EShaderPlatform Platform)
	{
		return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4) && RHISupportsGeometryShaders(Platform);
	}

	FWriteToSliceGS(const ShaderMetaType::CompiledShaderInitializerType& Initializer):
		FGlobalShader(Initializer)
	{
		MinZ.Bind(Initializer.ParameterMap, TEXT("MinZ"));
	}
	FWriteToSliceGS() {}

	void SetParameters(FRHICommandList& RHICmdList, const FVolumeBounds& VolumeBounds)
	{
		SetShaderValue(RHICmdList, GetGeometryShader(), MinZ, VolumeBounds.MinZ);
	}

	virtual bool Serialize(FArchive& Ar) override
	{
		bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
		Ar << MinZ;
		return bShaderHasOutdatedParameters;
	}

private:
	FShaderParameter MinZ;
};

extern void RasterizeToVolumeTexture(FRHICommandList& RHICmdList, FVolumeBounds VolumeBounds);


text:
require 'beaker-rspec/spec_helper'
require 'beaker-rspec/helpers/serverspec'

hosts.each do |host|
  install_puppet
end

RSpec.configure do |c|
  proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..'))

  c.formatter = :documentation

  c.before :suite do
    hosts.each do |host|
      #copy_module_to(host, :source => proj_root, :module_name => 'test')
      puppet_module_install(:source => proj_root, :module_name => 'test')
    end
  end
end


text:
LOGIN_ACTION=PLAY
LOGIN_TOKEN=Test
GAME_USERNAME=Test
GAME_DISL_ID=1
USER_TOONTOWN_ACCESS=FULL
GAME_CHAT_ELIGIBLE=1


text:
<?php
/**
 * Post Module
 *
 * Adds settings to the edit post screen.
 *
 * @author Mike Ems
 * @package WordPressHTTPS
 *
 */

class WordPressHTTPS_Module_Post extends Mvied_Plugin_Module {

	/**
	 * Initialize Module
	 *
	 * @param none
	 * @return void
	 */
	public function init() {
		// Save custom post data
		add_action('save_post', array(&$this, 'post_save'));
		// Add Force SSL checkbox to edit post screen
		add_action('add_meta_boxes', array(&$this, 'add_meta_box_post'));
	}

	/**
	 * Adds HTTPS Settings meta box to post edit screen.
	 * WordPress Hook - add_meta_boxes
	 *
	 * @param none
	 * @return void
	 */
	public function add_meta_box_post() {
		$args = array(
			'public' => true,
		);
		$post_types = get_post_types( $args );
		foreach($post_types as $post_type ) {
			add_meta_box(
				$this->getPlugin()->getSlug(),
				__( 'HTTPS', $this->getPlugin()->getSlug() ),
				array($this->getPlugin()->getModule('Admin'), 'meta_box_render'),
				$post_type,
				'side',
				'core',
				array( 'metabox' => 'post' )
			);
		};
	}

	/**
	 * Save Force SSL option to post or page
	 *
	 * @param int $post_id
	 * @return int $post_id
	 */
	public function post_save( $post_id ) {
		if ( array_key_exists($this->getPlugin()->getSlug(), $_POST) ) {
			if ( ! wp_verify_nonce($_POST[$this->getPlugin()->getSlug()], $this->getPlugin()->getSlug()) ) {
				return $post_id;
			}

			if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
				return $post_id;
			}

			if ( @$_POST['post_type'] == 'page' ) {
				if ( !current_user_can('edit_page', $post_id) ) {
					return $post_id;
				}
			} else {
				if ( !current_user_can('edit_post', $post_id) ) {
					return $post_id;
				}
			}

			$force_ssl = ( @$_POST['force_ssl'] == 1 ? true : false);
			if ( $force_ssl ) {
				update_post_meta($post_id, 'force_ssl', 1);
			} else {
				delete_post_meta($post_id, 'force_ssl');
			}

			$force_ssl_children = ( @$_POST['force_ssl_children'] == 1  ? true : false);
			if ( $force_ssl_children ) {
				update_post_meta($post_id, 'force_ssl_children', 1);
			} else {
				delete_post_meta($post_id, 'force_ssl_children');
			}
		}

		return $post_id;
	}

}


text:
package com.myjeeva.digitalocean.pojo;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;

import com.google.gson.annotations.Expose;
import com.myjeeva.digitalocean.common.ActionType;

/**
 * Represents Droplet Actions like reboot, powercycle, power on , power off, etc.
 *
 * @author Jeevanandam M. (jeeva@myjeeva.com)
 *
 * @since v2.0
 */
public class DropletAction {

  @Expose
  private ActionType type;

  @Expose
  private String name;

  @Expose
  private Integer image;

  @Expose
  private Integer kernel;

  @Expose
  private String size;

  public DropletAction() {
    // Default Constructor
  }

  public DropletAction(ActionType type) {
    this.type = type;
  }

  @Override
  public String toString() {
    return ReflectionToStringBuilder.toString(this);
  }

  /**
   * @return the type
   */
  public ActionType getType() {
    return type;
  }

  /**
   * @param type the type to set
   */
  public void setType(ActionType type) {
    this.type = type;
  }

  /**
   * @return the name
   */
  public String getName() {
    return name;
  }

  /**
   * @param name the name to set
   */
  public void setName(String name) {
    this.name = name;
  }

  /**
   * @return the image
   */
  public Integer getImage() {
    return image;
  }

  /**
   * @param image the image to set
   */
  public void setImage(Integer image) {
    this.image = image;
  }

  /**
   * @return the kernel
   */
  public Integer getKernel() {
    return kernel;
  }

  /**
   * @param kernel the kernel to set
   */
  public void setKernel(Integer kernel) {
    this.kernel = kernel;
  }

  /**
   * @return the size
   */
  public String getSize() {
    return size;
  }

  /**
   * @param size the size to set
   */
  public void setSize(String size) {
    this.size = size;
  }
}


text:
#ifndef MICROPY_INCLUDED_ESPRESSIF_COMMON_HAL_PULSEIO_PULSEOUT_H
#define MICROPY_INCLUDED_ESPRESSIF_COMMON_HAL_PULSEIO_PULSEOUT_H

#include "common-hal/microcontroller/Pin.h"
#include "components/driver/include/driver/rmt.h"
#include "peripherals/rmt.h"

#include "py/obj.h"

typedef struct {
    mp_obj_base_t base;
    rmt_channel_t channel;
} pulseio_pulseout_obj_t;

#endif // MICROPY_INCLUDED_ESPRESSIF_COMMON_HAL_PULSEIO_PULSEOUT_H


text:
package com.intellij.codeInsight.intention.impl;

import com.intellij.codeInsight.intention.HighPriorityAction;
import com.intellij.codeInsight.intention.LowPriorityAction;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import javax.annotation.Nonnull;

/**
 * @author Danila Ponomarenko
 */
public abstract class PriorityLocalQuickFixWrapper implements LocalQuickFix {
  private final LocalQuickFix fix;

  private PriorityLocalQuickFixWrapper(@Nonnull LocalQuickFix fix) {
    this.fix = fix;
  }

  @Nonnull
  @Override
  public String getName() {
    return fix.getName();
  }

  @Nonnull
  @Override
  public String getFamilyName() {
    return fix.getFamilyName();
  }

  @Override
  public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) {
    fix.applyFix(project, descriptor);
  }

  private static class HighPriorityLocalQuickFixWrapper extends PriorityLocalQuickFixWrapper implements HighPriorityAction {
    protected HighPriorityLocalQuickFixWrapper(@Nonnull LocalQuickFix fix) {
      super(fix);
    }
  }

  private static class NormalPriorityLocalQuickFixWrapper extends PriorityLocalQuickFixWrapper {
    protected NormalPriorityLocalQuickFixWrapper(@Nonnull LocalQuickFix fix) {
      super(fix);
    }
  }

  private static class LowPriorityLocalQuickFixWrapper extends PriorityLocalQuickFixWrapper implements LowPriorityAction {
    protected LowPriorityLocalQuickFixWrapper(@Nonnull LocalQuickFix fix) {
      super(fix);
    }
  }

  @Nonnull
  public static LocalQuickFix highPriority(@Nonnull LocalQuickFix fix) {
    return new HighPriorityLocalQuickFixWrapper(fix);
  }

  @Nonnull
  public static LocalQuickFix normalPriority(@Nonnull LocalQuickFix fix) {
    return new NormalPriorityLocalQuickFixWrapper(fix);
  }

  @Nonnull
  public static LocalQuickFix lowPriority(@Nonnull LocalQuickFix fix) {
    return new LowPriorityLocalQuickFixWrapper(fix);
  }
}


text:
[![Build Status](https://travis-ci.org/danielperna84/hass-configurator.svg?branch=master)](https://travis-ci.org/danielperna84/hass-configurator)
### Configuration UI for Home Assistant

The HASS Configurator is a small webapp (you access it via web browser) that provides a filesystem-browser and text-editor to modify files on the machine the configurator is running on. It has been created to allow easy configuration of [Home Assistant](https://home-assistant.io/). It is powered by [Ace editor](https://ace.c9.io/), which supports syntax highlighting for various code/markup languages. [YAML](https://en.wikipedia.org/wiki/YAML) files (the default language for Home Assistant configuration files) will be automatically checked for syntax errors while editing.
__IMPORTANT:__ The configurator fetches JavaScript libraries, CSS and fonts from CDNs. Hence it does __NOT__ work when your client device is offline. And it is only available for __Python 3__.

### Feature list:

- Web-Based editor to modify your files with syntax highlighting and automatic yaml-linting
- Upload and download files
- Lists of available triggers, events, entities, conditions and services. Selected element gets inserted into the editor at the last cursor position.
- Home Assistant event observer (connect to Home Assistant via WebSocket and see all the events that happen)
- Restart Home Assistant directly with the click of a button
- SSL support
- Optional authentication and IP filtering for added security
- Direct links to Home Assistant documentation and icons
- Execute shell commands
- Stage and commit changes in Git repositories, create and switch between branches, push to SSH remotes
- Customizable editor settings (saved using [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage))
- Standalone mode that hides the Home Assistant related panel on the left side (triggers, entities etc.). Set `HASS_API` to `None` or use the commandline flag `-s` / `--standalone` to enable this mode.

#### Screenshot HASS Configurator:
![Screenshot](https://github.com/danielperna84/hass-configurator/blob/master/screenshots/main.png)

If there is anything you want to have differently, feel free to fork and enhance. And if something is not working, create an issue here and I will have a look at it.
_WARNING_: This tool allows you to browse your filesystem and modify files. So be careful which files you edit, or you might break critical parts of your system.

### Installation
Possible methods to install the configurator are documented in the Wiki: [Installation](https://github.com/danielperna84/hass-configurator/wiki/Installation)

### Configuration
Available options to customize the behaviour of the configurator are documented in the Wiki: [Configuration](https://github.com/danielperna84/hass-configurator/wiki/Configuration)

### Keeping the configurator running
Since the configurator script on its own is no service, you'll have to take some extra steps to keep it running. More information on this topic can be found in the Wiki: [Daemonizing](https://github.com/danielperna84/hass-configurator/wiki/Daemonizing)

### API

There is an API available to programmatically add and remove IP addresses / networks to and from `ALLOWED_NETWORKS` and `BANNED_IPS`. Usage is documented in the Wiki: [API](https://github.com/danielperna84/hass-configurator/wiki/API)

### Embedding into Home Assistant
Once you have properly set up the configurator, you can use the [panel_iframe](https://home-assistant.io/components/panel_iframe/) component of Home Assistant to embed the configurator directly into the Home Assistant UI.
An example configuration would look like this:

```yaml
panel_iframe:
  configurator:
    title: Configurator
    icon: mdi:wrench
    url: http://1.2.3.4:3218
```
__IMPORTANT__: Be careful when setting up port forwarding to the configurator while embedding into Home Assistant. If you don't restrict access by requiring authentication and / or blocking based on client IP addresses, your configuration will be exposed to the web!


text:
require "parse/db/import/utils"
require "parse/db/import/activerecord_helpers"

module Parse
  module Db
    class Import
      def create_schema(options)
        Dir["#{options.path}/#{options.entity}/data.json"].each do |file|
          missing_columns = {}
          klass = klass_from_file(file)
          puts "Scanning....#{klass.name}"
          process_parse_file(file) do |record|
            columns = get_missing_columns(klass, record.keys)
            unless columns.empty?
              columns.each do |k|
                missing_columns[k] = get_column_type(record[k], k)
              end
            end
            missing_columns.each do |k, v|
              next unless v.is_a? Fixnum
              len = record[k].to_s.length
              missing_columns[k] = len if v < len
            end
          end
          if (missing_columns.length)
            puts "Creating....#{klass.name} columns #{missing_columns.map{|k,v| "#{k} varchar(#{v})"}.join(", ")}"
            create_missing_columns(klass, missing_columns)
          end
        end
      end
    end
  end
end


text:
namespace cursespp {
    class INavigationKeys {
        public:
            virtual ~INavigationKeys() { }

            virtual bool Up(const std::string& key) = 0;
            virtual bool Down(const std::string& key) = 0;
            virtual bool Left(const std::string& key) = 0;
            virtual bool Right(const std::string& key) = 0;
            virtual bool Next(const std::string& key) = 0;
            virtual bool PageUp(const std::string& key) = 0;
            virtual bool PageDown(const std::string& key) = 0;
            virtual bool Home(const std::string& key) = 0;
            virtual bool End(const std::string& key) = 0;
            virtual bool Prev(const std::string& key) = 0;
            virtual bool Mode(const std::string& key) = 0;

            virtual std::string Up() = 0;
            virtual std::string Down() = 0;
            virtual std::string Left() = 0;
            virtual std::string Right() = 0;
            virtual std::string Next() = 0;
            virtual std::string PageUp() = 0;
            virtual std::string PageDown() = 0;
            virtual std::string Home() = 0;
            virtual std::string End() = 0;
            virtual std::string Prev() = 0;
            virtual std::string Mode() = 0;
    };
}


text:
function pageScroll() {
    $("#backtop").css("background-position-x", "-28px"),
    window.scrollBy(0, -20),
    scrolldelay = setTimeout("pageScroll()", 2),
    0 == document.documentElement.scrollTop && 0 == document.body.scrollTop && ($("#backtop").css("background-position-x", "0"), clearTimeout(scrolldelay))
}
function cloud_animate(a, b) {
    $("#" + a).animate({
        marginLeft: parseInt($("#" + a).css("marginLeft")) + 30 * b
    },
    cloud_time,
    function() {
        cloud_animate(a, -b)
    })
}
function errorTips(a, b) {
    $.colorbox({
        html: '

' + a + "
	" + "
" + "
" + '确 定	' + "
" + "
" + "
",
        title: b ? b: "错误提示"
    })
}
function textCounter(a, b, c) {
    var d = $('textarea[name="' + a + '"]');
    $.trim(d.val()).length > c ? d.val(d.val().substring(0, c)) : d.next(".word_count").children("span").text(c - $.trim(d.val()).length)
}
function placeholderFn() {
    placeholderSupport() || $("[placeholder]").focus(function() {
        var a = $(this);
        a.val() == a.attr("placeholder") && (a.val(""), a.removeClass("placeholder"))
    }).blur(function() {
        var a = $(this); ("" == a.val() || a.val() == a.attr("placeholder")) && (a.addClass("placeholder"), a.val(a.attr("placeholder")))
    }).blur(),
    "" === $("[placeholder]").value && ($("[placeholder]").value = $("[placeholder]").attr("placeholder"))
}
function placeholderSupport() {
    return "placeholder" in document.createElement("input")
}
$(function() {
    $("#email,#password").blur(function() {
        $("#beError").hide()
    }),
    $(".collapsible_menu").hover(function() {
        $(this).addClass("expend"),
        $("dd", this).show()
    },
    function() {
        $(this).removeClass("expend"),
        $("dd", this).hide()
    }),
    $("#qrSide a").click(function() {
        $(this).parent().remove()
    }),
    $("#options dl dt").click(function() {
        $(this).parent().hasClass("slideUp") ? ($(this).children("em").removeClass("transform"), $(this).parent().children("dd").slideDown(200), $(this).parent().removeClass("slideUp").children("dd").slideDown(200)) : ($(this).children("em").addClass("transform"), $(this).parent().children("dd").slideUp(200), $(this).parent().addClass("slideUp").children("dd").slideUp(200))
    }),
    $("#selected ul").delegate("li span", "click",
    function() {
        var b = $(this).parent("li").children("strong").text();
        $("#options dl").each(function() {
            $("dt", this).text() == b && $("dt", this).trigger("click")
        }),
        1 == $("#selected").find("li").length ? $(this).parents("#selected").addClass("dn").find("li").remove() : $(this).parent().remove()
    }),
    cloud_animate("cloud_s", -1),
    cloud_animate("cloud_m", 1),
    $(".job_company h2 img").hover(function() {
        $(this).siblings("span").fadeIn(200)
    },
    function() {
        $(this).siblings("span").fadeOut(200)
    }),
    $(".c_box em").hover(function() {
        $(this).siblings("span.va").fadeIn(200)
    },
    function() {
        $(this).siblings("span.va").fadeOut(200)
    }),
    $(".c_logo").on("mouseenter", 'input[type="file"]',
    function() {
        $("#logoNo").css("backgroundColor", "#7e9597")
    }),
    $(".c_logo").on("mouseleave", 'input[type="file"]',
    function() {
        $("#logoNo").css("backgroundColor", "#93b7bb")
    }),
    $(".new_portrait").on("mouseenter", 'input[type="file"]',
    function() {
        $(".portrait_upload").css("backgroundColor", "#7e9597")
    }),
    $(".new_portrait").on("mouseleave", 'input[type="file"]',
    function() {
        $(".portrait_upload").css("backgroundColor", "#e7e7e7")
    }),
    $("#Product").on("mouseenter", 'input[type="file"]',
    function() {
        $(".product_upload").children("div").css("backgroundColor", "#7e9597")
    }),
    $("#Product").on("mouseleave", 'input[type="file"]',
    function() {
        $(".product_upload").children("div").css("backgroundColor", "#93b7bb")
    }),
    $(".business_license").on("mouseenter", 'input[type="file"]',
    function() {
        $(this).prev(".license_upload").children("div").css("backgroundColor", "#7e9597")
    }),
    $(".business_license").on("mouseleave", 'input[type="file"]',
    function() {
        $(this).prev(".license_upload").children("div").css("backgroundColor", "#93b7bb")
    }),
    $(window).scroll(function() { (document.documentElement.scrollTop || document.body.scrollTop) > 0 ? $("#backtop").show() : $("#backtop").hide()
    }),
    $("#backtop").click(function() {
        pageScroll()
    }),
    $(".footer_qr").hover(function() {
        $("i", this).fadeIn(200)
    },
    function() {
        $("i", this).fadeOut(200)
    }),
    $(document).click(function() {
        $("#box_expectCity").hide(),
        $("#workplaceSelect .more").removeClass("open").children(".citymore_arrow").removeClass("transform")
    }),
    $("#workplaceSelect .more").click(function(a) {
        a.stopPropagation(),
        $(this).hasClass("open") ? ($(this).removeClass("open"), $(this).children(".citymore_arrow").removeClass("transform"), $(this).siblings("#box_expectCity").hide()) : ($(this).addClass("open"), $(this).children(".citymore_arrow").addClass("transform"), $(this).siblings("#box_expectCity").show())
    })
});
var cloud_time = 2e3;
$(function() {
    placeholderFn()
}),
function(a) {
    a.fn.hoverDelay = function(b) {
        var e, f, c = {
            hoverDuring: 200,
            outDuring: 200,
            hoverEvent: function() {
                a.noop()
            },
            outEvent: function() {
                a.noop()
            }
        },
        d = a.extend(c, b || {}),
        g = this;
        return a(this).each(function() {
            a(this).hover(function() {
                clearTimeout(f),
                e = setTimeout(function() {
                    d.hoverEvent.apply(g)
                },
                d.hoverDuring)
            },
            function() {
                clearTimeout(e),
                f = setTimeout(function() {
                    d.outEvent.apply(g)
                },
                d.outDuring)
            })
        })
    }
} (jQuery);


text:
import { BuildContext, DeepLinkConfigEntry } from '../util/interfaces';
export declare class IonicEnvironmentPlugin {
    private context;
    private writeToDisk;
    constructor(context: BuildContext, writeToDisk: boolean);
    apply(compiler: any): void;
    private initializeWebpackFileSystemCaches(webpackFileSystem);
}
export declare function convertDeepLinkConfigToWebpackFormat(parsedDeepLinkConfigs: Map<string, DeepLinkConfigEntry>): {
    [index: string]: string;
};


text:
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;

using LiteCore.Util;

namespace LiteCore.Interop
{

    internal unsafe struct C4PredictiveModel
    {
        public void* context;
        public IntPtr prediction;
        public IntPtr unregistered;
    }

}


text:
package com.client.core.scheduledtasks.workflow.traversing.impl;

import com.client.core.base.model.relatedentity.BullhornRelatedEntity;
import com.client.core.scheduledtasks.model.helper.CustomSubscriptionEvent;
import com.client.core.scheduledtasks.model.helper.impl.PlacementCommissionScheduledTaskHelper;
import com.client.core.scheduledtasks.tools.enumeration.EventType;
import com.client.core.scheduledtasks.workflow.traversing.AbstractScheduledTasksTraverser;

import java.util.Map;
import java.util.Set;

public class PlacementCommissionEventTraverser extends AbstractScheduledTasksTraverser<PlacementCommissionScheduledTaskHelper> {

	public PlacementCommissionEventTraverser(CustomSubscriptionEvent event, Map<? extends BullhornRelatedEntity, Set<String>> relatedEntityFields) {
		super(new PlacementCommissionScheduledTaskHelper(event, relatedEntityFields), EventType.getType(event.getEntityEventType()));
	}

}


text:
class AddAuthTokenToUser < ActiveRecord::Migration
  def change
    add_column :users, :authentication_token, :string
    add_index :users, :authentication_token, :unique => true
  end
end


text:
import { OpenDialogOptions } from 'electron'

/** Options of import music dialog. */
export const ImportMusicDialogOption: OpenDialogOptions = {
  title: 'Select music files',
  filters: [
    {
      name: 'Musics',
      extensions: [
        'mp3',
        'mp2',
        'm2a',
        'm4a',
        'aac',
        'wav',
        'wma',
        'flac',
        'opus',
        'ogg'
      ]
    }
  ],
  properties: ['openFile', 'multiSelections']
}


text:
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

#include "libcgo.h"

/* Stub for creating a new thread */
void
x_cgo_thread_start(ThreadStart *arg)
{
	ThreadStart *ts;

	/* Make our own copy that can persist after we return. */
	_cgo_tsan_acquire();
	ts = malloc(sizeof *ts);
	_cgo_tsan_release();
	if(ts == nil) {
		fprintf(stderr, "runtime/cgo: out of memory in thread_start\n");
		abort();
	}
	*ts = *arg;

	_cgo_sys_thread_start(ts);	/* OS-dependent half */
}

#ifndef CGO_TSAN
void(* const _cgo_yield)() = NULL;
#else

#include <string.h>

char x_cgo_yield_strncpy_src = 0;
char x_cgo_yield_strncpy_dst = 0;
size_t x_cgo_yield_strncpy_n = 0;

/*
Stub for allowing libc interceptors to execute.

_cgo_yield is set to NULL if we do not expect libc interceptors to exist.
*/
static void
x_cgo_yield()
{
	/*
	The libc function(s) we call here must form a no-op and include at least one
	call that triggers TSAN to process pending asynchronous signals.

	sleep(0) would be fine, but it's not portable C (so it would need more header
	guards).
	free(NULL) has a fast-path special case in TSAN, so it doesn't
	trigger signal delivery.
	free(malloc(0)) would work (triggering the interceptors in malloc), but
	it also runs a bunch of user-supplied malloc hooks.

	So we choose strncpy(_, _, 0): it requires an extra header,
	but it's standard and should be very efficient.

	GCC 7 has an unfortunate habit of optimizing out strncpy calls (see
	https://golang.org/issue/21196), so the arguments here need to be global
	variables with external linkage in order to ensure that the call traps all the
	way down into libc.
	*/
	strncpy(&x_cgo_yield_strncpy_dst, &x_cgo_yield_strncpy_src,
	        x_cgo_yield_strncpy_n);
}

void(* const _cgo_yield)() = &x_cgo_yield;

#endif  /* GO_TSAN */


text:
"""
Extensions to the Mailbox and System classes for simulating message and/or
node failures.
"""

from collections import namedtuple
import random

from paxos import SystemConfig
from paxos.messages import ClientRequestMsg, AdjustWeightsMsg
from paxos.sim import Mailbox
from paxos.test import DebugMailbox

class FailTestMailbox(Mailbox):
    """
    A Mailbox class that drops messages destined to each process with a
    probability specified  in the system config.
    """

    def send(self, to, msg):
        """
        Test a random number between [0,1) against the fail rate to determine
        whether or not to deliver/drop the message.
        """
        try:
            fail_rate = self.config.fail_rates[to]
        except (AttributeError, IndexError):
            fail_rate = 0
        if msg == "quit" or isinstance(msg, SystemConfig) or isinstance(msg, ClientRequestMsg) or \
                isinstance(msg, AdjustWeightsMsg) or fail_rate == 0 or fail_rate <= random.random():
            super(FailTestMailbox, self).send(to, msg)
        else:
            self.message_failed()
            #print("****** Message to {} failed: {} ******".format(to, msg))

    def message_failed(self):
        """Hook for accounting of failed messages."""
        pass

class FailTestSystemConfig(SystemConfig):

    def __init__(self, *args, fail_rate=None, fail_rates=None, **kwargs):
        """
        If given, fail_rate should be a number between 0 and 1, inclusive, that
        will be set as a global message failure rate for all processes.
        If fail_rates is given, it should be a list of fail rates with length
        equal to the number of processes in the system.
        """
        super(FailTestSystemConfig, self).__init__(*args, **kwargs)
        if fail_rates:
            self.fail_rates = fail_rates
        else:
            if fail_rate is None:
                fail_rate = 0
            self.fail_rates = [fail_rate for _ in range(self.num_processes)]

class DebugFailTestMailbox(FailTestMailbox, DebugMailbox):

    def __init__(self, *args, **kwargs):
        super(DebugFailTestMailbox, self).__init__(*args, **kwargs)
        self.num_failed = 0

    def get_counts(self):
        #Counts = namedtuple('Counts', ['sent', 'recv', 'fail', 'total'])
        return (self.num_sent, self.num_recv, self.num_failed,
                self.num_sent + self.num_failed)

    def message_failed(self):
        self.num_failed += 1

def run_test(config):
    """

    """
    from test import DebugSystem
    system = DebugSystem(config, mailbox=DebugFailTestMailbox)
    system.start()

    for x in range(config.num_test_requests):
        # Always send to the same proposer, effective using that proposer as
        # the leader.
        to = 0
        #system.mailbox.send(to, ClientRequestMsg(None, "Query {}".format(x+1)))
        system.mailbox.send(to, ClientRequestMsg(None, x+1))
        #time.sleep(random.random()/10)

    system.shutdown_agents()
    system.logger.print_results()
    system.print_summary(log=True)
    system.quit()

def run_failrate_tests():
    for num_agents in (3, 5, 7, 9, 11):
        for fail_rate in [0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5]:
            config = FailTestSystemConfig(num_agents, num_agents, num_agents,
                                          num_test_requests=1000, fail_rate=fail_rate)
            run_test(config)

def run_reliability_example():
    fail_rates = [0, 0, 0, 0, 0,  0, 0.2, 0.2, 0.4, 0.4,   0, 0, 0, 0, 0]
    requests = 1000
    config = FailTestSystemConfig(5, 5, 5, num_test_requests=requests,
        fail_rates=fail_rates)
    run_test(config)
    config = FailTestSystemConfig(5, 5, 5, num_test_requests=requests,
        fail_rates=fail_rates, weights=[3,2,2,1,1])
    run_test(config)

def demo1():
    fail_rates = [0, 0, 0, 0, 0,  0, 0.2, 0.2, 0.4, 0.4,   0, 0, 0, 0, 0]
    requests = 100
    config = FailTestSystemConfig(5, 5, 5,
        num_test_requests=requests,
        fail_rates=fail_rates)
    run_test(config)

def demo2():
    fail_rates = [0, 0, 0, 0, 0,  0, 0.2, 0.2, 0.4, 0.4,   0, 0, 0, 0, 0]
    requests = 100
    config = FailTestSystemConfig(5, 5, 5,
        num_test_requests=requests,
        fail_rates=fail_rates, weights=[3,2,2,1,1])
    run_test(config)

if __name__ == "__main__":
    #run_failrate_tests()
    run_reliability_example()

    # Global fail rate for simulating unreliable messaging.
    #config = FailTestSystemConfig(3, 3, 3, fail_rate=0.1, num_test_requests=3)
    # Individual fail rates of 0/1 to simulate some machines down.
    #config = FailTestSystemConfig(3, 3, 3, num_test_requests=30, fail_rates=[0, 1, 1,   1, 0, 0,   0, 0, 1])

    # Failed acceptors.  With equal weights nothing is learned.  If we adjust
    # the rates to give the only alive acceptor a majority weight, then values
    # are accepted and it learns all values.
    #config = FailTestSystemConfig(3, 3, 3, num_test_requests=100, fail_rates=[0, 0, 0,   1, 1, 0,   0, 0, 0], weights=[1,1,3])
    #config = FailTestSystemConfig(3, 3, 3, num_test_requests=4000, fail_rates=[.2, .2, .2,   .8, .2, .1,   .2, .2, .2], weights=[1,2,4])
    #config = FailTestSystemConfig(6, 6, 6, num_test_requests=400, fail_rates=[.2, .2, .2, .2, .2, .2,   .8, .2, .1, .8, .2, .1,   .2, .2, .2, .2, .2, .2], weights=[1,2,4,1,2,4])
    #config = FailTestSystemConfig(3, 3, 3, num_test_requests=1000, fail_rate=0)


text:
define([
    'jquery',
    'underscore',
    'oroui/js/mediator',
    'oroui/js/app/views/base/view'
], function($, _, mediator, BaseView) {
    'use strict';

    /**
     * @export orouser/js/views/role-view
     */
    const RoleView = BaseView.extend({
        options: {
            elSelector: '',
            formName: '',
            formSelector: '',
            privilegesSelector: '',
            appendUsersSelector: '',
            removeUsersSelector: '',
            fields: ''
        },
        privileges: null,

        $form: null,

        $privileges: null,

        $appendUsers: null,

        $removeUsers: null,

        $fields: null,

        events: {
            click: 'onSubmit'
        },

        listen: {
            'securityAccessLevelsComponent:link:click mediator': 'onAccessLevelsLinkClicked'
        },

        /**
         * @inheritDoc
         */
        constructor: function RoleView(options) {
            RoleView.__super__.constructor.call(this, options);
        },

        /**
         * Initialize
         *
         * @param {Object} options
         */
        initialize: function(options) {
            this.options = _.defaults(options || {}, this.options);
            this.$el = $(this.options.elSelector);
            this.$form = $(this.options.formSelector);
            this.$privileges = $(this.options.privilegesSelector);
            this.$appendUsers = $(this.options.appendUsersSelector);
            this.$removeUsers = $(this.options.removeUsersSelector);

            const fields = {};
            _.each(
                this.options.fields,
                function(selector, name) {
                    fields[name] = $(selector);
                }
            );
            this.$fields = fields;
        },

        /**
         * @inheritDoc
         */
        dispose: function() {
            if (this.disposed) {
                return;
            }

            delete this.$form;
            delete this.$privileges;
            delete this.$appendUsers;
            delete this.$removeUsers;
            delete this.$fields;

            RoleView.__super__.dispose.call(this);
        },

        /**
         * onSubmit event listener
         */
        onSubmit: function(event) {
            const $form = this.$form;
            let hasError = false;
            _.each(this.$fields, function(field) {
                hasError = hasError || !field.valid();
            });
            if (hasError) {
                return;
            }
            if ($form.data('nohash') && !$form.data('sent')) {
                $form.data('sent', true);
                return;
            }
            if ($form.data('sent')) {
                return;
            }

            $form.data('sent', true);

            const action = $form.attr('action');
            const method = $form.attr('method');
            let url = (typeof action === 'string') ? $.trim(action) : '';
            url = url || window.location.href || '';
            if (url) {
                url += '?input_action=' + $(event.target).attr('data-action');

                // clean url (don't include hash value)
                url = (url.match(/^([^#]+)/) || [])[1];
            }

            const data = this.getData();

            const dataAction = $(event.target).attr('data-action');
            if (dataAction) {
                data.input_action = dataAction;
            }

            const options = {
                url: url,
                type: method || 'GET',
                data: $.param(data)
            };
            mediator.execute('submitPage', options);
        },

        /**
         * @returns {Object}
         */
        getData: function() {
            const data = {};

            const formName = this.options.formName;
            _.each(
                this.$fields,
                function(element, name) {
                    let value = element.val();

                    if (element.attr('type') === 'checkbox') {
                        value = element.is(':checked') ? 1 : 0;

                        if (value === 0) { // do not send the value of checkbox,
                            return; // it will be set as false in the backend
                        }
                    }

                    data[formName + '[' + name + ']'] = value;
                }
            );

            data[formName + '[privileges]'] = this.$privileges.val();
            data[formName + '[appendUsers]'] = this.$appendUsers.val();
            data[formName + '[removeUsers]'] = this.$removeUsers.val();

            return data;
        },

        /**
         * onClick event listener
         */
        onAccessLevelsLinkClicked: function(data) {
            if (this.disposed) {
                return;
            }
            const obj = JSON.parse(this.$privileges.val());

            const knownIdentities = _.reduce(obj, function(memo, group) {
                memo = _.reduce(group, function(memo, item) {
                    memo[item.identity.id] = item;
                    return memo;
                }, memo);
                return memo;
            }, {});

            let identity = data.identityId;
            const splittedIdentity = identity.split('::');
            let field;
            if (typeof splittedIdentity[1] !== 'undefined') {
                identity = splittedIdentity[0];
                field = splittedIdentity[1];
            }

            let privelege;
            let fieldPrivelege;
            if (identity in knownIdentities) {
                privelege = knownIdentities[identity];
            } else {
                // create privelege
                privelege = {
                    identity: {
                        id: identity
                    },
                    permissions: {}
                };
                if (data.permissionName === 'EXECUTE') {
                    obj.action[Object.keys(knownIdentities).length] = privelege;
                } else {
                    obj.entity[Object.keys(knownIdentities).length] = privelege;
                }
            }

            if (!field) {
                if (!(data.permissionName in privelege.permissions)) {
                    privelege.permissions[data.permissionName] = {
                        name: data.permissionName
                    };
                }
                const permission = privelege.permissions[data.permissionName];
                permission.accessLevel = data.accessLevel;
            } else {
                const knownFieldIdentities = _.reduce(privelege.fields, function(memo, item) {
                    memo[item.identity.id] = item;
                    return memo;
                }, {});

                fieldPrivelege = knownFieldIdentities[data.identityId];
                const fieldPermission = fieldPrivelege.permissions[data.permissionName];
                fieldPermission.accessLevel = data.accessLevel;
            }

            this.$privileges.val(JSON.stringify(obj)).trigger('change');
        }
    });

    return RoleView;
});