text:
<!doctype html>

		<meta charset="utf-8">

		<title>Programmera med Significant Bit</title>

		<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
		<meta name="author" content="Hakim El Hattab">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<link rel="stylesheet" href="css/reveal.min.css">
		<link rel="stylesheet" href="css/theme/solarized.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

		<link rel="stylesheet" href="css/extra.css">

Programmering

						Significant Bit

						Hej och välkomna! Vissa delar blir avancerade och jag förväntar mig inte att ni skall förstå allt.
						Jag kör igenom lite snabbt och sedan går vi runt och hjälper er igång.

Vilka är vi

						Jag kommer från ett företag som heter Significant Bit och heter Peter. Jag har med min kollega och bror Johan.

Vad jobbar vi med

						Vi är konsulter inom programmering.
						1. Webbutveckling
						2. Applikationer för iphone/android
						3. Spel och interaktiva system.

Varför programmera

Man vill slippa göra tråkiga saker

och göra roliga saker istället

						Datorer är ganska bra på att göra tråkiga repetitiva saker.
						Räkna på saker snabbt.

Vad är program

							Långa listor med instruktioner och vissa instruktioner som kan göra hopp till andra instruktioner. Addera, subtrahera, multiplicera, jämföra saker, flytta saker mellan minne och register.

Språk

							Vad har språk med program att göra?
							Vad är språk? Kan ni räkna upp några?
							Matematik?
							Svenska, engelska?

Programspråk

							Känner ni till några programspråk?
							Vad är liknande, grammatik, regler, meningar.

Maskinkod på hålkort

							Instruktioner som datorn direkt kan tolka.
							Programmet som det ser ut i minnet, och kan köras direkt av datorns CPU (hjärnan)
							Hål representerar bitar och ett hål är 0 och avsaknad av ett 1.

							Fungerar bara på den maskin som programmet är tänkt att köras på. Omständigt att flytta till andra typer av datorer. Omöjligt att förstå för en människa, datorer älskar sånt här!

Assembly

model small
.stack 100h

.data
msg     db      'Hello world!$'

.code
start:
        mov     ah, 09h   ; Display the message
        lea     dx, msg
        int     21h
        mov     ax, 4C00h  ; Terminate the executable
        int     21h

end start

							För att göra livet enklare och istället för att skriva maskinkod direkt.
							Namn på instruktioner-
							Lättare att läsa, fungerar bara på en viss typ av maskin, fortfarande rätt svårt, många instruktioner att lära sig utantill, spagettitrasselkod
							Assemblator översätter till maskinkod.
							flytta 09h till register ah.
							ladda effekt address till register dx.
							anropa interupt 21
							flytta 4c00h till register ax
							anropa interupt 21

C

#include <stdio.h>
int main(int argc, char *argv[])
{
	printf("Hello Wordl!\n");
	return 0;
}

							C ett av världens mest använda språk,
							För att få ett körbart program måste man först kompilera programmet, kan kompilera till olika datorer.
							Men måste kompileras om för varje dator.

							Mer läsbart än assembler, lättare att hitta fel, kompilatorn varnar för "dumma saker"

							Loopar och variabler

C#

// A Hello World! program in C#.
using System;
namespace HelloWorld
{
    class Hello
    {
        static void Main()
        {
            Console.WriteLine("Hello World!");
        }
    }
}

							C# är ett programspråk från Microsoft, kompileras också men istället till ett format som en virtuell maskin kan köra, ett slags program som kör program.
							Fördelen är att man inte behöver kompilera om programmet så länge den virtuella maskinen finns för datorn man vill köra programmet på.

							Objektorienterat, bra på att kapsla in beteende, kompilatorn kan varna för fel.

							Långsammare än C, men bättre möjlighet att sturkturera program

							Java är väldigt likt C# och körs också på en virtuellmaskin

Ruby

class Hello
  def say_hello
    puts "hello"
  end
end

program = Hello.new
program.say_hello

							Ruby är ett interpreterat språk.
							Körs av en tolk och översätts inte till maskinkod, istället tolkar tolken programmet medans det körs.

							Lätt att ändra i program, kan köras på alla datorer där det finns en tolk som förstår språket. Metaprogrammering, alltså propgram som skriver program är lättare.

							Python, php

Varför olika språk

För att olika saker är viktiga

Prestanda

Portabelt

Uttrycksfullt

Struktur

Tycke och smak

Vi skall titta på Ruby

							Vi programmerar mycket i Ruby,
							Bra för webbutveckling,
							Kraftfullt lite kod mycket verkstad.
							Riktigt språk, kan köras på många typer av datorer.

Centrala begrepp för programmering

						För att lära sig programmera är det bra om man har ett hum om några begrepp.

Variabel

						En namngiven plats i datorns minne, en slags förvaringslåda.

						Samma sak i matten (den där x)

						Variabler i Ruby skrivs med små bokstäver t.ex.

							omkrets = 3.145

						omkrets är en variabel här, man kan plocka fram värdet som är sparat i variabeln och använda den och man kan spara nya värden i variabeln.

Värde

						Ett värde är något man kan lagra i en variabel.

						Till exempel ett tal med värdet 12 eller en text med värdet "hej"

Typ

						Alla värden har en typ, typen beskriver hur värdet skall tolkas och vad man kan göra med det.

						Man kan säga att typen gör att innehållet får en betydelse.

						Några exempel på några (udda)typer:

								Heltal/Integers: 102

Flyttal/Floats: 1.20

Strängar/Strings: "hejsan"

Boolesk/Boolean: true/false

						 En dator arbetar bara med binära tal, för att veta hur man skall behandla annan data, strängar t.ex. så representeras detta på olika sätt i datorn men alltid med bitar. Därför behövs olika typer för att beskriva detta.

Uttryck

						Man kan sätta samman värden, variabler, operatorer och funktioner till uttryck.

						Till exempel kan man använda de fyra räknesätten på tal, och slå samman strängar och olika logiska operatorer för boolesk typer (och, eller, icke)

ett_tal = 1*10+20-2/10
en_strng = "Hejsan" + " Du gamle indian"
boolesk = a || b && !c

						 Uttryck är en kombination värden, variabler, operatorer och funktioner och spottar tillbaka ett nytt värde.
						 Uttryck kan vara allt från en enda variabel till ett sammansatt uttryck av många variabler, operatorer och funktioner.

Tilldelning

						Innebär att man ger en variabel ett värde. I de flesta språk symboliseras tilldelning med =

						Nedan syns ett exempel på tilldelning, vi beräknar omkretsen av en cirkel med uttrycket på höger sida om tilldelningen. Alltså beräknas en cirkels omkrets från radien och tilldelas variabeln omkrets.

omkrets = 3.14 * 2 * radie

						Tilldelning sparar värden från uttryck.

Funktion

						En funktion en uppsättning instruktioner som körs efter varandra, man använder dem för att få byggblock som man kan återanvända

						Funktioner har ett namn och kan utföra ett "arbete". De kan också ta parameterar och skicka tillbaka, returnera, ett värde.

def omkrets(radie)
	puts "Beräknar omkretsen av en cirkel"
	return 3.14*2*radie
end

Repetition, Upprepning, Loopar

Repetition, Upprepning, Loopar

						Innebär att programmet kommer upprepa en uppsättning instruktioner tills dess att något vilkor eventuellt avbryter.

sum = 0
i = 0
while i < 10 do #Upprepa medans i är mindre än 10
	sum = sum + i
	i = i + 1
end

sum = 0
for i in 0..9
	sum = sum + i
end

						For, while, each, reduce, map osv

Alternativ

						Betyder att datorn kan välja väg med hjälp av logiska uttryck. Alltså uttryck som antingen blir sanna eller falska.

 == Jämför värden, i exemplet jämförs värdet 42 med det som finns i variabeln svar.

puts "Vad är svaret på allt?"
svar = gets.to_i() #Läs in tal från tangentbordet
if(svar == 42)
	puts "Rätt svar"
else
	puts "Fel svar"
end

						Datorn kan välja väg genom programmet beroende på hur uttryck tolkas.

Objektorienterad programmering / OOP

Ganska avancerat koncept

						Vi går över på att prata om OOP, kallar det OOP.
						Ruby är ett objektorienterat språk.

						Betyder att man bryter ned problem genom att fundera på hur objekt kan samverka. Istället för att bara ordna program med hjälp av funktioner bryter man ner programmet i objekt.
						Objekten inkapslar både funktioner och data

OOP - Klasser

						Klasser är en användardefinierad typ.

						På samma sätt som heltal eller strängar i Ruby.

						En instans av en klass kallas objekt. Klassen är abstrakt, t.ex. Bok medan en instans av en klass kan vara en viss bok.

						När man gör nya objekt från en klass i Ruby använder man funktionen new på klassen.

class Bok #Klass definition
  def initialize(name)
    @name = name
  end

  def name()
    return @name
  end
end

hitchiker = Bok.new("The Hitchhiker's Guide to the Galaxy")
puts hitchiker.name() #Skriver ut namnet på boken

						Initialize constructor.
						Visa anrop till name i puts

Konstruktor

						Har hand om att ställa in det nya objektet så att det är redo att användas.

						Funktionen heter initialize och kan ta parameterar

class Bok
  def initialize(name)  #Konstruktor
    @name = name
  end

  def name()
    return @name
  end
end

hitchiker = Bok.new("The Hitchhiker's Guide to the Galaxy")
puts hitchiker.name() #Skriver ut namnet på boken

						inga, en eller flera parametrar
						värdet i new skickas till initialize

Instansvariabler

						Är variabler som kan nås från alla funktioner i klassen.

						@name är en instansvariabel. Det betyder att objektet har en variabel som kan nås från alla funktioner. Gör vi en ny Bok kommer den få en egen instansvariabel.

						Instansvariabler startar alltid med ett @

class Bok
  def initialize(name)  #Konstruktor
    @name = name
  end

  def name()
    return @name
  end
end

hitchiker = Bok.new("The Hitchhiker's Guide to the Galaxy")
puts hitchiker.name() #Skriver ut namnet på boken

						Nås ifrån olika funktioner i en klass.
						Delas inte mellan olika objekt

nog

						pratat mycket, väldigt abstrakt och ganska läskigt.
						Man behöver inte kunna allt direkt, läs program,

Demon/Frågor

http://tryruby.org / kidsruby


text:
package consulo.unity3d.shaderlab.lang;

import java.util.List;

import javax.annotation.Nonnull;

import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.CustomFoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import consulo.unity3d.shaderlab.lang.psi.ShaderBraceOwner;
import consulo.unity3d.shaderlab.lang.psi.ShaderRoleOwner;
import consulo.unity3d.shaderlab.lang.psi.SharpLabElementVisitor;

/**
 * @author VISTALL
 * @since 09.05.2015
 */
public class ShaderLabFoldingBuilder extends CustomFoldingBuilder
{
	@Override
	protected void buildLanguageFoldRegions(@Nonnull final List<FoldingDescriptor> descriptors, @Nonnull PsiElement root, @Nonnull Document document, boolean quick)
	{
		root.accept(new SharpLabElementVisitor()
		{
			@Override
			public void visitElement(PsiElement element)
			{
				if(element instanceof ShaderBraceOwner)
				{
					descriptors.add(new FoldingDescriptor(element, element.getTextRange()));
				}
				element.acceptChildren(this);
			}
		});
	}

