text:
package chandu0101.scalajs.react.components

import japgolly.scalajs.react.CompScope._
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.prefix_<^._

import scala.scalajs.js

case class TreeItem(item: Any, children: TreeItem*) {
  def apply(item: Any): TreeItem = this(item, Nil)
}

object ReactTreeView {

  trait Style {

    def reactTreeView = Seq[TagMod]()

    def treeGroup = Seq(^.margin := 0, ^.padding := "0 0 0 14px")

    def treeItem = Seq(^.listStyleType := "none")

    def selectedTreeItemContent = Seq(^.backgroundColor := "#1B8EB0",
      ^.color := "white", ^.fontWeight := 400,
      ^.padding := "0 7px")

    def treeItemBefore = Seq(
      ^.display := "inline-block",
      ^.fontSize := "11px",
      ^.color := "grey",
      ^.margin := "3px 7px 0 0",
      ^.textAlign := "center",
      ^.width := "11px"
    )

    def treeItemHasChildrenClosed = Seq(^.contentStyle := "▶")

    def treeItemHasChildrenOpened = Seq(^.contentStyle := "▼")

  }

  type NodeC = DuringCallbackU[NodeProps, NodeState, NodeBackend]

  case class State(filterText: String,
                   filterMode: Boolean,
                   selectedNode: js.UndefOr[NodeC])

  class Backend($: BackendScope[Props, State]) {

    def onNodeSelect(P: Props)(selected: NodeC): Callback = {
      val removeSelection: Callback =
        $.state.flatMap(
          _.selectedNode
            .filterNot(_ == selected)
            .filter(_.isMounted())
            .fold(Callback.empty)(_.modState(_.copy(selected = false)))
        )

      val updateThis: Callback =
        $.modState(_.copy(selectedNode = selected, filterMode = false))

      val setSelection: Callback =
        selected.modState(_.copy(selected = true))

      val tell: Callback =
        P.onItemSelect.asCbo(
          selected.props.root.item.toString,
          selected.props.parent,
          selected.props.depth
        )

      removeSelection >> updateThis >> setSelection >> tell
    }

    def onTextChange(text: String): Callback =
      $.modState(_.copy(filterText = text, filterMode = true))

    def render(P: Props, S: State) =
      <.div(P.style.reactTreeView)(
        P.showSearchBox ?= ReactSearchBox(onTextChange = onTextChange),
        TreeNode.withKey("root")(NodeProps(
          root         = P.root,
          open         = if (S.filterText.nonEmpty) true else P.open,
          onNodeSelect = onNodeSelect(P),
          filterText   = S.filterText,
          style        = P.style,
          filterMode   = S.filterMode
        ))
      )
  }

  case class NodeBackend($: BackendScope[NodeProps, NodeState]) {

    def onItemSelect(P: NodeProps)(e: ReactEventH): Callback =
      P.onNodeSelect($.asInstanceOf[NodeC]) >> e.preventDefaultCB >> e.stopPropagationCB

    def childrenFromProps(P: NodeProps): CallbackTo[Option[Unit]] =
      $.modState(S => S.copy(children = if (S.children.isEmpty) P.root.children else Nil))
        .conditionally(P.root.children.nonEmpty)

    def onTreeMenuToggle(P: NodeProps)(e: ReactEventH): Callback =
      childrenFromProps(P) >> e.preventDefaultCB >> e.stopPropagationCB

    def isFilterTextExist(filterText: String, data: TreeItem): Boolean = {
      def matches(item: TreeItem): Boolean =
        item.item.toString.toLowerCase.contains(filterText.toLowerCase)

      def loop(data: Seq[TreeItem]): Boolean =
        data.view.exists(
          item => if (item.children.isEmpty) matches(item) else loop(item.children)
        )

      matches(data) || loop(data.children)
    }

    def render(P: NodeProps, S: NodeState): ReactTag = {
      val depth    = P.depth + 1
      val parent   = if   (P.parent.isEmpty) P.root.item.toString
                     else s"${P.parent}<-${P.root.item.toString}"

      val treeMenuToggle: TagMod =
        if (S.children.nonEmpty)
          <.span(
            ^.onClick ==> onTreeMenuToggle(P),
            ^.key := "arrow",
            P.style.treeItemBefore,
            "▼"
          )
        else if (P.root.children.nonEmpty && S.children.isEmpty)
          <.span(
            ^.onClick ==> onTreeMenuToggle(P),
            ^.key := "arrow",
            P.style.treeItemBefore,
            "▶"
          )
        else ""

      <.li(
        P.style.treeItem,
        treeMenuToggle,
        ^.key := "toggle",
        ^.cursor := "pointer",
        <.span(
          S.selected ?= P.style.selectedTreeItemContent,
          ^.onClick ==> onItemSelect(P),
          P.root.item.toString
        ),
        <.ul(P.style.treeGroup)(
          S.children.map(child =>
            isFilterTextExist(P.filterText, child) ?=
              TreeNode.withKey(s"$parent$depth${child.item}")(P.copy(
                root = child,
                open = !P.filterText.trim.isEmpty,
                depth = depth,
                parent = parent,
                filterText = P.filterText
              ))
          ))
      )
    }
  }

  case class NodeState(children: Seq[TreeItem] = Nil, selected: Boolean = false)

  case class NodeProps(root: TreeItem,
                       open: Boolean,
                       depth: Int = 0,
                       parent: String = "",
                       onNodeSelect: (NodeC) => Callback,
                       filterText: String,
                       style: Style,
                       filterMode: Boolean)

  lazy val TreeNode = ReactComponentB[NodeProps]("ReactTreeNode")
    .initialState_P(P => if (P.open) NodeState(P.root.children) else NodeState())
    .renderBackend[NodeBackend]
    .componentWillReceiveProps {
      case ComponentWillReceiveProps(_$, newProps) =>
        _$.modState(_.copy(children = if (newProps.open) newProps.root.children else Nil))
          .conditionally(newProps.filterMode)
          .void
    }
    .build

  val component = ReactComponentB[Props]("ReactTreeView")
    .initialState(State("", false, js.undefined))
    .renderBackend[Backend]
    .build

  case class Props(root: TreeItem,
                   open: Boolean,
                   onItemSelect: js.UndefOr[(String, String, Int) => Callback],
                   showSearchBox: Boolean,
                   style: Style)

  def apply(root: TreeItem,
            openByDefault: Boolean = false,
            onItemSelect: js.UndefOr[(String, String, Int) => Callback] = js.undefined,
            showSearchBox: Boolean = false,
            ref: js.UndefOr[String] = js.undefined,
            key: js.UndefOr[js.Any] = js.undefined,
            style: Style = new Style {}) =
    component.set(key, ref)(Props(root, openByDefault, onItemSelect, showSearchBox, style))

}


text:
public class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (int num : nums) hashMap.put(num, hashMap.getOrDefault(num, 0) + 1);

        PriorityQueue<Map.Entry<Integer, Integer>> queue =
                new PriorityQueue<>(new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                return o2.getValue() - o1.getValue();
            }
        });
        queue.addAll(hashMap.entrySet());

        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < k; i++) result.add(queue.poll().getKey());
        return result;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.hitler.common.model.support;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;

import com.hitler.common.model.annotation.Checked;
import com.hitler.model.User;

@MappedSuperclass
public abstract class UserRelationEntity<PK extends Serializable> extends CheckableEntity<PK> {

	private static final long serialVersionUID = 7405522757503732970L;

	/**
	 * 用户ID
	 */
	@Checked
	@Column(name = "USER_ID", columnDefinition="INT COMMENT '用户ID'", nullable = false)
	private Integer userId;

	/**
	 * 用户帐号
	 */
	@Checked
	@Column(name = "USER_NAME", columnDefinition="varchar(16) COMMENT '用户帐号'", nullable = false)
	private String userName;

	/**
	 * 上级ID
	 */
	@Checked
	@Column(name = "PARENT_ID", columnDefinition="INT COMMENT '上级ID'")
	private Integer parentId;

	/**
	 * 直属上级帐号
	 */
	@Checked
	@Column(name = "PARENT_NAME", columnDefinition="varchar(16) COMMENT '直属上级帐号'")
	private String parentName;

	public UserRelationEntity() {}

	public UserRelationEntity(User user) {
		this.userId = user.getId();
		this.userName = user.getUserName();
		this.parentId = user.getParentId();
		this.parentName = user.getParentName();
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getParentName() {
		return parentName;
	}

	public void setParentName(String parentName) {
		this.parentName = parentName;
	}

	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	public Integer getParentId() {
		return parentId;
	}

	public void setParentId(Integer parentId) {
		this.parentId = parentId;
	}

	public User getUser() {
		User user = new User();
		user.setId(this.getUserId());
		user.setUserName(this.getUserName());
		user.setParentId(this.getParentId());
		user.setParentName(this.getParentName());
		return user;
	}

	/*********************************
	 * 枚举
	 *2015-05-08
	 ***********************************/
	public static enum UserRelationEntity_ {
		userId("userId"),
		userName("userName"),
		parentId("parentId"),
		parentName("parentName");

		private final String _name;
		UserRelationEntity_(String _name) {
			this._name = _name;
		}
		public String getName() {
			return _name;
		}
	}
}


text:
use ast::with_error_checking_parse;
use core::{Match, MatchType};
use typeinf::get_function_declaration;

use syntex_syntax::ast::ImplItem_;

pub fn snippet_for_match(m: &Match) -> String {
    match m.mtype {
        MatchType::Function => {
            let method = get_function_declaration(&m);
            if let Some(m) = MethodInfo::from_source_str(&method) {
                m.snippet()
            } else {
                "".to_string()
            }
        }
        _ => m.matchstr.clone()
    }
}

struct MethodInfo {
    name : String,
    args : Vec<String>
}

impl MethodInfo {
    ///Parses method declaration as string and returns relevant data
    fn from_source_str(source: &str) -> Option<MethodInfo> {
        let trim: &[_] = &['\n', '\r', '{', ' '];
        let decorated = format!("{} {{}}()", source.trim_right_matches(trim));

        with_error_checking_parse(decorated, |p| {
            use std::result::Result::{Ok, Err};
            use syntex_syntax::diagnostic::FatalError;
            match p.parse_impl_item() {
                Ok(method) => {
                    match method.node {
                        ImplItem_::MethodImplItem(ref msig, _) => {
                            let ref decl = msig.decl;
                            Some(MethodInfo {
                                // ident.as_str calls Ident.name.as_str
                                name: method.ident.name.as_str().to_string(),
                                args: decl.inputs.iter().map(|arg| {
                                    let ref codemap = p.sess.span_diagnostic.cm;
                                    match codemap.span_to_snippet(arg.pat.span) {
                                        Ok(name) => name,
                                        _ => "".to_string()
                                    }
                                }).collect(),
                            })
                        },
                        _ => {
                            debug!("Unable to parse method declaration. |{}|", source);
                            return None;
                        }
                    }
                },
                Err(FatalError) => {
                    debug!("Unable to parse method declaration. |{}|",source);
                    return None;
                }
            }
        })
    }

