/*
run the twitter REST API for a character to fill the database with tweets. startDate can be 2 weeks
in the past at most
421003
function (character, startDate, callback) {
        twitterAPI.getRest(character, startDate, new Date().toISOString(), false, callback);
    }
597027
function()
			{
				var tweenTime = (new Date()).getTime() / 1000;

				var time = tweenTime - _tweenTime;
				if (time < 0)
					time = 0;
				else if (time > 0.1)
					time = 0.1;
				_tweenTime = tweenTime;

				var runInfos = _tweenRunInfo.values();
				var runInfo;
				var position;
				for (var i = 0, l = runInfos.length; i < l; i++)
				{
					runInfo = runInfos[i];

					runInfo.time += time;

					position = runInfo.time / runInfo.duration;
					if (position > 1)
						position = 1;

					if (!runInfo.tween.updateTween(position))
						position = 1;

					if (position == 1)
						TweenRunner.stop(runInfo.tween);
				}
			}
650610
function run (N, op, init) {
  var stats = null, value
  for(var j = 0; j < 100; j++) {
    if(init) value = init(j)
    var start = Date.now()
    for(var i = 0; i < N; i++) op(value, i)
    stats = Stats(stats, N/((Date.now() - start)))
  }
  return stats
}
662198
def limitted_dump(cursor=None, twitter=None, path='tweets.json', limit=450, rate=TWITTER_SEARCH_RATE_LIMIT, indent=-1):
    
    if not twitter:
        twitter = get_twitter()
    cursor = cursor or 'python'
    if isinstance(cursor, basestring):
        cursor = get_cursor(twitter, search=cursor)
    newline = '\n' if indent is not None else ''
    if indent < 0:
        indent = None
    # TODO: keep track of T0 for the optimal "reset" sleep duration
    with (open(path, 'w') if not isinstance(path, file) else path) as f:
        f.write('[\n')
        for i, obj in enumerate(cursor):
            f.write(json.dumps(obj, indent=indent))
            if i < limit - 1:
                f.write(',' + newline)
            else:
                break
            remaining = int(twitter.get_lastfunction_header('x-rate-limit-remaining'))
            if remaining > 0:
                sleep(1. / rate)
            else:
                sleep(15 * 60)
        f.write('\n]\n')
416774
public static void main(String[] args) {
        try {
            Twitter twitter = new TwitterFactory().getInstance();
            List<Status> statuses = twitter.getFavorites();
            for (Status status : statuses) {
                System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            }
            System.out.println("done.");
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get favorites: " + te.getMessage());
            System.exit(-1);
        }
    }
44487
public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("Usage: java twitter4j.examples.list.ShowUserList [list id]");
            System.exit(-1);
        }
        try {
            Twitter twitter = new TwitterFactory().getInstance();
            UserList list = twitter.showUserList(Integer.parseInt(args[0]));
            System.out.println("id:" + list.getId() + ", name:" + list.getName() + ", description:"
                    + list.getDescription() + ", slug:" + list.getSlug() + "");
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to show the list: " + te.getMessage());
            System.exit(-1);
        }
    }
1308276
public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("Usage: java twitter4j.examples.geo.SearchPlaces [ip address] or [latitude] [longitude]");
            System.exit(-1);
        }
        try {
            Twitter twitter = new TwitterFactory().getInstance();
            GeoQuery query;
            if (args.length == 2) {
                query = new GeoQuery(new GeoLocation(Double.parseDouble(args[0]), Double.parseDouble(args[1])));
            } else {
                query = new GeoQuery(args[0]);
            }
            ResponseList<Place> places = twitter.searchPlaces(query);
            if (places.size() == 0) {
                System.out.println("No location associated with the specified IP address or lat/lang");
            } else {
                for (Place place : places) {
                    System.out.println("id: " + place.getId() + " name: " + place.getFullName());
                    Place[] containedWithinArray = place.getContainedWithIn();
                    if (containedWithinArray != null && containedWithinArray.length != 0) {
                        System.out.println("  contained within:");
                        for (Place containedWithinPlace : containedWithinArray) {
                            System.out.println("  id: " + containedWithinPlace.getId() + " name: " + containedWithinPlace.getFullName());
                        }
                    }
                }
            }
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to retrieve places: " + te.getMessage());
            System.exit(-1);
        }
    }
277688
function runQuery(query, connection) {
  const incomplete = false;

  return new Promise((resolve, reject) => {
    const client = hdb.createClient({
      host: connection.host,
      port: connection.hanaport,
      database: connection.hanadatabase,
      user: connection.username,
      password: connection.password,
      schema: connection.hanaSchema
    });

    client.on('error', err => {
      console.error('Network connection error', err);
      return reject(err);
    });

    client.connect(err => {
      if (err) {
        console.error('Connect error', err);
        return reject(err);
      }
      return client.execute(query, function(err, rs) {
        let rows = [];

        if (err) {
          client.disconnect();
          return reject(err);
        }

        if (!rs) {
          client.disconnect();
          return resolve({ rows, incomplete });
        }

        if (!rs.createObjectStream) {
          // Could be row count or something
          client.disconnect();
          return resolve({ rows: [{ result: rs }], incomplete });
        }

        const stream = rs.createObjectStream();

        stream.on('data', data => {
          if (rows.length < connection.maxRows) {
            return rows.push(data);
          }
          client.disconnect();
          return resolve({ rows, incomplete: true });
        });

        stream.on('error', error => {
          client.disconnect();
          return reject(error);
        });

        stream.on('finish', () => {
          client.disconnect();
          return resolve({ rows, incomplete });
        });
      });
    });
  });
}
394829
public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("Usage: java twitter4j.examples.list.GetUserLists [list owner screen name]");
            System.exit(-1);
        }
        try {
            Twitter twitter = new TwitterFactory().getInstance();
            ResponseList<UserList> lists = twitter.getUserLists(args[0]);
            for (UserList list : lists) {
                System.out.println("id:" + list.getId() + ", name:" + list.getName() + ", description:"
                        + list.getDescription() + ", slug:" + list.getSlug() + "");
            }
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to list the lists: " + te.getMessage());
            System.exit(-1);
        }
    }
398934
function run(data) {
  var cookies = cookie.parse(data.cookies);
  debug('cookies: ', cookies);
  request({
    method: 'POST',
    url: 'http://weibo.com/aj/mblog/add?_wv=5&__rnd=' + (new Date).getTime(),
    headers: {
      Cookie: data.cookies,
      Referer: data.referer
    },
    form: 'text=you%20are%20attacked' + (new Date).getTime() + '&pic_id=&rank=0&rankid=&_surl=&hottopicid=&location=home&module=stissue&_t=0'
  }, function(err, res, body) {
    debug('err', err);
    debug('body', body);
  });
}
6295
@Override
    public synchronized void run(){
        Date now = new Date();
        if ( !cache.isEmpty() &&
                ((cache.size() > cacheSize - 1) || (now.getTime() - lastCacheAccess.getTime() > cacheMillis))) {
            try {
                flush();
            } catch (RepositoryException e) {
                log.error(e.getLocalizedMessage());
                throw new RuntimeException(e);
            } catch (MalformedQueryException e) {
                log.error(e.getLocalizedMessage());
                throw new RuntimeException(e);
            } catch (UpdateExecutionException e) {
                log.error(e.getLocalizedMessage());
                throw new RuntimeException(e);
            } catch (IOException e) {
                log.error(e.getLocalizedMessage());
                throw new RuntimeException(e);
            }
        }
    }
380306
public static void main(String[] args) throws TwitterException {
        TwitterStream twitterStream = new TwitterStreamFactory().getInstance().addListener(new RawStreamListener() {
            @Override
            public void onMessage(String rawJSON) {
                System.out.println(rawJSON);
            }

            @Override
            public void onException(Exception ex) {
                ex.printStackTrace();
            }
        }).sample();
    }
1286306
public static void main(String[] args) {
        try {
            Twitter twitter = new TwitterFactory().getInstance();
            User user = twitter.verifyCredentials();
            System.out.println("Successfully verified credentials of " + user.getScreenName());
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to verify credentials: " + te.getMessage());
            System.exit(-1);
        }
    }
429089
function runTool(platform, args, done) {
  if (args.length < 1) {
    console.log('usage: query.js file.wtf-trace "[query string]"');
    done(1);
    return;
  }

  var inputFile = args[0];
  var exprArgs = args.slice(1);
  var expr = exprArgs.join(' ').trim();

  console.log('Querying ' + inputFile + '...');

  // Create database for querying.
  var loadStart = wtf.now();
  wtf.db.load(inputFile, function(db) {
    if (db instanceof Error) {
      console.log('ERROR: unable to open ' + inputFile, db);
      done(1);
      return;
    }

    var loadDuration = wtf.now() - loadStart;
    console.log('Database loaded in ' + loadDuration.toFixed(3) + 'ms');
    console.log('');

    queryDatabase(db, expr);

    done(0);
  });
}
608919
public static void main(String[] args) {
        try {
            Twitter twitter = new TwitterFactory().getInstance();
            ResponseList<Location> locations;
            locations = twitter.getAvailableTrends();
            System.out.println("Showing available trends");
            for (Location location : locations) {
                System.out.println(location.getName() + " (woeid:" + location.getWoeid() + ")");
            }
            System.out.println("done.");
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get trends: " + te.getMessage());
            System.exit(-1);
        }
    }
582220
function (json, callback) {
        //validate input
        if (!inputValidation(json)) {
            var inputError = new SearchError('invalid input');
            callback(undefined, inputError);
            return;
        }
        var number = json.number;
        //mongodb api here, then handle the response from mongodb
        database.getSentimentTimeframe(json.startDate, json.endDate, function (json, err) {
            if (err) {
                callback(undefined, err);
            } else {
                var res = calculateTopSum(json, number, ["posSum"]);
                callback(res);
            }
        });
    }
1297904
function runQuery(query, connection) {
  const config = {
    user: connection.username,
    password: connection.password,
    connection_string: connection.connection_string
  };
  // TODO use connection pool
  // TODO handle connection.maxRows

  let cn = config.connection_string;

  // Not all drivers require auth
  if (config.user) {
    cn = cn + ';Uid=' + config.user;
  }
  if (config.password) {
    cn = cn + ';Pwd=' + config.password;
  }

  return openConnection(cn)
    .then(() => executeQuery(query))
    .then(queryResult => {
      odbc.close(); // TODO consider putting into finally()?
      return Promise.resolve({ rows: queryResult, incomplete: false });
    })
    .catch(function(e) {
      console.error(e, e.stack);
    });
}