text:
namespace chromeos {
namespace multidevice {

// WebUIMessageHandler for chrome://multidevice-internals PhoneHub section.
class MultidevicePhoneHubHandler
    : public content::WebUIMessageHandler,
      public phonehub::NotificationManager::Observer,
      public phonehub::DoNotDisturbController::Observer,
      public phonehub::FindMyDeviceController::Observer,
      public phonehub::TetherController::Observer,
      public phonehub::OnboardingUiTracker::Observer,
      public ash::phonehub::CameraRollManager::Observer {
 public:
  MultidevicePhoneHubHandler();
  MultidevicePhoneHubHandler(const MultidevicePhoneHubHandler&) = delete;
  MultidevicePhoneHubHandler& operator=(const MultidevicePhoneHubHandler&) =
      delete;
  ~MultidevicePhoneHubHandler() override;

  // content::WebUIMessageHandler:
  void RegisterMessages() override;
  void OnJavascriptAllowed() override {}
  void OnJavascriptDisallowed() override;

 private:
  // NotificationManager::Observer
  void OnNotificationsRemoved(
      const base::flat_set<int64_t>& notification_ids) override;

  // DoNotDisturbController::Observer
  void OnDndStateChanged() override;

  // FindMyDeviceController::Observer
  void OnPhoneRingingStateChanged() override;

  // TetherController::Observer
  void OnTetherStatusChanged() override;

  // OnboardingUiTracker::Observer
  void OnShouldShowOnboardingUiChanged() override;

  // CameraRollManager::Observer:
  void OnCameraRollViewUiStateUpdated() override;

  void EnableRealPhoneHubManager();
  void EnableFakePhoneHubManager();
  void HandleEnableFakePhoneHubManager(const base::ListValue* args);
  void HandleSetFeatureStatus(const base::ListValue* args);
  void HandleSetShowOnboardingFlow(const base::ListValue* args);
  void HandleSetFakePhoneName(const base::ListValue* args);
  void HandleSetFakePhoneStatus(const base::ListValue* args);
  void HandleSetBrowserTabs(const base::ListValue* args);
  void HandleSetNotification(const base::ListValue* args);
  void HandleRemoveNotification(const base::ListValue* args);
  void HandleEnableDnd(const base::ListValue* args);
  void HandleSetFindMyDeviceStatus(const base::ListValue* args);
  void HandleSetTetherStatus(const base::ListValue* args);
  void HandleResetShouldShowOnboardingUi(const base::ListValue* args);
  void HandleResetHasMultideviceFeatureSetupUiBeenDismissed(
      const base::ListValue* args);
  void HandleSetFakeCameraRoll(const base::ListValue* args);

  void AddObservers();
  void RemoveObservers();

  std::unique_ptr<phonehub::FakePhoneHubManager> fake_phone_hub_manager_;
  base::ScopedObservation<phonehub::NotificationManager,
                          phonehub::NotificationManager::Observer>
      notification_manager_observation_{this};
  base::ScopedObservation<phonehub::DoNotDisturbController,
                          phonehub::DoNotDisturbController::Observer>
      do_not_disturb_controller_observation_{this};
  base::ScopedObservation<phonehub::FindMyDeviceController,
                          phonehub::FindMyDeviceController::Observer>
      find_my_device_controller_observation_{this};
  base::ScopedObservation<phonehub::TetherController,
                          phonehub::TetherController::Observer>
      tether_controller_observation_{this};
  base::ScopedObservation<phonehub::OnboardingUiTracker,
                          phonehub::OnboardingUiTracker::Observer>
      onboarding_ui_tracker_observation_{this};
  base::ScopedObservation<ash::phonehub::CameraRollManager,
                          ash::phonehub::CameraRollManager::Observer>
      camera_roll_manager_observation_{this};
};

}  // namespace multidevice
}  // namespace chromeos

#endif  // CHROME_BROWSER_UI_WEBUI_CHROMEOS_MULTIDEVICE_INTERNALS_MULTIDEVICE_INTERNALS_PHONE_HUB_HANDLER_H_


text:
import React, { PropTypes } from 'react'
import Text from '../Text'
import FlexView from '../FlexView'

const labeled = (DecoratedComponent) => {
  function Labeled({ labelElement, labelStyle, direction, ...props }) {
    return (
      <FlexView direction={direction}>

        <DecoratedComponent {...props} />
      </FlexView>)
  }

  Labeled.propTypes = {
    label: PropTypes.node,
    labelStyle: PropTypes.object,
    direction: PropTypes.oneOf(['vertical', 'horizontal']),
    labelElement: PropTypes.element,
  }

  Labeled.defaultProps = {
    labelElement: Text,
  }
}

export default labeled

redpajama_set_name: RedPajamaGithub


text:
<?php

add_action( 'widgets_init', 'widget_init_most_popular_article' );

function widget_init_most_popular_article() {
	register_widget( 'MostPopularArticle_Widget' );
}

class MostPopularArticle_Widget extends WP_Widget {

	function MostPopularArticle_Widget() {
		$widget_ops = array( 'classname' => 'most-popular-article', 'description' => __('Most Popular Article', 'most-popular-article') );

		$control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'most-popular-article-widget' );

		$this->WP_Widget( 'most-popular-article-widget', __('Most Popular Article', 'most-popular-article'), $widget_ops, $control_ops );
	}

	function widget( $args, $instance ) {
            extract( $args );
            $title = apply_filters('widget_title', $instance['title'] );
        ?>
        <?php
            query_posts(array(
                'posts_per_page' => 5,
                'paged'          => 1,
                'post_type'      => "article",
                "meta_key"       => "post_views_count",
                "orderby"        => "meta_value_num",
                "order"          => "DESC"
            ));
        ?>
        <?php if ( have_posts() ) : ?>

Most Popular Articles

                    <?php while ( have_posts() ) : the_post(); ?>

                            <a href="<?php the_permalink();?>"><?php the_title();?>

                    <?php endwhile;?>

        <?php endif;?>
        <?php
	}

	//Update the widget

	function update( $new_instance, $old_instance ) {
            $instance = $old_instance;
            $instance['title'] = strip_tags( $new_instance['title'] );
            return $instance;
	}

	function form( $instance ) {
            $defaults = array( 'title' => '');
            $instance = wp_parse_args( (array) $instance, $defaults ); ?>

	<?php
	}
}
?>


text:
-- ==================================================================
-- Author:		Stephen Quin
-- Create date: 03/07/2011
-- Description:	Gets the linked order info for the supplied orderRef
-- ==================================================================
CREATE PROCEDURE [dbo].[h3giGetLinkedOrderInfo]
	@orderRef INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	DECLARE @linkedOrderRef INT

    --1. Get the Linked Order id
    SELECT @linkedOrderRef = linkedOrderRef
    FROM h3giLinkedOrders
    WHERE orderRef = @orderRef

    SELECT @linkedOrderRef

    --2. Get the order details for the orders associated with that linked order Ref
    SELECT	link2.orderRef,
		h3gi.orderType,
		b4n.Status,
		device.productName AS device,
		ISNULL(pack.pricePlanPackageName,'') AS tariff,
		ISNULL(pack.contractLengthMonths,'') AS contractLength,
		h3gi.tariffRecurringPrice AS tariffCost,
		ISNULL(SUBSTRING((SELECT (', ' + line.itemName)
						 FROM b4nOrderLine line
						 INNER JOIN h3giOrderheader h3gi
							ON line.orderRef = h3gi.orderRef
						 INNER JOIN h3giProductCatalogue cat
							ON line.productId = cat.catalogueProductId
							AND cat.catalogueVersionId = h3gi.catalogueVersionId
						 INNER JOIN h3giLinkedOrders link1
							ON line.orderRef = link1.orderRef
						 WHERE  link1.linkedOrderRef = @linkedOrderRef
								AND cat.productType = 'ADDON'
								AND link1.orderRef = link2.orderRef
						 FOR XML PATH( '' )), 3, 1000), '') AS addOns
FROM	h3giLinkedOrders link2
	INNER JOIN b4nOrderHeader b4n
		ON link2.orderRef = b4n.OrderRef
	INNER JOIN h3giOrderheader h3gi
		ON link2.orderRef = h3gi.orderref
	INNER JOIN h3giProductCatalogue device
		ON h3gi.phoneProductCode = device.productFamilyId
		AND h3gi.catalogueVersionID = device.catalogueVersionID
	LEFT OUTER JOIN h3giPricePlanPackage pack
		ON h3gi.pricePlanPackageID = pack.pricePlanPackageID
		AND h3gi.catalogueVersionID = pack.catalogueVersionID
WHERE	link2.linkedOrderRef = @linkedOrderRef
AND		link2.orderRef <> @orderRef
GROUP BY link2.orderRef, h3gi.orderType, b4n.Status, device.productName, pack.pricePlanPackageName, pack.contractLengthMonths, h3gi.tariffRecurringPrice

END

GRANT EXECUTE ON h3giGetLinkedOrderInfo TO b4nuser
GO


text:
import { HttpModule } from '@angular/http';
import { TestBed, inject } from '@angular/core/testing';

import { AuthenticationService } from './authentication.service';

describe('AuthenticationService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [AuthenticationService],
      imports: [HttpModule]
    });
  });

  it('should be created', inject([AuthenticationService], (service: AuthenticationService) => {
    expect(service).toBeTruthy();
  }));
});


text:
package com.seleniumtests.it.util;

import org.openqa.selenium.Dimension;
import org.testng.Assert;
import org.testng.annotations.Test;

import com.seleniumtests.GenericDriverTest;
import com.seleniumtests.core.SeleniumTestsContextManager;
import com.seleniumtests.core.TestStepManager;
import com.seleniumtests.driver.CustomEventFiringWebDriver;
import com.seleniumtests.driver.WebUIDriver;
import com.seleniumtests.it.driver.support.pages.DriverTestPage;

public class TestPageObject extends GenericDriverTest {

	@Test(groups={"it"})
	public void testResizeWindow() throws Exception {
		SeleniumTestsContextManager.getThreadContext().setBrowser("*firefox");
		driver = WebUIDriver.getWebDriver(true);
		new DriverTestPage(true).resizeTo(600, 400);
		Dimension viewPortSize = ((CustomEventFiringWebDriver)driver).getViewPortDimensionWithoutScrollbar();
		Assert.assertEquals(viewPortSize.width, 600);
		Assert.assertEquals(viewPortSize.height, 400);
	}

	/**
	 * issue #421: check snapshot is not done when user set captureSnapshot=false
	 * @throws Exception
	 */
	@Test(groups={"it"})
	public void testSnapshotNotLogged() throws Exception {
		SeleniumTestsContextManager.getThreadContext().setBrowser("*firefox");
		SeleniumTestsContextManager.getThreadContext().setCaptureSnapshot(false);
		driver = WebUIDriver.getWebDriver(true);
		new DriverTestPage(true);

		// 0 capture because capture snapshot is set to false
		Assert.assertTrue(TestStepManager.getCurrentOrPreviousStep().getAllAttachments(true).isEmpty());

	}
	@Test(groups={"it"})
	public void testSnapshotLogged() throws Exception {
		SeleniumTestsContextManager.getThreadContext().setBrowser("*firefox");
		SeleniumTestsContextManager.getThreadContext().setCaptureSnapshot(true);
		driver = WebUIDriver.getWebDriver(true);
		new DriverTestPage(true);

		// one capture, due to opening page
		Assert.assertFalse(TestStepManager.getCurrentOrPreviousStep().getAllAttachments(true).isEmpty());
		Assert.assertEquals(TestStepManager.getCurrentOrPreviousStep().getAllAttachments(true).size(), 1);

	}