    ///Returns completion snippets usable by some editors
    fn snippet(&self) -> String {
        format!("{}({})", self.name, &self.args.iter()
            .filter(|&s| *s != "self").enumerate()
            .fold(String::new(), |cur, (i, ref s)| {
                let arg = format!("${{{}:{}}}", i+1, s);
                let delim = if i > 0 {", "} else {""};
                cur + delim + &arg
        }))
    }
}

#[test]
fn method_info_test() {
    let info = MethodInfo::from_source_str("pub fn new() -> Vec<T>").unwrap();
    assert_eq!(info.name, "new");
    assert_eq!(info.args.len(), 0);
    assert_eq!(info.snippet(), "new()");

    let info = MethodInfo::from_source_str("pub fn reserve(&mut self, additional: uint)").unwrap();
    assert_eq!(info.name, "reserve");
    assert_eq!(info.args.len(), 2);
    assert_eq!(info.args[0], "self");
    assert_eq!(info.snippet(), "reserve(${1:additional})");
}


text:
<!doctype html>

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Defining and Building Databases — Google Earth Enterprise 5.3.2 documentation</title>
    <link rel="stylesheet" href="../../static/bizstyle.css" type="text/css" />
    <link rel="stylesheet" href="../../static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="Pushing, Publishing, and Viewing a Database" href="pushPublishView.html" />
    <link rel="prev" title="Defining and Building Projects" href="buildProject.html" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0">

Navigation

          index

          next |

          previous |

Google Earth Enterprise 5.3.2 documentation »

Fusion Tutorial »

Previous topic

Defining and Building Projects

Next topic

Pushing, Publishing, and Viewing a Database

Quick search

    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Defining and Building Databases¶

The following exercises guide you through defining and building a
database, using the projects you created in the previous lesson.

Define a Database

Build a Database

Define a Database

When you define a database, you specify one or more Google Earth
Enterprise Fusion projects that Google Earth Enterprise Fusion
combines into a single self-contained world that is flyable in
Google Earth EC. You can select up to three projects for a
database–one of each type:

Vector

Imagery

Terrain

Because the majority of your efforts involve defining and
configuring different projects for inclusion in your database, it
is relatively fast to define a database once the projects are
created. You simply select the projects that comprise the database
and give it a name.

To define a database:

Select Asset Manager from the Tools menu. The Asset Manager
appears.

Click  in the toolbar. The
Database Editor appears with no projects selected.

Click  in the Vector Project row.

Navigate to ASSET_ROOT/Projects/Vector.

Note

The selection in the Type drop-down list near
the bottom of this dialog determines the type of projects
that appear on the list. Vector Project is automatically
selected, so only vector resources appear on the list.

Select the CARoads project and click Open. The CA Roads
project appears in the Database Editor next to Vector Project.

Click  in the Imagery Project row and select
Projects/Imagery/SFBayArea.

Click  in the Terrain Project row and select
Projects/Terrain/SFTerrain.

All three projects are now listed in the Database Editor
window:

Select File > Save and navigate to the
ASSET_ROOT/Databases folder.

Enter SFHighways as the name of your database, and click
Save.

The name of the database is displayed when you select the
/ASSET_ROOT/Databasesfolder in the asset navigation tree.

Build a Database

Once the database has been defined, it is ready to be built.

Note

If you had not built the projects included in this
database previously, the following process would build them in
the course of building the database. As you might expect, the
database build process takes much longer if it is building all
of the projects in the database at once. However, since Google
Earth Enterprise Fusion gives you the option to build each
project as soon as you finish making modifications or when you
build the database, you can determine the best work style for
yourself.

To build a database:

In the Asset Manager, select the /ASSET_ROOT/Databases
folder.

SFHighways appears on the right with the Current Version
and the Current State set to None, indicating that the
database has not yet been built.

Right-click SFHighways and select Build. The status of
the database immediately changes to Queued and then to In
Progress.

Double-click the Current Version or Current State column of the
SFHighways to view the progress of the build.

The Version Properties dialog displays the most recent version
of that database. You can expand the version tree to view the
status of the build in real time by clicking the + signs.

When Google Earth Enterprise Fusion finishes building the
database, its Current State column in the Asset Manager changes to
Succeeded, and its Current Version column changes to the date
and time the most recent build was started.

Close the Asset Manager by clicking the close box (X) in the
top right corner, and go on to the next lesson.

Navigation

          index

          next |

          previous |

Google Earth Enterprise 5.3.2 documentation »

Fusion Tutorial »

