text:
<?php
/**
 *	Asset manager class.
 *
 *	@author      Raymond van Velzen <raymond@latunyi.com>
 *	@package     LatunyiFramework
 **/

namespace System\Core;

/**
 * The AssetManager takes a list of CSS/JS files,
 * uses their combined names to check for a merged file with their contents,
 * checks if the merged file is still up to date, and
 * if the file doesn't exist or is out of date, merges the files
 * together.
 */
class AssetManager
{
	/**
	 * Asset mgmt configuration
	 * @var \System\Core\DataContainer
	 */
	protected $config;

	/**
	 * Response object
	 * @var \System\Core\REs
	 */
	protected $response;

	/**
	 * Array with keys for CSS and JS files
	 * @var array
	 */
	protected $files;

	/**
	 * Constructor, receives the asset configuration and additional styles and scripts.
	 */
	public function __construct(\System\Core\DataContainer $assetConfig, $styles, $scripts)
	{
		if (!is_array($styles) || !is_array($scripts))
		{
			throw new \Exception('Styles and/or scripts are not arrays');
		}

		$this->files = array();
		$this->files['styles'] = $styles;
		$this->files['scripts'] = $scripts;

		$this->files['remote_styles'] = array();
		$this->files['remote_scripts'] = array();

		$this->config = $assetConfig;
	}

	/**
	 * Merges all CSS/JS assets (if enabled in config), and returns an StdClassobject
	 * with keys for each type (styles/scripts), with an array with either all files,
	 * or a list with a single combined file.
	 *
	 * $return object
	 */
	public function mergeAssets()
	{
		$result = new \StdClass();
		$types = array('styles', 'scripts');

		foreach ($types as $type)
		{
			$this->files[$type] = $this->getFileList($type);

			// Move remote files into separate list
			foreach ($this->files[$type] as $index => $file)
			{
				if (substr($file, 0, 2) == '//')
				{
					$this->files['remote_' . $type][] = $file;
					unset($this->files[$type][$index]);
				}
			}

			// If there are files to process...
			if (!empty($this->files[$type]))
			{
				if ($this->config->merging === true)
				{
					$this->files[$type] = array($this->mergeFiles($type));
				}

				$this->addVersionNumbers($this->files[$type], $type);
				$this->addPath($this->files[$type], $type);
			}

			$result->$type = $this->files[$type];

			// Prepend remote files, if any, before local files
			if (!empty($this->files['remote_' . $type]))
			{
				$result->$type = array_merge($this->files['remote_' . $type], $this->files[$type]);
			}
		}

		return $result;
	}

	/**
	 * Combines the list of default files and additional files for the given type.
	 *
	 * @param string $type
	 * @return array
	 */
	private function getFileList($type)
	{
		// Get list of default files
		$defaultFiles = array();
		if ($this->config->has($type))
		{
			$defaultFiles = $this->config->$type->asArray();
		}

		// Get list of additional files from response
		$additionalFiles = $this->files[$type];

		// Merge default and additional files
		$files = array_merge($defaultFiles, $additionalFiles);

		return $files;
	}

	/**
	 * Takes a list of file names of the given type, prepends the correct dir,
	 * finds their last modified timestamp, and appends that as a query string parameter
	 * to the filename.
	 *
	 * @param string $list List, by reference
	 * @param string $type
	 * @throws \Exception
	 */
	private function addVersionNumbers(&$list, $type)
	{
		// Add timestamp as version number
		$path = WEB_ROOT . constant(strtoupper($type) . '_PATH');
		foreach ($list as &$file)
		{
			$filePath = $path . '/' . $file;
			if (!file_exists($filePath))
			{
				throw new \Exception('Can\'t find file ' . $filePath);
			}
			$mtime = filemtime($filePath);
			$file .= '?v=' . $mtime;
		}
		unset($file);
	}

	/**
	 * Adds the path to the CSS/JS file to the filename.
	 *
	 * @param array $list	List, by reference
	 * @param string $type
	 */
	private function addPath(&$list, $type)
	{
		$path = PUBLIC_ROOT . constant(strtoupper($type) . '_PATH');
		foreach ($list as &$file)
		{
			$file = $path . '/' . $file;
		}
		unset($file);
	}

	/**
	 * Takes the loaded list of styles, concatenates their file names,
	 * makes a hash from that string, checks for a CSS file with that name;
	 * If exists, compare timestamp of combined file with timestamps of
	 * each of the input files. If not existing or out of date, the contents
	 * of all files are combined into one file, named with the hash.
	 *
	 * @param string $type
	 * @return string
	 * @throws \Exception
	 */
	private function mergeFiles($type)
	{
		$hash = md5(implode(';', $this->files[$type]));
		$combinedFileName = $hash . '.' . ($type == 'styles' ? 'css' : 'js');

		// Check file already exists
		$normalPath = WEB_ROOT . constant(strtoupper($type) . '_PATH');
		$shortCombinedFileName = $combinedFileName;
		$combinedFileName = $normalPath . '/' . $combinedFileName;

		$makeNew = true;
		if (file_exists($combinedFileName))
		{
			if ($this->config->has('autorefresh') && $this->config->autorefresh === true)
			{
				// Get modified timestamp
				$combinedMtime = filemtime($combinedFileName);

				// Compare with modified timestamps of each file
				$makeNew = false;
				foreach ($this->files[$type] as $sourceFile)
				{
					$sourceMtime = filemtime($normalPath . '/' . $sourceFile);
					if ($sourceMtime > $combinedMtime)
					{
						$makeNew = true;
						break;
					}
				}
			}
			else
			{
				$makeNew = false;
			}
		}

		if ($makeNew)
		{
			// Get contents of each file
			$content = '';
			foreach ($this->files[$type] as $sourceFile)
			{
				$content .= '/* ***** ' . $sourceFile . ' ***** */' . "\n";
				$content .= file_get_contents($normalPath . '/' . $sourceFile);
				$content .= "\n";
			}

			// Write to combined file
			file_put_contents($combinedFileName, $content);

			// Check file exists
			if (!file_exists($combinedFileName))
			{
				throw new \Exception('AssetManager: Can\'t find combined file ' . $combinedFileName);
			}

			if ($this->config->minify === true)
			{
				$this->minifyFiles(array($shortCombinedFileName), $type);
			}
		}

		return $shortCombinedFileName;
	}

	/**
	 * Minifies the given list of files of the given type.
	 * The commands for the minifier are taken from the config.
	 *
	 * @param array $files
	 * @param string $type
	 * @throws \Exception
	 */
	private function minifyFiles($files, $type)
	{
		if (!is_array($files))
		{
			throw new \Exception('AssetManager: Files is not an array.');
		}
		foreach ($files as $file)
		{
			$path = WEB_ROOT . constant(strtoupper($type) . '_PATH');
			$file = $path . '/' . $file;
			$cmd = str_replace('[filename]', $file, $this->config->minify_commands->$type);
			$result = shell_exec($cmd);
		}
	}

}


text:
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Configuration
Imports System.Web.UI.WebControls

