text:
package com.moonlightpixels.jrpg.input;

import com.badlogic.gdx.Input;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * Stores the mapping of Keyboard Key Codes to logical control buttons.
 */
public final class KeyboardMapping {
    /**
     * A reasonable default mapping.
     */
    public static final KeyboardMapping DEFAULT = new KeyboardMapping()
        .registerUpKey(Input.Keys.UP)
        .registerDownKey(Input.Keys.DOWN)
        .registerLeftKey(Input.Keys.LEFT)
        .registerRightKey(Input.Keys.RIGHT)
        .registerActionKey(Input.Keys.ENTER)
        .registerCancelKey(Input.Keys.TAB)
        .registerMenuKey(Input.Keys.SPACE);

    private final Map<Key, KeyBinding> bindings = new HashMap<>();

    /**
     * Registers the key corresponding to the logical UP control button.
     *
     * @param keyCode Code for mapped key.
     * @return This KeyboardMapping for chaining calls.
     */
    public KeyboardMapping registerUpKey(final int keyCode) {
        bindings.put(
            Key.UP,
            new KeyBinding(
                keyCode,
                ControlEvent.UP_PRESSED,
                ControlEvent.UP_RELEASED
            )
        );

        return this;
    }

    /**
     * Registers the key corresponding to the logical DOWN control button.
     *
     * @param keyCode Code for mapped key.
     * @return This KeyboardMapping for chaining calls.
     */
    public KeyboardMapping registerDownKey(final int keyCode) {
        bindings.put(
            Key.DOWN,
            new KeyBinding(
                keyCode,
                ControlEvent.DOWN_PRESSED,
                ControlEvent.DOWN_RELEASED
            )
        );

        return this;
    }

    /**
     * Registers the key corresponding to the logical LEFT control button.
     *
     * @param keyCode Code for mapped key.
     * @return This KeyboardMapping for chaining calls.
     */
    public KeyboardMapping registerLeftKey(final int keyCode) {
        bindings.put(
            Key.LEFT,
            new KeyBinding(
                keyCode,
                ControlEvent.LEFT_PRESSED,
                ControlEvent.LEFT_RELEASED
            )
        );

        return this;
    }

    /**
     * Registers the key corresponding to the logical RIGHT control button.
     *
     * @param keyCode Code for mapped key.
     * @return This KeyboardMapping for chaining calls.
     */
    public KeyboardMapping registerRightKey(final int keyCode) {
        bindings.put(
            Key.RIGHT,
            new KeyBinding(
                keyCode,
                ControlEvent.RIGHT_PRESSED,
                ControlEvent.RIGHT_RELEASED
            )
        );

        return this;
    }

    /**
     * Registers the key corresponding to the logical ACTION control button.
     *
     * @param keyCode Code for mapped key.
     * @return This KeyboardMapping for chaining calls.
     */
    public KeyboardMapping registerActionKey(final int keyCode) {
        bindings.put(Key.ACTION, new KeyBinding(keyCode, ControlEvent.ACTION_PRESSED));
        return this;
    }

    /**
     * Registers the key corresponding to the logical CANCEL control button.
     *
     * @param keyCode Code for mapped key.
     * @return This KeyboardMapping for chaining calls.
     */
    public KeyboardMapping registerCancelKey(final int keyCode) {
        bindings.put(Key.CANCEL, new KeyBinding(keyCode, ControlEvent.CANCEL_PRESSED));
        return this;
    }

    /**
     * Registers the key corresponding to the logical MENU control button.
     *
     * @param keyCode Code for mapped key.
     * @return This KeyboardMapping for chaining calls.
     */
    public KeyboardMapping registerMenuKey(final int keyCode) {
        bindings.put(Key.MENU, new KeyBinding(keyCode, ControlEvent.MENU_PRESSED));
        return this;
    }

    /**
     * Returns the associated Pressed event if one is mapped ot this key.
     *
     * @param keyCode Key code for key that was pressed
     * @return Optional wrapping the associated Pressed event if one is mapped ot this key
     */
    public Optional<ControlEvent> getPressedEvent(final int keyCode) {
        return bindings
            .values()
            .stream()
            .filter(keyBinding -> keyBinding.getKeyCode() == keyCode)
            .findFirst()
            .flatMap(KeyBinding::getPressedControlEvent);
    }

    /**
     * Returns the associated Released event if one is mapped ot this key.
     *
     * @param keyCode Key code for key that was released
     * @return Optional wrapping the associated Released event if one is mapped ot this key
     */
    public Optional<ControlEvent> getReleasedEvent(final int keyCode) {
        return bindings
            .values()
            .stream()
            .filter(keyBinding -> keyBinding.getKeyCode() == keyCode)
            .findFirst()
            .flatMap(KeyBinding::getReleasedControlEvent);
    }

    private enum Key {
        UP, DOWN, LEFT, RIGHT, ACTION, CANCEL, MENU
    }

    private static final class KeyBinding {
        private final int keyCode;
        private final ControlEvent pressedControlEvent;
        private final ControlEvent releasedControlEvent;

        private KeyBinding(final int keyCode, final ControlEvent pressedControlEvent,
                           final ControlEvent releasedControlEvent) {
            this.keyCode = keyCode;
            this.pressedControlEvent = pressedControlEvent;
            this.releasedControlEvent = releasedControlEvent;
        }

        private KeyBinding(final int keyCode, final ControlEvent pressedControlEvent) {
            this(keyCode, pressedControlEvent, null);
        }

        public int getKeyCode() {
            return keyCode;
        }

        public Optional<ControlEvent> getPressedControlEvent() {
            return Optional.ofNullable(pressedControlEvent);
        }

        public Optional<ControlEvent> getReleasedControlEvent() {
            return Optional.ofNullable(releasedControlEvent);
        }
    }
}


text:
package com.mongodb;

import category.ReplicaSet;
import com.mongodb.client.model.Collation;
import com.mongodb.client.model.CollationAlternate;
import com.mongodb.client.model.CollationCaseFirst;
import com.mongodb.client.model.CollationMaxVariable;
import com.mongodb.client.model.CollationStrength;
import com.mongodb.operation.ListCollectionsOperation;
import com.mongodb.operation.UserExistsOperation;
import org.bson.BsonDocument;
import org.bson.BsonString;
import org.bson.codecs.BsonDocumentCodec;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import java.net.UnknownHostException;

import static com.mongodb.ClusterFixture.disableMaxTimeFailPoint;
import static com.mongodb.ClusterFixture.enableMaxTimeFailPoint;
import static com.mongodb.ClusterFixture.getBinding;
import static com.mongodb.ClusterFixture.isAuthenticated;
import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet;
import static com.mongodb.ClusterFixture.isSharded;
import static com.mongodb.ClusterFixture.serverVersionAtLeast;
import static com.mongodb.DBObjectMatchers.hasFields;
import static com.mongodb.DBObjectMatchers.hasSubdocument;
import static com.mongodb.Fixture.getDefaultDatabaseName;
import static com.mongodb.Fixture.getMongoClient;
import static com.mongodb.ReadPreference.secondary;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeThat;
import static org.junit.Assume.assumeTrue;

@SuppressWarnings("deprecation")
public class DBTest extends DatabaseTestCase {
    @Test
    public void shouldGetDefaultWriteConcern() {
        assertEquals(WriteConcern.ACKNOWLEDGED, database.getWriteConcern());
    }

    @Test
    public void shouldGetDefaultReadPreference() {
        assertEquals(ReadPreference.primary(), database.getReadPreference());
    }

    @Test
    public void shouldReturnCachedCollectionObjectIfExists() {
        DBCollection collection1 = database.getCollection("test");
        DBCollection collection2 = database.getCollection("test");
        assertThat("Checking that references are equal", collection1, sameInstance(collection2));
    }

    @Test
    public void shouldDropItself() {
        // when
        String databaseName = "drop-test-" + System.nanoTime();
        DB db = getMongoClient().getDB(databaseName);
        db.createCollection(collectionName, new BasicDBObject());

        // then
        assertThat(getMongoClient().getDatabaseNames(), hasItem(databaseName));

        // when
        db.dropDatabase();

        // then
        assertThat(getMongoClient().getDatabaseNames(), not(hasItem(databaseName)));
    }

    @Test
    public void shouldGetCollectionNames() {
        database.dropDatabase();

        String[] collectionNames = {"c1", "c2", "c3"};

        for (final String name : collectionNames) {
            database.createCollection(name, new BasicDBObject());
        }

        assertThat(database.getCollectionNames(), hasItems(collectionNames));
    }

    @Test
    public void shouldGetCollectionGivenAStringName() {
        DBCollection collection = database.getCollectionFromString("foo");
        assertEquals("foo", collection.getName());

        collection = database.getCollectionFromString("foo.bar");
        assertEquals("foo.bar", collection.getName());

        collection = database.getCollectionFromString("foo.bar.zoo");
        assertEquals("foo.bar.zoo", collection.getName());

        collection = database.getCollectionFromString("foo.bar.zoo.dork");
        assertEquals("foo.bar.zoo.dork", collection.getName());
    }

    @Test(expected = MongoException.class)
    public void shouldReceiveAnErrorIfCreatingCappedCollectionWithoutSize() {
        database.createCollection("someName", new BasicDBObject("capped", true));
    }