        © Copyright 2019, Open GEE Contributors.
      Created using Sphinx 1.7.5.


text:
package autumn.lang.annotations;

import high.mackenzie.autumn.resources.Finished;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * This annotation indicates the entry-point of a program.
 *
 * @author Mackenzie High
 */
@Finished("2014/07/12")
@Retention(RetentionPolicy.RUNTIME)
public @interface Start
{
    // Pass
}


text:
from __future__ import division
from psychopy import visual, core, data, event, logging, gui
from psychopy.constants import *

import sys
import pandas as pd
import numpy as np
from numpy import sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad, rad2deg, linspace, asarray
from numpy.random import random, randint, normal, shuffle
import itertools

import os
import statsmodels.api as sm
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels
import fnmatch
import time

# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)

# Store info about the experiment session
expName = 'behRemap'
expInfo = {u'participant': u''}
dlg = gui.DlgFromDict(dictionary=expInfo, title=expName)
if dlg.OK == False: core.quit()  # user pressed cancel
expInfo['date'] = data.getDateStr()  # add a simple timestamp
expInfo['expName'] = expName
expInfo['group (c or r)'] = 'c'

#Count how many days this subject has completed:
current_session_count = []
for file in os.listdir(_thisDir+os.sep + 'data'):
    if fnmatch.fnmatch(file, '*' + expInfo['participant'] + '*summary*.csv'):
        current_session_count.append(file)
expInfo['session'] = len(current_session_count) + 1
session = int(expInfo['session'])
if session==11:
    sys.exit("You are done!")

# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + 'data/%s_%s_%s_group_%s' %(expInfo['participant'], expName, expInfo['date'], expInfo['group (c or r)'])

# Output summary data and analyzed files
out_sum_fn =  _thisDir + os.sep +'data/%s_summary_%s_%s_session_%s_group_%s.csv' %(expInfo['participant'], expName, expInfo['date'], expInfo['session'],  expInfo['group (c or r)'])
out_all_fn =  _thisDir + os.sep +'data/%s_allResp_%s_%s_session_%s_group_%s.csv' %(expInfo['participant'], expName,  expInfo['date'], expInfo['session'],   expInfo['group (c or r)'])
data_out = pd.DataFrame(columns=('block','response','rt', 'type', 'keyPressed', 'correctKey'))

#Learning mapping data files.
practice_out_fn =  _thisDir + os.sep +'data/%s_practice_%s_%s_session_%s_group_%s.csv' %(expInfo['participant'], expName,  expInfo['date'], expInfo['session'],   expInfo['group (c or r)'])
practice_data_out = pd.DataFrame(columns=('nTrials','accuracy', 'time'))

#### Generate Stimuli ####
keys = [2, 3, 4, 5]
img_filenames = ['image_folder/stim_2.png', 'image_folder/stim_3.png', 'image_folder/stim_4.png', 'image_folder/stim_5.png']
key_name = ['j', 'k', 'l', 'semicolon']
img_dicts = [dict(zip(kperm, img_filenames)) for kperm in itertools.permutations(keys, len(img_filenames))]
key_dicts =  [dict(zip(kperm, key_name)) for kperm in itertools.permutations(keys, len(key_name))]
map_perm = [13,4,8,23,16,7,21,13,1,23,8,16,21,7,4]

# To keep the movements same change img_dict
if  expInfo['group (c or r)'] == 'c':
    img_dict = img_dicts[map_perm[session-1]]
    key_dict = key_dicts[0]
# to keep goals same change key_dict
if  expInfo['group (c or r)'] == 'r':
    img_dict = img_dicts[0]
    key_dict = key_dicts[map_perm[session-1]]

#64 chunks total, chunkSize = 4, 16 repititions of each chunk, no pause after first cue during first 7 blocks
key_map = {2:'x', 3:'x', 4:'x', 5:'x'}
this_practice_dict = {key: img_dict[key] for key in key_map.keys()}
#this_practice_dict = {key_dict[key]: img_dict[key] for key in key_map.keys()}
df_practice = {'cor_ans':this_practice_dict.keys(),'img_id': this_practice_dict.values()}
df_practice = pd.DataFrame(data=df_practice)
df_practice = df_practice[['img_id', 'cor_ans']]
df_practice = df_practice.replace({'cor_ans':key_dict})
practiceOnsets_fn =  _thisDir + os.sep + 'data/%s_practiceOnsets_session_%s.csv' %(expInfo['participant'], expInfo['session'])
df_practice.to_csv(practiceOnsets_fn, index=False)

n_trials = 16*16 # number of trials within a block should be 256
dfStims = pd.DataFrame()
block_ids = [1, 1, 2, 2, 2, 1, 2]# 1 is random, 2 is sequence
chunks = [[2,3,5,2],[4,5,3,5],[3,2,4,3],[5,4,2,4]]

#Generate Pseudo-Random Stimuli Ordering
def genRandom(n_trials):
    random_stims = []
    random_img_ids = []
    random_ans = []
    for x in range(0,n_trials):
        if len(random_stims) == 0:
            random_stims.append(randint(2,6))
        elif len(random_stims) > 0:
            val = randint(2,6)
            while val == random_stims[x-1]:
                val = randint(2,6)
            random_stims.append(val)
        random_img_ids.append(img_dict[random_stims[x]])
        random_ans.append(key_dict[random_stims[x]])
    random_img_ids = np.asarray(random_img_ids)
    random_ans= np.asarray(random_ans)
    return (random_img_ids, random_ans)

#Generate Sequence Ordering
def genSequence(n_trials):
    sequence_stims = [2,3,5,2,4,5,3,5,3,2,4,3,5,4,2,4]
    sequence_img_ids = []
    sequence_ans = []
    sequence_stims= np.tile(sequence_stims,16)
    for x in range(0,n_trials):
        sequence_img_ids.append(img_dict[sequence_stims[x]])
        sequence_ans.append(key_dict[sequence_stims[x]])
    return (sequence_img_ids, sequence_ans)

for type in range(0,len(block_ids)):
    if block_ids[type] == 1:
        img_ids, ran_ans = genRandom(n_trials)
        dfStims['block_'+str(type+1)+'_img'] = img_ids
        dfStims['block_'+str(type+1)+'_ans'] = ran_ans
    elif block_ids[type] == 2:
        img_ids, seq_ans = genSequence(n_trials)
        dfStims['block_'+str(type+1)+'_img'] = img_ids
        dfStims['block_'+str(type+1)+'_ans'] = seq_ans

dfStims.to_csv('behavior_stimuli.csv', index= False)

behavior_blocks = pd.DataFrame()
behavior_blocks['Block_id'] = ['block_1_img','block_2_img','block_3_img','block_4_img' ,'block_5_img','block_6_img' ,'block_7_img' ]
behavior_blocks['Block_ans'] = ['block_1_ans','block_2_ans','block_3_ans','block_4_ans','block_5_ans','block_6_ans','block_7_ans' ]
behavior_blocks.to_csv('behavior_blocks.csv', index= False)

thisExp = data.ExperimentHandler(name=expName, version='',
    extraInfo=expInfo, runtimeInfo=None,
    originPath=None,
    savePickle=True, saveWideText=True,
    dataFileName=filename)

#save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING)  # this outputs to the screen, not a file

endExpNow = False  # flag for 'escape' or other condition => quit the exp

# Setup the Window
win = visual.Window(size=[400,400], fullscr=False, screen=0, allowGUI=False, allowStencil=False,
    monitor='testMonitor', color=[-1,-1,-1], colorSpace='rgb',
    blendMode='avg', useFBO=True
    )

# store frame rate of monitor if we can measure it successfully
expInfo['frameRate']=win.getActualFrameRate()
if expInfo['frameRate']!=None:
    frameDur = 1.0/round(expInfo['frameRate'])
else:
    frameDur = 1.0/60.0 # couldn't get a reliable measure so guess

# Initialize components for Routine "Instructions"
InstructionsClock = core.Clock()
instrText = visual.TextStim(win=win, ori=0, name='instrText',
    text=u'In this experiment, you will see a series of images displayed on the screen. \
          Each image corresponds to a unique finger movement (index, middle, ring, pinky).\
          \n Position your index finger on \'j\', your middle finger on \'k\',your ring on \
          \'l\' and your pinky on \';\'. \n Before starting, you will learn the mapping of \
          each image to key press. Press any key to continue.',    font=u'Arial', pos=[0, 0], \
          height=0.1, wrapWidth=None, color=u'white', colorSpace='rgb', opacity=1, depth=0.0)

# Initialize components for Routine "practice"
practiceClock = core.Clock()

image = visual.ImageStim(win=win, name='image', units='pix',
    image='sin', mask=None,
    ori=0, pos=[0, 0], size=[200,200],
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=0.0)

# Initialize components for Feedback
practiceFeedback = visual.TextStim(win=win, ori=0, name='text_4',
    text=u'Press the space bar to continue. \n',    font=u'Arial',
    pos=[0, -.6], height=0.1, wrapWidth=None,
    color=u'white', colorSpace='rgb', opacity=1,
    depth=0.0)

Wrong_1 = visual.Circle(win=win, units = 'pix', radius = 100,lineColor='red', fillColor = 'red')

# Initialize components for Routine "Begin_Blocks"
Begin_BlocksClock = core.Clock()
text_3 = visual.TextStim(win=win, ori=0, name='text_3',
    text=u'End of practice rounds. Press any key to continue. ',    font=u'Arial',
    pos=[0, 0], height=0.1, wrapWidth=None,
    color=u'white', colorSpace='rgb', opacity=1,
    depth=0.0)

# Initialize components for Routine "Block"
BlockClock = core.Clock()
image_2 = visual.ImageStim(win=win, name='image_2',units='pix',
    image='sin', mask=None,
    ori=0, pos=[0, 0], size=[200,200],
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=0.0)

# Initialize components for Routine "Feedback"
FeedbackClock = core.Clock()
#initialize n_corr and mean_Rt

text_2 = visual.TextStim(win=win, ori=0, name='text_2',
    text='',    font=u'Arial',
    pos=[0, 0], height=0.1, wrapWidth=None,
    color=u'white', colorSpace='rgb', opacity=1,
    depth=0.0)

# Initialize components for Routine "End_Experiment"
End_ExperimentClock = core.Clock()
text = visual.TextStim(win=win, ori=0, name='text',
    text=u'Experiment is completed. Thank you for your participation.\n',    font=u'Arial',
    pos=[0, 0], height=0.1, wrapWidth=None,
    color=u'white', colorSpace='rgb', opacity=1,
    depth=0.0)

practice_with_help = visual.TextStim(win=win, ori=0, name='practice_with_help',
    text=u'Practice trails are about to begin. Ensure that you can comfortably press each button.',    font=u'Arial',
    pos=[0, 0], height=0.1, wrapWidth=None,
    color=u'white', colorSpace='rgb', opacity=1,
    depth=0.0)

practice_without_help = visual.TextStim(win=win, ori=0, name='practice_without_help',
        text=u'Now you will practice the same key presses, but there will not be any text telling you which key to press. The only feedback will be a red circle if you incorrectly press a finger. Once you reach at least 90 % accuarcy, the experiment will automatically advance to the next phase. ',    font=u'Arial',
        pos=[0, 0], height=0.1, wrapWidth=None,
        color=u'white', colorSpace='rgb', opacity=1,
        depth=0.0)

pause_text = 'Practice is completed. In the following sessions, move as fast and as accurately as possible. Press any key to continue'
pause_after_block = visual.TextStim(win=win, ori=0, name='text',
    text=pause_text,    font=u'Arial',
    pos=[0, 0], height=0.1, wrapWidth=None,
    color=u'white', colorSpace='rgb', opacity=1,
    depth=0.0)

# Create some handy timers
globalClock = core.Clock()  # to track the time since experiment started
routineTimer = core.CountdownTimer()  # to track time remaining of each (non-slip) routine

#------Prepare to start Routine "Instructions"-------
t = 0
InstructionsClock.reset()  # clock
frameN = -1
# update component parameters for each repeat
instructions_response = event.BuilderKeyResponse()  # create an object of type KeyResponse
instructions_response.status = NOT_STARTED
# keep track of which components have finished
InstructionsComponents = []
InstructionsComponents.append(instrText)
InstructionsComponents.append(instructions_response)
for thisComponent in InstructionsComponents:
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED

#-------Start Routine "Instructions"-------
continueRoutine = True
while continueRoutine:
    # get current time
    t = InstructionsClock.getTime()
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame

    # *instrText* updates
    if t >= 0.0 and instrText.status == NOT_STARTED:
        # keep track of start time/frame for later
        instrText.tStart = t  # underestimates by a little under one frame
        instrText.frameNStart = frameN  # exact frame index
        instrText.setAutoDraw(True)

    # *instructions_response* updates
    if t >= 0.0 and instructions_response.status == NOT_STARTED:
        # keep track of start time/frame for later
        instructions_response.tStart = t  # underestimates by a little under one frame
        instructions_response.frameNStart = frameN  # exact frame index
        instructions_response.status = STARTED
        # keyboard checking is just starting
        event.clearEvents(eventType='keyboard')
    if instructions_response.status == STARTED:
        theseKeys = event.getKeys()

        # check for quit:
        if "escape" in theseKeys:
            endExpNow = True
        if len(theseKeys) > 0:  # at least one key was pressed
            # a response ends the routine
            continueRoutine = False

    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in InstructionsComponents:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished

    # check for quit (the Esc key)
    if endExpNow or event.getKeys(keyList=["escape"]):
        core.quit()

    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

#-------Ending Routine "Instructions"-------
for thisComponent in InstructionsComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
routineTimer.reset()

# keep track of which components have finished
InstructionsComponents = []
InstructionsComponents.append(practice_with_help)
for thisComponent in InstructionsComponents:
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED

#-------Start Routine "Instructions"-------
continueRoutine = True
while continueRoutine and routineTimer.getTime() > 0:
    # get current time
    t = InstructionsClock.getTime()
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame

    # *practice_with_help* updates
    if t >= 0.0 and practice_with_help.status == NOT_STARTED:
        # keep track of start time/frame for later
        practice_with_help.tStart = t  # underestimates by a little under one frame
        practice_with_help.frameNStart = frameN  # exact frame index
        practice_with_help.setAutoDraw(True)
    if practice_with_help.status == STARTED and t >= (0.0 + (5-win.monitorFramePeriod*0.75)): #most of one frame period left
        practice_with_help.setAutoDraw(False)
        continueRoutine = False
    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in InstructionsComponents:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished

    # check for quit (the Esc key)
    if endExpNow or event.getKeys(keyList=["escape"]):
        core.quit()

    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

#Clear events of type keyboard so that next block doesn't immediately advance.
event.clearEvents(eventType='keyboard')

#-------Ending Routine "Instructions"-------
for thisComponent in InstructionsComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
# set up handler to look after randomisation of conditions etc
practice_loop = data.TrialHandler(nReps=5, method='sequential',
    extraInfo=expInfo, originPath=None,
    trialList=data.importConditions(practiceOnsets_fn),
    seed=None, name='practice_loop')

thisExp.addLoop(practice_loop)  # add the loop to the experiment
thisPractice_loop = practice_loop.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisPractice_loop.rgb)
if thisPractice_loop != None:
    for paramName in thisPractice_loop.keys():
        exec(paramName + '= thisPractice_loop.' + paramName)
mapping = {'j': 'Index ','k': 'Middle ', 'l': 'Ring ', 'semicolon':'Little '}
for thisPractice_loop in practice_loop:
    # abbreviate parameter names if possible (e.g. rgb = thisPractice_loop.rgb)
    if thisPractice_loop != None:
        for paramName in thisPractice_loop.keys():
            exec(paramName + '= thisPractice_loop.' + paramName)

    #------Prepare to start Routine "practice"-------
    t = 0
    practiceClock.reset()
    routineTimer.add(100)  # clock
    frameN = -1
    # update component parameters for each repeat
    image.setImage(img_id)
    Practice_response = event.BuilderKeyResponse()  # create an object of type KeyResponse
    Practice_response.status = NOT_STARTED
    # keep track of which components have finished
    practiceComponents = []
    practiceComponents.append(image)
    practiceComponents.append(Practice_response)
    practiceComponents.append(Wrong_1)
    eplicit_instruction = mapping[cor_ans]
    practiceFeedback = visual.TextStim(win=win, ori=0, name='text_4',
            text=eplicit_instruction,    font=u'Arial',
            pos=[0, -.6], height=0.1, wrapWidth=None,
            color=u'white', colorSpace='rgb', opacity=1,
            depth=0.0)
    practiceComponents.append(practiceFeedback)

    for thisComponent in practiceComponents:
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED

    #-------Start Routine "practice"-------
    continueRoutine = True
    while continueRoutine and routineTimer.getTime() > 0:

        practiceFeedback.setAutoDraw(True)
        # get current time
        t = practiceClock.getTime()
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame

        # *image* updates
        if t >= .25 and image.status == NOT_STARTED:
            # keep track of start time/frame for later
            image.tStart = t  # underestimates by a little under one frame
            image.frameNStart = frameN  # exact frame index
            image.setAutoDraw(True)

        # *Practice_response* updates
        if t >= .25 and Practice_response.status == NOT_STARTED:
            # keep track of start time/frame for later
            Practice_response.tStart = t  # underestimates by a little under one frame
            Practice_response.frameNStart = frameN  # exact frame index
            Practice_response.status = STARTED
            # keyboard checking is just starting
            Practice_response.clock.reset()  # now t=0
            event.clearEvents(eventType='keyboard')
        if Practice_response.status == STARTED:
            theseKeys = event.getKeys(keyList=['2', '3', '4', '5','j', 'k', 'l', 'semicolon'])

            # check for quit:
            if "escape" in theseKeys:
                endExpNow = True
            if len(theseKeys) > 0:  # at least one key was pressed

                if Practice_response.keys == []:
                    Practice_response.keys = theseKeys[0]  # just the last key pressed

                    Practice_response.rt = Practice_response.clock.getTime()
                    # was this 'correct'?
                    if (Practice_response.keys == str(cor_ans)) or (Practice_response.keys == cor_ans):
                        Practice_response.corr = 1
                        continueRoutine = False
                    else:
                        Practice_response.corr = 0
                        Wrong_1.setAutoDraw(True)
                        win.flip()
                        core.wait(.2)
                        continueRoutine = False

                    practiceFeedback.setAutoDraw(True)

        # a response ends the routine
        if practiceFeedback.status == STARTED and event.getKeys(keyList=['space']):
            continueRoutine = False

        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in practiceComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished

        # check for quit (the Esc key)
        if endExpNow or event.getKeys(keyList=["escape"]):
            core.quit()

        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()

    #-------Ending Routine "practice"-------
    for thisComponent in practiceComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    # Store nothing

        # a response ends the routine
        if practiceFeedback.status == STARTED and event.getKeys(keyList=['space']):
            continueRoutine = False

        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in practiceComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished

        # check for quit (the Esc key)
        if endExpNow or event.getKeys(keyList=["escape"]):
            core.quit()

        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()

    #-------Ending Routine "practice"-------
    for thisComponent in practiceComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    # Store nothing

#------Prepare to start Routine "Instructions"-------
t = 0
InstructionsClock.reset()  # clock
frameN = -1
routineTimer.add(5.000000)
# update component parameters for each repeat
# keep track of which components have finished
InstructionsComponents = []
InstructionsComponents.append(practice_without_help)
for thisComponent in InstructionsComponents:
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED

#-------Start Routine "Practice without help"-------
continueRoutine = True
while continueRoutine and routineTimer.getTime() > 0:
    # get current time
    t = InstructionsClock.getTime()
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame

    # *practice_with_help* updates
    if t >= 0.0 and practice_without_help.status == NOT_STARTED:
        # keep track of start time/frame for later
        practice_without_help.tStart = t  # underestimates by a little under one frame
        practice_without_help.frameNStart = frameN  # exact frame index
        practice_without_help.setAutoDraw(True)
    if practice_without_help.status == STARTED and t >= (0.0 + (1-win.monitorFramePeriod*0.75)): #most of one frame period left
        practice_without_help.setAutoDraw(False)
        continueRoutine = False
    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in InstructionsComponents:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished

    # check for quit (the Esc key)
    if endExpNow or event.getKeys(keyList=["escape"]):
        core.quit()

    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

#Clear events of type keyboard so that next block doesn't immediately advance.
event.clearEvents(eventType='keyboard')

#-------Ending Routine "Instructions"-------
for thisComponent in InstructionsComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
# set up handler to look after randomisation of conditions etc
practice_loop = data.TrialHandler(nReps=1000, method='random',
    extraInfo=expInfo, originPath=None,
    trialList=data.importConditions(practiceOnsets_fn),
    seed=None, name='practice_loop')

thisExp.addLoop(practice_loop)  # add the loop to the experiment
thisPractice_loop = practice_loop.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisPractice_loop.rgb)
if thisPractice_loop != None:
    for paramName in thisPractice_loop.keys():
        exec(paramName + '= thisPractice_loop.' + paramName)
mapping = {2: 'Index Finger', 3: 'Middle finger', 4: 'Ring finger', 5:'Little finger'}
running_accuracy = []
n_practice_trials = 0
start_time = time.time()
for thisPractice_loop in practice_loop:

    #%Check if threshold performance has been met.
    n_practice_trials +=1
    current_acc = (sum(running_accuracy[-20:])/20.0)
    if n_practice_trials > 80 and current_acc > .90:
        end_time = time.time() - start_time
        practice_data_out.loc[len(data_out)+1]=[n_practice_trials,current_acc, end_time]
        practice_data_out.to_csv(practice_out_fn, index=False)
        break

    # abbreviate parameter names if possible (e.g. rgb = thisPractice_loop.rgb)
    if thisPractice_loop != None:
        for paramName in thisPractice_loop.keys():
            exec(paramName + '= thisPractice_loop.' + paramName)

    #------Prepare to start Routine "practice"-------
    t = 0
    routineTimer.add(100)  # clock
    frameN = -1
    # update component parameters for each repeat
    image.setImage(img_id)
    Practice_response = event.BuilderKeyResponse()  # create an object of type KeyResponse
    Practice_response.status = NOT_STARTED
    # keep track of which components have finished
    practiceComponents = []
    practiceComponents.append(image)
    practiceComponents.append(Practice_response)
    practiceComponents.append(Wrong_1)
    #eplicit_instruction = mapping[cor_ans]
    #practiceFeedback = visual.TextStim(win=win, ori=0, name='text_4',text=eplicit_instruction,font=u'Arial', pos=[0, -.6], height=0.1, wrapWidth=None, color=u'white', colorSpace='rgb', opacity=1,depth=0.0)
    #practiceComponents.append(practiceFeedback)
    practiceClock.reset()
    for thisComponent in practiceComponents:
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED

    #-------Start Routine "practice"-------
    continueRoutine = True
    while continueRoutine and routineTimer.getTime() > 0:
        # get current time
        t = practiceClock.getTime()
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        if t >= 1.25:
            # keep track of start time/frame for later
            Practice_response.corr = 0
            running_accuracy.append(0)
            Wrong_1.setAutoDraw(True)
            win.flip()
            core.wait(.2)
            continueRoutine = False
        # *image* updates
        if t >= .25 and image.status == NOT_STARTED:
            # keep track of start time/frame for later
            image.tStart = t  # underestimates by a little under one frame
            image.frameNStart = frameN  # exact frame index
            image.setAutoDraw(True)

        # *Practice_response* updates
        if t >= .25 and Practice_response.status == NOT_STARTED:
            # keep track of start time/frame for later
            Practice_response.tStart = t  # underestimates by a little under one frame
            Practice_response.frameNStart = frameN  # exact frame index
            Practice_response.status = STARTED
            # keyboard checking is just starting
            Practice_response.clock.reset()  # now t=0
            event.clearEvents(eventType='keyboard')
        if Practice_response.status == STARTED:
            theseKeys = event.getKeys(keyList=['2', '3', '4', '5','j', 'k', 'l', 'semicolon'])

            # check for quit:
            if "escape" in theseKeys:
                endExpNow = True
            if len(theseKeys) > 0:  # at least one key was pressed
                if Practice_response.keys == []:
                    Practice_response.keys = theseKeys[0]  # just the last key pressed
                    Practice_response.rt = Practice_response.clock.getTime()
                    # was this 'correct'?
                    if (Practice_response.keys == str(cor_ans)) or (Practice_response.keys == cor_ans):
                        Practice_response.corr = 1
                        continueRoutine = False
                        running_accuracy.append(1)
                    else:
                        Practice_response.corr = 0
                        running_accuracy.append(0)
                        image.setAutoDraw(False)
                        Wrong_1.setAutoDraw(True)
                        win.flip()
                        core.wait(.2)
                        continueRoutine = False

        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in practiceComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished

        # check for quit (the Esc key)
        if endExpNow or event.getKeys(keyList=["escape"]):
            core.quit()

        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()

    #-------Ending Routine "practice"-------
    for thisComponent in practiceComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in practiceComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished

        # check for quit (the Esc key)
        if endExpNow or event.getKeys(keyList=["escape"]):
            core.quit()

        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()

    #-------Ending Routine "practice"-------
    for thisComponent in practiceComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)