Public Class USER_BLOCKING
    Inherits System.Web.UI.Page
    Dim conn As New SqlConnection(ConfigurationManager.AppSettings("ConnectionStringPORTAL"))
    Dim strQuery As String = "SELECT USER_NAME,ACCOUNT_STATUS LOCKED,BLOCKED,DISABLED FROM ADMIN_MAPS_USER_MASTER WHERE 1=1 "
    Dim cmd As New SqlCommand
    Dim da As New SqlDataAdapter
    Dim ds As New DataSet
    Dim objABProCommonClass As New HelperClass

    Protected WithEvents lnkLogout As System.Web.UI.WebControls.LinkButton
    Protected WithEvents lnkHome As System.Web.UI.WebControls.LinkButton
    Protected WithEvents Button1 As System.Web.UI.WebControls.Button
    Protected WithEvents MainLabel As System.Web.UI.WebControls.Label
    Protected WithEvents Btn_Logout As System.Web.UI.WebControls.Button

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region
    'load page and bind datagrid & bind ddlUserName dropdown

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        'Session("UserCode") = "ADMIN"

        Response.Buffer = True
        Response.ExpiresAbsolute = DateTime.Now.AddDays(-1.0)
        Response.Expires = 0
        Response.CacheControl = "no-cache"

        If Session("UserCode") = "" Then
            Response.Write("<script language=javascript>alert('Your Session Has EXPIRE/NOT LOGGED  IN Please Login Again.')</script>")
            Response.Redirect("../Master/index.aspx")
        End If

        If Not Page.IsPostBack Then
            '   To Check User Rights
            Dim strchk As String = objABProCommonClass.CheckSession(Session("UserCode"), System.IO.Path.GetFileName(Request.PhysicalPath))
            If strchk = "INVALID" Then
                Session("HomeFlag") = "N"
                Session("UserCode") = ""
                Response.Redirect("../Master/index.aspx")
            End If

            objABProCommonClass.loaddropdown(ddlUserName, "select distinct user_name from ADMIN_MAPS_USER_MASTER WHERE USER_NAME <>'ADMIN' AND DISABLED <> 'Y' UNION ALL select distinct '- - Select - -' user_name from ADMIN_MAPS_USER_MASTER WHERE USER_NAME <> 'ADMIN' ORDER BY user_name", conn, "user_name", "user_name")
            bindDataToGrid()
        End If

        'To enable back btn
        Response.Write("<script language=javascript>window.history.forward(1)</script>")
    End Sub

    'bind data to datagrid
    Private Sub bindDataToGrid()

        Dim prmSelectUser As New SqlParameter("SelectUser", SqlDbType.VarChar, 50)
        Dim prmDisabled As New SqlParameter("Disabled", SqlDbType.VarChar, 1)

        If ddlUserName.SelectedItem.Text.Trim <> "- - Select - -" Then
            strQuery = strQuery & "  and  RTRIM(LTRIM(USER_NAME))=RTRIM(LTRIM(@SelectUser)) "
            prmSelectUser.Value = ddlUserName.SelectedItem.Text.Trim
            cmd.Parameters.Add(prmSelectUser)
        End If

        Dim prmUSERNAME As New SqlParameter("@USERNAME", SqlDbType.VarChar, 50)

        prmUSERNAME.Value = "ADMIN"
        prmDisabled.Value = "Y"
        cmd.Parameters.Add(prmUSERNAME)
        cmd.Parameters.Add(prmDisabled)

        strQuery = strQuery & " AND USER_NAME <>RTRIM(LTRIM(@USERNAME)) AND DISABLED <> @Disabled order by USER_NAME  "
        cmd.CommandText = strQuery
        cmd.Connection = conn
        conn.Open()
        da.SelectCommand = cmd
        da.Fill(ds)

        Datagrid2.DataSource = ds
        Datagrid2.DataBind()
        conn.Close()
    End Sub
    'fill the the datagrid with records
    Private Sub lnkQuery_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnkQuery.Click
        Datagrid2.CurrentPageIndex = 0
        bindDataToGrid()
    End Sub
    'this is use to select all records or unselect all records
    Private Sub DataGrid2_ItemCommand(ByVal source As System.Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
        If e.Item.ItemType = ListItemType.Header Then
            Dim lnk As LinkButton = e.Item.FindControl("lnkSelectAll")
            Dim dgItem As DataGridItem
            Dim chkSelected As New System.Web.UI.WebControls.CheckBox
            If lnk.Text = "Select All" Then
                lnk.Text = "DeSelect All"
                For Each dgItem In Datagrid2.Items
                    chkSelected = dgItem.FindControl("checkbox1")
                    chkSelected.Checked = True
                Next
            Else
                lnk.Text = "Select All"
                For Each dgItem In Datagrid2.Items
                    chkSelected = dgItem.FindControl("checkbox1")
                    chkSelected.Checked = False
                Next
            End If
        End If
    End Sub
    'this is use to set pagination paroperty to datagrid
    Private Sub DataGrid2_PageIndexChanged(ByVal source As System.Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs)
        Datagrid2.CurrentPageIndex = e.NewPageIndex
        bindDataToGrid()
    End Sub
    'this is use to redirect page to link1(home page)
    Private Sub lnkHome_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnkHome.Click
        Session("HomeFlag") = "Y"
        Response.Redirect(objABProCommonClass.mapLink(Request.Path))
    End Sub
    'this is use ot clear & kill session & redirect to link1(home page)
    Private Sub lnkLogout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnkLogout.Click
        Session.Abandon()
        Session.Clear()
        Response.Redirect(objABProCommonClass.mapLink(Request.Path))
    End Sub
    ' get from date  from calendar
    Private Sub lnkFromDate_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs)
        Response.Write("<script language=javascript>window.open('popup.aspx?textbox=txtFromDate','cal','width=180,height=180,left=270,top=180')</script>")
    End Sub
    ' get to date from calenadar
    Private Sub lnkToDate_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs)
        Response.Write("<script language=javascript>window.open('popup.aspx?textbox=txtToDate','cal','width=180,height=180,left=180,top=180')</script>")
    End Sub
    'this is use to update data in ADMIN_MAPS_USER_MASTER table
    Private Sub lnkAuthNewEnrol_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnkAuthNewEnrol.Click
        Dim cmdUpd As New SqlCommand("update ADMIN_MAPS_USER_MASTER  SET   blocked=@BLOCKED,  UPDATED_BY=@UPDATED_BY,STATUS_DATE=GETDATE() where USER_NAME=@USER_NAME", conn)
        Dim prmUSER_NAME As New SqlParameter("@USER_NAME", SqlDbType.VarChar, 20)
        Dim prmBLOCKED As New SqlParameter("@BLOCKED", SqlDbType.VarChar, 20)
        Dim prmUPDATED_BY As New SqlParameter("@UPDATED_BY", SqlDbType.VarChar, 30)
        cmdUpd.Parameters.Add(prmUPDATED_BY)
        cmdUpd.Parameters.Add(prmUSER_NAME)
        cmdUpd.Parameters.Add(prmBLOCKED)

        Dim dgItem As DataGridItem
        Dim chkSelected As New System.Web.UI.WebControls.CheckBox

        Dim str As String = ""
        If conn.State = ConnectionState.Closed Then conn.Open()
        For Each dgItem In Datagrid2.Items
            chkSelected = dgItem.FindControl("checkbox1")
            prmUSER_NAME.Value = dgItem.Cells(1).Text.Trim
            prmUPDATED_BY.Value = Session("UserCode") + ""
            If chkSelected.Checked = True Then
                If dgItem.Cells(3).Text.Trim = "N" Then
                    prmBLOCKED.Value = "Y"
                ElseIf dgItem.Cells(3).Text.Trim = "Y" Then
                    prmBLOCKED.Value = "N"
                End If
            Else
                prmBLOCKED.Value = dgItem.Cells(3).Text.Trim
            End If
            cmdUpd.ExecuteNonQuery()
            ' INSERT TRAIN
            Dim A As New AdminClass
            If dgItem.Cells(3).Text.Trim = "N" Then
                A.INSERT_INTO_TRAIL(dgItem.Cells(1).Text.Trim, Session("UserCode"), "UNBLOCK")
            ElseIf dgItem.Cells(3).Text.Trim = "Y" Then
                A.INSERT_INTO_TRAIL(dgItem.Cells(1).Text.Trim, Session("UserCode"), "BLOCK")
            End If
        Next
        If conn.State = ConnectionState.Open Then conn.Close()
        bindDataToGrid()
        conn.Dispose()
    End Sub
    'this is use to set pagination property to datagrid2
    Private Sub Datagrid2_PageIndexChanged1(ByVal source As System.Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs)
        Datagrid2.CurrentPageIndex = e.NewPageIndex
        bindDataToGrid()
    End Sub
    'this is use to redirect to home page (link1)
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Session("HomeFlag") = "Y"
        Response.Redirect(objABProCommonClass.mapLink(Request.Path))
    End Sub
    'this is use to clear & kill session and redirect to home page (link1)
    Private Sub Btn_Logout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Logout.Click
        Dim a As New AdminClass
        a.UpateSessionInfo(Session("INDEXNO"))
        Session.Abandon()
        Session.Clear()
        'Response.Redirect("../ADMIN/links1.aspx")
        Response.Redirect(objABProCommonClass.mapLink(Request.Path))
    End Sub
    'this is use to set pagination property to datagrid2
    Private Sub Datagrid2_PageIndexChanged2(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles Datagrid2.PageIndexChanged
        Datagrid2.CurrentPageIndex = e.NewPageIndex
        bindDataToGrid()
    End Sub
    '/*this is use to when error comes then display error page */'

    Private Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Error
        Dim PhyFilePath As String = System.AppDomain.CurrentDomain.BaseDirectory
        Dim sUser As String = Session("UserCode")
        Dim sLastError As String = Server.GetLastError.Message.ToString
        Dim sStackTrace As String = Server.GetLastError.StackTrace.ToString
        objABProCommonClass.WriteError(sLastError, "", sUser, PhyFilePath, "NPCI_Loyalty User Blocking")
    End Sub
End Class

redpajama_set_name: RedPajamaGithub


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

<title>musicg.extension</title>
<meta name="date" content="2016-06-19">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

musicg.extension

Classes

NormalizedSampleAmplitudes

Spectrogram


text:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    if(nome.getText().toString().trim().equals("") || teste.getText().toString().trim().equals("") || cpf.getText().toString().trim().equals("")){
        Toast.makeText(getApplicationContext(),"Vazio", Toast.LENGTH_SHORT).show();
    }else{
        Toast.makeText(getApplicationContext(),"Não vazio", Toast.LENGTH_SHORT).show();
    }
}
});

//https://pt.stackoverflow.com/q/172216/101


text:
title: 07/11/16
layout: post
author: miles.groom
permalink: /07/11/16/
source-id: 1d64m3hmgf3zlZJLAovGVigLUcwWyhnXVKyn8iTHO6_o
published: true
---

    Title
    Week 7
    Date
    07/11/16

    Starting point:
    _____

    Target for this lesson?
    To improve on our blogs and add in a table

    Lesson Review

    How Did I Learn? What Strategies Were Effective?

    Hi Guys!!
Today I learnt by taking on what our teacher was talking about and using this information to improve my blog (Auditory). I found this very helpful as now my blog looks very good in my eyes.
Get in there!!!!!

    What limited my learning? Which habits do I need to work on?

    I now regret not taking notes… (Idiot). If I had taken notes I would have been able to remember everything Mr Keen said and put it all into my blog. Even those little things that will make it a tiny bit better. But hey, a bit better is better than nothing, Right??
Also I think we could have had some more time at our computers. I mean we are in a Computing Lesson??

    What will I change for next time? How will I improve my learning? Targets?

    Like I said before, I NEED TO TAKE SOME NOTES!!!! Having these notes will make my blog better, my understanding better etc. Also I need to think a bit harder as when the table coding was put up on Google Classroom (and by the way it has a password so all you hackers out there can think again), I was still copying it off the board instead of copying and pasting it!
Anyway my next blog will be out on Monday so have a nice time fans and Cyaaa!


text:
@implementation iCukeServer

+ (void)load
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	[[iCukeHTTPServer sharediCukeHTTPServer] start];

	NSFileManager *fileManager= [[NSFileManager alloc] init];
	NSArray *paths;

	if (!getenv("ICUKE_KEEP_PREFERENCES")) {
		NSString *preferences = [NSHomeDirectory() stringByAppendingPathComponent: @"Library/Preferences"];

		paths = [fileManager contentsOfDirectoryAtPath: preferences error: NULL];
		for (NSString *path in paths) {
			NSLog(@"Found: %@", path);
			if (![path hasPrefix: @"."]) {
				NSLog(@"Removing: %@", path);
				unlink([[preferences stringByAppendingPathComponent: path] cStringUsingEncoding: [NSString defaultCStringEncoding]]);
			}
		}
	}

	// This is a hack, I can't find a nicer way. The iPhone Simulator's
	// preferences are hidden away from applications. None of the preference APIs
	// allow access to them.
	NSString *path = [NSString stringWithFormat: @"/Users/%@/Library/Application Support/iPhone Simulator/%@/Library/Preferences", NSUserName(), [[UIDevice currentDevice] systemVersion]];
	path = [path stringByAppendingPathComponent: @"com.apple.Accessibility.plist"];
	NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile: path];
	if (!dict) {
		dict = [NSMutableDictionary dictionaryWithCapacity: 2];
	}
	NSNumber *enabled = [NSNumber numberWithBool: YES];
	[dict setObject: enabled forKey: @"AccessibilityEnabled"];
	[dict setObject: enabled forKey: @"ApplicationAccessibilityEnabled"];
	if (![dict writeToFile: path atomically: YES]) {
		NSLog(@"Failed to write %@ out to %@", dict, path);
	}

	NSString *documents = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents"];
	paths = [fileManager contentsOfDirectoryAtPath: documents error: NULL];
	for (NSString *path in paths) {
		if (![path hasPrefix: @"."]) {
			NSLog(@"Removing: %@", path);
			unlink([[documents stringByAppendingPathComponent: path] cStringUsingEncoding: [NSString defaultCStringEncoding]]);
		}
	}

	[pool release];
}

@end


text:
/**
 *
 */
package com.tvd12.ezyfox.sfs2x.testing.command;

import org.testng.annotations.Test;

import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;
import com.tvd12.ezyfox.core.bridge.ClientRequestHandlers;
import com.tvd12.ezyfox.core.entities.ApiUser;
import com.tvd12.ezyfox.sfs2x.command.impl.PropagateRequestImpl;
import com.tvd12.ezyfox.sfs2x.testing.ExampleUser;
import com.tvd12.ezyfox.sfs2x.testing.context.VideoPokerRoom;

/**
 * @author tavandung12
 *
 */
public class PropagateRequestImplTest extends BaseCommandTest2 {

	public PropagateRequestImplTest() {
		super();
		context.set(ClientRequestHandlers.class, new ClientRequestHandlers() {

			@Override
			public Object getClientRequestHandler(Object cmd) {
				return new BaseClientRequestHandler() {

					@Override
					public void handleClientRequest(User user, ISFSObject params) {
						System.out.println("PropagateRequestImplTest");
					}
				};
			}

			@Override
			public boolean containsClientRequestHandler(Object cmd) {
				return "hello".equals(cmd);
			}

		});
	}