	@Override
	protected String getLanguagePlaceholderText(@Nonnull ASTNode node, @Nonnull TextRange range)
	{
		PsiElement psi = node.getPsi();
		assert psi instanceof ShaderRoleOwner : psi.getClass().getSimpleName();
		PsiElement firstChild = psi.getFirstChild();
		return firstChild.getText();
	}

	@Override
	protected boolean isRegionCollapsedByDefault(@Nonnull ASTNode node)
	{
		return false;
	}
}

redpajama_set_name: RedPajamaGithub


text:
.genericPropertyForm {

}
.genericPropertyForm h2 {
    font-size: 16px;
    line-height: 20px;
    margin-bottom: 2px;
}

.genericPropertyList .header{
    padding: 4px;
}
.genericPropertyList .umb-pane{
    margin: 10px;
}

.genericPropertyList {
  margin: 0px 0px 30px 0px;
  list-style: none;
}

.genericPropertyList .delete-button, .genericPropertyList .toggle-button{
  float: right;
  margin-left: 3px;
  border: none;
  background: none;
  text-decoration: none;
}

.genericPropertyList .delete-button i {
    background: none;
    border: none;
}

.handle{
    color: #ccc;
    font-size: 12px;
}

.addNewProperty .handle {
    display: none;
}

.genericPropertyList li {
  display: block;
  position: relative;
  border-bottom: 1px solid #eee;
  margin-bottom: 3px;
  cursor: move;
}

.genericPropertyList li .delete-button i {
    color: #b94a48;
}

.addNewProperty li {
  cursor: default;
}

.genericPropertyList li table {
  display: block;
  margin-top: 10px;
}

.genericPropertyList li table th {
  width: 140px;
  padding: 5px;
}

.propertyFormInput {
  width: 300px;
  z-index: 9999;
}

.propertyForm SELECT {
  width: 300px;
}

.propertyForm h3 a {
  color: #000;
  text-decoration: none;
  font-size: 14px;
  font-weight: normal;
}

.genericPropertyList li img {
  background: red;
  z-index: 9999;
  position: relative;
  border-right: medium none;
  border-top: medium none;
  border-left: medium none;
  margin-right: 5px;
  border-bottom: medium none;
}
.genericPropertyList li h3 input {
  position: relative;
}

.aliasValidationError
{
    background-color: #ff9999;
    border: 1px solid: red;
}


text:
/**
 * make sure overrides get's called first!
 * - keeping the overrides import here works for installing Ghost as npm!
 *
 * the call order is the following:
 * - root index requires core module
 * - core index requires server
 * - overrides is the first package to load
 */
require('./overrides');

const debug = require('ghost-ignition').debug('boot:init');
const Promise = require('bluebird');
const config = require('./config');
const {events, i18n, logging} = require('./lib/common');
const migrator = require('./data/db/migrator');
const urlUtils = require('./lib/url-utils');
let parentApp;

// Frontend Components
const themeService = require('../frontend/services/themes');
const appService = require('../frontend/services/apps');

function initialiseServices() {
    // CASE: When Ghost is ready with bootstrapping (db migrations etc.), we can trigger the router creation.
    //       Reason is that the routers access the routes.yaml, which shouldn't and doesn't have to be validated to
    //       start Ghost in maintenance mode.
    // Routing is a bridge between the frontend and API
    const routing = require('../frontend/services/routing');
    // We pass the themeService API version here, so that the frontend services are less tightly-coupled
    routing.bootstrap.start(themeService.getApiVersion());

    const permissions = require('./services/permissions');
    const xmlrpc = require('./services/xmlrpc');
    const slack = require('./services/slack');
    const {mega} = require('./services/mega');
    const webhooks = require('./services/webhooks');
    const scheduling = require('./adapters/scheduling');

    debug('`initialiseServices` Start...');

    return Promise.join(
        // Initialize the permissions actions and objects
        permissions.init(),
        xmlrpc.listen(),
        slack.listen(),
        mega.listen(),
        webhooks.listen(),
        appService.init(),
        scheduling.init({
            // NOTE: When changing API version need to consider how to migrate custom scheduling adapters
            //       that rely on URL to lookup persisted scheduled records (jobs, etc.). Ref: https://github.com/TryGhost/Ghost/pull/10726#issuecomment-489557162
            apiUrl: urlUtils.urlFor('api', {version: 'v3', versionType: 'admin'}, true)
        })
    ).then(function () {
        debug('XMLRPC, Slack, MEGA, Webhooks, Scheduling, Permissions done');

        // Initialise analytics events
        if (config.get('segment:key')) {
            require('./analytics-events').init();
        }
    }).then(function () {
        debug('...`initialiseServices` End');
    });
}

/**
 * - initialise models
 * - initialise i18n
 * - load all settings into settings cache (almost every component makes use of this cache)
 * - load active theme
 * - create our express apps (site, admin, api)
 * - start the ghost server
 * - enable maintenance mode if migrations are missing
 */
const minimalRequiredSetupToStartGhost = (dbState) => {
    const settings = require('./services/settings');
    const models = require('./models');
    const GhostServer = require('./ghost-server');

    // Frontend
    const frontendSettings = require('../frontend/services/settings');

    let ghostServer;

    // Initialize Ghost core internationalization
    i18n.init();
    debug('Default i18n done for core');

    models.init();
    debug('Models done');

    return settings.init()
        .then(() => {
            debug('Settings done');

            return frontendSettings.init();
        })
        .then(() => {
            debug('Frontend settings done');
            return themeService.init();
        })
        .then(() => {
            debug('Themes done');

            parentApp = require('./web/parent/app')();
            debug('Express Apps done');

            return new GhostServer(parentApp);
        })
        .then((_ghostServer) => {
            ghostServer = _ghostServer;

            // CASE: all good or db was just initialised
            if (dbState === 1 || dbState === 2) {
                events.emit('db.ready');

                return initialiseServices()
                    .then(() => {
                        return ghostServer;
                    });
            }

            // CASE: migrations required, put blog into maintenance mode
            if (dbState === 4) {
                logging.info('Blog is in maintenance mode.');

                config.set('maintenance:enabled', true);

                migrator.migrate()
                    .then(() => {
                        events.emit('db.ready');
                        return initialiseServices();
                    })
                    .then(() => {
                        config.set('maintenance:enabled', false);
                        logging.info('Blog is out of maintenance mode.');
                        return GhostServer.announceServerStart();
                    })
                    .catch((err) => {
                        return GhostServer.announceServerStopped(err)
                            .finally(() => {
                                logging.error(err);
                                setTimeout(() => {
                                    process.exit(-1);
                                }, 100);
                            });
                    });

                return ghostServer;
            }
        });
};

/**
 * Connect to database.
 * Check db state.
 */
const isDatabaseInitialisationRequired = () => {
    const db = require('./data/db/connection');
    let dbState;

    return migrator.getState()
        .then((state) => {
            dbState = state;

            // CASE: db initialisation required, wait till finished
            if (dbState === 2) {
                return migrator.dbInit();
            }

            // CASE: is db incompatible? e.g. you can't connect a 0.11 database with Ghost 1.0 or 2.0
            if (dbState === 3) {
                return migrator.isDbCompatible(db)
                    .then(() => {
                        dbState = 2;
                        return migrator.dbInit();
                    });
            }
        })
        .then(() => {
            return minimalRequiredSetupToStartGhost(dbState);
        });
};

module.exports = isDatabaseInitialisationRequired;


text:
<?php

// Padrao do CI para não acessar a Classe direto pelo Browser
if (!defined('BASEPATH'))
	exit('No direct script access allowed');

/**
 * Layout Class
 *
 * @package hooks
 * @description Implementa as views do tipo layout no framework.
 */
class Layout {

	public $base_url;

	/**
	 * Metodo que executa as implementacoes.
	 * Este metodo e chamado atraves do arquivo hooks.php
	 * na pasta config.
	 *
	 * @return
	 */
	public function init() {
		// Instancia do CI.
		$CI = & get_instance();

		// Definindo o base_url.
		$this->base_url = $CI->config->slash_item('base_url');

		// Pegando a saida que o CI gera normalmente.
		$output = $CI->output->get_output();

		// Pegando o valor de title, se definido no controller.
		$title = (isset($CI->title)) ? $CI->title : '';

		// Links CSS definidos no controlador.
		$css = (isset($CI->css)) ? $this->createCSSLinks($CI->css) : '';

		// Links JS definidos no controlador.
		$js = (isset($CI->js)) ? $this->createJSLinks($CI->js) : '';

		// Se layout estiver definido e a regexp nao bater.
		if (isset($CI->layout) && !preg_match('/(.+).php$/', $CI->layout)) {
			$CI->layout .= '.php';
		} else {
			$CI->layout = 'default.php';
		}

		// Definindo caminho completo do layout.
		$layout = LAYOUTPATH . $CI->layout;

		// Se o layout for diferente do default, e o arquivo nao existir.
		if ($CI->layout !== 'default.php' && !file_exists($layout) && $CI->layout != '') {
		// Exibe a mensagem, se o layout for diferente de '.php'.
			if ($CI->layout != '.php') show_error("You have specified a invalid layout: " . $CI->layout);
		}

		// Se o arquivo layout existir.
		if (file_exists($layout)) {

			// Carrega o conteudo do  arquivo.
			$layout = $CI->load->file($layout, true);

			// Substitui o texto {content_for_layout} pelo valor de output em layout.
			$view = str_replace('{content_for_layout}', $output, $layout);

			// Substitui o texto {title_for_layout} pelo valor de title em view.
			$view = str_replace('{title_for_layout}', $title, $view);

			// Links CSS.
			$view = str_replace('{css_for_layout}', $css, $view);

			// Links JS.
			$view = str_replace('{js_for_layout}', $js, $view);
		} else {
			$view = $output;
		}

		echo $view;
	}

	/**
	 * Gera os links CSS utilizados no layout.
	 *
	 * @return void
	 */
	private function createCSSLinks($links) {
		$html = '';

		for ($i = 0; $i < count($links); $i++) {
			$html .= "<link rel='stylesheet' type='text/css' href='" . $this->base_url . 'application/css/' . $links[$i] . ".css?". filemtime(CSSPATH . $links[$i].'.css') ."' media='screen' />";
		}
		return $html;
	}

	/**
	 * Gera os links JS utilizados no layout.
	 *
	 * @return void
	 */
	private function createJSLinks($links) {
		$html = "";

		for ($i = 0; $i < count($links); $i++) {
			$html .= "<script type='text/javascript' src='" . $this->base_url . 'application/js/' . $links[$i] . ".js?". filemtime(JSPATH . $links[$i].'.js') ."'></script>";
		}
		return $html;
	}
}


