text:
/**************************************************************
 * mex interface to Andy Liaw et al.'s C code (used in R package randomForest)
 * Added by Abhishek Jaiantilal ( abhishek.jaiantilal@colorado.edu )
 * License: GPLv2
 * Version: 0.02
 *
 * other than adding the macros for F77_* and adding this message
 * nothing changed .
 *************************************************************/

/*******************************************************************
   Copyright (C) 2001-7 Leo Breiman, Adele Cutler and Merck & Co., Inc.

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; either version 2
   of the License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
*******************************************************************/
#ifndef RF_H
#define RF_H

/* test if the bit at position pos is turned on */
#define isBitOn(x,pos) (((x) & (1 << (pos))) > 0)
/* swap two integers */
#define swapInt(a, b) ((a ^= b), (b ^= a), (a ^= b))
/*
void classRF(double *x, int *dimx, int *cl, int *ncl, int *cat, int *maxcat,
	int *sampsize, int *Options, int *ntree, int *nvar,
	int *ipi, double *pi, double *cut, int *nodesize,
        int *outcl, int *counttr, double *prox,
	double *imprt, double *, double *impmat, int *nrnodes, int *ndbigtree,
	int *nodestatus, int *bestvar, int *treemap, int *nodeclass,
	double *xbestsplit, double *pid, double *errtr,
	int *testdat, double *xts, int *clts, int *nts, double *countts,
	int *outclts, int *labelts, double *proxts, double *errts);
*/

#define F77_CALL(x) x ## _
#define F77_NAME(x) F77_CALL(x)
#define F77_SUB(x) F77_CALL(x)

void normClassWt(int *cl, const int nsample, const int nclass,
                 const int useWt, double *classwt, int *classFreq);

void classForest(int *mdim, int *ntest, int *nclass, int *maxcat,
                 int *nrnodes, int *jbt, double *xts, double *xbestsplit,
                 double *pid, double *cutoff, double *countts, int *treemap,
                 int *nodestatus, int *cat, int *nodeclass, int *jts,
                 int *jet, int *bestvar, int *nodexts, int *ndbigtree,
                 int *keepPred, int *prox, double *proxmatrix, int *nodes);

void regTree(double *x, double *y, int mdim, int nsample,
	     int *lDaughter, int *rDaughter, double *upper, double *avnode,
             int *nodestatus, int nrnodes, int *treeSize, int nthsize,
             int mtry, int *mbest, int *cat, double *tgini, int *varUsed);

void findBestSplit(double *x, int *jdex, double *y, int mdim, int nsample,
		   int ndstart, int ndend, int *msplit, double *decsplit,
		   double *ubest, int *ndendl, int *jstat, int mtry,
		   double sumnode, int nodecnt, int *cat);

void predictRegTree(double *x, int nsample, int mdim,
		    int *lDaughter, int *rDaughter, int *nodestatus,
                    double *ypred, double *split, double *nodepred,
                    int *splitVar, int treeSize, int *cat, int maxcat,
                    int *nodex);

void predictClassTree(double *x, int n, int mdim, int *treemap,
		      int *nodestatus, double *xbestsplit,
		      int *bestvar, int *nodeclass,
		      int ndbigtree, int *cat, int nclass,
		      int *jts, int *nodex, int maxcat);

int pack(int l, int *icat);
void unpack(unsigned int npack, int *icat);

void zeroInt(int *x, int length);
void zeroDouble(double *x, int length);
void createClass(double *x, int realN, int totalN, int mdim);
void prepare(int *cl, const int nsample, const int nclass, const int ipi,
	     double *pi, double *pid, int *nc, double *wtt);
void makeA(double *x, const int mdim, const int nsample, int *cat, int *a,
           int *b);
void modA(int *a, int *nuse, const int nsample, const int mdim, int *cat,
          const int maxcat, int *ncase, int *jin);
void Xtranslate(double *x, int mdim, int nrnodes, int nsample,
		int *bestvar, int *bestsplit, int *bestsplitnext,
		double *xbestsplit, int *nodestatus, int *cat, int treeSize);
void permuteOOB(int m, double *x, int *in, int nsample, int mdim);
void computeProximity(double *prox, int oobprox, int *node, int *inbag,
                      int *oobpair, int n);

/* Template of Fortran subroutines to be called from the C wrapper */
/*extern void F77_NAME(buildtree)(int *a, int *b, int *cl, int *cat,
				int *maxcat, int *mdim, int *nsample,
				int *nclass, int *treemap, int *bestvar,
				int *bestsplit, int *bestsplitnext,
				double *tgini, int *nodestatus, int *nodepop,
				int *nodestart, double *classpop,
				double *tclasspop, double *tclasscat,
				int *ta, int *nrnodes, int *,
				int *, int *, int *, int *, int *, int *,
				double *, double *, double *,
				int *, int *, int *);
*/
/* Node status */
#define NODE_TERMINAL -1
#define NODE_TOSPLIT  -2
#define NODE_INTERIOR -3

#endif /* RF_H */


text:
package com.springboot.spark.starter.basic.rdd;

import java.io.Serializable;
import java.text.MessageFormat;
import java.util.Arrays;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;

import scala.Tuple2;

/**
 */
public class PairRDDfoldByKey implements Serializable {

  private static final long serialVersionUID = 5924321403879655951L;

  private final static SparkConf sparkConf = new SparkConf() //
      .setAppName(PairRDDfoldByKey.class.getName()) //
      .setMaster("local[1]") //
  ; //

  public final static JavaSparkContext sc = new JavaSparkContext(sparkConf);

  public void using() {
    // Create PairRDD
    JavaRDD<String> rdd = sc.parallelize(Arrays.asList("A", "B", "C", "D", "E"));
    // A function that returns key-value pairs (Tuple2<K, V>), and can be used
    // to construct PairRDDs.
    // 第一个为target,第二个为key,第三个为value。
    PairFunction<String, String, Integer> keyData = new PairFunction<String, String, Integer>() {
      private static final long serialVersionUID = 3054288968619423363L;

      @Override
      public Tuple2<String, Integer> call(String x) throws Exception {
        return new Tuple2<String, Integer>(x, (int) x.charAt(0));
      }
    };
    JavaPairRDD<String, Integer> javaPairRDD = rdd.mapToPair(keyData);
    System.err.println(javaPairRDD.collect());
    // [(A,65), (B,66), (C,67), (D,68), (E,69)]

    // 该函数用于RDD[K,V]根据K将V做折叠、合并处理,其中的参数zeroValue表示先根据映射函数将zeroValue应用于V,进行初始化V,再将映射函数应用于初始化后的V。
    JavaPairRDD<String, Integer> foldByKey = javaPairRDD.foldByKey(0,
        new Function2<Integer, Integer, Integer>() {
          private static final long serialVersionUID = 501814650371495610L;

          // 将rdd1中每个key对应的V进行累加,注意zeroValue=0,需要先初始化V,映射函数为+操
          // 作,比如("A",0), ("A",2),先将zeroValue应用于每个V,得到:("A",0+0), ("A",2+0),即:
          // ("A",0), ("A",2),再将映射函数应用于初始化后的V,最后得到(A,0+2),即(A,2)
          @Override
          public Integer call(Integer v1, Integer v2) throws Exception {
            System.err.println(MessageFormat.format("foldByKey->Key:{0}|Value:{1}", v1, v2));
            return v1 + v2;
          }
        });
    System.err.println(foldByKey.collect());
    // [(B,66), (A,65), (C,67), (E,69), (D,68)]

    // 以zeroValue为单位,依次进行折叠。
    Tuple2<String, Integer> fold = javaPairRDD.fold(new Tuple2<String, Integer>("A", 16),
        new Function2<Tuple2<String, Integer>, Tuple2<String, Integer>, Tuple2<String, Integer>>() {
          private static final long serialVersionUID = -6437742745628945630L;

          @Override
          public Tuple2<String, Integer> call(Tuple2<String, Integer> v1,
              Tuple2<String, Integer> v2) throws Exception {
            System.err.println(MessageFormat.format("fold Tuple2->v1:{0}|v2:{1}", v1, v2));
            return new Tuple2<String, Integer>(v1._1() + v2._1(), v1._2() + v2._2());
          }
        });
    System.err.println(fold);
    //(AAABCDE,367)
  }

  public static void main(String[] args) {
    new PairRDDfoldByKey().using();
    sc.close();
  }

}

redpajama_set_name: RedPajamaGithub


text:
package granulej.lang;

import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import granulej.util.xmlUtil;

public class GranuleUpdate{

	public HashMap<String, ArrayList<String>> update(String path){
      HashMap<String, ArrayList<String>> tree=new HashMap<String, ArrayList<String>>();
	  Document doc=xmlUtil.load(path+"TestGranuleTree.xml");
	  Element root=doc.getDocumentElement();
	  traversalGranuleTree(root.getFirstChild(),tree);
	  return tree;
	}

	public void traversalGranuleTree(Node node,HashMap<String, ArrayList<String>> tree) {
			if (node.getNodeType() == Node.ELEMENT_NODE) {
					String name = node.getNodeName();
					if (name.equals("granule")) {
						NamedNodeMap nodeMap = node.getAttributes();
						String gName = nodeMap.getNamedItem("name").getNodeValue();
						String cName="";
						String conName="";
						String key="";
						if (!gName.equals("g0")) {
						  cName=nodeMap.getNamedItem("class").getNodeValue();
						  conName=nodeMap.getNamedItem("context").getNodeValue();
						  key=gName+"("+ cName+ ")"+conName;
						  ArrayList<String> list=new ArrayList<String>();
						  int length = nodeMap.getLength();
						  for (int i = 0; i < length; i++) {
								String nodeName = nodeMap.item(i).getNodeName();
								if (nodeName.startsWith("shadow_class")){
									 list.add(nodeMap.item(i).getNodeValue());
						     }
                           }
						   tree.put(key, list);
						 }
					  }
				}

			for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
				traversalGranuleTree(child,tree);
			}
		}
 }


text:
import core.modules
import core.modules.module_registry
from core.modules.vistrails_module import Module, ModuleError

class ProteinDataBank(Module):
    pass

class Protein(ProteinDataBank):

    def __init__(self):
        ProteinDataBank.__init__(self)
        self.atoms = {}
        self.sequence = {}
        self.hatoms = {}
        self.author = ''
        self.title = ''

    def compute(self):
        pass

    def getAtomOfType(self, type):
        if self.atoms.has_key(type):
            return self.atoms[type]
        else:
            return 0

    def getHetAtomOfType(self, type):
        if self.hatoms.has_key(type):
            return self.hatoms[type]
        else:
            return 0

    def getSequence(self, seqID):
        if self.sequence.has_key(seqID):
            return self.sequence[seqID].__str__()
        else:
            k = self.sequence.keys().__str__()
            str =    'Invalid Sequence ID ' + k