    @Test(priority = 1)
    public void test() {
        PropagateRequestImpl command = new PropagateRequestImpl(context, api, extension);
        command.command("hello")
            .data(new VideoPokerRoom())
            .user(user)
            .param("a", "b")
            .only("a")
            .ignore("b")
            .execute();
    }

    @Test(priority = 2)
    public void test2() {
    	PropagateRequestImpl command = new PropagateRequestImpl(context, api, extension);
    	ApiUser apiUser = new ExampleUser();
    	apiUser.setName("unknown");
        command.command("hello")
            .data(null)
            .user(apiUser)
            .execute();
    }

    @Test(priority = 3, expectedExceptions = {IllegalStateException.class})
    public void test3() {
    	PropagateRequestImpl command = new PropagateRequestImpl(context, api, extension);
        command.command("")
            .data(null)
            .user(user)
            .execute();
    }

    @Test(priority = 5, expectedExceptions = {IllegalStateException.class})
    public void test5() {
    	PropagateRequestImpl command = new PropagateRequestImpl(context, api, extension);
        command.command(null)
            .data(null)
            .user(user)
            .execute();
    }

    @Test(priority = 6, expectedExceptions = {IllegalStateException.class})
    public void test6() {
    	PropagateRequestImpl command = new PropagateRequestImpl(context, api, extension);
        command.command("no comment")
            .data(null)
            .user(user)
            .execute();
    }

    public static void main(String[] args) {
        new PropagateRequestImplTest().test();
    }
}


text:
package com.kc.shiptransport.mvp.hsecheckdefect;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.kc.shiptransport.R;
import com.kc.shiptransport.data.bean.hse.HseDefectListBean;
import com.kc.shiptransport.data.bean.img.ImgList;
import com.kc.shiptransport.db.hse.HseDefectDeadline;
import com.kc.shiptransport.db.hse.HseDefectType;
import com.kc.shiptransport.interfaze.OnDailogCancleClickListener;
import com.kc.shiptransport.mvp.BaseFragment;
import com.kc.shiptransport.mvp.hsecheckdefectadd.HseCheckDefectAddActivity;
import com.kc.shiptransport.util.PopwindowUtil;
import com.kc.shiptransport.util.RxGalleryUtil;
import com.kc.shiptransport.util.SettingUtil;
import com.kc.shiptransport.util.ToastUtil;
import com.kc.shiptransport.view.actiivty.ImgViewPageActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author 邱永恒
 * @time 2017/11/22  17:20
 * @desc ${TODD}
 */

public class HseCheckDefectFragment extends BaseFragment<HseCheckDefectActivity> implements HseCheckDefectContract.View, View.OnClickListener {
    private static int pageSize = 20;
    private static int pageCount = 1;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    Unbinder unbinder;
    @BindView(R.id.select_1)
    TextView select1;
    @BindView(R.id.select_2)
    TextView select2;
    @BindView(R.id.select_3)
    TextView select3;
    @BindView(R.id.select_4)
    TextView select4;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    private HseCheckDefectContract.Presenter presenter;
    private CommonAdapter<HseDefectListBean> adapter;
    private int defectTypeID;
    private String defectItem;
    private int rectificationDeadline;
    private String creator;
    private int isSubmitted = 100; // 100表示默认全部显示
    private List<HseDefectType> defectTypeList;
    private List<HseDefectDeadline> defectDeadlineList;
    private String[] defectStatusList;
    private int deletePosition;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        initViews(rootView);
        initListener();

        presenter.subscribe();
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshLayout.autoRefresh();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_hse_check, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add:
                Bundle bundle = new Bundle();
                bundle.putInt(HseCheckDefectAddActivity.TYPE, SettingUtil.TYPE_HSE_DEFECT_ADD);
                bundle.putInt(HseCheckDefectAddActivity.CHECKRECORDID, activity.itemID);
                bundle.putInt(HseCheckDefectAddActivity.ITEMID, 0);
                HseCheckDefectAddActivity.startActivity(getContext(), bundle);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void initViews(View view) {
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        refreshLayout.setEnableHeaderTranslationContent(false);
        select1.setText("缺陷类别");
        select2.setVisibility(View.GONE);
        select3.setText("整改期限");
        select4.setText("处理状态");
    }

    @Override
    public void initListener() {
        select1.setOnClickListener(this);
        select2.setOnClickListener(this);
        select3.setOnClickListener(this);
        select4.setOnClickListener(this);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(30000, false);
                refresh(false);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadmore(30000, false);
                presenter.getDefects(pageSize, ++pageCount, new HseDefectListBean(activity.itemID, defectTypeID, defectItem, rectificationDeadline, creator, isSubmitted), false);
            }
        });
    }

    @Override
    public void setPresenter(HseCheckDefectContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void showLoading(boolean isShow) {
        if (isShow) {
            activity.showProgressDailog("请稍等", "请稍等...", new OnDailogCancleClickListener() {
                @Override
                public void onCancel(ProgressDialog dialog) {
                    presenter.unsubscribe();
                }
            });
        } else {
            activity.hideProgressDailog();
        }
    }

    @Override
    public void showError(String msg) {
        ToastUtil.tip(getContext(), msg);
    }

    @Override
    public int setView() {
        return R.layout.fragment_hsecheck_defect;
    }

    @Override
    public int setTitle() {
        return R.string.title_hse_check_defect;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.select_1: // 缺陷类别
                PopwindowUtil.showPopwindow(getContext(), defectTypeList, select1, false, new PopwindowUtil.InitHolder<HseDefectType>() {
                    @Override
                    public void initHolder(ViewHolder holder, final HseDefectType hseDefectType, int position) {
                        holder.setText(R.id.tv_spinner, hseDefectType.getName())
                                .setOnClickListener(R.id.tv_spinner, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        select1.setText(hseDefectType.getName());
                                        defectTypeID = hseDefectType.getItemID(); // 缺陷id
                                        refresh(true);
                                        PopwindowUtil.hidePopwindow();
                                    }
                                });
                    }
                }, null, new PopwindowUtil.OnHeadClickListener() {
                    @Override
                    public void onHeadClick(View view, RecyclerView.ViewHolder holder, int position) {
                        select1.setText("全部缺陷类型");
                        defectTypeID = 0;
                        refresh(true);
                    }
                });
                break;
            case R.id.select_3: // 整改期限
                PopwindowUtil.showPopwindow(getContext(), defectDeadlineList, select3, false, new PopwindowUtil.InitHolder<HseDefectDeadline>() {
                    @Override
                    public void initHolder(ViewHolder holder, final HseDefectDeadline hseDefectDeadline, int position) {
                        holder.setText(R.id.tv_spinner, hseDefectDeadline.getRectificationDeadlineName())
                                .setOnClickListener(R.id.tv_spinner, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        select3.setText(hseDefectDeadline.getRectificationDeadlineName());
                                        rectificationDeadline = hseDefectDeadline.getRectificationDeadlineID();
                                        PopwindowUtil.hidePopwindow();
                                        refresh(true);
                                    }
                                });
                    }
                }, null, new PopwindowUtil.OnHeadClickListener() {
                    @Override
                    public void onHeadClick(View view, RecyclerView.ViewHolder holder, int position) {
                        select3.setText("全部整改期限");
                        rectificationDeadline = 0;
                        refresh(true);
                    }
                });
                break;
            case R.id.select_4:
                PopwindowUtil.showPopwindow(getContext(), defectStatusList, select4, false, new PopwindowUtil.InitHolder<String>() {
                    @Override
                    public void initHolder(ViewHolder holder, final String s, final int position) {
                        holder.setText(R.id.tv_spinner, s)
                                .setOnClickListener(R.id.tv_spinner, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        select4.setText(s);
                                        isSubmitted = position - 1;
                                        refresh(true);
                                        PopwindowUtil.hidePopwindow();
                                    }
                                });
                    }
                }, null, new PopwindowUtil.OnHeadClickListener() {
                    @Override
                    public void onHeadClick(View view, RecyclerView.ViewHolder holder, int position) {
                        select4.setText("全部状态");
                        isSubmitted = 100;
                        refresh(true);
                    }
                });
                break;
        }
    }

    private void refresh(boolean isShow) {
        pageCount = 1;
        presenter.getDefects(pageSize, pageCount, new HseDefectListBean(activity.itemID, defectTypeID, defectItem, rectificationDeadline, creator, isSubmitted), isShow);
    }

    @Override
    public void showDefects(List<HseDefectListBean> list, boolean isFirst) {
        if (list == null || list.isEmpty()) {
            // 不能加载更多
            refreshLayout.finishLoadmore();
            refreshLayout.setLoadmoreFinished(true);
        }
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        if (adapter == null) {
            adapter = new CommonAdapter<HseDefectListBean>(getContext(), R.layout.item_hse_check_defect, list) {
                @Override
                protected void convert(ViewHolder holder, final HseDefectListBean bean, final int position) {
                    holder.setText(R.id.tv_defect_type, bean.getDefectTypeName())
                            .setText(R.id.tv_defect_project, bean.getDefectItem())
                            .setText(R.id.tv_defect_deadline, bean.getRectificationDeadlineName())
                            .setText(R.id.tv_defect_status, bean.getIsSubmitted() == 1 ? "已处理" : "未处理")
                            .setText(R.id.tv_remark, bean.getRemark())
                            .setOnClickListener(R.id.btn_show, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Bundle bundle = new Bundle();
                                    bundle.putInt(HseCheckDefectAddActivity.TYPE, SettingUtil.TYPE_HSE_DEFECT_READ_ONLY);
                                    bundle.putInt(HseCheckDefectAddActivity.CHECKRECORDID, activity.itemID);
                                    bundle.putInt(HseCheckDefectAddActivity.ITEMID, bean.getItemID());
                                    HseCheckDefectAddActivity.startActivity(getContext(), bundle);
                                }
                            })
                            .setOnClickListener(R.id.btn_update, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Bundle bundle = new Bundle();
                                    bundle.putInt(HseCheckDefectAddActivity.TYPE, SettingUtil.TYPE_HSE_DEFECT_UPDATE);
                                    bundle.putInt(HseCheckDefectAddActivity.CHECKRECORDID, activity.itemID);
                                    bundle.putInt(HseCheckDefectAddActivity.ITEMID, bean.getItemID());
                                    HseCheckDefectAddActivity.startActivity(getContext(), bundle);
                                }
                            })
                            .setOnClickListener(R.id.btn_delete, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    activity.showDailog("删除缺陷", "是否删除缺陷?", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            deletePosition = position;
                                            presenter.deleteForItem(bean.getItemID());
                                        }
                                    });
                                }
                            });

                    // 缺陷图片
                    RecyclerView recyclerView = holder.getView(R.id.recycler_view);
                    recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 4));
                    List<HseDefectListBean.DefectAttachmentList> defectAttachmentList = bean.getDefectAttachmentList();
                    final List<ImgList> imgLists = RxGalleryUtil.defectListToImgList(defectAttachmentList);

                    CommonAdapter<ImgList> commonAdapter = new CommonAdapter<ImgList>(getContext(), R.layout.item_img, imgLists) {
                        @Override
                        protected void convert(ViewHolder holder, ImgList imgList, final int position) {
                            holder.setVisible(R.id.iv_delete, false)
                                    .setOnClickListener(R.id.iv_img, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            ImgViewPageActivity.startActivity(getContext(), (ArrayList<ImgList>) imgLists, position);
                                        }
                                    });
                            ImageView imageView = holder.getView(R.id.iv_img);
                            RxGalleryUtil.showImage(getContext(), imgList.getPath(), null, null, imageView);
                        }
                    };

                    recyclerView.setAdapter(commonAdapter);
                }
            };

            recyclerView.setAdapter(adapter);
        } else {
            if (isFirst) {
                adapter.clear();
            }
            adapter.loadmore(list);

        }
    }

    @Override
    public void showSyncResult(boolean isSuccess) {
        if (isSuccess) {
            // 缺陷类别
            defectTypeList = DataSupport.findAll(HseDefectType.class);
            // 整改期限
            defectDeadlineList = DataSupport.findAll(HseDefectDeadline.class);
            // 处理状态
            defectStatusList = getResources().getStringArray(R.array.select_hse_defect_status);
            // 缺陷项目

        } else {
            ToastUtil.tip(getContext(), "同步数据失败, 请重试");
        }
    }

    @Override
    public void showDeleteResult(boolean isSuccess) {
        if (isSuccess) {
            ToastUtil.tip(getContext(), "删除成功");
            adapter.removeItem(deletePosition);
        } else {
            ToastUtil.tip(getContext(), "删除失败, 请重试");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (refreshLayout != null && refreshLayout.isRefreshing()) {
            refreshLayout.finishRefresh();
        }
        if (presenter != null) {
            presenter.unsubscribe();
        }
    }
}