text:
import { CdkVirtualForOf, CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
import { EventEmitter, NgZone } from '@angular/core';
import { fakeAsync, tick } from '@angular/core/testing';
import { of, Subscription } from 'rxjs';
import { ViewportChangeDirective } from './viewport-change.directive';

describe('ViewportChangeDirective', () => {

    let directive: ViewportChangeDirective;

    let zone: jasmine.SpyObj<NgZone>;
    let viewport: jasmine.SpyObj<CdkVirtualScrollViewport>;

    beforeEach(() => {

        zone = jasmine.createSpyObj<NgZone>('NgZone', ['run']);
        viewport = jasmine.createSpyObj<CdkVirtualScrollViewport>('CdkVirtualScrollViewport', [
            'elementScrolled',
            'measureScrollOffset',
            'getViewportSize'
        ]);

        directive = new ViewportChangeDirective(zone, viewport);
    });

    it('should create', () => {
        expect(directive).toBeTruthy();
    });
    it('time === 20', () => {
        expect(directive.time).toEqual(20);
    });
    it('viewChange', () => {
        expect(directive.viewChange instanceof EventEmitter).toEqual(true);
    });
    it('subscription', () => {
        expect(directive.subscription instanceof Subscription).toEqual(true);
    });

    describe('ngOnInit', () => {

        beforeEach(() => {
            spyOn(directive, 'emit');
            viewport.elementScrolled.and.returnValue(of(null));
        });

        it('with forOf (3 source of data)', fakeAsync(() => {
            directive.forOf = { dataStream: of(null) } as CdkVirtualForOf<any>;
            directive.ngOnInit();

            tick(directive.time);

            expect(viewport.elementScrolled).toHaveBeenCalled();
            expect(directive.emit).toHaveBeenCalledTimes(1);
        }));
        it('without', fakeAsync(() => {
            directive.ngOnInit();

            tick(directive.time);

            expect(viewport.elementScrolled).toHaveBeenCalled();
            expect(directive.emit).toHaveBeenCalledTimes(1);
        }));

        afterEach(() => directive.ngOnDestroy());
    });

    it('ngOnDestroy', () => {
        directive.ngOnDestroy();
        expect(directive.subscription.closed).toEqual(true);
    });
    it('emitViewChange', () => {
        spyOn(directive.viewChange, 'emit');
        zone.run.and.callFake(fn => fn());
        viewport.measureScrollOffset.and.returnValue(2500);
        viewport.getViewportSize.and.returnValue(900);

        const start = 12.5;
        const end = 17;
        directive.itemSize = 200;

        directive.emit();

        expect(directive.viewChange.emit).toHaveBeenCalledWith({ start, end });
    });
});


text:
package com.teliasonera.iptv.docker;

import org.junit.After;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;

import io.fabric8.docker.api.model.NetworkCreateResponse;
import io.fabric8.docker.api.model.NetworkResource;
import io.fabric8.docker.client.Config;
import io.fabric8.docker.client.ConfigBuilder;
import io.fabric8.docker.client.DefaultDockerClient;
import io.fabric8.docker.client.DockerClient;
import io.fabric8.docker.dsl.network.AllFiltersInterface;
import io.fabric8.docker.dsl.network.NetworkInterface;

import static org.assertj.core.api.Assertions.*;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class Networks {

    private Logger logger = LoggerFactory.getLogger(Networks.class);

    private DockerClient client;

    private static final String NETWORK_NAME = "alfa-net";

    @Before
    public void createClient() {
        Config config = new ConfigBuilder()
                .withDockerUrl("unix:///var/run/docker.sock")
                .build();

        client = new DefaultDockerClient(config);
    }

    @After
    public void closeClient() {
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void create() {
        NetworkCreateResponse res = client.network().createNew().withName(NETWORK_NAME).withDriver("bridge").done();
        logger.info(res.toString());
        assertThat(res.getId()).isNotEmpty();
    }

    @Test
    public void inspect() {

        NetworkResource inspect = client.network().withName(NETWORK_NAME).inspect();
        logger.info(inspect.toString());
        logger.info("Inspecting network: {}",inspect.getName());
        assertThat(inspect.getName()).isEqualToIgnoringCase(NETWORK_NAME);
    }

    @Test
    public void listAll() {

        NetworkInterface network = client.network();
        AllFiltersInterface<List<NetworkResource>> list = network.list();
        List<NetworkResource> all = list.all();
        boolean alfaNetFound = false;
        for(NetworkResource nr : all) {
            if(nr.getName().equalsIgnoreCase(NETWORK_NAME)) {
                alfaNetFound = true;
            }
        }
        assertThat(alfaNetFound).isEqualTo(true);
        assertThat(client.network().list().all().size()).isGreaterThan(0);
    }

    @Test
    public void remove() {
        boolean deleted = client.network().withName(NETWORK_NAME).delete();
        logger.info("{} is deleted: {}",NETWORK_NAME,deleted);
        assertThat(deleted).isEqualTo(true);
    }

}


text:
module.exports = {
  env: process.env.NODE_ENV || process.env.npm_package_config_env,
  serverPort: process.env.SERVER_PORT || process.env.npm_package_config_serverPort,
  serverHost: process.env.SERVER_HOST || process.env.npm_package_config_serverHost,
  publicPath: process.env.PUBLIC_PATH || process.env.npm_package_config_publicPath,

  webpackServer () {
    return require('./webpack')(
      Object.assign({mode: 'server'}, module.exports)
    );
  },
  webpackClient () {
    return require('./webpack')(
      Object.assign({mode: 'client'}, module.exports)
    );
  }
};


text:
#ifndef __DUMMY_OUT_STREAM_H
#define __DUMMY_OUT_STREAM_H

#include "../../../Common/MyCom.h"

#include "../../IStream.h"

class CDummyOutStream:
  public ISequentialOutStream,
  public CMyUnknownImp
{
  CMyComPtr<ISequentialOutStream> _stream;
  UInt64 _size;
public:
  void SetStream(ISequentialOutStream *outStream) { _stream = outStream; }
  void ReleaseStream() { _stream.Release(); }
  void Init() { _size = 0; }
  MY_UNKNOWN_IMP
  STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
  UInt64 GetSize() const { return _size; }
};

#endif


text:
'use strict'

var locator = require('node-service-locator');
var request = require('supertest');
var q = require('q');
var app = require('../../app.js');
var Acl = require('../../services/acl');
var UserModel = require('../../models/user');
var RoleModel = require('../../models/role');
var PermissionModel = require('../../models/permission');

describe('ACL service', function () {
    var config;
    var acl;
    var user;

    beforeEach(function () {
        config = locator.get('config');
        locator.register('logger', {
            log: function () {},
            trace: function () {},
            debug: function () {},
            info: function () {},
            warn: function () {},
            error: function () {},
        });
        acl = new Acl();
        user = new UserModel({ id: 42 });
    });

    afterEach(function () {
    });

    it('inherits roles', function (done) {
        var role1 = new RoleModel({ id: 1, parent_id: null });
        var role2 = new RoleModel({ id: 2, parent_id: 1 });
        var role3 = new RoleModel({ id: 3, parent_id: 1 });

        locator.register('role-repository', {
            find: function (id) {
                var defer = q.defer();
                if (id == 1)
                    defer.resolve([ role1 ]);
                else if (id == 2)
                    defer.resolve([ role2 ]);
                else if (id == 3)
                    defer.resolve([ role3 ]);
                return defer.promise;
            },
            findByUserId: function (id) {
                var defer = q.defer();
                defer.resolve([ role2 ]);
                return defer.promise;
            },
        });
        locator.register('permission-repository', {
            findByRoleId: function (id) {
                var defer = q.defer();
                if (id == 1)
                    defer.resolve([ new PermissionModel({ resource: 'resource1', action: 'action1' }) ]);
                else if (id == 2)
                    defer.resolve([ new PermissionModel({ resource: 'resource2', action: 'action2' }) ]);
                else if (id == 3)
                    defer.resolve([ new PermissionModel({ resource: 'resource3', action: 'action3' }) ]);
                return defer.promise;
            },
        });

        acl.isAllowed(user, 'resource1', 'action1')
            .then(function (allowed) {
                expect(allowed).toBeTruthy();

                acl.isAllowed(user, 'resource2', 'action2')
                    .then(function (allowed) {
                        expect(allowed).toBeTruthy();

                        acl.isAllowed(user, 'resource3', 'action3')
                            .then(function (allowed) {
                                expect(allowed).toBeFalsy();

                                done();
                            });
                    });
            });
    });

    it('supports wildcard for resource', function (done) {
        var role = new RoleModel({ id: 1, parent_id: null });

        locator.register('role-repository', {
            find: function (id) {
                var defer = q.defer();
                if (id == 1)
                    defer.resolve([ role ]);
                return defer.promise;
            },
            findByUserId: function (id) {
                var defer = q.defer();
                defer.resolve([ role ]);
                return defer.promise;
            },
        });
        locator.register('permission-repository', {
            findByRoleId: function (id) {
                var defer = q.defer();
                if (id == 1)
                    defer.resolve([ new PermissionModel({ resource: null, action: 'action1' }) ]);
                return defer.promise;
            },
        });

        acl.isAllowed(user, 'resource1', 'action1')
            .then(function (allowed) {
                expect(allowed).toBeTruthy();

                acl.isAllowed(user, 'resource2', 'action1')
                    .then(function (allowed) {
                        expect(allowed).toBeTruthy();

                        acl.isAllowed(user, 'resource3', 'action3')
                            .then(function (allowed) {
                                expect(allowed).toBeFalsy();

                                done();
                            });
                    });
            });
    });

    it('supports wildcard for action', function (done) {
        var role = new RoleModel({ id: 1, parent_id: null });

        locator.register('role-repository', {
            find: function (id) {
                var defer = q.defer();
                if (id == 1)
                    defer.resolve([ role ]);
                return defer.promise;
            },
            findByUserId: function (id) {
                var defer = q.defer();
                defer.resolve([ role ]);
                return defer.promise;
            },
        });
        locator.register('permission-repository', {
            findByRoleId: function (id) {
                var defer = q.defer();
                if (id == 1)
                    defer.resolve([ new PermissionModel({ resource: 'resource1', action: null }) ]);
                return defer.promise;
            },
        });

        acl.isAllowed(user, 'resource1', 'action1')
            .then(function (allowed) {
                expect(allowed).toBeTruthy();

                acl.isAllowed(user, 'resource1', 'action2')
                    .then(function (allowed) {
                        expect(allowed).toBeTruthy();

                        acl.isAllowed(user, 'resource3', 'action3')
                            .then(function (allowed) {
                                expect(allowed).toBeFalsy();

                                done();
                            });
                    });
            });
    });

    it('supports wildcard for both', function (done) {
        var role = new RoleModel({ id: 1, parent_id: null });

        locator.register('role-repository', {
            find: function (id) {
                var defer = q.defer();
                if (id == 1)
                    defer.resolve([ role ]);
                return defer.promise;
            },
            findByUserId: function (id) {
                var defer = q.defer();
                defer.resolve([ role ]);
                return defer.promise;
            },
        });
        locator.register('permission-repository', {
            findByRoleId: function (id) {
                var defer = q.defer();
                if (id == 1)
                    defer.resolve([ new PermissionModel({ resource: null, action: null }) ]);
                return defer.promise;
            },
        });

        acl.isAllowed(user, 'resource', 'action')
            .then(function (allowed) {
                expect(allowed).toBeTruthy();

                done();
            });
    });
});


text:
//
//  XFDialogAnimationUtil.h
//  XFDialogBuilder
//
//  Created by 付星 on 16/6/24.
//  Copyright © 2016年 yizzuide. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "XFDialogBuilder.h"

@interface XFDialogAnimationUtil : NSObject

/**
 *  推入对话框动画
 *
 *  @return 动画Block
 */
+ (addAnimationEngineBlock)topToCenter;
/**
 *  退出对话框动画
 *
 *  @return 动画Block
 */
+ (addAnimationEngineBlock)centerToTop;

@end


text:
module Piwik
  class Site < Piwik::Base
    attr_accessor :name, :main_url
    attr_reader :id, :created_at, :config

    # Initializes a new <tt>Piwik::Site</tt> object, with the supplied attributes.
    #
    # You can pass the URL for your Piwik install and an authorization token as
    # the second and third parameters. If you don't, than it will try to find
    # them in a <tt>'~/.piwik'</tt> (and create the file with an empty template if it
    # doesn't exists).
    #
    # Valid (and required) attributes are:
    # * <tt>:name</tt> - the site's name
    # * <tt>:main_url</tt> - the site's url
    def initialize(attributes={}, piwik_url=nil, auth_token=nil)
      raise ArgumentError, "expected an attributes Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash)
      @config = if piwik_url.nil? || auth_token.nil?
        self.class.load_config_from_file
      else
        {:piwik_url => piwik_url, :auth_token => auth_token}
      end
      load_attributes(attributes)
    end

    # Returns an instance of <tt>Piwik::Site</tt> representing the site identified by
    # the supplied <tt>site_id</tt>. Raises a <tt>Piwik::ApiError</tt> if the site doesn't
    # exists or if the user associated with the supplied auth_token does not
    # have at least 'view' access to the site.
    #
    # You can pass the URL for your Piwik install and an authorization token as
    # the second and third parameters. If you don't, than it will try to find
    # them in a <tt>'~/.piwik'</tt> (and create the file with an empty template if it
    # doesn't exists).
    def self.load(site_id, piwik_url=nil, auth_token=nil)
      raise ArgumentError, "expected a site Id" if site_id.nil?
      @config = if piwik_url.nil? || auth_token.nil?
        load_config_from_file
      else
        {:piwik_url => piwik_url, :auth_token => auth_token}
      end
      attributes = get_site_attributes_by_id(site_id, @config[:piwik_url], @config[:auth_token])
      new(attributes, @config[:piwik_url], @config[:auth_token])
    end

    # Returns <tt>true</tt> if the current site does not exists in the Piwik yet.
    def new?
      id.nil? && created_at.nil?
    end

    # Saves the current site in Piwik.
    #
    # Calls <tt>create</tt> it it's a new site, <tt>update</tt> otherwise.
    def save
      new? ? create : update
    end

    # Saves the current new site in Piwik.
    #
    # Equivalent Piwik API call: SitesManager.addSite (siteName, urls)
    def create
      raise ArgumentError, "Site already exists in Piwik, call 'update' instead" unless new?
      raise ArgumentError, "Name can not be blank" if name.blank?
      raise ArgumentError, "Main URL can not be blank" if main_url.blank?
      xml = call('SitesManager.addSite', :siteName => name, :urls => main_url)
      result = XmlSimple.xml_in(xml, {'ForceArray' => false})
      @id = result.to_i
      @created_at = Time.current
      id && id > 0 ? true : false
    end

    # Saves the current site in Piwik, updating it's data.
    #
    # Equivalent Piwik API call: SitesManager.updateSite (idSite, siteName, urls)
    def update
      raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
      raise ArgumentError, "Name can not be blank" if name.blank?
      raise ArgumentError, "Main URL can not be blank" if main_url.blank?
      xml = call('SitesManager.updateSite', :idSite => id, :siteName => name, :urls => main_url)
      result = XmlSimple.xml_in(xml, {'ForceArray' => false})
      result['success'] ? true : false
    end

    def reload
      #TODO
    end

    # Deletes the current site from Piwik.
    #
    # Equivalent Piwik API call: SitesManager.deleteSite (idSite)
    def destroy
      raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
      xml = call('SitesManager.deleteSite', :idSite => id)
      result = XmlSimple.xml_in(xml, {'ForceArray' => false})
      freeze
      result['success'] ? true : false
    end

    # Gives read access (<tt>'view'</tt>) to the supplied user login for the current
    # site.
    def give_view_access_to(login)
      give_access_to(:view, login)
    end

    # Gives read and write access (<tt>'admin'</tt>) for the supplied user login for the
    # current site.
    def give_admin_access_to(login)
      give_access_to(:admin, login)
    end

    # Removes all access (gives an <tt>'noaccess'</tt>) for the supplied user login for
    # the current site.
    def give_no_access_to(login)
      give_access_to(:noaccess, login)
    end
    alias_method :remove_access_from, :give_no_access_to

    # Returns a hash with a summary of access information for the current site
    # (visits, unique visitors, actions / pageviews, maximum actions per visit,
    # bounces and total time spent in all visits in seconds), filtered by the
    # supplied period and date.
    #
    # * <tt>period</tt> should be one of <tt>:day</tt>, <tt>:week</tt>, <tt>:month</tt> or <tt>:year</tt> (default: <tt>:day</tt>)
    # * <tt>date</tt> should be a <tt>Date</tt> object (default: <tt>Date.today</tt>)
    #
    # Equivalent Piwik API call: VisitsSummary.get (idSite, period, date)
    def summary(period=:day, date=Date.today)
      raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
      xml = call('VisitsSummary.get', :idSite => id, :period => period, :date => date)
      result = XmlSimple.xml_in(xml, {'ForceArray' => false})
      {
        :visits => result['nb_visits'].to_i,
        :unique_visitors => result['nb_uniq_visitors'].to_i,
        :actions => result['nb_actions'].to_i,
        :max_actions_per_visit => result['max_actions'].to_i,
        :bounces => result['bounce_count'].to_i,
        :total_time_spent => result['sum_visit_length'].to_i, # in seconds
      }
    end

    # Returns the amount of visits for the current site, filtered by the
    # supplied period and date.
    #
    # * <tt>period</tt> should be one of <tt>:day</tt>, <tt>:week</tt>, <tt>:month</tt> or <tt>:year</tt> (default: <tt>:day</tt>)
    # * <tt>date</tt> should be a <tt>Date</tt> object (default: <tt>Date.today</tt>)
    #
    # Equivalent Piwik API call: VisitsSummary.getVisits (idSite, period, date)
    def visits(period=:day, date=Date.today)
      raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
      xml = call('VisitsSummary.getVisits', :idSite => id, :period => period, :date => date)
      result = XmlSimple.xml_in(xml, {'ForceArray' => false})
      result.to_i
    end

    # Returns the amount of unique visitors for the current site, filtered by
    # the supplied period and date.
    #
    # * <tt>period</tt> should be one of <tt>:day</tt>, <tt>:week</tt>, <tt>:month</tt> or <tt>:year</tt> (default: <tt>:day</tt>)
    # * <tt>date</tt> should be a <tt>Date</tt> object (default: <tt>Date.today</tt>)
    #
    # Equivalent Piwik API call: VisitsSummary.getUniqueVisitors (idSite, period, date)
    def unique_visitors(period=:day, date=Date.today)
      raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
      xml = call('VisitsSummary.getUniqueVisitors', :idSite => id, :period => period, :date => date)
      result = XmlSimple.xml_in(xml, {'ForceArray' => false})
      result.to_i
    end

    # Returns the amount of actions (pageviews) for the current site, filtered
    # by the supplied period and date.
    #
    # * <tt>period</tt> should be one of <tt>:day</tt>, <tt>:week</tt>, <tt>:month</tt> or <tt>:year</tt> (default: <tt>:day</tt>)
    # * <tt>date</tt> should be a <tt>Date</tt> object (default: <tt>Date.today</tt>)
    #
    # Equivalent Piwik API call: VisitsSummary.getActions (idSite, period, date)
    def actions(period=:day, date=Date.today)
      raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
      xml = call('VisitsSummary.getActions', :idSite => id, :period => period, :date => date)
      result = XmlSimple.xml_in(xml, {'ForceArray' => false})
      result.to_i
    end
    alias_method :pageviews, :actions

    private
      # Calls the supplied Piwik API method, with the supplied parameters.
      #
      # Returns a string containing the XML reply from Piwik, or raises a
      # <tt>Piwik::ApiError</tt> exception with the error message returned by Piwik
      # in case it receives an error.
      def call(method, params={})
        self.class.call(method, params, config[:piwik_url], config[:auth_token])
      end

      # Loads the attributes in the instance variables.
      def load_attributes(attributes)
        @id = attributes[:id]
        @name = attributes[:name]
        @main_url = attributes[:main_url] ? attributes[:main_url].gsub(/\/$/, '') : nil
        @created_at = attributes[:created_at]
      end

      # Gives the supplied access for the supplied user, for the current site.
      #
      # * <tt>access</tt> can be one of <tt>:view</tt>, <tt>:admin</tt> or <tt>:noaccess</tt>
      # * <tt>login</tt> is the user login on Piwik
      #
      # Equivalent Piwik API call: UsersManager.setUserAccess (userLogin, access, idSites)
      def give_access_to(access, login)
        raise UnknownSite, "Site not existent in Piwik yet, call 'save' first" if new?
        xml = call('UsersManager.setUserAccess', :idSites => id, :access => access.to_s, :userLogin => login.to_s)
        result = XmlSimple.xml_in(xml, {'ForceArray' => false})
        result['success'] ? true : false
      end

      # Calls the supplied Piwik API method, with the supplied parameters.
      #
      # Returns a string containing the XML reply from Piwik, or raises a
      # <tt>Piwik::ApiError</tt> exception with the error message returned by Piwik
      # in case it receives an error.
      def self.call(method, params={}, piwik_url=nil, auth_token=nil)
        raise MissingConfiguration, "Please edit ~/.piwik to include your piwik url and auth_key" if piwik_url.nil? || auth_token.nil?
        url = "#{piwik_url}/?module=API&format=xml&method=#{method}"
        url << "&token_auth=#{auth_token}" unless auth_token.nil?
        params.each { |k, v| url << "&#{k}=#{CGI.escape(v.to_s)}" }
        verbose_obj_save = $VERBOSE
        $VERBOSE = nil # Suppress "warning: peer certificate won't be verified in this SSL session"
        xml = RestClient.get(url)
        $VERBOSE = verbose_obj_save
        if xml =~ /error message=/
          result = XmlSimple.xml_in(xml, {'ForceArray' => false})
          raise ApiError, result['error']['message'] if result['error']
        end
        xml
      end

      # Returns a hash with the attributes of the supplied site, identified
      # by it's Id in <tt>site_id</tt>.
      #
      # Equivalent Piwik API call: SitesManager.getSiteFromId (idSite)
      def self.get_site_attributes_by_id(site_id, piwik_url, auth_token)
        xml = call('SitesManager.getSiteFromId', {:idSite => site_id}, piwik_url, auth_token)
        result = XmlSimple.xml_in(xml, {'ForceArray' => false})
        attributes = {
          :id => result['row']['idsite'].to_i,
          :name => result['row']['name'],
          :main_url => result['row']['main_url'],
          :created_at => Time.parse(result['row']['ts_created']),
        }
        attributes
      end
  end
end


text:
package com.etiennelawlor.discreteslider.library.ui;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.etiennelawlor.discreteslider.library.R;
import com.etiennelawlor.discreteslider.library.utilities.DisplayUtility;

/**
 * Created by etiennelawlor on 7/3/16.
 */

public class DiscreteSliderBackdrop extends FrameLayout {

    // region Member Variables
    private Paint fillPaint = new Paint();
    private Paint strokePaint = new Paint();
    private int tickMarkCount = 0;
    private float tickMarkRadius = 0.0F;
    private float horizontalBarThickness = 0.0F;
    private int backdropFillColor = 0;
    private int backdropStrokeColor = 0;
    private float backdropStrokeWidth = 0.0F;
    // The x-radius of the oval used to round the corners
    private int xRadius = DisplayUtility.dp2px(getContext(), 8);
    // The y-radius of the oval used to round the corners
    private int yRadius = DisplayUtility.dp2px(getContext(), 8);
    private int discreteSliderBackdropLeftMargin = DisplayUtility.dp2px(getContext(), 32);
    private int discreteSliderBackdropRightMargin = DisplayUtility.dp2px(getContext(), 32);
    // endregion

    // region Constructors
    public DiscreteSliderBackdrop(Context context) {
        super(context);
        init(context, null);
    }

    public DiscreteSliderBackdrop(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public DiscreteSliderBackdrop(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }
    // endregion

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int width = getWidth();
        int height = getHeight();

        int interval = (width - (discreteSliderBackdropLeftMargin+discreteSliderBackdropRightMargin)) / (tickMarkCount-1);

        setUpFillPaint();
        setUpStrokePaint();

        canvas.drawRoundRect(new RectF(discreteSliderBackdropLeftMargin,
                        (height/2) - (horizontalBarThickness/2),
                        width - discreteSliderBackdropRightMargin,
                        (height/2) + (horizontalBarThickness/2)),
                        xRadius,
                        yRadius,
                        fillPaint);

        canvas.drawRoundRect(new RectF(discreteSliderBackdropLeftMargin,
                        (height/2) - (horizontalBarThickness/2),
                        width - discreteSliderBackdropRightMargin,
                        (height/2) + (horizontalBarThickness/2)),
                        xRadius,
                        yRadius,
                        strokePaint);

        for(int i=0; i<tickMarkCount; i++){
            canvas.drawCircle(discreteSliderBackdropLeftMargin + (i * interval), height/2, tickMarkRadius, fillPaint);
            canvas.drawCircle(discreteSliderBackdropLeftMargin + (i * interval), height/2, tickMarkRadius, strokePaint);
        }

        canvas.drawRoundRect(new RectF(discreteSliderBackdropLeftMargin,
                        (height/2) - ((horizontalBarThickness/2)-DisplayUtility.dp2px(getContext(), 1)),
                        width - discreteSliderBackdropRightMargin,
                        (height/2) + ((horizontalBarThickness/2)-DisplayUtility.dp2px(getContext(), 1))),
                        xRadius,
                        yRadius,
                        fillPaint);
    }

    // region Helper Methods
    private void init(Context context, AttributeSet attrs){
    }

    private void setUpFillPaint(){
        fillPaint.setColor(backdropFillColor);
        fillPaint.setStyle(Paint.Style.FILL);
        fillPaint.setAntiAlias(true);
    }

    private void setUpStrokePaint(){
        strokePaint.setColor(backdropStrokeColor);
        strokePaint.setStyle(Paint.Style.STROKE);
        strokePaint.setAntiAlias(true);
        strokePaint.setStrokeWidth(backdropStrokeWidth);
    }

    public void setTickMarkCount(int tickMarkCount) {
        this.tickMarkCount = tickMarkCount < 2 ? 2 : tickMarkCount;
    }

    public void setTickMarkRadius(float tickMarkRadius) {
        this.tickMarkRadius = tickMarkRadius < 2.0F ? 2.0F : tickMarkRadius;
    }

    public void setHorizontalBarThickness(float horizontalBarThickness) {
        this.horizontalBarThickness = horizontalBarThickness < 2.0F ? 2.0F : horizontalBarThickness;
    }

    public void setBackdropFillColor(int backdropFillColor) {
        this.backdropFillColor = backdropFillColor;
    }

    public void setBackdropStrokeColor(int backdropStrokeColor) {
        this.backdropStrokeColor = backdropStrokeColor;
    }

    public void setBackdropStrokeWidth(float backdropStrokeWidth) {
        this.backdropStrokeWidth = backdropStrokeWidth < 1.0F ? 1.0F : backdropStrokeWidth;
    }
    // endregion
}


text:
from neutron.openstack.common import excutils
from neutron.openstack.common import log as logging
from neutron.plugins.nec.common import config
from neutron.plugins.nec.common import exceptions as nexc
from neutron.plugins.nec.db import api as ndb
from neutron.plugins.nec.db import packetfilter as pf_db

LOG = logging.getLogger(__name__)

class PacketFilterMixin(pf_db.PacketFilterDbMixin):
    """Mixin class to add packet filter to NECPluginV2."""

    @property
    def packet_filter_enabled(self):
        if not hasattr(self, '_packet_filter_enabled'):
            self._packet_filter_enabled = (
                config.OFC.enable_packet_filter and
                self.ofc.driver.filter_supported())
        return self._packet_filter_enabled

    def remove_packet_filter_extension_if_disabled(self, aliases):
        if not self.packet_filter_enabled:
            LOG.debug(_('Disabled packet-filter extension.'))
            aliases.remove('packet-filter')

    def create_packet_filter(self, context, packet_filter):
        """Create a new packet_filter entry on DB, then try to activate it."""
        LOG.debug(_("create_packet_filter() called, packet_filter=%s ."),
                  packet_filter)

        if hasattr(self.ofc.driver, 'validate_filter_create'):
            pf = packet_filter['packet_filter']
            self.ofc.driver.validate_filter_create(context, pf)
        pf = super(PacketFilterMixin, self).create_packet_filter(
            context, packet_filter)

        return self.activate_packet_filter_if_ready(context, pf)

    def update_packet_filter(self, context, id, packet_filter):
        """Update packet_filter entry on DB, and recreate it if changed.

        If any rule of the packet_filter was changed, recreate it on OFC.
        """
        LOG.debug(_("update_packet_filter() called, "
                    "id=%(id)s packet_filter=%(packet_filter)s ."),
                  {'id': id, 'packet_filter': packet_filter})

        pf_data = packet_filter['packet_filter']
        if hasattr(self.ofc.driver, 'validate_filter_update'):
            self.ofc.driver.validate_filter_update(context, pf_data)

        # validate ownership
        pf_old = self.get_packet_filter(context, id)

        pf = super(PacketFilterMixin, self).update_packet_filter(
            context, id, packet_filter)

        def _packet_filter_changed(old_pf, new_pf):
            LOG.debug('old_pf=%(old_pf)s, new_pf=%(new_pf)s',
                      {'old_pf': old_pf, 'new_pf': new_pf})
            # When the status is ERROR, force sync to OFC.
            if old_pf['status'] == pf_db.PF_STATUS_ERROR:
                LOG.debug('update_packet_filter: Force filter update '
                          'because the previous status is ERROR.')
                return True
            for key in new_pf:
                if key in ('id', 'name', 'tenant_id', 'network_id',
                           'in_port', 'status'):
                    continue
                if old_pf[key] != new_pf[key]:
                    return True
            return False

        if _packet_filter_changed(pf_old, pf):
            if hasattr(self.ofc.driver, 'update_filter'):
                # admin_state is changed
                if pf_old['admin_state_up'] != pf['admin_state_up']:
                    LOG.debug('update_packet_filter: admin_state '
                              'is changed to %s', pf['admin_state_up'])
                    if pf['admin_state_up']:
                        self.activate_packet_filter_if_ready(context, pf)
                    else:
                        self.deactivate_packet_filter(context, pf)
                elif pf['admin_state_up']:
                    LOG.debug('update_packet_filter: admin_state is '
                              'unchanged (True)')
                    if self.ofc.exists_ofc_packet_filter(context, id):
                        pf = self._update_packet_filter(context, pf, pf_data)
                    else:
                        pf = self.activate_packet_filter_if_ready(context, pf)
                else:
                    LOG.debug('update_packet_filter: admin_state is unchanged '
                              '(False). No need to update OFC filter.')
            else:
                pf = self.deactivate_packet_filter(context, pf)
                pf = self.activate_packet_filter_if_ready(context, pf)

        return pf

    def _update_packet_filter(self, context, new_pf, pf_data):
        pf_id = new_pf['id']
        prev_status = new_pf['status']
        try:
            # If previous status is ERROR, try to sync all attributes.
            pf = new_pf if prev_status == pf_db.PF_STATUS_ERROR else pf_data
            self.ofc.update_ofc_packet_filter(context, pf_id, pf)
            new_status = pf_db.PF_STATUS_ACTIVE
            if new_status != prev_status:
                self._update_resource_status(context, "packet_filter",
                                             pf_id, new_status)
                new_pf['status'] = new_status
            return new_pf
        except Exception as exc:
            with excutils.save_and_reraise_exception():
                if (isinstance(exc, nexc.OFCException) or
                    isinstance(exc, nexc.OFCConsistencyBroken)):
                    LOG.error(_("Failed to create packet_filter id=%(id)s on "
                                "OFC: %(exc)s"),
                              {'id': pf_id, 'exc': exc})
                new_status = pf_db.PF_STATUS_ERROR
                if new_status != prev_status:
                    self._update_resource_status(context, "packet_filter",
                                                 pf_id, new_status)

    def delete_packet_filter(self, context, id):
        """Deactivate and delete packet_filter."""
        LOG.debug(_("delete_packet_filter() called, id=%s ."), id)

        # validate ownership
        pf = self.get_packet_filter(context, id)

        pf = self.deactivate_packet_filter(context, pf)
        if pf['status'] == pf_db.PF_STATUS_ERROR:
            msg = _("Failed to delete packet_filter id=%s which remains in "
                    "error status.") % id
            LOG.error(msg)
            raise nexc.OFCException(reason=msg)

        super(PacketFilterMixin, self).delete_packet_filter(context, id)

    def activate_packet_filter_if_ready(self, context, packet_filter):
        """Activate packet_filter by creating filter on OFC if ready.

        Conditions to create packet_filter on OFC are:
            * packet_filter admin_state is UP
            * (if 'in_port' is specified) portinfo is available
        """
        LOG.debug(_("activate_packet_filter_if_ready() called, "
                    "packet_filter=%s."), packet_filter)

        pf_id = packet_filter['id']
        in_port_id = packet_filter.get('in_port')
        current = packet_filter['status']

        pf_status = current
        if not packet_filter['admin_state_up']:
            LOG.debug(_("activate_packet_filter_if_ready(): skip pf_id=%s, "
                        "packet_filter.admin_state_up is False."), pf_id)
        elif in_port_id and not ndb.get_portinfo(context.session, in_port_id):
            LOG.debug(_("activate_packet_filter_if_ready(): skip "
                        "pf_id=%s, no portinfo for the in_port."), pf_id)
        elif self.ofc.exists_ofc_packet_filter(context, packet_filter['id']):
            LOG.debug(_("_activate_packet_filter_if_ready(): skip, "
                        "ofc_packet_filter already exists."))
        else:
            LOG.debug(_("activate_packet_filter_if_ready(): create "
                        "packet_filter id=%s on OFC."), pf_id)
            try:
                self.ofc.create_ofc_packet_filter(context, pf_id,
                                                  packet_filter)
                pf_status = pf_db.PF_STATUS_ACTIVE
            except (nexc.OFCException, nexc.OFCMappingNotFound) as exc:
                LOG.error(_("Failed to create packet_filter id=%(id)s on "
                            "OFC: %(exc)s"), {'id': pf_id, 'exc': exc})
                pf_status = pf_db.PF_STATUS_ERROR

        if pf_status != current:
            self._update_resource_status(context, "packet_filter", pf_id,
                                         pf_status)
            packet_filter.update({'status': pf_status})

        return packet_filter

    def deactivate_packet_filter(self, context, packet_filter):
        """Deactivate packet_filter by deleting filter from OFC if exixts."""
        LOG.debug(_("deactivate_packet_filter_if_ready() called, "
                    "packet_filter=%s."), packet_filter)
        pf_id = packet_filter['id']
        current = packet_filter['status']

        pf_status = current
        if self.ofc.exists_ofc_packet_filter(context, pf_id):
            LOG.debug(_("deactivate_packet_filter(): "
                        "deleting packet_filter id=%s from OFC."), pf_id)
            try:
                self.ofc.delete_ofc_packet_filter(context, pf_id)
                pf_status = pf_db.PF_STATUS_DOWN
            except (nexc.OFCException, nexc.OFCMappingNotFound) as exc:
                LOG.error(_("Failed to delete packet_filter id=%(id)s from "
                            "OFC: %(exc)s"), {'id': pf_id, 'exc': exc})
                pf_status = pf_db.PF_STATUS_ERROR
        else:
            LOG.debug(_("deactivate_packet_filter(): skip, "
                        "Not found OFC Mapping for packet_filter id=%s."),
                      pf_id)

        if pf_status != current:
            self._update_resource_status(context, "packet_filter", pf_id,
                                         pf_status)
            packet_filter.update({'status': pf_status})

        return packet_filter

    def activate_packet_filters_by_port(self, context, port_id):
        if not self.packet_filter_enabled:
            return

        filters = {'in_port': [port_id], 'admin_state_up': [True],
                   'status': [pf_db.PF_STATUS_DOWN]}
        pfs = self.get_packet_filters(context, filters=filters)
        for pf in pfs:
            self.activate_packet_filter_if_ready(context, pf)

    def deactivate_packet_filters_by_port(self, context, port_id):
        if not self.packet_filter_enabled:
            return

        filters = {'in_port': [port_id], 'status': [pf_db.PF_STATUS_ACTIVE]}
        pfs = self.get_packet_filters(context, filters=filters)
        for pf in pfs:
            self.deactivate_packet_filter(context, pf)

    def get_packet_filters_for_port(self, context, port):
        if self.packet_filter_enabled:
            return super(PacketFilterMixin,
                         self).get_packet_filters_for_port(context, port)


text:
namespace AnteyaVIP.Contracts
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    public abstract class DeletableEntity : AuditInfo, IDeletableEntity
    {
        [Editable(false)]
        public bool IsDeleted { get; set; }

        [Editable(false)]
        [Column(TypeName = "DateTime")]
        public DateTime? DeletedOn { get; set; }
    }
}


text:
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="../../../static/bootstrap 3.3.5/css/bootstrap.css"/>
    <link rel="stylesheet" type="text/css" href="../../../static/css/default/style.css"/>

TagName 2

TagName 10

TagName 30

TagName 100

TagName 150


text:
<!doctype html>

  <title>iron-query-params</title>

  <link rel="import" href="../iron-query-params.html">
  <link rel="import" href="../../iron-flex-layout/iron-flex-layout-classes.html">

  <dom-module id='iron-query-params-demo'>
    <template>

      <iron-query-params
          id="queryParams"
          params-string='{{paramString}}'
          params-object='{{params}}'>
      </iron-query-params>

Params as string:

          <input value="{{paramString::input}}">

Params as object

          <template is="dom-if" if="{{paramsInvalid}}">

INVALID PARAMS: Should be legal JSON

          </template>
          <input value="{{stringifiedParams::input}}">

    </template>

  </dom-module>

  <iron-query-params-demo></iron-query-params-demo>


text:
	background-image: url(/images/icons/32x32/apps/utilities-system-monitor.png);
	background-repeat: no-repeat;
	background-position: 0 3px;
	height: 36px;
	padding-left: 40px;
}
.nav-home{
	background-image: url(/images/icons/22x22/actions/edit-copy.png);
	background-repeat: no-repeat;
	height: 22px;
	padding-left: 26px;
}