#-------Start Routine "Instructions"-------
continueRoutine = True
while continueRoutine:
    # get current time
    t = InstructionsClock.getTime()
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    if t >= 0.0 and pause_after_block.status == NOT_STARTED:
        # keep track of start time/frame for later
        pause_after_block.tStart = t  # underestimates by a little under one frame
        pause_after_block.frameNStart = frameN  # exact frame index
        pause_after_block.setAutoDraw(True)
        event.clearEvents(eventType='keyboard')

    if pause_after_block.status == STARTED:
        theseKeys = event.getKeys()

        # check for quit:
        if "escape" in theseKeys:
            endExpNow = True
        if len(theseKeys) > 0:  # at least one key was pressed
            # a response ends the routine
            continueRoutine = False
    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    #continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in InstructionsComponents:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished

    # check for quit (the Esc key)
    if endExpNow or event.getKeys(keyList=["escape"]):
        core.quit()

    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()
#-------Ending Routine "Instructions"-------

pause_after_block.setAutoDraw(False)
win.flip()
#Clear events of type keyboard so that next block doesn't immediately advance.
event.clearEvents(eventType='keyboard')

# set up handler to look after randomisation of conditions etc
Block_Loop = data.TrialHandler(nReps=1, method='sequential',
    extraInfo=expInfo, originPath=None,
    trialList=data.importConditions(u'behavior_blocks.csv'),
    seed=None, name='Block_Loop')
thisExp.addLoop(Block_Loop)  # add the loop to the experiment
thisBlock_Loop = Block_Loop.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisBlock_Loop.rgb)
if thisBlock_Loop != None:
    for paramName in thisBlock_Loop.keys():
        exec(paramName + '= thisBlock_Loop.' + paramName)

nBlock = 0
max_rt = 1
iti = .25
RTclock = core.Clock()

for thisBlock_Loop in Block_Loop:
    nBlock = nBlock+1
    delay = 1
    if nBlock == 7 or nBlock == 6:
        delay = 0

    currentLoop = Block_Loop
    # abbreviate parameter names if possible (e.g. rgb = thisBlock_Loop.rgb)
    if thisBlock_Loop != None:
        for paramName in thisBlock_Loop.keys():
            exec(paramName + '= thisBlock_Loop.' + paramName)

    # set up handler to look after randomisation of conditions etc
    trials = data.TrialHandler(nReps=1, method='sequential',
        extraInfo=expInfo, originPath=None,
        trialList=data.importConditions(u'behavior_stimuli.csv'),
        seed=None, name='trials')
    thisExp.addLoop(trials)  # add the loop to the experiment
    thisTrial = trials.trialList[0]  # so we can initialise stimuli with some values
    # abbreviate parameter names if possible (e.g. rgb=thisTrial.rgb)
    if thisTrial != None:
        for paramName in thisTrial.keys():
            exec(paramName + '= thisTrial.' + paramName)

    block_rts = []
    acc_last_block = []
    n_stimuli = 0
    for thisTrial in trials:
        core.wait(.05)
        if n_stimuli % 4 == 0:
            core.wait(delay)
        currentLoop = trials
        # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
        if thisTrial != None:
            for paramName in thisTrial.keys():
                exec(paramName + '= thisTrial.' + paramName)

        #------Prepare to start Routine "Block"-------
        t = 0
        BlockClock.reset()  # clock
        frameN = -1
        routineTimer.add(.5+max_rt)
        # update component parameters for each repeat
        image_2.setImage(eval(Block_id))
        key_response = event.BuilderKeyResponse()  # create an object of type KeyResponse
        key_response.status = NOT_STARTED
        # keep track of which components have finished
        #see if this works better:

        BlockComponents = []
        BlockComponents.append(image_2)
        BlockComponents.append(key_response)
        BlockComponents.append(Wrong_1)
        for thisComponent in BlockComponents:
            if hasattr(thisComponent, 'status'):
                thisComponent.status = NOT_STARTED

        #-------Start Routine "Block"-------
        continueRoutine = True
        while continueRoutine and routineTimer.getTime() > 0:
            # get current time
            t = BlockClock.getTime()
            frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
            # update/draw components on each frame
            # *image_2* updates

            image_2.setAutoDraw(True)
            win.flip()
            RTclock.reset()
            event.clearEvents(eventType='keyboard')
            theseKeys = event.waitKeys(max_rt,('j','k','l','semicolon'), timeStamped = RTclock)

            if theseKeys is None:
                key_response.corr = 0
                key_response.keys=None
                key_response.rt = float('nan')
                Wrong_1.setAutoDraw(True)
                win.flip()
                core.wait(0.1)
                continueRoutine=False

            elif(len(theseKeys[0]) > 0):
                key_response.keys = theseKeys[0][0]  # just the last key pressed
                key_response.rt = theseKeys[0][1]
                # was this 'correct'?
                if (key_response.keys == str(eval(Block_ans))) or (key_response.keys == eval(Block_ans)):
                    key_response.corr = 1

                else:
                    key_response.corr = 0
                    Wrong_1.setAutoDraw(True)
                    win.flip()

                continueRoutine = False

            for thisComponent in BlockComponents:
                if hasattr(thisComponent, "setAutoDraw"):
                    thisComponent.setAutoDraw(False)
                    win.flip()

            core.wait(iti)
            if endExpNow or event.getKeys(keyList=["escape"]):
                core.quit()

            # refresh the screen
            if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
                win.flip()
            n_stimuli += 1

        # store data for trials (TrialHandler)
        trials.addData('key_response.keys',key_response.keys)
        trials.addData('key_response.corr', key_response.corr)
        if key_response.keys != None:  # we had a response
            trials.addData('key_response.rt', key_response.rt)

        thisExp.nextEntry()
        block_rts = np.append(block_rts,key_response.rt)
        acc_last_block = np.append(acc_last_block, key_response.corr)

        #save data in case program crashes -- remove this if its causing any hold ups
        if nBlock in [1,2,6]:
            trial_type = 1
        elif nBlock in [3,4,5,7]:
            trial_type = 2
        #ocasionally key is
        if not key_response.rt:
            key_response.rt = float('nan')
        #add data to file
        data_out.loc[len(data_out)+1]=[nBlock, key_response.corr, key_response.rt, trial_type, key_response.keys, str(eval(Block_ans))]
        data_out.to_csv(out_all_fn, index=False)
        #'data/%s_%s_%s' %(expInfo['participant'], expName, expInfo['date'])
    #build adaptive rt design.

    n_corr = np.sum(acc_last_block)
    acc_last_block = n_corr/len(acc_last_block)
    mean_rt = np.nanmean(block_rts)
    std_rt = np.nanstd(block_rts)
    adapt_rt = mean_rt+std_rt

    # completed 1 repeats of 'trials'

    #feedback text component after block completion.
    text_4 = visual.TextStim(win=win, ori=0, name='text_2',
        text='End of Block.\nMean response time: %i ms\nTrials correct: %i %% ' %(mean_rt*1000, n_corr/n_trials*100), font=u'Arial',
        pos=[0, 0], height=0.1, wrapWidth=None,
        color=u'white', colorSpace='rgb', opacity=1,
        depth=0.0)

    #------Prepare to start Routine "Feedback"-------
    t = 0
    FeedbackClock.reset()  # clock
    frameN = -1
    # update component parameters for each repeat
    key_resp_5 = event.BuilderKeyResponse()  # create an object of type KeyResponse
    key_resp_5.status = NOT_STARTED
    # keep track of which components have finished
    FeedbackComponents = []
    FeedbackComponents.append(text_4)
    FeedbackComponents.append(key_resp_5)
    for thisComponent in FeedbackComponents:
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED

    #-------Start Routine "Feedback"-------
    continueRoutine = True
    while continueRoutine:
        # get current time
        t = FeedbackClock.getTime()
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame

        # *text_2* updates
        if t >= 0.0 and text_4.status == NOT_STARTED:
            # keep track of start time/frame for later
            text_4.tStart = t  # underestimates by a little under one frame
            text_4.frameNStart = frameN  # exact frame index

            text_4.setAutoDraw(True)
            event.clearEvents(eventType='keyboard')
            core.wait(.5)
        # *key_resp_5* updates
        if t >= 0.0 and key_resp_5.status == NOT_STARTED:
            # keep track of start time/frame for later
            key_resp_5.tStart = t  # underestimates by a little under one frame
            key_resp_5.frameNStart = frameN  # exact frame index
            key_resp_5.status = STARTED

            # keyboard checking is just starting
            event.clearEvents(eventType='keyboard')

        if key_resp_5.status == STARTED:
            theseKeys = event.getKeys()

            # check for quit:
            if "escape" in theseKeys:
                endExpNow = True
            if len(theseKeys) > 0:  # at least one key was pressed
                # a response ends the routine
                continueRoutine = False

        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in FeedbackComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished

        # check for quit (the Esc key)
        if endExpNow or event.getKeys(keyList=["escape"]):
            core.quit()

        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()

    #-------Ending Routine "Feedback"-------
    for thisComponent in FeedbackComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    # the Routine "Feedback" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()