text:
module Sro::Mock
  class ActiveRecordModel < ActiveRecord::Base
    def inject_getter(key)
      getter = set_getter(key)
      self.instance_eval(getter)
    end

    def inject_setter(key)
      setter = set_setter(key)
      self.instance_eval(setter)
    end

    def run(args)
      args.each do |key, value|
        inject_getter(key)
        inject_setter(key)
        set_value(key, value)
      end

      self
    end

    def set_getter(key)
      "def #{key}; @#{key} ; end;"
    end

    def set_setter(key)
      "def #{key}=(value); @#{key}=value; end;"
    end

    def set_value(key, value)
      self.instance_variable_set("@#{key}", value)
    end
  end
end


text:
export * from './box';
export * from './plane';
export * from './sphere';


text:
[Screep](http://screeps.com) Game Files

# Package Manager
- Npm https://www.npmjs.com

# Screeps Game Objects

Forked and create a `package.json` to install via npm ;)
- https://github.com/thomaskneisel/ScreepsAutocomplete

Thanks Garethp!
https://github.com/Garethp/ScreepsAutocomplete

# Testing
## Framework
- mocha https://mochajs.org

## Assertions
- Chai http://chaijs.com

## Mocks
- mockery https://github.com/mfncooper/mockery


text:
using Orchard.Environment.Extensions;
using Orchard.Layouts.Framework.Elements;

namespace Orchard.Layouts.Elements {
    [OrchardFeature("Orchard.Layouts.Snippets")]
    public class Snippet : Element {
        public override string Category {
            get { return "Snippets"; }
        }

        public override bool IsSystemElement {
            get { return true; }
        }

        public override bool HasEditor {
            get { return false; }
        }
    }
}


text:
package com.conversantmedia.util.concurrent;

import com.conversantmedia.util.collection.Stack;
import com.conversantmedia.util.concurrent.ConcurrentStack;
import org.junit.Ignore;
import org.junit.Test;

/**
 * Created by jcairns on 1/26/16.
 */
public class ConcurrentStackPerformanceTest {
    private static final int NRUN = 1000*1;
    private static final Integer INTVAL = 6767;

    @Test
    public void testStackPerformance() throws InterruptedException {
        for(int c=0; c<6; c++) {
            System.gc();
            runRate(new ConcurrentStack<>(1024));
        }
    }

    @Ignore
    private static void runRate(Stack<Integer> stack) throws InterruptedException {
        final Thread thread = new Thread(() -> {
            for(int i=0; i<NRUN; i++) {
                while(!stack.push(INTVAL)) {
                    Thread.yield();;
                }
            }
        });

        final long startTime = System.nanoTime();
        thread.start();
        for(int i=0; i<NRUN; i++) {
            while(stack.pop() != INTVAL) {
                Thread.yield();
            }
        }
        thread.join();
        final long runTime = System.nanoTime() - startTime;
        System.out.println(Integer.toString(NRUN)+" in "+String.format("%3.1f ms", runTime/1e6)+": "+String.format("%d ns", runTime/NRUN));
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Boost.Geometry (aka GGL, Generic Geometry Library)</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Examples

Class List

Class Index

Class Hierarchy

Class Members

boost

geometry

inconsistent_turns_exception

boost::geometry::inconsistent_turns_exception Member List

This is the complete list of members for boost::geometry::inconsistent_turns_exception, including all inherited members.

inconsistent_turns_exception()	boost::geometry::inconsistent_turns_exception

what() const 	boost::geometry::inconsistent_turns_exception	virtual

~inconsistent_turns_exception()	boost::geometry::inconsistent_turns_exception	virtual

April 2, 2011

Copyright © 2007-2011 Barend Gehrels, Amsterdam, the Netherlands

Copyright © 2008-2011 Bruno Lalande, Paris, France

Copyright © 2009-2010 Mateusz Loskot, London, UK

<address style="text-align: right;">
Documentation is generated by Doxygen
</address>


text:
import pandas as pd
import numpy as np
import os
import json
import sys

def JSON_to_DataFrame(source):

	#Open source file and load data
	file_ = open(source)
	json_data = json.load(file_)

	#grab supernovae name frome source file
	SN_name = os.path.splitext(os.path.basename(source))[0]

	#If there are no photometric elements, ignore
	if('photometry' not in json_data[SN_name]):
		return
	#grab only the photometry elements from data
	photometry = json_data[SN_name]['photometry']

	#rid the data where 'upperlimit' is true
	photometry_clean = [x for x in photometry if 'upperlimit' not in x]

	#minimum number of elements needed for analysis

	#initialize and create a dataframe out of photometry data
	DF = pd.DataFrame(photometry_clean)

	#If bands arent specified, ignore
	if('band' not in DF):
		return

	DF.index.name = "Observation"

	#Reduce DF to these columns, only if they exist
	DF = DF.loc[:, DF.columns.isin(['time', 'magnitude', 'e_magnitude', 'e_upper_magnitude', 'e_lower_magnitude', 'band', 'source', 'telescope'])]

	#convert numerical quantities from strings to floats
	DF.time = DF.time.apply(float)
	if('magnitude' in DF.columns):
		DF.magnitude = DF.magnitude.apply(float)
	if('e_magnitude' in DF.columns):
		DF.e_magnitude = DF.e_magnitude.apply(float)
	if('e_upper_magnitude' in DF.columns):
		DF.e_upper_magnitude = DF.e_upper_magnitude.apply(float)
	if('e_lower_magnitude' in DF.columns):
		DF.e_lower_magnitude = DF.e_lower_magnitude.apply(float)

	file_.close()

	#save Dataframe as HDF5 file
	DF.to_hdf("../../../OSC_data/HDF5_data/" + SN_name + '.h5', "SN")
	return DF


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.propTypes = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _utils = require('./utils');

var _utils2 = _interopRequireDefault(_utils);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/* eslint-disable react/default-props-match-prop-types */

var convertValidationsToObject = function convertValidationsToObject(validations) {
  if (typeof validations === 'string') {
    return validations.split(/,(?![^{[]*[}\]])/g).reduce(function (validationsAccumulator, validation) {
      var args = validation.split(':');
      var validateMethod = args.shift();

      args = args.map(function (arg) {
        try {
          return JSON.parse(arg);
        } catch (e) {
          return arg; // It is a string if it can not parse it
        }
      });

      if (args.length > 1) {
        throw new Error('Formsy does not support multiple args on string validations. Use object format of validations instead.');
      }

      // Avoid parameter reassignment
      var validationsAccumulatorCopy = Object.assign({}, validationsAccumulator);
      validationsAccumulatorCopy[validateMethod] = args.length ? args[0] : true;
      return validationsAccumulatorCopy;
    }, {});
  }

  return validations || {};
};

var propTypes = {
  innerRef: _propTypes2.default.func,
  name: _propTypes2.default.string.isRequired,
  required: _propTypes2.default.oneOfType([_propTypes2.default.bool, _propTypes2.default.object, _propTypes2.default.string]),
  validations: _propTypes2.default.oneOfType([_propTypes2.default.object, _propTypes2.default.string]),
  value: _propTypes2.default.any // eslint-disable-line react/forbid-prop-types
};

exports.propTypes = propTypes;

exports.default = function (Component) {
  var WrappedComponent = function (_React$Component) {
    _inherits(WrappedComponent, _React$Component);

    function WrappedComponent(props) {
      _classCallCheck(this, WrappedComponent);

      var _this = _possibleConstructorReturn(this, (WrappedComponent.__proto__ || Object.getPrototypeOf(WrappedComponent)).call(this, props));

      _this.getErrorMessage = function () {
        var messages = _this.getErrorMessages();
        return messages.length ? messages[0] : null;
      };

      _this.getErrorMessages = function () {
        if (!_this.isValid() || _this.showRequired()) {
          return _this.state.externalError || _this.state.validationError || [];
        }
        return [];
      };

      _this.getValue = function () {
        return _this.state.value;
      };

      _this.setValidations = function (validations, required) {
        // Add validations to the store itself as the props object can not be modified
        _this.validations = convertValidationsToObject(validations) || {};
        _this.requiredValidations = required === true ? { isDefaultRequiredValue: true } : convertValidationsToObject(required);
      };

      _this.setValue = function (value) {
        var validate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

        if (!validate) {
          _this.setState({
            value: value
          });
        } else {
          _this.setState({
            value: value,
            isPristine: false
          }, function () {
            _this.context.formsy.validate(_this);
          });
        }
      };

      _this.hasValue = function () {
        return _this.state.value !== '';
      };

      _this.isFormDisabled = function () {
        return _this.context.formsy.isFormDisabled();
      };

      _this.isFormSubmitted = function () {
        return _this.state.formSubmitted;
      };

      _this.isPristine = function () {
        return _this.state.isPristine;
      };

      _this.isRequired = function () {
        return !!_this.props.required;
      };

      _this.isValid = function () {
        return _this.state.isValid;
      };

      _this.isValidValue = function (value) {
        return _this.context.formsy.isValidValue.call(null, _this, value);
      };

      _this.resetValue = function () {
        _this.setState({
          value: _this.state.pristineValue,
          isPristine: true
        }, function () {
          _this.context.formsy.validate(_this);
        });
      };

      _this.showError = function () {
        return !_this.showRequired() && !_this.isValid();
      };

      _this.showRequired = function () {
        return _this.state.isRequired;
      };

      _this.state = {
        value: props.value,
        isRequired: false,
        isValid: true,
        isPristine: true,
        pristineValue: props.value,
        validationError: [],
        externalError: null,
        formSubmitted: false
      };
      return _this;
    }

    _createClass(WrappedComponent, [{
      key: 'componentWillMount',
      value: function componentWillMount() {
        var _this2 = this;

        var configure = function configure() {
          _this2.setValidations(_this2.props.validations, _this2.props.required);

          // Pass a function instead?
          _this2.context.formsy.attachToForm(_this2);
        };

        if (!this.props.name) {
          throw new Error('Form Input requires a name property when used');
        }

        configure();
      }

      // We have to make sure the validate method is kept when new props are added

    }, {
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps) {
        this.setValidations(nextProps.validations, nextProps.required);
      }
    }, {
      key: 'componentDidUpdate',
      value: function componentDidUpdate(prevProps) {
        // If the value passed has changed, set it. If value is not passed it will
        // internally update, and this will never run
        if (!_utils2.default.isSame(this.props.value, prevProps.value)) {
          this.setValue(this.props.value);
        }

        // If validations or required is changed, run a new validation
        if (!_utils2.default.isSame(this.props.validations, prevProps.validations) || !_utils2.default.isSame(this.props.required, prevProps.required)) {
          this.context.formsy.validate(this);
        }
      }

      // Detach it when component unmounts

    }, {
      key: 'componentWillUnmount',
      value: function componentWillUnmount() {
        this.context.formsy.detachFromForm(this);
      }

      // By default, we validate after the value has been set.
      // A user can override this and pass a second parameter of `false` to skip validation.

    }, {
      key: 'render',
      value: function render() {
        var innerRef = this.props.innerRef;

        var propsForElement = _extends({
          getErrorMessage: this.getErrorMessage,
          getErrorMessages: this.getErrorMessages,
          getValue: this.getValue,
          hasValue: this.hasValue,
          isFormDisabled: this.isFormDisabled,
          isValid: this.isValid,
          isPristine: this.isPristine,
          isFormSubmitted: this.isFormSubmitted,
          isRequired: this.isRequired,
          isValidValue: this.isValidValue,
          resetValue: this.resetValue,
          setValidations: this.setValidations,
          setValue: this.setValue,
          showRequired: this.showRequired,
          showError: this.showError
        }, this.props);

        if (innerRef) {
          propsForElement.ref = innerRef;
        }

        return _react2.default.createElement(Component, propsForElement);
      }
    }]);

    return WrappedComponent;
  }(_react2.default.Component);

  function getDisplayName(component) {
    return component.displayName || component.name || (typeof component === 'string' ? component : 'Component');
  }

  WrappedComponent.displayName = 'Formsy(' + getDisplayName(Component) + ')';

  WrappedComponent.contextTypes = {
    formsy: _propTypes2.default.object // What about required?
  };

  WrappedComponent.defaultProps = {
    innerRef: function innerRef() {},
    required: false,
    validationError: '',
    validationErrors: {},
    validations: null,
    value: Component.defaultValue
  };

  WrappedComponent.propTypes = propTypes;

  return WrappedComponent;
};


text:
This utility tries to count the number of records in Primo Central. Therefor it issues search requests which should result in disjunct results (e.g. `a*`, `b*` in field `sid`) and retrieves `TOTALHITS` for each search result.

## Installation

