text:
package org.aja.tej.examples.streaming.twitter

import com.google.gson.Gson
import org.aja.tej.utils.{TejUtils, TejTwitterUtils}
import org.anormcypher.{Cypher, Neo4jREST}
import org.apache.spark.sql.{AnalysisException, Row, SQLContext}
import org.apache.spark.streaming.twitter.TwitterUtils
import org.apache.spark.streaming.{Seconds, StreamingContext}
import play.api.libs.ws.ning

import scala.collection.mutable

/**
 * Created by mageswaran on 24/4/16.
 */

//TODO: should check for any issues in sharing below details
/*
20
--consumerKey yM4CdwtCfDcs6OtEfrPUFLnPw
--consumerSecret k1QEczYNMKXZYFOhPB18Jtyde6uK9dKrB7PAOmM3oouhWlmRZ3
--accessToken 68559516-eoQTbOt4sOpJCHiGnKll8DGW4ihXpmPf0u2xwXLwE
--accessTokenSecret GOWRqKf1EDjxjPSoOAuazefweKdJgidvNQBvTpri7TEd5
*/

//For each tweet we are creating a REST connection. Very bad indeed!
case class Tweets(name: String, tag: String, location: String, inReplyToScreenName: String) {

  def executeCQL = {
    println("executing CQL : " )
    //Not an efficient way of creating nodes and relationship, however this
    //gives us a head start for learning CQL in the browser
    val cql =
      s"""MERGE (u:User {name:'${name}'})
         |MERGE (l:Location {name: '${location}'})
         |MERGE (t:Tag {name: '${tag}'})
         |MERGE (u) -[:LIVES_IN]-> (l)
         |MERGE (u) -[:TWEETS]-> (t)
       """.stripMargin

    println(cql)
    implicit val wsclient = ning.NingWSClient()

    // Setup the Rest Client
    implicit val connection = Neo4jREST("localhost", 7474, "/db/data/", "neo4j", "aja")

    // Provide an ExecutionContext
    implicit val ec = scala.concurrent.ExecutionContext.global

    Cypher(cql).execute()
  }
}

object TwitterWithNeo4j {

  var count = 0L
  private var gson = new Gson()

  def main(args: Array[String]) {

    var printSchema = true
    if (args.length < 3) {
      println("Usage : " + this.getClass.getSimpleName + " <numbeOfRuns> --consumerKey <key> --consumerSecret <key> " +
        "--accessToken <key> --accessTokenSecret <key>")
      System.exit(1)
    }

    val Array(numbeOfRuns) = TejTwitterUtils.parseCommandLineWithTwitterCredentials(args)
    println(numbeOfRuns)

    val sc = TejUtils.getSparkContext(this.getClass.getSimpleName)
    sc.setLogLevel("OFF")

    val ssc = new StreamingContext(sc, Seconds(1))

    val twitterStream = TwitterUtils.createStream(ssc, TejTwitterUtils.getAuth)
      .map(gson.toJson(_))

    //**************Streaming Processing********************//
    //Each RDD can have either 0 or N tweets, since each stream is an continuous sequence of RDD
    twitterStream.foreachRDD(rdd => {

      count += 1

      // Get the singleton instance of SQLContext
      val sqlContext = SQLContext.getOrCreate(rdd.sparkContext)
      import sqlContext.implicits._

      //val jsonRDD = gson.toJson(rdd)
      val df = sqlContext.read.json(rdd)
      df.registerTempTable("tweets")

      if (count > numbeOfRuns.toString.toLong)
        System.exit(0)

      println("1.>>>>>>>>>>>" + " Run: " + count + " Size: " + rdd.count() )

      try {

        val tweetDF = df.select("user.name", "user.friendsCount", "user.lang", "user.screenName",
          "hashtagEntities", "user.location", "inReplyToScreenName").explode($"hashtagEntities"){
          //
          case Row(content: Seq[Row]) => content.map(tags => HashTag(tags(2).asInstanceOf[String]))
        }.select("name", "friendsCount", "tag", "lang", "screenName", "location","inReplyToScreenName")

        println("1.>>>>>>>>>>>" + tweetDF.show())
        tweetDF.rdd.map(r =>
          //(name: String, tag: String, location: String, inReplyToScreenName: String)
        Tweets(r(0).asInstanceOf[String],r(2).asInstanceOf[String],r(5).asInstanceOf[String], r(6).asInstanceOf[String])).foreach(_.executeCQL)

      } catch {
        case e: AnalysisException =>
          println("!!!!!!!!!!!!!!!!!!!!!!!!!!!! Something wrong with incoming tweet !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" + e.toString)
      }
    })

    ssc.start()
    ssc.awaitTermination()

  }
}

/*
Tweet Schema: That's a big list indeed!

root
 |-- contributorsIDs: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- createdAt: string (nullable = true)
 |-- currentUserRetweetId: long (nullable = true)
 |-- geoLocation: struct (nullable = true)
 |    |-- latitude: double (nullable = true)
 |    |-- longitude: double (nullable = true)
 |-- hashtagEntities: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- end: long (nullable = true)
 |    |    |-- start: long (nullable = true)
 |    |    |-- text: string (nullable = true)
 |-- id: long (nullable = true)
 |-- inReplyToScreenName: string (nullable = true)
 |-- inReplyToStatusId: long (nullable = true)
 |-- inReplyToUserId: long (nullable = true)
 |-- isFavorited: boolean (nullable = true)
 |-- isPossiblySensitive: boolean (nullable = true)
 |-- isTruncated: boolean (nullable = true)
 |-- mediaEntities: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- displayURL: string (nullable = true)
 |    |    |-- end: long (nullable = true)
 |    |    |-- expandedURL: string (nullable = true)
 |    |    |-- id: long (nullable = true)
 |    |    |-- mediaURL: string (nullable = true)
 |    |    |-- mediaURLHttps: string (nullable = true)
 |    |    |-- sizes: struct (nullable = true)
 |    |    |    |-- 0: struct (nullable = true)
 |    |    |    |    |-- height: long (nullable = true)
 |    |    |    |    |-- resize: long (nullable = true)
 |    |    |    |    |-- width: long (nullable = true)
 |    |    |    |-- 1: struct (nullable = true)
 |    |    |    |    |-- height: long (nullable = true)
 |    |    |    |    |-- resize: long (nullable = true)
 |    |    |    |    |-- width: long (nullable = true)
 |    |    |    |-- 2: struct (nullable = true)
 |    |    |    |    |-- height: long (nullable = true)
 |    |    |    |    |-- resize: long (nullable = true)
 |    |    |    |    |-- width: long (nullable = true)
 |    |    |    |-- 3: struct (nullable = true)
 |    |    |    |    |-- height: long (nullable = true)
 |    |    |    |    |-- resize: long (nullable = true)
 |    |    |    |    |-- width: long (nullable = true)
 |    |    |-- start: long (nullable = true)
 |    |    |-- type: string (nullable = true)
 |    |    |-- url: string (nullable = true)
 |-- place: struct (nullable = true)
 |    |-- boundingBoxCoordinates: array (nullable = true)
 |    |    |-- element: array (containsNull = true)
 |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |-- latitude: double (nullable = true)
 |    |    |    |    |-- longitude: double (nullable = true)
 |    |-- boundingBoxType: string (nullable = true)
 |    |-- country: string (nullable = true)
 |    |-- countryCode: string (nullable = true)
 |    |-- fullName: string (nullable = true)
 |    |-- id: string (nullable = true)
 |    |-- name: string (nullable = true)
 |    |-- placeType: string (nullable = true)
 |    |-- url: string (nullable = true)
 |-- retweetCount: long (nullable = true)
 |-- retweetedStatus: struct (nullable = true)
 |    |-- contributorsIDs: array (nullable = true)
 |    |    |-- element: string (containsNull = true)
 |    |-- createdAt: string (nullable = true)
 |    |-- currentUserRetweetId: long (nullable = true)
 |    |-- hashtagEntities: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- end: long (nullable = true)
 |    |    |    |-- start: long (nullable = true)
 |    |    |    |-- text: string (nullable = true)
 |    |-- id: long (nullable = true)
 |    |-- inReplyToScreenName: string (nullable = true)
 |    |-- inReplyToStatusId: long (nullable = true)
 |    |-- inReplyToUserId: long (nullable = true)
 |    |-- isFavorited: boolean (nullable = true)
 |    |-- isPossiblySensitive: boolean (nullable = true)
 |    |-- isTruncated: boolean (nullable = true)
 |    |-- mediaEntities: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- displayURL: string (nullable = true)
 |    |    |    |-- end: long (nullable = true)
 |    |    |    |-- expandedURL: string (nullable = true)
 |    |    |    |-- id: long (nullable = true)
 |    |    |    |-- mediaURL: string (nullable = true)
 |    |    |    |-- mediaURLHttps: string (nullable = true)
 |    |    |    |-- sizes: struct (nullable = true)
 |    |    |    |    |-- 0: struct (nullable = true)
 |    |    |    |    |    |-- height: long (nullable = true)
 |    |    |    |    |    |-- resize: long (nullable = true)
 |    |    |    |    |    |-- width: long (nullable = true)
 |    |    |    |    |-- 1: struct (nullable = true)
 |    |    |    |    |    |-- height: long (nullable = true)
 |    |    |    |    |    |-- resize: long (nullable = true)
 |    |    |    |    |    |-- width: long (nullable = true)
 |    |    |    |    |-- 2: struct (nullable = true)
 |    |    |    |    |    |-- height: long (nullable = true)
 |    |    |    |    |    |-- resize: long (nullable = true)
 |    |    |    |    |    |-- width: long (nullable = true)
 |    |    |    |    |-- 3: struct (nullable = true)
 |    |    |    |    |    |-- height: long (nullable = true)
 |    |    |    |    |    |-- resize: long (nullable = true)
 |    |    |    |    |    |-- width: long (nullable = true)
 |    |    |    |-- start: long (nullable = true)
 |    |    |    |-- type: string (nullable = true)
 |    |    |    |-- url: string (nullable = true)
 |    |-- place: struct (nullable = true)
 |    |    |-- boundingBoxCoordinates: array (nullable = true)
 |    |    |    |-- element: array (containsNull = true)
 |    |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |    |-- latitude: double (nullable = true)
 |    |    |    |    |    |-- longitude: double (nullable = true)
 |    |    |-- boundingBoxType: string (nullable = true)
 |    |    |-- country: string (nullable = true)
 |    |    |-- countryCode: string (nullable = true)
 |    |    |-- fullName: string (nullable = true)
 |    |    |-- id: string (nullable = true)
 |    |    |-- name: string (nullable = true)
 |    |    |-- placeType: string (nullable = true)
 |    |    |-- url: string (nullable = true)
 |    |-- retweetCount: long (nullable = true)
 |    |-- source: string (nullable = true)
 |    |-- text: string (nullable = true)
 |    |-- urlEntities: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- displayURL: string (nullable = true)
 |    |    |    |-- end: long (nullable = true)
 |    |    |    |-- expandedURL: string (nullable = true)
 |    |    |    |-- start: long (nullable = true)
 |    |    |    |-- url: string (nullable = true)
 |    |-- user: struct (nullable = true)
 |    |    |-- createdAt: string (nullable = true)
 |    |    |-- description: string (nullable = true)
 |    |    |-- descriptionURLEntities: array (nullable = true)
 |    |    |    |-- element: string (containsNull = true)
 |    |    |-- favouritesCount: long (nullable = true)
 |    |    |-- followersCount: long (nullable = true)
 |    |    |-- friendsCount: long (nullable = true)
 |    |    |-- id: long (nullable = true)
 |    |    |-- isContributorsEnabled: boolean (nullable = true)
 |    |    |-- isFollowRequestSent: boolean (nullable = true)
 |    |    |-- isGeoEnabled: boolean (nullable = true)
 |    |    |-- isProtected: boolean (nullable = true)
 |    |    |-- isVerified: boolean (nullable = true)
 |    |    |-- lang: string (nullable = true)
 |    |    |-- listedCount: long (nullable = true)
 |    |    |-- location: string (nullable = true)
 |    |    |-- name: string (nullable = true)
 |    |    |-- profileBackgroundColor: string (nullable = true)
 |    |    |-- profileBackgroundImageUrl: string (nullable = true)
 |    |    |-- profileBackgroundImageUrlHttps: string (nullable = true)
 |    |    |-- profileBackgroundTiled: boolean (nullable = true)
 |    |    |-- profileBannerImageUrl: string (nullable = true)
 |    |    |-- profileImageUrl: string (nullable = true)
 |    |    |-- profileImageUrlHttps: string (nullable = true)
 |    |    |-- profileLinkColor: string (nullable = true)
 |    |    |-- profileSidebarBorderColor: string (nullable = true)
 |    |    |-- profileSidebarFillColor: string (nullable = true)
 |    |    |-- profileTextColor: string (nullable = true)
 |    |    |-- profileUseBackgroundImage: boolean (nullable = true)
 |    |    |-- screenName: string (nullable = true)
 |    |    |-- showAllInlineMedia: boolean (nullable = true)
 |    |    |-- statusesCount: long (nullable = true)
 |    |    |-- timeZone: string (nullable = true)
 |    |    |-- translator: boolean (nullable = true)
 |    |    |-- url: string (nullable = true)
 |    |    |-- utcOffset: long (nullable = true)
 |    |-- userMentionEntities: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- end: long (nullable = true)
 |    |    |    |-- id: long (nullable = true)
 |    |    |    |-- name: string (nullable = true)
 |    |    |    |-- screenName: string (nullable = true)
 |    |    |    |-- start: long (nullable = true)
 |-- source: string (nullable = true)
 |-- text: string (nullable = true)
 |-- urlEntities: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- displayURL: string (nullable = true)
 |    |    |-- end: long (nullable = true)
 |    |    |-- expandedURL: string (nullable = true)
 |    |    |-- start: long (nullable = true)
 |    |    |-- url: string (nullable = true)
 |-- user: struct (nullable = true)
 |    |-- createdAt: string (nullable = true)
 |    |-- description: string (nullable = true)
 |    |-- descriptionURLEntities: array (nullable = true)
 |    |    |-- element: string (containsNull = true)
 |    |-- favouritesCount: long (nullable = true)
 |    |-- followersCount: long (nullable = true)
 |    |-- friendsCount: long (nullable = true)
 |    |-- id: long (nullable = true)
 |    |-- isContributorsEnabled: boolean (nullable = true)
 |    |-- isFollowRequestSent: boolean (nullable = true)
 |    |-- isGeoEnabled: boolean (nullable = true)
 |    |-- isProtected: boolean (nullable = true)
 |    |-- isVerified: boolean (nullable = true)
 |    |-- lang: string (nullable = true)
 |    |-- listedCount: long (nullable = true)
 |    |-- location: string (nullable = true)
 |    |-- name: string (nullable = true)
 |    |-- profileBackgroundColor: string (nullable = true)
 |    |-- profileBackgroundImageUrl: string (nullable = true)
 |    |-- profileBackgroundImageUrlHttps: string (nullable = true)
 |    |-- profileBackgroundTiled: boolean (nullable = true)
 |    |-- profileBannerImageUrl: string (nullable = true)
 |    |-- profileImageUrl: string (nullable = true)
 |    |-- profileImageUrlHttps: string (nullable = true)
 |    |-- profileLinkColor: string (nullable = true)
 |    |-- profileSidebarBorderColor: string (nullable = true)
 |    |-- profileSidebarFillColor: string (nullable = true)
 |    |-- profileTextColor: string (nullable = true)
 |    |-- profileUseBackgroundImage: boolean (nullable = true)
 |    |-- screenName: string (nullable = true)
 |    |-- showAllInlineMedia: boolean (nullable = true)
 |    |-- statusesCount: long (nullable = true)
 |    |-- timeZone: string (nullable = true)
 |    |-- translator: boolean (nullable = true)
 |    |-- url: string (nullable = true)
 |    |-- utcOffset: long (nullable = true)
 |-- userMentionEntities: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- end: long (nullable = true)
 |    |    |-- id: long (nullable = true)
 |    |    |-- name: string (nullable = true)
 |    |    |-- screenName: string (nullable = true)
 |    |    |-- start: long (nullable = true)

 */