# completed 1 repeats of 'Block_Loop'

#------Prepare to start Routine "End_Experiment"-------
t = 0
End_ExperimentClock.reset()  # clock
frameN = -1
routineTimer.add(1.000000)
# update component parameters for each repeat
# keep track of which components have finished
End_ExperimentComponents = []
End_ExperimentComponents.append(text)
for thisComponent in End_ExperimentComponents:
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED

#-------Start Routine "End_Experiment"-------
continueRoutine = True
while continueRoutine and routineTimer.getTime() > 0:
    # get current time
    t = End_ExperimentClock.getTime()
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame

    # *text* updates
    if t >= 0.0 and text.status == NOT_STARTED:
        # keep track of start time/frame for later
        text.tStart = t  # underestimates by a little under one frame
        text.frameNStart = frameN  # exact frame index
        text.setAutoDraw(True)
    if text.status == STARTED and t >= (0.0 + (1.0-win.monitorFramePeriod*0.75)): #most of one frame period left
        text.setAutoDraw(False)

    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in End_ExperimentComponents:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished

    # check for quit (the Esc key)
    if endExpNow or event.getKeys(keyList=["escape"]):
        core.quit()

    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

#-------Ending Routine "End_Experiment"-------
for thisComponent in End_ExperimentComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)

#build summary statistics file
lag_names = ['lag' + str(i) for i in  range(1,16)]
data_lags = pd.DataFrame(columns = lag_names)
sum_names = ['block', 'accuracy', 'rt_all', 'rt_cor', 'sdAcc', 'sdRT', 'chunkSize']
data_summary = pd.DataFrame(columns = (sum_names))

win.close()

skip_index = 0
max_lags = 15
plot_fn =  _thisDir + os.sep +'data/rtPlot_%s_%s_%s_Day_%s.svg' %(expInfo['participant'], expName, expInfo['date'], expInfo['session'])
for i in np.unique(data_out[['block']]):
    #make a plot of the response times vs trial and plot by type save with subject's id.
    data_out['trial'] = np.array(range(1,len(data_out)+1))
    sns.set_context("paper")

    if i==7:
        plt.figure(figsize=(8, 6))
        sns.lmplot('trial', 'rt', hue = 'type', data=data_out, fit_reg=False)
        plt.savefig(plot_fn)

    block_df = data_out.loc[data_out['block']==i]
    mean_acc = block_df[['response']].mean()
    rt_all = block_df[['rt']].mean()
    block_df_cor = block_df.loc[block_df['response']==1]
    rt_cor = block_df_cor[['rt']].mean()
    std_acc = block_df[['response']].std()
    std_rt =  block_df_cor[['rt']].std()

    #del skip trials
    good_trials = block_df.drop(block_df.index[:skip_index])
    #replace NaNs with mean of rts in that block
    good_trials = good_trials[['rt']].replace(np.nan,rt_cor.rt)

    #regress the good trials
    y = np.array(good_trials['rt'])
    x = np.linspace(1,y.size,y.size)
    x = np.vstack([x,np.ones(len(x))]).T
    result = sm.OLS(y, x).fit()
    R = result.resid
    #regress the good trials using 5th order polynmoial
    idx = np.isfinite(y)
    y = y[idx]
    x = np.linspace(1,y.size,y.size)
    z = np.polyfit(x,y, 5)
    p = np.poly1d(z)
    R = y-p(x)

    acfResults = statsmodels.tsa.stattools.acf(R, unbiased=False, nlags=15, qstat=True, fft=False, alpha=0.05, missing='drop')
    lags = acfResults[0]
    lags = lags[1:] #don't care about first lag always 1
    data_lags.loc[i] = lags

    x = range(1,16)
    y = acfResults[0]
    y = y[1:].T
    error = acfResults[1]
    error = error[1:]
    up_conf = error[:,1]
    low_conf = error[:,0]

    #Put into summary data frame. As Column,
    chunkSize = np.argmax(low_conf<0)
    data_summary.loc[i] = [i, mean_acc.response, rt_all.rt, rt_cor.rt, std_acc.response, std_rt.rt, chunkSize]

#Save the file locally and in dropbox.
data_summary = pd.merge(data_summary, data_lags, left_on = 'block', right_on='lag1',left_index = True,right_index = True, how= 'outer')
data_summary.to_csv(out_sum_fn, index=False)
real_path = os.path.expanduser('~/Dropbox/modChunk/behavior/')
summary_dropbox =  real_path + '%s_summary_%s_%s_session_%s_group_%s.csv' %(expInfo['participant'], expName, expInfo['date'], expInfo['session'], expInfo['group (c or r)'])
allResp_dropbox =  real_path + '%s_allResp_%s_%s_session_%s_group_%s.csv' %(expInfo['participant'], expName,  expInfo['date'], expInfo['session'], expInfo['group (c or r)'])
data_summary.to_csv(summary_dropbox, index=False)
data_out.to_csv(allResp_dropbox, index=False)
data_out.to_csv(out_all_fn, index=False)
core.quit()


text:
/*
 * WSO2 API Manager - Store
 * This document specifies a **RESTful API** for WSO2 **API Manager** - Store.  It is written with [swagger 2](http://swagger.io/).
 *
 * OpenAPI spec version: v1.1
 * Contact: architecture@wso2.com
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */

package org.wso2.am.integration.clients.store.api.v1;

import org.wso2.am.integration.clients.store.api.ApiCallback;
import org.wso2.am.integration.clients.store.api.ApiClient;
import org.wso2.am.integration.clients.store.api.ApiException;
import org.wso2.am.integration.clients.store.api.ApiResponse;
import org.wso2.am.integration.clients.store.api.Configuration;
import org.wso2.am.integration.clients.store.api.Pair;
import org.wso2.am.integration.clients.store.api.ProgressRequestBody;
import org.wso2.am.integration.clients.store.api.ProgressResponseBody;

import com.google.gson.reflect.TypeToken;

import java.io.IOException;