    $ gem install primo_central_counter

## Usage

```
Usage: primo_central_counter [options]

    -u, --base-url=BASE_URL                Primo base url (e.g. http://primo.kobv.de) *required*
    -i, --institution=INSTITUTION          Institution (e.g. PAD) *required*
    -c, --on-campus=ON_CAMPUS              Set the on_campus flag (default: true)
    -f, --index-field=INDEX_FIELD          Index field to use (default: sid)
        --log-level=LOG_LEVEL              Enable logging (e.g. info or debug)
    -v, --version                          Display version
    -h, --help                             Display usage informations
```

The output is total record cound on STDOUT. If you enable logging, this will be outputted on STDERR.

### Examples

```
primo_central_counter -u http://primo.kobv.de -i PAD
```

```
primo_central_counter -u http://primo.kobv.de -i PAD -l info 1> ./sum.txt 2> ./messages.txt
```

## Development

After checking out the repo, run `bin/setup` to install dependencies. You can run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/ubpb/primo_central_counter.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
import deepFreeze from 'deep-freeze';
import { websocketConnected, websocketDisconnected } from '../ui-common/App/connectedActions';
import appReducer from './appReducer';

it('na začátku', () => {
  const stateBefore = undefined;

  const stateAfter = appReducer(stateBefore, {});
  expect(stateAfter).toMatchSnapshot();
});

it('websocket connected', () => {
  const stateBefore = { connected: false };
  deepFreeze(stateBefore);

  const stateAfter = appReducer(stateBefore, websocketConnected());
  expect(stateAfter.connected).toEqual(true);
  expect(stateAfter).toMatchSnapshot();
});

it('websocket disconnected', () => {
  const stateBefore = { connected: true };
  deepFreeze(stateBefore);

  const stateAfter = appReducer(stateBefore, websocketDisconnected());
  expect(stateAfter.connected).toEqual(false);
  expect(stateAfter).toMatchSnapshot();
});

/* :TODO:
it('FETCH_UCASTNICI_REQUEST', () => {
  const stateBefore = { fetchingUcastnici: undefined };
  deepFreeze(stateBefore);

  const stateAfter = appReducer(stateBefore, createRequestFromAction({ action: fetchUcastnici() }));
  expect(stateAfter.fetchingUcastnici).toEqual('fetching');
});

it('FETCH_UCASTNICI_SUCCESS', () => {
  const stateBefore = { fetchingUcastnici: 'fetching' };
  deepFreeze(stateBefore);

  const stateAfter = appReducer(
    stateBefore,
    createSuccessFromAction({ action: fetchUcastnici(), response: { response: {} } })
  );
  expect(stateAfter.fetchingUcastnici).toEqual('done');
});

it('FETCH_STOPKY_REQUEST', () => {
  const stateBefore = { fetchingStopky: undefined };
  deepFreeze(stateBefore);

  const stateAfter = appReducer(stateBefore, createRequestFromAction({ action: fetchStopky() }));
  expect(stateAfter.fetchingStopky).toEqual('fetching');
});

it('FETCH_STOPKY_SUCCESS', () => {
  const stateBefore = { fetchingStopky: 'fetching' };
  deepFreeze(stateBefore);

  const stateAfter = appReducer(
    stateBefore,
    createSuccessFromAction({ action: fetchStopky(), response: { response: {} } })
  );
  expect(stateAfter.fetchingStopky).toEqual('done');
});
*/


text:
void output_single();
void output_multiple_in();
void output_multiple_out();
void output_multiple_out2();
void output_multiple_in_out();
void output_multiple_in_out2();

void output_level_1_single();
void output_level_2_single();
void output_level_3_single();
void output_extra_single();

void output_deps();
void output_deps2();

void validate_link()
{
	output_single();
	output_multiple_in();
	output_multiple_out();
	output_multiple_out2();
	output_multiple_in_out();
	output_multiple_in_out2();

	output_level_1_single();
	output_level_2_single();
	output_level_3_single();
	output_extra_single();

	output_deps();
	output_deps2();
}

int main()
{
	validate_link();
}


text:
package org.apache.ambari.server.controller.internal;

import static org.apache.ambari.server.controller.internal.SettingResourceProvider.SETTING_CONTENT_PROPERTY_ID;
import static org.apache.ambari.server.controller.internal.SettingResourceProvider.SETTING_NAME_PROPERTY_ID;
import static org.apache.ambari.server.controller.internal.SettingResourceProvider.SETTING_SETTING_TYPE_PROPERTY_ID;
import static org.apache.ambari.server.controller.internal.SettingResourceProvider.SETTING_UPDATED_BY_PROPERTY_ID;
import static org.apache.ambari.server.controller.internal.SettingResourceProvider.SETTING_UPDATE_TIMESTAMP_PROPERTY_ID;
import static org.easymock.EasyMock.capture;
import static org.easymock.EasyMock.createControl;
import static org.easymock.EasyMock.expect;
import static org.junit.Assert.assertEquals;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.ambari.server.controller.spi.Predicate;
import org.apache.ambari.server.controller.spi.Request;
import org.apache.ambari.server.controller.spi.RequestStatus;
import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.controller.spi.ResourceAlreadyExistsException;
import org.apache.ambari.server.controller.utilities.PredicateBuilder;
import org.apache.ambari.server.controller.utilities.PropertyHelper;
import org.apache.ambari.server.orm.dao.SettingDAO;
import org.apache.ambari.server.orm.entities.SettingEntity;
import org.apache.ambari.server.security.TestAuthenticationFactory;
import org.apache.ambari.server.security.authorization.AuthorizationException;
import org.apache.ambari.server.security.authorization.AuthorizationHelper;
import org.apache.commons.lang.RandomStringUtils;
import org.easymock.Capture;
import org.easymock.IMocksControl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.core.context.SecurityContextHolder;

import com.google.common.collect.Lists;

public class SettingResourceProviderTest {
  IMocksControl mockControl;
  SettingDAO dao;
  SettingResourceProvider resourceProvider;

  @Before
  public void setUp() throws Exception {
    mockControl = createControl();
    dao = mockControl.createMock(SettingDAO.class);
    resourceProvider = new SettingResourceProvider();
    setPrivateField(resourceProvider, "dao", dao);
  }

  @After
  public void tearDown() {
    mockControl.verify();
    SecurityContextHolder.getContext().setAuthentication(null);
    mockControl.reset();
  }

  @Test(expected = AuthorizationException.class)
  public void testGetResources_instance_noAuth() throws Exception {
    getResources_instance(newEntity("motd"), readRequest());
  }

  @Test
  public void testGetResources_instance_clusterUser() throws Exception {
    setupAuthenticationForClusterUser();
    String name = "motd";
    SettingEntity entity = newEntity(name);

    Set<Resource> response = getResources_instance(entity, readRequest());
    assertEquals(1, response.size());
    Resource resource = response.iterator().next();
    assertEqualsEntityAndResource(entity, resource);
  }

  @Test
  public void testGetResources_instance_admin() throws Exception {
    setupAuthenticationForAdmin();
    SettingEntity entity = newEntity("motd");
    Set<Resource> response = getResources_instance(entity, readRequest());
    assertEquals(1, response.size());
    Resource resource = response.iterator().next();
    assertEqualsEntityAndResource(entity, resource);
  }

  @Test(expected = AuthorizationException.class)
  public void testGetResources_collection_noAuth() throws Exception {
    mockControl.replay();
    Request request = PropertyHelper.getReadRequest(
            SETTING_NAME_PROPERTY_ID,
            SETTING_CONTENT_PROPERTY_ID,
            SETTING_SETTING_TYPE_PROPERTY_ID,
            SETTING_UPDATED_BY_PROPERTY_ID,
            SETTING_UPDATE_TIMESTAMP_PROPERTY_ID);
    resourceProvider.getResources(request, null);
  }