class PDBParser(ProteinDataBank):

    ############################################################################
    # line parsers

    def is_continuation(self, line):
        try:
            int(line[0])
            return True
        except:
            return False

    def parse_ATOM(self, line, protein):
        type = line[-1]
        if protein.atoms.has_key(type):
            protein.atoms[type] = protein.atoms[type] + 1
        else:
            protein.atoms[type] = 1

    def parse_SEQRES(self, line, protein):
        els = len(line)
        seqID = line[2]
        if not protein.sequence.has_key(seqID):
            protein.sequence[seqID] = []

        s = protein.sequence[seqID]

        i = 4
        while i < len(line):
            s.append(line[i])
            i = i + 1

        protein.sequence[seqID] = s

    def parse_HETATM(self, line, protein):
        type = line[-1]
        if protein.hatoms.has_key(type):
            protein.hatoms[type] = protein.hatoms[type] + 1
        else:
            protein.hatoms[type] = 1

    def parse_AUTHOR(self, line, protein):
        if self.is_continuation(line):
            protein.author += ' ' + ' '.join(line[1:])
        else:
            protein.author = ' '.join(line)

    def parse_TITLE(self, line, protein):
        if self.is_continuation(line):
            protein.title += ' ' + ' '.join(line[1:])
        else:
            protein.title = ' '.join(line)

    def parse_HEADER(self, line, protein):
        protein.pdb_name = line[-1]
        protein.date = line[-2]
        protein.short_title = ' '.join(line[:-2])

    ############################################################################

    def compute(self):
        f = self.get_input("File")

        p = Protein()

        for l in file(f.name):
            l = l.strip()
            toks = l.split()
            if hasattr(self, 'parse_' + toks[0]):
                getattr(self, 'parse_' + toks[0])(toks[1:], p)

        self.set_output("Protein", p)

class GetAtoms(ProteinDataBank):
    def compute(self):
        prot = self.get_input("Protein")
        aType = self.get_input("Atom Type")
        self.set_output("NumAtoms", prot.getAtomOfType(aType))

class GetHetAtoms(ProteinDataBank):
    def compute(self):
        prot = self.get_input("Protein")
        aType = self.get_input("Atom Type")
        self.set_output("NumAtoms", prot.getHetAtomOfType(aType))

class GetSequence(ProteinDataBank):
    def compute(self):
        prot = self.get_input("Protein")
        sID = self.get_input("SequenceID")
        self.set_output("Sequence", prot.getSequence(sID))

class GetTitle(ProteinDataBank):
    def compute(self):
        prot = self.get_input("Protein")
        self.set_output("Title", prot.title)

class GetAuthor(ProteinDataBank):
    def compute(self):
        prot = self.get_input("Protein")
        self.set_output("Title", prot.author)

class GetPDBName(ProteinDataBank):
    def compute(self):
        prot = self.get_input("Protein")
        self.set_output("name", prot.pdb_name)


text:
from django.db import connection
from django.contrib.auth.models import User, Permission
from comperio.accounts.models import cUser
from django.core.validators import email_re
from django.contrib.auth.backends import ModelBackend

# TODO: check for User as well since the super is this by default
class ModelBackend(ModelBackend):
    """Authenticates against comperio.accounts.models.cUser"""
    supports_object_permissions = False
    supports_anonymous_user = True

    # TODO: Model, login attribute name and password attribute name should be
    # configurable.
    def authenticate(self, username=None, password=None):
        """returns the user object if the username/email and password match an existing account"""
        # allow authentication with email, otherwise username
        if email_re.search(username):
            try:
                user = cUser.objects.get(email=username)
            except cUser.DoesNotExist:
                # this may be the super user which is always a User type
                try:
                    user = User.objects.get(email=username)
                except User.DoesNotExist:
                    raise NameError("user does not exist for email: %s" % username)
                    return None
        else:
            try:
                user = cUser.objects.get(username=username)
            except cUser.DoesNotExist:
                # this may be the super user which is always a User type
                try:
                    user = User.objects.get(username=username)
                except User.DoesNotExist:
                    raise NameError("user does not exist for username: %s " % username)
                    return None
        if user.check_password(password):
            return user
        else:
            # new accounts use the activation key to automatically login upon activation
            if not user.is_active and (password == user.activation_key):
                    user.is_active = True
                    user.save()
                    return user
            else:
                # this was just a bad password
                raise NameError("password does not match: given: %s has: %s" % (password, user.password))
                return None

    def get_group_permissions(self, user_obj):
        """
        Returns a set of permission strings that this user has through his/her
        groups.
        """
        if not hasattr(user_obj, '_group_perm_cache'):
            perms = Permission.objects.filter(group__user=user_obj
                ).values_list('content_type__app_label', 'codename'
                ).order_by()
            user_obj._group_perm_cache = set(["%s.%s" % (ct, name) for ct, name in perms])
        return user_obj._group_perm_cache

    def get_all_permissions(self, user_obj):
        if user_obj.is_anonymous():
            return set()
        if not hasattr(user_obj, '_perm_cache'):
            user_obj._perm_cache = set([u"%s.%s" % (p.content_type.app_label, p.codename) for p in user_obj.user_permissions.select_related()])
            user_obj._perm_cache.update(self.get_group_permissions(user_obj))
        return user_obj._perm_cache

    def has_perm(self, user_obj, perm):
        return perm in self.get_all_permissions(user_obj)

    def has_module_perms(self, user_obj, app_label):
        """Returns True if user_obj has any permissions in the given app_label."""
        for perm in self.get_all_permissions(user_obj):
            if perm[:perm.index('.')] == app_label:
                return True
        return False

    # Do not change this def!
    # you will break the administration backend
    def get_user(self, user_id):
        """get a user by id"""
        try:
            return cUser.objects.get(pk=user_id)
        except cUser.DoesNotExist:
            try:
                return User.objects.get(pk=user_id)
            except User.DoesNotExist:
                return None

    def get_user_by_name(self, username):
        """get a user by user name"""
        try:
            return cUser.objects.get(username=username)
        except cUser.DoesNotExist:
            try:
                return User.objects.get(username=username)
            except User.DoesNotExist:
                return None


text:
<?xml version="1.0"?>
<Document>

	<Sentence>
		<value>But most of them are more like candy bars: low in fiber, and high in sugar, fat, and calories.</value>
		<pattern_crowdsource> But most of them are more like candy bars: low in [[fiber|C0225326]], and high in [[sugar|C0242209]], fat, and calories.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>most</surface-form>
				<RDF-ID>C0205393</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>more</surface-form>
				<RDF-ID>C0205172</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>candy</surface-form>
				<RDF-ID>C0006855</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>low</surface-form>
				<RDF-ID>C0205251</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>fiber</surface-form>
				<RDF-ID>C0225326</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>high</surface-form>
				<RDF-ID>C0205250</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>sugar</surface-form>
				<RDF-ID>C0242209</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>fat</surface-form>
				<RDF-ID>C0424612</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>calories</surface-form>
				<RDF-ID>C0439259</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0225326 COEXISTS_WITH C0242209</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>A cup of granola can range from 343 calories in a low-fat version you buy in the store, to 597 calories in a cup of homemade granola.</value>
		<pattern_crowdsource> A [[cup|C0220647]] of granola can range from 343 calories in a low-fat version you buy in the store, to 597 calories in a [[cup|C0220647]] of homemade granola.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>cup</surface-form>
				<RDF-ID>C0220647</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>range</surface-form>
				<RDF-ID>C1514721</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>calories</surface-form>
				<RDF-ID>C0439259</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>low-</surface-form>
				<RDF-ID>C0205251</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>fat</surface-form>
				<RDF-ID>C0424612</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>version</surface-form>
				<RDF-ID>C0333052</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>calories</surface-form>
				<RDF-ID>C0439259</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>cup</surface-form>
				<RDF-ID>C0220647</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0220647 COEXISTS_WITH C0220647</triple>
		</triples>
	</Sentence>

</Document>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleSeparateConfig
{
    class Program
    {
        static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        static void Main(string[] args)
        {
            var name = System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name;
            var underline = new String('=', name.Length);
            Console.WriteLine(name);
            Console.WriteLine(underline);

            log.Info(name);
            log.Info(underline);

            using (new AssocInt(42))
            using (new AssocString("Zaphod"))
            {
                log.Info("The int 42 will come out in the SQL log in the 'AssocInt' column and 'Zaphod' in the 'AssocString' column.");
            }
            log.Info("...and by this message they will be gone again.");

            try
            {
                throw new NotImplementedException("Just for demonstration purposes.");
            }
            catch (Exception ex)
            {
                log.Error("Got an exception.", ex);
            }

            Console.WriteLine("Setting1 = " + CZ.AppSettings.Setting1);
            Console.WriteLine("Setting2 = " + CZ.AppSettings.Setting2);
            Console.WriteLine();
            Console.WriteLine("ConnStr1 = " + CZ.ConnStrings.ConnStr1);
            Console.WriteLine("ConnStr2 = " + CZ.ConnStrings.ConnStr2);
            Console.WriteLine();
            Console.WriteLine("Reporting.PageSize = " + CZ.ReportingSettings.Current.PageSize.ToString());
            Console.WriteLine("Reporting.Server = " + CZ.ReportingSettings.Current.Server);
            Console.WriteLine("Reporting.RecipientEmail = " + CZ.ReportingSettings.Current.RecipientEmail);
            Console.Read();
        }
    }
}


text:
import EarthquakeMap from './map/EarthquakeMap';
import GraphManager from './graph/GraphManager';
import Logger from './util/Logger';

window.EQ = {
    /* Initialization function */
    initialize: _initialize,
    /* Shows debug information */
    debug: false,
    /* Allows to choose data source
     *
     * 'empty' -> no data found for each filter option specified,
     * 'test' -> test data, same data is returned for each filter option specified,
     * 'real' -> real data, data returned are real ones
     */
    proxy: 'real',
    /* Will contain main objects */
    map: null,
    graphManager: new GraphManager(),
    /* Simple configurable logger, able to show console messages depending on LogLevel specified */
    logger: new Logger(Logger.LogLevel.debug)
};

/* initialization when Gmaps is loaded */
/* initialization can start when G maps API and document are fully loaded */
function _initialize() {
    $(function () {

        /* Initialize Map object */
        let zoom = 2,
            center = {
                lat: 41.850,
                lng: -87.650
            };

        EQ.logger.debug('Map initialization');
        EQ.map = new EarthquakeMap(zoom, center);
        EQ.map.initializeMap();

        /* first time data fetch */
        EQ.map.refreshData();

        EQ.logger.debug('EQ initialized', EQ.debug ? ' in dev mode' : undefined);
        EQ.logger.debug('Visualization type initialization');
        /* set handler for visualization type -> list */
        $('div#radio-options input').change(() => EQ.map.setVisualizationType($('div#radio-options input:checked').val()));

        EQ.logger.debug('Magnitude range initialization');
        /* slider initialization */
        $("#magnitude-range")
            .slider({})
            .on('slideStop', (evt) => {
                EQ.logger.info('New magnitude range', evt.value[0], '-', evt.value[1]);
                EQ.map.fetcher
                    .set('minmagnitude', evt.value[0])
                    .set('maxmagnitude', evt.value[1]);
                EQ.map.refreshData();
            });

        /* Date range picker initialization */
        function cb(start, end) {
            $('#reportrange span').html(start.format('D MMMM, YYYY') + ' - ' + end.format('D MMMM, YYYY'));
        }
        cb(moment(), moment());
        /* Date range picker initialization */
        $('#reportrange').daterangepicker({
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(7, 'days'), moment()]
            }
        }, cb);

        /* callback when date range changes */
        $('#reportrange').on('apply.daterangepicker', function (ev, picker) {
            EQ.logger.info('New date range', picker.startDate, '-', picker.endDate);
            EQ.map.fetcher
                .set('starttime', picker.startDate.format('YYYY-MM-DD') + ' 00:00:00')
                .set('endtime', picker.endDate.format('YYYY-MM-DD') + ' 23:59:59');
            EQ.map.refreshData();
        });

        /* graph manager initialization */
        $('#show-timeline').click(() => EQ.graphManager.drawGraph(EQ.map._visibleEarthquakes));

        /* heatmap legend tooltip */
        $('[data-toggle="tooltip"]').tooltip();
    });
}


text:
package com.coillighting.udder.geometry;

import java.awt.geom.Point2D;