.nav-submit{
	background-image: url(/images/icons/22x22/apps/accessories-text-editor.png);
	background-repeat: no-repeat;
	height: 22px;
	padding-left: 26px;
}

.nav-browser{
	background-image: url(/images/icons/22x22/categories/applications-internet.png);
	background-repeat: no-repeat;
	height: 22px;
	padding-left: 26px;
}

.action-required a,
.action-required{
	color: red;
	font-weight: bold;
}

#problem_details{
	width: 99%;
	height: 10em;
}

button{ font-size: 1.3em; float: right;}

.paging{margin-top: 1em;}
.pager{float:right;text-align:center;}

h2 img{vertical-align: middle;}

#ipdata ul{
	list-style-type: none;
}

#ipdata li {
	margin-bottom: 2em;
	margin-left: 0;
}

#ipdata ul ul li{
	margin-bottom: auto;
}

#ipdata .ip span{
	display: block;
	font-size: 2.5em;
	font-weight: bold;
}

#ipdata .browser,
#ipdata .misc{
	display:none;
}

#ipdata .misc label,
#ipdata .browser label{
	margin-bottom: 0.5em;
}

.positive{color: green; font-weight: bold;}
.negative{color: red; font-weight: bold;}

#sessiondata textarea {
	font-family: Consolas, Courier New;
	height: 500px;
	width: 95%;
}