  @Test
  public void testGetResources_collection_clusterUser() throws Exception {
    setupAuthenticationForClusterUser();

    SettingEntity entity1 = newEntity("motd");
    SettingEntity entity2 = newEntity("ldap");
    Request request = PropertyHelper.getReadRequest(
            SETTING_NAME_PROPERTY_ID,
            SETTING_CONTENT_PROPERTY_ID,
            SETTING_SETTING_TYPE_PROPERTY_ID,
            SETTING_UPDATED_BY_PROPERTY_ID,
            SETTING_UPDATE_TIMESTAMP_PROPERTY_ID);

    expect(dao.findAll()).andReturn(Lists.newArrayList(entity1, entity2));
    mockControl.replay();

    Set<Resource> response = resourceProvider.getResources(request, null);
    assertEquals(2, response.size());
    Map<Object, Resource> resourceMap = new HashMap<>();
    Iterator<Resource> resourceIterator = response.iterator();
    Resource nextResource = resourceIterator.next();
    resourceMap.put(nextResource.getPropertyValue(SETTING_NAME_PROPERTY_ID), nextResource);
    nextResource = resourceIterator.next();
    resourceMap.put(nextResource.getPropertyValue(SETTING_NAME_PROPERTY_ID), nextResource);
    assertEqualsEntityAndResource(entity1, resourceMap.get(entity1.getName()));
    assertEqualsEntityAndResource(entity2, resourceMap.get(entity2.getName()));
  }

  @Test
  public void testGetResources_collection_admin() throws Exception {
    setupAuthenticationForAdmin();

    SettingEntity entity1 = newEntity("motd");
    SettingEntity entity2 = newEntity("ldap");
    Request request = PropertyHelper.getReadRequest(
            SETTING_NAME_PROPERTY_ID,
            SETTING_CONTENT_PROPERTY_ID,
            SETTING_SETTING_TYPE_PROPERTY_ID,
            SETTING_UPDATED_BY_PROPERTY_ID,
            SETTING_UPDATE_TIMESTAMP_PROPERTY_ID);
    expect(dao.findAll()).andReturn(Lists.newArrayList(entity1, entity2));
    mockControl.replay();

    Set<Resource> response = resourceProvider.getResources(request, null);
    assertEquals(2, response.size());
    Map<Object, Resource> resourceMap = new HashMap<>();
    Iterator<Resource> resourceIterator = response.iterator();
    Resource nextResource = resourceIterator.next();
    resourceMap.put(nextResource.getPropertyValue(SETTING_NAME_PROPERTY_ID), nextResource);
    nextResource = resourceIterator.next();
    resourceMap.put(nextResource.getPropertyValue(SETTING_NAME_PROPERTY_ID), nextResource);
    assertEqualsEntityAndResource(entity1, resourceMap.get(entity1.getName()));
    assertEqualsEntityAndResource(entity2, resourceMap.get(entity2.getName()));
  }

  @Test(expected = AuthorizationException.class)
  public void testCreateResource_noAuth() throws Exception {
    mockControl.replay();
    resourceProvider.createResources(createRequest(newEntity("moted")));
  }

  @Test(expected = AuthorizationException.class)
  public void testCreateResource_clusterUser() throws Exception {
    setupAuthenticationForClusterUser();
    mockControl.replay();
    resourceProvider.createResources(createRequest(newEntity("motd")));
  }

  @Test
  public void testCreateResource_admin() throws Exception {
    setupAuthenticationForAdmin();
    SettingEntity entity = newEntity("motd");
    Capture<SettingEntity> entityCapture = Capture.newInstance();
    Request request = createRequest(entity);

    expect(dao.findByName(entity.getName())).andReturn(null);
    dao.create(capture(entityCapture));
    mockControl.replay();

    RequestStatus response = resourceProvider.createResources(request);
    assertEquals(RequestStatus.Status.Complete, response.getStatus());
    Set<Resource> associatedResources = response.getAssociatedResources();
    assertEquals(1, associatedResources.size());
    SettingEntity capturedEntity = entityCapture.getValue();
    assertEquals(entity.getName(), capturedEntity.getName());
    assertEquals(entity.getContent(), capturedEntity.getContent());
    assertEquals(entity.getSettingType(), capturedEntity.getSettingType());
    assertEquals(AuthorizationHelper.getAuthenticatedName(), capturedEntity.getUpdatedBy());
  }

  @Test(expected = ResourceAlreadyExistsException.class)
  public void testCreateDuplicateResource() throws Exception {
    setupAuthenticationForAdmin();
    SettingEntity entity = newEntity("motd");
    Request request = createRequest(entity);

    expect(dao.findByName(entity.getName())).andReturn(entity);
    mockControl.replay();
    resourceProvider.createResources(request);
  }

  @Test(expected = AuthorizationException.class)
  public void testUpdateResources_noAuth() throws Exception {
    mockControl.replay();
    resourceProvider.updateResources(updateRequest(newEntity("motd")), null);
  }

  @Test(expected = AuthorizationException.class)
  public void testUpdateResources_clusterUser() throws Exception {
    setupAuthenticationForClusterUser();
    mockControl.replay();
    resourceProvider.updateResources(updateRequest(newEntity("motd")), null);
  }

  @Test
  public void testUpdateResources_admin() throws Exception {
    setupAuthenticationForAdmin();
    String name = "motd";
    SettingEntity oldEntity = newEntity(name);
    SettingEntity updatedEntity = oldEntity.clone();
    updatedEntity.setContent("{text}");
    updatedEntity.setSettingType("new-type");

    PredicateBuilder pb = new PredicateBuilder();
    Predicate predicate = pb.begin().property(SETTING_NAME_PROPERTY_ID).equals(name).end().toPredicate();
    Capture<SettingEntity> capture = Capture.newInstance();

    expect(dao.findByName(name)).andReturn(oldEntity);
    expect(dao.merge(capture(capture))).andReturn(updatedEntity);
    mockControl.replay();

    RequestStatus response = resourceProvider.updateResources(updateRequest(updatedEntity), predicate);
    SettingEntity capturedEntity = capture.getValue();
    assertEquals(RequestStatus.Status.Complete, response.getStatus());
    assertEquals(updatedEntity.getId(), capturedEntity.getId());
    assertEquals(updatedEntity.getName(), capturedEntity.getName());
    assertEquals(updatedEntity.getSettingType(), capturedEntity.getSettingType());
    assertEquals(updatedEntity.getContent(), capturedEntity.getContent());
    assertEquals(AuthorizationHelper.getAuthenticatedName(), capturedEntity.getUpdatedBy());
  }

  @Test(expected = AuthorizationException.class)
  public void testDeleteResources_noAuth() throws Exception {
    mockControl.replay();
    resourceProvider.deleteResources(new RequestImpl(null, null, null, null), null);
  }

  @Test(expected = AuthorizationException.class)
  public void testDeleteResources_clusterUser() throws Exception {
    setupAuthenticationForClusterUser();
    mockControl.replay();
    resourceProvider.deleteResources(new RequestImpl(null, null, null, null), null);
  }

  @Test
  public void testDeleteResources() throws Exception {
    setupAuthenticationForAdmin();

    String name = "motd";
    PredicateBuilder pb = new PredicateBuilder();
    Predicate predicate = pb.begin().property(SETTING_NAME_PROPERTY_ID).equals(name).end().toPredicate();
    dao.removeByName(name);
    mockControl.replay();
    resourceProvider.deleteResources(new RequestImpl(null, null, null, null), predicate);
  }

  private Set<Resource> getResources_instance(SettingEntity entity, Request request) throws Exception {
    String name = entity.getName();
    PredicateBuilder pb = new PredicateBuilder();
    Predicate predicate = pb.begin().property(SETTING_NAME_PROPERTY_ID).equals(name).end().toPredicate();

    expect(dao.findByName(name)).andReturn(entity).anyTimes();
    mockControl.replay();
    return resourceProvider.getResources(request, predicate);
  }

  private Request readRequest() {
    return PropertyHelper.getReadRequest(
            SETTING_NAME_PROPERTY_ID,
            SETTING_CONTENT_PROPERTY_ID,
            SETTING_SETTING_TYPE_PROPERTY_ID,
            SETTING_UPDATED_BY_PROPERTY_ID,
            SETTING_UPDATE_TIMESTAMP_PROPERTY_ID);
  }

  private Request createRequest(SettingEntity entity) {
    Map<String, Object> properties = new HashMap<>();
    properties.put(SETTING_NAME_PROPERTY_ID, entity.getName());
    properties.put(SETTING_CONTENT_PROPERTY_ID, entity.getContent());
    properties.put(SETTING_UPDATED_BY_PROPERTY_ID, entity.getUpdatedBy());
    properties.put(SETTING_SETTING_TYPE_PROPERTY_ID, entity.getSettingType());
    return PropertyHelper.getCreateRequest(Collections.singleton(properties), null);
  }

  private Request updateRequest(SettingEntity entity) {
    Map<String, Object> properties = new HashMap<>();
    properties.put(SETTING_NAME_PROPERTY_ID, entity.getName());
    properties.put(SETTING_CONTENT_PROPERTY_ID, entity.getContent());
    properties.put(SETTING_SETTING_TYPE_PROPERTY_ID, entity.getSettingType());
    return PropertyHelper.getUpdateRequest(properties, null);
  }

  private void setupAuthenticationForClusterUser() {
    SecurityContextHolder.getContext().setAuthentication(TestAuthenticationFactory.createClusterUser());
  }

  private void setupAuthenticationForAdmin() {
    SecurityContextHolder.getContext().setAuthentication(TestAuthenticationFactory.createAdministrator());
  }

  private SettingEntity newEntity(String name) {
    SettingEntity entity = new SettingEntity();
    entity.setName(name);
    entity.setContent(RandomStringUtils.randomAlphabetic(10));
    entity.setSettingType(RandomStringUtils.randomAlphabetic(5));
    entity.setUpdatedBy("ambari");
    entity.setUpdateTimestamp(System.currentTimeMillis());
    return entity;
  }

  private void assertEqualsEntityAndResource(SettingEntity entity, Resource resource) {
    assertEquals(entity.getName(), resource.getPropertyValue(SETTING_NAME_PROPERTY_ID));
    assertEquals(entity.getSettingType(), resource.getPropertyValue(SETTING_SETTING_TYPE_PROPERTY_ID));
    assertEquals(entity.getContent(), resource.getPropertyValue(SETTING_CONTENT_PROPERTY_ID));
    assertEquals(entity.getUpdatedBy(), resource.getPropertyValue(SETTING_UPDATED_BY_PROPERTY_ID));
    assertEquals(entity.getUpdateTimestamp(), resource.getPropertyValue(SETTING_UPDATE_TIMESTAMP_PROPERTY_ID));
  }

  private void setPrivateField(Object o, String field, Object value) throws Exception{
    Class<?> c = o.getClass();
    Field f = c.getDeclaredField(field);
    f.setAccessible(true);
    f.set(o, value);
  }
}


text:
package com.intellij.util.xmlb;

import com.intellij.util.xmlb.annotations.Attribute;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

class AttributeBinding extends BasePrimitiveBinding {
  private final Class<?> valueClass;