/** A simple public datastructure for storing four
 *  points of a control polygon.
 */
public class ControlQuad {

    // Distortion quad for Stretch.stretchXY
    public Point2D.Double sw = null;
    public Point2D.Double se = null;
    public Point2D.Double nw = null;
    public Point2D.Double ne = null;

    public ControlQuad(double[][] corners) {
        this.reset();
        this.setCorners(corners);
    }

    /** Set this ControlQuad to the given four points.
     *  Incorporate the four values by copy.
     */
    public ControlQuad(Point2D.Double sw, Point2D.Double se,
                       Point2D.Double nw, Point2D.Double ne)
    {
        this.reset();
        this.setCorners(sw, se, nw, ne);
    }

    public ControlQuad() {
        this.reset();
    }

    public void setCorners(double[][] corners) {
        if(corners != null) {
            if(corners.length != 4) {
                throw new IllegalArgumentException("A ControlQuad requires exactly 4 corners.");
            } else {
                final int X = 0;
                final int Y = 1;
                this.sw.x = corners[0][X];
                this.sw.y = corners[0][Y];
                this.se.x = corners[1][X];
                this.se.y = corners[1][Y];
                this.nw.x = corners[2][X];
                this.nw.y = corners[2][Y];
                this.ne.x = corners[3][X];
                this.ne.y = corners[3][Y];
            }
        }
    }

    public void setCorners(Point2D.Double sw, Point2D.Double se,
                           Point2D.Double nw, Point2D.Double ne)
    {
        this.sw.x = sw.x;
        this.sw.y = sw.y;
        this.se.x = se.x;
        this.se.y = se.y;
        this.nw.x = nw.x;
        this.nw.y = nw.y;
        this.ne.x = ne.x;
        this.ne.y = ne.y;

    }

    /** Set this ControlQuad to the unit square, which
     *  encodes the identity transform for StretchXY.
     *  (Re)allocate all four points.
     */
    public void reset() {
        sw = new Point2D.Double(0.0, 0.0);
        se = new Point2D.Double(1.0, 0.0);
        nw = new Point2D.Double(0.0, 1.0);
        ne = new Point2D.Double(1.0, 1.0);
    }

    /** Take the other's corner values and set them on this ControlQuad.
     *  If the other sends a value as null instead of a double, ignore
     *  it and keep the old value. Use this to eliminate boilerplate from the
     *  simple act of keeping this ControlQuad in a valid state for stretching.
     */
    public void setDoubleValues(ControlQuad other) {
        if(other != null) {
            if(other.sw != null) {
                sw.x = other.sw.x;
                sw.y = other.sw.y;
            }
            if(other.se != null) {
                se.x = other.se.x;
                se.y = other.se.y;
            }
            if(other.nw != null) {
                nw.x = other.nw.x;
                nw.y = other.nw.y;
            }
            if(other.ne != null) {
                ne.x = other.ne.x;
                ne.y = other.ne.y;
            }
        }
    }

    public Point2D.Double stretchXY(Point2D.Double xy) {
        return Stretch.stretchXY(xy, sw, se, nw, ne);
    }

    /** In JSON-compatible format. */
    public String toString() {
        return "[["+sw.x+","+sw.y+"],["+se.x+","+se.y+"],["+nw.x+","+nw.y+"],["+ne.x+","+ne.y+"]]";
    }
}


text:
package GameState;

/**
 * Created by Michael on 5/6/2016.
 */
public interface I_State
{
    public String display();

    public I_State execute();

    public boolean isEndOfGame();
}


text:
from datetime import datetime, date
from flask import Blueprint
from sqlalchemy import inspect, and_, orm

from ggrc import db
from ggrc.login import get_current_user
from ggrc.models import all_models
from ggrc.models.relationship import Relationship
from ggrc.rbac.permissions import is_allowed_update
from ggrc.services.common import Resource, log_event
from ggrc.services.registry import service
from ggrc_workflows import models, notification
from ggrc_workflows.models import relationship_helper
from ggrc_workflows.models import WORKFLOW_OBJECT_TYPES
from ggrc_workflows.converters import IMPORTABLE, EXPORTABLE
from ggrc_workflows.converters.handlers import COLUMN_HANDLERS
from ggrc_workflows.services.common import Signals
from ggrc_workflows.services import workflow_cycle_calculator
from ggrc_workflows.roles import (
    WorkflowOwner, WorkflowMember, BasicWorkflowReader, WorkflowBasicReader
)
from ggrc_basic_permissions.models import Role, UserRole, ContextImplication
from ggrc_basic_permissions.contributed_roles import (
    RoleContributions, RoleDeclarations, DeclarativeRoleImplications
)

# Initialize Flask Blueprint for extension
blueprint = Blueprint(
    'ggrc_workflows',
    __name__,
    template_folder='templates',
    static_folder='static',
    static_url_path='/static/ggrc_workflows',
)

for type_ in WORKFLOW_OBJECT_TYPES:
  model = getattr(all_models, type_)
  model.__bases__ = (
      models.task_group_object.TaskGroupable,
      models.cycle_task_group_object_task.CycleTaskable,
      models.workflow.WorkflowState,
  ) + model.__bases__
  model.late_init_task_groupable()

def get_public_config(current_user):  # noqa
  """Expose additional permissions-dependent config to client.
  """
  return {}

# Initialize service endpoints

def contributed_services():
  return [
      service('workflows', models.Workflow),
      service('workflow_people', models.WorkflowPerson),
      service('task_groups', models.TaskGroup),
      service('task_group_tasks', models.TaskGroupTask),
      service('task_group_objects', models.TaskGroupObject),

      service('cycles', models.Cycle),
      service('cycle_task_entries', models.CycleTaskEntry),
      service('cycle_task_groups', models.CycleTaskGroup),
      service('cycle_task_group_object_tasks', models.CycleTaskGroupObjectTask)
  ]

def contributed_object_views():
  """Contributed object views"""
  from ggrc.views.registry import object_view

  return [
      object_view(models.Workflow),
  ]

DONE_STATUSES = ("Verified",)

def _get_min_next_due_date(due_dated_objects, exclude_statuses=DONE_STATUSES):
  next_due_date = None

  for obj in due_dated_objects:
    if obj.status not in exclude_statuses:
      obj_next_due_date = obj.next_due_date
      if isinstance(obj_next_due_date, datetime):
        obj_next_due_date = obj_next_due_date.date()
      if obj_next_due_date is not None:
        if next_due_date is None or next_due_date > obj_next_due_date:
          next_due_date = obj_next_due_date

  return next_due_date

def _get_min_end_date(timeboxed_objects, exclude_statuses=DONE_STATUSES):
  end_date = None

  for obj in timeboxed_objects:
    if obj.status not in exclude_statuses:
      obj_end_date = obj.end_date
      if isinstance(obj_end_date, datetime):
        obj_end_date = obj_end_date.date()
      if obj_end_date is not None:
        if end_date is None or end_date > obj_end_date:
          end_date = obj_end_date
  return end_date

def _get_date_range(timeboxed_objects):
  start_date = None
  end_date = None

  for obj in timeboxed_objects:
    obj_start_date = obj.start_date
    if isinstance(obj_start_date, datetime):
      obj_start_date = obj_start_date.date()
    obj_end_date = obj.end_date
    if isinstance(obj_end_date, datetime):
      obj_end_date = obj_end_date.date()
    if obj_start_date is not None:
      if start_date is None or start_date > obj_start_date:
        start_date = obj_start_date
    if obj_end_date is not None:
      if end_date is None or end_date < obj_end_date:
        end_date = obj_end_date
  return start_date, end_date

def update_cycle_dates(cycle):
  """ This gets all cycle task groups and tasks associated with a cycle and
  calculates the start and end date for the cycle by aggregating cycle task
  dates to cycle task groups and then cycle task group dates to cycle.

  Args:
    cycle: Cycle for which we want to calculate the start and end dates.

  """
  if cycle.id:
    # If `cycle` is already in the database, then eager load required objects
    cycle = models.Cycle.query.filter_by(id=cycle.id).\
        options(orm
                .joinedload('cycle_task_groups')
                .joinedload('cycle_task_group_tasks')
                ).one()

  if not cycle.cycle_task_group_object_tasks and \
     cycle.workflow.kind != "Backlog":
    cycle.start_date, cycle.end_date = None, None
    cycle.next_due_date = None
    cycle.is_current = False
    db.session.add(cycle)
    return

  # Don't update cycle and cycle task group dates for backlog workflows
  if cycle.workflow.kind == "Backlog":
    return

  for ctg in cycle.cycle_task_groups:
    ctg.start_date, ctg.end_date = _get_date_range(
        ctg.cycle_task_group_tasks)
    ctg.next_due_date = _get_min_end_date(
        ctg.cycle_task_group_tasks)

  cycle.start_date, cycle.end_date = _get_date_range(cycle.cycle_task_groups)
  cycle.next_due_date = _get_min_next_due_date(cycle.cycle_task_groups)

@Resource.model_posted.connect_via(models.Cycle)
def handle_cycle_post(sender, obj=None, src=None, service=None):  # noqa pylint: disable=unused-argument
  if src.get('autogenerate', False):
    # When called via a REST POST, use current user.
    current_user = get_current_user()
    workflow = obj.workflow
    obj.calculator = workflow_cycle_calculator.get_cycle_calculator(workflow)

    if workflow.non_adjusted_next_cycle_start_date:
      base_date = workflow.non_adjusted_next_cycle_start_date
    else:
      base_date = date.today()
    build_cycle(obj, current_user=current_user, base_date=base_date)

    adjust_next_cycle_start_date(obj.calculator, workflow, move_forward=True)
    update_workflow_state(workflow)
    db.session.add(workflow)

def _create_cycle_task(task_group_task, cycle, cycle_task_group,
                       current_user, base_date=None):
  """Create a cycle task along with relations to other objects"""
  # TaskGroupTasks for one_time workflows don't save relative start/end
  # month/day. They only saves start and end dates.
  # TaskGroupTasks for all other workflow frequencies save the relative
  # start/end days.
  if not base_date:
    base_date = date.today()

  description = models.CycleTaskGroupObjectTask.default_description if \
      task_group_task.object_approval else task_group_task.description

  date_range = cycle.calculator.task_date_range(
      task_group_task, base_date=base_date)
  start_date, end_date = date_range

  cycle_task_group_object_task = models.CycleTaskGroupObjectTask(
      context=cycle.context,
      cycle=cycle,
      cycle_task_group=cycle_task_group,
      task_group_task=task_group_task,
      title=task_group_task.title,
      description=description,
      sort_index=task_group_task.sort_index,
      start_date=start_date,
      end_date=end_date,
      contact=task_group_task.contact,
      status="Assigned",
      modified_by=current_user,
      task_type=task_group_task.task_type,
      response_options=task_group_task.response_options,
  )
  return cycle_task_group_object_task

def create_old_style_cycle(cycle, task_group, cycle_task_group, current_user,
                           base_date):
  """ This function preserves the old style of creating cycles, so each object
  gets its own task assigned to it.
  """
  if len(task_group.task_group_objects) == 0:
    for task_group_task in task_group.task_group_tasks:
      cycle_task_group_object_task = _create_cycle_task(
          task_group_task, cycle, cycle_task_group,
          current_user, base_date)

  for task_group_object in task_group.task_group_objects:
    object_ = task_group_object.object
    for task_group_task in task_group.task_group_tasks:
      cycle_task_group_object_task = _create_cycle_task(
          task_group_task, cycle, cycle_task_group,
          current_user, base_date)
      db.session.add(Relationship(source=cycle_task_group_object_task,
                                  destination=object_))