/*
Sample Data
===========

{
  "createdAt": "Oct 18, 2015 1:01:47 PM",
  "id": 655647448245866500,
  "text": "RT @Thabo_Shingange: Asina mali asisebenzi #UPrising @TuksUPrising #TuksFeesMustFall",
  "source": "Twitter Web Client",
  "isTruncated": false,
  "inReplyToStatusId": -1,
  "inReplyToUserId": -1,
  "isFavorited": false,
  "retweetCount": 0,
  "isPossiblySensitive": false,
  "contributorsIDs": [],
  "retweetedStatus": {
    "createdAt": "Oct 18, 2015 12:57:42 PM",
    "id": 655646420905644000,
    "text": "Asina mali asisebenzi #UPrising @TuksUPrising #TuksFeesMustFall",
    "source": "Twitter for Android",
    "isTruncated": false,
    "inReplyToStatusId": -1,
    "inReplyToUserId": -1,
    "isFavorited": false,
    "place": {
      "name": "Pretoria",
      "countryCode": "ZA",
      "id": "0e587c59401d0a27",
      "country": "South Africa",
      "placeType": "city",
      "url": "https://api.twitter.com/1.1/geo/id/0e587c59401d0a27.json",
      "fullName": "Pretoria, South Africa",
      "boundingBoxType": "Polygon",
      "boundingBoxCoordinates": [
        [
          {
            "latitude": -25.915773,
            "longitude": 27.948304
          },
          {
            "latitude": -25.589432,
            "longitude": 27.948304
          },
          {
            "latitude": -25.589432,
            "longitude": 28.419829
          },
          {
            "latitude": -25.915773,
            "longitude": 28.419829
          }
        ]
      ]
    },
    "retweetCount": 1,
    "isPossiblySensitive": false,
    "contributorsIDs": [],
    "userMentionEntities": [
      {
        "name": "#UPrising",
        "screenName": "TuksUPrising",
        "id": 3973033815,
        "start": 32,
        "end": 45
      }
    ],
    "urlEntities": [],
    "hashtagEntities": [
      {
        "text": "UPrising",
        "start": 22,
        "end": 31
      },
      {
        "text": "TuksFeesMustFall",
        "start": 46,
        "end": 63
      }
    ],
    "mediaEntities": [],
    "currentUserRetweetId": -1,
    "user": {
      "id": 57374087,
      "name": "#TuksFeesMustFall",
      "screenName": "Thabo_Shingange",
      "location": "South Africa",
      "description": "#IWriteWhatILike\nStudent Activist\nPan Africanist\nSecretary: SASCO Tukkies Branch",
      "descriptionURLEntities": [],
      "isContributorsEnabled": false,
      "profileImageUrl": "http://pbs.twimg.com/profile_images/652389061592764416/NWvjzj6A_normal.jpg",
      "profileImageUrlHttps": "https://pbs.twimg.com/profile_images/652389061592764416/NWvjzj6A_normal.jpg",
      "isProtected": false,
      "followersCount": 386,
      "profileBackgroundColor": "090A0A",
      "profileTextColor": "333333",
      "profileLinkColor": "94D487",
      "profileSidebarFillColor": "DDFFCC",
      "profileSidebarBorderColor": "000000",
      "profileUseBackgroundImage": true,
      "showAllInlineMedia": false,
      "friendsCount": 56,
      "createdAt": "Jul 16, 2009 9:55:54 PM",
      "favouritesCount": 220,
      "utcOffset": 7200,
      "timeZone": "Pretoria",
      "profileBackgroundImageUrl": "http://pbs.twimg.com/profile_background_images/378800000162805661/OEdMK8VQ.jpeg",
      "profileBackgroundImageUrlHttps": "https://pbs.twimg.com/profile_background_images/378800000162805661/OEdMK8VQ.jpeg",
      "profileBannerImageUrl": "https://pbs.twimg.com/profile_banners/57374087/1444376646",
      "profileBackgroundTiled": true,
      "lang": "en",
      "statusesCount": 9343,
      "isGeoEnabled": true,
      "isVerified": false,
      "translator": false,
      "listedCount": 3,
      "isFollowRequestSent": false
    }
  },
  "userMentionEntities": [
    {
      "name": "#TuksFeesMustFall",
      "screenName": "Thabo_Shingange",
      "id": 57374087,
      "start": 3,
      "end": 19
    },
    {
      "name": "#UPrising",
      "screenName": "TuksUPrising",
      "id": 3973033815,
      "start": 53,
      "end": 66
    }
  ],
  "urlEntities": [],
  "hashtagEntities": [
    {
      "text": "UPrising",
      "start": 43,
      "end": 52
    },
    {
      "text": "TuksFeesMustFall",
      "start": 67,
      "end": 84
    }
  ],
  "mediaEntities": [],
  "currentUserRetweetId": -1,
  "user": {
    "id": 989746208,
    "name": "#TuksFeesMustFall",
    "screenName": "Amogelangkk",
    "location": "Ninapark",
    "description": "Better to die for an idea that shall live, than to live for an idea that shall die! #EFF #Orlando_
    Pirates BSc(Hons) Actuarial Science #AspiringActuary @EFFSCUP",
    "descriptionURLEntities": [],
    "isContributorsEnabled": false,
    "profileImageUrl": "http://pbs.twimg.com/profile_images/655364161283624960/fkpKRfyo_normal.jpg",
    "profileImageUrlHttps": "https://pbs.twimg.com/profile_images/655364161283624960/fkpKRfyo_normal.jpg",
    "url": "http://effighters.org.za",
    "isProtected": false,
    "followersCount": 236,
    "profileBackgroundColor": "7D237D",
    "profileTextColor": "333333",
    "profileLinkColor": "11E80E",
    "profileSidebarFillColor": "DDEEF6",
    "profileSidebarBorderColor": "FFFFFF",
    "profileUseBackgroundImage": true,
    "showAllInlineMedia": false,
    "friendsCount": 289,
    "createdAt": "Dec 5, 2012 4:24:27 AM",
    "favouritesCount": 451,
    "utcOffset": -1,
    "profileBackgroundImageUrl": "http://pbs.twimg.com/profile_background_images/378800000161345839/9VmfmCVm.jpeg",
    "profileBackgroundImageUrlHttps": "https://pbs.twimg.com/profile_background_images/378800000161345839/9VmfmCVm.jpeg",
    "profileBannerImageUrl": "https://pbs.twimg.com/profile_banners/989746208/1388690204",
    "profileBackgroundTiled": false,
    "lang": "en",
    "statusesCount": 3622,
    "isGeoEnabled": false,
    "isVerified": false,
    "translator": false,
    "listedCount": 1,
    "isFollowRequestSent": false
  }
}

 */


text:
struct buf;
struct context;
struct file;
struct inode;
struct pipe;
struct proc;
struct rtcdate;
struct spinlock;
struct stat;
struct superblock;
struct Window;
struct Node;

// bio.c
void            binit(void);
struct buf*     bread(uint, uint);
void            brelse(struct buf*);
void            bwrite(struct buf*);