text:
/**
 * The global state selectors
 */

import { createSelector } from 'reselect';

const selectGlobal = () => (state) => state.get('global');

const selectLocationState = () => {
  let prevRoutingState;
  let prevRoutingStateJS;

  return (state) => {
    const routingState = state.get('route'); // or state.route

    if (!routingState.equals(prevRoutingState)) {
      prevRoutingState = routingState;
      prevRoutingStateJS = routingState.toJS();
    }

    return prevRoutingStateJS;
  };
};

const selectToken = () => createSelector(
  selectGlobal(),
  (globalState) => globalState.get('token')
);

const selectErrors = () => createSelector(
  selectGlobal(),
  (globalState) => globalState.get('errors')
);

const selectAuthError = () => createSelector(
  selectGlobal(),
  (globalState) => globalState.get('authError')
);

const selectFlash = () => createSelector(
  selectGlobal(),
  (globalState) => globalState.get('flash')
);

export {
  selectGlobal,
  selectErrors,
  selectFlash,
  selectLocationState,
  selectToken,
  selectAuthError,
};


text:
package org.apache.pulsar.broker.service.plugin;

import static org.apache.pulsar.broker.service.plugin.EntryFilterProvider.ENTRY_FILTER_DEFINITION_FILE;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.apache.pulsar.common.nar.NarClassLoader;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.file.NoSuchFileException;