def build_cycle(cycle, current_user=None, base_date=None):
  """Build a cycle with it's child objects"""

  if not base_date:
    base_date = date.today()

  # Determine the relevant Workflow
  workflow = cycle.workflow

  # Use WorkflowOwner role when this is called via the cron job.
  if not current_user:
    for user_role in workflow.context.user_roles:
      if user_role.role.name == "WorkflowOwner":
        current_user = user_role.person
        break

  # Populate the top-level Cycle object
  cycle.context = workflow.context
  cycle.title = workflow.title
  cycle.description = workflow.description
  cycle.status = 'Assigned'

  # Populate CycleTaskGroups based on Workflow's TaskGroups
  for task_group in workflow.task_groups:
    cycle_task_group = models.CycleTaskGroup(
        context=cycle.context,
        cycle=cycle,
        task_group=task_group,
        title=task_group.title,
        description=task_group.description,
        end_date=cycle.end_date,
        modified_by=current_user,
        contact=task_group.contact,
        status="Assigned",
        sort_index=task_group.sort_index,
    )

    # preserve the old cycle creation for old workflows, so each object
    # gets its own cycle task
    if workflow.is_old_workflow:
      create_old_style_cycle(cycle, task_group, cycle_task_group, current_user,
                             base_date)
    else:
      for task_group_task in task_group.task_group_tasks:
        cycle_task_group_object_task = _create_cycle_task(
            task_group_task, cycle, cycle_task_group, current_user, base_date)

        for task_group_object in task_group.task_group_objects:
          object_ = task_group_object.object
          db.session.add(Relationship(source=cycle_task_group_object_task,
                                      destination=object_))

  update_cycle_dates(cycle)

  Signals.workflow_cycle_start.send(
      cycle.__class__,
      obj=cycle,
      new_status=cycle.status,
      old_status=None
  )

# 'InProgress' states propagate via these links
_cycle_task_parent_attr = {
    models.CycleTaskGroupObjectTask: ['cycle_task_group'],
    models.CycleTaskGroup: ['cycle']
}

# 'Finished' and 'Verified' states are determined via these links
_cycle_task_children_attr = {
    models.CycleTaskGroup: ['cycle_task_group_tasks'],
    models.Cycle: ['cycle_task_groups']
}

def update_cycle_task_child_state(obj):

  status_order = (None, 'Assigned', 'InProgress',
                  'Declined', 'Finished', 'Verified')
  status = obj.status
  children_attrs = _cycle_task_children_attr.get(type(obj), [])
  for children_attr in children_attrs:
    if children_attr:
      children = getattr(obj, children_attr, None)
      for child in children:
        if status == 'Declined' or \
           status_order.index(status) > status_order.index(child.status):
          if is_allowed_update(child.__class__.__name__,
                               child.id, child.context.id):
            old_status = child.status
            child.status = status
            db.session.add(child)
            Signals.status_change.send(
                child.__class__,
                obj=child,
                new_status=child.status,
                old_status=old_status
            )
          update_cycle_task_child_state(child)

def update_cycle_task_parent_state(obj):  # noqa
  """Propagate changes to obj's parents"""

  if not is_allowed_update(obj.__class__.__name__,
                           obj.id, obj.context.id):
    return

  def update_parent(parent, old_status, new_status):
    """Update a parent element and emit a signal about the change"""
    parent.status = new_status
    db.session.add(parent)
    Signals.status_change.send(
        parent.__class__,
        obj=parent,
        old_status=old_status,
        new_status=new_status,
    )
    update_cycle_task_parent_state(parent)

  parent_attrs = _cycle_task_parent_attr.get(type(obj), [])
  for parent_attr in parent_attrs:
    if not parent_attr:
      continue

    parent = getattr(obj, parent_attr, None)
    old_status = parent.status
    if not parent:
      continue

    # Don't propagate changes to CycleTaskGroup if it's a part of backlog wf
    if isinstance(parent, models.CycleTaskGroup) \
       and parent.cycle.workflow.kind == "Backlog":
      continue

    # If any child is `InProgress`, then parent should be `InProgress`
    if obj.status in {"InProgress", "Declined"} and old_status != "InProgress":
      new_status = "InProgress"
      update_parent(parent, old_status, new_status)
    # If all children are `Finished` or `Verified`, then parent should be same
    elif obj.status in {"Finished", "Verified", "Assigned"}:
      children_attrs = _cycle_task_children_attr.get(type(parent), [])
      for children_attr in children_attrs:
        children = getattr(parent, children_attr, None)
        if not children:
          continue

        children_statues = [c.status for c in children]
        unique_statuses = set(children_statues)
        for status in ["Verified", "Finished", "Assigned"]:
          # Check if all elements match a certain state
          if children_statues[0] == status and len(unique_statuses) == 1:
            new_status = status
            update_parent(parent, old_status, new_status)

def ensure_assignee_is_workflow_member(workflow, assignee):
  """Checks what role assignee has in the context of
  a workflow. If he has none he gets the Workflow Member role."""
  if not assignee:
    return

  if any(assignee == wp.person for wp in workflow.workflow_people):
    return

  # Check if assignee is mapped to the Workflow
  workflow_people = models.WorkflowPerson.query.filter(
      models.WorkflowPerson.workflow_id == workflow.id,
      models.WorkflowPerson.person_id == assignee.id).count()
  if not workflow_people:
    workflow_person = models.WorkflowPerson(
        person=assignee,
        workflow=workflow,
        context=workflow.context
    )
    db.session.add(workflow_person)

  # Check if assignee has a role assignment
  from ggrc_basic_permissions.models import UserRole
  user_roles = UserRole.query.filter(
      UserRole.context_id == workflow.context_id,
      UserRole.person_id == assignee.id).count()
  if not user_roles:
    workflow_member_role = _find_role('WorkflowMember')
    user_role = UserRole(
        person=assignee,
        role=workflow_member_role,
        context=workflow.context,
        modified_by=get_current_user(),
    )
    db.session.add(user_role)

@Resource.model_put.connect_via(models.TaskGroupTask)
def handle_task_group_task_put(sender, obj=None, src=None, service=None):  # noqa pylint: disable=unused-argument
  if inspect(obj).attrs.contact.history.has_changes():
    ensure_assignee_is_workflow_member(obj.task_group.workflow, obj.contact)

  # If relative days were change we must update workflow next cycle start date
  workflow_modifying_attrs = [
      "relative_start_day", "relative_start_month",
      "relative_end_day", "relative_end_month"]

  if any(getattr(inspect(obj).attrs, attr).history.has_changes()
         for attr in workflow_modifying_attrs):
    db.session.add(obj)
    update_workflow_state(obj.task_group.workflow)

@Resource.model_posted.connect_via(models.TaskGroupTask)
def handle_task_group_task_post(sender, obj=None, src=None, service=None):  # noqa pylint: disable=unused-argument
  ensure_assignee_is_workflow_member(obj.task_group.workflow, obj.contact)
  update_workflow_state(obj.task_group.workflow)

@Resource.model_deleted.connect_via(models.TaskGroupTask)
def handle_task_group_task_delete(sender, obj=None, src=None, service=None):  # noqa pylint: disable=unused-argument
  db.session.flush()
  update_workflow_state(obj.task_group.workflow)

@Resource.model_put.connect_via(models.TaskGroup)
def handle_task_group_put(sender, obj=None, src=None, service=None):  # noqa pylint: disable=unused-argument
  if inspect(obj).attrs.contact.history.has_changes():
    ensure_assignee_is_workflow_member(obj.workflow, obj.contact)

@Resource.model_posted.connect_via(models.TaskGroup)
def handle_task_group_post(sender, obj=None, src=None, service=None):  # noqa pylint: disable=unused-argument
  source_task_group = None

  if src.get('clone'):
    source_task_group_id = src.get('clone')
    source_task_group = models.TaskGroup.query.filter_by(
        id=source_task_group_id
    ).first()
    source_task_group.copy(
        obj,
        clone_people=src.get('clone_people', False),
        clone_tasks=src.get('clone_tasks', False),
        clone_objects=src.get('clone_objects', False)
    )

    db.session.add(obj)
    db.session.flush()

    obj.title = source_task_group.title + ' (copy ' + str(obj.id) + ')'

  ensure_assignee_is_workflow_member(obj.workflow, obj.contact)

@Resource.model_deleted.connect_via(models.TaskGroup)
def handle_task_group_delete(sender, obj=None, src=None, service=None):  # noqa pylint: disable=unused-argument
  db.session.flush()
  update_workflow_state(obj.workflow)

@Resource.model_deleted.connect_via(models.CycleTaskGroupObjectTask)
def handle_cycle_task_group_object_task_delete(sender, obj=None,
                                               src=None, service=None):  # noqa pylint: disable=unused-argument
  db.session.flush()
  update_cycle_dates(obj.cycle)

@Resource.model_put.connect_via(models.CycleTaskGroupObjectTask)
def handle_cycle_task_group_object_task_put(
        sender, obj=None, src=None, service=None):  # noqa pylint: disable=unused-argument

  if inspect(obj).attrs.contact.history.has_changes():
    ensure_assignee_is_workflow_member(obj.cycle.workflow, obj.contact)

  if inspect(obj).attrs.start_date.history.has_changes() \
          or inspect(obj).attrs.end_date.history.has_changes():
    update_cycle_dates(obj.cycle)

  if inspect(obj).attrs.status.history.has_changes():
    # TODO: check why update_cycle_object_parent_state destroys object history
    # when accepting the only task in a cycle. The listener below is a
    # workaround because of that.
    Signals.status_change.send(
        obj.__class__,
        obj=obj,
        new_status=obj.status,
        old_status=inspect(obj).attrs.status.history.deleted.pop(),
    )
    update_cycle_task_parent_state(obj)

  # Doing this regardless of status.history.has_changes() is important in order
  # to update objects that have been declined. It updates the os_last_updated
  # date and last_updated_by.
  if getattr(obj.task_group_task, 'object_approval', None):
    for tgobj in obj.task_group_task.task_group.objects:
      if obj.status == 'Verified':
        tgobj.set_reviewed_state()
        db.session.add(tgobj)
    db.session.flush()

@Resource.model_posted.connect_via(models.CycleTaskGroupObjectTask)
def handle_cycle_task_group_object_task_post(
        sender, obj=None, src=None, service=None):  # noqa pylint: disable=unused-argument

  if obj.cycle.workflow.kind != "Backlog":
    ensure_assignee_is_workflow_member(obj.cycle.workflow, obj.contact)
  update_cycle_dates(obj.cycle)

  Signals.status_change.send(
      obj.__class__,
      obj=obj,
      new_status=obj.status,
      old_status=None,
  )
  update_cycle_task_parent_state(obj)
  db.session.flush()

@Resource.model_put.connect_via(models.CycleTaskGroup)
def handle_cycle_task_group_put(
        sender, obj=None, src=None, service=None):  # noqa pylint: disable=unused-argument
  if inspect(obj).attrs.status.history.has_changes():
    update_cycle_task_parent_state(obj)
    update_cycle_task_child_state(obj)