	@Test(groups={"it"})
	public void testResizeWindowHeadless() throws Exception {
		SeleniumTestsContextManager.getThreadContext().setBrowser("*htmlunit");
		driver = WebUIDriver.getWebDriver(true);
		new DriverTestPage(true);
		new DriverTestPage(true).resizeTo(600, 400);
		Dimension viewPortSize = ((CustomEventFiringWebDriver)driver).getViewPortDimensionWithoutScrollbar();
		Assert.assertEquals(viewPortSize.width, 600);
		Assert.assertEquals(viewPortSize.height, 400);
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>ActionController::Testing::ClassMethods</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/github.css" type="text/css" media="screen" />

            Ruby on Rails 4.1.8

            Module
            ActionController::Testing::ClassMethods

/home/kristof/.rvm/gems/ruby-2.2.0/gems/actionpack-4.1.8/lib/action_controller/metal/testing.rb

Methods

B

                before_filters

Instance Public methods

              before_filters()

            Link

                Source:
                show

# File ../.rvm/gems/ruby-2.2.0/gems/actionpack-4.1.8/lib/action_controller/metal/testing.rb, line 26
def before_filters
  _process_action_callbacks.find_all{|x| x.kind == :before}.map{|x| x.name}
end


text:
<?php

/* REMOVE - Admin Bar CSS
-------------------------------------------------- */
function remove_admin_login_header() {
	remove_action('wp_head', '_admin_bar_bump_cb');
}
add_action('get_header', 'remove_admin_login_header');

/* REMOVE - Meta Head Tags
-------------------------------------------------- */
remove_action('wp_head', 'rsd_link'); // Weblog Client Link
remove_action('wp_head', 'wlwmanifest_link'); // Windows Live Writer Manifest Link
remove_action('wp_head', 'wp_shortlink_wp_head'); // WordPress Page/Post Shortlinks
remove_action('wp_head', 'print_emoji_detection_script', 7 ); // WordPress Emojis
remove_action('wp_print_styles', 'print_emoji_styles' ); // WordPress Emojis
remove_action('wp_head', 'wp_generator'); // WordPress Generator
add_filter('the_generator', function() { return ''; }); // WordPress Generator

/* Add Theme CSS to WP Content Editor
-------------------------------------------------- */
add_action( 'admin_init', function() {
  add_editor_style( get_template_directory_uri() . '/library/styles/main.css' );
});

remove_filter( 'the_content', 'wpautop' ); // Disable <p> tags auto adding in Editor


text:
package org.pinae.ndb.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

/**
 * ndbd读取
 *
 * 将ndb读取并解析为Map类型
 *
 * @author Huiyugeng
 *
 *
 */
public class NodeReader {

	private int linenum = 0; // 配置行号

	/**
	 * 载入文本文件
	 *
	 * @param filename 文件名
	 *
	 * @return 文件内容
	 *
	 * @throws IOException IO异常处理
	 */
	public List<String> readAsList(String filename) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader(filename));
		return readAsList(br);
	}

