text:
import string
import random

WORDLIST_FILENAME = "words.txt"

# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
def loadWords():
    """
    Returns a list of valid words. Words are strings of lowercase letters.

    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print "Loading word list from file..."
    inFile = open(WORDLIST_FILENAME, 'r')
    wordList = inFile.read().split()
    print "  ", len(wordList), "words loaded."
    return wordList

def isWord(wordList, word):
    """
    Determines if word is a valid word.

    wordList: list of words in the dictionary.
    word: a possible word.
    returns True if word is in wordList.

    Example:
    >>> isWord(wordList, 'bat') returns
    True
    >>> isWord(wordList, 'asdf') returns
    False
    """
    word = word.lower()
    word = word.strip(" !@#$%^&*()-_+={}[]|\\:;'<>?,./\"")
    return word in wordList

def randomWord(wordList):
    """
    Returns a random word.

    wordList: list of words
    returns: a word from wordList at random
    """
    return random.choice(wordList)

def randomString(wordList, n):
    """
    Returns a string containing n random words from wordList

    wordList: list of words
    returns: a string of random words separated by spaces.
    """
    return " ".join([randomWord(wordList) for _ in range(n)])

def randomScrambled(wordList, n):
    """
    Generates a test string by generating an n-word random string
    and encrypting it with a sequence of random shifts.

    wordList: list of words
    n: number of random words to generate and scamble
    returns: a scrambled string of n random words

    NOTE:
    This function will ONLY work once you have completed your
    implementation of applyShifts!
    """
    s = randomString(wordList, n) + " "
    shifts = [(i, random.randint(0, 25)) for i in range(len(s)) if s[i-1] == ' ']
    return applyShifts(s, shifts)[:-1]

def getStoryString():
    """
    Returns a story in encrypted text.
    """
    return open("story.txt", "r").read()

# (end of helper code)
# -----------------------------------

#
# Problem 1: Encryption
#
def buildCoder(shift):
    """
    Returns a dict that can apply a Caesar cipher to a letter.
    The cipher is defined by the shift value. Ignores non-letter characters
    like punctuation, numbers and spaces.

    shift: 0 <= int < 26
    returns: dict
    """
    ### TODO.
    codebook = {}
    alphabet = string.ascii_lowercase+string.ascii_uppercase
    for ltr in string.ascii_lowercase:
        codebook[ltr] = string.ascii_lowercase[(string.ascii_lowercase.index(ltr)+ shift) % 26]
    for ltr in string.ascii_uppercase:
        codebook[ltr] = string.ascii_uppercase[(string.ascii_uppercase.index(ltr)+ shift) % 26]
    return codebook

def applyCoder(text, coder):
    """
    Applies the coder to the text. Returns the encoded text.

    text: string
    coder: dict with mappings of characters to shifted characters
    returns: text after mapping coder chars to original text
    """
    ### TODO.
    cypher = ''
    for ltr in text:
        if ltr in coder.keys():
            cypher += coder[ltr]
        else:
            cypher += ltr
    return cypher

def applyShift(text, shift):
    """
    Given a text, returns a new text Caesar shifted by the given shift
    offset. Lower case letters should remain lower case, upper case
    letters should remain upper case, and all other punctuation should
    stay as it is.

    text: string to apply the shift to
    shift: amount to shift the text (0 <= int < 26)
    returns: text after being shifted by specified amount.
    """
    ### TODO.
    ### HINT: This is a wrapper function.
#    print shift, type(shift)
    codebook = buildCoder(shift)
#    print codebook
    return applyCoder(text,codebook)

#
# Problem 2: Decryption
#
def findBestShift(wordList, text):
    """
    Finds a shift key that can decrypt the encoded text.

    text: string
    returns: 0 <= int < 26
    """
    ### TODO
    max_words = -1
    best_shift = 0
    for shift in range(26):     # shift==0/26 could possibly be skipped
        cleartext = applyShift(text, shift)
        words = cleartext.split()   # split on whitespace
        num_words = 0
        #print words
        for word in words:
            alpha = ''  # get word without punctuation
            for c in word:
                if c in string.ascii_letters:
                    alpha += c
            if alpha.lower() in wordList:
                num_words += 1
                #print word, num_words
        #print shift, num_words
        if num_words > max_words:
            max_words = num_words
            best_shift = shift
    return best_shift

cypher = applyShift("Hello out there!",3)

    #return "Not yet implemented." # Remove this comment when you code the function

def decryptStory():
    """
    Using the methods you created in this problem set,
    decrypt the story given by the function getStoryString().
    Use the functions getStoryString and loadWords to get the
    raw data you need.

    returns: string - story in plain text
    """
    ### Answer - the key is 16
    ### Jack Florey is a mythical character created on the spur of a moment to help cover an insufficiently planned hack. He has been registered for classes at MIT twice before, but has reportedly never passed a class. It has been the tradition of the residents of East Campus to become Jack Florey for a few nights each year to educate incoming students in the ways, means, and ethics of hacking.
    wordList = loadWords()
    cypher_text = getStoryString();
    cypher_key = findBestShift(wordList,cypher_text)
    clear_text = applyShift(cypher_text,cypher_key)
    return clear_text

# Build data structures used for entire session and run encryption
#

if __name__ == '__main__':
    # To test findBestShift:
    wordList = loadWords()
    s = applyShift('Hello, world!', 8)
    bestShift = findBestShift(wordList, s)
    assert applyShift(s, bestShift) == 'Hello, world!'
    # To test decryptStory, comment the above four lines and uncomment this line:
    #    decryptStory()

print findBestShift(wordList,cypher)
print decryptStory()


text:
namespace content {

MediaInternals* MediaInternals::GetInstance() {
  return Singleton<MediaInternals>::get();
}

MediaInternals::~MediaInternals() {}

void MediaInternals::OnDeleteAudioStream(void* host, int stream_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  std::string stream = base::StringPrintf("audio_streams.%p:%d",
                                          host, stream_id);
  DeleteItem(stream);
}

void MediaInternals::OnSetAudioStreamPlaying(
    void* host, int stream_id, bool playing) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  UpdateAudioStream(host, stream_id,
                    "playing", new base::FundamentalValue(playing));
}

void MediaInternals::OnSetAudioStreamStatus(
    void* host, int stream_id, const std::string& status) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  UpdateAudioStream(host, stream_id,
                    "status", new base::StringValue(status));
}

void MediaInternals::OnSetAudioStreamVolume(
    void* host, int stream_id, double volume) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  UpdateAudioStream(host, stream_id,
                    "volume", new base::FundamentalValue(volume));
}

void MediaInternals::OnMediaEvents(
    int render_process_id, const std::vector<media::MediaLogEvent>& events) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  // Notify observers that |event| has occured.
  for (std::vector<media::MediaLogEvent>::const_iterator event = events.begin();
      event != events.end(); ++event) {
    base::DictionaryValue dict;
    dict.SetInteger("renderer", render_process_id);
    dict.SetInteger("player", event->id);
    dict.SetString("type", media::MediaLog::EventTypeToString(event->type));

    int64 ticks = event->time.ToInternalValue();
    double ticks_millis =
        ticks / static_cast<double>(base::Time::kMicrosecondsPerMillisecond);

    dict.SetDouble("ticksMillis", ticks_millis);
    dict.Set("params", event->params.DeepCopy());
    SendUpdate("media.onMediaEvent", &dict);
  }
}

void MediaInternals::AddUpdateCallback(const UpdateCallback& callback) {
  update_callbacks_.push_back(callback);
}

void MediaInternals::RemoveUpdateCallback(const UpdateCallback& callback) {
  for (size_t i = 0; i < update_callbacks_.size(); ++i) {
    if (update_callbacks_[i].Equals(callback)) {
      update_callbacks_.erase(update_callbacks_.begin() + i);
      return;
    }
  }
  NOTREACHED();
}

void MediaInternals::SendEverything() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  SendUpdate("media.onReceiveEverything", &data_);
}

MediaInternals::MediaInternals() {
}

void MediaInternals::UpdateAudioStream(void* host,
                                       int stream_id,
                                       const std::string& property,
                                       base::Value* value) {
  std::string stream = base::StringPrintf("audio_streams.%p:%d",
                                          host, stream_id);
  UpdateItem("media.addAudioStream", stream, property, value);
}

void MediaInternals::DeleteItem(const std::string& item) {
  data_.Remove(item, NULL);
  scoped_ptr<base::Value> value(new base::StringValue(item));
  SendUpdate("media.onItemDeleted", value.get());
}

void MediaInternals::UpdateItem(
    const std::string& update_fn, const std::string& id,
    const std::string& property, base::Value* value) {
  base::DictionaryValue* item_properties;
  if (!data_.GetDictionary(id, &item_properties)) {
    item_properties = new base::DictionaryValue();
    data_.Set(id, item_properties);
    item_properties->SetString("id", id);
  }
  item_properties->Set(property, value);
  SendUpdate(update_fn, item_properties);
}

void MediaInternals::SendUpdate(const std::string& function,
                                base::Value* value) {
  // Only bother serializing the update to JSON if someone is watching.
  if (update_callbacks_.empty())
    return;

  std::vector<const base::Value*> args;
  args.push_back(value);
  string16 update = WebUI::GetJavascriptCall(function, args);
  for (size_t i = 0; i < update_callbacks_.size(); i++)
    update_callbacks_[i].Run(update);
}

}  // namespace content

redpajama_set_name: RedPajamaGithub


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Sender ID"
            android:id="@+id/textView"
            android:layout_marginLeft="11dp"
            android:layout_marginTop="10dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"/>

    <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText"
            android:layout_alignTop="@+id/textView"
            android:layout_toRightOf="@+id/textView"
            android:layout_marginLeft="13dp"/>

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Location Callback"
            android:id="@+id/textView2"
            android:layout_below="@+id/editText"
            android:layout_alignLeft="@+id/textView"
            android:layout_marginTop="12dp"/>

    <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText2"
            android:layout_below="@+id/textView2"
            android:layout_alignLeft="@+id/textView2"/>

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:id="@+id/textView3"
            android:layout_centerVertical="true"
            android:layout_alignLeft="@+id/editText2"
            android:text="Pending"/>

    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Save"
            android:id="@+id/button"
            android:onClick="onSaveButtonClicked"
            android:layout_alignParentEnd="false"
            android:layout_alignParentBottom="true"
            android:layout_alignLeft="@+id/textView3"
            android:layout_marginBottom="14dp"/>

    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Start"
            android:id="@+id/button2"
            android:layout_alignTop="@+id/button"
            android:layout_toRightOf="@+id/textView"
            android:onClick="onStartButtonClicked"/>

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="RegID Callback"
            android:id="@+id/textView4"
            android:layout_below="@+id/editText2"
            android:layout_alignLeft="@+id/editText2"
            android:layout_marginTop="10dp"/>

    <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText3"
            android:layout_alignRight="@+id/editText"
            android:layout_below="@+id/textView4"
            android:layout_alignLeft="@+id/textView3"/>

    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Stop"
            android:id="@+id/button3"
            android:layout_marginLeft="15dp"
            android:layout_alignTop="@+id/button2"
            android:layout_toRightOf="@+id/textView2"
            android:onClick="onStopButtonClicked"/>
</RelativeLayout>


text:
"""
Sprite Change Coins