def update_workflow_state(workflow):
  today = date.today()
  calculator = workflow_cycle_calculator.get_cycle_calculator(workflow)

  # Start the first cycle if min_start_date < today < max_end_date
  if workflow.status == "Active" and workflow.recurrences and calculator.tasks:
    start_date, end_date = calculator.workflow_date_range()
    # Only create the cycle if we're mid-cycle
    if (start_date <= today <= end_date) \
            and not workflow.cycles:
      cycle = models.Cycle()
      cycle.workflow = workflow
      cycle.calculator = calculator
      # Other cycle attributes will be set in build_cycle.
      build_cycle(
          cycle,
          None,
          base_date=workflow.non_adjusted_next_cycle_start_date)
      notification.handle_cycle_created(None, obj=cycle)

    adjust_next_cycle_start_date(calculator, workflow)

    db.session.add(workflow)
    db.session.flush()
    return

  if not calculator.tasks:
    workflow.next_cycle_start_date = None
    workflow.non_adjusted_next_cycle_start_date = None
    return

  for cycle in workflow.cycles:
    if cycle.is_current:
      return

  if workflow.status == 'Draft':
    return

  if workflow.status == "Inactive":
    if workflow.cycles:
      workflow.status = "Active"
      db.session.add(workflow)
      db.session.flush()
      return

  # Active workflow with no recurrences and no active cycles, workflow is
  # now Inactive
  workflow.status = 'Inactive'
  db.session.add(workflow)
  db.session.flush()

# Check if workflow should be Inactive after end current cycle

@Resource.model_put.connect_via(models.Cycle)
def handle_cycle_put(
        sender, obj=None, src=None, service=None):  # noqa pylint: disable=unused-argument
  if inspect(obj).attrs.is_current.history.has_changes():
    update_workflow_state(obj.workflow)

# Check if workflow should be Inactive after recurrence change

@Resource.model_put.connect_via(models.Workflow)
def handle_workflow_put(
        sender, obj=None, src=None, service=None):  # noqa pylint: disable=unused-argument  # noqa pylint: disable=unused-argument
  update_workflow_state(obj)

@Resource.model_posted.connect_via(models.CycleTaskEntry)
def handle_cycle_task_entry_post(
        sender, obj=None, src=None, service=None):  # noqa pylint: disable=unused-argument
  if src['is_declining_review'] == '1':
    task = obj.cycle_task_group_object_task
    task.status = 'Declined'
    db.session.add(obj)
  else:
    src['is_declining_review'] = 0

# Check if workflow should be Inactive after cycle status change

@Signals.status_change.connect_via(models.Cycle)
def handle_cycle_status_change(sender, obj=None, new_status=None,  # noqa pylint: disable=unused-argument
                               old_status=None):  # noqa pylint: disable=unused-argument  # noqa pylint: disable=unused-argument
  if inspect(obj).attrs.status.history.has_changes():
    if obj.status == 'Verified':
      obj.is_current = False
      db.session.add(obj)
      update_workflow_state(obj.workflow)

@Signals.status_change.connect_via(models.CycleTaskGroupObjectTask)
def handle_cycle_task_status_change(sender, obj=None, new_status=None,  # noqa pylint: disable=unused-argument
                                    old_status=None):  # noqa pylint: disable=unused-argument
  if inspect(obj).attrs.status.history.has_changes():
    if new_status == 'Verified':
      obj.verified_date = datetime.now()
    elif new_status == 'Finished':
      obj.finished_date = datetime.now()
      obj.verified_date = None
    else:
      obj.finished_date = None
      obj.verified_date = None

def _get_or_create_personal_context(user):
  personal_context = user.get_or_create_object_context(
      context=1,
      name='Personal Context for {0}'.format(user.id),
      description='',
  )
  personal_context.modified_by = get_current_user()
  db.session.add(personal_context)
  db.session.flush()
  return personal_context

def _find_role(role_name):
  return db.session.query(Role).filter(Role.name == role_name).first()

@Resource.model_posted.connect_via(models.WorkflowPerson)
def handle_workflow_person_post(sender, obj=None, src=None, service=None):  # noqa pylint: disable=unused-argument
  db.session.flush()

  # add a user_roles mapping assigning the user creating the workflow
  # the WorkflowOwner role in the workflow's context.
  workflow_member_role = _find_role('WorkflowMember')
  user_role = UserRole(
      person=obj.person,
      role=workflow_member_role,
      context=obj.context,
      modified_by=get_current_user(),
  )
  db.session.add(user_role)

@Resource.model_posted.connect_via(models.Workflow)
def handle_workflow_post(sender, obj=None, src=None, service=None):  # noqa pylint: disable=unused-argument
  source_workflow = None

  if src.get('clone'):
    source_workflow_id = src.get('clone')
    source_workflow = models.Workflow.query.filter_by(
        id=source_workflow_id
    ).first()
    source_workflow.copy(obj)
    db.session.add(obj)
    db.session.flush()
    obj.title = source_workflow.title + ' (copy ' + str(obj.id) + ')'

  db.session.flush()
  # get the personal context for this logged in user
  user = get_current_user()
  personal_context = _get_or_create_personal_context(user)
  context = obj.build_object_context(
      context=personal_context,
      name='{object_type} Context {timestamp}'.format(
          object_type=service.model.__name__,
          timestamp=datetime.now()),
      description='',
  )
  context.modified_by = get_current_user()

  db.session.add(obj)
  db.session.flush()
  db.session.add(context)
  db.session.flush()
  obj.contexts.append(context)
  obj.context = context

  # add a user_roles mapping assigning the user creating the workflow
  # the WorkflowOwner role in the workflow's context.
  workflow_owner_role = _find_role('WorkflowOwner')
  user_role = UserRole(
      person=user,
      role=workflow_owner_role,
      context=context,
      modified_by=get_current_user(),
  )
  db.session.add(models.WorkflowPerson(
      person=user,
      workflow=obj,
      context=context,
      modified_by=get_current_user(),
  ))
  # pass along a temporary attribute for logging the events.
  user_role._display_related_title = obj.title
  db.session.add(user_role)
  db.session.flush()

  # Create the context implication for Workflow roles to default context
  db.session.add(ContextImplication(
      source_context=context,
      context=None,
      source_context_scope='Workflow',
      context_scope=None,
      modified_by=get_current_user(),
  ))

  if not src.get('private'):
    # Add role implication - all users can read a public workflow
    add_public_workflow_context_implication(context)

  if src.get('clone'):
    source_workflow.copy_task_groups(
        obj,
        clone_people=src.get('clone_people', False),
        clone_tasks=src.get('clone_tasks', False),
        clone_objects=src.get('clone_objects', False)
    )

    if src.get('clone_people'):
      workflow_member_role = _find_role('WorkflowMember')
      for authorization in source_workflow.context.user_roles:
        # Current user has already been added as workflow owner
        if authorization.person != user:
          db.session.add(UserRole(
              person=authorization.person,
              role=workflow_member_role,
              context=context,
              modified_by=user))
      for person in source_workflow.people:
        if person != user:
          db.session.add(models.WorkflowPerson(
              person=person,
              workflow=obj,
              context=context))

def add_public_workflow_context_implication(context, check_exists=False):
  if check_exists and db.session.query(ContextImplication).filter(
      and_(ContextImplication.context_id == context.id,
           ContextImplication.source_context_id == None)).count() > 0:  # noqa
    return
  db.session.add(ContextImplication(
      source_context=None,
      context=context,
      source_context_scope=None,
      context_scope='Workflow',
      modified_by=get_current_user(),
  ))

def init_extra_views(app):
  from . import views
  views.init_extra_views(app)

def start_recurring_cycles():
  # Get all workflows that should start a new cycle today
  # The next_cycle_start_date is precomputed and stored when a cycle is created
  today = date.today()
  workflows = db.session.query(models.Workflow)\
      .filter(
      models.Workflow.next_cycle_start_date == today,
      models.Workflow.recurrences == True  # noqa
  ).all()

  # For each workflow, start and save a new cycle.
  for workflow in workflows:
    cycle = models.Cycle()
    cycle.workflow = workflow
    cycle.calculator = workflow_cycle_calculator.get_cycle_calculator(workflow)
    cycle.context = workflow.context
    # We can do this because we selected only workflows with
    # next_cycle_start_date = today
    cycle.start_date = date.today()

    # Flag the cycle to be saved
    db.session.add(cycle)

    if workflow.non_adjusted_next_cycle_start_date:
      base_date = workflow.non_adjusted_next_cycle_start_date
    else:
      base_date = date.today()

    # Create the cycle (including all child objects)
    build_cycle(cycle, base_date=base_date)

    # Update the workflow next_cycle_start_date to push it ahead based on the
    # frequency.
    adjust_next_cycle_start_date(cycle.calculator, workflow, move_forward=True)

    db.session.add(workflow)

    notification.handle_workflow_modify(None, workflow)
    notification.handle_cycle_created(None, obj=cycle)

  log_event(db.session)
  db.session.commit()

def get_cycles(workflow):
  def is_valid_cycle(cycle):
    return ([ct for ct in cycle.cycle_task_group_object_tasks] and
            isinstance(cycle.start_date, (date, datetime)))
  return [c for c in workflow.cycles if is_valid_cycle(c)]

def adjust_next_cycle_start_date(
        calculator,
        workflow,
        base_date=None,
        move_forward=False):
  """Sets new cycle start date - it either recalculates a start date or moves
  it forward one interval if manual cycle start was requested or cycle
  was generated with start_recurring_cycles on next cycle start date.

  Args:
    calculator: Calculator that should be used for calculations
    workflow: Workflow that will have non adjusted and adjusted next cycle
              start date calculated.
    base_date: Date to be used for calculations
    move_forward: If true, NCSD will be calculated for next time unit,
                  otherwise it will recalculate on current time unit.
  """
  if not workflow.recurrences:
    return

  # If cycles were not generated already, recalculate start date with
  # fresh start.
  cycles = get_cycles(workflow)
  if not cycles:
    workflow.next_cycle_start_date = None
    workflow.non_adjusted_next_cycle_start_date = None
  else:
    # When all tasks got deleted we take last cycle start date as a base_date
    # from which to calculate
    if not workflow.non_adjusted_next_cycle_start_date:
      last_cycle_start_date = max([c.start_date for c in cycles])
      first_task = calculator.tasks[0]
      first_task_reified = calculator.relative_day_to_date(
          relative_day=first_task.relative_start_day,
          relative_month=first_task.relative_start_month,
          base_date=last_cycle_start_date
      )

      # In an edge case where reified first task happens before last cycle
      # start date, we should be calculating on the next time unit.
      if last_cycle_start_date >= first_task_reified:
        last_cycle_start_date = last_cycle_start_date + calculator.time_delta

      result = calculator.relative_day_to_date(
          relative_day=first_task.relative_start_day,
          relative_month=first_task.relative_start_month,
          base_date=last_cycle_start_date
      )
      if isinstance(result, datetime):
        result = result.date()
      workflow.non_adjusted_next_cycle_start_date = result

  # Unless we are moving forward one interval we just want to recalculate
  # the next_cycle_start_date to reflect the latest changes to the
  # task(s) - therefore, we just unwind one time unit backward and calculate
  # new next cycle start date.
  if not move_forward and workflow.non_adjusted_next_cycle_start_date:
    workflow.non_adjusted_next_cycle_start_date = (
        workflow.non_adjusted_next_cycle_start_date - calculator.time_delta)

  non_adjusted_ncsd = calculator.non_adjusted_next_cycle_start_date(
      base_date=workflow.non_adjusted_next_cycle_start_date)

  # In an edge case where we unwinded into the past for editing and
  # the next cycle start date returned back is less than or equal today,
  # we shouldn't have unwinded - therefore, we recalculate with
  # original value.
  if non_adjusted_ncsd <= date.today():
    workflow.non_adjusted_next_cycle_start_date = (
        workflow.non_adjusted_next_cycle_start_date + calculator.time_delta)
    non_adjusted_ncsd = calculator.non_adjusted_next_cycle_start_date(
        base_date=workflow.non_adjusted_next_cycle_start_date)

  workflow.non_adjusted_next_cycle_start_date = non_adjusted_ncsd
  workflow.next_cycle_start_date = calculator.adjust_date(non_adjusted_ncsd)