// console.c
void            consoleinit(void);
void            cprintf(char*, ...);
void            consoleintr(int(*)(void));
void            panic(char*) __attribute__((noreturn));

// exec.c
int             exec(char*, char**);

// file.c
struct file*    filealloc(void);
void            fileclose(struct file*);
struct file*    filedup(struct file*);
void            fileinit(void);
int             fileread(struct file*, char*, int n);
int             filestat(struct file*, struct stat*);
int             filewrite(struct file*, char*, int n);

//folder.c
void 			InitFolder(struct Window*);
void 			Folder(struct Window*, int, int, int);

// fs.c
void            readsb(int dev, struct superblock *sb);
int             dirlink(struct inode*, char*, uint);
struct inode*   dirlookup(struct inode*, char*, uint*);
struct inode*   ialloc(uint, short);
struct inode*   idup(struct inode*);
void            iinit(void);
void            ilock(struct inode*);
void            iput(struct inode*);
void            iunlock(struct inode*);
void            iunlockput(struct inode*);
void            iupdate(struct inode*);
int             namecmp(const char*, const char*);
struct inode*   namei(char*);
struct inode*   nameiparent(char*, char*);
int             readi(struct inode*, char*, uint, uint);
void            stati(struct inode*, struct stat*);
int             writei(struct inode*, char*, uint, uint);

// ide.c
void            ideinit(void);
void            ideintr(void);
void            iderw(struct buf*);

// ioapic.c
void            ioapicenable(int irq, int cpu);
extern uchar    ioapicid;
void            ioapicinit(void);

// kalloc.c
char*           kalloc(void);
void            kfree(char*);
void            kinit1(void*, void*);
void            kinit2(void*, void*);

// kbd.c
void            kbdintr(void);

//mouse.c
void			mouseinit(void);
void			mouseintr(uint);

// lapic.c
void            cmostime(struct rtcdate *r);
int             cpunum(void);
extern volatile uint*    lapic;
void            lapiceoi(void);
void            lapicinit(void);
void            lapicstartap(uchar, uint);
void            microdelay(int);

// log.c
void            initlog(void);
void            log_write(struct buf*);
void            begin_op();
void            end_op();

// mp.c
extern int      ismp;
int             mpbcpu(void);
void            mpinit(void);
void            mpstartthem(void);

// picirq.c
void            picenable(int);
void            picinit(void);

// pipe.c
int             pipealloc(struct file**, struct file**);
void            pipeclose(struct pipe*, int);
int             piperead(struct pipe*, char*, int);
int             pipewrite(struct pipe*, char*, int);

//PAGEBREAK: 16
// proc.c
struct proc*    copyproc(struct proc*);
void            exit(void);
int             fork(void);
int             growproc(int);
int             kill(int);
void            pinit(void);
void            procdump(void);
void            scheduler(void) __attribute__((noreturn));
void            sched(void);
void            sleep(void*, struct spinlock*);
void            userinit(void);
int             wait(void);
void            wakeup(void*);
void            yield(void);

// swtch.S
void            swtch(struct context**, struct context*);

// spinlock.c
void            acquire(struct spinlock*);
void            getcallerpcs(void*, uint*);
int             holding(struct spinlock*);
void            initlock(struct spinlock*, char*);
void            release(struct spinlock*);
void            pushcli(void);
void            popcli(void);

// string.c
int             memcmp(const void*, const void*, uint);
void*           memmove(void*, const void*, uint);
void*           memset(void*, int, uint);
char*           safestrcpy(char*, const char*, int);
int             strlen(const char*);
int             strncmp(const char*, const char*, uint);
char*           strncpy(char*, const char*, int);

// syscall.c
int             argint(int, int*);
int             argptr(int, char**, int);
int             argstr(int, char**);
int             fetchint(uint, int*);
int             fetchstr(uint, char**);
void            syscall(void);

// timer.c
void            timerinit(void);

// trap.c
void            idtinit(void);
extern uint     ticks;
void            tvinit(void);
extern struct spinlock tickslock;

// gui.c
void			display_to_screen(unsigned int, unsigned int, unsigned int, unsigned int);
void 			draw_loading();
void			draw_point(unsigned int, unsigned int, unsigned short);
int				draw_character(unsigned int, unsigned int, char, unsigned short);
void			draw_icon(int, int, int);
void			draw_window(struct Window*);
void 			draw_mouse(int, int);
void			clean_mouse();
void			draw_string(unsigned int, unsigned int, char *, unsigned short);
void			draw_again(int);
void			draw_bottom(int);
void			draw_background_point(unsigned int, unsigned int, int);

//photo.c
void			init_photo(unsigned int, unsigned int);
void			photo(char, int);

//text.c
void			init_text(unsigned int, unsigned int);
void			kbd_text(char, int);

// draw.c
void			draw_brush(unsigned int, unsigned int);
void			init_draw(unsigned int, unsigned int);
void			draw(struct Window*, unsigned int, unsigned int, int);

// setting.c
void			init_setting(unsigned int, unsigned int);
int 			set_current_bg(int);
int 			get_current_bg();
void			setting(unsigned int, unsigned int, int);

//game.c
void			initGameWindow(unsigned int, unsigned int);
void			pointInGameWindow(unsigned int, unsigned int, int);

// uart.c
void            uartinit(void);
void            uartintr(void);
void            uartputc(int);

// vm.c
void            seginit(void);
void            kvmalloc(void);
void            vmenable(void);
pde_t*          setupkvm(void);
char*           uva2ka(pde_t*, char*);
int             allocuvm(pde_t*, uint, uint);
int             deallocuvm(pde_t*, uint, uint);
void            freevm(pde_t*);
void            inituvm(pde_t*, char*, uint);
int             loaduvm(pde_t*, char*, struct inode*, uint, uint);
pde_t*          copyuvm(pde_t*, uint);
void            switchuvm(struct proc*);
void            switchkvm(void);
int             copyout(pde_t*, uint, void*, uint);
void            clearpteu(pde_t *pgdir, char *uva);

// number of elements in fixed-size array
#define NELEM(x) (sizeof(x)/sizeof((x)[0]))

redpajama_set_name: RedPajamaGithub


text:
#include "bistro/bistro/config/Config.h"

#include <boost/algorithm/string/predicate.hpp>
#include <folly/Conv.h>
#include <folly/Memory.h>
#include <folly/json.h>
#include <folly/experimental/DynamicParser.h>
#include <limits>
#include <thread>

#include "bistro/bistro/utils/Exception.h"
#include "bistro/bistro/config/Job.h"
#include "bistro/bistro/config/parsing_common.h"
#include "bistro/bistro/scheduler/SchedulerPolicyRegistry.h"

// Future: remove this once there is nobody using this.
DEFINE_bool(
  kill_job_if_disabled, false,
  "Deprecated in favor of the runtime (JSON) Bistro setting of "
  "kill_orphan_tasks_after_sec. Setting this to 1 or true is "
  "equivalent to \"kill_orphan_tasks_after_sec\": 0, but the "
  "JSON setting takes precedence."
);