This shows how you can change a sprite once it is hit, rather than eliminate it.

Artwork from http://kenney.nl
"""
import random
import arcade

SPRITE_SCALING = 1

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

class Collectable(arcade.Sprite):
    """ This class represents something the player collects. """
    def __init__(self, filename, scale):
        super().__init__(filename, scale)
        # Flip this once the coing has been collected.
        self.changed = False

class MyApplication(arcade.Window):
    """
    Main application class.a
    """

    def __init__(self, width, height):
        """
        Initializer
        :param width:
        :param height:
        """
        super().__init__(width, height)
        # Sprite lists
        self.all_sprites_list = None
        self.coin_list = None

        # Set up the player
        self.score = 0
        self.player_sprite = None

    def setup(self):
        """ Set up the game and initialize the variables. """

        # Sprite lists
        self.all_sprites_list = arcade.SpriteList()
        self.coin_list = arcade.SpriteList()

        # Set up the player
        self.score = 0
        self.player_sprite = arcade.Sprite("images/character.png", 0.5)
        self.player_sprite.center_x = 50
        self.player_sprite.center_y = 50
        self.all_sprites_list.append(self.player_sprite)

        for i in range(50):

            # Create the coin instance
            coin = Collectable("images/coin_01.png", SPRITE_SCALING)
            coin.width = 30
            coin.height = 30

            # Position the coin
            coin.center_x = random.randrange(SCREEN_WIDTH)
            coin.center_y = random.randrange(SCREEN_HEIGHT)

            # Add the coin to the lists
            self.all_sprites_list.append(coin)
            self.coin_list.append(coin)

        # Don't show the mouse cursor
        self.set_mouse_visible(False)

        # Set the background color
        arcade.set_background_color(arcade.color.AMAZON)

    def on_draw(self):
        """
        Render the screen.
        """

        # This command has to happen before we start drawing
        arcade.start_render()

        # Draw all the sprites.
        self.all_sprites_list.draw()

        # Put the text on the screen.
        output = "Score: {}".format(self.score)
        arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)

    def on_mouse_motion(self, x, y, dx, dy):
        """
        Called whenever the mouse moves.
        """
        self.player_sprite.center_x = x
        self.player_sprite.center_y = y

    def animate(self, delta_time):
        """ Movement and game logic """

        # Call update on all sprites (The sprites don't do much in this
        # example though.)
        self.all_sprites_list.update()

        # Generate a list of all sprites that collided with the player.
        hit_list = \
            arcade.check_for_collision_with_list(self.player_sprite,
                                                 self.coin_list)

        # Loop through each colliding sprite, change it, and add to the score.
        for coin in hit_list:
            # Have we collected this?
            if not coin.changed:
                # No? Then do so
                coin.texture = arcade.load_texture("images/bumper.png")
                coin.changed = True
                coin.width = 30
                coin.height = 30
                self.score += 1

window = MyApplication(SCREEN_WIDTH, SCREEN_HEIGHT)
window.setup()

arcade.run()


text:
'use strict';

const path 					=	require('path');
const fs 						= require('fs');

const chalk         = require('chalk');
const Promise 			= require('bluebird');
const SilentError 	= require('silent-error');

const Oss 					= require('restore-oss-client');
const Command       = require('../../models/command');
const confirm       = require('../../utilities/confirm');
const debug 				= require('debug')('rstc:commands/oss/job')

// Sub-command of Oss.
module.exports = Command.extend({
	name: 'job',
	description: 'Start a job.',
	works: 'everywhere',

	availableOptions: [
    { name: 'diff-base',    type: String,		default: 'md5', aliases: ['db'], 	      description: 'The base to compare the local and remote objects.' 	    },
		{ name: 'diff-compare',	type: Boolean,	default: false, aliases: ['diff, dc'],  description: 'Resolve differences between the local and remote object.'}
	],

	anonymousOptions: [
    '<job-file>'
  ],

	run: function(commandOptions, rawArgs) {
		debug('commandOptions: %o', commandOptions)
		debug('rawArgs: ', rawArgs);

		if(!this.superCommand.oss) {
			const message = 'System error: Either a Object Storage Service Client was not' +
											' succesfully created in command "' + this.superCommand.name +
											'" or it wasn\'t passed down to command "' + this.name + '".';
			throw Error(message);
		}

		const jobFile = rawArgs.shift();
		if(!jobFile) {
			this.printBasicHelp();
			const message = 'A path to a job file must be given.';
			return Promise.reject(new SilentError(message));
		}

    let job;
		try {
      job = JSON.parse(fs.readFileSync(jobFile, 'utf-8'));
		} catch(e) {
			const message = 'Invalid JSON in job file:\n' + e;
			return Promise.reject(new SilentError(message));
		}

    if(!job.options) {
			job.options = {};
      debug('Job doesn\'t have any options specified.');
		}

    if(!job.options.base) {
      job.options.base = process.cwd();
      const message = 'No \'base\' directory set in job file.' +
                      ' Using current working project\'s directory (\'' +
                      job.options.base + '\').';
      console.log(chalk.cyan(message));
    }

    let options = {
      oss: this.superCommand.oss,
      diff: commandOptions.diffCompare ? true : false,
      diffCb: commandOptions.diffCompare ? confirm.jobUploads : false,
      diffBase: commandOptions.diffBase
    };

		const ossJobProcessor = Oss.ossProc(options);

    job.options.processor = ossJobProcessor;

    commandOptions.jobProcessor = Oss.jobproc(job);

		const Task = this.availableTasks.Job;
		const task = new Task({
      cli: this.cli,
			ui: this.ui
		});

		return task.run(commandOptions);
	}
});


text:
package com.example.android.popularmovies.app;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.android.popularmovies.app.MoviesContract.MovieEntry;
import com.example.android.popularmovies.app.MoviesContract.TrailerEntry;
import com.example.android.popularmovies.app.MoviesContract.ReviewEntry;

public class MoviesDbHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 4;

    static final String DATABASE_NAME = "movie.db";

    public MoviesDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        final String SQL_CREATE_MOVIE_TABLE = "CREATE TABLE " + MovieEntry.TABLE_NAME + " (" +

                MovieEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +

                MovieEntry.COLUMN_POSTER_PATH + " TEXT, " +
                MovieEntry.COLUMN_ADULT + " INTEGER, " +
                MovieEntry.COLUMN_OVERVIEW + " TEXT, " +
                MovieEntry.COLUMN_RELEASE_DATE + " TEXT, " +
                MovieEntry.COLUMN_MOVIE_ID + " INTEGER UNIQUE NOT NULL, " +
                MovieEntry.COLUMN_ORIGINAL_TITLE + " TEXT, " +
                MovieEntry.COLUMN_ORIGINAL_LANGUAGE + " TEXT, " +
                MovieEntry.COLUMN_TITLE + " TEXT, " +
                MovieEntry.COLUMN_BACKDROP_PATH + " TEXT, " +
                MovieEntry.COLUMN_POPULARITY + " REAL, " +
                MovieEntry.COLUMN_VOTE_COUNT + " INTEGER, " +
                MovieEntry.COLUMN_VIDEO + " INTEGER, " +
                MovieEntry.COLUMN_VOTE_AVERAGE + " REAL , " +
                MovieEntry.COLUMN_GENRE_IDS + " TEXT, " +
                MovieEntry.COLUMN_FAVORITE + " INTEGER, " +
                MovieEntry.COLUMN_WATCHED + " INTEGER, " +
                MovieEntry.COLUMN_WATCH_ME + " INTEGER, " +
                MovieEntry.COLUMN_POSTER_BITMAP + " BLOB, " +

                // Should only be one entry for this movie
                " UNIQUE (" + MovieEntry.COLUMN_MOVIE_ID  + ") ON CONFLICT REPLACE);";

        final String SQL_CREATE_TRAILER_TABLE = "CREATE TABLE " + TrailerEntry.TABLE_NAME + " (" +

                TrailerEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +

                TrailerEntry.COLUMN_MOVIE_ID + " INTEGER NOT NULL , " +
                TrailerEntry.COLUMN_NAME + " TEXT , " +
                TrailerEntry.COLUMN_SIZE + " TEXT , " +
                TrailerEntry.COLUMN_SOURCE + " TEXT NOT NULL , " +
                TrailerEntry.COLUMN_TYPE + " TEXT  , " +

                " FOREIGN KEY (" + TrailerEntry.COLUMN_MOVIE_ID + ") REFERENCES " +
                MovieEntry.TABLE_NAME + " (" + MovieEntry.COLUMN_MOVIE_ID + "), " +

                // Should only be one entry for this movie with this trailer source
                " UNIQUE (" + TrailerEntry.COLUMN_MOVIE_ID + ", " +
                TrailerEntry.COLUMN_SOURCE + ") ON CONFLICT REPLACE);";

        final String SQL_CREATE_REVIEW_TABLE = "CREATE TABLE " + ReviewEntry.TABLE_NAME + " (" +

                ReviewEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +

                ReviewEntry.COLUMN_MOVIE_ID + " INTEGER NOT NULL , " +
                ReviewEntry.COLUMN_REVIEW_ID + " TEXT NOT NULL , " +
                ReviewEntry.COLUMN_AUTHOR + " TEXT , " +
                ReviewEntry.COLUMN_CONTENT + " TEXT NOT NULL , " +
                ReviewEntry.COLUMN_URL + " TEXT , " +

                " FOREIGN KEY (" + ReviewEntry.COLUMN_MOVIE_ID + ") REFERENCES " +
                MovieEntry.TABLE_NAME + " (" + MovieEntry.COLUMN_MOVIE_ID + "), " +

                // Should only be one entry for this movie with this review ID
                " UNIQUE (" + ReviewEntry.COLUMN_MOVIE_ID + ", " +
                ReviewEntry.COLUMN_REVIEW_ID + ") ON CONFLICT REPLACE);";

        sqLiteDatabase.execSQL(SQL_CREATE_MOVIE_TABLE);
        sqLiteDatabase.execSQL(SQL_CREATE_TRAILER_TABLE);
        sqLiteDatabase.execSQL(SQL_CREATE_REVIEW_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {

        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + ReviewEntry.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TrailerEntry.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + MovieEntry.TABLE_NAME);
        onCreate(sqLiteDatabase);
    }
}


text:
"""This program generates Snippet Status Reports.

The program calls the Google Ad-Exchange Buyer API, and generates
Snippet Status Reports in txt, pb, and csv format.

  Usage:

  python generate_ssr.py