    @Test
    public void shouldDeferCollectionCreationIfOptionsIsNull() {
        collection.drop();
        database.createCollection(collectionName, null);
        assertFalse(database.getCollectionNames().contains(collectionName));
    }

    @Test
    public void shouldCreateCappedCollection() {
        collection.drop();
        database.createCollection(collectionName, new BasicDBObject("capped", true)
                                                  .append("size", 242880));
        assertTrue(database.getCollection(collectionName).isCapped());
    }

    @Test(expected = MongoCommandException.class)
    public void shouldErrorIfCreatingACollectionThatAlreadyExists() {
        // given
        database.createCollection(collectionName, new BasicDBObject());

        // when
        database.createCollection(collectionName, new BasicDBObject());
    }

    @Test
    public void shouldCreateCappedCollectionWithMaxNumberOfDocuments() {
        collection.drop();
        DBCollection cappedCollectionWithMax = database.createCollection(collectionName, new BasicDBObject("capped", true)
                                                                                .append("size", 242880)
                                                                                .append("max", 10));

        assertThat(cappedCollectionWithMax.getStats(), hasSubdocument(new BasicDBObject("capped", true).append("max", 10)));

        for (int i = 0; i < 11; i++) {
            cappedCollectionWithMax.insert(new BasicDBObject("x", i));
        }
        assertThat(cappedCollectionWithMax.find().count(), is(10));
    }

    @Test
    public void shouldCreateUncappedCollection() {
        collection.drop();
        BasicDBObject creationOptions = new BasicDBObject("capped", false);
        database.createCollection(collectionName, creationOptions);

        assertFalse(database.getCollection(collectionName).isCapped());
    }

    @Test(expected = MongoCommandException.class)
    public void shouldThrowErrorIfCreatingACappedCollectionWithANegativeSize() {
        collection.drop();
        DBObject creationOptions = BasicDBObjectBuilder.start().add("capped", true)
                                                       .add("size", -20).get();
        database.createCollection(collectionName, creationOptions);
    }

    @Test
    public void shouldCreateCollectionWithTheSetCollation() {
        assumeThat(serverVersionAtLeast(3, 4), is(true));
        // Given
        collection.drop();
        Collation collation = Collation.builder()
                .locale("en")
                .caseLevel(true)
                .collationCaseFirst(CollationCaseFirst.OFF)
                .collationStrength(CollationStrength.IDENTICAL)
                .numericOrdering(true)
                .collationAlternate(CollationAlternate.SHIFTED)
                .collationMaxVariable(CollationMaxVariable.SPACE)
                .backwards(true)
                .build();

        DBObject options = BasicDBObject.parse("{ collation: { locale: 'en', caseLevel: true, caseFirst: 'off', strength: 5,"
                + "numericOrdering: true, alternate: 'shifted',  maxVariable: 'space', backwards: true }}");

        // When
        database.createCollection(collectionName, options);
        BsonDocument collectionCollation = getCollectionInfo(collectionName).getDocument("options").getDocument("collation");

        // Then
        BsonDocument collationDocument = collation.asDocument();
        for (String key: collationDocument.keySet()) {
            assertEquals(collationDocument.get(key), collectionCollation.get(key));
        }

        // When - collation set on the database
        database.getCollection(collectionName).drop();
        database.createCollection(collectionName, new BasicDBObject("collation", BasicDBObject.parse(collation.asDocument().toJson())));
        collectionCollation = getCollectionInfo(collectionName).getDocument("options").getDocument("collation");

        // Then
        collationDocument = collation.asDocument();
        for (String key: collationDocument.keySet()) {
            assertEquals(collationDocument.get(key), collectionCollation.get(key));
        }
    }

    @Test(expected = DuplicateKeyException.class)
    public void shouldGetDuplicateKeyException() {
        DBObject doc = new BasicDBObject("_id", 1);
        collection.insert(doc);
        collection.insert(doc, WriteConcern.ACKNOWLEDGED);
    }

    @Test
    public void shouldDoEval() {
        assumeThat(isAuthenticated(), is(false));
        String code = "function(name, incAmount) {\n"
                      + "var doc = db.myCollection.findOne( { name : name } );\n"
                      + "doc = doc || { name : name , num : 0 , total : 0 , avg : 0 , _id: 1 };\n"
                      + "doc.num++;\n"
                      + "doc.total += incAmount;\n"
                      + "doc.avg = doc.total / doc.num;\n"
                      + "db.myCollection.save( doc );\n"
                      + "return doc;\n"
                      + "}";
        database.doEval(code, "eliot", 5);
        assertEquals(database.getCollection("myCollection").findOne(), new BasicDBObject("_id", 1.0)
                                                                       .append("avg", 5.0)
                                                                       .append("num", 1.0)
                                                                       .append("name", "eliot")
                                                                       .append("total", 5.0));
    }

    @Test(expected = MongoException.class)
    public void shouldThrowErrorwhileDoingEval() {
        String code = "function(a, b) {\n"
                      + "var doc = db.myCollection.findOne( { name : b } );\n"
                      + "}";
        database.eval(code, 1);
    }

    @Test
    public void shouldInsertDocumentsUsingEval() {
        assumeThat(isAuthenticated(), is(false));
        // when
        database.eval("db." + collectionName + ".insert({name: 'Bob'})");

        // then
        assertThat(collection.find(new BasicDBObject("name", "Bob")).count(), is(1));
    }

    @Test
    public void shouldGetStats() {
        assumeThat(isSharded(), is(false));
        assertThat(database.getStats(), hasFields(new String[]{"collections", "avgObjSize", "indexes", "db", "indexSize", "storageSize"}));
    }

    @Test
    public void shouldExecuteCommand() {
        CommandResult commandResult = database.command(new BasicDBObject("isMaster", 1));
        assertThat(commandResult, hasFields(new String[]{"ismaster", "maxBsonObjectSize", "ok"}));
    }

    @Test(expected = MongoExecutionTimeoutException.class)
    public void shouldTimeOutCommand() {
        assumeThat(isSharded(), is(false));
        assumeTrue(serverVersionAtLeast(2, 6));
        enableMaxTimeFailPoint();
        try {
            database.command(new BasicDBObject("isMaster", 1).append("maxTimeMS", 1));
        } finally {
            disableMaxTimeFailPoint();
        }
    }

    @Test
    @Category(ReplicaSet.class)
    public void shouldExecuteCommandWithReadPreference() {
        assumeThat(isSharded(), is(false));
        CommandResult commandResult = database.command(new BasicDBObject("dbStats", 1).append("scale", 1), secondary());
        assertThat(commandResult, hasFields(new String[]{"collections", "avgObjSize", "indexes", "db", "indexSize", "storageSize"}));
    }

    @Test
    public void shouldNotThrowAnExceptionOnCommandFailure() {
        CommandResult commandResult = database.command(new BasicDBObject("collStats", "a" + System.currentTimeMillis()));
        assertThat(commandResult, hasFields(new String[]{"ok", "errmsg"}));
    }

    @Test
    public void shouldAddUser() {
        String userName = "jeff";
        char[] password = "123".toCharArray();
        boolean readOnly = true;
        try {
            database.removeUser(userName);
        } catch (Exception e) {
            // NOOP
        }

        WriteResult result = database.addUser(userName, password, readOnly);
        assertEquals(1, result.getN());
        assertFalse(result.isUpdateOfExisting());
        assertTrue(new UserExistsOperation(database.getName(), userName).execute(getBinding()));
    }

    @Test
    public void shouldUpdateUser() {
        String userName = "jeff";
        char[] password = "123".toCharArray();
        boolean readOnly = true;
        try {
            database.removeUser(userName);
        } catch (Exception e) {
            // NOOP
        }

        WriteResult result = database.addUser(userName, password, readOnly);
        assertEquals(1, result.getN());
        assertFalse(result.isUpdateOfExisting());

        char[] newPassword = "345".toCharArray();
        boolean newReadOnly = false;
        result = database.addUser(userName, newPassword, newReadOnly);
        assertEquals(1, result.getN());
        assertTrue(result.isUpdateOfExisting());
        assertTrue(new UserExistsOperation(database.getName(), userName).execute(getBinding()));
    }