  public AttributeBinding(@NotNull MutableAccessor accessor, @Nullable Attribute attribute) {
    super(accessor, attribute == null ? null : attribute.value(), attribute == null ? null : attribute.converter());

    valueClass = XmlSerializerImpl.typeToClass(accessor.getGenericType());
  }

  @Override
  @Nullable
  public Object serialize(@NotNull Object o, @Nullable SerializationFilter filter) {
    Object value = myAccessor.read(o);
    if (value == null) {
      return null;
    }

    Converter<Object> converter = getConverter();
    String stringValue;
    if (converter == null) {
      stringValue = XmlSerializerImpl.convertToString(value);
    }
    else {
      stringValue = converter.toString(value);
      if (stringValue == null) {
        return null;
      }
    }
    return new org.jdom.Attribute(myName, stringValue);
  }

  void set(@NotNull Object host, @NotNull String value) {
    if (myConverter == null) {
      XmlSerializerImpl.doSet(host, value, myAccessor, valueClass);
    }
    else {
      myAccessor.set(host, myConverter.fromString(value));
    }
  }

  public String toString() {
    return "AttributeBinding[" + myName + "]";
  }
}


text:
<plugin name='hibernate' version='3.6.10.6' grailsVersion='2.3.2 > *'>
  <author>Graeme Rocher</author>
  <title>Hibernate 3 for Grails</title>
  <description>Provides integration between Grails and Hibernate 3 through GORM</description>
  <type>HibernateGrailsPlugin</type>
  <resources />
</plugin>


text:
SET @OLD_UNIQUE_CHECKS = @@UNIQUE_CHECKS, UNIQUE_CHECKS = 0;
SET @OLD_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS = 0;
SET @OLD_SQL_MODE = @@SQL_MODE, SQL_MODE = 'TRADITIONAL';

DROP SCHEMA IF EXISTS `sakuli`;
CREATE SCHEMA IF NOT EXISTS `sakuli`
  DEFAULT CHARACTER SET utf8;
USE `sakuli`;

-- -----------------------------------------------------
-- Table `sakuli`.`sakuli_suites`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `sakuli`.`sakuli_suites` (
  `id`          INT(11)       NOT NULL AUTO_INCREMENT,
  `suiteID`     VARCHAR(255)  NOT NULL,
  `result`      INT(11)       NOT NULL,
  `result_desc` VARCHAR(45)   NOT NULL,
  `name`        VARCHAR(255)  NOT NULL,
  `guid`        VARCHAR(255)  NOT NULL,
  `start`       VARCHAR(255)  NOT NULL,
  `stop`        VARCHAR(255)  NULL,
  `warning`     INT(11)       NULL,
  `critical`    INT(11)       NULL,
  `duration`    FLOAT         NULL,
  `browser`     VARCHAR(255)  NULL,
  `host`        VARCHAR(255)  NULL,
  `screenshot`  MEDIUMBLOB    NULL,
  `msg`         VARCHAR(2500) NULL,
  `time`        TIMESTAMP     NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `guid_UNIQUE` (`guid` ASC))
  ENGINE = MyISAM
  DEFAULT CHARACTER SET = utf8
  COMMENT = 'Sakuli Testcases';

-- -----------------------------------------------------
-- Table `sakuli`.`sakuli_cases`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `sakuli`.`sakuli_cases` (
  `id`             INT(11)       NOT NULL AUTO_INCREMENT,
  `sakuli_suites_id` INT(11) NOT NULL,
  `caseID`         VARCHAR(255)  NOT NULL,
  `result`         INT(11)       NOT NULL,
  `result_desc`    VARCHAR(45)   NOT NULL,
  `name`           VARCHAR(255)  NOT NULL,
  `guid`           VARCHAR(255)  NOT NULL,
  `start`          VARCHAR(255)  NOT NULL,
  `stop`           VARCHAR(255)  NOT NULL,
  `warning`        INT(11)       NULL DEFAULT NULL,
  `critical`       INT(11)       NULL DEFAULT NULL,
  `duration`       FLOAT         NOT NULL,
  `lastpage`       VARCHAR(1000)  NULL DEFAULT NULL,
  `screenshot`     MEDIUMBLOB    NULL DEFAULT NULL,
  `msg`            VARCHAR(2500) NULL DEFAULT NULL,
  `time`           TIMESTAMP     NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`, `sakuli_suites_id`),
  INDEX `fk_sakuli_cases_sakuli_suites` (`sakuli_suites_id` ASC)
)
  ENGINE = MyISAM
  DEFAULT CHARACTER SET = utf8
  COMMENT = 'Sakuli Testcases';

-- -----------------------------------------------------
-- Table `sakuli`.`sakuli_jobs`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `sakuli`.`sakuli_jobs` (
  `id`   INT(11)      NOT NULL AUTO_INCREMENT,
  `guid` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `ind_guid` (`guid` ASC))
  ENGINE = MyISAM
  DEFAULT CHARACTER SET = utf8;

-- -----------------------------------------------------
-- Table `sakuli`.`sakuli_steps`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `sakuli`.`sakuli_steps` (
  `id`            INT(11)      NOT NULL AUTO_INCREMENT,
  `sakuli_cases_id` INT(11) NOT NULL,
  `result`        INT(11)      NOT NULL,
  `result_desc`   VARCHAR(45)  NOT NULL,
  `name`          VARCHAR(255) NOT NULL,
  `start`         VARCHAR(255) NOT NULL,
  `stop`          VARCHAR(255) NOT NULL,
  `warning`       INT(11)      NULL DEFAULT NULL,
  `duration`      FLOAT        NOT NULL,
  `time`          TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`, `sakuli_cases_id`),
  INDEX `fk_sakuli_steps_sakuli_cases1` (`sakuli_cases_id` ASC)
)
  ENGINE = MyISAM
  DEFAULT CHARACTER SET = utf8
  COMMENT = 'Sakuli Testcases';

SET SQL_MODE = @OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS = @OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS = @OLD_UNIQUE_CHECKS;


text:
import chai = require("chai");
import Collection = require("../../db-collections/Collection");
import MemDbPersisters = require("../../persisters/MemDbPersisters");
import M = require("../TestModels");

var asr = chai.assert;

suite("autoupdate", function () {

    test("auto updates inserted documents", function (done) {
        if (typeof (<any>Object).observe !== "function") {
            done();
            return;
        }

        var coll = new Collection("test", {
            unique: ["name"],
            //autoupdate: true
        });

        coll.insert({
            name: "Jack"
        });

        var doc = coll.insert({
            name: "Peter"
        });

        function change1() {
            coll.events.on("update", function (target) {
                asr.equal(target, doc);

                change2();
            });
            doc.name = "John";
        }

        function change2() {
            coll.events.on("error", function (err) {
                asr.deepEqual(err, new Error("Duplicate key for property name: " + doc.name));
                done();
            });
            doc.name = "Jack";
        }

        change1();
    });

    test("auto updates documents loaded from storage", function (done) {

        if (typeof (<any>Object).observe !== "function") {
            done();
            return;
        }

        var db1 = M.createDb("autoupdate1.json");
        var db2 = M.createDb("autoupdate2.json");

        var coll = new Collection("test", {
            unique: ["name"],
            //autoupdate: true
        });

        var originalDocs = coll.insert([{
            name: "Jack"
        }, {
            name: "Peter"
        }]);

        var db1Persister = new MemDbPersisters.DbPersister("testfile1.db", () => db1.collections);
        var db2Persister = new MemDbPersisters.DbPersister("testfile2.db", () => db2.collections);
        db2Persister.loadJSON(db1Persister.serialize(), db1, {});

        coll = new Collection("test");

        var doc = <any>coll.by("name", "Peter");

        //asr.isTrue(coll.autoupdate);
        asr.deepEqual(doc, originalDocs[1]);

        function change1() {
            coll.events.on("update", function (target) {
                asr.equal(target, doc);

                change2();
            });
            doc.name = "John";
        }

        function change2() {
            coll.events.on("error", function (err) {
                asr.deepEqual(err, new Error("Duplicate key for property name: " + doc.name));
                done();
            });
            doc.name = "Jack";
        }

        change1();
    });

});


text:
package datastore

import (
	"github.com/boltdb/bolt"
)

var (
	documentBucket = []byte("doc")

	pIdKey      = []byte(":id")
	pTitleKey   = []byte(":title")
	pContentKey = []byte(":content")
	pTypeKey    = []byte(":type")
)

type Document struct {
	Id, Title, Content, Type []byte
}

type Datastore struct {
	db *bolt.DB
}

// New opens a datastore.
func New(path string) (*Datastore, error) {
	db, err := bolt.Open(path, 0600, nil)
	if err != nil {
		return nil, err
	}

	return NewWithDb(db)
}

// New opens a datastore using the given Bolt database.
func NewWithDb(db *bolt.DB) (*Datastore, error) {
	err := db.Update(func(tx *bolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists(documentBucket)
		return err
	})
	if err != nil {
		return nil, err
	}

	return &Datastore{db}, nil
}

// Close releases all datastore resources.
func (d *Datastore) Close() error {
	return d.db.Close()
}

// WriteDocument writes document to the datastore. If a document
// exists with the same document ID, it is overwritten.
func (d *Datastore) WriteDocument(doc *Document) error {
	var (
		idKey      = concat(doc.Id, pIdKey)
		titleKey   = concat(doc.Id, pTitleKey)
		contentKey = concat(doc.Id, pContentKey)
		typeKey    = concat(doc.Id, pTypeKey)
	)

	err := d.db.Update(func(tx *bolt.Tx) error {
		b := tx.Bucket(documentBucket)

		ep := errPut{b: b}
		ep.put(idKey, doc.Id)
		ep.put(titleKey, doc.Title)
		ep.put(contentKey, doc.Content)
		ep.put(typeKey, doc.Type)

		if ep.err != nil {
			return ep.err
		}

		return nil
	})

	if err != nil {
		return err
	}

	return nil
}

// DeleteDocument removes a document from the datastore. No
// error is returned is the document does not exist.
func (d *Datastore) DeleteDocument(id []byte) error {
	var (
		idKey      = concat(id, pIdKey)
		titleKey   = concat(id, pTitleKey)
		contentKey = concat(id, pContentKey)
		typeKey    = concat(id, pTypeKey)
	)

	err := d.db.Update(func(tx *bolt.Tx) error {
		b := tx.Bucket(documentBucket)

		ep := errDelete{b: b}
		ep.delete(idKey)
		ep.delete(titleKey)
		ep.delete(contentKey)
		ep.delete(typeKey)

		if ep.err != nil {
			return ep.err
		}

		return nil
	})

	if err != nil {
		return err
	}

	return nil
}