@Test(groups = "broker")
public class EntryFilterProviderTest {

    @Test
    public void testReadYamlFile() throws IOException {
        try (NarClassLoader cl = mock(NarClassLoader.class)) {
            when(cl.getServiceDefinition(ENTRY_FILTER_DEFINITION_FILE + ".yaml"))
                    .thenThrow(new NoSuchFileException(""));
            try {
                EntryFilterProvider.getEntryFilterDefinition(cl);
                Assert.fail();
            } catch (Exception e) {
                Assert.assertFalse(e instanceof NoSuchFileException);
            }
        }
        try (NarClassLoader cl = mock(NarClassLoader.class)) {
            when(cl.getServiceDefinition(ENTRY_FILTER_DEFINITION_FILE + ".yml"))
                    .thenThrow(new NoSuchFileException(""));
            try {
                EntryFilterProvider.getEntryFilterDefinition(cl);
                Assert.fail();
            } catch (Exception e) {
                Assert.assertFalse(e instanceof NoSuchFileException);
            }
        }
        try (NarClassLoader cl = mock(NarClassLoader.class)) {
            when(cl.getServiceDefinition(ENTRY_FILTER_DEFINITION_FILE + ".yaml"))
                    .thenThrow(new NoSuchFileException(""));
            when(cl.getServiceDefinition(ENTRY_FILTER_DEFINITION_FILE + ".yml"))
                    .thenThrow(new NoSuchFileException(""));
            try {
                EntryFilterProvider.getEntryFilterDefinition(cl);
                Assert.fail();
            } catch (Exception e) {
                Assert.assertTrue(e instanceof NoSuchFileException);
            }
        }
    }
}


text:
<?php $this->load->view('embed_common/_inc_slides_trucks'); ?>

Home

Welcome to our website. 909Trading is for individual looking for Surplus Trucks,Bus,Generator set and Heavy Equipments.We are importer and dealer of China,Japan and Korea trucks for sale located in Quezon City,Philippine.
                Please contact us, if you want to visit our warehouse at Subic Bay Freeport Zone / Olongapo Philippines.

We are proud affiliates of the following.

                    <?php $this->load->view('embed_common/_inc_affiliates'); ?>

            <?php $this->load->view('embed_common/_inc_form_send_email'); ?>