namespace facebook { namespace bistro {

namespace {
const ResourceVector& workerLevelResourcesRef(const Config& config) {
  const int worker_level_id = checkedLookup(config.levels, "worker");
  CHECK(worker_level_id != StringTable::NotFound);
  CHECK(worker_level_id > 0);
  CHECK(worker_level_id < config.resourcesByLevel.size());
  return config.resourcesByLevel[worker_level_id];
}

// You must also update RemoteWorkerRunner.cpp with the policy implementation.
const std::map<
  cpp2::PhysicalResource, std::set<cpp2::PhysicalResourceEnforcement>
> kResourceToSupportedEnforcements = {
  {cpp2::PhysicalResource::CPU_CORES, {
    cpp2::PhysicalResourceEnforcement::NONE,
    cpp2::PhysicalResourceEnforcement::SOFT,
  }},
  {cpp2::PhysicalResource::RAM_MBYTES, {
    cpp2::PhysicalResourceEnforcement::NONE,
    cpp2::PhysicalResourceEnforcement::HARD,
  }},
  {cpp2::PhysicalResource::GPU_CARDS, {
    cpp2::PhysicalResourceEnforcement::NONE,
  }},
};

cpp2::PhysicalResource physicalResourceFromString(const std::string& name) {
  if (name == kRamMB) {
    return cpp2::PhysicalResource::RAM_MBYTES;
  } else if (name == kCPUCore) {
    return cpp2::PhysicalResource::CPU_CORES;
  } else if (name == kGPUCard) {
    return cpp2::PhysicalResource::GPU_CARDS;
  } else {
    // NB: Not supporting GPU_MBYTES since we don't have a usable
    // story for it at the moment.
    throw std::invalid_argument("Unknown physical resource type");
  }
}

cpp2::PhysicalResourceEnforcement physicalResourceEnforcementFromString(
    const std::string& name) {
  if (name == kNone) {
    return cpp2::PhysicalResourceEnforcement::NONE;
  } else if (name == kSoft) {
    return cpp2::PhysicalResourceEnforcement::SOFT;
  } else if (name == kHard) {
    return cpp2::PhysicalResourceEnforcement::HARD;
  } else {
    throw std::invalid_argument("Unknown resource enforcement type");
  }
}

void parsePhysicalResourceConfigs(
    folly::DynamicParser* p,
    const Config& config,  // Resources must be parsed already.
    std::vector<cpp2::PhysicalResourceConfig>* rcfgs,
    std::unordered_map<std::string, size_t>* logical_to_physical) {

  const auto num_worker_resources = workerLevelResourcesRef(config).size();
  p->optional(kPhysicalResources, [&]() {
    p->objectItems([&](const std::string& name, const folly::dynamic&) {
      rcfgs->emplace_back();
      auto& rcfg = rcfgs->back();
      const auto idx_of_rcfg = rcfgs->size() - 1;

      *rcfg.physical() = physicalResourceFromString(name);
      p->required(kLogicalResource, [&](std::string&& logical) {
        *rcfg.logical() = std::move(logical);
        *rcfg.logicalResourceID() =
            config.resourceNames.lookup(*rcfg.logical());
        if (*rcfg.logicalResourceID() == StringTable::NotFound ||
            *rcfg.logicalResourceID() >= num_worker_resources) {
          throw BistroException(
              "Physical resource maps to unknown resource ",
              *rcfg.logical());
        }
        // Make an inverted index by the string name of the logical
        // resource, since that's what workers report.  Do this at parse
        // time, so that errors are attached to the appropriate entry.
        if (!logical_to_physical->emplace(*rcfg.logical(), idx_of_rcfg)
                 .second) {
          throw BistroException(
            "Logical resource used in multiple physical_resources entries"
          );
        }
      });
      p->optional(kMultiplyLogicalBy, [&](double mul) {
        if (std::abs(mul) < 1e-12) {
          throw BistroException("Too close to 0 machine precision");
        }
        *rcfg.multiplyLogicalBy() = mul;
      });
      p->optional(kEnforcement, [&](const std::string& enforcement) {
        *rcfg.enforcement() =
            physicalResourceEnforcementFromString(enforcement);
        auto it = kResourceToSupportedEnforcements.find(*rcfg.physical());
        if (it == kResourceToSupportedEnforcements.end() ||
            !it->second.count(*rcfg.enforcement())) {
          throw BistroException(
              "Resource ",
              *rcfg.physical(),
              " does not support enforcement type");
        }
      });
      p->optional(kPhysicalReserveAmount, [&](double reserve) {
        // Allow negative values for now... maybe there is some use?
        *rcfg.physicalReserveAmount() = reserve;
      });
    });
  });
}
}  // anonymous namespace

// IMPORTANT: You MUST set each field's default **unconditionally** and
// BEFORE attempting to parse the field.  See the "IMPORTANT" note in
// Config.h for an explanation of Bistro's policy on defaults in the
// presence of parse errors.
Config::Config(const folly::dynamic& d_config)
  : idleWait(std::chrono::milliseconds(5000)),
    workingWait(std::chrono::milliseconds(500)),
    levels({"instance"}),
    schedulerPolicyName(kSchedulePolicyRoundRobin.str()) {

  folly::DynamicParser p(folly::DynamicParser::OnError::RECORD, &d_config);

  p.optional(kEnabled, [&](bool b) { enabled = b; });
  p.optional("working_wait", [&](double n) {
    workingWait = std::chrono::milliseconds(static_cast<int>(1000 * n));
  });
  p.optional("idle_wait", [&](double n) {
    idleWait = std::chrono::milliseconds(static_cast<int>(1000 * n));
  });
  p.optional("scheduler", [&](const std::string& s) {
    schedulerPolicyName = s;
    // Invalid value? Throw at parse-time rather than at runtime.
    throwUnlessPolicyNameExists(schedulerPolicyName);
  });
  p.optional("remote_worker_selector", [&](const std::string& s) {
    remoteWorkerSelectorType = getRemoteWorkerSelectorType(s);
  });
  p.optional(kBackoff, [&](const folly::dynamic& value) {
    defaultBackoffSettings = JobBackoffSettings(value);
  });
  p.required(kNodes, [&]() {
    p.optional(kNodeOrder, [&](const std::string& s) {
      nodeOrderType = getNodeOrderType(s);
    });
    p.required("levels", [&]() {
      p.arrayItems([&](std::string&& s) { levels.insert(s); });
    });
    p.optional("node_sources", [&]() {
      p.arrayItems([&]() {
        folly::dynamic d_prefs = folly::dynamic::object();
        p.optional("prefs", [&]() { d_prefs = p.value(); });
        p.required("source", [&](std::string&& s) {
          nodeConfigs.emplace_back(std::move(s), std::move(d_prefs));
        });
      });
    });
  });
  // No matter what may be wrong with the config, add a 'worker' level as
  // the bottom level.
  levels.insert("worker");
  if (nodeConfigs.empty()) {
    LOG(WARNING) << "Empty 'node_sources', can only run on the instance node.";
  }

  if (FLAGS_kill_job_if_disabled) {  // A deprecated command-line default
    killOrphanTasksAfter = std::chrono::milliseconds(0);
  }
  parseKillOrphanTasksAfter(&p, &killOrphanTasksAfter);

  parseTaskSubprocessOptions(&p, &taskSubprocessOptions);

  // This is outside of TaskSubprocessOptions, so that it can be changed
  // even while the task is running.
  parseKillRequest(&p, &killRequest);

  // This is a DANGEROUS setting, see the doc at the declaration site.
  p.optional(kExitInitialWaitBeforeTimestamp, [&](int64_t n) {
    exitInitialWaitBeforeTimestamp = n;
  });

  // What is the node level that jobs will use to create tasks by default?
  // You probably don't want to specify "worker" because there are no nodes.
  // It's not forbidden in the spirit of laissez-faire.
  //
  // Default to the bottom level ("instance" is 0, "worker" is last).
  levelForTasks = getNumConfiguredLevels();
  p.optional(kLevelForTasks, [&](const std::string& s) {
    levelForTasks = checkedLookup(levels, s);
  });

  resourcesByLevel.resize(levels.size());
  levelIDToResourceID.resize(levels.size());
  p.required("resources", [&]() {
    p.objectItems([&](const std::string& level, const folly::dynamic&) {
      int level_id = checkedLookup(levels, level);
      auto& level_rsrc = resourcesByLevel[level_id];
      p.objectItems([&](const std::string& name, const folly::dynamic&) {
        const int resource_id = resourceNames.insert(name);
        // This inverse index MUST happen as soon as we insert into
        // resourceNames, see the note on the "limit" default below.
        levelIDToResourceID[level_id].push_back(resource_id);

        // IMPORTANT: Nothing from this point onward throws, except inside
        // the parses, which are protected by DynamicParser (see "weight"
        // below for an acceptable example).  This is important so that the
        // various resource structures stay consistent with each other.

        defaultJobResources.resize(resource_id + 1, 0);
        p.required("default", [&](int64_t n) {
          defaultJobResources[resource_id] = n;
        });

        // This is pretty crazy: each level has slots for the resources with
        // IDs from 0 to the maximum resource ID for that level.  Most of
        // those IDs do not belong to this level, so those slots are just set
        // to INT_MAX, and we pray they do not run out.
        level_rsrc.resize(resource_id + 1, std::numeric_limits<int>::max());
        // This default is critical, for a subtle reason. In this parse, we
        // already committed to this being a valid resouce ID.  If "limit"
        // failed to parse and we left this at INT_MAX, then finding this ID
        // in levelIDToResourceID and using resourcesByLevel would yield a
        // sentinel value meaning "this level lacks this resource".  That's
        // a recipe for a CHECK failure.  It would be even worse not to
        // insert into levelIDToResourceID until "limit" is parsed, since
        // that would break Job::toDynamic() -- we wouldd cleanly parse such
        // a resource, and then fail to enumerate it via
        // levelIDToResourceID, resulting in data-loss on save/load cycles.
        // This default avoids both problems.
        level_rsrc[resource_id] = 0;
        p.required("limit", [&](int64_t n) {
          level_rsrc[resource_id] = n;
        });

        // Defaulting to a weight of 0 means that resource won't be a factor
        // when using the "busiest" worker selection strategy.
        resourceIDToWeight.resize(resource_id + 1, 0);
        p.optional("weight", [&](int64_t n) {
          if (n < 0) { throw BistroException("Must be >= 0"); }
          resourceIDToWeight[resource_id] = n;
        });
      });
    });
  });

  p.optional(kWorkerResourceOverride, [&]() {
    const auto& default_rsrcs = workerLevelResourcesRef(*this);
    p.objectItems([&](const std::string& worker, const folly::dynamic&) {
      auto& worker_overrides = workerResourcesOverride[worker];
      p.objectItems([&](const std::string& resource_name, int64_t amount) {
        const int resource_id = checkedLookup(resourceNames, resource_name);
        if (resource_id >= default_rsrcs.size()) {
          throw BistroException("Overriding unknown resource");
        }
        // If a resource is set to max, then we haven't set it for this level.
        if (default_rsrcs[resource_id] == std::numeric_limits<int>::max()) {
          throw BistroException("Overriding resource for wrong level");
        }
        worker_overrides.emplace_back(resource_id, amount);
      });
    });
  });

  parsePhysicalResourceConfigs(
    &p, *this, &physicalResourceConfigs, &logicalToPhysical
  );

  auto errors = p.releaseErrors();
  if (!errors.empty()) {
    throw BistroException("Invalid config: ", folly::toPrettyJson(errors));
  }
}

Config::JobStatus Config::addJob(
    std::shared_ptr<Job> job,
    const Config* prev_config) {
  auto p = jobs.emplace(job->name(), job);
  if (!p.second) {
    throw BistroException("Adding a job that already exists: ", job->name());
  }
  if (prev_config) {
    auto it = prev_config->jobs.find(job->name());
    if (it != prev_config->jobs.end()) {
      auto new_d = job->toDynamic(*this);
      // Slower than a dedicated comparator, but less likely to have bugs.
      if (new_d == it->second->toDynamic(*prev_config)) {
        return Config::JobStatus::UNCHANGED;
      }
      // This and the next log both seem useful for all config loaders.
      LOG(INFO) << "Job " << job->name() << " was modified: "
        << folly::toJson(new_d);
      return Config::JobStatus::UPDATED;
    }
    LOG(INFO) << "Job " << job->name() << " was added: "
      << folly::toJson(job->toDynamic(*this));
    return Config::JobStatus::ADDED;
  }
  return Config::JobStatus::NEW_CONFIG;
}

}}  // namespace facebook::bistro


text:
package command

import (
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"strings"

	"github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
	"github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd"
)

type handlerFunc func(*cli.Context, *etcd.Client) (*etcd.Response, error)
type printFunc func(*etcd.Response, string)
type contextualPrintFunc func(*cli.Context, *etcd.Response, string)

// dumpCURL blindly dumps all curl output to os.Stderr
func dumpCURL(client *etcd.Client) {
	client.OpenCURL()
	for {
		fmt.Fprintf(os.Stderr, "Curl-Example: %s\n", client.RecvCURL())
	}
}

// rawhandle wraps the command function handlers and sets up the
// environment but performs no output formatting.
func rawhandle(c *cli.Context, fn handlerFunc) (*etcd.Response, error) {
	endpoints, err := getEndpoints(c)
	if err != nil {
		return nil, err
	}

	tr, err := getTransport(c)
	if err != nil {
		return nil, err
	}

	client := etcd.NewClient(endpoints)
	client.SetTransport(tr)

	if c.GlobalBool("debug") {
		go dumpCURL(client)
	}

	// Sync cluster.
	if !c.GlobalBool("no-sync") {
		if ok := client.SyncCluster(); !ok {
			handleError(FailedToConnectToHost, errors.New("cannot sync with the cluster using endpoints "+strings.Join(endpoints, ", ")))
		}
	}

	if c.GlobalBool("debug") {
		fmt.Fprintf(os.Stderr, "Cluster-Endpoints: %s\n", strings.Join(client.GetCluster(), ", "))
	}

	// Execute handler function.
	return fn(c, client)
}

// handlePrint wraps the command function handlers to parse global flags
// into a client and to properly format the response objects.
func handlePrint(c *cli.Context, fn handlerFunc, pFn printFunc) {
	resp, err := rawhandle(c, fn)

	// Print error and exit, if necessary.
	if err != nil {
		handleError(ErrorFromEtcd, err)
	}

	if resp != nil && pFn != nil {
		pFn(resp, c.GlobalString("output"))
	}
}

// Just like handlePrint but also passed the context of the command
func handleContextualPrint(c *cli.Context, fn handlerFunc, pFn contextualPrintFunc) {
	resp, err := rawhandle(c, fn)

	if err != nil {
		handleError(ErrorFromEtcd, err)
	}

	if resp != nil && pFn != nil {
		pFn(c, resp, c.GlobalString("output"))
	}
}

// handleDir handles a request that wants to do operations on a single dir.
// Dir cannot be printed out, so we set NIL print function here.
func handleDir(c *cli.Context, fn handlerFunc) {
	handlePrint(c, fn, nil)
}

// handleKey handles a request that wants to do operations on a single key.
func handleKey(c *cli.Context, fn handlerFunc) {
	handlePrint(c, fn, printKey)
}

func handleAll(c *cli.Context, fn handlerFunc) {
	handlePrint(c, fn, printAll)
}

// printKey writes the etcd response to STDOUT in the given format.
func printKey(resp *etcd.Response, format string) {
	// printKey is only for keys, error on directories
	if resp.Node.Dir == true {
		fmt.Fprintln(os.Stderr, fmt.Sprintf("Cannot print key [%s: Is a directory]", resp.Node.Key))
		os.Exit(1)
	}
	printKeyOnly(resp, format)
}

// printAll prints the etcd response in the given format in its best efforts.
func printAll(resp *etcd.Response, format string) {
	if resp.Node.Dir == true {
		return
	}
	printKeyOnly(resp, format)
}