import org.wso2.am.integration.clients.store.api.v1.dto.APIKeyDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.APIKeyGenerateRequestDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.APIKeyRevokeRequestDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ErrorDTO;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ApiKeysApi {
    private ApiClient apiClient;

    public ApiKeysApi() {
        this(Configuration.getDefaultApiClient());
    }

    public ApiKeysApi(ApiClient apiClient) {
        this.apiClient = apiClient;
    }

    public ApiClient getApiClient() {
        return apiClient;
    }

    public void setApiClient(ApiClient apiClient) {
        this.apiClient = apiClient;
    }

    /**
     * Build call for applicationsApplicationIdApiKeysKeyTypeGeneratePost
     * @param applicationId Application Identifier consisting of the UUID of the Application.  (required)
     * @param keyType **Application Key Type** standing for the type of the keys (i.e. Production or Sandbox).  (required)
     * @param body API Key generation request object  (optional)
     * @param ifMatch Validator for conditional requests; based on ETag.  (optional)
     * @param progressListener Progress listener
     * @param progressRequestListener Progress request listener
     * @return Call to execute
     * @throws ApiException If fail to serialize the request body object
     */
    public com.squareup.okhttp.Call applicationsApplicationIdApiKeysKeyTypeGeneratePostCall(String applicationId, String keyType, APIKeyGenerateRequestDTO body, String ifMatch, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
        Object localVarPostBody = body;

        // create path and map variables
        String localVarPath = "/applications/{applicationId}/api-keys/{keyType}/generate"
            .replaceAll("\\{" + "applicationId" + "\\}", apiClient.escapeString(applicationId.toString()))
            .replaceAll("\\{" + "keyType" + "\\}", apiClient.escapeString(keyType.toString()));

        List<Pair> localVarQueryParams = new ArrayList<Pair>();
        List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();

        Map<String, String> localVarHeaderParams = new HashMap<String, String>();
        if (ifMatch != null)
        localVarHeaderParams.put("If-Match", apiClient.parameterToString(ifMatch));

        Map<String, Object> localVarFormParams = new HashMap<String, Object>();

        final String[] localVarAccepts = {
            "application/json"
        };
        final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
        if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);

        final String[] localVarContentTypes = {
            "application/json"
        };
        final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
        localVarHeaderParams.put("Content-Type", localVarContentType);

        if(progressListener != null) {
            apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
                @Override
                public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
                    com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
                    return originalResponse.newBuilder()
                    .body(new ProgressResponseBody(originalResponse.body(), progressListener))
                    .build();
                }
            });
        }

        String[] localVarAuthNames = new String[] { "OAuth2Security" };
        return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
    }

    @SuppressWarnings("rawtypes")
    private com.squareup.okhttp.Call applicationsApplicationIdApiKeysKeyTypeGeneratePostValidateBeforeCall(String applicationId, String keyType, APIKeyGenerateRequestDTO body, String ifMatch, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {

        // verify the required parameter 'applicationId' is set
        if (applicationId == null) {
            throw new ApiException("Missing the required parameter 'applicationId' when calling applicationsApplicationIdApiKeysKeyTypeGeneratePost(Async)");
        }

        // verify the required parameter 'keyType' is set
        if (keyType == null) {
            throw new ApiException("Missing the required parameter 'keyType' when calling applicationsApplicationIdApiKeysKeyTypeGeneratePost(Async)");
        }

        com.squareup.okhttp.Call call = applicationsApplicationIdApiKeysKeyTypeGeneratePostCall(applicationId, keyType, body, ifMatch, progressListener, progressRequestListener);
        return call;

    }

    /**
     * Generate API Key
     * Generate a self contained API Key for the application
     * @param applicationId Application Identifier consisting of the UUID of the Application.  (required)
     * @param keyType **Application Key Type** standing for the type of the keys (i.e. Production or Sandbox).  (required)
     * @param body API Key generation request object  (optional)
     * @param ifMatch Validator for conditional requests; based on ETag.  (optional)
     * @return APIKeyDTO
     * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
     */
    public APIKeyDTO applicationsApplicationIdApiKeysKeyTypeGeneratePost(String applicationId, String keyType, APIKeyGenerateRequestDTO body, String ifMatch) throws ApiException {
        ApiResponse<APIKeyDTO> resp = applicationsApplicationIdApiKeysKeyTypeGeneratePostWithHttpInfo(applicationId, keyType, body, ifMatch);
        return resp.getData();
    }

    /**
     * Generate API Key
     * Generate a self contained API Key for the application
     * @param applicationId Application Identifier consisting of the UUID of the Application.  (required)
     * @param keyType **Application Key Type** standing for the type of the keys (i.e. Production or Sandbox).  (required)
     * @param body API Key generation request object  (optional)
     * @param ifMatch Validator for conditional requests; based on ETag.  (optional)
     * @return ApiResponse<APIKeyDTO>
     * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
     */
    public ApiResponse<APIKeyDTO> applicationsApplicationIdApiKeysKeyTypeGeneratePostWithHttpInfo(String applicationId, String keyType, APIKeyGenerateRequestDTO body, String ifMatch) throws ApiException {
        com.squareup.okhttp.Call call = applicationsApplicationIdApiKeysKeyTypeGeneratePostValidateBeforeCall(applicationId, keyType, body, ifMatch, null, null);
        Type localVarReturnType = new TypeToken<APIKeyDTO>(){}.getType();
        return apiClient.execute(call, localVarReturnType);
    }

    /**
     * Generate API Key (asynchronously)
     * Generate a self contained API Key for the application
     * @param applicationId Application Identifier consisting of the UUID of the Application.  (required)
     * @param keyType **Application Key Type** standing for the type of the keys (i.e. Production or Sandbox).  (required)
     * @param body API Key generation request object  (optional)
     * @param ifMatch Validator for conditional requests; based on ETag.  (optional)
     * @param callback The callback to be executed when the API call finishes
     * @return The request call
     * @throws ApiException If fail to process the API call, e.g. serializing the request body object
     */
    public com.squareup.okhttp.Call applicationsApplicationIdApiKeysKeyTypeGeneratePostAsync(String applicationId, String keyType, APIKeyGenerateRequestDTO body, String ifMatch, final ApiCallback<APIKeyDTO> callback) throws ApiException {

        ProgressResponseBody.ProgressListener progressListener = null;
        ProgressRequestBody.ProgressRequestListener progressRequestListener = null;

        if (callback != null) {
            progressListener = new ProgressResponseBody.ProgressListener() {
                @Override
                public void update(long bytesRead, long contentLength, boolean done) {
                    callback.onDownloadProgress(bytesRead, contentLength, done);
                }
            };

            progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
                @Override
                public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                    callback.onUploadProgress(bytesWritten, contentLength, done);
                }
            };
        }

        com.squareup.okhttp.Call call = applicationsApplicationIdApiKeysKeyTypeGeneratePostValidateBeforeCall(applicationId, keyType, body, ifMatch, progressListener, progressRequestListener);
        Type localVarReturnType = new TypeToken<APIKeyDTO>(){}.getType();
        apiClient.executeAsync(call, localVarReturnType, callback);
        return call;
    }
    /**
     * Build call for applicationsApplicationIdApiKeysKeyTypeRevokePost
     * @param applicationId Application Identifier consisting of the UUID of the Application.  (required)
     * @param keyType **Application Key Type** standing for the type of the keys (i.e. Production or Sandbox).  (required)
     * @param body API Key revoke request object  (optional)
     * @param ifMatch Validator for conditional requests; based on ETag.  (optional)
     * @param progressListener Progress listener
     * @param progressRequestListener Progress request listener
     * @return Call to execute
     * @throws ApiException If fail to serialize the request body object
     */
    public com.squareup.okhttp.Call applicationsApplicationIdApiKeysKeyTypeRevokePostCall(String applicationId, String keyType, APIKeyRevokeRequestDTO body, String ifMatch, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
        Object localVarPostBody = body;

        // create path and map variables
        String localVarPath = "/applications/{applicationId}/api-keys/{keyType}/revoke"
            .replaceAll("\\{" + "applicationId" + "\\}", apiClient.escapeString(applicationId.toString()))
            .replaceAll("\\{" + "keyType" + "\\}", apiClient.escapeString(keyType.toString()));

        List<Pair> localVarQueryParams = new ArrayList<Pair>();
        List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();

        Map<String, String> localVarHeaderParams = new HashMap<String, String>();
        if (ifMatch != null)
        localVarHeaderParams.put("If-Match", apiClient.parameterToString(ifMatch));

        Map<String, Object> localVarFormParams = new HashMap<String, Object>();

        final String[] localVarAccepts = {
            "application/json"
        };
        final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
        if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);

        final String[] localVarContentTypes = {
            "application/json"
        };
        final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
        localVarHeaderParams.put("Content-Type", localVarContentType);

        if(progressListener != null) {
            apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
                @Override
                public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
                    com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
                    return originalResponse.newBuilder()
                    .body(new ProgressResponseBody(originalResponse.body(), progressListener))
                    .build();
                }
            });
        }

        String[] localVarAuthNames = new String[] { "OAuth2Security" };
        return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
    }

    @SuppressWarnings("rawtypes")
    private com.squareup.okhttp.Call applicationsApplicationIdApiKeysKeyTypeRevokePostValidateBeforeCall(String applicationId, String keyType, APIKeyRevokeRequestDTO body, String ifMatch, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {

        // verify the required parameter 'applicationId' is set
        if (applicationId == null) {
            throw new ApiException("Missing the required parameter 'applicationId' when calling applicationsApplicationIdApiKeysKeyTypeRevokePost(Async)");
        }

        // verify the required parameter 'keyType' is set
        if (keyType == null) {
            throw new ApiException("Missing the required parameter 'keyType' when calling applicationsApplicationIdApiKeysKeyTypeRevokePost(Async)");
        }

        com.squareup.okhttp.Call call = applicationsApplicationIdApiKeysKeyTypeRevokePostCall(applicationId, keyType, body, ifMatch, progressListener, progressRequestListener);
        return call;

    }

    /**
     * Revoke API Key
     * Revoke a self contained API Key for the application
     * @param applicationId Application Identifier consisting of the UUID of the Application.  (required)
     * @param keyType **Application Key Type** standing for the type of the keys (i.e. Production or Sandbox).  (required)
     * @param body API Key revoke request object  (optional)
     * @param ifMatch Validator for conditional requests; based on ETag.  (optional)
     * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
     */
    public void applicationsApplicationIdApiKeysKeyTypeRevokePost(String applicationId, String keyType, APIKeyRevokeRequestDTO body, String ifMatch) throws ApiException {
        applicationsApplicationIdApiKeysKeyTypeRevokePostWithHttpInfo(applicationId, keyType, body, ifMatch);
    }

    /**
     * Revoke API Key
     * Revoke a self contained API Key for the application
     * @param applicationId Application Identifier consisting of the UUID of the Application.  (required)
     * @param keyType **Application Key Type** standing for the type of the keys (i.e. Production or Sandbox).  (required)
     * @param body API Key revoke request object  (optional)
     * @param ifMatch Validator for conditional requests; based on ETag.  (optional)
     * @return ApiResponse<Void>
     * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
     */
    public ApiResponse<Void> applicationsApplicationIdApiKeysKeyTypeRevokePostWithHttpInfo(String applicationId, String keyType, APIKeyRevokeRequestDTO body, String ifMatch) throws ApiException {
        com.squareup.okhttp.Call call = applicationsApplicationIdApiKeysKeyTypeRevokePostValidateBeforeCall(applicationId, keyType, body, ifMatch, null, null);
        return apiClient.execute(call);
    }

    /**
     * Revoke API Key (asynchronously)
     * Revoke a self contained API Key for the application
     * @param applicationId Application Identifier consisting of the UUID of the Application.  (required)
     * @param keyType **Application Key Type** standing for the type of the keys (i.e. Production or Sandbox).  (required)
     * @param body API Key revoke request object  (optional)
     * @param ifMatch Validator for conditional requests; based on ETag.  (optional)
     * @param callback The callback to be executed when the API call finishes
     * @return The request call
     * @throws ApiException If fail to process the API call, e.g. serializing the request body object
     */
    public com.squareup.okhttp.Call applicationsApplicationIdApiKeysKeyTypeRevokePostAsync(String applicationId, String keyType, APIKeyRevokeRequestDTO body, String ifMatch, final ApiCallback<Void> callback) throws ApiException {

        ProgressResponseBody.ProgressListener progressListener = null;
        ProgressRequestBody.ProgressRequestListener progressRequestListener = null;

        if (callback != null) {
            progressListener = new ProgressResponseBody.ProgressListener() {
                @Override
                public void update(long bytesRead, long contentLength, boolean done) {
                    callback.onDownloadProgress(bytesRead, contentLength, done);
                }
            };

            progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
                @Override
                public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                    callback.onUploadProgress(bytesWritten, contentLength, done);
                }
            };
        }

        com.squareup.okhttp.Call call = applicationsApplicationIdApiKeysKeyTypeRevokePostValidateBeforeCall(applicationId, keyType, body, ifMatch, progressListener, progressRequestListener);
        apiClient.executeAsync(call, callback);
        return call;
    }
}


text:
/* --------------------------------------------------------------------------
 *    Name: lookup-prefix.c
 * Purpose: Associative array implemented as a binary search tree
 * ----------------------------------------------------------------------- */

#include <stdlib.h>
#include <string.h>

#include "base/errors.h"
#include "base/types.h"

#include "datastruct/bstree.h"

#include "impl.h"

typedef struct bstree_lookup_prefix_args
{
  const unsigned char   *uprefix;
  size_t                 prefixlen;
  bstree_found_callback *cb;
  void                  *opaque;
  int                    found;
}
bstree_lookup_prefix_args_t;

static error bstree__lookup_prefix(bstree__node_t *n,
                                   int             level,
                                   void           *opaque)
{
  bstree_lookup_prefix_args_t *args = opaque;
  size_t                       len;

  NOT_USED(level);

  len = args->prefixlen;

  if (n->item.keylen >= len && memcmp(n->item.key, args->uprefix, len) == 0)
  {
    args->found = 1;
    return args->cb(&n->item, args->opaque);
  }

  return error_OK;
}