text:
describe('navbar test suite', function () {

    var element, scope;

    //load widgets modules, including the html template, needed to support the test
    beforeEach(module('ui.navbar'));
    beforeEach(module('template/navbar-ul.html'));
    beforeEach(module('template/navbar-li.html'));

    beforeEach(inject(function ($rootScope, $compile, $templateCache) {

        scope = $rootScope.$new();
        scope.tree = [{
            name: 'States',
            link: '#'
        }];

        element = $compile('
<tree tree="tree"></tree>
')(scope);
        scope.$digest();
    }));

    it('should display the navbar', function () {
        expect(element.text()).toBe('');
    });
});

angular.module('ui.directive', [])
    .directive('writers', function () {

        return {
            restrict: 'E',
            link: function (scope, element) {
                element.text('a simple artist: ' + scope.artist);
            }
        };
    });

describe('directive test suite', function () {

    var scope, element;
    var artist = 'test artist';

    // Load the module
    beforeEach(module('ui.directive'));

    // Inject dependencies and create a new scope
    beforeEach(inject(function ($rootScope, $compile) {
        scope = $rootScope.$new();
        scope.artist = artist;

        // Create the element
        element = angular.element('<writers></writers>');
        // Compile it with the given scope
        $compile(element)(scope);
        // Simulate the scope life cycle that is render the element as if were called in the browser
        scope.$digest();
    }));

    it('should display the correct test in the DOM', function(){
        expect(element.text()).toBe('a simple artist: ' + artist);
    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.8.0//EN" "http://google-web-toolkit.googlecode.com/svn/tags/2.8.0/distro-source/core/src/gwt-module.dtd">
<module>
    <inherits name="cn.mapway.ui.client.theme.enn.Enn" />
    <source path="client" />
</module>


text:
每日一个Linux命令
======================

.. toctree::
   :titlesonly:

   file-directory-operation/index
   file-find-operation/index


text: require 'light-service/testing/context_factory'


text:
using System.Collections.Generic;

namespace Audiotica.Web.Models
{
    public class WebResults
    {
        public enum Type
        {
            Song,
            Artist,
            Album
        }

        public string PageToken { get; set; }
        public bool HasMore { get; set; }
        public List<WebSong> Songs { get; set; }
        public List<WebArtist> Artists { get; set; }
        public List<WebAlbum> Albums { get; set; }
    }
}


text:
# TypeScript

You can add static typing to JavaScript to improve developer productivity and code quality thanks to TypeScript.

Have a look at the [Create React App with TypeScript](https://github.com/mui-org/material-ui/tree/master/examples/create-react-app-with-typescript) example. A minimum version of TypeScript 2.8 is required.

Our definitions are tested with the following [tsconfig.json](https://github.com/mui-org/material-ui/tree/master/tsconfig.json). Using a less strict `tsconfig.json` or omitting some of the libraries might cause errors.

## Usage of `withStyles`

Using `withStyles` in TypeScript can be a little tricky, but there are some utilities to make the experience as painless as possible.

### Using `createStyles` to defeat type widening

A frequent source of confusion is TypeScript's [type widening](https://blog.mariusschulz.com/2017/02/04/typescript-2-1-literal-type-widening), which causes this example not to work as expected:

```ts
const styles = {
  root: {
    display: 'flex',
    flexDirection: 'column',
  }
};

withStyles(styles);
//         ^^^^^^
//         Types of property 'flexDirection' are incompatible.
//           Type 'string' is not assignable to type '"-moz-initial" | "inherit" | "initial" | "revert" | "unset" | "column" | "column-reverse" | "row"...'.
```

The problem is that the type of the `flexDirection` property is inferred as `string`, which is too arbitrary. To fix this, you can pass the styles object directly to `withStyles`:

```ts
withStyles({
  root: {
    display: 'flex',
    flexDirection: 'column',
  },
});
```

However type widening rears its ugly head once more if you try to make the styles depend on the theme:

```ts
withStyles(({ palette, spacing }) => ({
  root: {
    display: 'flex',
    flexDirection: 'column',
    padding: spacing.unit,
    backgroundColor: palette.background.default,
    color: palette.primary.main,
  },
}));
```

This is because TypeScript [widens the return types of function expressions](https://github.com/Microsoft/TypeScript/issues/241).

Because of this, we recommend using our `createStyles` helper function to construct your style rules object:

```ts
// Non-dependent styles
const styles = createStyles({
  root: {
    display: 'flex',
    flexDirection: 'column',
  },
});

// Theme-dependent styles
const styles = ({ palette, spacing }: Theme) => createStyles({
  root: {
    display: 'flex',
    flexDirection: 'column',
    padding: spacing.unit,
    backgroundColor: palette.background.default,
    color: palette.primary.main,
  },
});
```

`createStyles` is just the identity function; it doesn't "do anything" at runtime, just helps guide type inference at compile time.

### Media queries

`withStyles` allows a styles object with top level media-queries like so:

```ts
const styles = createStyles({
  root: {
    minHeight: '100vh',
  },
  '@media (min-width: 960px)': {
    root: {
      display: 'flex',
    },
  },
});
```

However to allow these styles to pass TypeScript the definitions have to be ambiguous concerning names for CSS classes and actual CSS property names. Due to this class names that are equal to CSS properties should be avoided.

```ts
// error because TypeScript thinks `@media (min-width: 960px)` is a class name
// and `content` is the css property
const ambiguousStyles = createStyles({
  content: {
    minHeight: '100vh',
  },
  '@media (min-width: 960px)': {
    content: {
      display: 'flex',
    },
  },
});

// works just fine
const ambiguousStyles = createStyles({
  contentClass: {
    minHeight: '100vh',
  },
  '@media (min-width: 960px)': {
    contentClass: {
      display: 'flex',
    },
  },
});
```

### Augmenting your props using `WithStyles`

Since a component decorated with `withStyles(styles)` gets a special `classes` prop injected, you will want to define its props accordingly:

```ts
const styles = (theme: Theme) => createStyles({
  root: { /* ... */ },
  paper: { /* ... */ },
  button: { /* ... */ },
});

interface Props {
  // non-style props
  foo: number;
  bar: boolean;
  // injected style props
  classes: {
    root: string;
    paper: string;
    button: string;
  };
}
```

However this isn't very [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) because it requires you to maintain the class names (`'root'`, `'paper'`, `'button'`, ...) in two different places. We provide a type operator `WithStyles` to help with this, so that you can just write

```ts
import { WithStyles, createStyles } from '@material-ui/core';

const styles = (theme: Theme) => createStyles({
  root: { /* ... */ },
  paper: { /* ... */ },
  button: { /* ... */ },
});

interface Props extends WithStyles<typeof styles> {
  foo: number;
  bar: boolean;
}
```

### Decorating components

Applying `withStyles(styles)` as a function works as expected:

```tsx
const DecoratedSFC = withStyles(styles)(({ text, type, color, classes }: Props) => (
  <Typography variant={type} color={color} classes={classes}>
    {text}
  </Typography>
));

const DecoratedClass = withStyles(styles)(
  class extends React.Component<Props> {
    render() {
      const { text, type, color, classes } = this.props
      return (
        <Typography variant={type} color={color} classes={classes}>
          {text}
        </Typography>
      );
    }
  }
);
```

Unfortunately due to a [current limitation of TypeScript decorators](https://github.com/Microsoft/TypeScript/issues/4881), `withStyles(styles)` can't be used as a decorator in TypeScript.

## Customization of `Theme`

When adding custom properties to the `Theme`, you may continue to use it in a strongly typed way by exploiting [Typescript's module augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation).

The following example adds an `appDrawer` property that is merged into the one exported by `material-ui`:

```ts
import { Theme } from '@material-ui/core/styles/createMuiTheme';
import { Breakpoint } from '@material-ui/core/styles/createBreakpoints';

declare module '@material-ui/core/styles/createMuiTheme' {
  interface Theme {
    appDrawer: {
      width: React.CSSProperties['width']
      breakpoint: Breakpoint
    }
  }
  // allow configuration using `createMuiTheme`
  interface ThemeOptions {
    appDrawer?: {
      width?: React.CSSProperties['width']
      breakpoint?: Breakpoint
    }
  }
}
```

And a custom theme factory with additional defaulted options:

**./styles/createMyTheme**:

```ts
import createMuiTheme, { ThemeOptions } from '@material-ui/core/styles/createMuiTheme';

export default function createMyTheme(options: ThemeOptions) {
  return createMuiTheme({
    appDrawer: {
      width: 225,
      breakpoint: 'lg',
    },
    ...options,
  })
}
```

This could be used like:

```ts
import createMyTheme from './styles/createMyTheme';

const theme = createMyTheme({ appDrawer: { breakpoint: 'md' }});
```


text:
using System.Collections.Generic;

namespace Mat.Common
{
    public interface IQueueManager
    {
        IEnumerable<Media> Queue { get; }
        IEnumerable<Media> History { get; }

        /// <summary>
        /// Jumps to the next image immediately.
        /// </summary>
        Media Next();
        /// <summary>
        /// Jumps to the previous image immediately.
        /// </summary>
        Media Previous();

        Media Current { get; }

        /// <summary>
        /// Adds a new image to the queue.
        /// </summary>
        /// <param name="media">The image to add.</param>
        void NewMedia(Media media);

        /// <summary>
        /// Removes an image from the queue.
        /// </summary>
        /// <param name="media">The image to remove.</param>
        void RemoveMedia(Media media);
    }
}


text:
<?php

namespace Forte\OsBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class TecnicoType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nome')
            ->add('email')
            ->add('tel')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Forte\OsBundle\Entity\Tecnico'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'forte_osbundle_tecnico';
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Dell™ Warranty Finder</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="scan">Scan Barcode</string>

    <string name="no_scan_data">No scan data received!</string>
    <string name="retrieving_warranty_data">Attempting to retrieve warranty data!</string>
    <string name="unrecognized_product">Not a recognized Dell™ product.</string>
    <string name="bad_data">Data was bad, please scan again.</string>

    <string name="coin_name_ending"> Address</string>
    <string name="coin_1_name">BitCoin</string>
    <string name="coin_1_value">1MJN2mccLB47ht2FQtS5fgRhbiSF7edUjh</string>
    <string name="coin_1_popup">Copied BitCoin Address!</string>
    <string name="coin_2_name">DogeCoin</string>
    <string name="coin_2_value">DHMCCzCzbU5iAMU61nJYp4tyyDsU8ES8YJ</string>
    <string name="coin_2_popup">Copied DogeCoin Address!</string>

    <string name="base_url">https://api.dell.com/support/v2/assetinfo/warranty/tags.json?svctags=</string>
    <string name="url_ending"></string>
    <string name="api_key"></string>

    <string name="error_announcement"></string>
    <string name="connection_error"></string>

</resources>


text:
RSpec::Matchers.define(:be_same_file_as) do |exected_file|
  match do |actual_file|
    md5_hash(relevant_contents_of(actual_file)).should == md5_hash(relevant_contents_of(exected_file))
  end

  def md5_hash(string)
    Digest::MD5.hexdigest(string)
  end

  def relevant_contents_of(file)
    file.read.encode('UTF-8', 'binary', :invalid => :replace, :undef => :replace, :replace => '').tap do |contents|
      contents.sub!(/\/Title[^\n]*/, '')
      contents.sub!(/\/CreationDate[^\n]*/, '')
      contents.sub!(/\/ModDate[^\n]*/, '')
      contents.sub!(/\/Producer[^\n]*/, '')
      contents.sub!(/\/ID[^\]]*/, '')
      contents.sub!(/\/DocChecksum[^\n]*/, '')
      contents.sub!(/startxref\n[\d]+/, '')
    end
  end
end


text:
//
// ip/basic_endpoint.hpp
// ~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2022 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef ASIO_IP_BASIC_ENDPOINT_HPP
#define ASIO_IP_BASIC_ENDPOINT_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include "asio/detail/config.hpp"
#include "asio/detail/cstdint.hpp"
#include "asio/ip/address.hpp"
#include "asio/ip/detail/endpoint.hpp"

#if defined(ASIO_HAS_STD_HASH)
# include <functional>
#endif // defined(ASIO_HAS_STD_HASH)

#if !defined(ASIO_NO_IOSTREAM)
# include <iosfwd>
#endif // !defined(ASIO_NO_IOSTREAM)

#include "asio/detail/push_options.hpp"

namespace asio {
namespace ip {

/// Type used for storing port numbers.
typedef uint_least16_t port_type;

/// Describes an endpoint for a version-independent IP socket.
/**
 * The asio::ip::basic_endpoint class template describes an endpoint that
 * may be associated with a particular socket.
 *
 * @par Thread Safety
 * @e Distinct @e objects: Safe.@n
 * @e Shared @e objects: Unsafe.
 *
 * @par Concepts:
 * Endpoint.
 */
template <typename InternetProtocol>
class basic_endpoint
{
public:
  /// The protocol type associated with the endpoint.
  typedef InternetProtocol protocol_type;

  /// The type of the endpoint structure. This type is dependent on the
  /// underlying implementation of the socket layer.
#if defined(GENERATING_DOCUMENTATION)
  typedef implementation_defined data_type;
#else
  typedef asio::detail::socket_addr_type data_type;
#endif

  /// Default constructor.
  basic_endpoint() ASIO_NOEXCEPT
    : impl_()
  {
  }

  /// Construct an endpoint using a port number, specified in the host's byte
  /// order. The IP address will be the any address (i.e. INADDR_ANY or
  /// in6addr_any). This constructor would typically be used for accepting new
  /// connections.
  /**
   * @par Examples
   * To initialise an IPv4 TCP endpoint for port 1234, use:
   * @code
   * asio::ip::tcp::endpoint ep(asio::ip::tcp::v4(), 1234);
   * @endcode
   *
   * To specify an IPv6 UDP endpoint for port 9876, use:
   * @code
   * asio::ip::udp::endpoint ep(asio::ip::udp::v6(), 9876);
   * @endcode
   */
  basic_endpoint(const InternetProtocol& internet_protocol,
      port_type port_num) ASIO_NOEXCEPT
    : impl_(internet_protocol.family(), port_num)
  {
  }

  /// Construct an endpoint using a port number and an IP address. This
  /// constructor may be used for accepting connections on a specific interface
  /// or for making a connection to a remote endpoint.
  basic_endpoint(const asio::ip::address& addr,
      port_type port_num) ASIO_NOEXCEPT
    : impl_(addr, port_num)
  {
  }

  /// Copy constructor.
  basic_endpoint(const basic_endpoint& other) ASIO_NOEXCEPT
    : impl_(other.impl_)
  {
  }

#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  /// Move constructor.
  basic_endpoint(basic_endpoint&& other) ASIO_NOEXCEPT
    : impl_(other.impl_)
  {
  }
#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)

  /// Assign from another endpoint.
  basic_endpoint& operator=(const basic_endpoint& other) ASIO_NOEXCEPT
  {
    impl_ = other.impl_;
    return *this;
  }

#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  /// Move-assign from another endpoint.
  basic_endpoint& operator=(basic_endpoint&& other) ASIO_NOEXCEPT
  {
    impl_ = other.impl_;
    return *this;
  }
#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)

  /// The protocol associated with the endpoint.
  protocol_type protocol() const ASIO_NOEXCEPT
  {
    if (impl_.is_v4())
      return InternetProtocol::v4();
    return InternetProtocol::v6();
  }

  /// Get the underlying endpoint in the native type.
  data_type* data() ASIO_NOEXCEPT
  {
    return impl_.data();
  }

  /// Get the underlying endpoint in the native type.
  const data_type* data() const ASIO_NOEXCEPT
  {
    return impl_.data();
  }

  /// Get the underlying size of the endpoint in the native type.
  std::size_t size() const ASIO_NOEXCEPT
  {
    return impl_.size();
  }

  /// Set the underlying size of the endpoint in the native type.
  void resize(std::size_t new_size)
  {
    impl_.resize(new_size);
  }

  /// Get the capacity of the endpoint in the native type.
  std::size_t capacity() const ASIO_NOEXCEPT
  {
    return impl_.capacity();
  }

  /// Get the port associated with the endpoint. The port number is always in
  /// the host's byte order.
  port_type port() const ASIO_NOEXCEPT
  {
    return impl_.port();
  }

  /// Set the port associated with the endpoint. The port number is always in
  /// the host's byte order.
  void port(port_type port_num) ASIO_NOEXCEPT
  {
    impl_.port(port_num);
  }

  /// Get the IP address associated with the endpoint.
  asio::ip::address address() const ASIO_NOEXCEPT
  {
    return impl_.address();
  }

  /// Set the IP address associated with the endpoint.
  void address(const asio::ip::address& addr) ASIO_NOEXCEPT
  {
    impl_.address(addr);
  }

  /// Compare two endpoints for equality.
  friend bool operator==(const basic_endpoint<InternetProtocol>& e1,
      const basic_endpoint<InternetProtocol>& e2) ASIO_NOEXCEPT
  {
    return e1.impl_ == e2.impl_;
  }

  /// Compare two endpoints for inequality.
  friend bool operator!=(const basic_endpoint<InternetProtocol>& e1,
      const basic_endpoint<InternetProtocol>& e2) ASIO_NOEXCEPT
  {
    return !(e1 == e2);
  }

  /// Compare endpoints for ordering.
  friend bool operator<(const basic_endpoint<InternetProtocol>& e1,
      const basic_endpoint<InternetProtocol>& e2) ASIO_NOEXCEPT
  {
    return e1.impl_ < e2.impl_;
  }

  /// Compare endpoints for ordering.
  friend bool operator>(const basic_endpoint<InternetProtocol>& e1,
      const basic_endpoint<InternetProtocol>& e2) ASIO_NOEXCEPT
  {
    return e2.impl_ < e1.impl_;
  }

  /// Compare endpoints for ordering.
  friend bool operator<=(const basic_endpoint<InternetProtocol>& e1,
      const basic_endpoint<InternetProtocol>& e2) ASIO_NOEXCEPT
  {
    return !(e2 < e1);
  }

  /// Compare endpoints for ordering.
  friend bool operator>=(const basic_endpoint<InternetProtocol>& e1,
      const basic_endpoint<InternetProtocol>& e2) ASIO_NOEXCEPT
  {
    return !(e1 < e2);
  }

private:
  // The underlying IP endpoint.
  asio::ip::detail::endpoint impl_;
};

#if !defined(ASIO_NO_IOSTREAM)

/// Output an endpoint as a string.
/**
 * Used to output a human-readable string for a specified endpoint.
 *
 * @param os The output stream to which the string will be written.
 *
 * @param endpoint The endpoint to be written.
 *
 * @return The output stream.
 *
 * @relates asio::ip::basic_endpoint
 */
template <typename Elem, typename Traits, typename InternetProtocol>
std::basic_ostream<Elem, Traits>& operator<<(
    std::basic_ostream<Elem, Traits>& os,
    const basic_endpoint<InternetProtocol>& endpoint);

#endif // !defined(ASIO_NO_IOSTREAM)

} // namespace ip
} // namespace asio

#if defined(ASIO_HAS_STD_HASH)
namespace std {

template <typename InternetProtocol>
struct hash<asio::ip::basic_endpoint<InternetProtocol> >
{
  std::size_t operator()(
      const asio::ip::basic_endpoint<InternetProtocol>& ep)
    const ASIO_NOEXCEPT
  {
    std::size_t hash1 = std::hash<asio::ip::address>()(ep.address());
    std::size_t hash2 = std::hash<unsigned short>()(ep.port());
    return hash1 ^ (hash2 + 0x9e3779b9 + (hash1 << 6) + (hash1 >> 2));
  }
};

} // namespace std
#endif // defined(ASIO_HAS_STD_HASH)

#include "asio/detail/pop_options.hpp"

#include "asio/ip/impl/basic_endpoint.hpp"

#endif // ASIO_IP_BASIC_ENDPOINT_HPP


text:
package org.wso2.carbon.apimgt.usage.client.billing;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.math.BigDecimal;
import java.util.*;

/**
 * This class is used for keep details about the some data parameter, as example we can take calls
 * so this will hold data of call (Various regions that bill calculate and costs within those
 * regions) also this can calculate the cost for given usage of particular data parameter
 * and this contains multiple regions and costs within those regions
 */
public class DataParameter extends BillingBase {

    //This vector holds sub parameter elements of Data Parameter
    private Vector<ParameterElement> elementVector = new Vector<ParameterElement>();
    private static final Log log = LogFactory.getLog(DataParameter.class);

    public Vector<ParameterElement> getElementVector() {
        return elementVector;
    }

    public void setElementVector(Vector<ParameterElement> elementVector) {
        this.elementVector = elementVector;
    }

    public DataParameter() {
        super();
    }

    public DataParameter(Vector<ParameterElement> parameterElementVector, String parameterName) {
        this.objectName = parameterName;
        this.elementVector = parameterElementVector;
    }

    /**
     * constructor element that initialize object based on serialized Data parameter
     * @param dataParameterOME is used to get parameters of current object
     */
    public DataParameter(OMElement dataParameterOME) {
        this.objectOMElement = dataParameterOME;
        objectName =
                this.objectOMElement.getAttributeValue(new javax.xml.namespace.QName(null, "name"));
        Iterator dataParametersChildItr = objectOMElement.getChildElements();
        int paramCount = 0;
        while (dataParametersChildItr.hasNext()) {
            Object dataParameterChild = dataParametersChildItr.next();
            if (!(dataParameterChild instanceof OMElement)) {
                continue;
            }
            OMElement dataParameterChildEle = (OMElement) dataParameterChild;
            elementVector.add(new ParameterElement(dataParameterChildEle));
            paramCount = paramCount + 1;
        }
    }

    /**
     *
     * @param newElement is ParameterElement object going to add element vector
     * @return true if adding success else false
     */
    public boolean addNewParameterElement(ParameterElement newElement) {
        try {
            elementVector.add(newElement);
            return true;
        }
        catch (Exception e) {
            log.error("Error in adding new parameter element to parameter vector");
            return false;
        }

    }

    /**Get serialized OMElement of the current object
     * @return OMElelement of the object
     */
    public OMElement serialize() {
        OMFactory fac = OMAbstractFactory.getOMFactory();
        OMNamespace omNs = fac.createOMNamespace("", "");
        Iterator itr = elementVector.iterator();
        OMElement returnElement = fac.createOMElement("parameter", omNs);
        returnElement.addAttribute("name", this.objectName, null);
        while (itr.hasNext()) {
            ParameterElement element = (ParameterElement) itr.next();
            returnElement.addChild(element.getSerializedElement());
        }
        return returnElement;
    }

    /**
     * totalInvocation - total amount of data units used
     *
     * This method calculate the total amount of money used for each data unit range
     */

    public List<APIUsageRangeCost> evaluateInvocationCost(int totalInvocation)  {

        int start, end, rangeInvocation = totalInvocation;
        double unitCost, rangeCost;
        List<APIUsageRangeCost> rangeCosts = new ArrayList<APIUsageRangeCost>();
        Vector<ParameterElement> reverseElements = new Vector<ParameterElement>(elementVector);
        Collections.reverse(reverseElements);
        for (ParameterElement element : reverseElements)  {
            start = element.getStartingValue();
            end = element.getEndValue();
            unitCost = element.getCostPerUnit();

            if (start < rangeInvocation && rangeInvocation <= end) {
                int rangeUnits = rangeInvocation - start;
                rangeCost = unitCost * rangeUnits;
                APIUsageRangeCost usageRangeCost = new APIUsageRangeCost();
                usageRangeCost.setRangeInvocationCount(rangeUnits);
                usageRangeCost.setCostPerUnit(unitCost);
                usageRangeCost.setCost(rangeCost);
                rangeCosts.add(usageRangeCost);
                rangeInvocation = start;
            } else if (start < rangeInvocation && end <= rangeInvocation) {
                int rangeUnits = end - start;
                rangeCost = rangeUnits * unitCost;
                APIUsageRangeCost usageRangeCost = new APIUsageRangeCost();
                usageRangeCost.setCost(rangeCost);
                usageRangeCost.setCostPerUnit(unitCost);
                usageRangeCost.setRangeInvocationCount(rangeInvocation);
                rangeInvocation = start;
                rangeCosts.add(usageRangeCost);
            }
        }
        return rangeCosts;
    }
}


text:
import { MutationTree } from 'vuex'
import * as types from './mutation-types'
import RecentlyViewedState from '../types/RecentlyViewedState'

const mutations: MutationTree<RecentlyViewedState> = {
  /**
  * Add product to Recently Viewed Products
  * @param {Object} product data format for products is described in /doc/ElasticSearch data formats.md
  */
  [types.RECENTLY_VIEWED_ADD_ITEM] (state, { product }) {
    const record = state.items.find(p => p.sku === product.sku)
    if (!record) {
      state.items.unshift(product)
    }
  },
  [types.RECENTLY_VIEWED_LOAD] (state, storedItems) {
    state.items = storedItems || []
  }
}

export default mutations