// printKeyOnly only supports to print key correctly.
func printKeyOnly(resp *etcd.Response, format string) {
	// Format the result.
	switch format {
	case "simple":
		fmt.Println(resp.Node.Value)
	case "extended":
		// Extended prints in a rfc2822 style format
		fmt.Println("Key:", resp.Node.Key)
		fmt.Println("Created-Index:", resp.Node.CreatedIndex)
		fmt.Println("Modified-Index:", resp.Node.ModifiedIndex)

		if resp.PrevNode != nil {
			fmt.Println("PrevNode.Value:", resp.PrevNode.Value)
		}

		fmt.Println("TTL:", resp.Node.TTL)
		fmt.Println("Etcd-Index:", resp.EtcdIndex)
		fmt.Println("Raft-Index:", resp.RaftIndex)
		fmt.Println("Raft-Term:", resp.RaftTerm)
		fmt.Println("")
		fmt.Println(resp.Node.Value)
	case "json":
		b, err := json.Marshal(resp)
		if err != nil {
			panic(err)
		}
		fmt.Println(string(b))
	default:
		fmt.Fprintln(os.Stderr, "Unsupported output format:", format)
	}
}


text:
import {
    describe,
    it
} from 'mocha';

import {
    expect
} from 'chai';

import deferredTaskResolveSpy from './util/deferred-task-resolve-spy';
import parallelArray from '../js/parallel-array';

describe('parallelArray', () => {
    it('should run each task in parallel', () => {
        const {
                resolveSpy: resolve1,
                taskSpy: task1
            } = deferredTaskResolveSpy('value 1'),
            {
                resolveSpy: resolve2,
                taskSpy: task2
            } = deferredTaskResolveSpy('value 2');

        return parallelArray([
            task1,
            task2
        ]).then(() => {
            expect(task1.calledBefore(task2)).to.equal(true, 'task1 should be called before task2');
            expect(task2.calledBefore(resolve1)).to.equal(true, 'task2 should be called before resolve1');
            expect(resolve1.calledBefore(resolve2)).to.equal(true, 'resolve1 should be called before resolve2');
        });
    });

    it('should resolve with an array of the resolved return values from each task', () => parallelArray([
        () => Promise.resolve('value 1'),
        () => Promise.resolve('value 2')
    ]).then(result => {
        expect(result).to.eql([
            'value 1',
            'value 2'
        ]);
    }));

    it('should pass along non-Promise values to resolve value', () => parallelArray([
        () => Promise.resolve('value 1'),
        () => 'value 2'
    ]).then(result => {
        expect(result).to.eql([
            'value 1',
            'value 2'
        ]);
    }));

    it('should reject if any task rejects', () => parallelArray([
        () => Promise.resolve('value 1'),
        () => Promise.reject(new Error('test error'))
    ]).catch(error => {
        expect(error).to.be.an.instanceOf(Error).with.property('message', 'test error');
    }));

    it('should reject if the tasks argument is not an array', () => {
        expect(parallelArray.bind(null, {})).to.throw();
    });
});


text:
// This file is automatically generated.

package adila.db;

/*
 * Micromax Canvas Nitro
 *
 * DEVICE: A311
 * MODEL: Micromax A311
 */
final class a311_micromax20a311 {
    public static final String DATA = "Micromax|Canvas Nitro|";
}


text:
Safe, concurrent, practical language

## Maintainers

* The Habitat Maintainers: <humans@habitat.sh>

## Type of Package

Binary package

## Usage

*TODO: Add instructions for usage*


text:
class ShimLocalDataTarget : public ShimDataTarget
{
public:
    ShimLocalDataTarget(DWORD processId, HANDLE hProcess);

    ~ShimLocalDataTarget();

    virtual void Dispose();

    //
    // ICorDebugMutableDataTarget.
    //

    virtual HRESULT STDMETHODCALLTYPE GetPlatform(
        CorDebugPlatform *pPlatform);

    virtual HRESULT STDMETHODCALLTYPE ReadVirtual(
        CORDB_ADDRESS address,
        BYTE * pBuffer,
        ULONG32 request,
        ULONG32 *pcbRead);

    virtual HRESULT STDMETHODCALLTYPE WriteVirtual(
        CORDB_ADDRESS address,
        const BYTE * pBuffer,
        ULONG32 request);

    virtual HRESULT STDMETHODCALLTYPE GetThreadContext(
        DWORD dwThreadID,
        ULONG32 contextFlags,
        ULONG32 contextSize,
        BYTE * context);

    virtual HRESULT STDMETHODCALLTYPE SetThreadContext(
        DWORD dwThreadID,
        ULONG32 contextSize,
        const BYTE * context);

    virtual HRESULT STDMETHODCALLTYPE ContinueStatusChanged(
        DWORD dwThreadId,
        CORDB_CONTINUE_STATUS dwContinueStatus);

    virtual HRESULT STDMETHODCALLTYPE VirtualUnwind(
        DWORD threadId, ULONG32 contextSize, PBYTE context);

private:
    // Handle to the process. We own this.
    HANDLE m_hProcess;
};

// Determines whether the target and host are running on compatible platforms.
// Arguments:
//     input: hTargetProcess - handle for the target process
// Return Value: TRUE iff both target and host are both Wow64 or neither is.
// Note: throws
BOOL CompatibleHostAndTargetPlatforms(HANDLE hTargetProcess)
{
#if defined(FEATURE_PAL)
    return TRUE;
#else
    // get the platform for the host process
    BOOL fHostProcessIsWow64 = FALSE;
    BOOL fSuccess = FALSE;
    HANDLE hHostProcess = GetCurrentProcess();

    fSuccess = IsWow64Process(hHostProcess, &fHostProcessIsWow64);
    CloseHandle(hHostProcess);
    hHostProcess = NULL;

    if (!fSuccess)
    {
        ThrowHR(HRESULT_FROM_GetLastError());
    }

    //  get the platform for the target process
    if (hTargetProcess == NULL)
    {
        ThrowHR(HRESULT_FROM_GetLastError());
    }

    BOOL fTargetProcessIsWow64 = FALSE;
    fSuccess = IsWow64Process(hTargetProcess, &fTargetProcessIsWow64);

    if (!fSuccess)
    {
        ThrowHR(HRESULT_FROM_GetLastError());
    }

    // We don't want to expose the IPC block if one process is x86 and
    // the other is ia64 or amd64
    if (fTargetProcessIsWow64 != fHostProcessIsWow64)
    {
        return FALSE;
    }
    else
    {
        return TRUE;
    }
#endif
} // CompatibleHostAndTargetPlatforms

// Helper macro to check for failure conditions at the start of data-target methods.
#define ReturnFailureIfStateNotOk() \
    if (m_hr != S_OK) \
    { \
        return m_hr; \
    }

//---------------------------------------------------------------------------------------
//
// ctor for ShimLocalDataTarget.
//
// Arguments:
//      processId - pid of live process.
//      hProcess - handle to kernel process object.
//
// Assumptions:
//    Shim takes ownership of handle hProcess.
//

ShimLocalDataTarget::ShimLocalDataTarget(DWORD processId, HANDLE hProcess)
{
    m_ref = 0;

    m_processId = processId;
    m_hProcess = hProcess;

    m_hr = S_OK;

    m_fpContinueStatusChanged = NULL;
    m_pContinueStatusChangedUserData = NULL;
}

//---------------------------------------------------------------------------------------
//
// dctor for ShimLocalDataTarget.
//
ShimLocalDataTarget::~ShimLocalDataTarget()
{
    Dispose();
}

//---------------------------------------------------------------------------------------
//
// Dispose all resources and neuter the object.
//
//
//
// Notes:
//    Release all resources (such as the handle to the process we got in the ctor).
//    May be called multiple times.
//    All other non-trivial APIs (eg, not IUnknown) will fail after this.
//

void ShimLocalDataTarget::Dispose()
{
    if (m_hProcess != NULL)
    {
        CloseHandle(m_hProcess);
        m_hProcess = NULL;
    }
    m_hr = CORDBG_E_OBJECT_NEUTERED;
}

//---------------------------------------------------------------------------------------
//
// Construction method for data-target
//
// Arguments:
//      processId - (input) live OS process ID to build a data-target for.
//      ppDataTarget - (output) new data-target instance. This gets addreffed.
//
// Return Value:
//    S_OK on success.
//
// Assumptions:
//    pid must be for local, same architecture, process.
//    Caller must have security permissions for OpenProcess()
//    Caller must release *ppDataTarget.
//

HRESULT BuildPlatformSpecificDataTarget(MachineInfo machineInfo,
                                        DWORD processId,
                                        ShimDataTarget ** ppDataTarget)
{
    HRESULT hr = S_OK;
    HANDLE hProcess = NULL;
    ShimLocalDataTarget * pLocalDataTarget = NULL;

    *ppDataTarget = NULL;

    hProcess = OpenProcess(
        PROCESS_DUP_HANDLE        |
        PROCESS_QUERY_INFORMATION |
        PROCESS_TERMINATE         |
        PROCESS_VM_OPERATION      |
        PROCESS_VM_READ           |
        PROCESS_VM_WRITE          |
        SYNCHRONIZE,
        FALSE,
        processId);

    if (hProcess == NULL)
    {
        hr = HRESULT_FROM_GetLastError();
        goto Label_Exit;
    }

    EX_TRY
    {
        if (!CompatibleHostAndTargetPlatforms(hProcess))
        {
            hr = CORDBG_E_UNCOMPATIBLE_PLATFORMS;
            goto Label_Exit;
        }
    }
    EX_CATCH_HRESULT(hr);
    if (FAILED(hr))
    {
        goto Label_Exit;
    }
    pLocalDataTarget = new (nothrow) ShimLocalDataTarget(processId, hProcess);
    if (pLocalDataTarget == NULL)
    {
        hr = E_OUTOFMEMORY;
        goto Label_Exit;
    }

    // ShimLocalDataTarget now has ownership of Handle.
    hProcess = NULL;

    _ASSERTE(SUCCEEDED(hr));
    *ppDataTarget = pLocalDataTarget;
    pLocalDataTarget->AddRef(); // must addref out-parameters

Label_Exit:
    if (FAILED(hr))
    {
        if (hProcess != NULL)
        {
            CloseHandle(hProcess);
        }
        delete pLocalDataTarget;
    }

    return hr;
}

// impl of interface method ICorDebugDataTarget::GetPlatform
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::GetPlatform(
        CorDebugPlatform *pPlatform)
{
#ifdef FEATURE_PAL
#error ShimLocalDataTarget is not implemented on PAL systems yet
#endif
    // Assume that we're running on Windows for now.
#if defined(DBG_TARGET_X86)
    *pPlatform = CORDB_PLATFORM_WINDOWS_X86;
#elif defined(DBG_TARGET_AMD64)
    *pPlatform = CORDB_PLATFORM_WINDOWS_AMD64;
#elif defined(DBG_TARGET_ARM)
    *pPlatform = CORDB_PLATFORM_WINDOWS_ARM;
#elif defined(DBG_TARGET_ARM64)
    *pPlatform = CORDB_PLATFORM_WINDOWS_ARM64;
#else
#error Unknown Processor.
#endif
    return S_OK;
}

// impl of interface method ICorDebugDataTarget::ReadVirtual
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::ReadVirtual(
    CORDB_ADDRESS address,
    PBYTE pBuffer,
    ULONG32 cbRequestSize,
    ULONG32 *pcbRead)
{
    ReturnFailureIfStateNotOk();

    // ReadProcessMemory will fail if any part of the
    // region to read does not have read access.  This
    // routine attempts to read the largest valid prefix
    // so it has to break up reads on page boundaries.

    HRESULT hrStatus = S_OK;
    ULONG32 totalDone = 0;
    SIZE_T read;
    ULONG32 readSize;

    while (cbRequestSize > 0)
    {
        // Calculate bytes to read and don't let read cross
        // a page boundary.
        readSize = GetOsPageSize() - (ULONG32)(address & (GetOsPageSize() - 1));
        readSize = min(cbRequestSize, readSize);

        if (!ReadProcessMemory(m_hProcess, (PVOID)(ULONG_PTR)address,
                               pBuffer, readSize, &read))
        {
            if (totalDone == 0)
            {
                // If we haven't read anything indicate failure.
                hrStatus = HRESULT_FROM_GetLastError();
            }
            break;
        }

        totalDone += (ULONG32)read;
        address += read;
        pBuffer += read;
        cbRequestSize -= (ULONG32)read;
    }

    *pcbRead = totalDone;
    return hrStatus;
}