	/**
	 * 载入文本文件
	 *
	 * @param file 文件名
	 *
	 * @return 文件内容
	 *
	 * @throws IOException IO异常处理
	 */
	public List<String> readAsList(File file) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader(file));
		return readAsList(br);
	}

	private List<String> readAsList(BufferedReader br) throws IOException {
		List<String> content = new ArrayList<String>();
		if (br != null) {
			String line = "";
			while ((line = br.readLine()) != null) {
				content.add(line);
			}
			br.close();
		}
		return content;
	}

	/**
	 * 载入解析ndb文件内容
	 *
	 * @param filename 文件名
	 *
	 * @return 解析后的ndb信息
	 *
	 * @throws IOException IO异常处理
	 */
	public Map<String, Object> read(String filename) throws IOException {
		List<String> content = readAsList(filename);
		Map<String, Object> ndb = parse(content);
		return ndb;
	}

	/**
	 * 载入解析ndb文件内容
	 *
	 * @param file 文件对象
	 *
	 * @return 解析后的ndb信息
	 *
	 * @throws IOException IO异常处理
	 */
	public Map<String, Object> read(File file) throws IOException {
		List<String> content = readAsList(file);
		Map<String, Object> ndb = parse(content);
		return ndb;
	}

	/*
	 * 解析为Map
	 *
	 * @param fileContentList 文件内容列表
	 *
	 * @return 解析后的Map
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private Map<String, Object> parse(List<String> fileContentList) {
		Map<String, Object> ndb = new HashMap<String, Object>();

		while (linenum < fileContentList.size()) {
			try {
				String line = fileContentList.get(linenum).trim();

				linenum++;

				if (line == null || line.equals("") || StringUtils.startsWith(line, "#")) {
					continue;
				}

				if (line.endsWith("{")) {
					String nodeName = line.substring(0, line.indexOf("{")).trim();
					Map<String, Object> nodeValue = parse(fileContentList);

					Object node = ndb.get(nodeName);
					if (node == null) {
						ndb.put(nodeName, nodeValue);
					} else {
						List nodeList = null;
						if (node instanceof List) {
							nodeList = (List) node;
						} else {
							nodeList = new ArrayList();
							nodeList.add(node);
						}
						nodeList.add(nodeValue);
						ndb.put(nodeName, nodeList);
					}

				} else if (line.endsWith("}")) {
					return ndb;
				} else {
					if (line.indexOf(":") > 0) {
						String items[] = new String[2];

						items[0] = line.substring(0, line.indexOf(":")).trim();
						items[1] = line.substring(line.indexOf(":") + 1, line.length()).trim();

						Object itemValue = ndb.get(items[0]);
						if (itemValue != null) {
							List itemValueList = null;
							if (itemValue instanceof List) {
								itemValueList = (List) itemValue;
							} else {
								itemValueList = new ArrayList();
								itemValueList.add(itemValue);
							}
							itemValueList.add(items[1]);

							ndb.put(items[0], itemValueList);
						} else {
							ndb.put(items[0], items[1]);
						}
					}
				}
			} catch (Exception e) {

			}
		}
		return ndb;
	}
}


text:
void PauseMenuUiController::onNewGameButtonSelected(Game &game)
{
	game.setGameState(nullptr);
	game.setPanel<MainMenuPanel>();

	const MusicLibrary &musicLibrary = game.getMusicLibrary();
	const MusicDefinition *musicDef = musicLibrary.getRandomMusicDefinition(
		MusicDefinition::Type::MainMenu, game.getRandom());

	if (musicDef == nullptr)
	{
		DebugLogWarning("Missing main menu music.");
	}

	AudioManager &audioManager = game.getAudioManager();
	audioManager.setMusic(musicDef);
}

void PauseMenuUiController::onLoadButtonSelected(Game &game)
{
	game.setPanel<LoadSavePanel>(LoadSavePanel::Type::Load);
}

void PauseMenuUiController::onSaveButtonSelected(Game &game)
{
	// @todo

	// SaveGamePanel...
	//auto optionsPanel = std::make_unique<OptionsPanel>(game);
	//game.setPanel(std::move(optionsPanel));
}

void PauseMenuUiController::onExitButtonSelected(Game &game)
{
	SDL_Event evt;
	evt.quit.type = SDL_QUIT;
	evt.quit.timestamp = 0;
	SDL_PushEvent(&evt);
}

void PauseMenuUiController::onResumeButtonSelected(Game &game)
{
	game.setPanel<GameWorldPanel>();
}

void PauseMenuUiController::onOptionsButtonSelected(Game &game)
{
	game.setPanel<OptionsPanel>();
}

void PauseMenuUiController::onSoundUpButtonSelected(Game &game, PauseMenuPanel &panel)
{
	auto &options = game.getOptions();
	options.setAudio_SoundVolume(std::min(options.getAudio_SoundVolume() + 0.050, 1.0));

	auto &audioManager = game.getAudioManager();
	audioManager.setSoundVolume(options.getAudio_SoundVolume());
	panel.updateSoundText(options.getAudio_SoundVolume());
}

void PauseMenuUiController::onSoundDownButtonSelected(Game &game, PauseMenuPanel &panel)
{
	auto &options = game.getOptions();
	const double newVolume = [&options]()
	{
		const double volume = std::max(options.getAudio_SoundVolume() - 0.050, 0.0);

		// Clamp very small values to zero to avoid precision issues with tiny numbers.
		return volume < Constants::Epsilon ? 0.0 : volume;
	}();

	options.setAudio_SoundVolume(newVolume);

	auto &audioManager = game.getAudioManager();
	audioManager.setSoundVolume(options.getAudio_SoundVolume());
	panel.updateSoundText(options.getAudio_SoundVolume());
}

void PauseMenuUiController::onMusicUpButtonSelected(Game &game, PauseMenuPanel &panel)
{
	auto &options = game.getOptions();
	options.setAudio_MusicVolume(std::min(options.getAudio_MusicVolume() + 0.050, 1.0));

	auto &audioManager = game.getAudioManager();
	audioManager.setMusicVolume(options.getAudio_MusicVolume());
	panel.updateMusicText(options.getAudio_MusicVolume());
}

void PauseMenuUiController::onMusicDownButtonSelected(Game &game, PauseMenuPanel &panel)
{
	auto &options = game.getOptions();
	const double newVolume = [&options]()
	{
		const double volume = std::max(options.getAudio_MusicVolume() - 0.050, 0.0);

		// Clamp very small values to zero to avoid precision issues with tiny numbers.
		return volume < Constants::Epsilon ? 0.0 : volume;
	}();

	options.setAudio_MusicVolume(newVolume);

	auto &audioManager = game.getAudioManager();
	audioManager.setMusicVolume(options.getAudio_MusicVolume());
	panel.updateMusicText(options.getAudio_MusicVolume());
}


text:
.hidden {
	display: block;
}


text:
namespace data_reduction_proxy {
class DataUsageBucket;
}

namespace extensions {

class DataReductionProxyClearDataSavingsFunction : public ExtensionFunction {
 private:
  ~DataReductionProxyClearDataSavingsFunction() override {}

  DECLARE_EXTENSION_FUNCTION("dataReductionProxy.clearDataSavings",
                             DATAREDUCTIONPROXY_CLEARDATASAVINGS)

  ResponseAction Run() override;
};

class DataReductionProxyGetDataUsageFunction : public ExtensionFunction {
 private:
  ~DataReductionProxyGetDataUsageFunction() override {}

  DECLARE_EXTENSION_FUNCTION("dataReductionProxy.getDataUsage",
                             DATAREDUCTIONPROXY_GETDATAUSAGE)

  ResponseAction Run() override;

  void ReplyWithDataUsage(
      std::unique_ptr<std::vector<data_reduction_proxy::DataUsageBucket>>
          data_usage);
};

}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_API_DATA_REDUCTION_PROXY_DATA_REDUCTION_PROXY_API_H_


text:
Spotify Web API Start Template
===========

This is a template for a project using the Spotify Web API.

## Features

The template includes:

- **Bootstrap**. It uses Twitter Bootstrap to provide default styling.
- **Implementation for [Spotify Web API OAuth 2.0 Implicit Grant](https://developer.spotify.com/web-api/authorization-guide/#implicit_grant_flow) flow**. This is the simplest authentication flow, and works for webapps that want a user to log in and don't need to remember the authentication for a long time. Examples are webapps that want to access user's Your Music (saved tracks) or manipulate user's playlists. The login form is opened in a popup.
- **Wrapper for Spotify Web API in JavaScript**. Though not strictly necessary, it makes it easier to use the Web API. You can have a look at the [documentation](http://jmperezperez.com/spotify-web-api-js/) to have an overview of the available functions, which cover all the Web API endpoints.
- **Knockout.js** as the binding library. This is the _de facto_ library used in lots of Spotify spotlets, and it removes the necessity of manipulating DOM, even in projects such as this basic template.

## Usage

All the dependencies are included in the project, as well as basic credentials for using authentication with the Spotify Web API.

Just start a server listening on port 8000. If you have python installed, you can run:

    python -m SimpleHTTPServer 8000

If you want to deploy the project on a site different from `http://localhost:8000` you will need to register your own Application on the [My Applications section of the Developer Site](https://developer.spotify.com/my-applications/). Register the desired redirect uri and edit the file `js/oauth-config.js` replacing the `clientId` and `redirectUri`.


text:
import numpy as np
import matplotlib.pyplot as plt
import h5py

def sigmoid(Z):
    """
    Implements the sigmoid activation in numpy

    Arguments:
    Z -- numpy array of any shape

    Returns:
    A -- output of sigmoid(z), same shape as Z
    cache -- returns Z as well, useful during backpropagation
    """

    A = 1/(1+np.exp(-Z))
    cache = Z

    return A, cache

def relu(Z):
    """
    Implement the RELU function.

    Arguments:
    Z -- Output of the linear layer, of any shape

    Returns:
    A -- Post-activation parameter, of the same shape as Z
    cache -- a python dictionary containing "A" ; stored for computing the backward pass efficiently
    """

    A = np.maximum(0,Z)

    assert(A.shape == Z.shape)

    cache = Z
    return A, cache

def relu_backward(dA, cache):
    """
    Implement the backward propagation for a single RELU unit.

    Arguments:
    dA -- post-activation gradient, of any shape
    cache -- 'Z' where we store for computing backward propagation efficiently

    Returns:
    dZ -- Gradient of the cost with respect to Z
    """

    Z = cache
    dZ = np.array(dA, copy=True) # just converting dz to a correct object.

    # When z <= 0, you should set dz to 0 as well.
    dZ[Z <= 0] = 0

    assert (dZ.shape == Z.shape)

    return dZ

def sigmoid_backward(dA, cache):
    """
    Implement the backward propagation for a single SIGMOID unit.

    Arguments:
    dA -- post-activation gradient, of any shape
    cache -- 'Z' where we store for computing backward propagation efficiently

    Returns:
    dZ -- Gradient of the cost with respect to Z
    """

    Z = cache

    s = 1/(1+np.exp(-Z))
    dZ = dA * s * (1-s)

    assert (dZ.shape == Z.shape)

    return dZ

def load_data():
    train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r")
    train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features
    train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labels

    test_dataset = h5py.File('datasets/test_catvnoncat.h5', "r")
    test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set features
    test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labels

    classes = np.array(test_dataset["list_classes"][:]) # the list of classes

    train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))
    test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))

    return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes

def initialize_parameters(n_x, n_h, n_y):
    """
    Argument:
    n_x -- size of the input layer
    n_h -- size of the hidden layer
    n_y -- size of the output layer

    Returns:
    parameters -- python dictionary containing your parameters:
                    W1 -- weight matrix of shape (n_h, n_x)
                    b1 -- bias vector of shape (n_h, 1)
                    W2 -- weight matrix of shape (n_y, n_h)
                    b2 -- bias vector of shape (n_y, 1)
    """

    np.random.seed(1)

    W1 = np.random.randn(n_h, n_x)*0.01
    b1 = np.zeros((n_h, 1))
    W2 = np.random.randn(n_y, n_h)*0.01
    b2 = np.zeros((n_y, 1))

    assert(W1.shape == (n_h, n_x))
    assert(b1.shape == (n_h, 1))
    assert(W2.shape == (n_y, n_h))
    assert(b2.shape == (n_y, 1))

    parameters = {"W1": W1,
                  "b1": b1,
                  "W2": W2,
                  "b2": b2}

    return parameters

def initialize_parameters_deep(layer_dims):
    """
    Arguments:
    layer_dims -- python array (list) containing the dimensions of each layer in our network

    Returns:
    parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
                    Wl -- weight matrix of shape (layer_dims[l], layer_dims[l-1])
                    bl -- bias vector of shape (layer_dims[l], 1)
    """

    np.random.seed(1)
    parameters = {}
    L = len(layer_dims)            # number of layers in the network

    for l in range(1, L):
        parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1]) / np.sqrt(layer_dims[l-1]) #*0.01
        parameters['b' + str(l)] = np.zeros((layer_dims[l], 1))

        assert(parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l-1]))
        assert(parameters['b' + str(l)].shape == (layer_dims[l], 1))

    return parameters

def linear_forward(A, W, b):
    """
    Implement the linear part of a layer's forward propagation.

    Arguments:
    A -- activations from previous layer (or input data): (size of previous layer, number of examples)
    W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)
    b -- bias vector, numpy array of shape (size of the current layer, 1)

    Returns:
    Z -- the input of the activation function, also called pre-activation parameter
    cache -- a python dictionary containing "A", "W" and "b" ; stored for computing the backward pass efficiently
    """

    Z = W.dot(A) + b

    assert(Z.shape == (W.shape[0], A.shape[1]))
    cache = (A, W, b)

    return Z, cache

def linear_activation_forward(A_prev, W, b, activation):
    """
    Implement the forward propagation for the LINEAR->ACTIVATION layer

    Arguments:
    A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples)
    W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)
    b -- bias vector, numpy array of shape (size of the current layer, 1)
    activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu"

    Returns:
    A -- the output of the activation function, also called the post-activation value
    cache -- a python dictionary containing "linear_cache" and "activation_cache";
             stored for computing the backward pass efficiently
    """

    if activation == "sigmoid":
        # Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
        Z, linear_cache = linear_forward(A_prev, W, b)
        A, activation_cache = sigmoid(Z)

    elif activation == "relu":
        # Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
        Z, linear_cache = linear_forward(A_prev, W, b)
        A, activation_cache = relu(Z)

    assert (A.shape == (W.shape[0], A_prev.shape[1]))
    cache = (linear_cache, activation_cache)

    return A, cache

def L_model_forward(X, parameters):
    """
    Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation

    Arguments:
    X -- data, numpy array of shape (input size, number of examples)
    parameters -- output of initialize_parameters_deep()

    Returns:
    AL -- last post-activation value
    caches -- list of caches containing:
                every cache of linear_relu_forward() (there are L-1 of them, indexed from 0 to L-2)
                the cache of linear_sigmoid_forward() (there is one, indexed L-1)
    """

    caches = []
    A = X
    L = len(parameters) // 2                  # number of layers in the neural network

    # Implement [LINEAR -> RELU]*(L-1). Add "cache" to the "caches" list.
    for l in range(1, L):
        A_prev = A
        A, cache = linear_activation_forward(A_prev, parameters['W' + str(l)], parameters['b' + str(l)], activation = "relu")
        caches.append(cache)

    # Implement LINEAR -> SIGMOID. Add "cache" to the "caches" list.
    AL, cache = linear_activation_forward(A, parameters['W' + str(L)], parameters['b' + str(L)], activation = "sigmoid")
    caches.append(cache)

    assert(AL.shape == (1,X.shape[1]))

    return AL, caches

def compute_cost(AL, Y):
    """
    Implement the cost function defined by equation (7).

    Arguments:
    AL -- probability vector corresponding to your label predictions, shape (1, number of examples)
    Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples)

    Returns:
    cost -- cross-entropy cost
    """

    m = Y.shape[1]

    # Compute loss from aL and y.
    cost = (1./m) * (-np.dot(Y,np.log(AL).T) - np.dot(1-Y, np.log(1-AL).T))

    cost = np.squeeze(cost)      # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17).
    assert(cost.shape == ())

    return cost

def linear_backward(dZ, cache):
    """
    Implement the linear portion of backward propagation for a single layer (layer l)

    Arguments:
    dZ -- Gradient of the cost with respect to the linear output (of current layer l)
    cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer

    Returns:
    dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev
    dW -- Gradient of the cost with respect to W (current layer l), same shape as W
    db -- Gradient of the cost with respect to b (current layer l), same shape as b
    """
    A_prev, W, b = cache
    m = A_prev.shape[1]

    dW = 1./m * np.dot(dZ,A_prev.T)
    db = 1./m * np.sum(dZ, axis = 1, keepdims = True)
    dA_prev = np.dot(W.T,dZ)

    assert (dA_prev.shape == A_prev.shape)
    assert (dW.shape == W.shape)
    assert (db.shape == b.shape)

    return dA_prev, dW, db

def linear_activation_backward(dA, cache, activation):
    """
    Implement the backward propagation for the LINEAR->ACTIVATION layer.

    Arguments:
    dA -- post-activation gradient for current layer l
    cache -- tuple of values (linear_cache, activation_cache) we store for computing backward propagation efficiently
    activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu"

    Returns:
    dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev
    dW -- Gradient of the cost with respect to W (current layer l), same shape as W
    db -- Gradient of the cost with respect to b (current layer l), same shape as b
    """
    linear_cache, activation_cache = cache

    if activation == "relu":
        dZ = relu_backward(dA, activation_cache)
        dA_prev, dW, db = linear_backward(dZ, linear_cache)

    elif activation == "sigmoid":
        dZ = sigmoid_backward(dA, activation_cache)
        dA_prev, dW, db = linear_backward(dZ, linear_cache)

    return dA_prev, dW, db

def L_model_backward(AL, Y, caches):
    """
    Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group

    Arguments:
    AL -- probability vector, output of the forward propagation (L_model_forward())
    Y -- true "label" vector (containing 0 if non-cat, 1 if cat)
    caches -- list of caches containing:
                every cache of linear_activation_forward() with "relu" (there are (L-1) or them, indexes from 0 to L-2)
                the cache of linear_activation_forward() with "sigmoid" (there is one, index L-1)

    Returns:
    grads -- A dictionary with the gradients
             grads["dA" + str(l)] = ...
             grads["dW" + str(l)] = ...
             grads["db" + str(l)] = ...
    """
    grads = {}
    L = len(caches) # the number of layers
    m = AL.shape[1]
    Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL

    # Initializing the backpropagation
    dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))

    # Lth layer (SIGMOID -> LINEAR) gradients. Inputs: "AL, Y, caches". Outputs: "grads["dAL"], grads["dWL"], grads["dbL"]
    current_cache = caches[L-1]
    grads["dA" + str(L)], grads["dW" + str(L)], grads["db" + str(L)] = linear_activation_backward(dAL, current_cache, activation = "sigmoid")

    for l in reversed(range(L-1)):
        # lth layer: (RELU -> LINEAR) gradients.
        current_cache = caches[l]
        dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads["dA" + str(l + 2)], current_cache, activation = "relu")
        grads["dA" + str(l + 1)] = dA_prev_temp
        grads["dW" + str(l + 1)] = dW_temp
        grads["db" + str(l + 1)] = db_temp

    return grads

def update_parameters(parameters, grads, learning_rate):
    """
    Update parameters using gradient descent

    Arguments:
    parameters -- python dictionary containing your parameters
    grads -- python dictionary containing your gradients, output of L_model_backward

    Returns:
    parameters -- python dictionary containing your updated parameters
                  parameters["W" + str(l)] = ...
                  parameters["b" + str(l)] = ...
    """

    L = len(parameters) // 2 # number of layers in the neural network

    # Update rule for each parameter. Use a for loop.
    for l in range(L):
        parameters["W" + str(l+1)] = parameters["W" + str(l+1)] - learning_rate * grads["dW" + str(l+1)]
        parameters["b" + str(l+1)] = parameters["b" + str(l+1)] - learning_rate * grads["db" + str(l+1)]

    return parameters

def predict(X, y, parameters):
    """
    This function is used to predict the results of a  L-layer neural network.

    Arguments:
    X -- data set of examples you would like to label
    parameters -- parameters of the trained model

    Returns:
    p -- predictions for the given dataset X
    """

    m = X.shape[1]
    n = len(parameters) // 2 # number of layers in the neural network
    p = np.zeros((1,m))

    # Forward propagation
    probas, caches = L_model_forward(X, parameters)

    # convert probas to 0/1 predictions
    for i in range(0, probas.shape[1]):
        if probas[0,i] > 0.5:
            p[0,i] = 1
        else:
            p[0,i] = 0

    #print results
    #print ("predictions: " + str(p))
    #print ("true labels: " + str(y))
    print("Accuracy: "  + str(np.sum((p == y)/m)))

    return p

def print_mislabeled_images(classes, X, y, p):
    """
    Plots images where predictions and truth were different.
    X -- dataset
    y -- true labels
    p -- predictions
    """
    a = p + y
    mislabeled_indices = np.asarray(np.where(a == 1))
    plt.rcParams['figure.figsize'] = (40.0, 40.0) # set default size of plots
    num_images = len(mislabeled_indices[0])
    for i in range(num_images):
        index = mislabeled_indices[1][i]

        plt.subplot(2, num_images, i + 1)
        plt.imshow(X[:,index].reshape(64,64,3), interpolation='nearest')
        plt.axis('off')
        plt.title("Prediction: " + classes[int(p[0,index])].decode("utf-8") + " \n Class: " + classes[y[0,index]].decode("utf-8"))


text:
<head>
  <!-- Canonical link to help search engines -->
  <link rel="canonical" href="{{ site.baseurl }}{{ page.url }}"/>

  <!-- Basic meta elements -->
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
  <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

  <!-- Enable responsiveness on mobile devices-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1"/>

  <!--   Dublin Core metadata for Zotero -->
  <meta name="DC.title" content="{{ page.title }}" />
  <meta name="DC.creator" content="{{ page.author }}" />
  <meta name="DC.contributor" content="{{ page.editor }}" />
  <meta name="DC.date" content="{{ page.publication-date }}" />
  <meta name="DC.rights" content="{{ page.rights }}" />
  <meta name="DC.source" content="{{ site.title }}" />

  <!-- Open Graph metadata -->
  <meta property="og:title" content="{{ page.title }}"/>
  <meta property="og:author" content="{{ page.author }}"/>
  <meta property="og:book:release_date" content="{{ page.publication-date }}"/>
  <meta property="og:type" content="website" />
  <meta property="og:url" content="{{ site.url }}"/>
  <meta property="og:image" content="http://elotroalex.github.io/ed/public/apple-touch-icon-precomposed.png"/>

  <title>
    {% if page.title == "Home" %}
      {{ site.title }}
    {% else %}
      {{ page.title }}
    {% endif %}
  </title>

  <!-- CSS links -->
  <link rel="stylesheet" href="{{ site.baseurl }}/public/css/syntax.css"/>
  <link rel="stylesheet" href="{{ site.baseurl }}/public/css/ed.css"/>

  <!-- Icons -->
  <link rel="apple-touch-icon-precomposed" sizes="180x180" href="{{ site.baseurl }}/public/apple-touch-icon-precomposed.png"/>
  <link rel="shortcut icon" href="{{ site.baseurl }}/public/favicon.ico"/>

  <!-- RSS -->
  <link rel="alternate" type="application/rss+xml" title="RSS" href="{{ site.baseurl }}/atom.xml"/>
</head>


text:
Installationsanleitung XAMP
========================
Check out our website http://www.yaos.ch
1. Install and enable the intl extension (used for validators).

	Open C:/xampp/php/php.ini to edit.

	Search for

	    ;extension=php_intl.dll

	and uncomment the line by removing semicolon.

	In [intl] section, uncomment and define default_local and error_level values.

	    [intl]
	    intl.default_locale = de-CH
	    intl.error_level = E_WARNING

	Save and exit the editior.
	In XAMPP control panel, restart the apache.

2. Install and enable a PHP accelerator like APC (highly recommended).

	Download the follwing file on http://dev.freshsite.pl/php-accelerators/apc.html

		APC 3.1.14 beta for PHP 5.4 (Win7/2008)

	Important: Use the one without "nts" in its name.

	Copy the downloaded file into C:/xampp/php/ext

	Open C:/xampp/php/php.ini to edit.

	Add the following line in the "Dynamic Extensions" section

		extension=php_apc_3114_beta_php54_win7-2008.dll

	Then at the bottom of the php.ini file, add

		[APC]
		apc.enabled = 1
		;apc.shm_segments = 1
		;apc.shm_size = 64
		;apc.max_file_size = 10M
		apc.stat=1

	Save and exit the editior.
	In XAMPP control panel, restart the apache.

3. Open cmd and go into your spotted folder (ex. C:\xampp\htdocs\spotted)

	Run the following command

		php composer.phar install

4. Check if your "parameters.yml" file in your spotted app/config folder exists (ex.C:\xampp\htdocs\spotted\app\config)

	If not rename the following file in your spotted app/config folder (ex.C:\xampp\htdocs\spotted\app\config)

	from

		parameters.yml.dist

	to

		parameters.yml

5. Run http://localhost/spotted/web/app_dev.php/_configurator
	Set all parameters as mentioned in our "hosting.txt" on dropbox ITPM folder and complete all steps.

Symfony Standard Edition
========================

Welcome to the Symfony Standard Edition - a fully-functional Symfony2
application that you can use as the skeleton for your new applications.

This document contains information on how to download, install, and start
using Symfony. For a more detailed explanation, see the [Installation][1]
chapter of the Symfony Documentation.

1) Installing the Standard Edition
----------------------------------

When it comes to installing the Symfony Standard Edition, you have the
following options.

### Use Composer (*recommended*)

As Symfony uses [Composer][2] to manage its dependencies, the recommended way
to create a new project is to use it.

If you don't have Composer yet, download it following the instructions on
http://getcomposer.org/ or just run the following command:

    curl -s http://getcomposer.org/installer | php

Then, use the `create-project` command to generate a new Symfony application:

    php composer.phar create-project symfony/framework-standard-edition path/to/install

Composer will install Symfony and all its dependencies under the
`path/to/install` directory.

### Download an Archive File

To quickly test Symfony, you can also download an [archive][3] of the Standard
Edition and unpack it somewhere under your web server root directory.

If you downloaded an archive "without vendors", you also need to install all
the necessary dependencies. Download composer (see above) and run the
following command:

    php composer.phar install

2) Checking your System Configuration
-------------------------------------

Before starting coding, make sure that your local system is properly
configured for Symfony.

Execute the `check.php` script from the command line:

    php app/check.php

The script returns a status code of `0` if all mandatory requirements are met,
`1` otherwise.

Access the `config.php` script from a browser:

    http://localhost/path/to/symfony/app/web/config.php

If you get any warnings or recommendations, fix them before moving on.

3) Browsing the Demo Application
--------------------------------

Congratulations! You're now ready to use Symfony.

From the `config.php` page, click the "Bypass configuration and go to the
Welcome page" link to load up your first Symfony page.

You can also use a web-based configurator by clicking on the "Configure your
Symfony Application online" link of the `config.php` page.

To see a real-live Symfony page in action, access the following page:

    web/app_dev.php/demo/hello/Fabien

4) Getting started with Symfony
-------------------------------

This distribution is meant to be the starting point for your Symfony
applications, but it also contains some sample code that you can learn from
and play with.

A great way to start learning Symfony is via the [Quick Tour][4], which will
take you through all the basic features of Symfony2.

Once you're feeling good, you can move onto reading the official
[Symfony2 book][5].

A default bundle, `AcmeDemoBundle`, shows you Symfony2 in action. After
playing with it, you can remove it by following these steps:

  * delete the `src/Acme` directory;

  * remove the routing entry referencing AcmeDemoBundle in `app/config/routing_dev.yml`;

  * remove the AcmeDemoBundle from the registered bundles in `app/AppKernel.php`;

  * remove the `web/bundles/acmedemo` directory;

  * remove the `security.providers`, `security.firewalls.login` and
    `security.firewalls.secured_area` entries in the `security.yml` file or
    tweak the security configuration to fit your needs.

What's inside?
---------------

The Symfony Standard Edition is configured with the following defaults:

  * Twig is the only configured template engine;

  * Doctrine ORM/DBAL is configured;

  * Swiftmailer is configured;

  * Annotations for everything are enabled.

It comes pre-configured with the following bundles:

  * **FrameworkBundle** - The core Symfony framework bundle

  * [**SensioFrameworkExtraBundle**][6] - Adds several enhancements, including
    template and routing annotation capability

  * [**DoctrineBundle**][7] - Adds support for the Doctrine ORM

  * [**TwigBundle**][8] - Adds support for the Twig templating engine

  * [**SecurityBundle**][9] - Adds security by integrating Symfony's security
    component

  * [**SwiftmailerBundle**][10] - Adds support for Swiftmailer, a library for
    sending emails

  * [**MonologBundle**][11] - Adds support for Monolog, a logging library

  * [**AsseticBundle**][12] - Adds support for Assetic, an asset processing
    library

  * **WebProfilerBundle** (in dev/test env) - Adds profiling functionality and
    the web debug toolbar

  * **SensioDistributionBundle** (in dev/test env) - Adds functionality for
    configuring and working with Symfony distributions

  * [**SensioGeneratorBundle**][13] (in dev/test env) - Adds code generation
    capabilities

  * **AcmeDemoBundle** (in dev/test env) - A demo bundle with some example
    code

All libraries and bundles included in the Symfony Standard Edition are
released under the MIT or BSD license.

Enjoy!

[1]:  http://symfony.com/doc/2.3/book/installation.html
[2]:  http://getcomposer.org/
[3]:  http://symfony.com/download
[4]:  http://symfony.com/doc/2.3/quick_tour/the_big_picture.html
[5]:  http://symfony.com/doc/2.3/index.html
[6]:  http://symfony.com/doc/2.3/bundles/SensioFrameworkExtraBundle/index.html
[7]:  http://symfony.com/doc/2.3/book/doctrine.html
[8]:  http://symfony.com/doc/2.3/book/templating.html
[9]:  http://symfony.com/doc/2.3/book/security.html
[10]: http://symfony.com/doc/2.3/cookbook/email.html
[11]: http://symfony.com/doc/2.3/cookbook/logging/monolog.html
[12]: http://symfony.com/doc/2.3/cookbook/assetic/asset_management.html
[13]: http://symfony.com/doc/2.3/bundles/SensioGeneratorBundle/index.html


text:
.class Landroid/widget/Toolbar$SavedState;
.super Landroid/view/View$BaseSavedState;
.source "Toolbar.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/widget/Toolbar;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "SavedState"
.end annotation

.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/widget/Toolbar$SavedState$1;
    }
.end annotation

# static fields
.field public static final CREATOR:Landroid/os/Parcelable$Creator;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Landroid/os/Parcelable$Creator",
            "<",
            "Landroid/widget/Toolbar$SavedState;",
            ">;"
        }
    .end annotation
.end field

# instance fields
.field public expandedMenuItemId:I

.field public isOverflowOpen:Z

# direct methods
.method static constructor <clinit>()V
    .locals 1

    .prologue
    .line 1918
    new-instance v0, Landroid/widget/Toolbar$SavedState$1;

    invoke-direct {v0}, Landroid/widget/Toolbar$SavedState$1;-><init>()V

    sput-object v0, Landroid/widget/Toolbar$SavedState;->CREATOR:Landroid/os/Parcelable$Creator;

    .line 1897
    return-void
.end method

.method public constructor <init>(Landroid/os/Parcel;)V
    .locals 2
    .param p1, "source"    # Landroid/os/Parcel;

    .prologue
    const/4 v0, 0x0

    .line 1902
    invoke-direct {p0, p1}, Landroid/view/View$BaseSavedState;-><init>(Landroid/os/Parcel;)V

    .line 1903
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    iput v1, p0, Landroid/widget/Toolbar$SavedState;->expandedMenuItemId:I

    .line 1904
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    if-eqz v1, :cond_0

    const/4 v0, 0x1

    :cond_0
    iput-boolean v0, p0, Landroid/widget/Toolbar$SavedState;->isOverflowOpen:Z

    .line 1901
    return-void
.end method

.method public constructor <init>(Landroid/os/Parcelable;)V
    .locals 0
    .param p1, "superState"    # Landroid/os/Parcelable;

    .prologue
    .line 1908
    invoke-direct {p0, p1}, Landroid/view/View$BaseSavedState;-><init>(Landroid/os/Parcelable;)V

    .line 1907
    return-void
.end method

# virtual methods
.method public writeToParcel(Landroid/os/Parcel;I)V
    .locals 1
    .param p1, "out"    # Landroid/os/Parcel;
    .param p2, "flags"    # I

    .prologue
    .line 1913
    invoke-super {p0, p1, p2}, Landroid/view/View$BaseSavedState;->writeToParcel(Landroid/os/Parcel;I)V

    .line 1914
    iget v0, p0, Landroid/widget/Toolbar$SavedState;->expandedMenuItemId:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 1915
    iget-boolean v0, p0, Landroid/widget/Toolbar$SavedState;->isOverflowOpen:Z

    if-eqz v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 1912
    return-void

    .line 1915
    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method


text:
@class NSMapTable, NSWindow;

@interface DVTWindowActivationNotifier : NSObject
{
    NSMapTable *_activationStateObservers;
    long long _nextKey;
    NSWindow *_window;
}

- (void).cxx_destruct;
@property __weak NSWindow *window; // @synthesize window=_window;
- (void)windowDidResignMain:(id)arg1;
- (void)windowDidBecomeMain:(id)arg1;
- (void)windowDidResignKey:(id)arg1;
- (void)windowDidBecomeKey:(id)arg1;
- (void)notifyObserversOfStateChange:(long long)arg1;
- (id)registerActivationStateObserver:(id)arg1;
- (void)dealloc;
- (id)initWithWindow:(id)arg1;

@end


text:
<Record>
<Term>Estrazinol</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Therapeutic Estrogen</ParentTerm>
<ParentTerm>Selective Estrogen Receptor Modulator</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Therapeutic Hormone/Therapeutic Estrogen/Estrazinol Hydrobromide</ClassificationPath>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Chemopreventive Agent/Selective Estrogen Receptor Modulator/Estrazinol</ClassificationPath>
<BroaderTerm>Chemopreventive Agent</BroaderTerm>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>Estrazinol Hydrobromide</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Therapeutic Estrogen</BroaderTerm>
<BroaderTerm>Estrazinol</BroaderTerm>
<BroaderTerm>Selective Estrogen Receptor Modulator</BroaderTerm>
<BroaderTerm>Therapeutic Hormone</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<Synonym>Estrazinol Hydrobromide</Synonym>
<Synonym>Estrazinol</Synonym>
<Synonym>ESTRAZINOL HYDROBROMIDE</Synonym>
<Synonym>ESTRAZINOL</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Creative - Start Bootstrap Theme</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>

    <link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet">

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

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                Matt Kjer

                        About

                        Photography

                        Videography

                        Development

                        Contact

Matt Kjer

Passionate Creations

Bachelor of Science & Commerce

Computer Science - Information Systems - Marketing
 University of Auckland

I code, take pictures and make videos. A creative individual with a passion for the discrete and finite. Implementing creative solutions to technical problems is what gets me up in the morning.

                    Linkedin

Experience

Jr Web Dev

Web Vine

Created pixel for pixel representations of given designs. A total of four websites delivered whilst working part-time.

Software Internship

Healthlink

Gained exposure to production Java, CI/CD, Javascript and various Web Technologies. The primary product focus  being Search & Directory.

Marketing Manager

Computer Lounge

Headed digital innovation & strategy. My time led to an increase of digital revenue by 250% and a strong increase in social KPI's.

Producer

Matt Kjer Media

Videography, commercial photography and reviews. My Youtube channel now has over 400,000 total views.

Photography

                                    Category

                                    Food

                                    Category

                                    Portraits

                                    Category

                                    Animals

                                    Category

                                    Landscapes

                                    Category

                                    Products

                                    Category

                                    Misc

Videography

                                    Category

                                    Macbook Pro Final Cut Comparison

                                    Category

                                    Acer Predator X34 vs Asus PG348Q

                                    Category

                                    Sennheiser HD630VB Review

                                    Category

                                    Should you buy an Ultrawide Monitor?

                                    Category

                                    Youtuber Audio on a Budget

                                    Category

                                    NZXT Hue+ Review

Development

Primary

Python | Java | HTML & CSS | Javascript

Secondary

 Hibernate | Jersey | Node.js | Jquery | TypeScript | SwaggerUI |  SpringBoot | NPM | MSSQL | CI/CD (Docker, Rancher) | Adobe CC Suite

Check Out My Development Portfolio

Hack Fest

Placed third at the Summer of Tech Hackfest. Pulling from the TradeMe API, the team presented a user friendly, graphical view of final auction prices in 48 hours.

Naki Cloud

First website I developed at Webvine. Taking an existing design, I was responsible for the html & css generation, and final pixel for pixel representation.

Healthlink

Acting Scrum Master during a three month internship focused on API's, CI/CD, Redis & MSSQL culminating in an architecture proposal and prototype to reduce search query times.

Github

 A Python tutorial, Twitter bot that tells you what movie to watch, File-sync program and the "Morning Browser" app

So why all the images if you're a Dev?

To show I have a personality behind the industry buzz words.
To prove that I enjoy integrating my passions and interests where possible.
To demonstrate some of my web skills and give you an insight as to what makes me tick.

Also... Websites are fun.

That's me, thanks for looking.

Like and Subscribe

021-124-8473

mattkjer@gmail.com


text:
using System.Collections.Generic;

namespace lox
{
    class Environment
    {
        readonly Dictionary<string, object> values = new Dictionary<string, object>();
        readonly Environment parent;

        public void Define(string name, object value) => values[name] = value;

        public void AssignAt(int distance, Token name, object value)
        {
            var environment = this;
            for (int i = 0; i < distance; i++)
                environment = environment.parent;
            environment.values[name.Lexeme] = value;
        }

        public void Assign(Token name, object value)
        {
            if (values.ContainsKey(name.Lexeme))
                values[name.Lexeme] = value;
            else if (parent != null)
                parent.Assign(name, value);
            else
                throw new RuntimeException(name, $"Undefined variable '{name.Lexeme}'.");
        }

        public object LookupAt(int distance, string name)
        {
            var environment = this;
            for (int i = 0; i < distance; i++)
                environment = environment.parent;
            return environment.values[name];
        }

        public object Lookup(Token name)
        {
            if (values.TryGetValue(name.Lexeme, out var value))
                return value;
            if (parent != null)
                return parent.Lookup(name);
            throw new RuntimeException(name, $"Undefined variable '{name.Lexeme}'.");
        }

        public Environment()
            : this(null)
        {
        }

        public Environment(Environment parent)
        {
            this.parent = parent;
        }
    }
}


text:
int main(int argc, char** argv)
{
  // Read command lines arguments.
  QApplication application(argc,argv);

  // Instantiate the viewer.
  Viewer viewer;
  //for Windows
#if (QT_VERSION >= QT_VERSION_CHECK(5, 3, 0))
  application.setAttribute(Qt::AA_UseDesktopOpenGL);
#endif
  viewer.setWindowTitle("Intersection points of randomly generated circles.");

  // Make the viewer window visible on screen.
  viewer.show();

  // Run main loop.
  return application.exec();
}


text:
package mrcode.duckprxy.impl;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.Modifier;
import javassist.NotFoundException;
import mrcode.duckprxy.DuckArg;
import mrcode.duckprxy.DuckMethod;
import mrcode.duckprxy.DuckPrxy;
import mrcode.duckprxy.impl.AbstractPrxyInvocationHandler.DelegateClassInformation;
import mrcode.duckprxy.impl.MethodUtils.MethodRetrieveStrategy;
import mrcode.duckprxy.util.ObjectUtil;

/**
 * Javassist implementation of DuckPrxy.
 * A new class is generated for a proxy which will delegate
 * calls to the provided delegate object.
 * No runtime reflection is used, making it very efficient.
 * Also, it can implement classes, not just interfaces.
 * However, there are some down-sides:
 * <ul>
 * <li> Some JVMs cannot garbage collect classes. In such JVM every
 * javassist duck proxy instance will leak memory.
 * <li> Javassist cannot handle inner interfaces and classes. Hence,
 * javassist duck proxies cannot implement inner interfaces
 * (and inner classes, but the reflection based implementation
 * cannot implement classes at all).
 * </ul>
 * There are some rough edges: The proxy creator assumes that the delegate
 * methods have a appropriate parameter and return types. This is not checked.
 * You will probably get strange javassist or class loading exceptions
 * when this assumption is not met.
 */