class WorkflowRoleContributions(RoleContributions):
  contributions = {
      'ProgramCreator': {
          'read': ['Workflow'],
          'create': ['Workflow'],
      },
      'Creator': {
          'create': ['Workflow', 'CycleTaskGroupObjectTask']
      },
      'Editor': {
          'read': ['Workflow', 'CycleTaskGroupObjectTask'],
          'create': ['Workflow', 'CycleTaskGroupObjectTask'],
          'update': ['CycleTaskGroupObjectTask'],
          'edit': ['CycleTaskGroupObjectTask'],
          'delete': ['CycleTaskGroupObjectTask']
      },
      'Reader': {
          'read': ['Workflow', 'CycleTaskGroupObjectTask'],
          'create': ['Workflow', 'CycleTaskGroupObjectTask'],
      },
      'ProgramEditor': {
          'read': ['Workflow'],
          'create': ['Workflow'],
      },
      'ProgramOwner': {
          'read': ['Workflow'],
          'create': ['Workflow'],
      },
  }

class WorkflowRoleDeclarations(RoleDeclarations):

  def roles(self):
    return {
        'WorkflowOwner': WorkflowOwner,
        'WorkflowMember': WorkflowMember,
        'BasicWorkflowReader': BasicWorkflowReader,
        'WorkflowBasicReader': WorkflowBasicReader,
    }

class WorkflowRoleImplications(DeclarativeRoleImplications):
  # (Source Context Type, Context Type)
  #   -> Source Role -> Implied Role for Context
  implications = {
      (None, 'Workflow'): {
          'ProgramCreator': ['BasicWorkflowReader'],
          'Editor': ['WorkflowOwner'],
          'Reader': ['BasicWorkflowReader'],
          'Creator': ['WorkflowBasicReader'],
      },
      ('Workflow', None): {
          'WorkflowOwner': ['WorkflowBasicReader'],
          'WorkflowMember': ['WorkflowBasicReader'],
      },
  }

ROLE_CONTRIBUTIONS = WorkflowRoleContributions()
ROLE_DECLARATIONS = WorkflowRoleDeclarations()
ROLE_IMPLICATIONS = WorkflowRoleImplications()

contributed_notifications = notification.contributed_notifications
contributed_importables = IMPORTABLE
contributed_exportables = EXPORTABLE
contributed_column_handlers = COLUMN_HANDLERS
contributed_get_ids_related_to = relationship_helper.get_ids_related_to
CONTRIBUTED_CRON_JOBS = [start_recurring_cycles]
NOTIFICATION_LISTENERS = [notification.register_listeners]


text:
class Input_buffer;

// The parser performs syntactic analysis, transforming
// a token stream into an AST.
class Parser
{
public:
  Parser(Symbol_table&, Token_stream&);
  Parser(Symbol_table&, Token_stream&, Location_map&);

  // Expression parsers
  Expr* primary_expr();
  Expr* call_expr();
  Expr* postfix_expr();
  Expr* unary_expr();
  Expr* multiplicative_expr();
  Expr* additive_expr();
  Expr* bitshift_expr();
  Expr* ordering_expr();
  Expr* equality_expr();
  Expr* bitwise_and_expr();
  Expr* bitwise_xor_expr();
  Expr* bitwise_or_expr();
  Expr* logical_and_expr();
  Expr* logical_or_expr();
  Expr* field_name_expr();
  Expr* field_access_expr();
  Expr* expr();

  // Postfix expr
  Expr* dot_expr(Expr*);
  Expr* call_expr(Expr*);

  // Type parsers
  Type const* integer_type();
  Type const* unsigned_integer_type();
  Type const* primary_type();
  Type const* postfix_type();
  Type const* type();

  // Declaration parsers
  Decl* decl();
  Decl* variable_decl(Specifier);
  Decl* function_decl(Specifier);
  Decl* parameter_decl();
  Decl* record_decl(Specifier);
  Decl* field_decl(Specifier);
  Decl* method_decl(Specifier);
  Specifier specifier_seq();

  // network specific
  Decl* layout_decl();
  Decl* decode_decl();
  Decl* exact_table_decl();
  Decl* key_decl();
  Decl* inport_key_decl();
  Decl* inphysport_key_decl();
  Decl* flow_decl();
  Decl* port_decl();
  Decl* extract_decl();
  Decl* rebind_decl();
  Decl* event_decl();

  // Statement parsers
  Stmt* stmt();
  Stmt* empty_stmt();
  Stmt* block_stmt();
  Stmt* return_stmt();
  Stmt* if_stmt();
  Stmt* while_stmt();
  Stmt* break_stmt();
  Stmt* continue_stmt();
  Stmt* declaration_stmt();
  Stmt* expression_stmt();
  Stmt* match_stmt();
  Stmt* case_stmt();
  Stmt* miss_case_stmt();
  Stmt* decode_stmt();
  Stmt* goto_stmt();
  Stmt* drop_stmt();
  Stmt* clear_stmt();
  Stmt* output_stmt();
  Stmt* set_stmt();
  Stmt* copy_stmt();
  Stmt* write_stmt();
  Stmt* add_flow_stmt();
  Stmt* rmv_flow_stmt();
  Stmt* raise_stmt();

  // Top-level.
  Decl* module(Module_decl*);

  // Helpers
  Expr_seq parse_colon_seperated(Token tok);
  Symbol const* get_qualified_name(Expr_seq const&);
  Stmt_seq flow_properties();

  // Parse state
  bool ok() const { return errs_ == 0; }

  explicit operator bool() const { return ok(); }

private:
  // Actions
  Type const* on_id_type(Token);
  Type const* on_reference_type(Type const*);
  Type const* on_array_type(Type const*, Expr*);
  Type const* on_block_type(Type const*);
  Type const* on_function_type(Type_seq const&, Type const*);

  Expr* on_id(Token);
  Expr* on_bool(Token);
  Expr* on_int(Token);
  Expr* on_uint(Token);
  Expr* on_hex(Token);
  Expr* on_binary(Token);
  Expr* on_char(Token);
  Expr* on_str(Token);
  Expr* on_add(Expr*, Expr*);
  Expr* on_sub(Expr*, Expr*);
  Expr* on_mul(Expr*, Expr*);
  Expr* on_div(Expr*, Expr*);
  Expr* on_rem(Expr*, Expr*);
  Expr* on_lshift(Expr*, Expr*);
  Expr* on_rshift(Expr*, Expr*);
  Expr* on_bitwise_and(Expr*, Expr*);
  Expr* on_bitwise_or(Expr*, Expr*);
  Expr* on_xor(Expr*, Expr*);
  Expr* on_neg(Expr*);
  Expr* on_pos(Expr*);
  Expr* on_eq(Expr*, Expr*);
  Expr* on_ne(Expr*, Expr*);
  Expr* on_lt(Expr*, Expr*);
  Expr* on_gt(Expr*, Expr*);
  Expr* on_le(Expr*, Expr*);
  Expr* on_ge(Expr*, Expr*);
  Expr* on_and(Expr*, Expr*);
  Expr* on_or(Expr*, Expr*);
  Expr* on_not(Expr*);
  Expr* on_call(Expr*, Expr_seq const&);
  Expr* on_index(Expr*, Expr*);
  Expr* on_dot(Expr*, Expr*);
  Expr* on_field_name(Expr_seq const&);
  Expr* on_field_access(Expr_seq const&);
  Expr* on_inport(Token);
  Expr* on_inphysport(Token);
  Expr* on_all_port(Token);
  Expr* on_controller_port(Token);
  Expr* on_reflow_port(Token);
  Expr* on_flood_port(Token);
  Expr* on_egress_port(Token);

  Decl* on_variable(Specifier, Token, Type const*);
  Decl* on_variable(Specifier, Token, Type const*, Expr*);
  Decl* on_parameter(Specifier, Type const*);
  Decl* on_parameter(Specifier, Token, Type const*);
  Decl* on_function(Specifier, Token, Decl_seq const&, Type const*);
  Decl* on_function(Specifier, Token, Decl_seq const&, Type const*, Stmt*);
  Decl* on_record(Specifier, Token, Decl_seq const&, Decl_seq const&, Type const*);
  Decl* on_field(Specifier, Token, Type const*);
  Decl* on_method(Specifier, Token, Decl_seq const&, Type const*, Stmt*);
  Decl* on_module(Module_decl*, Decl_seq const&);

  Decl* on_layout(Token, Decl_seq const&);
  Decl* on_decoder(Token, Type const*, Stmt*, bool);
  Decl* on_extract(Expr*);
  Decl* on_rebind(Expr*, Expr*);
  Decl* on_exact_table(Token, Decl_seq&, Expr_seq&, Decl_seq&, Decl*);
  Decl* on_key(Expr*);
  Decl* on_inport_key(Token);
  Decl* on_inphysport_key(Token);
  Decl* on_flow(Expr_seq const&, Stmt*, Stmt_seq const&);
  Decl* on_flow_miss(Stmt*, Stmt_seq const&);
  Decl* on_port(Token, Expr*);
  Decl* on_event(Token, Expr_seq const&, Stmt*);

  // FIXME: Remove _stmt from handlers.
  Stmt* on_empty();
  Stmt* on_block(Stmt_seq const&);
  Stmt* on_assign(Expr*, Expr*);
  Stmt* on_return(Expr*);
  Stmt* on_if_then(Expr*, Stmt*);
  Stmt* on_if_else(Expr*, Stmt*, Stmt*);
  Stmt* on_while(Expr*, Stmt*);
  Stmt* on_break();
  Stmt* on_continue();
  Stmt* on_expression(Expr*);
  Stmt* on_declaration(Decl*);

  Stmt* on_case(Expr*, Stmt*);
  Stmt* on_match(Expr*, Stmt_seq&, Stmt*);
  Stmt* on_decode(Expr*, Expr*);
  Stmt* on_goto(Expr*, Expr*);
  Stmt* on_drop();
  Stmt* on_clear();
  Stmt* on_output(Expr*);
  Stmt* on_set(Expr*, Expr*);
  Stmt* on_copy(Expr*, Expr*);
  Stmt* on_write(Stmt*);
  Stmt* on_add_flow(Decl*, Expr*);
  Stmt* on_rmv_flow(Expr_seq const&, Expr*);
  Stmt* on_rmv_miss(Expr*);
  Stmt* on_raise(Expr*, Expr*);

  // Parsing support
  Token_kind lookahead() const;
  Token_kind lookahead(int) const;
  Token      match(Token_kind);
  Token      match_if(Token_kind);
  Token      require(Token_kind);
  Token      accept();
  void       consume_until(Token_kind);
  void       consume_thru(Token_kind);

  // Error handling. These functions throw
  // exceptions. They never return.
  [[noreturn]] void error(char const*);
  [[noreturn]] void error(String const&);

  // Location management
  void locate(void*, Location);
  Location locate(void*);

  template<typename T, typename... Args>
  T* init(Location, Args&&...);

private:
  Symbol_table& syms_;
  Token_stream& ts_;
  Location_map* locs_;

  Specifier spec_;  // Current specifeirs

  int errs_;        // Error count

  // Parse flags
  Token_kind term_; // Statement termination token.
};

inline
Parser::Parser(Symbol_table& s, Token_stream& t)
  : syms_(s), ts_(t), locs_(nullptr), errs_(0), term_()
{ }

inline
Parser::Parser(Symbol_table& s, Token_stream& t, Location_map& l)
  : syms_(s), ts_(t), locs_(&l), errs_(0), term_()
{ }