// impl of interface method ICorDebugMutableDataTarget::WriteVirtual
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::WriteVirtual(
    CORDB_ADDRESS pAddress,
    const BYTE * pBuffer,
    ULONG32 cbRequestSize)
{
    ReturnFailureIfStateNotOk();

    SIZE_T cbWritten;
    BOOL fWriteOk = WriteProcessMemory(m_hProcess, CORDB_ADDRESS_TO_PTR(pAddress), pBuffer, cbRequestSize, &cbWritten);
    if (fWriteOk)
    {
        _ASSERTE(cbWritten == cbRequestSize);  // MSDN docs say this must always be true
        return S_OK;
    }
    else
    {
        return HRESULT_FROM_GetLastError();
    }
}

HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::GetThreadContext(
    DWORD dwThreadID,
    ULONG32 contextFlags,
    ULONG32 contextSize,
    BYTE * pContext)
{
    ReturnFailureIfStateNotOk();
    // @dbgtodo - Ideally we should cache the thread handles so that we don't need to
    // open and close the thread handles every time.

    HRESULT hr = E_FAIL;

    if (!CheckContextSizeForBuffer(contextSize, pContext))
    {
        return E_INVALIDARG;
    }

    HandleHolder hThread = OpenThread(
        THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_QUERY_INFORMATION ,
        FALSE, // thread handle is not inheritable.
        dwThreadID);

    if (hThread != NULL)
    {
        DT_CONTEXT * pCtx = reinterpret_cast<DT_CONTEXT *>(pContext);
        pCtx->ContextFlags = contextFlags;

        if (DbiGetThreadContext(hThread, pCtx))
        {
            hr = S_OK;
        }
    }

    // hThread destructed automatically
    return hr;
}

// impl of interface method ICorDebugMutableDataTarget::SetThreadContext
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::SetThreadContext(
    DWORD dwThreadID,
    ULONG32 contextSize,
    const BYTE * pContext)
{
    ReturnFailureIfStateNotOk();
    HRESULT hr = E_FAIL;

    if (!CheckContextSizeForBuffer(contextSize, pContext))
    {
        return E_INVALIDARG;
    }

    HandleHolder hThread = OpenThread(
        THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_QUERY_INFORMATION,
        FALSE, // thread handle is not inheritable.
        dwThreadID);

    if (hThread != NULL)
    {
        if (DbiSetThreadContext(hThread, reinterpret_cast<const DT_CONTEXT *>(pContext)))
        {
            hr = S_OK;
        }
    }

    // hThread destructed automatically
    return hr;
}

// Public implementation of ICorDebugMutableDataTarget::ContinueStatusChanged
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::ContinueStatusChanged(
    DWORD dwThreadId,
    CORDB_CONTINUE_STATUS dwContinueStatus)
{
    ReturnFailureIfStateNotOk();
    if (m_fpContinueStatusChanged != NULL)
    {
        return m_fpContinueStatusChanged(m_pContinueStatusChangedUserData, dwThreadId, dwContinueStatus);
    }
    return E_NOTIMPL;
}

//---------------------------------------------------------------------------------------
//
// Unwind the stack to the next frame.
//
// Return Value:
//     context filled in with the next frame
//
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::VirtualUnwind(DWORD threadId, ULONG32 contextSize, PBYTE context)
{
#ifndef FEATURE_PAL
    _ASSERTE(!"ShimLocalDataTarget::VirtualUnwind NOT IMPLEMENTED");
#endif
    return E_NOTIMPL;
}


text:
package com.lin.school1.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lin.school1.service.UserService;

import cn.itcast.servlet.BaseServlet;

/**
 * 用户数据的控制层
 * @author Administrator
 *
 */
@WebServlet("/UserServlet")
public class UserServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	/**
	 * 用户的业务逻辑层
	 */
    private UserService service = new UserService();

	public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		return "";
	}
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>HDF Metadata Extraction</title>
</head>
<body>
  <form action="http://localhost:8080/odisees/data/extract"
	method="post" enctype="multipart/form-data">
    <input name="file" type="file" size="20" />
    <input type="submit" name="submit" value="submit" />
  </form>
</body>
</html>


text:
class Identity < ActiveRecord::Base
  belongs_to :user

  validates :provider, presence: true
  # validates :extern_uid, allow_blank: true, uniqueness: { scope: :provider }
  validates :extern_uid, uniqueness: { scope: :provider }
  validates :user_id, uniqueness: { scope: :provider }

  #
  # from http://sourcey.com/rails-4-omniauth-using-devise-with-twitter-facebook-and-linkedin/
  #

  def self.find_for_oauth(auth)
    find_or_create_by(extern_uid: auth.uid, provider: auth.provider)
  end
end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. Anat. Physiol. Norm. Pathol. Homme Anim. Paris 43(4): 60 (1954)

#### Original name
Graphium fragrans Math.-Käärik, 1954

### Remarks
null


text:
class CreateLinks < ActiveRecord::Migration[5.1]
  def change
    create_table :links do |t|
      t.string :name
      t.string :link
      t.references :link_category, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end


text:
import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';
import { reactReduxFirebase, firebaseStateReducer } from 'react-redux-firebase';
import reducerCaptcha from './reducer_captcha';

const rootReducer = combineReducers({
  form: formReducer,
  firebase: firebaseStateReducer,
  login: reducerCaptcha
});

export default rootReducer;


text:
Building:
========

Install [Go](http://golang.org/doc/install), git, and
[VIPS 8.3+](http://www.vips.ecs.soton.ac.uk/index.php?title=Stable).

If you haven't used Go before, first create a source tree for your Go code:

    mkdir -p $HOME/gocode/src
    export GOPATH=$HOME/gocode

On OSX, you can install all of the dependencies with [Homebrew](http://brew.sh/):

    brew install go git homebrew/science/vips

On most Linux flavors, you can install Go and VIPS with the ```preinstall.sh``` script:

    git clone https://github.com/die-net/fotomat.git $GOPATH/src/github.com/die-net/fotomat/
    cd $GOPATH/src/github.com/die-net/fotomat/
    sudo ./preinstall.sh

Then for all OSes:

    go get -u github.com/die-net/fotomat

And you'll end up with the executable:```$GOPATH/bin/fotomat```

Docker:
------

Alternatively if you use Docker, there's a
[Dockerfile](https://github.com/die-net/fotomat/blob/master/Dockerfile)
which is used to build an up-to-date
[Docker image](https://hub.docker.com/r/dienet/fotomat/). Fetch it with:

    docker pull dienet/fotomat:latest


text:
import React from 'react';

import { render, screen, fireEvent } from '@testing-library/react';
import { BrowserRouter as Router } from 'react-router-dom';

import buildStripes from '__mock__/stripes.mock';
import '__mock__/stripesCore.mock';

import PermissionSetForm from './PermissionSetForm';

jest.unmock('@folio/stripes/components');

const handleSubmit = () => ({});
const onRemove = () => ({});

const initialVal = {};
const initialValData = {
  id: '14c7a734-f029-4350-8fe0-0bbef7942ce5',
  displayName: 'test-permission-set',
  metadata: {
    createdDate : '',
  },
};

const renderPermissionSetForm = initialValues => {
  const component = (
    <Router>
      <PermissionSetForm
        stripes={buildStripes()}
        handleSubmit={handleSubmit}
        onSubmit={handleSubmit}
        initialValues={initialValues}
        onRemove={onRemove}
      />
    </Router>
  );

  return render(component);
};

describe('PermissionSetForm', () => {
  it('show if component renders data with no inital values', () => {
    renderPermissionSetForm();

    expect(screen.getByText('ui-users.saveAndClose')).toBeDefined();
  });
  it('show if component renders data with empty inital values', () => {
    renderPermissionSetForm(initialVal);

    expect(screen.getByText('ui-users.saveAndClose')).toBeDefined();
  });
  it('Permission list check', () => {
    renderPermissionSetForm(initialVal);

    expect(screen.getByText('ui-users.permissions.newPermissionSet')).toBeDefined();
  });
  it('General info check', () => {
    renderPermissionSetForm(initialVal);

    expect(screen.getByText('ui-users.permissions.generalInformation')).toBeDefined();
  });
  it('description check', () => {
    renderPermissionSetForm(initialVal);

    expect(screen.getByText('ui-users.description')).toBeDefined();
  });
  it('oncancel delete modal check', () => {
    renderPermissionSetForm(initialValData);

    expect(screen.getByText('ui-users.delete')).toBeDefined();
    fireEvent.click(screen.getByText('ui-users.delete'));
    fireEvent.click(screen.getByText('stripes-components.cancel'));
  });
  it('delete check', () => {
    renderPermissionSetForm(initialValData);

    expect(screen.getByText('ui-users.delete')).toBeDefined();
    fireEvent.click(screen.getByText('ui-users.delete'));
    fireEvent.click(document.querySelector('[data-test-confirmation-modal-confirm-button="true"]'));
  });
  it('expand collapse check', () => {
    renderPermissionSetForm(initialValData);

    expect(screen.getByText('stripes-components.collapseAll')).toBeDefined();
    fireEvent.click(screen.getByText('stripes-components.collapseAll'));
  });
  it('toggle accordion check', () => {
    renderPermissionSetForm(initialValData);

    fireEvent.click(screen.getByText('ui-users.permissions.generalInformation'));
  });
});


text:
package com.com.robert.image.demonew;

/**
 * Created by michael on 13-12-18.
 */
public class Config {

    public static final String QRCODE_CONTENT = "http://dajie.me/2vc294";

    public static final int QRCODE_DEFAULT_SIZE = 500;

    public static final String KEY_QRCODE_CONTENT = "content";
    public static final String KEY_RES_ID = "res";
}


text:
package net.coding.program.project.detail;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;

import net.coding.program.MyApp;
import net.coding.program.R;
import net.coding.program.common.Global;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by chaochen on 15/1/30.
 */

@EFragment(R.layout.project_git_fragment_main)
public class ProjectGitFragmentMain extends ProjectGitFragment {

    private final String HOST_LIST_BRANCHES = Global.HOST + "/api/user/%s/project/%s/git/list_branches";
    private final String HOST_LIST_TAG = Global.HOST + "/api/user/%s/project/%s/git/list_tags";

    private ArrayList<String> mDataVers[] = new ArrayList[]{new ArrayList(), new ArrayList()};

    @ViewById
    TextView versionButton;

    @ViewById
    View versionLayout;

    @ViewById
    ExpandableListView versionList;

    @ViewById
    View expandableIndicator;

    // 父类已经使用了 init,子类就不能再用这个名字,否则 init 会调用两次
    @AfterViews
    protected void init2() {
        setHasOptionsMenu(true);

        String urlBranches = String.format(HOST_LIST_BRANCHES, mProjectObject.owner_user_name, mProjectObject.name);
        getNetwork(urlBranches, HOST_LIST_BRANCHES);

        String urlTag = String.format(HOST_LIST_TAG, mProjectObject.owner_user_name, mProjectObject.name);
        getNetwork(urlTag, HOST_LIST_TAG);
        versionList.setAdapter(versionAdapter);

        int left = Global.dpToPx(MyApp.sWidthDp - 40);
        int right = Global.dpToPx(MyApp.sWidthDp - 12);
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            versionList.setIndicatorBounds(left, right);
        } else {
            versionList.setIndicatorBoundsRelative(left, right);
        }
        versionList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                String data = (String) versionAdapter.getChild(groupPosition, childPosition);
                mVersion = data;

                versionButton.performClick();
                onRefresh();
                return true;
            }
        });
    }

    @Click
    void versionButton() {
        showList(versionLayout.getVisibility() != View.VISIBLE);
    }

    @Click
    void versionLayout() {
        showList(versionLayout.getVisibility() != View.VISIBLE);
    }

    @Override
    public void parseJson(int code, JSONObject respanse, String tag, int pos, Object data) throws JSONException {
        if (tag.equals(HOST_LIST_BRANCHES)) {
            parseVersion(mDataVers[0], code, respanse);
        } else if (tag.equals(HOST_LIST_TAG)) {
            parseVersion(mDataVers[1], code, respanse);
        } else {
            super.parseJson(code, respanse, tag, pos, data);
        }
    }

    @Override
    protected void switchVersionSuccess() {
        showButtomToast(String.format("已切换到 %s", mVersion));
        versionButton.setText(mVersion);
    }

    private void parseVersion(ArrayList<String> data, int code, JSONObject respanse) {
        if (code == 0) {
            JSONArray array = respanse.optJSONArray("data");
            data.clear();
            for (int i = 0; i < array.length(); ++i) {
                data.add(array.optJSONObject(i).optString("name", ""));
            }

            ((BaseExpandableListAdapter) versionAdapter).notifyDataSetChanged();

        } else {
            showErrorMsg(code, respanse);
        }
    }

    ExpandableListAdapter versionAdapter = new BaseExpandableListAdapter() {
        @Override
        public int getGroupCount() {
            return mDataVers.length;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return mDataVers[groupPosition].size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return "";
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return mDataVers[groupPosition].get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            ViewGroupHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.git_view_group, parent, false);
                holder = new ViewGroupHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewGroupHolder) convertView.getTag();
            }

            final String[] datas = new String[]{"branches", "tags"};
            final int[] iconsId = new int[]{R.drawable.icon_git_branch, R.drawable.icon_git_tag};

            holder.title.setText(datas[groupPosition]);
            holder.icon.setBackgroundResource(iconsId[groupPosition]);

            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.git_view_child, parent, false);
            }

            String data = (String) getChild(groupPosition, childPosition);
            ((TextView) convertView).setText(data);

            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

    };

    private static class ViewGroupHolder {

        public ViewGroupHolder(View parent) {
            icon = parent.findViewById(R.id.icon);
            title = (TextView) parent.findViewById(R.id.title);
        }

        View icon;
        TextView title;
    }

    private void showList(boolean show) {
        Animation animation;
        Animation fadeIn;
        if (show) {
            animation = AnimationUtils.loadAnimation(getActivity(), R.anim.listview_top_down);
            fadeIn = AnimationUtils.loadAnimation(getActivity(), R.anim.listview_fade_in);
            fadeIn.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    expandableIndicator.setBackgroundResource(R.drawable.icon_git_indicator_up);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });
        } else {
            animation = AnimationUtils.loadAnimation(getActivity(), R.anim.listview_top_up);
            fadeIn = AnimationUtils.loadAnimation(getActivity(), R.anim.listview_fade_out);
            fadeIn.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    versionLayout.setVisibility(View.INVISIBLE);
                    expandableIndicator.setBackgroundResource(R.drawable.icon_git_indicator_down);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });
        }

        versionList.startAnimation(animation);
        versionLayout.startAnimation(fadeIn);

        if (show) {
            versionLayout.setVisibility(View.VISIBLE);
        }
    }

}


