text:
layout: post
title:  "Quino: Hay quienes tienen vista corta..."
author: rafa_aguilar
date:   2015-04-17 11:35:40
categories: entradas
comments: true
---

Esta semana Quino nos muestra como hay veces que por no ver más allá muchos se quedan con los crespos hechos, si, seguro te llegan a la mente unos cuantos... al menos a mi sí, fué algo como qué: primero los de vista corta, luego los invidentes, luego el señor de la imagen y ahí le siguen esos que vinieron en mis recuerdos. Espero la disfruten.

![][quino]

[quino]: https://kylesroberts.files.wordpress.com/2012/01/quino001a.jpg

redpajama_set_name: RedPajamaGithub


text:
export const colors = /\u001b\[([0-9]+)m|\u001b/g;

// TODO(bh): Perhaps unify this with debuggerSignature by making
// whitespace entirely optional in the latter regular expression?
export const db = /^(\[(pid=)?[0-9\->]+\])?(\[\d+\])?DB\<+([0-9]+)\>+$/;

export const restartWarning = /^Warning: some settings and command-line options may be lost!/;

export const breakPoint = {
	// The condition my condition was in eg.:
	// '    break if (1)'
	condition: /^    break/,
	// This looks like a filename eg.:
	// 'test.pl:'
	filename: /^(([a-zA-Z]:)?[a-zA-Z.\_ \-0-9\/]+)\:$/,
	// Got a line nr eg.:
	// '5:\tprint "Testing\\n";'
	ln: /^ ([0-9]+):/,
}

export function cleanLine(line: string) {
	return line.replace(colors, '').replace(/\s|(\\b)/g, '').replace('\b', '');
}

export function isGarbageLine(line: string) {
	return cleanLine(line) === '' || lastCommandLine.test(line);
}

export const lastCommandLine = {
	// Improve this function... I think the test is the issue
	test(line: string) {
		const stripped = cleanLine(line);
		// console.log(`${db.test(stripped)} DB: "${stripped}"`);

		/*const chars = new Array([...stripped]);
		console.log(`CHARS:`, chars);*/

		return db.test(stripped);
	},

	match(line: string) {
		const stripped = cleanLine(line);
		return stripped.match(db);
	}
};

export const fileMatch = /^[a-zA-Z]+::\((.+):([0-9]+)\):($|\t.*)/;

export const fileMatchException = /at ([a-zA-Z\._-]+) line ([0-9]+)\./;

export const codeErrorSyntax = /^syntax error at (\S+) line ([0-9]+), near ([\S|\s]+)/;

export const codeErrorRuntime = /([\S|\s]+) at (\S+) line ([0-9]+)\.$/;

// EG. PadWalker for scope investigation
export const codeErrorMissingModule = /^(\S+) module not found - please install$/;

// Optional `pidprompt` like `[pid=123->456->789]` followed by an
// optional thread id, followed by `DB`, and for nested debuggers
// the number of `<` and `>` corresponds to the level of nesting.
export const debuggerSignature = /^(\[pid=[0-9>\-]+\])? (\[\d+\])? DB<+[0-9]+>+ $/;

export const watchpointChange = /^Watchpoint (\d+):\t(.*) changed:/;
export const watchpointOldval = /^\s+old value:\t'(.*)'/;
export const watchpointNewval = /^\s+new value:\t'(.*)'/;


text:
namespace OsEngine.OsTrader.AdminPanelApi
{
    public class AuthorizationMessage
    {
        public string Token { get; set; }
    }
}


text:
from FoodScan.ShopList import ShopList
from FoodScan.ShopSync.metaShop import MetaShopItem
from FoodScan.items import *
import wunderpy2
from pysimplelog import Logger

import requests
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS'

class WuList(ShopList):

    def __init__(self, config):
        ShopList.__init__(self)
        self.logger = Logger('Wunderlist')
        self.client = wunderpy2.WunderApi().get_client(config['wunderlist_token'], config['wunderlist_client_id'])
        self.list_id = config['wunderlist_list_id']

    def is_meta_item(self, task):
        return MetaShopItem.is_meta_item(task)

    def create_web_hook(self, url, port):
        hooks = self.client.get_webhooks(self.list_id)
        for hook in hooks:
            self.client.delete_webhook(hook['id'], 0)

        self.client.create_webhook(self.list_id, url + ":" + str(port), "generic")

    def list_tasks(self):
        return self.client.get_tasks(self.list_id)

    def list_revision(self):
        return self.client.get_list(self.list_id)['revision']

    def task_sub_tasks(self, iid):
        return self.client.get_task_subtasks(iid)

    def item_from_task(self, task, with_selects=True):
        notes = self.client.get_task_notes(task['id'])
        notes = notes[0]['content'] if len(notes) > 0 else ""

        sub_tasks = self.client.get_task_subtasks(task['id']) if with_selects else []
        return Item.parse(task['title'], notes, sub_tasks)

    def create_item(self, item):
        task = self.client.create_task(self.list_id, title=item.title())
        iid = task['id']
        if item.note():
            self.client.create_note(iid, item.note())

        if item.position():
            self.task_position(iid, item.position())

        for s in item.sub_items():
            self.client.create_subtask(iid, s.title(), completed=s.selected())
        return iid

    def update_item(self, task, item, rebuild_notes=False, rebuild_subs=False):
        iid = task['id']

        if rebuild_subs:
            for sub in self.client.get_task_subtasks(iid):
                self.client.delete_subtask(sub['id'], sub['revision'])

            for sub_item in item.sub_items():
                self.client.create_subtask(iid, sub_item.title(), completed=sub_item.selected())
        else:
            for sub in self.client.get_task_subtasks(iid):
                for sub_item in item.sub_items():
                    if sub_item.title() == sub['title']:
                        self.client.update_subtask(sub['id'], sub['revision'], completed=sub_item.selected())
                        break

        if rebuild_notes:
            notes = self.client.get_task_notes(iid)
            if len(notes) == 1:
                if notes[0]['content'].encode('utf-8') != item.note():
                    self.client.delete_note(notes[0]['id'], notes[0]['revision'])
                    if item.note():
                        self.client.create_note(iid, item.note())
            else:
                if item.note():
                    self.client.create_note(iid, item.note())

        if 'title' in task and item.title() != task['title']:
            while True:
                try:
                    new_revision = self.client.get_task(iid)['revision']
                    resp = self.client.update_task(iid, new_revision, title=item.title())
                    return resp['revision']
                except ValueError:
                    pass

        if rebuild_notes or rebuild_subs:
            return self.client.get_task(iid)['revision']
        else:
            return task['revision']

    def delete_item(self, task):
        while True:
            try:
                new_revision = self.client.get_task(task['id'])['revision']
                self.client.delete_task(task['id'], new_revision)
                return
            except ValueError:
                pass

    def task_position(self, iid, position):
        pos = self.client.get_task_positions_objs(self.list_id)[0]
        v = pos['values']
        if len(v) <= abs(position) or iid != v[position]:
            if iid in v:
                v.remove(iid)
            if position == -1:
                v.append(iid)
            else:
                if position < 0:
                    position += 1
                v.insert(position, iid)
            self.client.update_task_positions_obj(pos['id'], pos['revision'], v)


text:
from fuel.datasets import H5PYDataset
from fuel.utils import find_in_data_path

class Adult(H5PYDataset):
    filename = 'adult.hdf5'

    def __init__(self, which_sets, **kwargs):
        kwargs.setdefault('load_in_memory', True)
        super(Adult, self).__init__(
            file_or_path=find_in_data_path(self.filename),
            which_sets=which_sets, **kwargs
        )


text:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#ifdef _WIN32
#include <windows.h>
#include <winsock.h>
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <sys/select.h>
#include <netdb.h>
#endif
#include "net.h"

/*
 * Read a full line (terminated by \n) from socket sock, divide it into
 * command and argument and store it accordingly in pointers command and arg
 * name: recvline
 * @param   sock      socket from which the line shall be read
 * @param   command   pointer to memory area where command shall be stored
 * @param   arg       pointer to memory area where argument shall be stored
 *                    May be NULL, in which case no split in command and
 *                    argument is perfomed.
 * @return  0 on error (connection closed), 1 otherwise
 */
int recvline(int sock, char *command, char *arg)
{
  int readlength;

  memset(buffer, 0, bufsize);

  while((readlength = recv(sock, buffer+strlen(buffer), 1, 0)) == 1 && buffer[strlen(buffer) - 1] != '\n' && strlen(buffer) < bufsize);

  if(readlength == 0 || readlength == -1)
  {
    // Connection closed
    return 0;
  }

  // strip newline
  *(buffer + strlen(buffer) - 1) = '\0';

  // split command and argument
  if(strchr(buffer, ' ') != NULL && arg != NULL)
  {
    strcpy(arg, strchr(buffer, ' ')+1);
    *(strchr(buffer, ' ')) = '\0';
  }
  else
    strcpy(arg, "");
  strcpy(command, buffer);
#ifdef DEBUG
  if(debug >= 3)
    fprintf(logfile, "Received: %s %s\n", command, arg);
#endif
  return 1;
}

/*
 * Send a full line (terminated by \n, which is added automatically) to the
 * socket sock
 * name: sendline
 * @param   sock    socket to which shall be written
 * @param   str     string that shall be written WITHOUT terminating \n
 * @return  0 on error (connection closed), 1 otherwise
 */
int sendline(int sock, const char *str)
{
  char *buf;
  buf = malloc(strlen(str)+2);
  memset(buf, 0, strlen(str)+2);
  strcpy(buf, str);
  *(buf + strlen(buf)) = '\n';
#ifdef DEBUG
  if(debug >= 3)
    fprintf(logfile, "Sending: %s", buf);
#endif
  if(send(sock, buf, strlen(buf), 0) != strlen(buf))
  {
    // Connection closed
    free(buf);
    return 0;
  }
  free(buf);
  return 1;
}


text:
#pragma once

#include <stdexcept>

namespace ceema {
    /**
     * Exception occurring at session level
     */
    class session_exception : public std::runtime_error {
        using std::runtime_error::runtime_error;
    };

    /**
     * Exception occurring at Threema protocol level
     */
    class protocol_exception : public std::runtime_error {
        using std::runtime_error::runtime_error;
    };

    class packet_type_exception : public protocol_exception {
        using protocol_exception::protocol_exception;
    };

    /**
     * Exception occurring when handling Threema message packets
     */
    class message_exception : public std::runtime_error {
        using std::runtime_error::runtime_error;
    };

}


text:
/// <reference path="../_references.ts"/>

module jsCommon {
    // NOTE: this file includes standalone utilities that should have no dependencies on external libraries, including jQuery.

    /**
     * Interface to help define objects indexed by number to a particular type.
     */
    export interface INumberDictionary<T> {
        [key: number]: T;
    }

    /**
     * Interface to help define objects indexed by name to a particular type.
     */
    export interface IStringDictionary<T> {
        [key: string]: T;
    }

    /**
     * Extensions for Enumerations.
     */
    export module EnumExtensions {
        /**
         * Gets a value indicating whether the value has the bit flags set.
         */
        export function hasFlag(value: number, flag: number): boolean {
            debug.assert(!!flag, 'flag must be specified and nonzero.');

            return (value & flag) === flag;
        }

        /**
         * Sets a value of a flag without modifying any other flags.
         */
        export function setFlag(value: number, flag: number): number {
            debug.assert(!!flag, "flag must be specified and nonzero.");
            return value |= flag;
        }

        /**
         * Resets a value of a flag without modifying any other flags.
         */
        export function resetFlag(value: number, flag: number): number {
            debug.assert(!!flag, "flag must be specified and nonzero.");
            return value &= ~flag;
        }

        /**
         * According to the TypeScript Handbook, this is safe to do.
         */
        export function toString(enumType: any, value: number): string {
            return enumType[value];
        }
    }

    /**
     * Extensions to String class.
     */
    export module StringExtensions {
        /**
         * Checks if a string ends with a sub-string.
         */
        export function endsWith(str: string, suffix: string): boolean {
            debug.assertValue(str, 'str');
            debug.assertValue(suffix, 'suffix');

            return str.indexOf(suffix, str.length - suffix.length) !== -1;
        }
    }

    export module LogicExtensions {
        export function XOR(a: boolean, b: boolean): boolean {
            return (a || b) && !(a && b);
        }
    }

    export module JsonComparer {
        /**
         * Performs JSON-style comparison of two objects.
         */
        export function equals<T>(x: T, y: T): boolean {
            if (x === y)
                return true;

            return JSON.stringify(x) === JSON.stringify(y);
        }
    }

    /**
     * Values are in terms of 'pt'
     * Convert to pixels using PixelConverter.fromPoint
     */
    export module TextSizeDefaults {
        /**
         * Stored in terms of 'pt'
         * Convert to pixels using PixelConverter.fromPoint
         */
        export const TextSizeMin: number = 8;

        /**
         * Stored in terms of 'pt'
         * Convert to pixels using PixelConverter.fromPoint
         */
        export const TextSizeMax: number = 40;

        const TextSizeRange: number = TextSizeMax - TextSizeMin;

        /**
         * Returns the percentage of this value relative to the TextSizeMax
         * @param textSize - should be given in terms of 'pt'
         */
        export function getScale(textSize: number) {
            return (textSize - TextSizeMin) / TextSizeRange;
        }

    }

    export module PixelConverter {
        const PxPtRatio: number = 4 / 3;
        const PixelString: string = 'px';

        /**
         * Appends 'px' to the end of number value for use as pixel string in styles
         */
        export function toString(px: number): string {
            return px + PixelString;
        }

        /**
         * Converts point value (pt) to pixels
         * Returns a string for font-size property
         * e.g. fromPoint(8) => '24px'
         */
        export function fromPoint(pt: number): string {
            return toString(fromPointToPixel(pt));
        }

        /**
       * Converts point value (pt) to pixels
       * Returns a number for font-size property
       * e.g. fromPoint(8) => 24px
       */
        export function fromPointToPixel(pt: number): number {
            return (PxPtRatio * pt);
        }

        /**
         * Converts pixel value (px) to pt
         * e.g. toPoint(24) => 8
         */
        export function toPoint(px: number): number {
            return px / PxPtRatio;
        }
    }
}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<title>OffCanvas Navigation</title>
		<meta name="description" content="OffCanvas Navigation">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link rel="stylesheet" href="../offcanvas.css">
		<link rel="stylesheet" href="demo.css">

			<span data-label="Mobile nav" data-label-back="< Back">

Item 1

Item 2 lorem ipsum

Item 3 duis aute irure

Item 4 excepteur

Item 1

Item 2 lorem ipsum

Item 3 duis aute irure

Item 4 excepteur

Item 1

Item 2 lorem ipsum

Item 3 is a long item  duis aute irure  ullamco laboris nisi ut aliquip exullamco laboris  ea

Item 4 excepteur

Item 1

Item 2 lorem ipsum

Item 3 duis aute irure

Item 4 excepteur

Item 4 excepteur

Item 1

Item 2 lorem ipsum

Item 3 duis aute irure

Item 4 excepteur

Item 1

Item 2 lorem ipsum

Item 3 duis aute irure

Item 4 excepteur

Item 1

Item 2 lorem ipsum

Item 3 duis aute irure

Item 4 excepteur

Header of the page goes here...

Main content goes here...

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Footer of the page goes here...


text:
/*flexberryautogenerated="true"*/
namespace IIS.Ипподром
{
    using System;
    using ICSSoft.STORMNET.Web.Controls;

    using Resources;

    public partial class КонюшняL : BaseListForm<Конюшня>
    {
        /// <summary>
        /// Конструктор без параметров,
        /// инициализирует свойства, соответствующие конкретной форме.
        /// </summary>
        public КонюшняL() : base(Конюшня.Views.КонюшняL)
        {
            EditPage = КонюшняE.FormPath;
        }

        /// <summary>
        /// Путь до формы.
        /// </summary>
        public static string FormPath
        {
            get { return "~/forms/Horse/KonyushnyaL.aspx"; }
        }

        /// <summary>
        /// Вызывается самым первым в Page_Load.
        /// </summary>
        protected override void Preload()
        {
        }

        /// <summary>
        /// Вызывается самым последним в Page_Load.
        /// </summary>
        protected override void Postload()
        {
        }
    }
}


text:
package org.apache.camel.processor;

import java.io.File;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.processor.idempotent.FileIdempotentRepository;
import org.apache.camel.spi.IdempotentRepository;

/**
 * @version $Revision$
 */
public class FileIdempotentTrunkStoreTest extends ContextTestSupport {
    protected Endpoint startEndpoint;
    protected MockEndpoint resultEndpoint;
    private File store = new File("target/idempotentfilestore.dat");
    private IdempotentRepository<String> repo;

    public void testTrunkFileStore() throws Exception {
        resultEndpoint.expectedBodiesReceived("A", "B", "C", "D", "E");

        sendMessage("AAAAAAAAAA", "A");
        sendMessage("BBBBBBBBBB", "B");
        sendMessage("CCCCCCCCCC", "C");
        sendMessage("AAAAAAAAAA", "A");
        sendMessage("DDDDDDDDDD", "D");
        sendMessage("BBBBBBBBBB", "B");
        sendMessage("EEEEEEEEEE", "E");

        resultEndpoint.assertIsSatisfied();
        resultEndpoint.reset();
        resultEndpoint.expectedBodiesReceived("Z", "X");

        // should trunk the file store
        sendMessage("ZZZZZZZZZZ", "Z");

        // load in new store and verify we only have the last 5 elements
        IdempotentRepository<String> repo2 = FileIdempotentRepository.fileIdempotentRepository(store);
        repo2.start();
        assertFalse(repo2.contains("AAAAAAAAAA"));
        assertTrue(repo2.contains("BBBBBBBBBB"));
        assertTrue(repo2.contains("CCCCCCCCCC"));
        assertTrue(repo2.contains("DDDDDDDDDD"));
        assertTrue(repo2.contains("EEEEEEEEEE"));
        assertTrue(repo2.contains("ZZZZZZZZZZ"));

        // should trunk the file store
        sendMessage("XXXXXXXXXX", "X");

        resultEndpoint.assertIsSatisfied();
        assertFalse(repo.contains("BBBBBBBBBB"));
        assertTrue(repo.contains("XXXXXXXXXX"));
    }

    protected void sendMessage(final Object messageId, final Object body) {
        template.send(startEndpoint, new Processor() {
            public void process(Exchange exchange) {
                // now lets fire in a message
                Message in = exchange.getIn();
                in.setBody(body);
                in.setHeader("messageId", messageId);
            }
        });
    }

    @Override
    protected void setUp() throws Exception {
        // delete file store before testing
        if (store.exists()) {
            store.delete();
        }

        // 5 elements in cache, and 50 bytes as max size limit for when trunking should start
        repo = FileIdempotentRepository.fileIdempotentRepository(store, 5, 50);
        repo.start();

        super.setUp();
        startEndpoint = resolveMandatoryEndpoint("direct:start");
        resultEndpoint = getMockEndpoint("mock:result");
    }

    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            public void configure() {
                from("direct:start")
                    .idempotentConsumer(header("messageId"), repo)
                    .to("mock:result");
            }
        };
    }
}