Output files are SnippetStatusReport.txt, SnippetStatusReport.pb,
and SnippetStatusReport.csv
"""

import argparse
import contextlib
import csv
import StringIO
import sys

from apiclient import sample_tools
from oauth2client import client

from third_party.protobuf_json import protobuf_json
import snippet_status_report_pb2

import google.protobuf.descriptor as descriptor
import google.protobuf.text_format as text_format

RICH_MEDIA_CAPABILITY_SSL = 47
INVALID_SSL_DECLARATION = u'INVALID_SSL_DECLARATION'
SSL_ATTRIBUTE = u'SSL_ATTRIBUTE'
FLASHLESS_ATTRIBUTE = u'FLASHLESS_ATTRIBUTE'

KEY_TRANSLATION = {
    u'advertiserId': u'advertiser_id',
    u'buyerCreativeId': u'buyer_creative_id',
    u'clickThroughUrl': u'click_through_url',
    u'corrections': u'snippet_correction',
    u'corrections.details': u'detail',
    u'corrections.reason': u'type',
    u'disapprovalReasons': u'disapproval_reason',
    u'disapprovalReasons.details': u'detail',
    u'disapprovalReasons.reason': u'reason',
    u'filteringReasons': u'snippet_filtering',
    u'filteringReasons.date': u'date',
    u'filteringReasons.reasons': u'item',
    u'filteringReasons.reasons.filteringCount': u'filtering_count',
    u'filteringReasons.reasons.filteringStatus': u'filtering_status',
    u'height': u'height',
    u'productCategories': u'detected_product_category',
    u'sensitiveCategories': u'detected_sensitive_category',
    u'status': u'status',
    u'width': u'width'}

# Declare command-line flags.
argparser = argparse.ArgumentParser(add_help=False)

def _ReplaceKey(dictionary, old_key, new_key):
  if old_key in dictionary:
    dictionary[new_key] = dictionary.pop(old_key)

def _ReplaceJSONFields(json, translation, prefix):
  """Traverses JSON hierarchy, renaming keys indicated by translation table.

  Args:
    json: JSON data to modify.
    translation: Table of key translations for JSON.
    prefix: String representing current position in JSON hierarchy.
  """
  if type(json) is list:
    for item in json:
      _ReplaceJSONFields(item, translation, prefix)
  elif type(json) is dict:
    for field_name in json:
      full_key = prefix + field_name
      if full_key in translation:
        new_key = translation[full_key]
        _ReplaceKey(json, field_name, new_key)
        _ReplaceJSONFields(json[new_key], translation, full_key + '.')

def _RemoveFlashlessAttributeCorrection(item):
  """Remove FLASHLESS_ATTRIBUTE if it's one of the correction reasons.

  This correction reason is not exposed in the protobol buffer, and therefore
  it needs to be removed
  Args:
    item: snippet status item to process
  """
  for snippet_correction in item.get('snippet_correction', []):
    if snippet_correction.get('type', None) == FLASHLESS_ATTRIBUTE:
      item['snippet_correction'].remove(snippet_correction)

def _IsSSLCapable(item):
  """Checkes whether a Snippet Status Item is SSL Capable.

  Args:
    item: a dictionary that represents one Snippet Status Item
  Returns:
    True if 1. RICH_MEDIA_CAPABILITY_SSL is declared in the attribute
            2. The snippet is not disapproved for INVALID_SSL_DECLARATION
            3. The snippet is not corrected for SSL_ATTRIBUTE
    False otherwise
  """
  if RICH_MEDIA_CAPABILITY_SSL not in item.get('attribute', []):
    return False
  for disapproval_reason in item.get('disapproval_reason', []):
    if disapproval_reason.get('reason', None) == INVALID_SSL_DECLARATION:
      return False
  for snippet_correction in item.get('snippet_correction', []):
    if snippet_correction.get('type', None) == SSL_ATTRIBUTE:
      return False
  return True

def GenerateSnippetStatusReportPBObject(response):
  """Generates Snippet Status Reports as a Protocol Buffer object.

  Args:
    response: A dictionary containing response from the creative.list API
        call
  Returns:
    a Snippet Status Report Protocol Buffer Object
  """
  report = snippet_status_report_pb2.SnippetStatusReport()

  # Convert the report to a protocol buffer
  for item in response['items']:
    snippet_status = report.snippet_status.add()
    _ReplaceJSONFields(item, KEY_TRANSLATION, '')
    translated_item = item.copy()  # Make a copy so we can keep the original
    _RemoveFlashlessAttributeCorrection(item)
    protobuf_json.json2pb(snippet_status, translated_item, True)

    # Fill in fields that are not directly read from the response:
    snippet_status.source = snippet_status_report_pb2.SnippetStatusItem.RTB
    snippet_status.is_ssl_capable = _IsSSLCapable(translated_item)

  return report

def WriteSnippetStatusReportInCSV(report, report_csv):
  """Write the Snippet Status Report in csv format in the output stream.

  Args:
    report: Snippet Status Report as a protobol buffer object
    report_csv: output stream to write to
  """
  if not report_csv:
    return

  writer = csv.writer(report_csv)
  fields = snippet_status_report_pb2.SnippetStatusItem.DESCRIPTOR.fields
  active_fields = [field for field in fields
                   if not field.name.startswith('DEPRECATED_')]

  header_row = [field.name for field in active_fields]
  writer.writerow(header_row)

  def FieldSingletonAsString(field, value):
    """Generates string value for a field singleton."""
    with contextlib.closing(StringIO.StringIO()) as buf:
      text_format.PrintFieldValue(field, value, buf, as_one_line=True)
      return buf.getvalue()

  def FieldAsString(field, value):
    """Generates string value for a field.  Handles repeated fields."""
    if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
      items = [FieldSingletonAsString(field, item) for item in value]
      return '[%s]' % (';'.join(items))
    else:
      return FieldSingletonAsString(field, value)

  def SnippetStatusColumns(snippet_status):
    """Generates columns for a snippet status row."""
    for field in active_fields:
      yield FieldAsString(field, getattr(snippet_status, field.name, None))

  for snippet_status in report.snippet_status:
    columns = list(SnippetStatusColumns(snippet_status))
    writer.writerow(columns)

def main(argv):
  # Authenticate and construct service.
  service, _ = sample_tools.init(
      argv, 'adexchangebuyer', 'v1.3', __doc__, __file__, parents=[argparser],
      scope='https://www.googleapis.com/auth/adexchange.buyer')

  try:
    # Construct a list request.
    request = service.creatives().list()
    # Execute the request and store the response.
    response = request.execute()
  except client.AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')

  # Generate a Snippet Status Report Protocol buffer object
  report = GenerateSnippetStatusReportPBObject(response)

  # Write the report to files in txt, pb and csv format
  with open('SnippetStatusReport.txt', 'w') as report_txt:
    text_format.PrintMessage(report, report_txt)
  with open('SnippetStatusReport.pb', 'wb') as report_pb:
    report_pb.write(report.SerializeToString())
  with open('SnippetStatusReport.csv', 'w') as report_csv:
    WriteSnippetStatusReportInCSV(report, report_csv)

if __name__ == '__main__':
  main(sys.argv)


text:
author: chipoglesby
comments: true
date: 2006-02-12 19:04:00+00:00
layout: post
slug: charleston-day-iii
title: Charleston Day III
wordpress_id: 20
categories:
- Photojournalism
tags:
- Charleston
---

Today was my final day in Charleston and the end of the SCNPA seminar.  We had three great speakers who gave me a lot of insight about what the future holds for photographers and about what we can look foward to doing.  I went and drove around for a while afterwards snapping pictures.  Enjoy.[![](http://photos1.blogger.com/blogger/3124/2183/400/charleston2.jpg)](http://photos1.blogger.com/blogger/3124/2183/1600/charleston2.jpg)
[![](http://photos1.blogger.com/blogger/3124/2183/400/charleston3.jpg)](http://photos1.blogger.com/blogger/3124/2183/1600/charleston3.jpg)
[![](http://photos1.blogger.com/blogger/3124/2183/400/charleston1.jpg)](http://photos1.blogger.com/blogger/3124/2183/1600/charleston1.jpg)


text:
cask 'safari-technology-preview' do
  if MacOS.version <= :mojave
    version '103,061-90754-20200325-37467264-9c34-454c-be4a-1cb87e93c62c'
    sha256 'f2175a2ca69152b6c1067d47b56d464b0ba0c71323a76137b488a8088a25f44c'
  else
    version '103,061-90752-20200325-cc5192c4-619a-45b4-83b5-70a1bed8c912'
    sha256 '846f2c9e7ebcc293f01ea36c8e1184e2d1bfb985eb3a590fc7c730c40e10a4b6'
  end

  url "https://secure-appldnld.apple.com/STP/#{version.after_comma}/SafariTechnologyPreview.dmg"
  appcast 'https://developer.apple.com/safari/download/'
  name 'Safari Technology Preview'
  homepage 'https://developer.apple.com/safari/download/'

  auto_updates true
  depends_on macos: '>= :mojave'

  pkg 'Safari Technology Preview.pkg'

  uninstall delete: '/Applications/Safari Technology Preview.app'

  zap trash: [
               '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.apple.safaritechnologypreview.sfl*',
               '~/Library/Caches/com.apple.SafariTechnologyPreview',
               '~/Library/Preferences/com.apple.SafariTechnologyPreview.plist',
               '~/Library/SafariTechnologyPreview',
               '~/Library/Saved Application State/com.apple.SafariTechnologyPreview.savedState',
               '~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview-com.apple.Safari.UserRequests.plist',
               '~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview-com.apple.Safari.WebFeedSubscriptions.plist',
               '~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview.plist',
               '~/Library/WebKit/com.apple.SafariTechnologyPreview',
             ]
end


text:
Google Checkout
==================

### Installation

1. Run `script/extension install git://github.com/romul/spree-google-checkout.git`
1. Run `db:migrate`
1. Create seller account in Google Checkout
1. Open `https://sandbox.google.com/checkout/sell/settings?section=Integration`
or `https://checkout.google.com/sell/settings?section=Integration`
1. remember your merchant ID and merchant key
1. set 'API callback URL' to `http://your.spree.site/google_checkout_notification`
1. select 'Notification as XML'
1. Create a billing integration using `http://your.spree.site/admin/billing_configurations` and set the merchant ID, etc.

### Usage

* After filling your gateway settings, users can place order through Google Checkout.
* After placing order through Google Checkout, you can charge it or cancel it from Spree admin-panel.


text:
package br.gov.siscomex.portalunico.duimp_api.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import com.fasterxml.jackson.annotation.JsonProperty;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@XmlAccessorType(XmlAccessType.FIELD)
 @XmlType(name = "SeguroConsultaItemCover", propOrder =
    { "valorBRL"
})

@XmlRootElement(name="SeguroConsultaItemCover")
/**
  * Valor do seguro.
 **/
@ApiModel(description="Valor do seguro.")
public class SeguroConsultaItemCover  {

  @XmlElement(name="valorBRL")
  @ApiModelProperty(example = "12.4", value = "Valor do seguro em R$ (Reais).
Tamanho: 16,7
Formato: Decimal, com até 7 casas decimais separadas por ponto.")
 /**
   * Valor do seguro em R$ (Reais).
Tamanho: 16,7
Formato: Decimal, com até 7 casas decimais separadas por ponto.
  **/
  private Double valorBRL = null;
 /**
   * Valor do seguro em R$ (Reais).<br>Tamanho: 16,7<br>Formato: Decimal, com até 7 casas decimais separadas por ponto.
   * @return valorBRL
  **/
  @JsonProperty("valorBRL")
  public Double getValorBRL() {
    return valorBRL;
  }

  public void setValorBRL(Double valorBRL) {
    this.valorBRL = valorBRL;
  }

  public SeguroConsultaItemCover valorBRL(Double valorBRL) {
    this.valorBRL = valorBRL;
    return this;
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class SeguroConsultaItemCover {\n");

    sb.append("    valorBRL: ").append(toIndentedString(valorBRL)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private static String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
function model=flux_ratio(model,top_rx,bottom_rx,top_dir,bottom_dir,ratio)

%written by the Senger Research Group, 7/21/2012, last updated 9/26/2012

%this function constrains flux ratios based on the concept that multiple
%enzymes are competing for the same limited metabolite.

%the flux ratio is constrained for a specified (top) reaction over all
%competing reactions.

%example: A -> B (rxn1)
%         A -> C (rxn2)

%define the ratio based on rxn1 (e.g., ensure half of the total flux goes through rxn1):

%flux(rxn1)/[flux(rxn1 + flux(rxn2)] = 0.5

%note the reaction in the numerator of the ratio must also appear in the
%denominator

%Inputs:
%model: a cobra-style model
%top_rxn: the numerical index in the "rxns" variable of the reaction in the
%numerator of the ratio -- example: 12
%bottom_rx: a row vector of all indices of reactions in the denominator --
%example: [10 54 67]
%top_dir: 1 = top_rxn is written in the forward direction; -1 = written in
%the reverse direction -- example: 1
%bottom_dir: row vector of 1 or -1 values specifying the direction for each
%reaction in the bottom_rx vector -- example: [1 -1 -1]
%ratio: the numerical value of the flux ratio as defined above -- example:
%0.5

%Outputs:
%model: cobra-style model with added flux ratio constraint

%check if inputs are sized correctly
if size(top_rx) ~= size(top_dir)
    fprintf(['Error. The top reaction and direction do not agree.' '\n']);
    return
end

if size(bottom_rx) ~= size(bottom_dir)
    fprintf(['Error. The bottom reactions and directions do not agree.' '\n']);
    return
end

%check that the top reaction is also in the bottom reaction list
a=ismember(top_rx,bottom_rx);
for i=1:size(a,2)
    if a(1,i)==0
        fprintf(['Error. The top reaction must also appear in the bottom reaction vector.' '\n']);
        return
    end
end

%add new constraint row to stoichiometric matrix
new_row=size(model.S,1)+1;
model.S(new_row,:)=zeros(1,size(model.S,2));

%modify the row to constrain the flux ratio
for i=1:size(top_rx,2)
    model.S(new_row,top_rx(1,i))=top_dir(1,i).*(1-ratio);
end

for i=1:size(bottom_rx,2)
    if ismember(bottom_rx(1,i),top_rx)==0
        model.S(new_row,bottom_rx(1,i))=-1.*bottom_dir(1,i).*ratio;
    end
end

%add information to the metabolite fields
model.mets{new_row}=['ratio_' model.rxns{top_rx} ':' model.rxns{bottom_rx}];
model.metNames{new_row}=['ratio_' model.rxns{top_rx} ':' model.rxns{bottom_rx}];

%updating additional fields - different models contain different fields
%(this handles them all)
fnames=fieldnames(model);

%S and mets are already processed - remove them from the existing list
fnames(strmatch('mets',fnames,'exact'),:)=[];
fnames(strmatch('S',fnames,'exact'),:)=[];

for i=1:size(fnames,1)

    fget=getfield(model,fnames{i,1});

    if iscell(fget)==1

        if size(fget,1)==new_row-1
            fget{new_row,1}='';
        end

    end

    if isnumeric(fget)==1

        if size(fget,1)==new_row-1
            fget(new_row,1)=0;
        end
    end

    model=setfield(model,fnames{i,1},fget);

end

end


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class NetDhcpConfigInfoDhcpOptions extends DynamicData {
  public boolean enable;
  public KeyValue[] config;

  public boolean isEnable() {
    return this.enable;
  }

  public KeyValue[] getConfig() {
    return this.config;
  }

  public void setEnable(boolean enable) {
    this.enable=enable;
  }

  public void setConfig(KeyValue[] config) {
    this.config=config;
  }
}


text:
'use strict';
const test_desc = 'Request for absent characteristics. Reject with ' +
    'NotFoundError.';
const expected =
    new DOMException('No Characteristics found in service.', 'NotFoundError');

bluetooth_test(async () => {
  let {service} = await getEmptyHealthThermometerService();
  return assert_promise_rejects_with_message(
      service.getCharacteristics(), expected);
}, test_desc);


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.reactor</groupId>
        <artifactId>reactor-lib</artifactId>
        <version>0.0.1</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>reactor-transport-elastic-push</artifactId>

    <properties>
        <es.version>1.3.2</es.version>
        <quartz.version>2.2.1</quartz.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.reactor</groupId>
            <artifactId>reactor-api</artifactId>
        </dependency>

        <dependency>
            <groupId>org.reactor</groupId>
            <artifactId>reactor-renderer-json</artifactId>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>${es.version}</version>
        </dependency>

        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>${quartz.version}</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.easytesting</groupId>
            <artifactId>fest-assert</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>


text:
package org.i3xx.util.ctree.impl;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

import org.i3xx.util.ctree.IConfNode;
import org.i3xx.util.ctree.parser.AbstractReader;
import org.i3xx.util.ctree.parser.AbstractRule;
import org.i3xx.util.ctree.parser.IParserWrapper;
import org.i3xx.util.ctree.parser.KeyValueRuleComment;
import org.i3xx.util.ctree.parser.KeyValueRuleEmptyLine;
import org.i3xx.util.ctree.parser.KeyValueRuleIncludeA;
import org.i3xx.util.ctree.parser.KeyValueRuleProcessLine;
import org.i3xx.util.ctree.parser.LineReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The default parser parses the configuration files into the configuration tree.
 *
 * How to read the configuration:
 * - DefaultParser.process()
 * - DefaultParser.process(LineReader reader) <-------
 *     //LineReader family                            |  The recursive circle
 *   - String line = AbstractLineReader.readNext()    |  to load all files.
 *     - KeyValueRuleIncludeA.exec(line)              |  KeyValueIncludeA got
 *         //LineReader family                        |  a link to this.
 *       - AbstractLineReader.readNext() -------------
 *
 * @author Stefan
 *
 */
public class DefaultParser implements IParserWrapper {

	private static final Logger logger = LoggerFactory.getLogger(DefaultParser.class);

	private File file;
	private AbstractRule[] inputRules;

	/**
	 * Parses the parameter file and builds the configuration
	 *
	 * @param fileName The file to parse
	 * @throws IOException
	 */
	public DefaultParser(String fileName) throws IOException {
		this(new File(fileName));
	}

	/**
	 * Parses the parameter file and builds the configuration
	 *
	 * @param file The file to parse
	 * @throws IOException
	 */
	public DefaultParser(File file) throws IOException {
		this.file = file;
		this.inputRules = null;
	}

	/**
	 * Set the rules
	 * @param root The root node
	 */
	public void setRules(IConfNode root) {

		inputRules = new AbstractRule[4];

		inputRules[0] = new KeyValueRuleIncludeA(this);
		inputRules[1] = new KeyValueRuleComment();
		inputRules[2] = new KeyValueRuleEmptyLine();
		inputRules[3] = new KeyValueRuleProcessLine(root, new LinkableResolverFactory());
	}

	/**
	 * Process the input
	 *
	 * @throws IOException
	 */
	public void process() throws IOException {
		logger.trace("Process file: '{}'.", file.toString());
		LineReader reader = new LineReader( new FileReader(file));
		reader.setParams(new HashMap<String, String>());
		reader.getParams().put("filename", file.getAbsolutePath());
		reader.getParams().put("mimetype", "text/plain");
		reader.getParams().put("datatype", "line");
		process( reader );
		reader.close();
	}

	/* (non-Javadoc)
	 * @see com.i3xx.util.ctree.parser.IParserWrapper#process(com.i3xx.util.ctree.parser.AbstractReader)
	 */
	public void process(AbstractReader current) throws IOException {

		//
		//Println.console("[CONF] Read file '"+
		//		(current.getParams()!=null && current.getParams().get("filename")!=null ?
		//				current.getParams().get("filename") : "-")+"'");
		//

		while(current.available()) {
			String data = current.readNext();

			//
			// The whole configuration can be accessed here
			//

			String mime = current.getParams().get("mimetype");
			if( mime!=null && ( mime.equals("text/xml") || mime.equals("application/json") ) ){
				data = Protector.escape(data);

				//usually this is not necessary - but useful to get into the process how-to
				logger.trace("Escape data: '{}', type: {}.", data, mime);
			}
			data = Protector.wrap(data);

			//usually this is not necessary - but useful to get into the process how-to
			logger.debug("Process data: '{}', type: {}.", data, mime);

			//
			// Run the rules to every line
			//
			for(int i=0;i<inputRules.length;i++){
				if(inputRules[i].match(data, current.getParams())){
					inputRules[i].exec(data, current.getParams());
					break;
				}
			}//for
		}//while
	}
}


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

namespace NBitcoin.BitcoinCore
{
	public class CoinsView
	{
		public CoinsView(NoSqlRepository index)
		{
			if(index == null)
				throw new ArgumentNullException("index");
			_Index = index;
		}

		public CoinsView()
			: this(new InMemoryNoSqlRepository())
		{

		}
		private readonly NoSqlRepository _Index;
		public NoSqlRepository Index
		{
			get
			{
				return _Index;
			}
		}

		public Coins GetCoins(uint256 txId)
		{
			try
			{
				return Index.GetAsync<Coins>(txId.ToString()).Result;
			}
			catch(AggregateException aex)
			{
				ExceptionDispatchInfo.Capture(aex.InnerException).Throw();
				return null; //Can't happen
			}
		}

		public Task<Coins> GetCoinsAsync(uint256 txId)
		{
			return Index.GetAsync<Coins>(txId.ToString());
		}

		public void SetCoins(uint256 txId, Coins coins)
		{
			Index.PutAsync(txId.ToString(), coins);
		}

		public bool HaveCoins(uint256 txId)
		{
			return GetCoins(txId) != null;
		}

		public uint256 GetBestBlock()
		{
			try
			{
				return GetBestBlockAsync().Result;
			}
			catch(AggregateException aex)
			{
				ExceptionDispatchInfo.Capture(aex.InnerException).Throw();
				return null; //Can't happen
			}
		}
		public async Task<uint256> GetBestBlockAsync()
		{
			var block = await Index.GetAsync<uint256.MutableUint256>("B").ConfigureAwait(false);
			return block == null ? uint256.Zero : block.Value;
		}

		public void SetBestBlock(uint256 blockId)
		{
			Index.PutAsync("B", blockId.AsBitcoinSerializable());
		}

		public bool HaveInputs(Transaction tx)
		{
			if(!tx.IsCoinBase)
			{
				// first check whether information about the prevout hash is available
				foreach(var input in tx.Inputs)
				{
					OutPoint prevout = input.PrevOut;
					if(!HaveCoins(prevout.Hash))
						return false;
				}

				// then check whether the actual outputs are available
				foreach(var input in tx.Inputs)
				{
					OutPoint prevout = input.PrevOut;
					Coins coins = GetCoins(prevout.Hash);
					if(!coins.IsAvailable(prevout.N))
						return false;
				}
			}
			return true;
		}

		public TxOut GetOutputFor(TxIn input)
		{
			Coins coins = GetCoins(input.PrevOut.Hash);
			if(!coins.IsAvailable(input.PrevOut.N))
			{
				return null;
			}
			return coins.Outputs[(int)input.PrevOut.N];
		}

		public Money GetValueIn(Transaction tx)
		{
			if(tx.IsCoinBase)
				return 0;
			return tx.Inputs.Select(i => GetOutputFor(i).Value).Sum();
		}

		public CoinsView CreateCached()
		{
			return new CoinsView(new CachedNoSqlRepository(Index));
		}

		public void AddTransaction(Transaction tx, int height)
		{
			SetCoins(tx.GetHash(), new Coins(tx, height));
		}
	}
}


text:
[ ![Download](https://api.bintray.com/packages/aritraroy/maven/kerning-views/images/download.svg) ](https://bintray.com/aritraroy/maven/kerning-views/_latestVersion) [![API](https://img.shields.io/badge/API-14%2B-orange.svg?style=flat)](https://android-arsenal.com/api?level=14) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-KerningViews-green.svg?style=true)](https://android-arsenal.com/details/1/3662)

![KerningViews](https://raw.githubusercontent.com/aritraroy/KerningViews/master/images/kerning.png)

KerningViews provides a set of views (currently only `TextView` and `Button`) which lets you adjust the spacing between the characters in the text of that view also know as **Kerning**.

Kerning is a common feature in design apps like Photoshop or Sketch, but Android natively doesn't allow Kerning. From API level 21, Android allows you to do this using ```setLetterSpacing``` attribute , but there is no way to achieve this in pre-21 devices.

KerningViews provides a simple API to achieve this feature in `TextView` and `Button` text across all API levels in Android.

# Screenshot
This screenshot is from the sample app showing different text with different spacing (kerning factor).
![Screenshot](https://raw.githubusercontent.com/aritraroy/KerningViews/master/images/screenshot.png)

# Download

This library is available in jCenter which is the default Maven repository used in Android Studio.

```groovy
dependencies {
    // other dependencies here
    implementation 'com.andrognito.kerningview:kerningview:x.y.z'
}
```

# Usage
You should see the sample app for complete usage details. You can either use these views and set the attribute via XML or programmatically change the kerning factor as required.

### XML

Just use the  ```KerningTextView ``` or  ```KerningButton ``` in your XML layouts. If you do not put the  ```kv_spacing ``` attribute then it will behave as a normal TextView with no letter spacing.

You can customize the letter spacing by using the ```kv_spacing ``` attribute with different kerning factor (supports floating point values).

 ```java
<com.andrognito.kerningview.KerningTextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif"
        android:text="@string/sample_text_1"
        android:textSize="@dimen/text_size_xlarge"
        app:kv_spacing="10" />
 ```

### JAVA

Just reference the views from your layout and use the setter to change the letter spacing of the texts.

 ```java
KerningTextView mText = (KerningTextView) findViewById(R.id.text);
mText.setKerningFactor(3.5f);
```

# Contribution

This is a very simple and tiny library that solves one simple use case.But I would love to accept contributions to improve or add functionality to it. It is my first library too.

# About The Author

### Aritra Roy

Design-focussed Engineer. Full-stack Developer. Hardcore Android Geek. UI/UX Designer. Part-time Blogger.

# License

```
Copyright 2016 aritraroy

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```


text:
%% Module for visualizing optimal frustrum sizes

% A "bowl" is an inverted frustrum.
% r1 is the top of the frustrum (i.e., the BOTTOM of the bowl)
% r2 is the base of the frustrum (i.e., the TOP of the bowl)
clear ; close all; clc

%% Settings

% Step size in the plot
step_size = 1/10;
% Bounds of the critical ratio
min_crit_ratio = 0;
max_crit_ratio = 5;

% Resolution of the angles in the plot
angle_res = 1;
% Minimum exterior bowl angle
min_degrees = 5;

%% Graph variables
[crit_ratio, exterior_angle] = meshgrid( ...
    min_crit_ratio:step_size:max_crit_ratio , ...
    min_degrees:angle_res:90);

% Convert to radians
exterior_angle = exterior_angle * pi / 180;

[vol, grad_h, grad_theta] = frustrum(crit_ratio, exterior_angle);

% For each exterior angle, find the critical ratio where the volume is
% maximized
max_ratio_at_fixed_angle = max(vol,[],1);

figure;
plot(crit_ratio, max_ratio_at_fixed_angle);
title('Volume of a frustrum');
xlabel('Critical Ratio');
ylabel('Volume');

figure;
surf(crit_ratio, exterior_angle, vol, 'EdgeColor', 'none');
title('Volume of a frustrum');
xlabel('Critical Ratio');
ylabel('Exterior Angle (radians)');
zlabel('Volume');


text:
<?php

namespace Inversion\Service;

use Inversion\Exception\ClassNameNotSpecified;
use Inversion\Container;
use Inversion\Exception\InvalidNumberOfArguments;
use Inversion\Reference;

abstract class AbstractService
{
    protected static $cache = array();
    protected $className;

    /**
     * @param string $className A class name on service.
     */
    public function __construct($className)
    {
        $this->className = $className;
    }

    /**
     * @return mixed|object
     */
    public abstract function get();

    /**
     * Return interfaces for class.
     * @throw ClassNameNotSpecified
     * @return array
     */
    public function getInterfaces()
    {
        if(empty($this->className)) {
            throw new ClassNameNotSpecified();
        }

        $reflectionClass = new \ReflectionClass($this->className);
        $reflectionInterfaces = $reflectionClass->getInterfaces();

        $interfaces = array();

        foreach($reflectionInterfaces as $reflectionClassInterface) {
            $interfaces[] = $reflectionClassInterface->getName();
        }

        return $interfaces;
    }

    /**
     * Create class instance by given class name and associated arguments array.
     * @param $className
     * @param array $arguments
     * @return object
     * @throws InvalidNumberOfArguments
     */
    public static function create($className, $arguments = array())
    {
        $container = Container::getInstance();
        $parameters = self::getParameters($className);

        $args = array();
        foreach ($parameters as $parameter) {
            try {
                $classReflection = $parameter->getClass();
            } catch(\ReflectionException $e) {
                $classReflection = false;
            }

            // TODO: Add functionality to be able declare as array('@config', '@request', '@router')
            if(isset($arguments[$parameter->getName()])) {
                // Set service from arguments by parameter name.
                $value = $arguments[$parameter->getName()];

                if($value instanceof Reference) {
                    $args[] = $value->get();
                } else {
                    $args[] = $value;
                }
            } else if ($classReflection instanceof \ReflectionClass) {
                // If parameter have class.
                $args[] = $container->get($classReflection->getName());
            } else {
                if (!$parameter->isDefaultValueAvailable()) {
                    throw new InvalidNumberOfArguments("Not enough arguments to create an instance of \"$className\".");
                }
            }
        }

        $reflectionClass = new \ReflectionClass($className);
        return $reflectionClass->newInstanceArgs($args);
    }

    /**
     * Get constructor parameters of class.
     * @static
     * @param string $className
     * @return \ReflectionParameter[]
     */
    protected static function getParameters($className)
    {
        if (isset(self::$cache[$className])) {
            return self::$cache[$className];
        }

        $parameters = array();
        $reflectionClass = new \ReflectionClass($className);

        if ($reflectionMethod = $reflectionClass->getConstructor()) {
            foreach ($reflectionMethod->getParameters() as $reflectionParameter) {
                $parameters[] = $reflectionParameter;
            }
        }

        return self::$cache[$className] = $parameters;
    }
}


text:
#include <stdio.h>
#include <sqlite3.h>
#include "debug.h"
#include "record.h"

/*
int odem_has_table(sqlite3 *db, const char* table_name)
{
    #define HAS_TABLE_SQL "SELECT
}
*/

/**
 * Execute a noselect statement
 *
 * @param db Database connection
 * @param sql Query to execute
 * @return sqlite3 code
 */
int odem_exec_noselect_db(sqlite3 *db, const char* sql)
{
    int rc;
    char msg[100];
    sqlite3_stmt* stmt;

    sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    rc = sqlite3_step(stmt);

    if (rc != SQLITE_DONE)
    {
        snprintf(msg, sizeof(msg), "ERROR: %s\n", sqlite3_errmsg(db));
        die(msg);
    }

    sqlite3_finalize(stmt);

    return rc;
}

/**
 * Initialize a odem results database
 *
 * @param db Database connection
 * @return sqlite3 code
 */
void odem_init_results_db(sqlite3 *db)
{
    odem_exec_noselect_db(db, "PRAGMA foreign_keys = ON");

    odem_exec_noselect_db(db, "CREATE TABLE particle"
        "(particle_id INTEGER PRIMARY KEY AUTOINCREMENT, mass REAL,"
        " radius REAL)");

    #if ODEM_DOF == 3
        odem_exec_noselect_db(db, "CREATE TABLE model"
            "(iters INTEGER, delta_time REAL, x_min REAL, x_max REAL,"
            " y_min REAL, y_max REAL, z_min REAL, z_max REAL)");
    #elif ODEM_DOF == 2
        odem_exec_noselect_db(db, "CREATE TABLE model"
            "(iters INTEGER, delta_time REAL, x_min REAL, x_max REAL,"
            " y_min REAL, y_max REAL)");
    #endif

    #if ODEM_DOF == 3
        odem_exec_noselect_db(db,
            "CREATE TABLE motion (time REAL, particle_id INTEGER, x REAL,"
            " y REAL, z REAL, v_x REAL, v_y REAL, v_z REAL, a_x REAL, a_y REAL,"
            " a_z REAL, f_x REAL, f_y REAL, f_z REAL,"
            " FOREIGN KEY(particle_id) REFERENCES particle(particle_id))");
    #elif ODEM_DOF == 2
        odem_exec_noselect_db(db,
            "CREATE TABLE motion (time REAL, particle_id INTEGER, x REAL,"
            " y REAL, v_x REAL, v_y REAL, a_x REAL, a_y REAL, f_x REAL,"
            " f_y REAL, FOREIGN KEY(particle_id) REFERENCES"
            " particle(particle_id))");
    #endif
    odem_exec_noselect_db(db,
        "CREATE INDEX time_particle_id_idx ON motion (time, particle_id)");
}

/**
 * Record particle attributes
 *
 * @param db Database connection
 * @param ppart_list Particle linked list
 */
void odem_record_particle_data(sqlite3 *db, struct odem_particle_node*
    const ppart_list)
{
    char sql[512];

    struct odem_particle_node* curr_node;

    size_t sql_size = sizeof(sql);

    for (curr_node = ppart_list; curr_node != NULL; curr_node = curr_node->next)
    {
        snprintf(sql, sql_size, "INSERT INTO particle VALUES (NULL, %lf, %lf)",
            curr_node->ppart->mass, curr_node->ppart->radius);
        odem_exec_noselect_db(db, sql);
    }
}

/**
 * Record model constants
 *
 * @param db Database connection
 * @param iters Number of iterations
 * @param delta_time Size of time step
 * @param bounds Array of boundary values
 */
void odem_record_model_data(sqlite3 *db, const int iters, const double
    delta_time, const double bounds[])
{
    char sql[512];

    #if ODEM_DOF == 3
        snprintf(sql, sizeof(sql), "INSERT INTO model"
            " VALUES (%d, %lf, %lf, %lf, %lf, %lf, %lf, %lf)",
            iters, delta_time, bounds[2*X], bounds[2*X+1], bounds[2*Y],
            bounds[2*Y+1], bounds[2*Z], bounds[2*Z+1]);
    #elif ODEM_DOF == 2
        snprintf(sql, sizeof(sql), "INSERT INTO model"
            " VALUES (%d, %lf, %lf, %lf, %lf, %lf)",
            iters, delta_time, bounds[2*X], bounds[2*X+1], bounds[2*Y],
            bounds[2*Y+1]);
    #endif

    odem_exec_noselect_db(db, sql);
}

/**
 * Record particle motion for a single time step
 *
 * @param db Database connection
 * @param time Time of step
 * @param particle_id Id of particle
 * @param ppart Pointer to particle
 * @param accel_vec Acceleration vector of particle for time step
 * @param force_vec Force vector of particle for time step
 */
void odem_record_motion(sqlite3 *db, const double time,
    const int particle_id, const struct odem_particle* ppart,
    const double accel_vec[], const double force_vec[])
{
    char sql[512];

    #if ODEM_DOF == 3
        snprintf(sql, sizeof(sql), "INSERT INTO motion"
            " VALUES (%lf, %d, %lf, %lf, %lf, %lf, %lf, %lf, %lf, %lf, %lf,"
            " %lf, %lf)",
            time, particle_id, ppart->centroid[X], ppart->centroid[Y],
            ppart->centroid[Z], ppart->velocity[X], ppart->velocity[Y],
            accel_vec[X], accel_vec[Y], accel_vec[Z], force_vec[X],
            force_vec[Y], force_vec[Z]);
    #elif ODEM_DOF == 2
        snprintf(sql, sizeof(sql), "INSERT INTO motion"
            " VALUES (%lf, %d, %lf, %lf, %lf, %lf, %lf, %lf, %lf, %lf)",
            time, particle_id, ppart->centroid[X], ppart->centroid[Y],
            ppart->velocity[X], ppart->velocity[Y], accel_vec[X], accel_vec[Y],
            force_vec[X], force_vec[Y]);
    #endif

    odem_exec_noselect_db(db, sql);
}


text:
package com.facebook.buck.junit;

import org.junit.runner.JUnitCore;
import org.junit.runner.Request;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;

/**
 * Result of an individual test method in JUnit. Similar to {@link Result}, except that it always
 * corresponds to exactly one test method.
 */
final class TestResult {

  private static final String ENCODING = "UTF-8";

  final String testClassName;
  final String testMethodName;
  final long runTime;
  final /* @Nullable */ Failure failure;
  final /* @Nullable */ String stdOut;
  final /* @Nullable */ String stdErr;

  public TestResult(String testClassName,
      String testMethodName,
      long runTime,
      Failure failure,
      /* @Nullable */ String stdOut,
      /* @Nullable */ String stdErr) {
    this.testClassName = testClassName;
    this.testMethodName = testMethodName;
    this.runTime = runTime;
    this.failure = failure;
    this.stdOut = stdOut;
    this.stdErr = stdErr;
  }

  public boolean isSuccess() {
    return failure == null;
  }

  /**
   * Runs the specified test method using the specified test runner.
   */
  static TestResult runTestMethod(Class<?> clazz, String methodName, JUnitCore testRunner)
      throws UnsupportedEncodingException {
    Request request = Request.method(clazz, methodName);

    // Create an intermediate stdout/stderr to capture any debugging statements (usually in the
    // form of System.out.println) the developer is using to debug the test.
    PrintStream originalOut = System.out;
    PrintStream originalErr = System.err;
    ByteArrayOutputStream rawStdOutBytes = new ByteArrayOutputStream();
    ByteArrayOutputStream rawStdErrBytes = new ByteArrayOutputStream();
    PrintStream stdOutStream = new PrintStream(
        rawStdOutBytes, true /* autoFlush */, ENCODING);
    PrintStream stdErrStream = new PrintStream(
        rawStdErrBytes, true /* autoFlush */, ENCODING);
    System.setOut(stdOutStream);
    System.setErr(stdErrStream);

    // Run the test!
    Result result = testRunner.run(request);

    // Restore the original stdout/stderr.
    System.setOut(originalOut);
    System.setErr(originalErr);

    // Get the stdout/stderr written during the test as strings.
    stdOutStream.flush();
    stdErrStream.flush();

    int numFailures = result.getFailureCount();
    // In practice, I have seen one case of a test having more than one failure:
    // com.xtremelabs.robolectric.shadows.H2DatabaseTest#shouldUseH2DatabaseMap() had 2 failures.
    // However, I am not sure what to make of it, so we let it through.
    if (numFailures < 0) {
      throw new IllegalStateException(String.format(
          "Unexpected number of failures while testing %s#%s(): %d (%s)",
          clazz.getName(),
          methodName,
          numFailures,
          result.getFailures()));
    }
    Failure failure = numFailures == 0 ? null : result.getFailures().get(0);

    String stdOut = rawStdOutBytes.size() == 0 ? null : rawStdOutBytes.toString(ENCODING);
    String stdErr = rawStdErrBytes.size() == 0 ? null : rawStdErrBytes.toString(ENCODING);
    return new TestResult(clazz.getName(),
        methodName,
        result.getRunTime(),
        failure,
        stdOut,
        stdErr);
  }
}


text:
title: "Kitura-Session 3.3: Sharing Codable objects between a user's requests"
blurb: This blog will describe Kitura-Session's new capabilities and provide an example of using sessions with a Kitura server
date: "2018-12-18"
author: Andrew Lees
path: /blogs/codable-kitura-session
---

Web application servers are generally "stateless" and handle HTTP requests independently. However, it's common for a developer to want to link requests from the same user together in a session. A simple way to achieve this is by using a cookie to identify the user and associating data to that cookie. [Kitura-Session](https://github.com/Kitura/Kitura-Session) allows you to implement this flow and, as of version 3.3, you can now directly store and retrieve Codable objects. This blog will describe Kitura-Session's new capabilities and provide an example of using sessions with a Kitura server.

##Codable Kitura-Session

Previously, if you wanted to save something in a Raw routing session, you would store it as an Any. This is not type safe since you could try and save objects the would fail to be serialized as JSON. Furthermore, when you retrieve the item you have to cast it to the type you expect. With the 3.3 release of Kitura-Session, you can store and retrieve Codable objects adding type safety and removing the need for explicit casting. To demonstrate how this improves usability, we will apply these changes to the sessions example from `Kitura-Sample:

###An online Bookstore

This example simulates a website where users buy books. The user doesn't want to have to select all their book at once so they add the book they are interested in to their shopping cart. This cart is shared between requests until the checkout. In server terms, the cart is our session, where we store the users selected Book models.

```swift
public struct Book: Codable {
    var name: String
    var author: String
    var rating: Int
}
```

###Adding a book to the shopping cart

The user wants to add a book to their cart. They do this by sending a POST request with the book's data to the server. The server receives the request, uses cookies to identify the user and adds the book to their session.

In Kitura-Session 3.2 this would be done as follows:

```swift
router.post("/session") { request, response, next in
    let inputBook = try request.read(as: Book.self)
    var books = request.session?["books"] as? [[String: String]] ?? []
    let newBook: [String: String] = ["name": inputBook.name, "author": inputBook.author, "rating": String(inputBook.rating)]
    books.append(newBook)
    session["books"] = books
    response.send(inputBook)
    next()
}
```

In Kitura-Session 3.3, we can pass the book from the request body straight into the session:

```swift
router.post("/session") { request, response, next in
    let inputBook = try request.read(as: Book.self)
    var books: [Book] = request.session?["books"] ?? []
    books.append(inputBook)
    session["books"] = books
    response.send(inputBook)
    next()
}
```

This has removed the need to convert our model into a JSON dictionary, saving us from clunky boilerplate code.

###Viewing your shopping cart

Once the user has added a few books to their cart, they want to view all their books. The do this by sending a GET request to the server. Cookies identify the user again and all the books they previously saved in the session are returned to them.

In Kitura-Session 3.2 this would be done as follows:

```swift
router.get("/session") { request, response, next in
    let bookData = request.session?["books"] as? [[String: String]] ?? []
    var books: [Book] = []
    for book in bookData {
        guard let bookName = book["name"],
              let bookAuthor = book["author"],
              let ratingString = book["rating"],
              let bookRating = Int(ratingString)
        else { continue }
        let newBook = Book(name: bookName, author: bookAuthor, rating: bookRating)
        books.append(newBook)
    }
    response.send(books)
    next()
}
```

In Kitura-Session 3.3, by defining the type we expect from the session, we get our Codable model straight out of the session:

```swift
router.get("/session") { request, response, next in
    let books: [Book] = request.session?["books"] ?? []
    response.send(books)
    next()
}
```

Even with a simple model, this has vastly reduced the amount of code required, added compile time safety and made our code easier to read!


text:
include_recipe 'orchestrator::_database_setup'

local_rpm = nil

if centos? && !node['orchestrator']['package']['url'].nil?
  local_rpm = File.join(Chef::Config['file_cache_path'], 'orchestrator.rpm')
  remote_file local_rpm do
    source node['orchestrator']['package']['url']
    checksum node['orchestrator']['package']['checksum']
    action :create_if_missing if node['orchestrator']['package']['checksum'].nil?
    notifies :install, 'package[orchestrator]', :immediately
  end
end

package 'orchestrator' do
  source local_rpm if centos? && !local_rpm.nil?
  version node['orchestrator']['package']['version'] if centos? && !node['orchestrator']['package']['version'].nil?
  action node['orchestrator']['package']['version'].nil? ? :upgrade : :install
end


text:
"""
Syslog server support.