text:
package com.fetoxdevelopments.optix.api.struct;

import org.bridj.Pointer;
import org.bridj.TypedPointer;

public class RTtransform
  extends TypedPointer
{
  public RTtransform(long address)
  {
    super(address);
  }

  public RTtransform(Pointer address)
  {
    super(address);
  }
}


text:
(function() {
  var JumpTable, OMeta, extend, programString, propertyNames, subclass, _ref;

  OMeta = require('./ometa-base');

  _ref = require('./ometa-lib'), subclass = _ref.subclass, propertyNames = _ref.propertyNames, programString = _ref.programString, extend = _ref.extend;

  BSNullOptimization = subclass(OMeta, {
    "setHelped": function() {
      return this._didSomething = true
    },
    "helped": function() {
      return this._pred(this._didSomething)
    },
    "trans": function() {
      var t, ans;
      return (function() {
        at = this._idxConsumedBy((function() {
          return this._form((function() {
            return (function() {
              t = this._apply("anything");
              this._pred(this[t] != null);
              return ans = this._applyWithArgs("apply", t)
            }).call(this)
          }))
        }));
        return ans
      }).call(this)
    },
    "optimize": function() {
      var x;
      return (function() {
        at = this._idxConsumedBy((function() {
          return (function() {
            x = this._apply("trans");
            return this._apply("helped")
          }).call(this)
        }));
        return x
      }).call(this)
    },
    "App": function() {
      var rule, args;
      return (function() {
        at = this._idxConsumedBy((function() {
          return (function() {
            rule = this._apply("anything");
            return args = this._many((function() {
              return this._apply("anything")
            }))
          }).call(this)
        }));
        return ['App', rule].concat(args)
      }).call(this)
    },
    "Act": function() {
      var expr;
      return (function() {
        at = this._idxConsumedBy((function() {
          return expr = this._apply("anything")
        }));
        return ['Act', expr]
      }).call(this)
    },
    "Pred": function() {
      var expr;
      return (function() {
        at = this._idxConsumedBy((function() {
          return expr = this._apply("anything")
        }));
        return ['Pred', expr]
      }).call(this)
    },
    "Or": function() {
      var xs;
      return (function() {
        at = this._idxConsumedBy((function() {
          return xs = this._many((function() {
            return this._apply("trans")
          }))
        }));
        return ['Or'].concat(xs)
      }).call(this)
    },
    "XOr": function() {
      var xs;
      return (function() {
        at = this._idxConsumedBy((function() {
          return xs = this._many((function() {
            return this._apply("trans")
          }))
        }));
        return ['XOr'].concat(xs)
      }).call(this)
    },
    "And": function() {
      var xs;
      return (function() {
        at = this._idxConsumedBy((function() {
          return xs = this._many((function() {
            return this._apply("trans")
          }))
        }));
        return ['And'].concat(xs)
      }).call(this)
    },
    "Opt": function() {
      var x;
      return (function() {
        at = this._idxConsumedBy((function() {
          return x = this._apply("trans")
        }));
        return ['Opt', x]
      }).call(this)
    },
    "Many": function() {
      var x;
      return (function() {
        at = this._idxConsumedBy((function() {
          return x = this._apply("trans")
        }));
        return ['Many', x]
      }).call(this)
    },
    "Many1": function() {
      var x;
      return (function() {
        at = this._idxConsumedBy((function() {
          return x = this._apply("trans")
        }));
        return ['Many1', x]
      }).call(this)
    },
    "Set": function() {
      var n, v;
      return (function() {
        at = this._idxConsumedBy((function() {
          return (function() {
            n = this._apply("anything");
            return v = this._apply("trans")
          }).call(this)
        }));
        return ['Set', n, v]
      }).call(this)
    },
    "Not": function() {
      var x;
      return (function() {
        at = this._idxConsumedBy((function() {
          return x = this._apply("trans")
        }));
        return ['Not', x]
      }).call(this)
    },
    "Lookahead": function() {
      var x;
      return (function() {
        at = this._idxConsumedBy((function() {
          return x = this._apply("trans")
        }));
        return ['Lookahead', x]
      }).call(this)
    },
    "Form": function() {
      var x;
      return (function() {
        at = this._idxConsumedBy((function() {
          return x = this._apply("trans")
        }));
        return ['Form', x]
      }).call(this)
    },
    "ConsBy": function() {
      var x;
      return (function() {
        at = this._idxConsumedBy((function() {
          return x = this._apply("trans")
        }));
        return ['ConsBy', x]
      }).call(this)
    },
    "IdxConsBy": function() {
      var x;
      return (function() {
        at = this._idxConsumedBy((function() {
          return x = this._apply("trans")
        }));
        return ['IdxConsBy', x]
      }).call(this)
    },
    "JumpTable": function() {
      var c, e, ces;
      return (function() {
        at = this._idxConsumedBy((function() {
          return ces = this._many((function() {
            return (function() {
              at = this._idxConsumedBy((function() {
                return this._form((function() {
                  return (function() {
                    c = this._apply("anything");
                    return e = this._apply("trans")
                  }).call(this)
                }))
              }));
              return [c, e]
            }).call(this)
          }))
        }));
        return ['JumpTable'].concat(ces)
      }).call(this)
    },
    "Interleave": function() {
      var m, p, xs;
      return (function() {
        at = this._idxConsumedBy((function() {
          return xs = this._many((function() {
            return (function() {
              at = this._idxConsumedBy((function() {
                return this._form((function() {
                  return (function() {
                    m = this._apply("anything");
                    return p = this._apply("trans")
                  }).call(this)
                }))
              }));
              return [m, p]
            }).call(this)
          }))
        }));
        return ['Interleave'].concat(xs)
      }).call(this)
    },
    "Rule": function() {
      var name, ls, body;
      return (function() {
        at = this._idxConsumedBy((function() {
          return (function() {
            name = this._apply("anything");
            ls = this._apply("anything");
            return body = this._apply("trans")
          }).call(this)
        }));
        return ['Rule', name, ls, body]
      }).call(this)
    },
    "initialize": function() {
      return (function() {
        at = this._idxConsumedBy((function() {
          return undefined
        }));
        return this._didSomething = false
      }).call(this)
    }
  });;

  BSAssociativeOptimization = subclass(BSNullOptimization, {
    "And": function() {
      var x, xs;
      return this._or((function() {
        return (function() {
          at = this._idxConsumedBy((function() {
            return (function() {
              x = this._apply("trans");
              this._apply("end");
              return this._apply("setHelped")
            }).call(this)
          }));
          return x
        }).call(this)
      }), (function() {
        return (function() {
          at = this._idxConsumedBy((function() {
            return xs = this._applyWithArgs("transInside", 'And')
          }));
          return ['And'].concat(xs)
        }).call(this)
      }))
    },
    "Or": function() {
      var x, xs;
      return this._or((function() {
        return (function() {
          at = this._idxConsumedBy((function() {
            return (function() {
              x = this._apply("trans");
              this._apply("end");
              return this._apply("setHelped")
            }).call(this)
          }));
          return x
        }).call(this)
      }), (function() {
        return (function() {
          at = this._idxConsumedBy((function() {
            return xs = this._applyWithArgs("transInside", 'Or')
          }));
          return ['Or'].concat(xs)
        }).call(this)
      }))
    },
    "XOr": function() {
      var x, xs;
      return this._or((function() {
        return (function() {
          at = this._idxConsumedBy((function() {
            return (function() {
              x = this._apply("trans");
              this._apply("end");
              return this._apply("setHelped")
            }).call(this)
          }));
          return x
        }).call(this)
      }), (function() {
        return (function() {
          at = this._idxConsumedBy((function() {
            return xs = this._applyWithArgs("transInside", 'XOr')
          }));
          return ['XOr'].concat(xs)
        }).call(this)
      }))
    },
    "transInside": function() {
      var t, xs, ys, x;
      return (function() {
        t = this._apply("anything");
        return this._or((function() {
          return (function() {
            at = this._idxConsumedBy((function() {
              return (function() {
                this._form((function() {
                  return (function() {
                    this._applyWithArgs("exactly", t);
                    return xs = this._applyWithArgs("transInside", t)
                  }).call(this)
                }));
                ys = this._applyWithArgs("transInside", t);
                return this._apply("setHelped")
              }).call(this)
            }));
            return xs.concat(ys)
          }).call(this)
        }), (function() {
          return (function() {
            at = this._idxConsumedBy((function() {
              return (function() {
                x = this._apply("trans");
                return xs = this._applyWithArgs("transInside", t)
              }).call(this)
            }));
            return [x].concat(xs)
          }).call(this)
        }), (function() {
          return (function() {
            at = this._idxConsumedBy((function() {
              return undefined
            }));
            return []
          }).call(this)
        }))
      }).call(this)
    }
  });;

  BSSeqInliner = subclass(BSNullOptimization, {
    "App": function() {
      var s, cs, rule, args;
      return this._or((function() {
        return (function() {
          at = this._idxConsumedBy((function() {
            return (function() {
              this._applyWithArgs("exactly", "seq");
              s = this._apply("anything");
              this._apply("end");
              cs = this._applyWithArgs("seqString", s);
              return this._apply("setHelped")
            }).call(this)
          }));
          return ['And'].concat(cs).concat([
            ['Act', s]
          ])
        }).call(this)
      }), (function() {
        return (function() {
          at = this._idxConsumedBy((function() {
            return (function() {
              rule = this._apply("anything");
              return args = this._many((function() {
                return this._apply("anything")
              }))
            }).call(this)
          }));
          return ['App', rule].concat(args)
        }).call(this)
      }))
    },
    "inlineChar": function() {
      var BSOMetaParser, c;
      return (function() {
        at = this._idxConsumedBy((function() {
          return (function() {
            BSOMetaParser = (require('./bs-ometa-compiler')).BSOMetaParser;
            c = this._applyWithArgs("foreign", BSOMetaParser, 'escapedChar');
            return this._not((function() {
              return this._apply("end")
            }))
          }).call(this)
        }));
        return ['App', 'exactly', programString(c)]
      }).call(this)
    },
    "seqString": function() {
      var s, cs;
      return (function() {
        this._lookahead((function() {
          return (function() {
            s = this._apply("anything");
            return this._pred(typeof s === 'string')
          }).call(this)
        }));
        return this._or((function() {
          return (function() {
            at = this._idxConsumedBy((function() {
              return this._form((function() {
                return (function() {
                  this._applyWithArgs("exactly", "\"");
                  cs = this._many((function() {
                    return this._apply("inlineChar")
                  }));
                  return this._applyWithArgs("exactly", "\"")
                }).call(this)
              }))
            }));
            return cs
          }).call(this)
        }), (function() {
          return (function() {
            at = this._idxConsumedBy((function() {
              return this._form((function() {
                return (function() {
                  this._applyWithArgs("exactly", "\'");
                  cs = this._many((function() {
                    return this._apply("inlineChar")
                  }));
                  return this._applyWithArgs("exactly", "\'")
                }).call(this)
              }))
            }));
            return cs
          }).call(this)
        }))
      }).call(this)
    }
  });;

  JumpTable = (function() {

    function JumpTable(choiceOp, choice) {
      this.choiceOp = choiceOp;
      this.choices = {};
      this.add(choice);
      return;
    }

    JumpTable.prototype.add = function(choice) {
      var c, t;
      c = choice[0], t = choice[1];
      if (this.choices[c]) {
        if (this.choices[c][0] === this.choiceOp) {
          this.choices[c].push(t);
        } else {
          this.choices[c] = [this.choiceOp, this.choices[c], t];
        }
      } else {
        this.choices[c] = t;
      }
    };

    JumpTable.prototype.toTree = function() {
      var choiceKey, choiceKeys, r, _i, _len;
      r = ['JumpTable'];
      choiceKeys = propertyNames(this.choices);
      for (_i = 0, _len = choiceKeys.length; _i < _len; _i++) {
        choiceKey = choiceKeys[_i];
        r.push([choiceKey, this.choices[choiceKey]]);
      }
      return r;
    };

    return JumpTable;

  })();

  BSJumpTableOptimization = subclass(BSNullOptimization, {
    "Or": function() {
      var cs;
      return (function() {
        at = this._idxConsumedBy((function() {
          return cs = this._many((function() {
            return this._or((function() {
              return this._applyWithArgs("jtChoices", 'Or')
            }), (function() {
              return this._apply("trans")
            }))
          }))
        }));
        return ['Or'].concat(cs)
      }).call(this)
    },
    "XOr": function() {
      var cs;
      return (function() {
        at = this._idxConsumedBy((function() {
          return cs = this._many((function() {
            return this._or((function() {
              return this._applyWithArgs("jtChoices", 'XOr')
            }), (function() {
              return this._apply("trans")
            }))
          }))
        }));
        return ['XOr'].concat(cs)
      }).call(this)
    },
    "quotedString": function() {
      var BSOMetaParser, c, cs;
      return (function() {
        at = this._idxConsumedBy((function() {
          return (function() {
            BSOMetaParser = (require('./bs-ometa-compiler')).BSOMetaParser;
            this._lookahead((function() {
              return this._apply("string")
            }));
            return this._form((function() {
              return (function() {
                switch (this._apply('anything')) {
                  case "\"":
                    return (function() {
                      cs = this._many((function() {
                        return (function() {
                          at = this._idxConsumedBy((function() {
                            return (function() {
                              c = this._applyWithArgs("foreign", BSOMetaParser, 'escapedChar');
                              return this._not((function() {
                                return this._apply("end")
                              }))
                            }).call(this)
                          }));
                          return c
                        }).call(this)
                      }));
                      return this._applyWithArgs("exactly", "\"")
                    }).call(this);
                  case "\'":
                    return (function() {
                      cs = this._many((function() {
                        return (function() {
                          at = this._idxConsumedBy((function() {
                            return (function() {
                              c = this._applyWithArgs("foreign", BSOMetaParser, 'escapedChar');
                              return this._not((function() {
                                return this._apply("end")
                              }))
                            }).call(this)
                          }));
                          return c
                        }).call(this)
                      }));
                      return this._applyWithArgs("exactly", "\'")
                    }).call(this);
                  default:
                    throw this.fail
                }
              }).call(this)
            }))
          }).call(this)
        }));
        return cs.join('')
      }).call(this)
    },
    "jtChoice": function() {
      var x, rest;
      return this._or((function() {
        return (function() {
          at = this._idxConsumedBy((function() {
            return this._form((function() {
              return (function() {
                this._applyWithArgs("exactly", "And");
                this._form((function() {
                  return (function() {
                    this._applyWithArgs("exactly", "App");
                    this._applyWithArgs("exactly", "exactly");
                    return x = this._apply("quotedString")
                  }).call(this)
                }));
                return rest = this._many((function() {
                  return this._apply("anything")
                }))
              }).call(this)
            }))
          }));
          return [x, ['And'].concat(rest)]
        }).call(this)
      }), (function() {
        return (function() {
          at = this._idxConsumedBy((function() {
            return this._form((function() {
              return (function() {
                this._applyWithArgs("exactly", "App");
                this._applyWithArgs("exactly", "exactly");
                return x = this._apply("quotedString")
              }).call(this)
            }))
          }));
          return [x, ['Act', programString(x)]]
        }).call(this)
      }))
    },
    "jtChoices": function() {
      var op, c, jt;
      return (function() {
        op = this._apply("anything");
        at = this._idxConsumedBy((function() {
          return (function() {
            c = this._apply("jtChoice");
            jt = new JumpTable(op, c);
            this._many((function() {
              return (function() {
                c = this._apply("jtChoice");
                return jt.add(c)
              }).call(this)
            }));
            return this._apply("setHelped")
          }).call(this)
        }));
        return jt.toTree()
      }).call(this)
    }
  });;

  BSOMetaOptimizer = subclass(OMeta, {
    "optimizeGrammar": function() {
      var n, sn, rs;
      return (function() {
        at = this._idxConsumedBy((function() {
          return this._form((function() {
            return (function() {
              this._applyWithArgs("exactly", "Grammar");
              n = this._apply("anything");
              sn = this._apply("anything");
              return rs = this._many((function() {
                return this._apply("optimizeRule")
              }))
            }).call(this)
          }))
        }));
        return ['Grammar', n, sn].concat(rs)
      }).call(this)
    },
    "optimizeRule": function() {
      var r;
      return (function() {
        at = this._idxConsumedBy((function() {
          return (function() {
            r = this._apply("anything");
            this._or((function() {
              return r = this._applyWithArgs("foreign", BSSeqInliner, 'optimize', r)
            }), (function() {
              return this._apply("empty")
            }));
            return this._many((function() {
              return this._or((function() {
                return r = this._applyWithArgs("foreign", BSAssociativeOptimization, 'optimize', r)
              }), (function() {
                return r = this._applyWithArgs("foreign", BSJumpTableOptimization, 'optimize', r)
              }))
            }))
          }).call(this)
        }));
        return r
      }).call(this)
    }
  });;

  module.exports = BSOMetaOptimizer;

}).call(this);


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Pump</title>
<meta name="date" content="2014-11-13">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.vertx.java.core.streams