public class JavassistDuckPrxy implements DuckPrxy {

    /**
     * Method missing body simulates the behavior of throwing
     * NoSuchMethodExcpetion in an invocation handler.
     */
    private static final String METHOD_MISSING_BODY =
        "throw new java.lang.reflect.UndeclaredThrowableException(" +
        "new java.lang.reflect.InvocationTargetException(" +
        "new NoSuchMethodException()));";

    /**
     * Mapping to hold classes associated with their name.
     */
    private Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();

    /**
     * Prefix for the generated class names.
     */
    private final String classNamePrefix;

    public JavassistDuckPrxy() {
        this("duckprxy:");
    }

    /**
     * Constructor to set own class name prefix.
     * Normally, you do not want to override the class name prefix.
     * @param classNamePrefix  Override value for class name prefix.
     */
    public JavassistDuckPrxy(String classNamePrefix) {
        this.classNamePrefix = classNamePrefix;
    }

    public <T> T makeProxy(
            final Class<T> mainInterface,
            final Object delegate,
            final Class<?>... interfaces) {
        final Class<?> delegateClass = delegate.getClass();
        final ClassPool classPool = ClassPool.getDefault();
        final String className = createClassName(
                delegateClass,
                mainInterface,
                interfaces);
        try {
            @SuppressWarnings("unchecked")
            final Class<T> proxyClass = (Class<T>) getProxyClass(
                    className,
                    delegate,
                    delegateClass,
                    mainInterface,
                    interfaces,
                    classPool);
            final T result = proxyClass.newInstance();
            result.getClass().getField("delegate").set(result, delegate);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public Class<?> getProxyClass(
            final String className,
            final Object delegate,
            final Class<?> delegateClass,
            final Class<?> mainInterface,
            final Class<?>[] interfaces,
            final ClassPool classPool)
    throws CannotCompileException, NotFoundException {
        if (classMap.containsKey(className)) {
            return classMap.get(className);
        }
        final CtClass ctClass = createCtClass(
                className,
                delegate,
                delegateClass,
                mainInterface,
                interfaces,
                classPool);
        Class<?> proxyClass = ctClass.toClass();
        classMap.put(className, proxyClass);
        return proxyClass;
    }

    private CtClass createCtClass(
            final String className,
            final Object delegate,
            final Class<?> delegateClass,
            final Class<?> mainInterface,
            final Class<?>[] interfaces,
            final ClassPool classPool)
    throws CannotCompileException, NotFoundException {
        final DelegateClassInformation info =
            getDelegateClassInformation(delegateClass);
        final List<MethodRetrieveStrategy> strategies =
            makeStrategies(delegateClass, info);
        final CtClass ctClass = classPool.makeClass(className);
        final CtField delegateField = new CtField(classPool.get(
                delegate.getClass().getName()),
                "delegate",
                ctClass);
        delegateField.setModifiers(Modifier.PUBLIC);
        ctClass.addField(delegateField);
        if (mainInterface.isInterface()) {
            ctClass.addInterface(classPool.get(mainInterface.getName()));
        } else {
            ctClass.setSuperclass(classPool.get(mainInterface.getName()));
        }
        addInterface(
                classPool,
                ctClass,
                mainInterface,
                delegateClass,
                strategies,
                info.subDelegateGetter);
        for (final Class<?> interfce : interfaces) {
            ctClass.addInterface(classPool.get(interfce.getName()));
            addInterface(
                    classPool,
                    ctClass,
                    interfce,
                    delegateClass,
                    strategies,
                    info.subDelegateGetter);
        }
        final CtConstructor ctConstructor =
            new CtConstructor(new CtClass[0], ctClass);
        ctConstructor.setBody(null);
        ctClass.addConstructor(ctConstructor);
        return ctClass;
    }

    protected String createClassName(
            final Class<?> delegateClass,
            final Class<?> mainInterface,
            final Class<?>[] interfaces) {
        final StringBuilder builder = new StringBuilder(classNamePrefix)
        .append(delegateClass.getName())
        .append("+").append(mainInterface.getName());
        for (final Class<?> intrfce : interfaces) {
            builder.append("+").append(intrfce.getName());
        }
        return builder.toString();
    }

    protected void addInterface(
            final ClassPool classPool,
            final CtClass ctClass,
            final Class<?> interfce,
            final Class<?> delegateClass,
            final List<MethodRetrieveStrategy> strategies,
            final Method subDelegateGetter)
    throws NotFoundException, CannotCompileException {
        for (final Method method : interfce.getMethods()) {
            if (!method.getDeclaringClass().equals(Object.class) &&
                    isInterfaceMethod(method.getModifiers())) {
                addMethod(
                        classPool,
                        ctClass,
                        method,
                        delegateClass,
                        strategies,
                        subDelegateGetter);
            }
        }
    }

    protected void addMethod(
            final ClassPool classPool,
            final CtClass ctClass,
            final Method method,
            final Class<?> delegateClass,
            final List<MethodRetrieveStrategy> strategies,
            final Method subDelegateGetter)
    throws NotFoundException, CannotCompileException {
        final String methodName = method.getName();
        CtMethod ctMethod = new CtMethod(
                getCtClass(classPool, method.getReturnType()),
                methodName,
                getCtClass(classPool, method.getParameterTypes()),
                ctClass);
        System.out.println("Adding " + methodName + " " + method.getModifiers() + " " + method.getDeclaringClass());
        for (Class<?> pc : method.getParameterTypes()) {
            System.out.println("  " + pc);
        }
        final StringBuilder delegatePath = new StringBuilder("delegate.");
        final Method delegateMethod = getMethodDelegate(
                method,
                delegateClass,
                strategies, subDelegateGetter,
                delegatePath);
        final StringBuilder body = new StringBuilder();
        if (delegateMethod != null) {
            final Class<?> returnType = method.getReturnType();
            final Class<?> delegateReturnType =
                delegateMethod.getReturnType();
            final String delegateCall = delegatePath.toString() +
            getDelegateCall(
                    methodName,
                    delegateMethod,
                    method.getParameterTypes().length);
            body.append("{\n    ");
            if ("void".equals(delegateReturnType.getName())) {
                body.append(delegateCall).append(";\n");
                if (!"void".equals(returnType.getName())) {
                    body.append("    return null;\n");
                }
            } else {
                if (!"void".equals(returnType.getName())) {
                    body.append("return ");
                }
                body.append(delegateCall).append(";\n");
            }
            body.append("}");
        } else {
            body.append(METHOD_MISSING_BODY);
        }
        ctMethod.setBody(body.toString());
        ctClass.addMethod(ctMethod);
    }

    protected Method getMethodDelegate(
            final Method method,
            final Class<?> delegateClass,
            final List<MethodRetrieveStrategy> strategies,
            final Method subDelegateGetter,
            final StringBuilder delegatePath) {
        final Method delegateMethod = getDelegateMethod(
                strategies,
                method.getName(),
                method.getParameterTypes());
        if (delegateMethod != null) {
            return delegateMethod;
        }
        if (subDelegateGetter == null) {
            return null;
        }
        final Class<?> subDelegateClass = subDelegateGetter.getReturnType();
        final DelegateClassInformation info =
            getDelegateClassInformation(subDelegateClass);
        delegatePath.append(subDelegateGetter.getName()).append("().");
        return getMethodDelegate(
                method,
                subDelegateClass,
                makeStrategies(subDelegateClass, info),
                info.subDelegateGetter,
                delegatePath);
    }

    protected String getDelegateCall(
            final String name,
            final Method delegateMethod,
            final int argsLen) {
        final Annotation[][] annotations =
            delegateMethod.getParameterAnnotations();
        final int len = annotations.length;
        int argIndex = 0;
        final StringBuilder delegateArgs =
            new StringBuilder().append(delegateMethod.getName())
            .append("(");
        for (int annoIndex = 0; annoIndex < len; annoIndex++) {
            if (annoIndex > 0) {
                delegateArgs.append(", ");
            }
            final DuckArg duckArg = getDuckArg(annotations[annoIndex]);
            if (duckArg == null) {
                if (argIndex < argsLen) {
                    argIndex++;
                    delegateArgs.append("$").append(argIndex);
                }
            } else {
                switch (duckArg.value()) {
                    case NULL:
                        delegateArgs.append("null");
                        break;
                    case NAME:
                        delegateArgs.append("\"").append(name).append("\"");
                        break;
                    case ARGS:
                        appendPutArgumentsIntoArray(argsLen, delegateArgs);
                        break;
                    case ARGN:
                        if (duckArg.pos() < argsLen) {
                            delegateArgs.append("$")
                            .append(duckArg.pos() + 1);
                        }
                        break;
                }
            }
        }
        delegateArgs.append(")");
        return delegateArgs.toString();
    }

    private void appendPutArgumentsIntoArray(
            final int argsLen,
            final StringBuilder delegateArgs) {
        delegateArgs.append("new Object[] {");
        for (int i = 1; i <= argsLen; i++) {
            if (i > 1) {
                delegateArgs.append(", ");
            }
            // TODO: Converting to object is only needed for primitives.
            delegateArgs.append(ObjectUtil.class.getName())
            .append(".toObject($").append(i).append(")");
        }
        delegateArgs.append("}");
    }

    public DuckArg getDuckArg(Annotation[] annotations) {
        for (Annotation annotation : annotations) {
            if (DuckArg.class.equals(annotation.annotationType())) {
                return (DuckArg) annotation;
            }
        }
        return null;
    }

    protected CtClass getCtClass(
            final ClassPool classPool,
            final Class<?> clazz)
    throws NotFoundException {
        if (clazz == null) {
            return null;
        }
        return classPool.get(clazz.getName());
    }

    protected CtClass[] getCtClass(
            final ClassPool classPool,
            final Class<?>[] classes)
    throws NotFoundException {
        CtClass[] ctClasses = new CtClass[classes.length];
        for (int i=0; i<classes.length; i++) {
            ctClasses[i] = classPool.get(classes[i].getName());
        }
        return ctClasses;
    }

    protected List<MethodRetrieveStrategy> makeStrategies(
            final Class<?> delegateClass,
            final DelegateClassInformation info) {
        final List<MethodRetrieveStrategy> strategies =
            new ArrayList<MethodRetrieveStrategy>();
        strategies.add(MethodUtils.methodByNameAndArgsStrategy(delegateClass));
        strategies.add(MethodUtils.methodByNameWithoutArgsStrategy(
                delegateClass));
        strategies.add(MethodUtils.methodByPatternStrategy(
                delegateClass, info.patternMap));
        if (info.fallbackMethod != null) {
            strategies.add(MethodUtils.defaultMethodStrategy(
                    info.fallbackMethod));
        }
        return strategies;
    }

    protected DelegateClassInformation getDelegateClassInformation(
            final Class<?> delegateClass) {
        Map<Pattern, Method> patternMap = new HashMap<Pattern, Method>();
        Method fallbackMethod = null;
        Method subDelegateGetter = null;
        for (final Method method : delegateClass.getMethods()) {
            final DuckMethod duckMethod =
                method.getAnnotation(DuckMethod.class);
            if (duckMethod != null) {
                for (final String value : duckMethod.value()) {
                    patternMap.put(Pattern.compile(value), method);
                }
                if (duckMethod.fallback()) {
                    fallbackMethod = method;
                }
                if (duckMethod.subdelegate()) {
                    subDelegateGetter = method;
                }
            }
        }
        return new DelegateClassInformation(
                fallbackMethod, subDelegateGetter, patternMap);
    }

    private static Method getDelegateMethod(
            final List<MethodRetrieveStrategy> strategies,
            final String name,
            final Class<?>[] parameterTypes) {
        Method delegateMethod = null;
        for(MethodRetrieveStrategy strategy : strategies) {
            try {
                delegateMethod = strategy.getMethod(name, parameterTypes);
            } catch (Exception e) {
                delegateMethod = null;
            }
            if (delegateMethod != null) {
                break;
            }
        }
        return delegateMethod;
    }

    /**
     * Helper method to check whether a method is of interest,
     * i.e., is it a public non-static method.
     * @param modifiers The modifiers of the method
     * @return true iff the method is of interest.
     */
    protected static boolean isInterfaceMethod(final int modifiers) {
        return Modifier.isPublic(modifiers) &&
        (modifiers & (4094 + Modifier.STATIC)) == 0;
    }

}


text:
(function() {
  'use strict';

    angular
      .module('plottAppApp')
      .factory('icons', icons);

    icons.$inject = [];

    function icons() {
      var service = {
        sensor: setSensor
      };
      return service;

      /**
       * @name setSensor
       * @desc Creates sensor icon for leaflet map
       * @param {String} status Name of the sensor status, matches icons found in assets
       */
      function setSensor(status) {
        var url;

        if (status) {
          url = 'assets/images/rssi_' + status + '.png'
        }

        var sensor = L.icon({
          iconUrl: url || 'assets/images/rssi.png',
          iconSize: [35, 35], // size of the icon
          // iconAnchor: [22, 94], // point of the icon which will correspond to marker's location
          // popupAnchor: [-3, -76] // point from which the popup should open relative to the iconAnchor
        });

        return sensor;
      }

    }

})();


text:
using UnityEngine;

public class PlayerMove : MonoBehaviour {

    /// <summary>
    /// このスクリプトをアタッチしたオブジェクトのCharacterControllerを参照します。
    /// </summary>
    private CharacterController mController;

    /// <summary>
    /// このスクリプトをアタッチしたオブジェクトのAnimatorを参照します。
    /// </summary>
    private Animator mAnimator;

    /// <summary>
    /// このスクリプトをアタッチしたオブジェクトのRigidBodyを参照します。
    /// </summary>
    private Rigidbody mRigidBody;

	// Use this for initialization
	void Start ()
    {
        // コンポーネントを参照します。
        this.mController = GetComponent<CharacterController>();
        this.mAnimator = GetComponent<Animator>();
        this.mRigidBody = GetComponent<Rigidbody>();

	}

	// Update is called once per frame
	void Update ()
    {
        // キー入力でオブジェクトを移動します。
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

	}

}


text:
package org.apache.geode.security;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;

import java.io.NotSerializableException;
import java.io.Serializable;

import javax.naming.NamingException;

import org.apache.commons.lang3.SerializationUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;

import org.apache.geode.test.junit.categories.SecurityTest;

/**
 * Unit tests for {@link GemFireSecurityException}.
 */
@Category(SecurityTest.class)
public class GemFireSecurityExceptionTest {

  private String message;
  private String causeMessage;
  private Object nonSerializableResolvedObj;
  private NamingException nonSerializableNamingException;
  private SerializableObject serializableResolvedObj;
  private NamingException serializableNamingException;

  @Rule
  public TestName testName = new TestName();

  @Before
  public void setUp() throws Exception {
    message = testName.getMethodName() + " message";
    causeMessage = testName.getMethodName() + " cause message";

    nonSerializableResolvedObj = new Object();
    nonSerializableNamingException = new NamingException(causeMessage);
    nonSerializableNamingException.setResolvedObj(nonSerializableResolvedObj);

    serializableResolvedObj = new SerializableObject(testName.getMethodName());
    serializableNamingException = new NamingException(causeMessage);
    serializableNamingException.setResolvedObj(serializableResolvedObj);

    assertPreConditions();
  }

  private void assertPreConditions() {
    Throwable thrown =
        catchThrowable(() -> SerializationUtils.clone(nonSerializableNamingException));
    assertThat(thrown).isNotNull();
    assertThat(thrown.getCause())
        .isInstanceOf(NotSerializableException.class);

    thrown = catchThrowable(() -> SerializationUtils.clone(serializableNamingException));
    assertThat(thrown).isNull();

    assertThat(nonSerializableResolvedObj).isNotInstanceOf(Serializable.class);

    thrown = catchThrowable(() -> SerializationUtils.clone(serializableResolvedObj));
    assertThat(thrown).isNull();
  }

  @Test
  public void isSerializable() {
    assertThat(GemFireSecurityException.class).isInstanceOf(Serializable.class);
  }

  @Test
  public void serializes() {
    GemFireSecurityException instance = new GemFireSecurityException(message);

    GemFireSecurityException cloned = SerializationUtils.clone(instance);

    assertThat(cloned).hasMessage(message);
  }

  @Test
  public void serializesWithThrowable() {
    Throwable cause = new Exception(causeMessage);
    GemFireSecurityException instance = new GemFireSecurityException(message, cause);

    GemFireSecurityException cloned = SerializationUtils.clone(instance);

    assertThat(cloned).hasMessage(message).hasCause(cause);
    assertThat(cloned.getCause()).hasMessage(causeMessage);
  }

  @Test
  public void serializesWithNonSerializableNamingException() {
    GemFireSecurityException instance =
        new GemFireSecurityException(message, nonSerializableNamingException);

    GemFireSecurityException cloned = SerializationUtils.clone(instance);

    assertThat(cloned).hasMessage(message).hasCause(nonSerializableNamingException);
    NamingException cause = (NamingException) cloned.getCause();
    assertThat(cause).hasMessage(causeMessage);
    assertThat(cause.getResolvedObj()).isNull();
  }

  @Test
  public void serializesWithSerializableNamingException() {
    GemFireSecurityException instance =
        new GemFireSecurityException(message, serializableNamingException);

    GemFireSecurityException cloned = SerializationUtils.clone(instance);

    assertThat(cloned).hasMessage(message).hasCause(serializableNamingException);
    NamingException cause = (NamingException) cloned.getCause();
    assertThat(cause).hasMessage(causeMessage);
    assertThat(cause.getResolvedObj()).isNotNull().isEqualTo(serializableResolvedObj);
  }

  @Test
  public void isSerializableReturnsTrueForSerializableClass() {
    assertThat(new GemFireSecurityException("").isSerializable(serializableResolvedObj))
        .isTrue();
  }

  @Test
  public void isSerializableReturnsFalseForNonSerializableClass() {
    assertThat(new GemFireSecurityException("").isSerializable(nonSerializableResolvedObj))
        .isFalse();
  }

  private static class SerializableObject implements Serializable {

    private final String name;

    SerializableObject(String name) {
      this.name = name;
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) {
        return true;
      }
      if (o == null || getClass() != o.getClass()) {
        return false;
      }

      SerializableObject that = (SerializableObject) o;

      return name != null ? name.equals(that.name) : that.name == null;
    }

    @Override
    public int hashCode() {
      return name != null ? name.hashCode() : 0;
    }
  }
}


text:
from scipy import stats
import numpy as np

__all__ = ['chisquare', 'kolsmi']

def kolsmi(dist, fit_result, data):
    """Perform a Kolmogorow-Smirnow-Test for goodness of fit.

    This tests the H0 hypothesis, if data is a sample of dist

    Args:
        dist:         A mle.Distribution instance
        fit_result:   The solution dict, returned by the Distribution.fit method
        data:         The data used in Distribution.fit
    Returns:
        teststat:     the test statistic, e.g. the max distance between the
                      cumulated distributions
        p-value:      the p-value, probability that dist describes the data
    """
    variables = dist.get_vars()
    if len(variables) > 1:
        raise ValueError("Kolmogorov-Smirnov-Test is only valid for 1d distributions")
    var = variables[0]
    teststat, pvalue = stats.kstest(data[var.name], lambda x: dist.cdf(x, **fit_result["x"]))
    return teststat, pvalue

def chisquare(dist, fit_result, data, bins=None, range=None):
    """Perform a Chi^2 test for goodness of fit.

    Tests the H0 hypothesis if the distances between fit result and
    data are compatible  with random fluctuations.

    Args:
        dist:         A mle.Distribution instance
        fit_result:   The solution dict, returned by the Distribution.fit method
        data:         The data used in Distribution.fit
        bins:         Number of bins for the histogram (default: 1+log2(N))
        range:        Range for the histogram (default: min(data), max(data))
    Returns:
        chisquare:    the test statistic, chi^2/ndf
        p-value:      the p-value, probability that differences between dist
                      and data are compatible with random fluctuation
    """
    variables = dist.get_vars()
    if len(variables) > 1:
        raise ValueError("This is a 1d only chisquare test")
    var = variables[0]