// ReadDocument retrives a document from the datastore.
// If the document does not exist, it is nil.
func (d *Datastore) ReadDocument(id []byte) (*Document, error) {
	var (
		doc        *Document
		idKey      = concat(id, pIdKey)
		titleKey   = concat(id, pTitleKey)
		contentKey = concat(id, pContentKey)
		typeKey    = concat(id, pTypeKey)
	)

	err := d.db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket(documentBucket)

		if id := b.Get(idKey); id != nil {
			doc = &Document{
				Id:      id,
				Title:   b.Get(titleKey),
				Content: b.Get(contentKey),
				Type:    b.Get(typeKey),
			}
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return doc, nil
}

type errPut struct {
	b   *bolt.Bucket
	err error
}

func (ep *errPut) put(key, value []byte) {
	if ep.err != nil {
		return
	}
	ep.err = ep.b.Put(key, value)
}

type errDelete struct {
	b   *bolt.Bucket
	err error
}

func (ep *errDelete) delete(key []byte) {
	if ep.err != nil {
		return
	}
	ep.err = ep.b.Delete(key)
}

func concat(a, b []byte) []byte {
	c := make([]byte, len(a))
	copy(c, a)

	return append(c, b...)
}


text:
package fi.tkk.tml.xformsdb.manager.xformsdb;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import fi.tkk.tml.xformsdb.core.Constants;
import fi.tkk.tml.xformsdb.error.ErrorConstants;
import fi.tkk.tml.xformsdb.error.ManagerException;

/**
 * Manage the logged in <xformsdb:widget-data-sources> element.
 *
 *
 * @author Markku Laine
 * @version 1.0	 Created on October 22, 2009
 */
public class XFormsDBWidgetDataSourcesManager {

	// PRIVATE STATIC FINAL VARIABLES
	private static final Logger logger	= Logger.getLogger( XFormsDBWidgetDataSourcesManager.class );

	// PRIVATE CONSTURCTORS
	// Prevent instantiation of this class
	private XFormsDBWidgetDataSourcesManager() {
		logger.log( Level.DEBUG, "Constructor has been called." );
	}

	// PUBLIC METHODS
	public static synchronized void setXFormsDBWidgetDataSources( HttpSession session, String xformsdbWidgetDataSources ) throws ManagerException {
		logger.log( Level.DEBUG, "Method has been called." );

		try {
			// Set the <xformsdb:widget-data-sources> element into the session
			session.setAttribute( Constants.SESSION_ATTRIBUTE_XFORMSDB_WIDGET_DATA_SOURCES, xformsdbWidgetDataSources );
			logger.log( Level.DEBUG, "The <xformsdb:widget-data-sources> element has been successfully set into the session." );
		} catch ( Exception ex ) {
			throw new ManagerException( ErrorConstants.ERROR_CODE_MANAGER_33, ErrorConstants.ERROR_MESSAGE_MANAGER_33, ex );
		}
	}

	public static synchronized void removeXFormsDBWidgetDataSources( HttpSession session ) throws ManagerException {
		logger.log( Level.DEBUG, "Method has been called." );

		try {
			// Remove the <xformsdb:widget-data-sources> element from the session
			session.removeAttribute( Constants.SESSION_ATTRIBUTE_XFORMSDB_WIDGET_DATA_SOURCES );
			logger.log( Level.DEBUG, "The <xformsdb:widget-data-sources> element has been successfully removed from the session." );
		} catch ( Exception ex ) {
			throw new ManagerException( ErrorConstants.ERROR_CODE_MANAGER_34, ErrorConstants.ERROR_MESSAGE_MANAGER_34, ex );
		}
	}

	public static synchronized String getXFormsDBWidgetDataSources( HttpSession session ) throws ManagerException {
		logger.log( Level.DEBUG, "Method has been called." );
		String xformsdbWidgetDataSources	= null;

		try {
			// Retrieve/write the <xformsdb:widget-data-sources> element from the session
			xformsdbWidgetDataSources		= ( String ) session.getAttribute( Constants.SESSION_ATTRIBUTE_XFORMSDB_WIDGET_DATA_SOURCES );
			logger.log( Level.DEBUG, "The <xformsdb:widget-data-sources> element has been successfully retrieved from the session." );
		} catch ( Exception ex ) {
			throw new ManagerException( ErrorConstants.ERROR_CODE_MANAGER_35, ErrorConstants.ERROR_MESSAGE_MANAGER_35, ex );
		}

		return xformsdbWidgetDataSources;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 324122 $ -->
<refentry xml:id="function.fdf-enum-values" xmlns="http://docbook.org/ns/docbook">
 <refnamediv>
  <refname>fdf_enum_values</refname>
  <refpurpose>Call a user defined function for each document value </refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>bool</type><methodname>fdf_enum_values</methodname>
   <methodparam><type>resource</type><parameter>fdf_document</parameter></methodparam>
   <methodparam><type>callable</type><parameter>function</parameter></methodparam>
   <methodparam choice="opt"><type>mixed</type><parameter>userdata</parameter></methodparam>
  </methodsynopsis>
  &warn.undocumented.func;
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
select n.listname as name, n.polygon,y2007,y2008,y2009,y2010,y2011,y2012,y2013

FROM

(
    SELECT name,listname, wkb_geometry as polygon FROM neighborhoods_philadelphia
) as n

LEFT JOIN

(
    SELECT listname,COUNT(*) as y2013 FROM (
        SELECT locationid, listname
        FROM neighborhoods_philadelphia
        INNER JOIN permit ON ST_Contains(wkb_geometry,point)
        WHERE DATE(issueddatetime) BETWEEN DATE('2013-01-01') AND DATE('2013-12-31')
        GROUP BY listname,locationid
    ) as a GROUP BY listname
) as a

ON n.listname = a.listname

LEFT JOIN

 (
    SELECT listname,COUNT(*) as y2012 FROM (
        SELECT locationid, listname
        FROM neighborhoods_philadelphia
        INNER JOIN permit ON ST_Contains(wkb_geometry,point)
        WHERE DATE(issueddatetime) BETWEEN DATE('2012-01-01') AND DATE('2012-12-31')
        GROUP BY listname,locationid
    ) as a GROUP BY listname
) as b

ON n.listname = b.listname

LEFT JOIN

 (
    SELECT listname,COUNT(*) as y2011 FROM (
        SELECT locationid, listname
        FROM neighborhoods_philadelphia
        INNER JOIN permit ON ST_Contains(wkb_geometry,point)
        WHERE DATE(issueddatetime) BETWEEN DATE('2011-01-01') AND DATE('2011-12-31')
        GROUP BY listname,locationid
    ) as a GROUP BY listname
) as c

ON n.listname = c.listname

LEFT JOIN

 (
    SELECT listname,COUNT(*) as y2010 FROM (
        SELECT locationid, listname
        FROM neighborhoods_philadelphia
        INNER JOIN permit ON ST_Contains(wkb_geometry,point)
        WHERE DATE(issueddatetime) BETWEEN DATE('2010-01-01') AND DATE('2010-12-31')
        GROUP BY listname,locationid
    ) as a GROUP BY listname
) as d

ON n.listname = d.listname

LEFT JOIN

 (
    SELECT listname,COUNT(*) as y2009 FROM (
        SELECT locationid, listname
        FROM neighborhoods_philadelphia
        INNER JOIN permit ON ST_Contains(wkb_geometry,point)
        WHERE DATE(issueddatetime) BETWEEN DATE('2009-01-01') AND DATE('2009-12-31')
        GROUP BY listname,locationid
    ) as a GROUP BY listname
) as e

ON n.listname = e.listname

LEFT JOIN

 (
    SELECT listname,COUNT(*) as y2008 FROM (
        SELECT locationid, listname
        FROM neighborhoods_philadelphia
        INNER JOIN permit ON ST_Contains(wkb_geometry,point)
        WHERE DATE(issueddatetime) BETWEEN DATE('2008-01-01') AND DATE('2008-12-31')
        GROUP BY listname,locationid
    ) as a GROUP BY listname
) as f

ON n.listname = f.listname

LEFT JOIN

 (
    SELECT listname,COUNT(*) as y2007 FROM (
        SELECT locationid, listname
        FROM neighborhoods_philadelphia
        INNER JOIN permit ON ST_Contains(wkb_geometry,point)
        WHERE DATE(issueddatetime) BETWEEN DATE('2007-01-01') AND DATE('2007-12-31')
        GROUP BY listname,locationid
    ) as a GROUP BY listname
) as g

ON n.listname = g.listname


text:
package com.example.anvil.databinding;

import android.content.Context;
import android.widget.LinearLayout;

import static trikita.anvil.DSL.*;
import trikita.anvil.RenderableView;

public class NumberPickerLayout extends RenderableView {

    int n = 0;

    public NumberPickerLayout(Context c) {
        super(c);
    }

    @Override
    public void view() {
        linearLayout(() -> {
            size(FILL, FILL);
            orientation(LinearLayout.VERTICAL);

            numberPickerLayout();
            numberPickerLayout();
        });
    }

    private void numberPickerLayout() {
        numberPicker(() -> {
            size(WRAP, WRAP);
            weight(1);
            layoutGravity(CENTER);

            minValue(0);
            maxValue(9);

            value(n);

            onValueChanged((picker, old, value) -> {
                n = value;
            });
        });
    }
}


text:
using System;
using MultiPacMan.Game;
using MultiPacMan.Pellet;
using MultiPacMan.Photon.Player.SerializersAndReceivers;
using MultiPacMan.Player;
using MultiPacMan.Player.Input;
using MultiPacMan.Player.Movement;
using MultiPacMan.Player.PelletEater;
using MultiPacMan.Player.Turbo;
using UnityEngine;

namespace MultiPacMan.Photon.Player {
    [RequireComponent (typeof (PhotonView))]
    public class PhotonLocalPlayer : IPlayer {

        public override TurboController TurboController {
            get {
                return GetComponent<LocalTurboController> ();
            }
        }

        protected override void AddComponents () {
            DesktopInputInterpreter inputInterpreter = Add<DesktopInputInterpreter> ();

            LocalTurboController turboController = Add<LocalTurboController> ();
            turboController.turboDelegate += inputInterpreter.IsTurboOn;

            LocalMovementController movementController = Add<LocalMovementController> ();
            movementController.directionDelegate += inputInterpreter.GetMovementDirection;
            movementController.turboDelegate += turboController.IsTurboOn;

            SpriteDirectionChanger.directionDelegate += inputInterpreter.GetMovementDirection;

            PelletEater pelletEater = Add<PelletEater> ();
            pelletEater.eatPelletDelegate += (PelletBehaviour pellet) => {
                pellet.AnimatePelletEaten ();

                int pelletId = pellet.Point.GetHashCode ();

                RaiseEventOptions options = new RaiseEventOptions ();
                options.CachingOption = EventCaching.AddToRoomCacheGlobal;
                options.Receivers = ReceiverGroup.MasterClient;

                PhotonNetwork.RaiseEvent ((byte) Events.EAT_PELLET_EVENT_CODE,
                    new object[1] { pelletId },
                    true, options
                );
            };

            PelletCollisionDetector collisionDetector = Add<PelletCollisionDetector> ();
            collisionDetector.collisionDelegate += pelletEater.EatPellet;

            PhotonPlayerInfoSerializer serializer = Add<PhotonPlayerInfoSerializer> ();
            serializer.positionDelegate += movementController.GetPosition;
            serializer.velocityDelegate += movementController.GetVelocity;

            this.gameObject.GetComponent<PhotonView> ().ObservedComponents.Add (serializer);
        }
    }
}