This provides support for receiving syslog messages and utilities for
further shipping similar to the native udplog protocol.
"""

from __future__ import division, absolute_import

from datetime import datetime
import json
import re

from dateutil.parser import parse
from dateutil import tz

from twisted.internet.protocol import DatagramProtocol
from twisted.python import log

FACILITIES = [
    u'kern', u'user', u'mail', u'daemon', u'auth', u'syslog', u'lpr', u'news',
    u'uucp', u'cron', u'authpriv', u'ftp', u'ntp', u'audit', u'alert', u'at',
    u'local0', u'local1', u'local2', u'local3', u'local4', u'local5',
    u'local6', u'local7'
    ]

SEVERITIES = [
    u'emerg', u'alert', u'crit', u'err', u'warn', u'notice', u'info', u'debug'
    ]

LOG_LEVELS = {
    u'emerg': u'EMERGENCY',
    u'alert': u'ALERT',
    u'crit': u'CRITICAL',
    u'err': u'ERROR',
    u'warn': u'WARNING',
    u'notice': u'NOTICE',
    u'info': u'INFO',
    u'debug': u'DEBUG',
    }

RE_SYSLOG = re.compile(
    u"""
    ^
    <(?P<priority>\d+)>
    (?P<timestamp>(\w\w\w[ ][ \d]?\d[ ]\d\d:\d\d:\d\d|
                   \d\d\d\d-\d\d-\d\dT\S+))[ ]
    (?P<hostname>\w*)[ ]
    (?P<tag>\w+)(\[(?P<pid>\d+)\])?:[ ]?
    (?P<content>(?P<bom>\xef\xbb\xbf)?(?P<message>.*?)
    ([ ]?@cee:[ ](?P<cee>.*))?)
    $
    """,
    re.IGNORECASE | re.VERBOSE)

def parsePriority(priority):
    """
    Extract facility and severity from syslog priority.

    @param priority: Syslog priority. Between 0 and 191.
    @type priority: L{int}

    @return: Tuple of facility and severity names. See C{FACILITIES} and
        C{SEVERITIES}.
    @rtype: L{tuple} of L{unicode}

    @raise: L{IndexError} for invalid priority values.
    """
    facility, severity = divmod(priority, 8)
    return FACILITIES[facility], SEVERITIES[severity]

def parseSyslog(line, tzinfo):
    """
    Parse syslog log message.

    This parses a syslog message per RFC 3164 into a dictionary with keys
    C{'message'}, C{'timestamp'}, C{'facility'}, C{'severity'}, C{'hostname'},
    C{'tag'} and C{'pid'}. If the log line doesn't match the syntax defined in
    RFC 3164 it returns the entire line as the value of the C{'message'} key.

    The syslog timestamp format only specifies month, day and time, lacking
    year or timestamp information. L{dateutil} is used to fill in the blanks
    using the C{tzinfo} parameter. Most likely you want to pass
    L{dateutil.tz.gettz()} as the value, as this attempts to determine the
    system's time zone (e.g. from C{/etc/localtime}), which is most likely the
    same as the one used for logging the timezone-naive timestamps.

    If the timestamp cannot be parsed, the C{'timestamp'} key will be absent
    from the resulting dictionary. If there is no PID in square brackets
    directly following the tag, the C{'pid'} key will be absent. For invalid
    priority values, the C{'facility'} and C{'severity'} fields will be empty.

    If the message has the C{'@cee:'} marker, the rest of the message
    is interpreted as a JSON object and merged into the resulting event
    dictionary. See U{Mitre CEE<https://cee.mitre.org/>}. Note that no
    attempt is made to interpret the field names. It is advisable to explicitly
    set the C{category} field to provide a namespace for the other fields, as
    this helps type mapping to storage facilities like Elasticsearch.

    @param line: Syslog log message.
    @type line: L{bytes}

    @param tzinfo: Timezone information to attach to syslog's timezone-naive
        timestamps.
    @type tzinfo: L{datetime.tzinfo}

    @return: Event dictionary. The C{'timestamp'} key will have a
        timezone-aware L{datetime.datetime} as value. All other values are
        L{unicode} strings.

    @rtype: L{dict}
    """
    eventDict = {}

    match = RE_SYSLOG.match(line)
    if match:
        try:
            facility, severity = parsePriority(int(match.group('priority')))
        except IndexError:
            pass
        else:
            eventDict['facility'] = facility
            eventDict['severity'] = severity

        try:
            dt = parse(match.group('timestamp'))
        except ValueError:
            log.err()
        else:
            if not dt.tzinfo:
                dt = dt.replace(tzinfo=tzinfo)
            eventDict['timestamp'] = dt

        eventDict['hostname'] = match.group('hostname')
        eventDict['tag'] = match.group('tag')
        if match.group('pid'):
            eventDict['pid'] = match.group('pid')
        message = match.group('message')

        if match.group('cee'):
            try:
                cee = json.loads(match.group('cee'))
            except:
                log.err()
                message = match.group('content')
            else:
                eventDict.update(cee)

        if match.group('bom'):
            message = message.decode('utf-8', 'replace')
        else:
            message = message.decode('latin1')

        eventDict['message'] = message
    else:
        eventDict['message'] = line.decode('latin1')

    return eventDict

def syslogToUDPLogEvent(eventDict, hostnames=None):
    """
    Convert syslog event to a UDPLog event.

    This converts the timestamp to POSIX style and renames the C{tag}
    and C{severity} fields into respectively C{appname} and C{logLevel} for
    consistency in field naming.

    Additionally, this sets the C{category} field to C{'syslog'} if not set
    through the use of CEE.

    @param eventDict: The event dictionary.
    @type eventDict: C{dict}

    @param hostnames: Map to rewrite hostnames.
    @type hostnames: L{dict}
    """
    if 'timestamp' in eventDict:
        posixTimestamp = (eventDict['timestamp'] -
                          datetime(1970, 1, 1, tzinfo=tz.tzutc())
                          ).total_seconds()
        eventDict['timestamp'] = posixTimestamp

    eventDict.setdefault('category', u'syslog')

    if 'tag' in eventDict:
        eventDict['appname'] = eventDict['tag']
        del eventDict['tag']

    if 'severity' in eventDict:
        eventDict['logLevel'] = LOG_LEVELS[eventDict['severity']]
        del eventDict['severity']

    if (hostnames and eventDict.get('hostname') in hostnames):
        eventDict['hostname'] = hostnames[eventDict['hostname']]

    return eventDict

class SyslogDatagramProtocol(DatagramProtocol):
    """
    Datagram protocol for syslog.

    This can be used with
    C{UNIXDatagramServer<twisted.application.internet.UNIXDatagramServer} or
    C{UDPServer<twisted.application.internet.UDPServer} to accept syslog events
    over UNIX sockets or UDP respectively. See L{udplog.tap} for examples.
    """

    def __init__(self, callback, hostnames=None):
        """
        @param callback: Callback function that is called with a parsed
            syslog event, with fields made consistent for UDPLog. See
            L{parseSyslog} and L{syslogToUDPLogEvent} for details.
        """
        self._callback = callback
        self._hostnames = hostnames

    def datagramReceived(self, datagram, addr):
        eventDict = parseSyslog(datagram, tz.gettz())
        eventDict = syslogToUDPLogEvent(eventDict, self._hostnames)
        self._callback(eventDict)


text:
package com.facebook.buck.jvm.java.intellij;

import com.google.common.collect.ImmutableSortedSet;

import java.nio.file.Path;

/**
 * A path which contains a set of sources we wish to present to IntelliJ.
 */
public class ExcludeFolder extends IjFolder {

  public static final IJFolderFactory FACTORY = new IJFolderFactory() {
    @Override
    public IjFolder create(
        Path path, boolean wantsPrefix, ImmutableSortedSet<Path> inputs) {
      if (wantsPrefix) {
        throw new IllegalArgumentException("ExcludeFolder does not support prefixes");
      }
      return new ExcludeFolder(path, inputs);
    }
  };

  private static final String FOLDER_IJ_NAME = "excludeFolder";

  ExcludeFolder(Path path, ImmutableSortedSet<Path> inputs) {
    super(path, false, inputs);
  }

  ExcludeFolder(Path path) {
    super(path);
  }

  @Override
  public IJFolderFactory getFactory() {
    return FACTORY;
  }

  /**
   * @return name IntelliJ would use to refer to this type of folder.
   */
  @Override
  public String getIjName() {
    return FOLDER_IJ_NAME;
  }

  /**
   * @return true if the folder can be coalesced with others of the same type
   */
  @Override
  public boolean isCoalescent() {
    return false;
  }

  @SuppressWarnings("unused")
  public boolean canMergeWith(SourceFolder other) {
    return false;
  }

  @Override
  public IjFolder merge(IjFolder otherFolder) {
    checkMergeConditions(otherFolder);

    if (otherFolder == this) {
      return this;
    }

    return new ExcludeFolder(
        otherFolder.getPath(),
        combineInputs(this, otherFolder)
    );
  }
}


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

<title>ExOleObjAtom (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.poi.hslf.record

Class ExOleObjAtom

java.lang.Object

org.apache.poi.hslf.record.Record

org.apache.poi.hslf.record.RecordAtom

org.apache.poi.hslf.record.ExOleObjAtom

public class ExOleObjAtom
extends RecordAtom

Atom storing information for an OLE object.

Author:

Daniel Noll

Field Summary

Fields

Modifier and Type
Field and Description

static int
DRAW_ASPECT_DOCPRINT

The object is displayed on the screen as though it were printed to a printer.

static int
DRAW_ASPECT_ICON

The object is displayed as an icon.

static int
DRAW_ASPECT_THUMBNAIL

The object is displayed as a thumbnail image.

static int
DRAW_ASPECT_VISIBLE

The object) is displayed as an embedded object inside of a container,

static int
SUBTYPE_CLIPART_GALLERY

static int
SUBTYPE_DEFAULT

static int
SUBTYPE_EQUATION

static int
SUBTYPE_EXCEL

static int
SUBTYPE_EXCEL_CHART

static int
SUBTYPE_GRAPH

static int
SUBTYPE_IMAGE

static int
SUBTYPE_MEDIA_PLAYER

static int
SUBTYPE_NOTEIT

static int
SUBTYPE_ORGANIZATION_CHART

static int
SUBTYPE_POWERPOINT_PRESENTATION

static int
SUBTYPE_POWERPOINT_SLIDE

static int
SUBTYPE_PROJECT

static int
SUBTYPE_SOUND

static int
SUBTYPE_WORD_TABLE

static int
SUBTYPE_WORDART

static int
TYPE_CONTROL

The OLE object is an ActiveX control.

static int
TYPE_EMBEDDED

An embedded OLE object; the object is serialized and saved within the file.

static int
TYPE_LINKED

A linked OLE object; the object is saved outside of the file.

Fields inherited from class org.apache.poi.hslf.record.Record

logger

Constructor Summary

Constructors

Modifier
Constructor and Description

ExOleObjAtom()

Constructs a brand new link related atom record.

protected
ExOleObjAtom(byte[] source,
            int start,
            int len)

Constructs the link related atom record from its
  source data.

Method Summary

Methods

Modifier and Type
Method and Description

int
getDrawAspect()

Gets whether the object can be completely seen, or if only the
 icon is visible.

boolean
getIsBlank()

Gets whether the object's image is blank.

int
getObjID()

Gets the unique identifier for the OLE object.

int
getObjStgDataRef()

Gets the reference to the persistent object

int
getOptions()

Gets misc options (the last four bytes in the atom).

long
getRecordType()

Returns the type (held as a little endian in bytes 3 and 4)
 that this class handles.

int
getSubType()

Gets the type of OLE object.

int
getType()

Gets whether the object is embedded or linked.

void
setDrawAspect(int aspect)

Sets whether the object can be completely seen, or if only the
 icon is visible.

void
setObjID(int id)

Sets the unique identifier for the OLE object.

void
setObjStgDataRef(int ref)

Sets the reference to the persistent object

void
setOptions(int opts)

Sets misc options (the last four bytes in the atom).

void
setSubType(int type)

Sets the type of OLE object.

void
setType(int type)

Sets whether the object is embedded or linked.

java.lang.String
toString()

void
writeOut(java.io.OutputStream out)

Have the contents printer out into an OutputStream, used when
 writing a file back out to disk
 (Normally, atom classes will keep their bytes around, but
 non atom classes will just request the bytes from their
 children, then chuck on their header and return)

Methods inherited from class org.apache.poi.hslf.record.RecordAtom

getChildRecords, isAnAtom

Methods inherited from class org.apache.poi.hslf.record.Record

buildRecordAtOffset, createRecordForType, findChildRecords, writeLittleEndian, writeLittleEndian

Methods inherited from class java.lang.Object

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

Field Detail

DRAW_ASPECT_VISIBLE

public static final int DRAW_ASPECT_VISIBLE

The object) is displayed as an embedded object inside of a container,

See Also:

Constant Field Values

DRAW_ASPECT_THUMBNAIL

public static final int DRAW_ASPECT_THUMBNAIL

The object is displayed as a thumbnail image.

See Also:

Constant Field Values

DRAW_ASPECT_ICON

public static final int DRAW_ASPECT_ICON

The object is displayed as an icon.

See Also:

Constant Field Values

DRAW_ASPECT_DOCPRINT

public static final int DRAW_ASPECT_DOCPRINT

The object is displayed on the screen as though it were printed to a printer.

See Also:

Constant Field Values

TYPE_EMBEDDED

public static final int TYPE_EMBEDDED

An embedded OLE object; the object is serialized and saved within the file.

See Also:

Constant Field Values

TYPE_LINKED

public static final int TYPE_LINKED

A linked OLE object; the object is saved outside of the file.

See Also:

Constant Field Values

TYPE_CONTROL

public static final int TYPE_CONTROL

The OLE object is an ActiveX control.

See Also:

Constant Field Values

SUBTYPE_DEFAULT

public static final int SUBTYPE_DEFAULT

See Also:

Constant Field Values

SUBTYPE_CLIPART_GALLERY

public static final int SUBTYPE_CLIPART_GALLERY

See Also:

Constant Field Values

SUBTYPE_WORD_TABLE

public static final int SUBTYPE_WORD_TABLE

See Also:

Constant Field Values

SUBTYPE_EXCEL

public static final int SUBTYPE_EXCEL

See Also:

Constant Field Values

SUBTYPE_GRAPH

public static final int SUBTYPE_GRAPH

See Also:

Constant Field Values

SUBTYPE_ORGANIZATION_CHART

public static final int SUBTYPE_ORGANIZATION_CHART

See Also:

Constant Field Values

SUBTYPE_EQUATION

public static final int SUBTYPE_EQUATION

See Also:

Constant Field Values

SUBTYPE_WORDART

public static final int SUBTYPE_WORDART

See Also:

Constant Field Values

SUBTYPE_SOUND

public static final int SUBTYPE_SOUND

See Also:

Constant Field Values

SUBTYPE_IMAGE

public static final int SUBTYPE_IMAGE

See Also:

Constant Field Values

SUBTYPE_POWERPOINT_PRESENTATION

public static final int SUBTYPE_POWERPOINT_PRESENTATION

See Also:

Constant Field Values

SUBTYPE_POWERPOINT_SLIDE

public static final int SUBTYPE_POWERPOINT_SLIDE

See Also:

Constant Field Values

SUBTYPE_PROJECT

public static final int SUBTYPE_PROJECT

See Also:

Constant Field Values

SUBTYPE_NOTEIT

public static final int SUBTYPE_NOTEIT

See Also:

Constant Field Values

SUBTYPE_EXCEL_CHART

public static final int SUBTYPE_EXCEL_CHART

See Also:

Constant Field Values

SUBTYPE_MEDIA_PLAYER

public static final int SUBTYPE_MEDIA_PLAYER

See Also:

Constant Field Values

Constructor Detail

ExOleObjAtom

public ExOleObjAtom()

Constructs a brand new link related atom record.

ExOleObjAtom

protected ExOleObjAtom(byte[] source,
            int start,
            int len)

Constructs the link related atom record from its
  source data.

Parameters:

source - the source data as a byte array.

start - the start offset into the byte array.

len - the length of the slice in the byte array.

Method Detail

getDrawAspect

public int getDrawAspect()

Gets whether the object can be completely seen, or if only the
 icon is visible.

Returns:

the draw aspect, one of the DRAW_ASPECT_* constants.

setDrawAspect

public void setDrawAspect(int aspect)

Sets whether the object can be completely seen, or if only the
 icon is visible.

Parameters:

aspect - the draw aspect, one of the DRAW_ASPECT_* constants.

getType

public int getType()

Gets whether the object is embedded or linked.

Returns:

the type, one of the TYPE_EMBEDDED_* constants.

setType

public void setType(int type)

Sets whether the object is embedded or linked.

Parameters:

type - the type, one of the TYPE_EMBEDDED_* constants.

getObjID

public int getObjID()

Gets the unique identifier for the OLE object.

Returns:

the object ID.

setObjID

public void setObjID(int id)

Sets the unique identifier for the OLE object.

Parameters:

id - the object ID.

getSubType

public int getSubType()

Gets the type of OLE object.

Returns:

the sub-type, one of the SUBTYPE_* constants.

setSubType

public void setSubType(int type)

Sets the type of OLE object.

Parameters:

type - the sub-type, one of the SUBTYPE_* constants.

getObjStgDataRef

public int getObjStgDataRef()

Gets the reference to the persistent object

Returns:

the reference to the persistent object, corresponds with an
         ExOleObjStg storage container.

setObjStgDataRef

public void setObjStgDataRef(int ref)

Sets the reference to the persistent object

Parameters:

ref - the reference to the persistent object, corresponds with an
         ExOleObjStg storage container.

getIsBlank

public boolean getIsBlank()

Gets whether the object's image is blank.

Returns:

true if the object's image is blank.

getOptions

public int getOptions()

Gets misc options (the last four bytes in the atom).

Returns:

true if the object's image is blank.

setOptions

public void setOptions(int opts)

Sets misc options (the last four bytes in the atom).

getRecordType

public long getRecordType()

Returns the type (held as a little endian in bytes 3 and 4)
 that this class handles.

Specified by:

getRecordType in class Record

writeOut

public void writeOut(java.io.OutputStream out)
              throws java.io.IOException

Have the contents printer out into an OutputStream, used when
 writing a file back out to disk
 (Normally, atom classes will keep their bytes around, but
 non atom classes will just request the bytes from their
 children, then chuck on their header and return)

Specified by:

writeOut in class Record

Throws:

java.io.IOException

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

                Copyright 2015 The Apache Software Foundation or
        its licensors, as applicable.


text:
class Users::PasswordsController < Devise::PasswordsController
  layout 'user'

  def initialize(*params)
    super(*params)
    @controller_name = t(:login)
  end

  protected

  def after_sending_reset_password_instructions_path_for(_resource_name)
    root_path
  end
end


text:
import eql from "should-equal";
import getType from "should-type";
import { formatProp, format } from "../format";
import { forEach } from "should-type-adaptors";

function formatEqlResult(r, a, b) {
  return ((r.path.length > 0
    ? "at " + r.path.map(formatProp).join(" -> ")
    : "") +
    (r.a === a ? "" : ", A has " + format(r.a)) +
    (r.b === b ? "" : " and B has " + format(r.b)) +
    (r.showReason ? " because " + r.reason : "")).trim();
}

export default function(should, Assertion) {
  /**
   * Deep object equality comparison. For full spec see [`should-equal tests`](https://github.com/shouldjs/equal/blob/master/test.js).
   *
   * @name eql
   * @memberOf Assertion
   * @category assertion equality
   * @alias Assertion#eqls
   * @alias Assertion#deepEqual
   * @param {*} val Expected value
   * @param {string} [description] Optional message
   * @example
   *
   * (10).should.be.eql(10);
   * ('10').should.not.be.eql(10);
   * (-0).should.not.be.eql(+0);
   *
   * NaN.should.be.eql(NaN);
   *
   * ({ a: 10}).should.be.eql({ a: 10 });
   * [ 'a' ].should.not.be.eql({ '0': 'a' });
   */
  Assertion.add("eql", function(val, description) {
    this.params = { operator: "to equal", expected: val, message: description };
    var obj = this.obj;
    var fails = eql(this.obj, val, should.config);
    this.params.details = fails
      .map(function(fail) {
        return formatEqlResult(fail, obj, val);
      })
      .join(", ");

    this.params.showDiff = eql(getType(obj), getType(val)).length === 0;

    this.assert(fails.length === 0);
  });

  /**
   * Exact comparison using ===.
   *
   * @name equal
   * @memberOf Assertion
   * @category assertion equality
   * @alias Assertion#equals
   * @alias Assertion#exactly
   * @param {*} val Expected value
   * @param {string} [description] Optional message
   * @example
   *
   * 10.should.be.equal(10);
   * 'a'.should.be.exactly('a');
   *
   * should(null).be.exactly(null);
   */
  Assertion.add("equal", function(val, description) {
    this.params = { operator: "to be", expected: val, message: description };

    this.params.showDiff = eql(getType(this.obj), getType(val)).length === 0;

    this.assert(val === this.obj);
  });

  Assertion.alias("equal", "equals");
  Assertion.alias("equal", "exactly");
  Assertion.alias("eql", "eqls");
  Assertion.alias("eql", "deepEqual");

  function addOneOf(name, message, method) {
    Assertion.add(name, function(vals) {
      if (arguments.length !== 1) {
        vals = Array.prototype.slice.call(arguments);
      } else {
        should(vals).be.Array();
      }

      this.params = { operator: message, expected: vals };

      var obj = this.obj;
      var found = false;

      forEach(vals, function(val) {
        try {
          should(val)[method](obj);
          found = true;
          return false;
        } catch (e) {
          if (e instanceof should.AssertionError) {
            return; //do nothing
          }
          throw e;
        }
      });

      this.assert(found);
    });
  }

  /**
   * Exact comparison using === to be one of supplied objects.
   *
   * @name equalOneOf
   * @memberOf Assertion
   * @category assertion equality
   * @param {Array|*} vals Expected values
   * @example
   *
   * 'ab'.should.be.equalOneOf('a', 10, 'ab');
   * 'ab'.should.be.equalOneOf(['a', 10, 'ab']);
   */
  addOneOf("equalOneOf", "to be equals one of", "equal");

  /**
   * Exact comparison using .eql to be one of supplied objects.
   *
   * @name oneOf
   * @memberOf Assertion
   * @category assertion equality
   * @param {Array|*} vals Expected values
   * @example
   *
   * ({a: 10}).should.be.oneOf('a', 10, 'ab', {a: 10});
   * ({a: 10}).should.be.oneOf(['a', 10, 'ab', {a: 10}]);
   */
  addOneOf("oneOf", "to be one of", "eql");
}


text:
package org.kie.workbench.common.screens.projecteditor.client.forms;

import java.util.List;

import org.kie.workbench.common.services.shared.kmodule.ListenerModel;
import org.guvnor.common.services.project.model.WorkItemHandlerModel;

public interface KSessionModelOptionsPopUpView {

    void setListeners(List<ListenerModel> listeners);

    void setWorkItemHandlers(List<WorkItemHandlerModel> workItemHandlerModels);

    void show();

}