    @Test
    public void shouldRemoveUser() {
        String userName = "jeff";

        char[] password = "123".toCharArray();
        boolean readOnly = true;
        database.addUser(userName, password, readOnly);

        database.removeUser(userName);

        assertFalse(new UserExistsOperation(database.getName(), userName).execute(getBinding()));
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldThrowAnExceptionWhenDBNameContainsSpaces() {
        getMongoClient().getDB("foo bar");
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldThrowAnExceptionWhenDBNameIsEmpty() {
        getMongoClient().getDB("");
    }

    @Test
    public void shouldIgnoreCaseWhenCheckingIfACollectionExists() {
        // Given
        database.getCollection("foo1").drop();
        assertFalse(database.collectionExists("foo1"));

        // When
        database.createCollection("foo1", new BasicDBObject());

        // Then
        assertTrue(database.collectionExists("foo1"));
        assertTrue(database.collectionExists("FOO1"));
        assertTrue(database.collectionExists("fOo1"));

        // Finally
        database.getCollection("foo1").drop();
    }

    @Test
    public void shouldReturnFailureWithErrorMessageWhenExecutingInvalidCommand() {
        assumeTrue(serverVersionAtLeast(2, 4) || !isSharded());

        // When
        CommandResult commandResult = database.command(new BasicDBObject("NotRealCommandName", 1));

        // Then
        assertThat(commandResult.ok(), is(false));
        assertThat(commandResult.getErrorMessage(), containsString("no such"));
    }

    @Test
    public void shouldReturnOKWhenASimpleCommandExecutesSuccessfully() {
        // When
        CommandResult commandResult = database.command(new BasicDBObject("isMaster", 1));

        // Then
        assertThat(commandResult.ok(), is(true));
        assertThat((Boolean) commandResult.get("ismaster"), is(true));
    }

    @Test
    @Category(ReplicaSet.class)
    public void shouldRunCommandAgainstSecondaryWhenOnlySecondaryReadPreferenceSpecified() throws UnknownHostException {
        assumeTrue(isDiscoverableReplicaSet());

        // When
        CommandResult commandResult = database.command(new BasicDBObject("dbstats", 1), secondary());

        // Then
        assertThat(commandResult.ok(), is(true));
        assertThat((String) commandResult.get("serverUsed"), not(containsString(":27017")));
    }

    @Test
    @Category(ReplicaSet.class)
    public void shouldRunStringCommandAgainstSecondaryWhenSecondaryReadPreferenceSpecified() throws UnknownHostException {
        assumeTrue(isDiscoverableReplicaSet());

        // When
        CommandResult commandResult = database.command("dbstats", secondary());

        // Then
        assertThat(commandResult.ok(), is(true));
        assertThat((String) commandResult.get("serverUsed"), not(containsString(":27017")));
    }

    @Test
    @Category(ReplicaSet.class)
    public void shouldRunCommandAgainstSecondaryWhenOnlySecondaryReadPreferenceSpecifiedAlongWithEncoder() throws UnknownHostException {
        assumeTrue(isDiscoverableReplicaSet());

        // When
        CommandResult commandResult = database.command(new BasicDBObject("dbstats", 1), secondary(), DefaultDBEncoder.FACTORY.create());

        // Then
        assertThat(commandResult.ok(), is(true));
        assertThat((String) commandResult.get("serverUsed"), not(containsString(":27017")));
    }

    BsonDocument getCollectionInfo(final String collectionName) {
        return new ListCollectionsOperation<BsonDocument>(getDefaultDatabaseName(), new BsonDocumentCodec())
                .filter(new BsonDocument("name", new BsonString(collectionName))).execute(getBinding()).next().get(0);
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: Page Family Reunion
date: 2016-05-24
author: Joe Eaton
tags: weekly links, java
status: published
summary: Donec sit amet nulla in nibh.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 09/06/2016
  endDate: 09/10/2016
  ctyhocn: MLUMOHX
  groupCode: PFR
published: true
---
Duis sem urna, vestibulum malesuada tincidunt vitae, pharetra ac neque. Donec nec dui sed diam sollicitudin auctor. Etiam et nisi consequat lorem vestibulum finibus ut nec eros. Duis eu justo sed mauris consequat consectetur eu ac ipsum. Mauris accumsan, justo eu vehicula faucibus, quam nisl molestie neque, ut commodo diam velit ac nibh. Vivamus pretium turpis non nibh bibendum, at aliquam metus commodo. Maecenas semper, sapien quis cursus hendrerit, dolor risus venenatis tortor, sit amet lacinia eros urna eget magna. Proin egestas sed justo ut interdum. Duis at varius mi. Vestibulum ante nisl, mollis eu auctor ac, porttitor id nunc. Nulla ac tempus tortor.

* Sed blandit lectus ac euismod fermentum
* Aenean sed justo non nunc auctor pharetra a vitae elit
* Pellentesque fermentum turpis vel tellus bibendum vehicula
* Donec euismod quam eget diam ornare, eget mollis nibh finibus.

Suspendisse posuere ultrices hendrerit. Aenean posuere, nisl id volutpat tempor, orci enim posuere mauris, sed feugiat ipsum massa quis metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum non metus urna. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent efficitur aliquam aliquam. Mauris rhoncus sit amet odio quis egestas.


text:
Vue starter example

Vue starter project the way I find it useful.

## Features
* Single File .vue components
* Server Side Rendering
* less
* Webpack dev config


text:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';

import { Movie } from '../movie';
import { MovieService } from '../movie.service';

import { NumberValidators } from '../../shared/number.validator';

@Component({
  templateUrl: './movie-edit-reactive.component.html'
})
export class MovieEditReactiveComponent implements OnInit {
  pageTitle = 'Edit Movie';
  editForm: FormGroup;
  formError: { [id: string]: string };
  private validationMessages: { [id: string]: { [id: string]: string } };
  movie: Movie;
  errorMessage: string;

  constructor(private fb: FormBuilder,
              private movieService: MovieService,
              private router: Router,
              private route: ActivatedRoute) {

    // Without FormBuilder
    // this.editForm = new FormGroup({
    //     title: new FormControl('', [Validators.required,
    //                                 Validators.minLength(3),
    //                                 Validators.maxLength(50)]),
    //     director: new FormControl('', [Validators.required,
    //                                    Validators.minLength(5),
    //                                    Validators.maxLength(50)]),
    //     starRating: new FormControl('', NumberValidators.range(1, 5)),
    //     description: new FormControl('')
    // });

    // With FormBuilder
    this.editForm = this.fb.group({
      title: ['', [Validators.required,
      Validators.minLength(3),
      Validators.maxLength(50)]],
      director: ['', [Validators.required,
      Validators.minLength(5),
      Validators.maxLength(50)]],
      starRating: ['', NumberValidators.range(1, 5)],
      description: ['']
    });

    // Watch all of the controls on the form
    this.editForm.valueChanges
      .subscribe(data => this.onValueChanged(data));
    // this.editForm.valueChanges
    //         .debounceTime(500)
    //         .subscribe(data => this.onValueChanged(data));

    // Watch one control on the form.
    this.editForm.get('title').valueChanges
      .subscribe(value => console.log(`Title Changed to: ${value}`));

    // Initialize strings
    this.formError = {
      title: '',
      director: '',
      starRating: '',
      description: ''
    };

    this.validationMessages = {
      title: {
        required: 'Movie title is required',
        minlength: 'Movie title must be at least three characters.',
        maxlength: 'Movie title cannot exceed 50 characters.'
      },
      director: {
        required: 'Director is required',
        minlength: 'Director must be at least 5 characters.',
        maxlength: 'Director cannot exceed 50 characters.'
      },
      starRating: {
        range: 'Rate the movie between 1 (lowest) and 5 (highest).'
      }
    };
  }

  ngOnInit(): void {
    this.route.params.subscribe(
      params => {
        const paramName = 'id';
        const id = +params[paramName];
        this.getMovie(id);
      }
    );
  }

  getMovie(id: number): void {
    this.movieService.getMovie(id).subscribe(
      movie => this.onMovieRetrieved(movie),
      error => this.errorMessage = error
    );
  }

  onMovieRetrieved(movie: Movie): void {
    if (this.editForm) {
      this.editForm.reset();
    }
    this.movie = movie;

    if (this.movie.id === 0) {
      this.pageTitle = 'Add Movie (Reactive)';
    } else {
      this.pageTitle = `Edit Movie (Reactive): ${this.movie.title}`;
    }

    // Update the data on the form
    this.editForm.patchValue({
      title: this.movie.title,
      director: this.movie.director,
      starRating: this.movie.starRating,
      description: this.movie.description
    });
  }

  // Start of a generic validator
  onValueChanged(data: any): void {
    Object.keys(this.formError).forEach(field => {
      const hasError = this.editForm.get(field).dirty &&
        !this.editForm.get(field).valid;
      this.formError[field] = '';
      if (hasError) {
        Object.keys(this.editForm.get(field).errors).forEach(rule =>
          this.formError[field] += this.validationMessages[field][rule] + ' '
        );
      }
    });
  }

  saveMovie(): void {
    console.log(this.editForm);
    if (this.editForm.dirty && this.editForm.valid) {
      // Copy the form values over the object values
      const m = Object.assign({}, this.movie, this.editForm.value);

      this.movieService.saveMovie(m).subscribe(
        () => this.onSaveComplete(),
        (error: any) => this.errorMessage = error
      );
    } else if (!this.editForm.dirty) {
      this.onSaveComplete();
    }
  }

  onSaveComplete(): void {
    // Reset the form to clear the flags
    this.editForm.reset();
    this.router.navigate(['/movies']);
  }
}


text:
package com.agenthun.eseal.utils;

import android.content.Context;
import android.graphics.Point;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;

/**
 * Created by Agent Henry on 2015/4/23.
 */
public class UiUtil {
    public static int getScreenWidthPixels(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    public static int getScreenHeightPixels(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    public static float dipToPx(Context context, int dip) {
        return dip * getScreenDensity(context) + 0.5f;
    }

    public static int pxToDip(Context context, float px) {
        return (int) (px / getScreenDensity(context) + 0.5f);
    }

    public static float getScreenDensity(Context context) {
        try {
            DisplayMetrics dm = new DisplayMetrics();
            ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(dm);
            return dm.density;
        } catch (Exception e) {
            return DisplayMetrics.DENSITY_DEFAULT;
        }
    }
}


text:
ProvinceSearchSubPanel::ProvinceSearchSubPanel(Game &game)
	: Panel(game) { }

bool ProvinceSearchSubPanel::init(ProvinceMapPanel &provinceMapPanel, int provinceID)
{
	auto &game = this->getGame();
	auto &renderer = game.getRenderer();
	const auto &fontLibrary = game.getFontLibrary();

	// Don't initialize the locations list box until it's reached, since its contents
	// may depend on the search results.
	const std::string textTitleText = ProvinceSearchUiModel::getTitleText(game);
	const TextBox::InitInfo textTitleTextBoxInitInfo =
		ProvinceSearchUiView::getTitleTextBoxInitInfo(textTitleText, fontLibrary);
	if (!this->textTitleTextBox.init(textTitleTextBoxInitInfo, textTitleText, renderer))
	{
		DebugLogError("Couldn't init title text box.");
		return false;
	}

	const TextBox::InitInfo textEntryTextBoxInitInfo = ProvinceSearchUiView::getTextEntryTextBoxInitInfo(fontLibrary);
	if (!this->textEntryTextBox.init(textEntryTextBoxInitInfo, renderer))
	{
		DebugLogError("Couldn't init text entry text box.");
		return false;
	}

	// Button proxies for these are added when the locations list is initialized.
	this->listUpButton = Button<ListBox&>(
		ProvinceSearchUiView::ListUpButtonCenterPoint,
		ProvinceSearchUiView::ListUpButtonWidth,
		ProvinceSearchUiView::ListUpButtonHeight,
		ProvinceSearchUiController::onListUpButtonSelected);
	this->listDownButton = Button<ListBox&>(
		ProvinceSearchUiView::ListDownButtonCenterPoint,
		ProvinceSearchUiView::ListDownButtonWidth,
		ProvinceSearchUiView::ListDownButtonHeight,
		ProvinceSearchUiController::onListDownButtonSelected);

	this->addInputActionListener(InputActionName::Accept,
		[this, &game](const InputActionCallbackValues &values)
	{
		if (values.performed)
		{
			if (this->mode == ProvinceSearchUiModel::Mode::TextEntry)
			{
				// Begin the next step in the location search. Run the entered text through some
				// checks to see if it matches any location names.
				ProvinceSearchUiController::onTextAccepted(this->getGame(), *this);
			}
		}
	});

	this->addInputActionListener(InputActionName::Back,
		[this, &game](const InputActionCallbackValues &values)
	{
		if (values.performed)
		{
			auto &inputManager = game.getInputManager();
			inputManager.setTextInputMode(false);

			// Return to the province map panel.
			game.popSubPanel();
		}
	});

	this->addInputActionListener(InputActionName::Backspace,
		[this](const InputActionCallbackValues &values)
	{
		if (values.performed)
		{
			if (this->mode == ProvinceSearchUiModel::Mode::TextEntry)
			{
				const bool textChanged = TextEntry::backspace(this->locationName);
				if (textChanged)
				{
					this->textEntryTextBox.setText(this->locationName);
				}
			}
		}
	});

	this->addMouseScrollChangedListener([this](Game &game, MouseWheelScrollType type, const Int2 &position)
	{
		if (this->mode == ProvinceSearchUiModel::Mode::List)
		{
			const Rect &listBoxRect = this->locationsListBox.getRect();
			const Int2 classicPosition = game.getRenderer().nativeToOriginal(position);
			if (listBoxRect.contains(classicPosition))
			{
				if (type == MouseWheelScrollType::Up)
				{
					this->listUpButton.click(this->locationsListBox);
				}
				else if (type == MouseWheelScrollType::Down)
				{
					this->listDownButton.click(this->locationsListBox);
				}
			}
		}
	});

	this->addTextInputListener([this](const std::string_view &text)
	{
		if (this->mode == ProvinceSearchUiModel::Mode::TextEntry)
		{
			const bool textChanged = TextEntry::append(this->locationName, text,
				ProvinceSearchUiModel::isCharAllowed, ProvinceSearchUiModel::MaxNameLength);

			if (textChanged)
			{
				this->textEntryTextBox.setText(this->locationName);
			}
		}
	});

	auto &textureManager = game.getTextureManager();
	const UiTextureID parchmentTextureID = ProvinceSearchUiView::allocParchmentTexture(textureManager, renderer);
	this->parchmentTextureRef.init(parchmentTextureID, renderer);

	UiDrawCall::ActiveFunc textEntryActiveFunc = [this]()
	{
		return this->mode == ProvinceSearchUiModel::Mode::TextEntry;
	};

	this->addDrawCall(
		[this]() { return this->parchmentTextureRef.get(); },
		[]() { return Int2((ArenaRenderUtils::SCREEN_WIDTH / 2) - 1, (ArenaRenderUtils::SCREEN_HEIGHT / 2) - 1); },
		[]() { return Int2(ProvinceSearchUiView::TextureWidth, ProvinceSearchUiView::TextureHeight); },
		[]() { return PivotType::Middle; },
		textEntryActiveFunc);

	const Rect &textTitleTextBoxRect = this->textTitleTextBox.getRect();
	this->addDrawCall(
		[this]() { return this->textTitleTextBox.getTextureID(); },
		[textTitleTextBoxRect]() { return textTitleTextBoxRect.getTopLeft(); },
		[textTitleTextBoxRect]() { return Int2(textTitleTextBoxRect.getWidth(), textTitleTextBoxRect.getHeight()); },
		[]() { return PivotType::TopLeft; },
		textEntryActiveFunc);

	const Rect &textEntryTextBoxRect = this->textEntryTextBox.getRect();
	this->addDrawCall(
		[this]() { return this->textEntryTextBox.getTextureID(); },
		[textEntryTextBoxRect]() { return textEntryTextBoxRect.getTopLeft(); },
		[textEntryTextBoxRect]() { return Int2(textEntryTextBoxRect.getWidth(), textEntryTextBoxRect.getHeight()); },
		[]() { return PivotType::TopLeft; },
		textEntryActiveFunc);

	// @todo: draw blinking cursor for text entry

	const auto &binaryAssetLibrary = game.getBinaryAssetLibrary();
	const UiTextureID listBackgroundTextureID = ProvinceSearchUiView::allocListBackgroundTexture(
		provinceID, binaryAssetLibrary, textureManager, renderer);
	listBackgroundTextureRef.init(listBackgroundTextureID, renderer);

	UiDrawCall::ActiveFunc listActiveFunc = [this]()
	{
		return this->mode == ProvinceSearchUiModel::Mode::List;
	};

	this->addDrawCall(
		[this]() { return this->listBackgroundTextureRef.get(); },
		[]() { return Int2(ProvinceSearchUiView::ListTextureX, ProvinceSearchUiView::ListTextureY); },
		[this]() { return Int2(this->listBackgroundTextureRef.getWidth(), this->listBackgroundTextureRef.getHeight()); },
		[]() { return PivotType::TopLeft; },
		listActiveFunc);

	UiDrawCall::PositionFunc listBoxPositionFunc = [this]()
	{
		const Rect &locationsListBoxRect = this->locationsListBox.getRect();
		return locationsListBoxRect.getTopLeft();
	};

	UiDrawCall::SizeFunc listBoxSizeFunc = [this]()
	{
		// Have to get the size dynamically due to the list not being initialized or populated yet.
		const Rect &locationsListBoxRect = this->locationsListBox.getRect();
		return Int2(locationsListBoxRect.getWidth(), locationsListBoxRect.getHeight());
	};

	this->addDrawCall(
		[this]() { return this->locationsListBox.getTextureID(); },
		listBoxPositionFunc,
		listBoxSizeFunc,
		[]() { return PivotType::TopLeft; },
		listActiveFunc);

	const UiTextureID cursorTextureID = CommonUiView::allocDefaultCursorTexture(textureManager, renderer);
	this->cursorTextureRef.init(cursorTextureID, renderer);
	this->addCursorDrawCall(this->cursorTextureRef.get(), PivotType::TopLeft, listActiveFunc);

	this->provinceMapPanel = &provinceMapPanel;
	this->mode = ProvinceSearchUiModel::Mode::TextEntry;
	this->provinceID = provinceID;

	// Start with text input enabled.
	auto &inputManager = game.getInputManager();
	inputManager.setTextInputMode(true);

	return true;
}

void ProvinceSearchSubPanel::initLocationsList()
{
	// @todo: move the locationNames into UiModel
	auto &game = this->getGame();
	auto &gameState = game.getGameState();
	const WorldMapDefinition &worldMapDef = gameState.getWorldMapDefinition();
	const WorldMapInstance &worldMapInst = gameState.getWorldMapInstance();
	const ProvinceInstance &provinceInst = worldMapInst.getProvinceInstance(this->provinceID);
	const int provinceDefIndex = provinceInst.getProvinceDefIndex();
	const ProvinceDefinition &provinceDef = worldMapDef.getProvinceDef(provinceDefIndex);

	this->locationsListBox.init(ProvinceSearchUiView::ListBoxRect,
		ProvinceSearchUiView::makeListBoxProperties(game.getFontLibrary()), game.getRenderer());

	this->clearButtonProxies();

	// Add list box scroll button proxies.
	this->addButtonProxy(MouseButtonType::Left, this->listUpButton.getRect(),
		[this]()
	{
		this->listUpButton.click(this->locationsListBox);
	});

	this->addButtonProxy(MouseButtonType::Left, this->listDownButton.getRect(),
		[this]()
	{
		this->listDownButton.click(this->locationsListBox);
	});

	// Add list box items and button proxies.
	for (int i = 0; i < static_cast<int>(this->locationsListIndices.size()); i++)
	{
		const int locationIndex = this->locationsListIndices[i];
		const LocationInstance &locationInst = provinceInst.getLocationInstance(locationIndex);
		const int locationDefIndex = locationInst.getLocationDefIndex();
		const LocationDefinition &locationDef = provinceDef.getLocationDef(locationDefIndex);
		std::string locationName = locationInst.getName(locationDef);

		this->locationsListBox.add(std::move(locationName));
		this->locationsListBox.setCallback(i, [this, &game, i]()
		{
			DebugAssertIndex(this->locationsListIndices, i);
			const int locationsListIndex = this->locationsListIndices[i];
			ProvinceSearchUiController::onListLocationSelected(game, *this, locationsListIndex);
		});

		auto rectFunc = [this, i]()
		{
			return this->locationsListBox.getItemGlobalRect(i);
		};

		auto callback = [this, i]()
		{
			const ListBox::ItemCallback &itemCallback = this->locationsListBox.getCallback(i);
			itemCallback();
		};

		this->addButtonProxy(MouseButtonType::Left, rectFunc, callback);
	}
}

void ProvinceSearchSubPanel::tick(double dt)
{
	// @todo: eventually blink text input cursor in text entry, and listen for scrolling in list box.
	static_cast<void>(dt);
}


text:
<?php

namespace Detail\Apigility\Hydrator;

use Zend\EventManager\EventInterface;

use ZF\Hal\Collection as HalCollection;
use ZF\Hal\Entity as HalEntity;

use Detail\Apigility\Hal\BaseRenderListener;
use Detail\Apigility\Normalization\NormalizationGroupsProviderAwareInterface;
use Detail\Apigility\Normalization\NormalizationGroupsProviderAwareTrait;
use Detail\Apigility\Normalization\NormalizationGroupsProviderInterface;

class NormalizerBasedHydrationListener extends BaseRenderListener implements
    NormalizationGroupsProviderAwareInterface
{
    use NormalizationGroupsProviderAwareTrait;

    /**
     * @var NormalizerBasedHydrator
     */
    protected $hydrator;

    /**
     * @param NormalizerBasedHydrator $hydrator
     * @param NormalizationGroupsProviderInterface $groupsProvider
     */
    public function __construct(
        NormalizerBasedHydrator $hydrator,
        NormalizationGroupsProviderInterface $groupsProvider = null
    ) {
        $this->setHydrator($hydrator);

        if ($groupsProvider !== null) {
            $this->setNormalizationGroupsProvider($groupsProvider);
        }
    }

    /**
     * @return NormalizerBasedHydrator
     */
    public function getHydrator()
    {
        return $this->hydrator;
    }

    /**
     * @param NormalizerBasedHydrator $hydrator
     */
    public function setHydrator(NormalizerBasedHydrator $hydrator)
    {
        $this->hydrator = $hydrator;
    }

    /**
     * Listener for the "renderCollection" event.
     *
     * @param EventInterface $event
     */
    public function onRenderCollection(EventInterface $event)
    {
        /** @var HalCollection $halCollection */
        $halCollection = $event->getParam('collection');

        $this->applyDefaultGroups($halCollection);
    }

    /**
     * Listener for the "renderCollection.entity" event
     *
     * @param EventInterface $event
     * @return void
     */
    public function onRenderCollectionEntity(EventInterface $event)
    {
        // Nothing to do
    }

    /**
     * Listener for the "renderEntity" event
     *
     * @param EventInterface $event
     */
    public function onRenderEntity(EventInterface $event)
    {
        /** @var HalEntity $halEntity */
        $halEntity = $event->getParam('entity');

        $this->applyDefaultGroups($halEntity);
    }

    /**
     * @param HalEntity|HalCollection $collectionOrEntity
     * @param boolean $force
     */
    protected function applyDefaultGroups($collectionOrEntity, $force = false)
    {
        $groupsProvider = $this->getNormalizationGroupsProvider();
        $hydrator = $this->getHydrator();

        if ($groupsProvider === null
            || ($hydrator->hasDefaultGroups() && $force !== true)
        ) {
            return;
        }

        $groups = $groupsProvider->getGroups($collectionOrEntity);

        $hydrator->setDefaultGroups($groups);
    }
}


text:
description: This template allows you to create an Azure Security Center Automation which triggers an empty logic app, which will be triggered by any Security Center Alert
page_type: sample
products:
- azure
- azure-resource-manager
urlFragment: securitycenter-create-automation-for-all-alerts
languages:
- json
---
# Create A Security Automation for all Alerts

![Azure Public Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.security/securitycenter-create-automation-for-all-alerts/PublicLastTestDate.svg)
![Azure Public Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.security/securitycenter-create-automation-for-all-alerts/PublicDeployment.svg)

![Azure US Gov Last Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.security/securitycenter-create-automation-for-all-alerts/FairfaxLastTestDate.svg)
![Azure US Gov Last Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.security/securitycenter-create-automation-for-all-alerts/FairfaxDeployment.svg)

![Best Practice Check](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.security/securitycenter-create-automation-for-all-alerts/BestPracticeResult.svg)
![Cred Scan Check](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.security/securitycenter-create-automation-for-all-alerts/CredScanResult.svg)

[![Deploy To Azure](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazure.svg?sanitize=true)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fquickstarts%2Fmicrosoft.security%2Fsecuritycenter-create-automation-for-all-alerts%2Fazuredeploy.json)  [![Visualize](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/visualizebutton.svg?sanitize=true)](http://armviz.io/#/?load=https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fquickstarts%2Fmicrosoft.security%2Fsecuritycenter-create-automation-for-all-alerts%2Fazuredeploy.json)

This template deploys an Azure Security Center Automation for any of Azure Security Center's alerts.
Automation is an Azure Resource which triggers a Logic App.

## Overview and deployed resources

This is an overview of the solution

The following resources are deployed as part of the solution

### Microsoft.Logic Resource provider

The Microsoft.Logic Resource provider is used to create an empty triggerable Logic App.

+ **Logic App**: An Empty triggerable Logic App

### Microsoft.Security Resource provider

The Microsoft.Security Resource provider (Azure Security Center) is where the Automation which will trigger the logic app will be created.

+ **Automation**: The Automation which will trigger the empty Logic App, upon receiving any Azure Security Center alert.

## Prerequisites

Users need to be registered to both Microsoft.Logic and Microsoft.Security resource providers to run this.

## Deployment steps

You can click the "deploy to Azure" button at the beginning of this document or follow the instructions for command line deployment using the scripts in the root of this repo.

## Notes

Solution notes

`Tags: Security, Security Center, LogicApps, Automations, Microsoft.Security/automations, Microsoft.Logic/workflows, request, object, string`


text:
from http.server import HTTPServer, SimpleHTTPRequestHandler
try:
    from html_json_forms import parse_json_form
except ImportError:
    def parse_json_form(data):
        return parse_values_array(data)

import json
import random
import string
import cgi

batch_number = 0

class RequestHandler(SimpleHTTPRequestHandler):
    def echo(self, status=200, id=None):
        ctype, pdict = cgi.parse_header(self.headers.get('content-type'))
        pdict = {key: val.encode('utf-8') for key, val in pdict.items()}
        form = cgi.parse_multipart(self.rfile, pdict)
        data = parse_json_form({
            key: val[0]
            for key, val in form.items()
        })
        for value in data.values():
            if isinstance(value, list):
                for i, val in enumerate(value):
                    val['@index'] = i
        if id and 'id' not in data:
            data['id'] = id
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(json.dumps(data).encode('utf-8'))

    def do_POST(self):
        if '/error' in self.path or 'status/400' in self.path:
            self.status_400()
        elif 'status/500' in self.path:
            self.status_500()
        elif 'reset-batch-number' in self.path:
            self.reset_batch_number()
        elif 'batch' in self.path:
            self.process_batch()
        else:
            self.status_200()

    def generate_id(self):
        return ''.join([
            random.choice(string.ascii_lowercase)
            for o in range(3)
        ])

    def status_200(self):
        self.echo(id=self.generate_id())

    def status_400(self):
        self.send_response(400)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(json.dumps({
            "label": ["Not a valid label"]
        }).encode('utf-8'))

    def status_500(self):
        self.send_response(500)
        self.send_header("Content-Type", "text/html")
        self.end_headers()
        self.wfile.write(b"SERVER ERROR")

    def reset_batch_number(self):
        global batch_number
        batch_number = 0
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"{}")

    def process_batch(self):
        global batch_number
        batch_number += 1
        size = int(self.headers['Content-Length'])
        requests = json.loads(self.rfile.read(size).decode('utf-8'))

        def process_request(request):
            data = json.loads(request['body'])
            data['id'] = self.generate_id()
            data['batch'] = batch_number
            return {
                'status_code': 200,
                'headers': {},
                'body': json.dumps(data)
            }

        responses = [
            process_request(request) for request in requests
        ]

        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(json.dumps(responses).encode('utf-8'))

    def do_PUT(self):
        pk = self.path.split('/')[-1].split('.')[0]
        self.echo(id=pk)

    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.end_headers()
        self.wfile.write(b"OK")

    def end_headers(self):
        self.send_header("Access-Control-Allow-Origin", "*")
        super().end_headers()

def run():
    address = ("", 8080)
    httpd = HTTPServer(address, RequestHandler)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        httpd.server_close()

def parse_values_array(data):
    for key, val in list(data.items()):
        if key.startswith('values['):
            i = int(key[7])
            if 'values' not in data:
                data['values'] = []
            while len(data['values']) < i + 1:
                data['values'].append({})
            data['values'][i][key[9:].strip('[]')] = data[key]
            data.pop(key)
    return data

if __name__ == "__main__":
    run()


text:
layout: post
title: This is the start…
categories:
- Musing
---

yes! Even I have started blogging...after much contemplation. I was pestering Anand and Jazz…should I blog or not. Recently, due to the much free time in my internship, I started reading my friends' blogs. In a weird way it was teaching me about life…about love, about friends, about family and regrets. Yes, I do put down my thoughts in total privacy…but hey!…suddenly I want the whole word to know?? Why?…as Villa was saying Blogs are **oxymoron**….yeah in a way…

 I wrote down my thoughts since primary school…let's see what blogging does to me! But this blog will remain a secret…till I want my friends to know about it…let's see when that time will come.


text:
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "states/loading_state.h"

#include <cmath>

#include "assets_generated.h"
#include "camera.h"
#include "fplbase/asset_manager.h"
#include "fplbase/glplatform.h"
#include "fplbase/input.h"
#include "fplbase/material.h"
#if FPLBASE_ANDROID_VR
#include "fplbase/renderer_hmd.h"
#endif // FPLBASE_ANDROID_VR
#include "fplbase/shader.h"
#include "fplbase/utilities.h"
#include "full_screen_fader.h"
#include "mathfu/constants.h"
#include "mathfu/glsl_mappings.h"
#include "mathfu/matrix.h"
#include "mathfu/quaternion.h"
#include "mathfu/vector.h"
#include "pindrop/pindrop.h"
#include "states/states.h"
#include "states/states_common.h"
#include "world.h"

#define ZOOSHI_WAIT_ON_LOADING_SCREEN 0

namespace fpl {
namespace zooshi {

using mathfu::kOnes3f;
using mathfu::kOnes4f;
using mathfu::kZeros3f;
using mathfu::kZeros4f;
using mathfu::mat3;
using mathfu::mat4;
using mathfu::vec2;
using mathfu::vec3;
using mathfu::vec4;

static const corgi::WorldTime kLoadingScreenFadeInTime = 400;
static const corgi::WorldTime kLoadingScreenFadeOutTime = 200;

void LoadingState::Initialize(fplbase::InputSystem* input_system, World* world,
                              const AssetManifest& asset_manifest,
                              fplbase::AssetManager* asset_manager,
                              pindrop::AudioEngine* audio_engine,
                              fplbase::Shader* shader_textured,
                              FullScreenFader* fader) {
  input_system_ = input_system;
  world_ = world;
  asset_manager_ = asset_manager;
  audio_engine_ = audio_engine;
  asset_manifest_ = &asset_manifest;
  shader_textured_ = shader_textured;
  loading_complete_ = false;
  fader_ = fader;
}

void LoadingState::AdvanceFrame(int delta_time, int* next_state) {
  const bool fade_out_complete = fader_->AdvanceFrame(delta_time);
#if ZOOSHI_WAIT_ON_LOADING_SCREEN
  loading_complete_ = false;
#endif  // !ZOOSHI_WAIT_ON_LOADING_SCREEN

  // Exit state when everything has finished loading.
  if (loading_complete_ && fade_out_complete) {
    *next_state = kGameStateGameMenu;
  }

#if FPLBASE_ANDROID_VR
  // Get the direction vector from the HMD input.
  const fplbase::HeadMountedDisplayInput& head_mounted_display_input =
    input_system_->head_mounted_display_input();
  const vec3 hmd_forward = head_mounted_display_input.forward();
  const vec2 forward = vec2(hmd_forward.x, -hmd_forward.z).Normalized();
  const float rotation = atan2(forward.x, forward.y);
  // Rate of convergence (angle moved = 0.5 * convergence * time) to the
  // target rotation angle.
  static const float kConvergenceRate = 2.0f;
  banner_rotation_ += (((M_PI * 2) - rotation) - banner_rotation_) *
    kConvergenceRate * std::min(delta_time / 1000.0f, 1.0f);
#endif  // FPLBASE_ANDROID_VR

}

void LoadingState::Render(fplbase::Renderer* renderer) {
  // Ensure assets are instantiated after they've been loaded.
  // This must be called from the render thread.
  loading_complete_ =
      asset_manager_->TryFinalize() && audio_engine_->TryFinalize();

  // Get a handle to the loading material.
  const char* loading_material_name =
      asset_manifest_->loading_material()->c_str();
  fplbase::Material* loading_material =
      asset_manager_->FindMaterial(loading_material_name);

  // Render black until the loading material itself has loaded.
  auto texture = loading_material->textures()[0];
  if (!fplbase::ValidTextureHandle(texture->id()) ||
      (world_->rendering_mode() == kRenderingStereoscopic &&
       !fplbase::ValidTextureHandle(
           world_->cardboard_settings_gear->textures()[0]->id()))) {
    renderer->ClearFrameBuffer(kZeros4f);
    return;
  }

  const vec2 res(renderer->window_size());
  const float aspect_ratio = res.x / res.y;
  if (world_->rendering_mode() == kRenderingStereoscopic) {
#if FPLBASE_ANDROID_VR
    fplbase::Shader *shader_textured = shader_textured_;
    fplbase::HeadMountedDisplayViewSettings view_settings;
    HeadMountedDisplayRenderStart(input_system_->head_mounted_display_input(),
                                  renderer, mathfu::kZeros4f, true,
                                  &view_settings);
    // Create rotation matrix for banner based upon banner_angle_
    static const float kAngle = M_PI / 2.0f;  // Around X to face the camera.
    const mat4 banner_transform = mat4::FromRotationMatrix(
      mat3::RotationX(kAngle) * mat3::RotationY(banner_rotation_));
    for (auto i = 0; i < 2; ++i) {
      renderer->set_camera_pos(kZeros3f);
      Camera camera;
      renderer->set_model_view_projection(
          camera.GetTransformMatrix() * banner_transform *
          view_settings.viewport_transforms[i]);
      renderer->set_color(kOnes4f);
      loading_material->Set(*renderer);
      shader_textured->Set(*renderer);
      auto vp = view_settings.viewport_extents[i];
      glViewport(vp.x, vp.y, vp.z, vp.w);

      // Render the loading banner floating in front of the viewer.
      const vec2 size = vec2(texture->size()).Normalized() * 50.0f;
      // Place the banner just in front and behind the camera.
      static const float kDistance = -120.0f;
      const vec3 bottom_left(-size.x, size.y, kDistance);
      const vec3 top_right(size.x, -size.y, kDistance);
      fplbase::Mesh::RenderAAQuadAlongX(bottom_left, top_right);
    }
    HeadMountedDisplayRenderEnd(renderer, true);
#endif // FPLBASE_ANDROID_VR
  } else {
    // Always clear the background.
    renderer->ClearFrameBuffer(kOnes4f);

    // In ortho space:
    //  - screen centered at (0,0)
    //  - unit of 1 is distance from middle to top of screen
    //  - bottom left is (-aspect_ratio, -1)
    //  - top right is (aspect_ratio, +1)
    //  - horizontal and vertical units are same distance on screen
    renderer->set_model_view_projection(
        mat4::Ortho(-aspect_ratio, aspect_ratio, -1.0f, 1.0f, -1.0f, 1.0f));

    // Set up rendering context.
    renderer->set_color(kOnes4f);
    loading_material->Set(*renderer);
    shader_textured_->Set(*renderer);

    // Only scale the image by 2, 1, or 0.5 so that it remains crisp.
    // We assume the loading texture is square and that the screen is wider
    // than it is high, so only check height.
    const int window_y = renderer->window_size().y;
    const int image_y = texture->original_size().y;
    const float scale = image_y * 2 <= window_y ? 2.0f :
                        image_y > window_y ? 0.5f : 1.0f;

    // Render the overlay in front on the screen.
    const vec2 size = scale * vec2(texture->size()) / res.y;
    const vec3 bottom_left(-size.x, size.y, 0.0f);
    const vec3 top_right(size.x, -size.y, 0.0f);
    fplbase::Mesh::RenderAAQuadAlongX(bottom_left, top_right);
  }

  const vec3 fade_bottom_left(-aspect_ratio, 1.0f, 0.0f);
  const vec3 fade_top_right(aspect_ratio, -1.0f, 0.0f);
  if (fader_->current_fade_time() == 0) {
    // If this is the first frame the textures have been loaded, start fade-in.
    fader_->Start(kLoadingScreenFadeInTime, kZeros3f, kFadeIn, fade_bottom_left,
                  fade_top_right);
  } else if (loading_complete_ && fader_->Finished()) {
    // If this is the first frame the textures have been loaded, start fade-out.
    fader_->Start(kLoadingScreenFadeOutTime, kZeros3f, kFadeOutThenIn,
                  fade_bottom_left, fade_top_right);
  }

  // Draw fader on top of everything.
  if (!fader_->Finished()) {
    fader_->Render(renderer);
  }
}

void LoadingState::OnEnter(int /*previous_state*/) {
#if FPLBASE_ANDROID_VR
  input_system_->head_mounted_display_input().ResetHeadTracker();
#endif  // FPLBASE_ANDROID_VR
}

}  // zooshi
}  // fpl


text:
<?php

class BookStore_SocialWidget_Block_Share extends
Mage_Core_Block_Abstract implements Mage_Widget_Block_Interface {

    protected function _toHtml() {
// Get Widget Data
        $block_title = $this->getData('block_title');
        $show_count = $this->getData('show_count');
// Variable that contains the bubble count code
        $bubblecode = "";
        if ($show_count == 'true')
            $bubblecode = "";
        $html = '

' . $block_title
                . '
';
        $html .='

            ' . $bubblecode . '

';
        return $html;
    }

}


text:
<Alloy>

	<TabGroup backgroundColor="white" >
		<Menu platform="android" backgroundColor="white">
			<MenuItem id="preferencias" title="Preferências" onClick="openPref">...</MenuItem>
		</Menu>
		<!--<RightNavButton platform="ios">
			<Button id="btIosPref" >...</Button>
	</RightNavButton> -->
		<Require src="categorias"></Require>
		<Require src="favoritos"></Require>

	</TabGroup>
</Alloy>


text:
/**
 * Module dependencies
 */

var _ = require('lodash');
var rttc = require('rttc');
var escapeHtmlEntitiesDeep = require('./escape-html-entities-deep');

/**
 * htmlScriptify()
 *
 * Generate a string of HTML code that can be injected onto a page
 * in order to expose a JSON-serializable version of the provided
 * data to client-side JavaScript.
 *
 * @required {Dictionary} options.data
 *           The dictionary (i.e. of locals) that will be converted into an HTML snippet containing
 *           our script tag. If any of the keys cannot be coerced to be JSON-serializable (i.e.
 *           contain nothing that isn't a string, number, boolean, plain dictionary, array, or null),
 *           then they are simply excluded.  Additionally, each key is recursively parsed to snip off
 *           any circular references and otherwise ensure full JSON-serializability of ever nested key
 *           therein.  See rttc.dehydrate() for more information.
 *
 * @optional {Array} options.keys
 *           An array of strings; the names of keys in data which should be exposed to on the namespace. If left unspecified, all keys in data will be exposed.
 *
 * @optional {String} options.namespace
 *           The name of the key on the window object where data should be exposed. Defaults to 'SAILS_LOCALS'.
 *
 * @optional {Boolean} options.dontUnescapeOnClient
 *           Defaults to false. When false (by default) client-side JavaScript code will be
 *           injected around the exposed data. When the page loads, the injected client-side
 *           JavaScript runs, unescaping the values so that they are accessible to client-side
 *           JavaScript with no further transformation necessary (i.e. they are immediately
 *           usable just like they would be if they had been fetched using AJAX). If this flag
 *           is enabled, no additional client-side JavaScript code will be injected and so the
 *           exposed values will still be escaped; e.g. `window.SAILS_LOCALS.funnyFace === '<o_o>'`
 *           (this is useful for customizing client-side unescaping logic)
 *
 *
 * @returns {String} a string of HTML code-- specifically a script tag containing the exposed data.
 */
module.exports = function htmlScriptify(options){

  // Validate usage
  if (!_.isObject(options)) { throw new Error('Usage: A dictionary of options should be provided as the sole argument `htmlScriptify()`'); }
  // Check required properties
  else if (_.isUndefined(options.data)) { throw new Error('Usage: `data` is a required option'); }
  else if (!_.isObject(options.data)) { throw new Error('Usage: `data` should be a dictionary'); }
  // Check optional properties and apply defaults
  if (_.isUndefined(options.keys)) {
    // `options.keys` defaults to `undefined`-- meaning all keys in provided data
    // are permitted; i.e. no whitelist.
  }
  else {
    try { options.keys = rttc.validate(['string'], options.keys); }
    catch (e) {
      if (e.code === 'E_INVALID') { throw new Error('Usage: If provided, `keys` should be an array of strings'); }
      else { throw e; }
    }
  }
  if (_.isUndefined(options.namespace)) { options.namespace = 'SAILS_LOCALS'; }
  else {
    // Note that while we might also consider validating `namespace` as an
    // ecmascript-compatible variable name, in the interest of avoiding any
    // more dependencies here, we do not.
    try { options.namespace = rttc.validate('string', options.namespace); }
    catch (e) {
      if (e.code === 'E_INVALID') { throw new Error('Usage: If provided, `namespace` should be a string'); }
      else { throw e; }
    }
  }
  if (_.isUndefined(options.dontUnescapeOnClient)) { options.dontUnescapeOnClient = false; }
  else {
    try { options.dontUnescapeOnClient = rttc.validate('boolean', options.dontUnescapeOnClient); }
    catch (e) {
      if (e.code === 'E_INVALID') { throw new Error('Usage: If provided, `dontUnescapeOnClient` should be either `true` or `false`'); }
      else { throw e; }
    }
  }

  // console.log('options.data',options.data);
  // console.log('_.keys(options.data)',_.keys(options.data));

  // Build and return HTML to inject.
  var html = '<script type="text/javascript">';
  html += ' (function (){ ';
  // Unless `dontUnescapeOnClient` flag was enabled, don't build the code
  // to do the unescaping. (useful for customizing client-side unescaping logic)
  if (!options.dontUnescapeOnClient) {
    // Inject client-side JavaScript code that will be used to unescape the
    // bootstrapped data.
    //
    // This is kind of like _.unescape().
    // (see https://github.com/lodash/lodash/blob/4.7.0/dist/lodash.js#L14038)
    // Except it also has to be recursive.  But luckily, we don't have to worry
    // about circular references, since we know this was just serialized.
    html += ' var unescape = ' + (function clientSideUnescapeFn(escapedValue){
      var unescapedValue = escapedValue;
      // TODO: actually unescape it
      //
      // This may kind of suck because it needs to be vanilla JS.
      // Not planning on any kind of special backwards-compatible support for older browsers,
      // but if that IS needed, or any other customizations to the client-side escaping code
      // are necessary, then the built-in client-side escaping can be disabled using
      // `dontUnescapeOnClient: true`.
      return unescapedValue;
    }).toString() + '; ';
  }
  html += ' window.'+options.namespace+' = { ';

  // Determine the relevant keys to inject.
  // (filtering using `options.keys` whitelist, if provided)
  var keysToInject = _.keys(options.data);
  if (!_.isUndefined(options.keys)) {
    keysToInject = _.intersection(keysToInject, options.keys);
  }

  // Then inject them in our <script> tag string.
  _.each(keysToInject, function eachRelevantKey(key){
    var unsafeVal = options.data[key];

    // If this top-level key in the provided data is undefined, exclude it altogether.
    if (_.isUndefined(unsafeVal)) { return; }

    // Now, dive into `unsafeVal` and recursively HTML-escape any nested strings
    // and compile the whole thing into a JavaScript string which will accurately
    // represent it as an r-value (watching out for circular refs along the way).
    if (!options.dontUnescapeOnClient) {
      html += ''+key+': unescape('+rttc.compile(escapeHtmlEntitiesDeep(unsafeVal))+'),';
    }
    else {
      html += ''+key+': '+rttc.compile(escapeHtmlEntitiesDeep(unsafeVal))+',';
    }
  });
  html += ' }; ';
  html += ' })(); ';
  html += '</script>';

  return html;

  // ~Example usage:
  // ============================================================
  // xss-test: ∑ sails console
  //
  // info: Starting app in interactive mode...
  //
  // info: Welcome to the Sails console.
  // info: ( to exit, type <CTRL>+<C> )
  //
  // sails> sails.hooks.views.htmlScriptify({data: {3: 'stuff'}, keys: ['4'], namespace: '32', dontUnescapeOnClient: true})
  // '<script type="text/javascript"> (function (){  window.32 = {  };  })(); </script>'
  // sails> sails.hooks.views.htmlScriptify({data: {3: 'stuff'}, keys: ['3'], namespace: '32'})
  // '<script type="text/javascript"> (function (){  var unescape = function (u){\n      // TODO: implement `unescape()`\n      return u;\n    };  window.32 = { 3: unescape(\'stuff\'), };  })(); </script>'
  // sails> sails.hooks.views.htmlScriptify({data: {3: 'stuff'}})
  // '<script type="text/javascript"> (function (){  var unescape = function (u){\n      // TODO: implement `unescape()`\n      // (see https://github.com/lodash/lodash/blob/4.7.0/dist/lodash.js#L14038)\n      return u;\n    };  window.SAILS_LOCALS = { 3: unescape(\'stuff\'), };  })(); </script>'

  // ~Example of end result:
  // ============================================================
  //
  // <script type="text/javascript">
  //   window.SAILS_LOCALS = {
  //     _csrf: (function (escapedValue){
  //       var unescaped = escapedValue;
  //       // Unescape all strings in `escapedValue`.
  //       // (recursively parse escapedValue if it is an array or dictionary)
  //       // (also need to prevent endless circular recursion for circular objects)
  //       return unescaped;
  //     })('d8a831-d8a8381h1-adgadga3'),

  //     me: (function (escapedValue){
  //       var unescaped = escapedValue;
  //       // Unescape all strings in `escapedValue`.
  //       // (recursively parse escapedValue if it is an array or dictionary)
  //       // (also need to prevent endless circular recursion for circular objects)
  //       return unescaped;
  //     })({
  //       gravatarUrl: '</script>',
  //       admin: false
  //     })
  //   };
  // </script>

};


text:
if Rails.configuration.respond_to?("paperclip_defaults")
  Paperclip::Attachment.default_options.merge!(Rails.configuration.paperclip_defaults)
  interpolations = Paperclip::Attachment.default_options.fetch(:interpolations, {})
  interpolations.each do |k, v|
    Paperclip.interpolates k do |attachment, style|
      v
    end
  end
end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Führ. Pilzk. (Zwickau) 112 (1871)

#### Original name
Agaricus psittacinus Schaeff., 1774

### Remarks
null


text:
'use strict'
import { createStore, applyMiddleware } from 'redux'
import reduxLogger from 'redux-logger'
import reduxThunk from 'redux-thunk'

import { isDevEnv } from '../../shared/utils'

import {
  ADD_MOVIE_FILE,
  CRAWL_COMPLETE,
  CRAWL_START,
  MOVIE_FILE_COMPLETE,
  MOVIE_FILE_ERROR
} from './actionTypes'

import addMovieFile from './addMovieFile'
import deleteMovieFile from './deleteMovieFile'
import deleteMovieDatabase from './deleteMovieDatabase'
import updateMovieMetadata from './updateMovieMetadata'
import { sendCrawlComplete } from './electronActions'

// Re-export the electron actions
// ------------------------------
export * from './electronActions'

// Reducer
// -------
const initialState = {
  completeCnt: 0,
  crawling: false,
  crawlDirectory: '',
  error: [],
  inProgress: []
}

const progress = (state = initialState, action) => {
  switch (action.type) {
    case ADD_MOVIE_FILE: {
      return {
        ...state,
        inProgress: [...state.inProgress, action.payload]
      }
    }

    case CRAWL_COMPLETE: {
      return {
        ...state,
        crawling: false
      }
    }

    case CRAWL_START: {
      return {
        ...initialState,
        crawling: true,
        crawlDirectory: action.payload
      }
    }

    case MOVIE_FILE_COMPLETE: {
      return {
        ...state,
        inProgress: state.inProgress.filter(movieFile => movieFile !== action.payload),
        completeCnt: state.completeCnt + 1
      }
    }

    case MOVIE_FILE_ERROR: {
      return {
        ...state,
        inProgress: state.inProgress.filter(
          movieFile => movieFile !== action.payload.movieFile
        ),
        error: [...state.error, action.payload]
      }
    }

    default:
      return state
  }
}

// Export function for creating redux store.
// -----------------------------------------
export const createReduxStore = (useReduxLogger) => {
  // Create the redux store.
  // This is the default export.
  // ---------------------------
  let middlewares = [reduxThunk]
  if (useReduxLogger) {
    middlewares.push(reduxLogger)
  }

  const store = createStore(progress, applyMiddleware(...middlewares))
  return store
}

// This is the actual store used in the background worker.
// -------------------------------------------------------
const store = createReduxStore(isDevEnv())
export default store

// action creators
// ----------------
function crawlStartInternal (rootDirectory) {
  return {
    type: CRAWL_START,
    payload: rootDirectory
  }
}

function crawlCompleteInternal () {
  return {
    type: CRAWL_COMPLETE
  }
}

// Thunked action creators.
// ------------------------
export function crawlCompleteEnhanced (directory) {
  return (dispatch, getState) => {
    dispatch(crawlCompleteInternal())
    if (getState().inProgress.length === 0) {
      sendCrawlComplete(directory)
    }
  }
}

// bound action creators
// ----------------------
export const addMovie = (movieFile, db) => store.dispatch(addMovieFile(movieFile, db))
export const deleteMovie = (movieFile, db) => store.dispatch(deleteMovieFile(movieFile, db))
export const deleteAllMovies = (db) => store.dispatch(deleteMovieDatabase(db))
export const updateMovie = (movie, db) => store.dispatch(updateMovieMetadata(movie, db))
export const crawlStart = (rootDirectory) => store.dispatch(crawlStartInternal(rootDirectory))
export const crawlComplete = (directory) => store.dispatch(crawlCompleteEnhanced(directory))


text:
module Jekyll
  class LinkSampleBlock < Liquid::Block
    def initialize(tag_name, markup, tokens)
      super
      @file = markup
    end

    def render(context)
        page = context.environments.first["page"]
        path = context.registers[:site].source;
        String filepath = File.join(File.dirname(page["path"]), @file).sub("/_code", "")
        url = File.join(context.registers[:site].baseurl, "/resources/samples", filepath).strip
        out = super(context)
        "#{out}"
    end
  end

  class IncludeCodeTag < Liquid::Tag
    include Liquid::StandardFilters

    # This is the base domain we will link to for samples.
    @@sample_link_base = "https://google-developers.appspot.com/"
    @@comment_formats = {
      "html" => [""],
      "css" => ["\\\/\\\*", "\\\*\\\/"],
      "javascript" => ["\\\/\\\*", "\\\*\\\/"],
    }

    def initialize(tag_name, markup, tokens)
      super
      @options = {}
      @file, @section, @lang = markup.strip.split(' ', 3)
      if @lang.nil?
        @lang = "html"
      end
      if @@comment_formats[@lang].nil?
        Jekyll.logger.warn "Include_code doesn't know #{@lang}"
      end
      @character = '/'
    end

    def getmatcher_tag(lang, section, tag)
      startc, endc = @@comment_formats[lang]
      "#{startc} \\/\\/ \\[#{tag} #{section}\\] #{endc}\n?"
    end

    def getmatch(contents, lang, section)
      start = getmatcher_tag(lang, section, "START")
      endt = getmatcher_tag(lang, section, "END")
      contents.match(/#{start}(.*)#{endt}/im)[1]
    end

    def render(context)
        page = context.environments.first["page"]
        path = context.registers[:site].source;
        String filepath = File.join(File.dirname(page["path"]), @file)
        String file = File.join(path, filepath)
        contents = File.read(file)
        snippet = getmatch(contents, @lang, @section)
        @@comment_formats.each do |lang, parms|
            match = getmatcher_tag(lang, "[^\\]]+", "\\w+")
            snippet.gsub!(/#{match}/mi, "")
        end
        render_codehighlighter(context, snippet, filepath)
    end

    def render_codehighlighter(context, code, filepath)
      require 'pygments'

      # TODO(ianbarber): This is a bit of a fudge. We should know the definitive sample
      # path. I think we may want to have a central shared "code sample" object that is
      # knows how to get such paths for this and the sample_builder.
      filepath.sub!("_code/", "")
      offset = false
      snippet = ""
      initial = code.lines.first[/\A */].size

      # Indenter
      # TODO(ianbarber): Look for multiples of original offset rather than absolute spaces.
      # paulk edit: updated logic.  gets first line, works out indent. then uses that as initial offset
      code.each_line {|s|

        #Jekyll.logger.warn " #{initial} #{offset} #{(initial + offset)} #{s.lstrip.rstrip}"
        if s.size >= initial
          snippet += (" " * 4)
          snippet += s.slice(initial..s.size).rstrip
        end
        snippet += "\n"
      }

      @options[:encoding] = 'utf-8'
      highlighted_code = Pygments.highlight(snippet, :lexer => @lang, :options => @options)
      if highlighted_code.nil?
          Jekyll.logger.error "There was an error highlighting your code."
      end

      if @lang == 'css'
        @character = '}'
      end

      <<-HTML

      #{highlighted_code.strip}
      查看完整示例

        HTML
      end
  end
end

Liquid::Template.register_tag('include_code', Jekyll::IncludeCodeTag)
Liquid::Template.register_tag('link_sample', Jekyll::LinkSampleBlock)


text:
This inspection reports any clases which extend java.lang.Thread.
It is usually thought better practice to delegate to rather than extend
java.lang.Thread, so that a thread creator may exert better
control over the thread's behavior, and to better localize all concurrency related operations.

  Powered by InspectionGadgets


text:
cask "clion" do
  version "2020.2.1,202.6948.80"
  sha256 "5560c3cb2feb72eafa94f2caef663af079ae83274d664365d524e322a526a699"

  url "https://download.jetbrains.com/cpp/CLion-#{version.before_comma}.dmg"
  appcast "https://data.services.jetbrains.com/products/releases?code=CL&latest=true&type=release"
  name "CLion"
  homepage "https://www.jetbrains.com/clion/"

  auto_updates true

  app "CLion.app"

  uninstall_postflight do
    ENV["PATH"].split(File::PATH_SEPARATOR).map { |path| File.join(path, "clion") }.each do |path|
      if File.exist?(path) &&
         File.readlines(path).grep(/# see com.intellij.idea.SocketLock for the server side of this interface/).any?
        File.delete(path)
      end
    end
  end

  zap trash: [
    "~/Library/Application Support/CLion#{version.major_minor}",
    "~/Library/Caches/CLion#{version.major_minor}",
    "~/Library/Logs/CLion#{version.major_minor}",
    "~/Library/Preferences/CLion#{version.major_minor}",
  ]
end