text: load File.expand_path("../../tasks/gitinfos.rake", __FILE__)


text:
var App = require('app');
var _ = require('underscore');

var Match = App.Model.extend({
	initialize: function() {
		this.resetPlayers();
		// this.listenTo(this, "change:players", this.resetPlayers);
	},
	toJSON: function() {
		var data = this._super("toJSON", arguments);

		if (data.type) {
			data.maxPlayers = data.type.split('v').map(parseFloat).reduce(function(a,b) { return a+b; });
		}

		return data;
	},
	parse: function() {
		var data = this._super("parse", arguments);

		this.resetPlayers(data.players);

		return data;
	},
	resetPlayers: function(data) {
		if (!this.players) {
			this.players = new App.Collection(this.get('players'), {
				model: require('./matchPlayer')
			});
		}
		this.players.set(data || this.get('players'));
	},
	getPlayer: function(team, position) {
		var matchPlayer = this.getMatchPlayer(team, position);
		return matchPlayer ? matchPlayer.user : null;
	},
	getMatchPlayer: function(team, position) {
		var result = this.players.find(function(player) {
			if (position && player.get('position') !== position) {
				return false;
			}
			return player.get('team') === team;
		});
		return result;
	},
	sit: function(options) {
		var self = this;
		return App.rpcgw.get('matchSit', options)
			.done(function(data) {
				self.set(data.match);
				self.resetPlayers();
			});
	},
	finish: function(scoreOne, scoreTwo) {
		return App.rpcgw.get('matchFinish', {
			scoreOne: scoreOne,
			scoreTwo: scoreTwo
		}).done(function() {
			App.user.set({
				currentMatch: null,
				match_state: 'inactive'
			})
		});
	}
}, {
	noun: 'match'
});