Class Pump

java.lang.Object

org.vertx.java.core.streams.Pump

public class Pump
extends java.lang.Object

Pumps data from a ReadStream to a WriteStream and performs flow control where necessary to
 prevent the write stream buffer from getting overfull.

 Instances of this class read bytes from a ReadStream and write them to a WriteStream. If data
 can be read faster than it can be written this could result in the write queue of the WriteStream growing
 without bound, eventually causing it to exhaust all available RAM.

 To prevent this, after each write, instances of this class check whether the write queue of the WriteStream is full, and if so, the ReadStream is paused, and a drainHandler is set on the
 WriteStream. When the WriteStream has processed half of its backlog, the drainHandler will be
 called, which results in the pump resuming the ReadStream.

 This class can be used to pump from any ReadStream to any WriteStream,
 e.g. from an HttpServerRequest to an AsyncFile,
 or from NetSocket to a WebSocket.

 Instances of this class are not thread-safe.

Method Summary

Methods

Modifier and Type
Method and Description

int
bytesPumped()

Return the total number of bytes pumped by this pump.

static Pump
createPump(ReadStream<?> rs,
          WriteStream<?> ws)

Create a new Pump with the given ReadStream and WriteStream

static Pump
createPump(ReadStream<?> rs,
          WriteStream<?> ws,
          int writeQueueMaxSize)

Create a new Pump with the given ReadStream and WriteStream and
 writeQueueMaxSize

Pump
setWriteQueueMaxSize(int maxSize)

Set the write queue max size to maxSize

Pump
start()

Start the Pump.

Pump
stop()

Stop the Pump.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

createPump

public static Pump createPump(ReadStream<?> rs,
              WriteStream<?> ws)

Create a new Pump with the given ReadStream and WriteStream

createPump

public static Pump createPump(ReadStream<?> rs,
              WriteStream<?> ws,
              int writeQueueMaxSize)

Create a new Pump with the given ReadStream and WriteStream and
 writeQueueMaxSize

setWriteQueueMaxSize

public Pump setWriteQueueMaxSize(int maxSize)

Set the write queue max size to maxSize

start

public Pump start()

Start the Pump. The Pump can be started and stopped multiple times.

stop

public Pump stop()

Stop the Pump. The Pump can be started and stopped multiple times.

bytesPumped

public int bytesPumped()

Return the total number of bytes pumped by this pump.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method