// Returns the first token of lookahead.
inline Token_kind
Parser::lookahead() const
{
  return Token_kind(ts_.peek().kind());
}

// Returns the nth token of lookahead.
inline Token_kind
Parser::lookahead(int n) const
{
  return Token_kind(ts_.peek(n).kind());
}

// Save the location of the declaratio.
inline void
Parser::locate(void* p, Location l)
{
  locs_->emplace(p, l);
}

inline Location
Parser::locate(void* p)
{
  auto iter = locs_->find(p);
  if (iter != locs_->end())
    return iter->second;
  else
    return {};
}

// A helper function to create nodes and record their
// source location.
//
// TODO: Put this in the .cpp file? It is private.
template<typename T, typename... Args>
inline T*
Parser::init(Location loc, Args&&... args)
{
  T* t = new T(std::forward<Args>(args)...);
  locs_->emplace(t, loc);
  return t;
}

#endif


text:
var uie = require('lib/IndicatorWindow');
var indicator = uie.createIndicatorWindow({
    top : 200,
    text : Alloy.Globals.PHRASES.loadingTxt
});
var argsIn = arguments[0] || {};
var profileView = null;
profileView = argsIn.profile;

var fontawesome = require('lib/IconicFont').IconicFont({
    font : 'lib/FontAwesome'
});

var isAndroid = false;
var context;

if (OS_ANDROID) {
    isAndroid = true;
    $.settingsWindow.orientationModes = [Titanium.UI.PORTRAIT];

    $.settingsWindow.addEventListener('open', function() {
        Alloy.Globals.setAndroidCouponMenu($.settingsWindow.activity);

        $.settingsWindow.activity.actionBar.onHomeIconItemSelected = function() {
            if($.settingsWindow) {
                $.settingsWindow.close();
            	$.settingsWindow = null;
            }
        };
        $.settingsWindow.activity.actionBar.displayHomeAsUp = true;
        $.settingsWindow.activity.actionBar.title = Alloy.Globals.PHRASES.settingsTxt;
    });

    context = require('lib/Context');
} else {
    $.settingsWindow.titleControl = Ti.UI.createLabel({
        text : Alloy.Globals.PHRASES.settingsTxt,
        font : Alloy.Globals.getFontCustom(18, "Bold"),
        color : '#FFF'
    });
}

function onOpen(evt) {
    if(isAndroid) {
        context.on('settingsActivity', this.activity);
    }
}

function onClose(evt) {
    if(isAndroid) {
        context.off('settingsActivity');
    }
}

var picker;

// hide modal pickers (ios)
$.settingsWindow.addEventListener('close', function() {
    indicator.closeIndicator();
    if (!isAndroid) {
        picker.close();
    }
});

function changeLanguageConfirm(lang) {
    var languageDescription = Alloy.Globals.AVAILABLELANGUAGES[lang].description;

    var alertWindow = Titanium.UI.createAlertDialog({
        title : Alloy.Globals.PHRASES.betbattleTxt,
        message : Alloy.Globals.PHRASES.confirmLanguageChangeTxt + ' "' + languageDescription + '"?',
        buttonNames : [Alloy.Globals.PHRASES.okConfirmTxt, Alloy.Globals.PHRASES.abortBtnTxt]
    });

    alertWindow.addEventListener('click', function(e) {
        switch (e.index) {
        case 0:
            alertWindow.hide();
            Alloy.Globals.LOCALE = Alloy.Globals.AVAILABLELANGUAGES[lang].name;
            getLanguage();
            break;
        case 1:
            alertWindow.hide();
            break;
        }
    });
    alertWindow.show();
}

function sendSettingsServer(param, type, valueToStore) {
    // check connection
    if (Alloy.Globals.checkConnection()) {
        indicator.openIndicator();

        var xhr = Titanium.Network.createHTTPClient();
        xhr.onerror = function(e) {
            indicator.closeIndicator();
            Ti.API.error('Bad Sever =>' + JSON.stringify(e));
            Alloy.Globals.showFeedbackDialog(JSON.parse(this.responseText));

            //if (e.code === 400) {
                // Alloy.Globals.showFeedbackDialog(Alloy.Globals.PHRASES.nameUnique);
            //}
        };

        try {
            xhr.open('POST', Alloy.Globals.BETKAMPENSETTINGURL);
            xhr.setRequestHeader("content-type", "application/json");
            xhr.setRequestHeader("Authorization", Alloy.Globals.BETKAMPEN.token);
            xhr.setTimeout(Alloy.Globals.TIMEOUT);
            xhr.send(param);
        } catch(e) {
            indicator.closeIndicator();
            Alloy.Globals.showFeedbackDialog(JSON.stringify(e));
        }

        xhr.onload = function() {
            if (this.status == '200') {
                if (this.readyState == 4) {
                    if (type === 0) {
                        // store value about push
                        Ti.App.Properties.setBool("pushSetting", valueToStore);
                        if (isAndroid) {
        					$.table.setData($.table.data);
        				}
                    } else if (type === 1) {
                        // name change
                        Alloy.Globals.PROFILENAME = valueToStore;

                        // set name in view
                        $.profile_name_value_label.text = valueToStore;
                        if (Alloy.Globals.PROFILENAME.length > 12) {
                            $.profile_name_value_label.text = Alloy.Globals.PROFILENAME.substring(0, 9) + '...';
                        }

                        // update event
                        Ti.App.fireEvent('app:updateMenu');
                        Ti.App.fireEvent('userInfoUpdate');
                    }
                    Alloy.Globals.showToast(JSON.parse(this.responseText));
                }
                indicator.closeIndicator();
            } else {
                indicator.closeIndicator();
                Alloy.Globals.showToast(JSON.parse(this.responseText));
                Ti.API.error("Error =>" + this.response);
            }
        };
    } else {
        Alloy.Globals.showFeedbackDialog(Alloy.Globals.PHRASES.noConnectionErrorTxt);
    }
}

function createGUI() {
    if (isAndroid) {
        $.table.headerView = Ti.UI.createView({
            height : 0.5,
            backgroundColor : '#303030'
        });

        $.table.footerView = Ti.UI.createView({
            height : 0.5,
            backgroundColor : '#303030'
        });
    } else {
        var iOSVersion;
        iOSVersion = parseInt(Ti.Platform.version);

        if (iOSVersion < 7) {
            $.table.separatorStyle = Titanium.UI.iPhone.TableViewSeparatorStyle.NONE;
            $.table.separatorColor = 'transparent';
        } else {
            $.table.separatorStyle = Titanium.UI.iPhone.TableViewSeparatorStyle.SINGLE_LINE;
        }

        $.table.headerView = Ti.UI.createView({
            height : 0.3,
            top : 0,
            width : Ti.UI.FILL,
            layout : 'vertical',
            backgroundColor : '#303030',
        });

        $.table.footerView = Ti.UI.createView({
            height : 0,
            top : 0,
            width : Ti.UI.FILL,
            layout : 'vertical',
            backgroundColor : "transparent",
        });
    }

    /* First row */
    $.language_row.add(createPickers());
    $.language_row.addEventListener('click', function() {
        if (picker.open) {
            // the picker is visible, don't do anything
            return;
        }
        picker.fireEvent('click');
    });

    /* Second row */
    var pushEnabled;

    // true will be set if no stored value is found
    if (!Ti.App.Properties.hasProperty("pushSetting")) {
        Ti.App.Properties.setBool("pushSetting", true);
    }

    pushEnabled = Ti.App.Properties.getBool('pushSetting');
    var basicSwitch;

    if (!isAndroid) {
        basicSwitch = Ti.UI.createSwitch({
            right : 10,
            width : 40,
            titleOn : Alloy.Globals.PHRASES.onTxt,
            titleOff : Alloy.Globals.PHRASES.offTxt,
            value : pushEnabled
        });
    } else {
        basicSwitch = Ti.UI.createSwitch({
  			style: Titanium.UI.Android.SWITCH_STYLE_SWITCH,
            titleOn : Alloy.Globals.PHRASES.onTxt,
            titleOff : Alloy.Globals.PHRASES.offTxt,
  			value: pushEnabled,
            right : 10,
            width : 80,
		});
    }

    basicSwitch.addEventListener('change', function(e) {
        var value = 0;
        if (basicSwitch.value) {
            value = 1;
        }

        // build the json string
        var deviceType = Titanium.Platform.osname;
        var param = '{"device_token":"' + Alloy.Globals.DEVICETOKEN + '", "device_type":"' + deviceType + '", "push_status":' + value + ', "app_identifier":"' + Alloy.Globals.APPID + '", "lang":"' + Alloy.Globals.LOCALE + '"}';
        // send to backend
        if (Alloy.Globals.DEVICETOKEN) {
            // only send if not emulator
            sendSettingsServer(param, 0, basicSwitch.value);
        }
    });
    $.push_notification_row.selectionStyle = 'none';
    $.push_notification_row.add(basicSwitch);

    /* Third row */
    $.upload_indicator.message = $.upload_indicator.message + '...';

    $.profile_picture_row.addEventListener('click', function() {
        if (Alloy.Globals.FACEBOOKOBJECT) {
            Alloy.Globals.showToast(Alloy.Globals.PHRASES.fbImageChangeError);
            return;
        }

        Ti.Media.openPhotoGallery({
            success : function(event) {
                // check connection
                if (Alloy.Globals.checkConnection()) {
                    var image = event.media;
                    $.upload_indicator.show();

                    var xhr = Titanium.Network.createHTTPClient();
                    xhr.onerror = function(e) {
                        Ti.API.error('Bad Sever =>' + JSON.stringify(e));
                        $.upload_indicator.hide();
                        Alloy.Globals.showFeedbackDialog(Alloy.Globals.PHRASES.commonErrorTxt);
                    };

                    xhr.onsendstream = function(e) {
                        // upload progress
                        $.upload_indicator.value = e.progress;
                    };

                    try {
                        xhr.open('POST', Alloy.Globals.BETKAMPENIMAGEUPLOADURL + '?lang=' + Alloy.Globals.LOCALE);
                        xhr.setRequestHeader("Authorization", Alloy.Globals.BETKAMPEN.token);
                        xhr.setTimeout(Alloy.Globals.TIMEOUT);

                        xhr.send({
                            media : image
                        });
                    } catch(e) {
                        $.upload_indicator.hide();
                        Alloy.Globals.showFeedbackDialog(Alloy.Globals.PHRASES.commonErrorTxt);
                    }

                    xhr.onload = function() {
                        if (this.status == '200') {
                            var response = JSON.parse(this.responseText);
                            Alloy.Globals.showToast(response);
                            $.upload_indicator.hide();

                            if(profileView) {
                                profileView.image = Alloy.Globals.BETKAMPENURL + '/profile_images/' + Alloy.Globals.BETKAMPENUID + '.png' + "?t=" + new Date().getTime();
                            }

                            // update event
                            Ti.App.fireEvent('app:updateMenu');
                            Ti.App.fireEvent('userInfoUpdate');
                        } else {
                            $.upload_indicator.hide();
                            Ti.API.error("Error =>" + this.response);
                            Alloy.Globals.showFeedbackDialog(JSON.parse(this.responseText));
                        }
                    };
                } else {
                    Alloy.Globals.showFeedbackDialog(Alloy.Globals.PHRASES.noConnectionErrorTxt);
                }
            },
            cancel : function() {
                // Do nothing
                // TODO
            },
            error : function() {
                // some error trying to access photos
                Alloy.Globals.showFeedbackDialog(Alloy.Globals.PHRASES.commonErrorTxt);
            },
            allowEditing : true,
            mediaTypes : [Ti.Media.MEDIA_TYPE_PHOTO]
        });

    });

    /* Fourth row */
    if (Alloy.Globals.PROFILENAME.length > 12) {
        $.profile_name_value_label.text = Alloy.Globals.PROFILENAME.substring(0, 9) + '...';
    }

    $.profile_name_row.addEventListener('click', function() {
        var dialog;
        var profileName = Alloy.Globals.PROFILENAME;
        var confirm = Alloy.Globals.PHRASES.okConfirmTxt;
        var cancel = Alloy.Globals.PHRASES.abortBtnTxt;
        var titleTxt = Alloy.Globals.PHRASES.profileNameTitleTxt;
        var messageTxt = Alloy.Globals.PHRASES.profileNameMessageTxt + ": " + profileName;

        if (!isAndroid) {
            dialog = Ti.UI.createAlertDialog({
                title : titleTxt,
                message : messageTxt,
                style : Ti.UI.iPhone.AlertDialogStyle.PLAIN_TEXT_INPUT,
                buttonNames : [confirm, cancel]
            });

        } else {
            var textfield = Ti.UI.createTextField();
            textfield.value = profileName;

            dialog = Ti.UI.createAlertDialog({
                title : titleTxt,
                message : messageTxt,
                androidView : textfield,
                buttonNames : [confirm, cancel]
            });
        }

        dialog.addEventListener('click', function(e) {
            if (e.index == 0) {
                var text;

                if (OS_IOS) {
                    text = e.text;
                } else if (OS_ANDROID) {
                    text = textfield.value;
                }

                if (text.length > 2 && text.length < 16) {
                    // set new profileName
                    profileName = text;
                    // build the json string
                    var param = '{"profile_name":"' + profileName + '", "app_identifier":"' + Alloy.Globals.APPID + '", "lang":"' + Alloy.Globals.LOCALE + '"}';
                    // send to backend
                    sendSettingsServer(param, 1, profileName);

                } else {
                    Alloy.Globals.showToast(Alloy.Globals.PHRASES.groupNameErrorTxt);
                }
            } else {
                dialog.hide();
            }
        });
        dialog.show();
    });

   	/* Fifth Row */
    $.favorite_team_settings_row.addEventListener('click', function() {
        var args = {navOpen : true, label : favoriteTeamLabel};
        var loginSuccessWindow = Alloy.createController('pickTeam', args).getView();

        if (!isAndroid) {
            Alloy.Globals.NAV.openWindow(loginSuccessWindow);
            loginSuccessWindow = null;
        } else {
            loginSuccessWindow.open();
            loginSuccessWindow = null;
        }
    });

    var favoriteTeam = "";

    if(Ti.App.Properties.hasProperty("favorite_team")) {
         favoriteTeam = Ti.App.Properties.getString("favorite_team");
    }

    if(favoriteTeam.length > 12) {
        favoriteTeam = favoriteTeam.substring(0, 9);
        favoriteTeam = favoriteTeam + "...";
    }

    var favoriteTeamLabel = Ti.UI.createLabel({
        textAlign : "left",
        text : favoriteTeam,
        right : 20,
        height : Ti.UI.SIZE,
        font : Alloy.Globals.FONT,
        color : "#FFF",
        width : Ti.UI.SIZE
    });

    $.favorite_team_settings_row.add(favoriteTeamLabel);

  	/* Sixth row */
    var showVersionEnabled;

    // true will be set if no stored value is found
    if (!Ti.App.Properties.hasProperty("showVersionSetting")) {
        Ti.App.Properties.setBool("showVersionSetting", true);
    }

    showVersionEnabled = Ti.App.Properties.getBool('showVersionSetting');
    var basicInviteSwitch;

    if (!isAndroid) {
        basicInviteSwitch = Ti.UI.createSwitch({
            right : 10,
            width : 40,
            titleOn : Alloy.Globals.PHRASES.onTxt,
            titleOff : Alloy.Globals.PHRASES.offTxt,
            value : showVersionEnabled
        });
    } else {
        basicInviteSwitch = Ti.UI.createSwitch({
  			style: Titanium.UI.Android.SWITCH_STYLE_SWITCH,
            titleOn : Alloy.Globals.PHRASES.onTxt,
            titleOff : Alloy.Globals.PHRASES.offTxt,
  			value: showVersionEnabled,
            right : 10,
            width : 80,
		});
    }

    basicInviteSwitch.addEventListener('change', function(e) {
       	if (isAndroid) {
        	$.table.setData($.table.data);
        }

        var value = false;
        if (basicInviteSwitch.value) {
            value = true;
        }

        Ti.App.Properties.setBool("showVersionSetting", value);
    });
    $.show_version_settings_row.selectionStyle = 'none';
    $.show_version_settings_row.add(basicInviteSwitch);
}