    # rule of thumb for number if bins if not provided
    if bins is None:
        bins = np.ceil(2*len(data[var.name])**(1.0/3.0))

    entries, edges = np.histogram(data[var.name], bins=bins, range=range)

    # get expected frequencies from the cdf
    cdf = dist.cdf(edges, **fit_result["x"])
    exp_entries = np.round(len(data[var.name]) * (cdf[1:]-cdf[:-1]))

    # use only bins where more then 4 entries are expected
    mask = exp_entries >= 5

    chisq, pvalue = stats.chisquare(entries[mask], exp_entries[mask], ddof=len(fit_result["x"]))
    chisq = chisq/(np.sum(mask) - len(fit_result["x"]) - 1)
    return chisq, pvalue


text:
```
sam build
make test
```

## 参考情報

- [チュートリアル – カスタムランタイムの公開](https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/runtimes-walkthrough.html)
- [カスタムランタイムの構築](https://docs.aws.amazon.com/ja_jp/serverless-application-model/latest/developerguide/building-custom-runtimes.html)


text:
var PARSE_UI_AUTOSAVE = 'autosave';
var parseUIContext = new Parse.Object('ParseUIContext');

parseUIContext.set(PARSE_UI_AUTOSAVE, false);

function getDataFromParseObject(obj, fieldName) {
    var fieldNames = fieldName.split('.');
    var result = obj;

    for (var i = 0; i < fieldNames.length; i++) {
        if (result == null) {
            return null;
        }

        result = result.get(fieldNames[i]);
    }

    return result;
}

function setDataToParseObject(obj, fieldName, value) {
    var fieldNames = fieldName.split('.');

    for (var i = 1; i < fieldNames.length; i++) {
        if (obj == null) {
            return;
        }

        obj = obj.get(fieldNames[i - 1]);
    }

    obj.set(fieldNames[fieldNames.length - 1], value);
}

function updateCurrentValues() {
    jQuery.each($("input, span, paper-input, gold-email-input"), function(i, val) {
        var objName = $(this).attr('parseobj');
        var objField = $(this).attr('parsefield');
        var object = parseUIContext.get(objName);

        if (!objName || !objField || !object) {
            return;
        }

        var newVal = getDataFromParseObject(object, objField);

        var className = $(this).prop('tagName');

        if (className == 'SPAN') {
            $(this).text(newVal);
        } else {
            $(this).val(newVal);
        }
    });
}

$("input, paper-input, gold-email-input").change(function(e) {
    var objName = $(this).attr('parseobj');
    var objField = $(this).attr('parsefield');
    var parseSave = $(this).attr('parsesave');
    var object = parseUIContext.get(objName);

    if (!objName || !objField || !object) {
        return;
    }

    setDataToParseObject(object, objField, $(this).val());

    if ((parseSave == null) || (parseSave == undefined)) {
        parseSave = "true";
    }

    if ((parseSave == "true") && (parseUIContext.get(PARSE_UI_AUTOSAVE))) {
        object.save();
    }
});


text:
package org.keycloak.testsuite.console.page.clients.authorization.permission;

import org.keycloak.representations.idm.authorization.DecisionStrategy;
import org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation;
import org.keycloak.testsuite.console.page.fragment.MultipleStringSelect2;
import org.keycloak.testsuite.console.page.fragment.OnOffSwitch;
import org.keycloak.testsuite.page.Form;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.Select;

/**
 * @author Pedro Igor
 */
public class ResourcePermissionForm extends Form {

    @FindBy(id = "name")
    private WebElement name;

    @FindBy(id = "description")
    private WebElement description;

    @FindBy(id = "decisionStrategy")
    private Select decisionStrategy;

    @FindBy(xpath = ".//div[@class='onoffswitch' and ./input[@id='applyToResourceTypeFlag']]")
    private OnOffSwitch resourceTypeSwitch;

    @FindBy(id = "resourceType")
    private WebElement resourceType;

    @FindBy(xpath = "//i[contains(@class,'pficon-delete')]")
    private WebElement deleteButton;

    @FindBy(xpath = ACTIVE_DIV_XPATH + "/button[text()='Delete']")
    private WebElement confirmDelete;

    @FindBy(id = "s2id_policies")
    private MultipleStringSelect2 policySelect;

    @FindBy(id = "s2id_resources")
    private MultipleStringSelect2 resourceSelect;

    public void populate(ResourcePermissionRepresentation expected) {
        setInputValue(name, expected.getName());
        setInputValue(description, expected.getDescription());
        decisionStrategy.selectByValue(expected.getDecisionStrategy().name());

        resourceTypeSwitch.setOn(expected.getResourceType() != null);

        if (expected.getResourceType() != null) {
            setInputValue(resourceType, expected.getResourceType());
        } else {
            resourceTypeSwitch.setOn(false);
            resourceSelect.update(expected.getResources());
        }

        policySelect.update(expected.getPolicies());

        save();
    }

    public void delete() {
        deleteButton.click();
        confirmDelete.click();
    }

    public ResourcePermissionRepresentation toRepresentation() {
        ResourcePermissionRepresentation representation = new ResourcePermissionRepresentation();

        representation.setName(getInputValue(name));
        representation.setDescription(getInputValue(description));
        representation.setDecisionStrategy(DecisionStrategy.valueOf(decisionStrategy.getFirstSelectedOption().getText().toUpperCase()));
        representation.setPolicies(policySelect.getSelected());
        String inputValue = getInputValue(resourceType);

        if (!"".equals(inputValue)) {
            representation.setResourceType(inputValue);
        }

        representation.setResources(resourceSelect.getSelected());

        return representation;
    }
}


text:
package ru.contextguide.ad;

import ru.contextguide.yandexservices.utils.JsonSerializableObject;

import javax.annotation.Nonnull;
import javax.validation.constraints.NotNull;

/**
 * Объявления, которые требуется добавить.
 */
public class AdAddItem implements JsonSerializableObject {
    private final Long adGroupId;
    private TextAdAdd textAd;
    private MobileAppAdAdd mobileAppAdAdd;
    private DynamicTextAdAdd dynamicTextAd;
    private TextImageAdAdd textImageAd;
    private MobileAppImageAdAdd mobileAppImageAd;

    public AdAddItem(@Nonnull Long adGroupId, @NotNull TextAdAdd textAd) {
        this.adGroupId = adGroupId;
        this.textAd = textAd;
    }

    public AdAddItem(@Nonnull Long adGroupId, @NotNull MobileAppAdAdd mobileAppAdAdd) {
        this.adGroupId = adGroupId;
        this.mobileAppAdAdd = mobileAppAdAdd;
    }

    public AdAddItem(@Nonnull Long adGroupId, @NotNull DynamicTextAdAdd dynamicTextAd) {
        this.adGroupId = adGroupId;
        this.dynamicTextAd = dynamicTextAd;
    }

    public AdAddItem(@Nonnull Long adGroupId, @NotNull TextImageAdAdd textImageAd) {
        this.adGroupId = adGroupId;
        this.textImageAd = textImageAd;
    }

    public AdAddItem(@Nonnull Long adGroupId, @NotNull MobileAppImageAdAdd mobileAppImageAd) {
        this.adGroupId = adGroupId;
        this.mobileAppImageAd = mobileAppImageAd;
    }

    /**
     * Идентификатор группы, в которую добавляется объявление.
     */
    public Long getAdGroupId() {
        return adGroupId;
    }

    /**
     * Параметры текстово-графического объявления.
     */
    public TextAdAdd getTextAd() {
        return textAd;
    }

    /**
     * Параметры объявления для рекламы мобильных приложений.
     */
    public MobileAppAdAdd getMobileAppAdAdd() {
        return mobileAppAdAdd;
    }

    /**
     * Параметры динамического объявления.
     */
    public DynamicTextAdAdd getDynamicTextAd() {
        return dynamicTextAd;
    }

    /**
     * Параметры графического объявления (при добавлении в группу текстово-графических объявлений).
     */
    public TextImageAdAdd getTextImageAd() {
        return textImageAd;
    }

    /**
     * Параметры графического объявления (при добавлении в группу для рекламы мобильных приложений).
     */
    public MobileAppImageAdAdd getMobileAppImageAd() {
        return mobileAppImageAd;
    }
}


text:
update: 2022-05-28
---

# If syntax

```shell
if [[ expression1 ]]; then
  echo 'First condition satisfied!!'
elif [[ expression2 ]]; then
  echo 'Second condition satisfied!!'
else
  echo 'No conditions satisfied.'
fi
```

# Case syntax

```shell
case $FRUIT in
  apple) echo Here is your apple.  ;;
  banana) echo Here is your banana.  ;;
  *) exit 1 ;;
esac
```


text:
<?php

namespace Magic\Commands;

use Magic\Http\MagicHttp;
use Symfony\Component\Process\Process;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;

class ListTemplatesCommand extends Command
{
    /**
     * Configure the command options.
     *
     * @return void
     */
    protected function configure()
    {
        $this
            ->setName('templates')
            ->setDescription('List all available templates');
    }

    /**
     * Execute the command.
     *
     * @return void
     */
    protected function fire(InputInterface $input, OutputInterface $output)
    {
        $this->title('Available templates');

        if(($templates = $this->templates()) == null) {
            $this->error('Error while fetching templates');
            return;
        }

        $this->listing($this->listOutput($templates));
    }

    /**
     * Build templates output
     *
     * @param  array  $templates
     * @return array
     */
    protected function listOutput(array $templates)
    {
        return array_map(function($template) {
            return sprintf("<info>%s</info> - %s", $template['name'], $template['description']);
        }, $templates);
    }

    /**
     * Get all available templates
     *
     * @return array|null
     */
    protected function templates()
    {
        $response = MagicHttp::get('https://api.github.com/users/magic-cli-templates/repos');

        if ($response->getStatusCode() != 200) {
            return;
        }

        $repos = json_decode((string) $response->getBody(), true);

        return $repos;
    }
}


text:
import React from 'react'
import PropTypes from 'prop-types'

import Link from '../../utils/Link'

const UserBodyItem = ({href, onClick, children}) => {
  return (
    <div className='col-xs-4 text-center'>
      <Link
        href={href}
        onClick={onClick}>
        {children}
      </Link>
    </div>
  )
}

UserBodyItem.propTypes = {
  href: PropTypes.string,
  onClick: PropTypes.func,
  children: PropTypes.node
}

export default UserBodyItem


text:
<?php

namespace DSchoenbauer\Orm\Events\Validate\Schema;

use DSchoenbauer\Orm\Entity\HasRequiredFieldsInterface;
use DSchoenbauer\Orm\Exception\RequiredFieldMissingException;
use PHPUnit\Framework\TestCase;

/**
 * Ensures required fields are present
 *
 * @author David Schoenbauer
 */
class RequiredFieldsTest extends TestCase
{

    protected $object;

    protected function setUp()
    {
        $this->object = new RequiredFields();
    }

    public function testGetFields()
    {
        $fields = ['field', 'field1', 'field3'];
        $entity = $this->getMockBuilder(HasRequiredFieldsInterface::class)->getMock();
        $entity->expects($this->exactly(1))->method('getRequiredFields')->willReturn($fields);
        $this->assertEquals($fields, $this->object->getFields($entity));
    }

    public function testTypeInterface()
    {
        $this->assertEquals(HasRequiredFieldsInterface::class, $this->object->getInterface());
    }

    /**
     * @dataProvider validateDataProvider
     * @param array $data
     * @param array $fields
     * @param boolean $result
     */
    public function testValidate($data, $fields, $result)
    {
        if (!$result) {
            $this->expectException(RequiredFieldMissingException::class);
            $this->object->validate($data, $fields);
        }else{
            $this->assertTrue($this->object->validate($data, $fields));
        }
    }

    public function validateDataProvider()
    {
        return[
            "Nothing Wrong" => [['id' => 1, 'name' => 2], ['id', 'name'], true],
            "Only 1 field required" => [['id' => 1, 'name' => 2], ['name'], true],
            "Zero fields required" => [['id' => 1, 'name' => 2], [], true],

            "Missing a Required Fields" => [['id' => 1, 'name' => 2], ['ack'], false],
        ];
    }
}


text:
%% Demonstrate training a lattice-structured CRF
% Based on http://people.cs.ubc.ca/~schmidtm/Software/UGM/trainApprox

% This file is from pmtk3.googlecode.com

%% Get  data
setSeed(0);
X = loadData('Ximg');
Xclean = X;
y = 1+X;
X = Xclean + 0.5*randn(size(Xclean));
figure; imagesc(X); colormap(gray)

[nRows,nCols] = size(X);
nNodes = nRows*nCols;
nStates = 2;
y = reshape(y,[1 1 nNodes]);
X = reshape(X,1,1,nNodes);

%% Make model
adj = latticeAdjMatrix(nRows,nCols);
tied = 1;
ising = 1;
edgeStruct = UGM_makeEdgeStruct(adj,nStates);

% Add bias and Standardize Columns
Xnode = [ones(1,1,nNodes) UGM_standardizeCols(X,tied)];
sharedFeatures = [1 0];
Xedge = UGM_makeEdgeFeatures(Xnode,edgeStruct.edgeEnds,sharedFeatures);

%% Fit by PL, decode by ICM
model = crf2Create(adj, nStates, 'ising', ising, 'tied', tied, 'method', 'ICM');
model = crf2Train(model, Xnode, Xedge, y, 'method', 'PL');
yDecode = crf2Map(model, Xnode, Xedge);

figure;
imagesc(reshape(yDecode,nRows,nCols)); colormap gray
title('ICM Decoding with pseudo-likelihood parameters');

%% Fit with submodular PL and decode with graph cuts

sharedFeatures = [1 0];
Xedge = UGM_makeEdgeFeaturesInvAbsDif(Xnode,edgeStruct.edgeEnds,sharedFeatures);
model = crf2Create(adj, nStates, 'ising', ising, 'tied', tied, 'method', 'GraphCut');
model = crf2Train(model, Xnode, Xedge, y, 'method', 'PLsubmod');

figure;
imagesc(reshape(yDecode,nRows,nCols)); colormap gray
title('GraphCut Decoding with constrained pseudo-likelihood parameters');