/* Walk the entire tree looking for matches.
 * Is there a more cunning way than this? */
error bstree_lookup_prefix(const bstree_t        *t,
                           const void            *prefix,
                           size_t                 prefixlen,
                           bstree_found_callback *cb,
                           void                  *opaque)
{
  error                       err;
  bstree_lookup_prefix_args_t args;

  args.uprefix   = prefix;
  args.prefixlen = prefixlen;
  args.cb        = cb;
  args.opaque    = opaque;
  args.found     = 0;

  err = bstree__walk_internal((bstree_t *) t, /* must cast away constness */
                              bstree__lookup_prefix,
                              &args);
  if (err)
    return err;

  return args.found ? error_OK : error_NOT_FOUND;
}


text:
package ro.pub.cs.systems.pdsd.practicalTest01Var05;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class PracticalTest01Var05MainActivity extends Activity {

private ButtonClickListener buttonClickListener = new ButtonClickListener();

	static int contor = 0;
	final private int[] ButtonIds = {
			R.id.button1, R.id.button2, R.id.button3, R.id.button4, R.id.go2sec
	};
	final static int SECONDARY_ACTIVITY_REQUEST_CODE = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_practical_test01_var05_main);

		for(int i = 0; i < ButtonIds.length; i++)
		{
			Button b = (Button)findViewById(ButtonIds[i]);
			b.setOnClickListener(buttonClickListener);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.practical_test01_var05_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onSaveInstanceState(Bundle savedInstanceState)
	{
		super.onSaveInstanceState(savedInstanceState);
		savedInstanceState.putString("go_2_sec",Integer.toString(contor));
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState)
	{
		if(savedInstanceState != null)
		{
			if(savedInstanceState.getString("go_2_sec") != null)
			{
				contor = Integer.parseInt(savedInstanceState.getString("go_2_sec"));

			}
		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if(resultCode != 0)
			contor++;
		Toast.makeText(this, "The activity returned with result "+resultCode, Toast.LENGTH_LONG).show();
	    EditText ed = (EditText)findViewById(R.id.editText1);
	    ed.setText(null);
	  }

	private class ButtonClickListener implements View.OnClickListener{

		@Override
		public void onClick(View v) {
			EditText ed = (EditText)findViewById(R.id.editText1);

			if(v instanceof Button)
			{
				if( (ed.getText().toString().length() > 0) && (((Button)v).getId() != R.id.go2sec))
				{
					ed.setText(ed.getText() + ", ");
				}

				if(((Button)v).getId() == R.id.button1)
				{
					ed.setText(ed.getText() + "North");
				}
				if(((Button)v).getId() == R.id.button2)
				{
					ed.setText(ed.getText() + "West");
				}

				if(((Button)v).getId() == R.id.button3)
				{
					ed.setText(ed.getText() + "East");
				}
				if(((Button)v).getId() == R.id.button4)
				{
					ed.setText(ed.getText() + "South");
				}

				if(((Button)v).getId() == R.id.go2sec)
				{
					Intent intent = new Intent("ro.pub.cs.systems.pdsd.intent.action.PracticalTest01SecondaryActivity");
					intent.putExtra("secventa",ed.getText().toString());
					intent.putExtra("contor",Integer.toString(contor));
					startActivityForResult(intent, SECONDARY_ACTIVITY_REQUEST_CODE);
				}
			}
		}
	}
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>umnhoj.com</groupId>
	<artifactId>gol-java</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<build>
		<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
		<testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.19.1</version>
				<dependencies>
					<dependency>
						<groupId>org.apache.maven.surefire</groupId>
						<artifactId>surefire-junit47</artifactId>
						<version>2.19.1</version>
					</dependency>
				</dependencies>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>1.1.8</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.5</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>


text:
<?php

namespace Bluetea\Jira\Endpoint;

use Bluetea\Api\Endpoint\BaseEndpoint;
use Bluetea\Api\Endpoint\EndpointInterface;

class JqlEndpoint extends BaseEndpoint implements EndpointInterface
{
    /**
     * Searches for issues using JQL
     *
     * @param $jql
     * @param null $startAt
     * @param null $maxResults
     * @param null $validateQuery
     * @param null $fields
     * @param null $expand
     *
     * @return mixed
     */
    public function search($jql, $startAt = null, $maxResults = null, $validateQuery = null, $fields = null, $expand = null)
    {
        $parameters = array(
            'jql' => $jql,
            'startAt' => $startAt,
            'maxResults' => $maxResults,
            'validateQuery' => $validateQuery,
            'fields' => $fields,
            'expand' => $expand
        );
        return $this->apiClient->callEndpoint('search', $parameters);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace EducationV2
{
    partial class DataClassesDataContext
    {
        partial void DeleteDeptMent(DeptMent instance)
        {
            ExecuteDynamicDelete(instance);
            LoggerHelper.Log("部门删除", "部门名:" + instance.F_name + ",ID:" + instance.F_ID);
        }

        partial void DeleteUser(User instance)
        {
            ExecuteDynamicDelete(instance);
            LoggerHelper.Log("用户删除", "用户名:" + instance.F_userName + ",ID:" + instance.F_ID);
        }

        partial void DeletePosApplicant(PosApplicant instance)
        {
            ExecuteDynamicDelete(instance);
            LoggerHelper.Log("岗位申请删除", "用户ID:" + instance.F_UserID + ",ID:" + instance.F_ID);
        }

        /*
        partial void DeleteApplicantUnit(ApplicantUnit instance)
        {
            ExecuteDynamicDelete(instance);
            LoggerHelper.Log("单位删除", "项目名:" + instance.F_name + ",ID:" + instance.F_ID);
        }
         * */
    }
}


text:
package com.freewaycoffee.clientobjlib;

import android.app.Activity;
import android.os.Bundle;

public class FCClientObjectLibraryActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}


text:
// This file is automatically generated.

package adila.db;

/*
 * Motorola Moto G4 Play
 *
 * DEVICE: harpia
 * MODEL: XT1609
 */
final class harpia_xt1609 {
    public static final String DATA = "Motorola|Moto G4 Play|";
}


text:
namespace XdsKit.Hl7.Datatypes
{
    public class TS : DataType
    {
        public DTM Time { get; set; }

        public ID DegreeOfPrecision { get; set; }
    }
}


text:
<?php

namespace Suitcoda\Model;

use Suitcoda\Model\Scope;

class Command extends BaseModel
{
    protected $table = 'commands';

    protected $fillable = [
        'name',
        'command_line',
        'is_active'
    ];

    /**
     * Get the scope for the command.
     *
     * @return object
     */
    public function scope()
    {
        return $this->belongsTo(Scope::class);
    }
}


text:
package intellij.haskell.alex.lang.psi.impl

import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import com.intellij.psi._
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.IncorrectOperationException
import intellij.haskell.alex.lang.psi._

import scala.collection.mutable

/**
  * @author ice1000
  * @param node ast node
  */
abstract class AlexIdMixin(node: ASTNode) extends AlexElementImpl(node)
  with PsiNameIdentifierOwner with PsiPolyVariantReference {
  override def resolve(): PsiElement = {
    val r = multiResolve(false)
    if (r.isEmpty) null
    else r(0).getElement
  }

  override def multiResolve(b: Boolean): Array[ResolveResult] = {
    val declarations = getAlexDeclarationsSection
    if (declarations == null) return Array()
    val variants = mutable.ArrayBuffer[ResolveResult]()
    declarations.getDeclarationList.forEach { decl =>
      val tokenSet = decl.getTokenSetDeclaration
      if (tokenSet != null && (tokenSet.getTokenSetId.getText equals getText))
        variants += new PsiElementResolveResult(tokenSet.getTokenSetId)
      val rules = decl.getRuleDeclaration
      if (rules != null && (rules.getRuleId.getText equals getText))
        variants += new PsiElementResolveResult(rules.getRuleId)
    }
    variants.toArray
  }

  private def getAlexDeclarationsSection: AlexDeclarationsSection = {
    val file = getElement.getContainingFile
    if (file == null) return null
    val declarations = PsiTreeUtil.findChildOfType(file, classOf[AlexDeclarationsSection])
    if (declarations == null) return null
    declarations
  }

  override def getVariants: Array[AnyRef] = {
    val declarations = getAlexDeclarationsSection
    if (declarations == null) return Array()
    val variants = mutable.ArrayBuffer[AnyRef]()
    declarations.getDeclarationList.forEach { decl =>
      val tokenSet = decl.getTokenSetDeclaration
      if (tokenSet != null) variants += tokenSet.getTokenSetId.getText
      val rules = decl.getRuleDeclaration
      if (rules != null) variants += rules.getRuleId.getText
    }
    variants.toArray
  }

  override def getElement: PsiElement = {
    this
  }

  private val range = new TextRange(0, getTextLength)

  override def getRangeInElement: TextRange = {
    range
  }

  override def getReference: AlexIdMixin = {
    this
  }

  override def getReferences: Array[PsiReference] = {
    Array(getReference)
  }

  override def getName: String = {
    getText
  }

  override def getCanonicalText: String = {
    getText
  }

  override def isSoft: Boolean = {
    true
  }

  override def isReferenceTo(psiElement: PsiElement): Boolean = {
    psiElement == this
  }

  override def handleElementRename(s: String): PsiElement = throw new IncorrectOperationException("Unsupported")

  override def bindToElement(psiElement: PsiElement): PsiElement = throw new IncorrectOperationException("Unsupported")

  override def getNameIdentifier: PsiElement = {
    this
  }

  override def setName(s: String): PsiElement = throw new IncorrectOperationException("Unsupported")
}


text:
<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

/**
 * If the incoming request is an OPTIONS request
 * we will register a handler for the requested route
 */
class CatchAllOptionsRequestsProvider extends ServiceProvider {

  public function register()
  {
    $request = app('request');

    if ($request->isMethod('OPTIONS')) {
      app()->options($request->path(), function() {
          return response('', 200);
      });
    }
  }

}