function createPickers() {
    var data = [];
    var dataAndroid = {};
    var currentLocale = JSON.parse(Ti.App.Properties.getString('language'));
    var currentLanguage;
    var currentLangPosAndroid;
    var pos = 0;

    for (var lang in Alloy.Globals.AVAILABLELANGUAGES) {
        if (currentLocale.language == Alloy.Globals.AVAILABLELANGUAGES[lang].name) {
            currentLanguage = Alloy.Globals.AVAILABLELANGUAGES[lang].description;

            // can't keep 0 index on android picker widget
            currentLangPosAndroid = (lang - 0) + 1;
        }

        data.push(Titanium.UI.createPickerRow({
            title : Alloy.Globals.AVAILABLELANGUAGES[lang].description,
            value : lang
        }));

        // for android picker widget
        pos = (lang - 0) + 1;
        dataAndroid[pos] = Alloy.Globals.AVAILABLELANGUAGES[lang].description;
    }

    if (isAndroid) {
        picker = Ti.UI.createLabel({
            right : 20,
            backgroundColor : 'transparent',
            width : Ti.UI.SIZE,
            height : Ti.UI.SIZE,
            textAlign : 'left',
            color : '#FFF',
            text : currentLanguage,
            font : Alloy.Globals.FONT
        });

        picker.addEventListener('click', function() {
            picker.open = true;
            Alloy.createWidget('danielhanold.pickerWidget', {
                id : 'sColumnLanguage',
                outerView : $.settingsWindow,
                hideNavBar : false,
                type : 'single-column',
                selectedValues : [currentLangPosAndroid],
                pickerValues : [dataAndroid],
                onDone : function(e) {
                    if (e.data) {
                        // change language
                        // key can't be 0, that's why we need to "-1"
                        changeLanguageConfirm(e.data[0].key - 1);
                    }
                    picker.open = false;
                },
            });
        });
    } else {
        var ModalPicker = require("lib/ModalPicker");
        var visualPrefs = {
            right : 20,
            backgroundColor : '#000',
            width : Ti.UI.SIZE,
            height : Ti.UI.SIZE,
            textAlign : 'left',
            color : '#FFF',
            font : Alloy.Globals.FONT
        };

        picker = new ModalPicker(visualPrefs, data, Alloy.Globals.PHRASES.chooseConfirmBtnTxt, Alloy.Globals.PHRASES.closeBtnTxt);

        picker.text = currentLanguage;

        picker.self.addEventListener('change', function(e) {
            changeLanguageConfirm(picker.value);
            Alloy.Globals.CURRENTVIEW = $.settingsWindow;
        });

    }
    return picker;
}

// get correct language file for this device
function getLanguage() {
    Alloy.Globals.getLanguage(indicator);
}

// run it
createGUI();


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

#include "media/capture/video/linux/video_capture_device_chromeos.h"

#include "base/bind.h"
#include "base/memory/ref_counted.h"
#include "base/single_thread_task_runner.h"
#include "base/thread_task_runner_handle.h"
#include "ui/gfx/display.h"
#include "ui/gfx/display_observer.h"
#include "ui/gfx/screen.h"

namespace media {

// This is a delegate class used to transfer Display change events from the UI
// thread to the media thread.
class VideoCaptureDeviceChromeOS::ScreenObserverDelegate
    : public gfx::DisplayObserver,
      public base::RefCountedThreadSafe<ScreenObserverDelegate> {
 public:
  ScreenObserverDelegate(
      VideoCaptureDeviceChromeOS* capture_device,
      scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner)
      : capture_device_(capture_device),
        ui_task_runner_(ui_task_runner),
        capture_task_runner_(base::ThreadTaskRunnerHandle::Get()) {
    ui_task_runner_->PostTask(
        FROM_HERE,
        base::Bind(&ScreenObserverDelegate::AddObserverOnUIThread, this));
  }

  void RemoveObserver() {
    DCHECK(capture_task_runner_->BelongsToCurrentThread());
    capture_device_ = NULL;
    ui_task_runner_->PostTask(
        FROM_HERE,
        base::Bind(&ScreenObserverDelegate::RemoveObserverOnUIThread, this));
  }

 private:
  friend class base::RefCountedThreadSafe<ScreenObserverDelegate>;

  ~ScreenObserverDelegate() override { DCHECK(!capture_device_); }

  void OnDisplayAdded(const gfx::Display& /*new_display*/) override {}
  void OnDisplayRemoved(const gfx::Display& /*old_display*/) override {}
  void OnDisplayMetricsChanged(const gfx::Display& display,
                               uint32_t metrics) override {
    DCHECK(ui_task_runner_->BelongsToCurrentThread());
    if (!(metrics & DISPLAY_METRIC_ROTATION))
      return;
    SendDisplayRotation(display);
  }

  void AddObserverOnUIThread() {
    DCHECK(ui_task_runner_->BelongsToCurrentThread());
    gfx::Screen* screen =
        gfx::Screen::GetScreenByType(gfx::SCREEN_TYPE_ALTERNATE);
    if (screen) {
      screen->AddObserver(this);
      SendDisplayRotation(screen->GetPrimaryDisplay());
    }
  }

  void RemoveObserverOnUIThread() {
    DCHECK(ui_task_runner_->BelongsToCurrentThread());
    gfx::Screen* screen =
        gfx::Screen::GetScreenByType(gfx::SCREEN_TYPE_ALTERNATE);
    if (screen)
      screen->RemoveObserver(this);
  }

  // Post the screen rotation change from the UI thread to capture thread
  void SendDisplayRotation(const gfx::Display& display) {
    DCHECK(ui_task_runner_->BelongsToCurrentThread());
    capture_task_runner_->PostTask(
        FROM_HERE,
        base::Bind(&ScreenObserverDelegate::SendDisplayRotationOnCaptureThread,
                   this, display));
  }

  void SendDisplayRotationOnCaptureThread(const gfx::Display& display) {
    DCHECK(capture_task_runner_->BelongsToCurrentThread());
    if (capture_device_)
      capture_device_->SetDisplayRotation(display);
  }

  VideoCaptureDeviceChromeOS* capture_device_;
  scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_;
  scoped_refptr<base::SingleThreadTaskRunner> capture_task_runner_;
  DISALLOW_IMPLICIT_CONSTRUCTORS(ScreenObserverDelegate);
};

VideoCaptureDeviceChromeOS::VideoCaptureDeviceChromeOS(
    scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
    const Name& device_name)
    : VideoCaptureDeviceLinux(device_name),
      screen_observer_delegate_(
          new ScreenObserverDelegate(this, ui_task_runner)) {
}

VideoCaptureDeviceChromeOS::~VideoCaptureDeviceChromeOS() {
  screen_observer_delegate_->RemoveObserver();
}

void VideoCaptureDeviceChromeOS::SetDisplayRotation(
    const gfx::Display& display) {
  if (display.IsInternal())
    SetRotation(display.rotation() * 90);
}

}  // namespace media