module.exports = Match;


text:
package org.fiolino.common.util;

/**
 * This is thrown if two types are not assignable by each other where it should be.
 */
public class NotAssignableException extends RuntimeException {
    private static final long serialVersionUID = -1512289958073742778L;

    NotAssignableException(String message) {
        super(message);
    }
}


text:
class CreateIndexedRecord < ActiveRecord::Migration
  def change
    create_table :indexed_records do |t|
      t.references :index_job, foreign_key: true
      t.references :harvested_record, foreign_key: true
      t.datetime :submitted_time
      t.integer :status, default: 0
    end

    # TODO: Remove these once foreign_key works
    add_index :indexed_records, :index_job_id
    add_index :indexed_records, :harvested_record_id
  end
end


text:
<?php

/**
 * This is the model class for table "video".
 *
 * The followings are the available columns in table 'video':
 * @property integer $video_id
 * @property string $title
 * @property string $url
 * @property string $content
 * @property integer $create_time
 * @property integer $update_time
 */
class Video extends CActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'video';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('create_time, update_time', 'numerical', 'integerOnly'=>true),
			array('title, url', 'length', 'max'=>255),
			array('author, content', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('video_id, title, url, content, create_time, update_time', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'video_id' => 'Video',
			'title' => 'Title',
			'url' => 'Url',
            'author' => 'Author',
			'content' => 'Content',
			'create_time' => 'Create Time',
			'update_time' => 'Update Time',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('video_id',$this->video_id);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('url',$this->url,true);
		$criteria->compare('content',$this->content,true);
		$criteria->compare('create_time',$this->create_time);
		$criteria->compare('update_time',$this->update_time);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Video the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    public function beforeSave() {
        if (parent::beforeSave()) {
            if ($this->isNewRecord) {
                $this->create_time = $this->update_time = time();
            }
            else
                $this->update_time = time();
            return true;
        }
        else
            return false;
    }
}


text:
import React, { Component } from 'react';
import './Score.css';

class Score extends Component {
	render() {
		return (

				{this.props.points}
				{this.props.time}

		);
	}
}

export default Score;


text:
import { injectable } from 'inversify';
import { GitRepositoryWatcher } from '../git-repository-watcher';
import { Disposable, Event, Emitter } from '@theia/core';
import { GitStatusChangeEvent } from '../../common/git-watcher';

@injectable()
export class MockRepositoryWatcher implements GitRepositoryWatcher {

    private readonly onStatusChangedEmitter = new Emitter<GitStatusChangeEvent>();
    readonly onStatusChanged: Event<GitStatusChangeEvent> = this.onStatusChangedEmitter.event;

    sync(): Promise<void> {
        return Promise.resolve();
    }

    watch(): Disposable {
        return Disposable.create(() => { /* NOOP */ });
    }

}


text:
import json

from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.common.abstract_client import AbstractClient
from tencentcloud.soe.v20180724 import models

class SoeClient(AbstractClient):
    _apiVersion = '2018-07-24'
    _endpoint = 'soe.tencentcloudapi.com'
    _service = 'soe'

    def InitOralProcess(self, request):
        """初始化发音评估过程,每一轮评估前进行调用。语音输入模式分为流式模式和非流式模式,流式模式支持数据分片传输,可以加快评估响应速度。评估模式分为词模式和句子模式,词模式会标注每个音节的详细信息;句子模式会有完整度和流利度的评估。

        :param request: Request instance for InitOralProcess.
        :type request: :class:`tencentcloud.soe.v20180724.models.InitOralProcessRequest`
        :rtype: :class:`tencentcloud.soe.v20180724.models.InitOralProcessResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("InitOralProcess", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.InitOralProcessResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def KeywordEvaluate(self, request):
        """指定主题关键词词汇评估,分析语音与关键词的切合程度,可指定多个关键词,支持中文英文同时评测。分片传输时,尽量保证纯异步调用,即不等待上一个分片的传输结果边录边传,这样可以尽可能早的提供音频数据。音频源目前仅支持16k采样率16bit单声道编码方式,如有不一致可能导致评估不准确或失败。

        :param request: Request instance for KeywordEvaluate.
        :type request: :class:`tencentcloud.soe.v20180724.models.KeywordEvaluateRequest`
        :rtype: :class:`tencentcloud.soe.v20180724.models.KeywordEvaluateResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("KeywordEvaluate", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.KeywordEvaluateResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def TransmitOralProcess(self, request):
        """本接口可用于中英文发音评测数据传输。在使用本接口时需要注意:传输音频数据,必须在完成发音评估初始化接口之后调用,且SessonId要与初始化接口保持一致。分片传输时,尽量保证SeqId顺序传输(请确认SeqId由1开始)。音频源目前仅支持16k采样率16bit单声道编码方式,如有不一致可能导致评估不准确或失败。

        :param request: Request instance for TransmitOralProcess.
        :type request: :class:`tencentcloud.soe.v20180724.models.TransmitOralProcessRequest`
        :rtype: :class:`tencentcloud.soe.v20180724.models.TransmitOralProcessResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("TransmitOralProcess", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.TransmitOralProcessResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def TransmitOralProcessWithInit(self, request):
        """本接口可用于中英文发音评测。在使用本接口时需要注意:初始化并传输音频数据,分片传输时,尽量保证SeqId顺序传输(请确认SeqId由1开始)。音频源目前仅支持16k采样率16bit单声道编码方式,如有不一致可能导致评估不准确或失败。

        :param request: Request instance for TransmitOralProcessWithInit.
        :type request: :class:`tencentcloud.soe.v20180724.models.TransmitOralProcessWithInitRequest`
        :rtype: :class:`tencentcloud.soe.v20180724.models.TransmitOralProcessWithInitResponse`

        """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("TransmitOralProcessWithInit", params, headers=headers)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.TransmitOralProcessWithInitResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)


text:
package org.zstack.sdk;

public class VipInventory  {

    public java.lang.String uuid;
    public void setUuid(java.lang.String uuid) {
        this.uuid = uuid;
    }
    public java.lang.String getUuid() {
        return this.uuid;
    }

    public java.lang.String name;
    public void setName(java.lang.String name) {
        this.name = name;
    }
    public java.lang.String getName() {
        return this.name;
    }

    public java.lang.String description;
    public void setDescription(java.lang.String description) {
        this.description = description;
    }
    public java.lang.String getDescription() {
        return this.description;
    }

    public java.lang.String l3NetworkUuid;
    public void setL3NetworkUuid(java.lang.String l3NetworkUuid) {
        this.l3NetworkUuid = l3NetworkUuid;
    }
    public java.lang.String getL3NetworkUuid() {
        return this.l3NetworkUuid;
    }

    public java.lang.String ip;
    public void setIp(java.lang.String ip) {
        this.ip = ip;
    }
    public java.lang.String getIp() {
        return this.ip;
    }

    public java.lang.String state;
    public void setState(java.lang.String state) {
        this.state = state;
    }
    public java.lang.String getState() {
        return this.state;
    }

    public java.lang.String gateway;
    public void setGateway(java.lang.String gateway) {
        this.gateway = gateway;
    }
    public java.lang.String getGateway() {
        return this.gateway;
    }

    public java.lang.String netmask;
    public void setNetmask(java.lang.String netmask) {
        this.netmask = netmask;
    }
    public java.lang.String getNetmask() {
        return this.netmask;
    }

    public java.lang.String serviceProvider;
    public void setServiceProvider(java.lang.String serviceProvider) {
        this.serviceProvider = serviceProvider;
    }
    public java.lang.String getServiceProvider() {
        return this.serviceProvider;
    }

    public java.util.List peerL3NetworkUuids;
    public void setPeerL3NetworkUuids(java.util.List peerL3NetworkUuids) {
        this.peerL3NetworkUuids = peerL3NetworkUuids;
    }
    public java.util.List getPeerL3NetworkUuids() {
        return this.peerL3NetworkUuids;
    }

    public java.lang.String useFor;
    public void setUseFor(java.lang.String useFor) {
        this.useFor = useFor;
    }
    public java.lang.String getUseFor() {
        return this.useFor;
    }

    public java.sql.Timestamp createDate;
    public void setCreateDate(java.sql.Timestamp createDate) {
        this.createDate = createDate;
    }
    public java.sql.Timestamp getCreateDate() {
        return this.createDate;
    }

    public java.sql.Timestamp lastOpDate;
    public void setLastOpDate(java.sql.Timestamp lastOpDate) {
        this.lastOpDate = lastOpDate;
    }
    public java.sql.Timestamp getLastOpDate() {
        return this.lastOpDate;
    }

}


text:
namespace cylvionpp {
namespace phase {

namespace {

class Summon2Phase: public SummonPhase {
private:
    std::unique_ptr<Phase> NextPhase() override;
};

std::unique_ptr<Phase>
Summon2Phase::NextPhase()
{
    return Desertion();
}

} // namespace

std::unique_ptr<Phase>
Summon2()
{
    return std::make_unique<Summon2Phase>();
}

} // namespace phase
} // namespace cylvionpp


text:
A simple time logger, made in Angular 4.
Features:
* Add tasks per day
* Record time logs in realtime
* Add logs manually
* Get a summary
* Copy tasks from previous days
* Scroll through the past few days.

Go to the [DEMO](https://timelogg.herokuapp.com) for this app is available on Heroku.

## Heroku

### Create a Heroku app first (if you don't have already one)

```
heroku create --region eu timelogg
```

### Create a remote for heroku if it does not exits yet (if you don't have already one)

```
heroku git:remote -a timelogg
```
### Add MongoDB

You can use a free plan of [MongoLab](https://elements.heroku.com/addons/mongolab) for data storage:

```
heroku addons:create mongolab:sandbox
```

### Deploy

```
git push heroku master
```

### Open Heroku app in browser

```
heroku open
```


text:
/**
 *
 */
package mx.com.cct.atzintli.ds.entity.negocio;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

/**
 * @author Daniel Jiménez
 *
 */
@Entity
@Table
public class VentaDetalle {

	@Id
	@SequenceGenerator(name = "id_venta_producto_sequence", sequenceName = "id_venta_producto_sequence", allocationSize = 1)
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_venta_producto_sequence")
	@Column(name = "id_venta_producto")
	private Long id;

	@ManyToOne
	@JoinColumn(name = "id_producto")
	private Producto producto;

	@Column(name = "cantidad")
	private Double cantidad;

	/**
	 * Provee acceso de lectura al atributo id
	 *
	 * @return id
	 */
	public Long getId() {
		return id;
	}

	/**
	 * Provee acceso de escritura al atributo id reemplazando su
	 * valor con el del parametro id
	 *
	 * @param id
	 *            el valor de id a escribir
	 */
	public void setId(Long id) {
		this.id = id;
	}

	/**
	 * Provee acceso de lectura al atributo producto
	 *
	 * @return producto
	 */
	public Producto getProducto() {
		return producto;
	}

	/**
	 * Provee acceso de escritura al atributo producto reemplazando
	 * su valor con el del parametro producto
	 *
	 * @param producto
	 *            el valor de producto a escribir
	 */
	public void setProducto(Producto producto) {
		this.producto = producto;
	}

	/**
	 * Provee acceso de lectura al atributo cantidad
	 *
	 * @return cantidad
	 */
	public Double getCantidad() {
		return cantidad;
	}

	/**
	 * Provee acceso de escritura al atributo cantidad reemplazando
	 * su valor con el del parametro cantidad
	 *
	 * @param cantidad
	 *            el valor de cantidad a escribir
	 */
	public void setCantidad(Double cantidad) {
		this.cantidad = cantidad;
	}

}


text:
<!DOCTYPE html>

<title>Canvas test: 2d.text.draw.stroke.basic</title>

<link rel="stylesheet" href="/html/canvas/resources/canvas-tests.css">

2d.text.draw.stroke.basic

strokeText draws stroked text

Actual output:

<canvas id="c" class="output" width="100" height="50">
FAIL (fallback content)
</canvas>

Expected output:


text:
module IOActions(

    putChar,                   -- :: Char   -> IO ()
    putStr,                    -- :: String -> IO ()
    putStrLn,                  -- :: String -> IO ()
    print,                     -- :: Show a => a -> IO ()
    getChar,                   -- :: IO Char
    getLine,                   -- :: IO String
    getContents,               -- :: IO String
    readFile,                  -- :: String -> IO String
    writeFile,                 -- :: String -> IO ()

    FilePath, (</>),
    getDirectoryContents,      -- :: FilePath -> IO [FilePath]
    getDirectoryPaths,         -- :: FilePath -> IO [FilePath]
    getCurrentDirectory,       -- :: IO FilePath
    getHomeDirectory,          -- :: IO FilePath
    doesFileExist,             -- :: FilePath -> IO Bool
    doesDirectoryExist,        -- :: FilePath -> IO Bool
    createDirectory,           -- :: FilePath -> IO ()

    FileSystem(..),            -- :: data FileSystem = ...
    getFileSystem,             -- :: Int -> FilePath -> IO FileSystem

    getFiles,                  -- :: FilePath -> IO [FilePath]
    getDirectories,            -- :: FilePath -> IO [FilePath]

    system,                    -- :: String -> IO ExitCode
    getArgs,                   -- :: IO [String]
    getProgName,               -- :: IO String
    getEnv,                    -- :: String -> IO String

    runCommand,                -- :: String -> FilePath -> IO ExitCode

    inIO,                      -- :: (a -> b) -> a -> IO b
    (>>=),                     -- :: IO a -> (a -> IO b) -> IO b
    return,                    -- :: a -> IO a
    mapM,                      -- :: (a -> IO b) -> [a] -> IO [b]
    mapM_,                     -- :: (a -> IO b) -> [a] -> IO ()
    filterM,                   -- :: (a -> IO Bool) -> [a] -> IO [a]
    foldM,                     -- :: (a -> b -> IO a) -> a -> [b] -> IO a
    foldM_,                    -- :: (a -> b -> IO a) -> a -> [b] -> IO ()
    replicateM,                -- :: Int -> IO a -> IO [a]
    replicateM_,               -- :: Int -> IO a -> IO ()

    module Data.List,          -- :: isPrefixOf, isSuffixOf, ...

	graphviz,                  -- :: LabeledTree t => String -> t -> IO ()

 )  where

import Control.Monad
import System.IO
import System.Cmd
import System.Directory
import System.Environment
import System.Exit
import Data.List

import Treedot

inIO  :: (a -> b) -> a -> IO b
inIO f = return . f

runCommand :: String -> FilePath -> IO ExitCode
runCommand cmd path = system (cmd ++ " " ++ show path)

{-

readFile "tree.dot" >>= inIO (length . lines) >>= print
getCurrentDirectory >>= getDirectoryContents >>= print
getHomeDirectory    >>= getFileSystem 1 >>= inIO toDot >>= writeFile "tree.dot"
getCurrentDirectory >>= inIO (</> "Archive") >>= getFileSystem 3 >>= inIO toDot >>= writeFile "tree.dot"
getCurrentDirectory >>= getFiles >>= inIO sort >>= print
getCurrentDirectory >>= getFiles >>= inIO (filter (isSuffixOf ".lhs")) >>= mapM (\f -> readFile f >>= inIO (length . lines)) >>= inIO maximum >>= print
getCurrentDirectory >>= getFiles >>= inIO (filter (isSuffixOf ".lhs")) >>= mapM (\f -> readFile f >>= inIO (length . lines)) >>= inIO sum >>= print
getCurrentDirectory >>= getFiles >>= inIO (filter (isSuffixOf ".pdf")) >>= inIO head >>= runCommand "open"
getHomeDirectory >>= inIO (</> "local/lib") >>= getFileSystem 2 >>= inIO toDot >>= writeFile "tree.dot" >>= const (runCommand "open -a GraphViz" "tree.dot")
getCurrentDirectory >>= getFiles >>= inIO (filter (isSuffixOf "hs")) >>= mapM (runCommand "wc")

-}

getFiles        :: FilePath -> IO [FilePath]
getFiles path    = getDirectoryContents path
                   >>= inIO (filter (not . dotFile))
                   >>= filterM doesFileExist

getDirectories     :: FilePath -> IO [FilePath]
getDirectories path = getDirectoryContents path
                      >>= inIO (filter (not . dotFile))
                      >>= filterM doesDirectoryExist

dotFile           :: FilePath -> Bool
dotFile ('.':name) = True
dotFile other      = False

getDirectoryPaths :: FilePath -> IO [FilePath]
getDirectoryPaths path
                   = getDirectoryContents path >>= return . map (path </>)

(</>)  :: FilePath -> FilePath -> FilePath
p </> q = p ++ "/" ++ q

data FileSystem = File FilePath
                | Folder FilePath [FileSystem]
                | Foldep FilePath
                  deriving Show

instance Tree FileSystem where
  subtrees (File path)      = []
  subtrees (Folder name cs) = cs
  subtrees (Foldep path)    = []

instance LabeledTree FileSystem where
  label (File path)      = path
  label (Folder path cs) = path ++ "/"
  label (Foldep path)    = path ++ "..."

getFileSystem :: Int -> FilePath -> IO FileSystem
getFileSystem n path
 = getFileSystemDir n path path

getFileSystemDir :: Int -> FilePath -> FilePath -> IO FileSystem
getFileSystemDir n path name
 | n < 1     = return (Foldep name)
 | otherwise = getDirectoryContents path
               >>= inIO (filter (not . dotFile))
               >>= mapM (getFileSystemIn (n-1) path)
               >>= inIO (Folder name)

getFileSystemIn :: Int -> FilePath -> FilePath -> IO FileSystem
getFileSystemIn n parent child
 = doesDirectoryExist path
   >>= \b-> case b of
        True  -> getFileSystemDir n path child
        False -> return (File child)
   where path = parent </> child

graphviz       :: LabeledTree t => String -> t -> IO ()
graphviz path t = writeFile path (toDot t)
                  >> runCommand "open -a GraphViz" path
                  >> return ()


text:
ASTERISK_USER=${ASTERISK_USER:-asterisk}
ASTERISK_GROUP=${ASTERISK_GROUP:-${ASTERISK_USER}}

if [ "$1" = "" ]; then
  COMMAND="/usr/sbin/asterisk -T -W -U ${ASTERISK_USER} -p -vvvdddf"
else
  COMMAND="$@"
fi

if [ "${ASTERISK_UID}" != "" ] && [ "${ASTERISK_GID}" != "" ]; then
  # recreate user and group for asterisk
  # if they've sent as env variables (i.e. to macth with host user to fix permissions for mounted folders

  deluser asterisk && \
  addgroup -g ${ASTERISK_GID} ${ASTERISK_GROUP} && \
  adduser -D -H -u ${ASTERISK_UID} -G ${ASTERISK_GROUP} ${ASTERISK_USER} \
  || exit
fi

chown -R ${ASTERISK_USER}: /var/log/asterisk \
                           /var/lib/asterisk \
                           /var/run/asterisk \
                           /var/spool/asterisk
exec ${COMMAND}


text:
\documentclass[11pt]{article}

\usepackage{graphics}
\usepackage{url}
\usepackage{verbatim}
\usepackage{fullpage}
\usepackage{html}
%I don't like my paragraphs indented because we have lots of 1-line paragraphs with URLs or code after them
\setlength{\parindent}{0in}
%I like space between my paragraphs
\setlength{\parskip}{10pt}

\title{RL-Glue Matlab Codec 1.03 Manual }
\author{Brian Tanner :: brian@tannerpages.com}
\date{}

\begin{document}
\maketitle
\tableofcontents

\section{Introduction}

This document describes how to use the Matlab RL-Glue Codec, a software library that provides socket-compatibility with the RL-Glue Reinforcement Learning software library.  Matlab is a brand new codec, created specifically for the RL-Glue 3.0 release.  Special thanks (or pokes) should go to Dale, Doina, and Yaki who gave voices to the countless others who probably
have scorned us for not supporting Matlab earlier.  It turned out to not even be that difficult :)

For general information and motivation about the RL-Glue\footnote{\url{http://glue.rl-community.org/}} project, please refer to the documentation provided with that project.

This codec will allow you to create agents, environments, and experiment programs in Matlab.

This software project is licensed under the Apache-2.0\footnote{\url{http://www.apache.org/licenses/LICENSE-2.0.html}} license. We're not lawyers, but our intention is that this code
should be used however it is useful.  We'd appreciate to hear what you're using it for, and to get credit if appropriate.

This project has a home here:\\
\url{http://glue.rl-community.org/Home/Extensions/matlab-codec}

\subsection{Software Requirements}
To run agents, environments, and experiments created with this codec, you will need to have RL-Glue executable socket server (\texttt{rl\_glue(.exe)}) installed on your computer.  It is available in several packages at:\newline
\url{http://code.google.com/p/rl-glue-ext/wiki/RLGlueCore}

Compiling and running components with this codec requires Matlab.  The codec was developed on Matlab 7.6.0.x, it has not been tested extensively on other versions.  Reports from the community suggest that Matlab 7.5 or higher is required to run this codec.

This Matlab codec uses the RL-Glue Java Extension, which means that Matlab needs to be running with the Java Virtual Machine enabled (it is by default).  The Java extension does not need to be installed independently.

\textbf{Possible Contribution: }Someone with Matlab experience could help us find out what exact version of Matlab is required to use this codec, and could help us update the codec to be as robust as possible to older versions.

\subsection{Getting the Codec}
The codec can be downloaded either as a .tar.gz or can be checked out of the subversion repository where it is hosted.

The .tar.gz distribution can be found here:\newline
\url{http://code.google.com/p/rl-glue-ext/wiki/Matlab}

To check the code out of subversion:\newline
\small \texttt{svn checkout http://rl-glue-ext.googlecode.com/svn/trunk/projects/codecs/Matlab Matlab-Codec} \normalsize

\subsection{Installing the Codec}
This codec is package with a Matlab ``installer'' which copies the codec source files and the RL-Glue Java Extension JAR file to a user-configurable location and adds them to your Matlab path and Matlab Java classpaths.  This is the recommended way of using the codec.  Alternatively, you can skip the installer and setup these paths on your own.   This manual will assume that you are using the installer.

To run the installer, use the \texttt{installRLGlue()} function from within Matlab in the main directory of the package you downloaded.  This will suggest installing Matlab to your home directory at \texttt{\~{}/rl-glue/codecs/matlab}.  If you would prefer an alternate location, you can call the function with a path, like:
\begin{verbatim}
	>>installRLGlue('~/desired/path/to/codec')
\end{verbatim}

\subsection{Removing the Codec}
The Matlab codec can be uninstalled by deleting the directory that you installed it \newline(eg. \texttt{\~{}/rl-glue/codecs/matlab}), and using the Matlab path editor to remove the associated directories from your path.

\section{Sample Project}
We have included two example projects with this codec, located in the \texttt{examples} directory.  Each project contains an agent, environment, and experiment written for this Matlab codec.  The two projects are \texttt{skeleton} and \texttt{mines-sarsa-sample}.

The \texttt{skeleton} contains all of the bare-bones plumbing that is required to create an agent / environment / experiment with this codec and might be a good starting point for creating your own components.

The \texttt{mines-sarsa-sample} contains a fully functional tabular Sarsa learning algorithm, a discrete-observation grid world problem, and an experiment program that can run these together and gather results.  More details below in Section \ref{mines-sarsa-sample}.

In the following sections, we will describe the skeleton project.  Running and using the \texttt{mines-sarsa-sample} is analogous.

\subsection{Skeleton Agent}
\label{sec:agent}
We have provided a skeleton agent with the codec that is a good starting point for agents that you may write in the future.
It implements all the required functions and provides a good example of how create and run a simple agent.

There are several functions that need to be written. They are all contained in a single Matlab source file:
\begin{verbatim}
	examples/skeleton/skeleton_agent.m
\end{verbatim}

The \texttt{skeleton\_agent.m} file has a public function that returns a structure with function pointers to all of the required RL-Glue functions.  The structure looks like this:

\begin{verbatim}
>> theAgent=skeleton_agent()

theAgent =

       agent_init: @skeleton_agent_init
      agent_start: @skeleton_agent_start
       agent_step: @skeleton_agent_step
        agent_end: @skeleton_agent_end
    agent_cleanup: @skeleton_agent_cleanup
    agent_message: @skeleton_agent_message
\end{verbatim}

Alternatively, these different functions could each be in their own \texttt{skeleton\_agent\_}\{init, start, step, end, cleanup, message\}\texttt{.m} files.  This is a personal choice.

This agent does not learn anything and randomly chooses integer action $0$ or $1$.

You can compile and run the agent like:
\begin{verbatim}
	>$ cd examples/skeleton
	>$ theAgent=skeleton_agent();
	>$ runAgent(theAgent);
\end{verbatim}

\htmladdnormallink{\texttt{skeleton\_agent()}}{http://code.google.com/p/rl-glue-ext/source/browse/trunk/projects/codecs/Matlab/examples/skeleton/skeleton\_agent.m} creates a struct with function pointers to the other \texttt{skeleton\_agent} methods.  \htmladdnormallink{\texttt{runAgent(theAgent)}}{http://code.google.com/p/rl-glue-ext/source/browse/trunk/projects/codecs/Matlab/src/agent/runAgent.m} then
connects to RL-Glue and runs one step at a time until RL-Glue disconnects.

Alternatively, for a more interactive experience, you can run the agent manually one step at a time:
\begin{verbatim}
	>$ cd examples/skeleton/
	>$ theAgent=skeleton_agent()
	>$ connectAgent(theAgent);
	>$ runAgentLoop(theAgent);    %run one step
	>$ runAgentLoop(theAgent);    %run one step
	>$ runAgentLoop(theAgent);    %run one step
	   ...
\end{verbatim}

Using this method, you can stop and examine what your agent is learning, and potentially modify, visualize, or analyze it however you like.

You will see something like:
\begin{verbatim}
	>> runAgent(theAgent)
	RL-Glue Matlab Agent Codec Version: 1.0 ($Revision$)
	    Connecting to rl_glue at host: localhost on port 4096
\end{verbatim}

This means that the skeleton\_agent is running, and trying to connect to the \texttt{rl\_glue} executable server on the local machine through port $4096$!

You can kill the process by pressing \texttt{CTRL-c} on your keyboard.

The Skeleton agent is very simple and well documented, so we won't spend any more time talking about it in these instructions.
Please open it up and take a look.

\subsection{Skeleton Environment}
\label{sec:env}

We have provided a skeleton environment with the codec that is a good starting point for environments that you may write in the future.
It implements all the required functions and provides a good example of how to compile a simple environment.  This section will follow the same
pattern as the agent version (Section \ref{sec:agent}).  This section will be less detailed because many ideas are similar or identical.

The pertinent file is:
\begin{verbatim}
	examples/skeleton/skeleton_environment.m
\end{verbatim}

This environment is episodic, with 21 states, labeled $\{0, 1,\ldots,19,20\}$. States $\{0, 20\}$ are terminal and return rewards of $\{-1, +1\}$ respectively.  The other states return reward of $0$.
There are two actions, $\{0, 1\}$.  Action $0$ decrements the state number, and action $1$ increments it. The environment starts in state 10.

You can compile and run the environment like:
\begin{verbatim}
	>$ cd examples/skeleton
	>$ theEnv=skeleton_environment();
	>$ runEnvironment(theEnv);
\end{verbatim}

You will see something like:
\begin{verbatim}
	RL-Glue Matlab Environment Codec Version: 1.0 ($Revision$)
	    Connecting to rl_glue at host: localhost on port 4096
	\end{verbatim}

This means that the skeleton\_environment is running, and trying to connect to the \texttt{rl\_glue} executable server on the local machine through port $4096$!

You can kill the process by pressing \texttt{CTRL-c} on your keyboard.

The Skeleton environment is very simple and well documented, so we won't spend any more time talking about it in these instructions.
Please open it up and take a look.

\subsection{Skeleton Experiment}
We have provided a skeleton experiment with the codec that is a good starting point for experiments that you may write in the future.
It implements all the required functions and provides a good example of how to compile a simple experiment.  This section will follow the same
pattern as the agent version (Section \ref{sec:agent}).  This section will be less detailed because many ideas are similar or identical.

The pertinent files are:
\begin{verbatim}
	examples/skeleton/skeleton_experiment.m
\end{verbatim}

This experiment runs \texttt{RL\_Episode} a few times, sends some messages to the agent and environment, and then steps through one episode using \texttt{RL\_step}.

\begin{verbatim}
	>$ cd examples/skeleton
	>$ skeleton_experiment();
\end{verbatim}

You will see something like:
\begin{verbatim}
	Experiment starting up!
	RL-Glue Matlab Experiment Codec Version: 1.0 ($Revision$)
	    Connecting to rl_glue at host: 127.0.0.1 on port 4096
\end{verbatim}

This means that the skeleton\_experiment is running, and trying to connect to the \texttt{rl\_glue} executable server on the local machine through port $4096$!

You can kill the process by pressing \texttt{CTRL-c} on your keyboard.

The Skeleton experiment is very simple and well documented, so we won't spend any more time talking about it in these instructions.
Please open it up and take a look.

\subsection{Running All Three Components Together}
At this point, we've run each of the three components, now it's time to run them with the \texttt{rl\_glue} executable server.  As of version 1.03, the Matlab codec supports running any combination of agent, environment, and experiment, all from a single Matlab instance.  Note that although they are all in Matlab, they are still running over a local network connection to talk to the \texttt{rl\_glue} executable socket server.  In a future version, we may provide a local RL-Glue implementation so that they can work together without needing sockets. This capability already exists in both the RLGlueCore project for C/C++ and the RL-Glue Java Extension codec.

The following will work if you have the \texttt{rl\_glue} socket server is installed at \texttt{/usr/local/bin/rl\_glue}.

We will run all of the components in the Matlab interpreter.  Alternatively, it may be convenient to run \texttt{rl\_glue} in a terminal window of its own.
In the Matlab interpreter:
\begin{verbatim}
	>> cd examples/skeleton
	%Start the rl_glue socket server as a background process
	>> !/usr/local/bin/rl_glue &
	>> runAllTogether();
\end{verbatim}

If RL-Glue is not installed in the default location, you'll have to start the \texttt{rl\_glue} executable server using its full path (unless it's in your \texttt{PATH} environment variable):
\begin{verbatim}
	>> /path/to/rl-glue/bin/rl_glue &
\end{verbatim}

In the Matlab window, you should see the following if it worked:
\begin{verbatim}
	>> runAllTogether
	RL-Glue Matlab Agent Codec Version: 1.0 ($Revision$)
		Connecting to rl_glue at host: 127.0.0.1 on port 4096
		Agent Codec Connected
	RL-Glue Matlab Environment Codec Version: 1.0 ($Revision$)
		Connecting to rl_glue at host: 127.0.0.1 on port 4096
		Environment Codec Connected
	RL-Glue Matlab Experiment Codec Version: 1.0 ($Revision$)
		Connecting to rl_glue at host: 127.0.0.1 on port 4096
		Experiment Codec Connected
	Experiment starting up!
	RL_init called, the environment sent task spec: VERSION RL-Glue-3.0
	PROBLEMTYPE episodic DISCOUNTFACTOR 1.0 OBSERVATIONS INTS (0 20)
	ACTIONS INTS (0 1)  REWARDS (-1.0 1.0)
	EXTRA skeleton_environment(Matlab) by Brian Tanner.

	----------Sending some sample messages----------
	Agent responded to 'what is your name?' with:
	my name is skeleton_agent, Matlab edition!
	Agent responded to 'If at first you don't succeed; call it version 1.0  '
	with: I don\'t know how to respond to your message
	Environment responded to 'what is your name?' with:
	my name is skeleton_environment, Matlab edition!
	Environment responded to 'If at first you don't succeed;
	call it version 1.0  ' with:
	I don\'t know how to respond to your message

	----------Running a few episodes----------
	Episode 0	 48 steps 	 -1.000000 total reward	 natural end 1
	Episode 1	 100 steps 	 0.000000 total reward	 natural end 0
	Episode 2	 74 steps 	 -1.000000 total reward	 natural end 1
	Episode 3	 34 steps 	 -1.000000 total reward	 natural end 1
	Episode 4	 100 steps 	 0.000000 total reward	 natural end 0
	Episode 5	 1 steps 	 0.000000 total reward	 natural end 0
	Episode 6	 70 steps 	 1.000000 total reward	 natural end 1

	----------Stepping through an episode----------
	First observation and action were: 10 and: 1

	----------Summary----------
	It ran for 86, total reward was: -1.000000
\end{verbatim}

Congratulations, you have run an RL-Glue agent / environment / experiment together, all using the Matlab codec!

\subsection{Notes on Running Agents, Environments, and Experiments Together}
There is a function called \htmladdnormallink{\texttt{runRLGlueMultiExperiment}}{http://code.google.com/p/rl-glue-ext/source/browse/trunk/projects/codecs/Matlab/src/runRLGlueMultiExperiment.m} that facilities running any combination of agent, environment, and experiment together within Matlab.

This function takes a struct as a parameter, and the struct can have any combination of the following three fields set (at least one should be set):
\begin{description}
	\item[agent] An agent struct, like the one that is created by \texttt{skeleton\_agent}.
	\item[environment] An environment struct, like the one that is created by \texttt{skeleton\_environment}.
	\item[experiment] An experiment function pointer, like \texttt{@skeleton\_experiment}.
\end{description}

As long as you set one more of these fields, then you can call \texttt{runRLGlueMultiExperiment} and the Matlab codec will make sure that everything gets called when it needs to. Don't forget to make sure you run any components that you \textbf{don't} specify with another codec or another Matlab instance!

\subsection{Going Further -- Mines Sarsa Example Project}
\label{mines-sarsa-sample}
The \texttt{skeleton} sample project is extremely limited and only shows the mechanics of how RL-Glue components are structured using the Matlab codec.  The \texttt{mines-sarsa} sample project is much richer.

More details about the \texttt{mines-sarsa} sample project can be found at their RL-Library home:\newline
\url{http://library.rl-community.org/packages/mines-sarsa-sample}

\subsubsection{Sample-Mines-Environment}
\label{mines-sample}
The
\htmladdnormallink{mines environment}{http://code.google.com/p/rl-library/source/browse/trunk/projects/packages/examples/mines-sarsa-matlab/sample_mines_environment.m}
is internally a two-dimensional, discrete grid world where the agent receives a penalty per step until reaching a goal state, hopefully without stepping on any exploding land-mines along the way.  The (x,y) state is flattened into a discrete, scalar observation for the agent.  This environment can receive special messages from the experiment program to print the current state to the screen, and also to toggle between random starting states and a fixed starting-state specified by the experiment.

The task specification string\footnote{\url{http://glue.rl-community.org/Home/rl-glue/task-spec-language}} is created in a semi-automated way using the Java RL-Glue Extension task spec parser/builder.

\subsubsection{Samples-Sarsa-Agent}
\label{sarsa-sample}
The
\htmladdnormallink{SARSA agent}{http://code.google.com/p/rl-library/source/browse/trunk/projects/packages/examples/mines-sarsa-matlab/sample_sarsa_agent.m}
is a tabular learning agent that uses $\epsilon-greedy$ exploration as described in \htmladdnormallink{Reinforcement Learning: An Introduction}{http://www.cs.ualberta.ca/~sutton/book/ebook/node64.html} by Sutton and Barto.

The SARSA agent parses the task specification string using the Java RL-Glue Extension task spec parser.  This agent can receive special messages from the experiment program to pause/unpause learning, pause/unpause exploring, save the current value function to a file, and load the the value function from a file.

\subsubsection{Sample-Experiment}
The sample experiment program runs the show.  First, it alternates running the agent in the environment for a number of episodes, and telling the agent to pause learning so that the current performance can be evaluated.  These results are plotted with error-bars in a Matlab figure.

The sample experiment then tells the agent to save the value function to a file, and then resets the experiment (and agent) to initial conditions.  After verifying that the agent's initial policy is bad, the experiment tells the agent to load the value function from the file.  The agent is evaluated again using this previously-learned value function, and performance is dramatically better.

Finally, the experiment sends a message to specify that the environment should use a fixed (instead of random) starting state, and runs the agent from that fixed start state for a while.

\section{Who creates and frees memory?}
The RL-Glue technical manual has a section called \textit{Who creates and frees memory?}.  The general approach recommended there is to make a copy of data you want to keep beyond the method it was given to you.  The same rules of thumb from that manual should be followed when using the Matlab codec.  The observations and actions can be copied using the same techniques as \htmladdnormallink{the RL-Glue Java Extension}{http://glue.rl-community.org/Home/Extensions/java-codec}.

\section{Advanced Features}
\subsection{Task Specification Parser}
As of fall 2008, we've updated the task specification language:\\
\url{http://glue.rl-community.org/Home/rl-glue/task-spec-language}

The Matlab codec uses the task spec parser implementation from the RL-Glue Java Extension.  This task spec parser/builder can be used in environments to create task specification strings for \texttt{env\_init}.  The sample mines environment in Section \ref{mines-sample} provides an example of creating a task spec in this way.  There are also several advanced examples of this in the RL-Library\footnote{\url{http://library.rl-community.org}}.  The task spec parser/builder can also be used by agents to decode the task spec string for \texttt{agent\_init}.  The sample sarsa agent in Section \ref{sarsa-sample} demonstrates how to do this.

\subsection{Connecting on custom ports to custom hosts}
This section will explain how to set custom target IP addresses (to connect over the network) and custom ports (to run multiple experiments on one machine or to avoid firewall issues).
Sometimes you will want run the \texttt{rl\_glue} server on a port other than the default
($4096$) either because of firewall issues, or because you want to run multiple instances on the same machine.

In these cases, you can tell your Matlab agent, environment, or experiment program to connect on a custom port and/or to a custom host using the  \texttt{RL\_set\_port()} and \texttt{RL\_set\_host()} Matlab functions.

For example, the following code:
\begin{verbatim}
>> RL_set_port(4097);
>> RL_set_host('yahoo.ca')
>> cd examples/skeleton
>> skeleton_experiment();
\end{verbatim}

That command could give output like:
\begin{verbatim}
	RL-Glue Matlab Experiment Codec Version: 1.0 ($Revision$)
	     Connecting to rl_glue at host: yahoo.ca on port 4097
\end{verbatim}

This works for agents, environments, and experiments.  In practice though, remember that yahoo.ca probably isn't running an RL-Glue server.

You can specify the port, the host, neither, or both.  Ports must be numbers, hosts can be hostnames or ip addresses. Default port value is $4096$ and host is $127.0.0.1$.

Remember, on most *nix systems, you need \texttt{superuser} privileges to listen on ports lower than $1024$, so you probably want to pick one higher than that.

\section{Codec Specification Reference}
This section will explain how the RL-Glue types and functions are defined for the Matlab codec.  This isn't meant to be the most exciting section of this document, but it will
be handy.

Since the Matlab is built on top of the Java codec, many of the underlying data structures are from the Java codec.  We recommend checking out the Java documentation (\htmladdnormallink{PDF}{http://rl-glue-ext.googlecode.com/svn/trunk/projects/codecs/Java/docs/JavaCodec.pdf}) (\htmladdnormallink{HTML}{http://rl-glue-ext.googlecode.com/svn/trunk/projects/codecs/Java/docs/html/index.html}) (\htmladdnormallink{JAVADOC}{http://rl-glue-ext.googlecode.com/svn/trunk/projects/codecs/Java/javadocs/index.html}) for more information.

\subsection{Types}

\subsubsection{Simple Types}
Unlike the C/C++ codec, we will not be using \texttt{typedef} statements to create special labels for the types. Since Matlab is loosely typed, these things aren't so hard and
fast:
\begin{itemize}
	\item \textit{reward} is \texttt{double}
	\item \textit{terminal} is \texttt{int} (1 for terminal, 0 for non-terminal) We hope to replace these with boolean eventually.
	\item \textit{messages} come as Java \texttt{strings} and can be returned as Matlab strings
	\item \textit{task specifications} come as Java \texttt{strings} and can be returned as Matlab strings
\end{itemize}

\def\rat{RL\_Abstract\_Type}

\subsubsection{Structure Types}
\label{sec:structure-types}
All of the major structure types (observations, actions) come off the network as the appropriate object from the Java codec.
The \htmladdnormallink{Java codec manual}{http://glue.rl-community.org/Home/Extensions/java-codec} should have all the information required to understand those objects.

So in a given Matlab method, like \newline
\texttt{function theAction=skeleton\_agent\_step(theReward, theObservation)},
\texttt{theObservation} is actually of type: \texttt{org.rlcommunity.rlglue.codec.types.Observation}.

Java and Matlab play very well together, so you can do things like:
\begin{verbatim}
	>> testObs=org.rlcommunity.rlglue.codec.types.Observation();
	>> testObs.intArray=[1 2 3 4];
	>> testObs.doubleArray=[0.1 0.5];
	>> testObs.charArray='fun things!';
	>> testObs.toString()

	ans =

	numInts: 4
	numDoubles: 2
	numChars: 11
	 1 2 3 4 0.1 0.5 f u n   t h i n g s !
\end{verbatim}

\subsection{Functions}
\subsubsection{Agent Functions}
All agent constructor functions \textbf{should set} the same functions as our \htmladdnormallink{Skeleton agent}{http://code.google.com/p/rl-glue-ext/source/browse/trunk/projects/codecs/Matlab/examples/skeleton/skeleton_agent.m}.

Useful utility methods for connecting, disconnecting, and running with the \texttt{rl\_glue} executable server are in the \htmladdnormallink{\texttt{agent}}{http://code.google.com/p/rl-glue-ext/source/browse/trunk/projects/codecs/Matlab/src/agent} directory of the Matlab codec source.

\subsubsection{Environment Functions}
All environment constructor functions \textbf{should set} the same functions as our \htmladdnormallink{Skeleton environment}{http://code.google.com/p/rl-glue-ext/source/browse/trunk/projects/codecs/Matlab/examples/skeleton/skeleton_environment.m}.

Useful utility methods for connecting, disconnecting, and running with the \texttt{rl\_glue} executable server are in the \htmladdnormallink{\texttt{environment}}{http://code.google.com/p/rl-glue-ext/source/browse/trunk/projects/codecs/Matlab/src/environment} directory of the Matlab codec source.

\subsubsection{Experiments Functions}
All experiments \textbf{can call} the methods in the  \htmladdnormallink{\texttt{glue}}{http://code.google.com/p/rl-glue-ext/source/browse/trunk/projects/codecs/Matlab/src/glue} directory.
In this case we'll include their prototypes, because the source file is full of implementation details.

\section{Frequently Asked Questions}
We're waiting to hear your questions!

\subsection{Where can I get more help?}
\subsubsection{Online FAQ}
We suggest checking out the online RL-Glue Matlab Codec FAQ:\newline
\url{http://glue.rl-community.org/Home/Extensions/matlab-codec#TOC-Frequently-Asked-Questions}

The online FAQ may be more current than this document, which may have been distributed some time ago.

\subsubsection{Google Group / Mailing List}
First, you should join the RL-Glue Google Group Mailing List:\newline
\url{http://groups.google.com/group/rl-glue}

We're happy to answer any questions about RL-Glue.  Of course, try to search through previous messages first in case your question has been answered before.

\section{Credits and Acknowledgements}
Brian Tanner wrote the Matlab codec. He is also responsible for creating the installer, which is pretty nifty.  Yay Brian.

\subsection{Contributing}
If you would like to become a member of this project and contribute updates/changes to the code, please send a message to rl-glue@googlegroups.com.

\section*{Document Information}
\begin{verbatim}
Revision Number: $Rev$
Last Updated By: $Author$
Last Updated   : $Date$
$URL$
\end{verbatim}

\end{document}


text:
package com.anttoolkit.hbase.tasks.server;

import org.apache.tools.ant.*;

import com.anttoolkit.hbase.tasks.*;

public class CheckServerExistsTask extends GenericHBaseTask
{
	private String server;
	private String property;

	public void setServer(String name)
	{
		server = name;
	}

	public void setProperty(String property)
	{
		this.property = property;
	}

	@Override
	protected void doHadoopWork() throws BuildException
	{
		try
		{
			getServer(server);
		}
		catch (BuildException e)
		{
			setPropertyThreadSafe(property, Boolean.TRUE.toString());
			return;
		}

		setPropertyThreadSafe(property, Boolean.FALSE.toString());
	}

	@Override
	protected void hadoopValidate()
	{
		if (server == null || server.trim().isEmpty())
		{
			throw new BuildException("Server name should be specified");
		}

		if (property == null || property.trim().isEmpty())
		{
			throw new BuildException("Property name should be specified");
		}
	}
}


text:
            <button type="button" class="star-button star-conversation-bar-full" star-touch-end="onStopVoice()" star-touch-start="onVoice()" ng-show="isVoice" >按下录音</button>

            发送

功能1

功能2

功能3

功能4

功能5

功能6

功能7

功能8


text:
import abc

import six

from tempest.lib import auth
from tempest.lib import exceptions

@six.add_metaclass(abc.ABCMeta)
class CredentialProvider(object):
    def __init__(self, identity_version, name=None, network_resources=None,
                 credentials_domain=None, admin_role=None):
        """A CredentialProvider supplies credentials to test classes.

        :param identity_version: Identity version of the credentials provided
        :param name: Name of the calling test. Included in provisioned
                     credentials when credentials are provisioned on the fly
        :param network_resources: Network resources required for the
                                  credentials
        :param credentials_domain: Domain credentials belong to
        :param admin_role: Name of the role of the admin account
        """
        self.identity_version = identity_version
        self.name = name or "test_creds"
        self.network_resources = network_resources
        self.credentials_domain = credentials_domain or 'Default'
        self.admin_role = admin_role
        if not auth.is_identity_version_supported(self.identity_version):
            raise exceptions.InvalidIdentityVersion(
                identity_version=self.identity_version)

    @abc.abstractmethod
    def get_primary_creds(self):
        return

    @abc.abstractmethod
    def get_admin_creds(self):
        return

    @abc.abstractmethod
    def get_alt_creds(self):
        return

    @abc.abstractmethod
    def clear_creds(self):
        return

    @abc.abstractmethod
    def is_multi_user(self):
        return

    @abc.abstractmethod
    def is_multi_tenant(self):
        return

    @abc.abstractmethod
    def get_creds_by_roles(self, roles, force_new=False):
        return

    @abc.abstractmethod
    def is_role_available(self, role):
        return

class TestResources(object):
    """Readonly Credentials, with network resources added."""

    def __init__(self, credentials):
        self._credentials = credentials
        self.network = None
        self.subnet = None
        self.router = None

    def __getattr__(self, item):
        return getattr(self._credentials, item)

    def __str__(self):
        _format = "Credentials: %s, Network: %s, Subnet: %s, Router: %s"
        return _format % (self._credentials, self.network, self.subnet,
                          self.router)

    def set_resources(self, **kwargs):
        for key in kwargs:
            if hasattr(self, key):
                setattr(self, key, kwargs[key])

    @property
    def credentials(self):
        return self._credentials


text:
package org.yuanheng.cookjson;

import java.io.*;

import javax.json.JsonReader;
import javax.json.JsonWriter;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonParser;

import org.junit.Assert;
import org.junit.Test;

/**
 * @author	Heng Yuan
 */
public class CookJsonProviderTest
{
	@Test
	public void test1 () throws IOException
	{
		CookJsonProvider provider = new CookJsonProvider ();

		File srcFile = new File ("../tests/data/types.json".replace ('/', File.separatorChar));
		JsonParser p = provider.createParser (new FileInputStream (srcFile));
		StringWriter sw = new StringWriter ();
		JsonGenerator g = provider.createGenerator (sw);
		Utils.convert (p, g);
		p.close ();
		g.close ();

		Assert.assertEquals (Utils.getString (srcFile), sw.toString ());
	}

	@Test
	public void test2 () throws IOException
	{
		CookJsonProvider provider = new CookJsonProvider ();

		File srcFile = new File ("../tests/data/types.json".replace ('/', File.separatorChar));

		JsonReader r = provider.createReader (new InputStreamReader (new FileInputStream (srcFile), BOM.utf8));
		ByteArrayOutputStream bos = new ByteArrayOutputStream ();
		JsonWriter w = provider.createWriter (bos);

		w.write (r.read ());
		r.close ();
		w.close ();

		Assert.assertEquals (Utils.getString (srcFile).length (), new String (bos.toByteArray (), BOM.utf8).length ());
	}
}


text:
<?php

namespace Kahlan\Spec\Suite;

use Valit\Util\Val;

describe('Valit\Util\Val', function () {

    describe('::escape()', function () {

        it('escapes scalars', function () {
            expect(Val::escape('foo'))->toBe('"foo"');
            expect(Val::escape(42))->toBe('42');
            expect(Val::escape(9.2))->toBe('9.2');
            expect(Val::escape(true))->toBe('true');
        });

        it('escapes null', function () {
            expect(Val::escape(null))->toBe('null');
        });

        it('escapes resources', function () {
            // for instance Resource id #183 (curl)
            expect(Val::escape(curl_init()))->toMatch('/^Resource id #\d+ \(curl\)$/');
            expect(Val::escape(fopen('php://memory', 'r')))->toMatch('/^Resource id #\d+ \(stream\)$/');
        });

        it('escapes callables', function () {
            $closure = function () {
                return 'foo';
            };
            eval('class Val__escape__Invokable { function __invoke() {} }');
            expect(Val::escape($closure))->toBe('Callable ({closure})');
            expect(Val::escape([Val::class, 'toInt']))->toBe('Callable (Valit\Util\Val::toInt)');
            expect(Val::escape(new \Val__escape__Invokable()))->toBe('Callable (Val__escape__Invokable::__invoke)');
        });

        it('escapes DateTime objects', function () {
            eval('class Val__escape__DateTime extends DateTimeImmutable {}');

            expect(Val::escape(new \DateTime('2000-01-01 00:00:00')))
                ->toBe('DateTime (2000-01-01T00:00:00+00:00)');

            expect(Val::escape(new \DateTimeImmutable('2000-01-01 00:00:00')))
                ->toBe('DateTimeImmutable (2000-01-01T00:00:00+00:00)');

            expect(Val::escape(new \Val__escape__DateTime('2000-01-01 00:00:00')))
                ->toBe('Val__escape__DateTime (2000-01-01T00:00:00+00:00)');
        });

        it('escapes objects', function () {
            expect(Val::escape(new \stdClass()))->toBe('Object (stdClass)');
            expect(Val::escape((object) []))->toBe('Object (stdClass)');
            expect(Val::escape((json_decode('{}'))))->toBe('Object (stdClass)');
            expect(Val::escape(new \SimpleXMLElement('<r/>')))->toBe('Object (SimpleXMLElement)');
            expect(Val::escape(new \Exception()))->toBe('Object (Exception)');
        });

        it('escapes arrays', function () {
            expect(Val::escape([]))->toBe('Array (0 entries)');
            expect(Val::escape([1, 2, 3]))->toBe('Array (3 entries)');
            expect(Val::escape(new \ArrayIterator([1, 2, 3])))->not->toBe('Array (3 entries)');
        });
    });
});


text:
1.	Założenia:

•	Administrator wypożyczalni ma panel do zarządzania filmami.

•	Może dodawać nowe filmy zmieniać im statusy na wypożyczony itp.. Ma być moduł liczący cenę wypożyczenia i naliczający kary w przypadku nie zwrócenia filmu w terminie.

•	Admin może usuwać filmy z listy.

•	Admin może dodawać usuwać i zmieniać dane klienta.


text:
package it.rainbowbreeze.playtog.logic;

/**
 * Created by alfredomorresi on 03/01/15.
 */
public class PlayersUpdateEvent {
}


text:
layout: page
title: Ease of Adaption
dropdown: FREME-Showroom
pos: 2.2
---

FREME Ease of Adaption

Background

This examples shows how easy it is to adapt FREME for your application. Here we target browser developers. Adapation in this example means:

Choosing the language you want to process. Here we process text with the e-Entity service.

Choosing the data set to be used for enrichment. FREME provides several data sets on the fly.

More information

For more information visit the FREME API documentation, FREME on GitHub or the FREME homepage.

Try it out

In the form below enter some English text (or use this example) and click on the bottom <q>Call FREME e-Entity</q>. Also, adapt the language and the data set used for enrichment to your needs.

<form name="input">

Set the language of the input:

    <input type="radio" name="language" value="en" checked>English<input type="radio" name="language" value="de">German<input type="radio" name="language" value="nl">Dutch<input type="radio" name="language" value="fr">French<input type="radio" name="language" value="it">Italien<input type="radio" name="language" value="es">Spanish

Set the data set to be used for enrichment:

    <input type="radio" name="dataset" value="dbpedia" checked>DBpedia<input type="radio" name="dataset" value="onld">ONLD<input type="radio" name="dataset" value="geopolitical">Geopolitical ontology<input type="radio" name="dataset" value="viaf">VIAF<input type="radio" name="dataset" value="orcid">ORCID

    <textarea rows="4" cols="50" name="content"  id="content"></textarea>
</form>
<button onclick="sendFreme();">Call FREME e-Entity</button>
<button onclick="$('#out').empty().append('Output');">Refresh output</button>

Output appears here:

Output


text:
#pragma once
#ifndef _EFI_BOOT_H
#define _EFI_BOOT_H

#include <stddef.h>
#include <stdbool.h>
#include <stdint.h>

/**
 * Get the default boot entry
 *
 * @param[out] path to the EFI executable (or NULL, only return value os provided)
 * @param[in] len length of the buffer, pointed to by path.
 * @returns length of the path
 */
int efi_boot_get_default(char* path, size_t len);

/**
 * Get the current boot entry
 *
 * @param[out] path to the EFI executable (or NULL, only return value os provided)
 * @param[in] len length of the buffer, pointed to by path.
 * @returns length of the path
 */
int efi_boot_get_current(char* path, size_t len);

/**
 * Get the a boot entry with the privided number
 *
 * @param[in] entry nu,ber of the EFI boot entry
 * @param[out] path to the EFI executable (or NULL, only return value os provided)
 * @param[in] len length of the buffer, pointed to by path.
 * @returns length of the path
 */
int efi_boot_get_numbered(const uint16_t entry, char* path, size_t len);

/**
 * Determine the ESP from EFI variables set by systemd-boot
 *
 * @param[out] esp
 * @return true on success
 */
bool efi_boot_get_esp(char* esp);

#endif // _EFI_BOOT_H


text:
jQuery-mosaic-tiles
===================

Makes tiles fill the block as a mosaic


text:
package org.sakaiproject.tool.gradebook.ui;

import java.io.Serializable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.service.gradebook.shared.StaleObjectModificationException;
import org.sakaiproject.tool.gradebook.Assignment;
import org.sakaiproject.tool.gradebook.jsf.FacesUtil;

/**
 * Backing Bean for removing assignments from a gradebook.
 *
 * @author Josh Holtzman
 */
public class RemoveAssignmentBean extends GradebookDependentBean implements Serializable {
    private static final Log logger = LogFactory.getLog(RemoveAssignmentBean.class);

    // View maintenance fields - serializable.
    private Long assignmentId;
    private boolean removeConfirmed;
    private Assignment assignment;

    protected void init() {
        if (assignmentId != null) {
            assignment = getGradebookManager().getAssignment(assignmentId);
            if (assignment == null) {
                // The assignment might have been removed since this link was set up.
                if (logger.isWarnEnabled()) logger.warn("No assignmentId=" + assignmentId + " in gradebookUid " + getGradebookUid());

                // TODO Deliver an appropriate message.
            }
        }
    }

    public String removeAssignment() {
        if(removeConfirmed) {
            try {
                getGradebookManager().removeAssignment(assignmentId);
            } catch (StaleObjectModificationException e) {
                FacesUtil.addErrorMessage(getLocalizedString("remove_assignment_locking_failure"));
                return null;
            }
            String authzLevel = (getGradebookBean().getAuthzService().isUserAbleToGradeAll(getGradebookUid())) ?"instructor" : "TA";
            getGradebookBean().getEventTrackingService().postEvent("gradebook.deleteItem","/gradebook/"+getGradebookId()+"/"+assignment.getName()+"/"+authzLevel);
            FacesUtil.addRedirectSafeMessage(getLocalizedString("remove_assignment_success", new String[] {assignment.getName()}));
            return "overview";
        } else {
            FacesUtil.addErrorMessage(getLocalizedString("remove_assignment_confirmation_required"));
            return null;
        }
    }

    public String cancel() {
        // Go back to the Assignment Details page for this assignment.
        AssignmentDetailsBean assignmentDetailsBean = (AssignmentDetailsBean)FacesUtil.resolveVariable("assignmentDetailsBean");
        assignmentDetailsBean.setAssignmentId(assignmentId);
        return "assignmentDetails";
    }

    public Assignment getAssignment() {
        return assignment;
    }
    public void setAssignment(Assignment assignment) {
        this.assignment = assignment;
    }

    /**
	 * @return Returns the assignmentId.
	 */
	public Long getAssignmentId() {
		return assignmentId;
	}
	/**
	 * @param assignmentId The assignmentId to set.
	 */
	public void setAssignmentId(Long assignmentId) {
		this.assignmentId = assignmentId;
	}
	/**
	 * @return Returns the removeConfirmed.
	 */
	public boolean isRemoveConfirmed() {
		return removeConfirmed;
	}
	/**
	 * @param removeConfirmed The removeConfirmed to set.
	 */
	public void setRemoveConfirmed(boolean removeConfirmed) {
		this.removeConfirmed = removeConfirmed;
	}
}


text:
layout          : blocks/page-participant
title           : Adam Obrien
type            : participant
job-title       : Security Assurance Architect
company         : Oracle
travel-from     : London
image           : https://media.licdn.com/mpr/mpr/shrinknp_400_400/p/2/005/04a/086/1c3ff3d.jpg
linkedin        : adamlobrien
twitter          :
facebook        :
website         :
email           :
ticket          :
status          : empty
ticket          : 5x8h
working-sessions: SAMM - V2 Ground Rules, SAMM - Conducting Assessments, SAMM - Core Model Update 1 - Intro, SAMM - Core Model Update 2 - Dev Methods, A7 - Insufficient Attack Protection, Creating AppSec Teams, Securing the CI Pipeline, SAMM - Core Model Update 3 - Implementation, SAMM - Core Metrics, SAMM - Outreach and Marketing, SAMM - Standards and Compliance Mapping, Securing Legacy Applications, Machine Learning and Security, Scaling Static Analysis Reviews and Deployments
# add above a comma delimited list of the Working Sessions you would like to attend (use the session's title)
---

I'm the editor of Oracle's secure software development lifecycle called Oracle Software Security Assurance standards. My focus is making sure that our security assurance process is effective and efficient for all development models. I've recently worked on an overhaul of the process to better fit with cloud, devops, and agile development.

I'll be attending most of the Open SAMM sessions.
I'd like to attend the session on 'A7 - Insufficient Attack Protection' but this clashes with the Open SAMM sessions.


text:
using System;
using System.Diagnostics.CodeAnalysis;
using UELib.Core;

namespace UELib.Engine
{
    [UnrealRegisterClass]
    public class UTexture : UBitmapMaterial, IUnrealViewable
    {
        public UArray<MipMap> Mips;
        public bool HasComp;

        protected override void Deserialize()
        {
            base.Deserialize();

            if (_Buffer.Version > 160)
            {
                throw new NotSupportedException("UTexture is not supported for this build");
            }

            _Buffer.ReadArray(out Mips);
            Record(nameof(Mips), Mips);

            var bHasCompProperty = Properties.Find("bHasComp");
            if (bHasCompProperty != null)
            {
                HasComp = bool.Parse(bHasCompProperty.Value);
                if (HasComp)
                {
                    throw new NotSupportedException("UTexture of this kind is not supported");
                }
            }
        }

        [SuppressMessage("ReSharper", "MemberCanBePrivate.Global")]
        public struct MipMap : IUnrealSerializableClass
        {
            public byte[] Data;
            public int USize;
            public int VSize;
            public byte UBits;
            public byte VBits;

            public void Deserialize(IUnrealStream stream)
            {
                if (stream.Version >= 63)
                {
                    int positionAfterData = stream.ReadInt32();
                }

                Data = new byte[stream.ReadIndex()];
                stream.Read(Data, 0, Data.Length);
                USize = stream.ReadInt32();
                VSize = stream.ReadInt32();
                UBits = stream.ReadByte();
                VBits = stream.ReadByte();
            }

            public void Serialize(IUnrealStream stream)
            {
                throw new NotImplementedException();
            }
        }
    }
}


text:
using Grafika.Data.Mongo;
using Grafika.Services;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Net.Http;

namespace Grafika.TestConsole
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}