text:
import React, {PropTypes} from 'react';

// image specified as CSS background-image, but size constants required in JavaScript
export const  EGG_IMAGE_WIDTH = 213,
              EGG_IMAGE_HEIGHT = 256;

class EggView extends React.Component {

  static propTypes = {
    egg: PropTypes.object,
    id: PropTypes.string,
    index: PropTypes.number,
    isSelected: PropTypes.bool,
    displayStyle: PropTypes.object,
    onClick: PropTypes.func
  };

  handleClick = (evt) => {
    const { egg, id, index, onClick } = this.props;
    if (onClick)
      onClick(id, index, egg);
    evt.stopPropagation();
  }

  render() {
    const { egg, id, displayStyle, isSelected } = this.props,
          eggStyle = Object.assign({ flexShrink: 0 }, displayStyle),
          isHidden = (egg == null),
          classes = 'clutch-egg' + (isSelected ? ' selected' : '')
                                 + (isHidden ? ' hidden' : '');
    if (displayStyle && (displayStyle.size != null)) {
      eggStyle.width = displayStyle.size;
      eggStyle.height = eggStyle.width * (EGG_IMAGE_HEIGHT / EGG_IMAGE_WIDTH);
    }
    return (
      <div id={id} className={classes} key={id} ref='domNode' style={eggStyle} onClick={this.handleClick} />
    );
  }
}

export default EggView;


text:
#include <QtCore/QString>
#include <QtTest/QtTest>
#include "gutil_icollections.h"
#include "gutil_vector.h"
#include "gutil_list.h"
USING_NAMESPACE_GUTIL;

class RandomAccessContainerTest : public QObject
{
    Q_OBJECT

public:
    RandomAccessContainerTest();

private Q_SLOTS:
    void test_vectorRAC();
    void test_listRAC();

private:
    void _test_rac(RandomAccessContainer<int> &);
};

RandomAccessContainerTest::RandomAccessContainerTest()
{
}

void RandomAccessContainerTest::test_vectorRAC()
{
    VectorRandomAccessContainer<int> r;
    _test_rac(r);
}

void RandomAccessContainerTest::test_listRAC()
{
    ListRandomAccessContainer<int> r;
    _test_rac(r);
}

#define ITEM_COUNT 10000

void RandomAccessContainerTest::_test_rac(RandomAccessContainer<int> &r)
{
    for(int i(0); i < ITEM_COUNT; ++i)
    {
        r.InsertAt(i, i);
        QVERIFY(r.CountContainerItems() == (i + 1));

        // Check both at functions for correctness
        QVERIFY(r.At(0) == 0);
        QVERIFY(r.At(i) == i);
        QVERIFY(const_cast<const RandomAccessContainer<int> &>(r).At(0) == 0);
        QVERIFY(const_cast<const RandomAccessContainer<int> &>(r).At(i) == i);
    }

    for(int i(0); i < ITEM_COUNT; ++i)
    {
        // Check both front/back functions for correctness
        QVERIFY(r.At(0) == i);
        QVERIFY(r.At(ITEM_COUNT - i - 1) == ITEM_COUNT - 1);
        QVERIFY(const_cast<const RandomAccessContainer<int> &>(r).At(0) == i);
        QVERIFY(const_cast<const RandomAccessContainer<int> &>(r).At(ITEM_COUNT - i - 1) == ITEM_COUNT - 1);

        QVERIFY(r.CountContainerItems() == (ITEM_COUNT - i));
        r.RemoveAt(0);
    }

    for(int i(0); i < ITEM_COUNT; ++i)
    {
        r.InsertAt(i, 0);
        QVERIFY(r.CountContainerItems() == (i + 1));

        // Check both front/back functions for correctness
        QVERIFY(r.At(0) == i);
        QVERIFY(r.At(i) == 0);
        QVERIFY(const_cast<const RandomAccessContainer<int> &>(r).At(0) == i);
        QVERIFY(const_cast<const RandomAccessContainer<int> &>(r).At(i) == 0);
    }

    for(int i(0); i < ITEM_COUNT; ++i)
    {
        // Check both front/back functions for correctness
        QVERIFY(r.At(0) == ITEM_COUNT - 1);
        QVERIFY(r.At(ITEM_COUNT - i - 1) == i);
        QVERIFY(const_cast<const RandomAccessContainer<int> &>(r).At(0) == ITEM_COUNT - 1);
        QVERIFY(const_cast<const RandomAccessContainer<int> &>(r).At(ITEM_COUNT - i - 1) == i);

        QVERIFY(r.CountContainerItems() == (ITEM_COUNT - i));
        r.RemoveAt(ITEM_COUNT - i - 1);
    }

    // Test the clear function
    const int cnt( 10 );
    for(int i(0); i < cnt; i++)
    {
        r.InsertAt(i, i);
    }
    QVERIFY(r.CountContainerItems() == cnt);

    r.FlushContainer();
    QVERIFY(r.CountContainerItems() == 0);
}

QTEST_APPLESS_MAIN(RandomAccessContainerTest);

#include "tst_randomaccesscontainertest.moc"

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

  <meta charset="utf-8">
  <title id="network" i18n-content="titleText"></title>
  <link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
  <link rel="stylesheet" href="chrome://network/network_ui.css">
  <link rel="import" href="chrome://resources/cr_elements/v1_0/network/cr_network_icon.html">
  <link rel="import" href="chrome://resources/cr_elements/v1_0/network/cr_network_select.html">
  <link rel="import" href="chrome://resources/cr_elements/v1_0/network/cr_onc_types.html">
  <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">

      <select id="get-property-format">
        <option value="normal" i18n-content="normalFormatOption"></option>
        <option value="managed" i18n-content="managedFormatOption"></option>
        <option value="state" i18n-content="stateFormatOption"></option>
        <option value="shill" i18n-content="shillFormatOption"></option>
      </select>

    <cr-network-select expandable show-active max-height="100">
    </cr-network-select>

      <paper-button raised class="colored" id="refresh"
          i18n-content="networkRefreshText">
      </paper-button>

      GUID
      Path
      Name
      Type
      State
      Connect?
      Error
      Security
      Tech
      Activation
      Roam
      Strength

      GUID
      Path
      Name
      Type
      Profile
      Visible
      ONC Source


text:
package org.jetbrains.git4idea.ssh;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcHttpClientConfig;

import javax.annotation.Nullable;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * Client for IDEA SSH GUI event handler
 */
@SuppressWarnings({"UseOfObsoleteCollectionType"})
public class GitSSHXmlRpcClient implements GitSSHHandler
{
	/**
	 * XML RPC client
	 */
	@Nullable
	private final XmlRpcClient myClient;

	/**
	 * A constructor
	 *
	 * @param port      port number
	 * @param batchMode if true, the client is run in the batch mode, so nothing should be prompted
	 * @throws IOException if there is IO problem
	 */
	GitSSHXmlRpcClient(final int port, final boolean batchMode) throws IOException
	{
		//noinspection HardCodedStringLiteral
		if(batchMode)
		{
			myClient = null;
		}
		else
		{
			XmlRpcClientConfigImpl clientConfig = new XmlRpcClientConfigImpl();
			clientConfig.setEncoding("UTF-8");
			clientConfig.setServerURL(new URL("http://127.0.0.1:" + port + "/RPC2"));

			myClient = new XmlRpcClient();
			myClient.setConfig(clientConfig);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public boolean verifyServerHostKey(String token, final String hostname, final int port, final String serverHostKeyAlgorithm, final String serverHostKey, final boolean isNew)
	{
		if(myClient == null)
		{
			return false;
		}
		List parameters = new ArrayList<>();
		parameters.add(token);
		parameters.add(hostname);
		parameters.add(port);
		parameters.add(serverHostKeyAlgorithm);
		parameters.add(serverHostKey);
		parameters.add(isNew);
		try
		{
			return ((Boolean) myClient.execute(methodName("verifyServerHostKey"), parameters)).booleanValue();
		}
		catch(XmlRpcException e)
		{
			throw new RuntimeException("Invocation failed " + e.getMessage(), e);
		}
	}

	/**
	 * Get the full method name
	 *
	 * @param method short name of the method
	 * @return full method name
	 */
	private static String methodName(final String method)
	{
		return GitSSHHandler.HANDLER_NAME + "." + method;
	}

	/**
	 * {@inheritDoc}
	 */
	@Nullable
	@SuppressWarnings("unchecked")
	public String askPassphrase(String token, final String username, final String keyPath, final boolean resetPassword, final String lastError)
	{
		if(myClient == null)
		{
			return null;
		}
		Vector parameters = new Vector();
		parameters.add(token);
		parameters.add(username);
		parameters.add(keyPath);
		parameters.add(resetPassword);
		parameters.add(lastError);
		try
		{
			return adjustNull(((String) myClient.execute(methodName("askPassphrase"), parameters)));
		}
		catch(XmlRpcException e)
		{
			throw new RuntimeException("Invocation failed " + e.getMessage(), e);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Nullable
	@SuppressWarnings("unchecked")
	public List<String> replyToChallenge(String token,
										   final String username,
										   final String name,
										   final String instruction,
										   final int numPrompts,
										   final Vector<String> prompt,
										   final Vector<Boolean> echo,
										   final String lastError)
	{
		if(myClient == null)
		{
			return null;
		}
		List parameters = new ArrayList();
		parameters.add(token);
		parameters.add(username);
		parameters.add(name);
		parameters.add(instruction);
		parameters.add(numPrompts);
		parameters.add(prompt);
		parameters.add(echo);
		parameters.add(lastError);
		try
		{
			return adjustNull((List<String>) myClient.execute(methodName("replyToChallenge"), parameters));
		}
		catch(XmlRpcException e)
		{
			throw new RuntimeException("Invocation failed " + e.getMessage(), e);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Nullable
	@SuppressWarnings("unchecked")
	public String askPassword(String token, final String username, final boolean resetPassword, final String lastError)
	{
		if(myClient == null)
		{
			return null;
		}
		Vector parameters = new Vector();
		parameters.add(token);
		parameters.add(username);
		parameters.add(resetPassword);
		parameters.add(lastError);
		try
		{
			return adjustNull(((String) myClient.execute(methodName("askPassword"), parameters)));
		}
		catch(XmlRpcException e)
		{
			throw new RuntimeException("Invocation failed " + e.getMessage(), e);
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public String setLastSuccessful(String token, String userName, String method, String error)
	{
		if(myClient == null)
		{
			return "";
		}
		Vector parameters = new Vector();
		parameters.add(token);
		parameters.add(userName);
		parameters.add(method);
		parameters.add(error);
		try
		{
			return (String) myClient.execute(methodName("setLastSuccessful"), parameters);
		}
		catch(XmlRpcException e)
		{
			throw new RuntimeException("Invocation failed " + e.getMessage(), e);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	@SuppressWarnings("unchecked")
	public String getLastSuccessful(String token, String userName)
	{
		if(myClient == null)
		{
			return "";
		}
		Vector parameters = new Vector();
		parameters.add(token);
		parameters.add(userName);
		try
		{
			return (String) myClient.execute(methodName("getLastSuccessful"), parameters);
		}
		catch(XmlRpcException e)
		{
			XmlRpcHttpClientConfig clientConfig = (XmlRpcHttpClientConfig) myClient.getConfig();
			log("getLastSuccessful failed. token: " + token + ", userName: " + userName + ", client: " + clientConfig.getServerURL());
			throw new RuntimeException("Invocation failed " + e.getMessage(), e);
		}
	}

	/**
	 * Since XML RPC client does not understand null values, the value should be
	 * adjusted (The password is {@code "-"} if null, {@code "+"+s) if non-null).
	 *
	 * @param s a value to adjust
	 * @return adjusted value.
	 */
	@Nullable
	private static String adjustNull(final String s)
	{
		return s.charAt(0) == '-' ? null : s.substring(1);
	}

	/**
	 * Since XML RPC client does not understand null values, the value should be
	 * adjusted. This is done by replacing empty array with null.
	 *
	 * @param s a value to adjust
	 * @return adjusted value.
	 */
	@Nullable
	private static <T> List<T> adjustNull(final List<T> s)
	{
		return s.size() == 0 ? null : s;
	}

	private static void log(String s)
	{
		System.err.println(s);
	}
}


text:
nonogram-generator
==================

Takes a black and white bitmap and creates a nonogram puzzle.


text:
layout: default
---
{% block content %}

    <video playsinline autoplay muted loop id="bgvid" class="vid">
        <source src="assets/video/electric_bulb_hd.mp4" type="video/mp4">
    </video>

{{ page.title | default(site.title) }}

                    {{ page.description }}
                    {% if page.header_img.author %}

                    Photo by
                        {% if page.header_img.author_url %}
                        {{ page.header_img.author }}
                        {% else %}
                        {{ page.header_img.author }}
                    {% endif %}
                    {% endif %}

            {{ page.content }}

{% endblock %}


text:
title: Function
localeTitle: وظيفة
---
## وظيفة

هذا هو كعب. [ساعد مجتمعنا على توسيعه](https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/standard-objects/function/index.md) .

[سيساعدك دليل النمط السريع هذا على ضمان قبول طلب السحب](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### معلومات اكثر:


text:
// -----------------------------------------------------------------------
// <copyright file="CustomerUserRestore.cs" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// -----------------------------------------------------------------------

namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
    using Models.Users;

    /// <summary>
    /// Showcases customer user restore API.
    /// </summary>
    public class CustomerUserRestore : BasePartnerScenario
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="CustomerUserRestore"/> class.
        /// </summary>
        /// <param name="context">The scenario context.</param>
        public CustomerUserRestore(IScenarioContext context) : base("Restore a deleted customer user", context)
        {
        }

        /// <summary>
        /// Executes the restore customer user scenario.
        /// </summary>
        protected override void RunScenario()
        {
            // get customer Id of the entered customer user.
            string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the corresponding customer to restore customer user details");

            // get customer user Id.
            string selectedCustomerUserId = this.ObtainCustomerUserId("Enter the ID of the customer user to restore");

            var partnerOperations = this.Context.UserPartnerOperations;

            var updatedCustomerUser = new CustomerUser()
            {
                State = UserState.Active
            };

            this.Context.ConsoleHelper.StartProgress("Restoring the customer user");

            // restore customer user information using older upn.
            var restoredCustomerUserInfo = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).Patch(updatedCustomerUser);
            this.Context.ConsoleHelper.StopProgress();
            this.Context.ConsoleHelper.WriteObject(restoredCustomerUserInfo, "Restored customer user.");
        }
    }
}


text:
<?php

namespace Framework;

class AbstractModel extends \Phalcon\Mvc\Model {

}


text:
package com.francetelecom.clara.cloud.paas.activation.v1.async.listener;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.francetelecom.clara.cloud.commons.tasks.TaskStatus;
import com.francetelecom.clara.cloud.paas.activation.v1.async.TaskHandler;
import com.francetelecom.clara.cloud.paas.activation.v1.async.TaskHandlerCallback;
import com.francetelecom.clara.cloud.paas.activation.v1.async.message.ErrorMessage;

public class ErrorMessageListener implements MessageListener {

	private TaskHandler<TaskStatus, TaskHandlerCallback<TaskStatus>> taskHandler;

	private static final Logger log = LoggerFactory.getLogger(ErrorMessageListener.class);

	@Override
	public void onMessage(Message message) {

		try {
			log.debug("unxepected error occured during task polling process");
			ErrorMessage msg = new ErrorMessage((ObjectMessage) message);
			Throwable error = (Throwable) msg.getObject();
			String communicationId = msg.getCommunicationId();
			taskHandler.onTaskFailure(error, communicationId);
		} catch (JMSException ex) {
			log.error("JMSException occured during task polling process; details : " + ex);
			throw new RuntimeException(ex);
		}

	}

	public void setTaskHandler(TaskHandler<TaskStatus, TaskHandlerCallback<TaskStatus>> taskHandler) {
		this.taskHandler = taskHandler;
	}

}


text:
<!doctype html>

<meta charset="utf-8">
<title>Off Canvas - Top | Responsive Patterns</title>
<link rel="stylesheet" href="../../../common/css/clearfix.css">
<link rel="stylesheet" href="style.css">

Here is more content. This could be related items, navigation or other content you feel is conducive to this type of treatment. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean quis nisi et dui placerat ornare. Maecenas molestie lacus lobortis libero lacinia sed scelerisque lectus congue.


text:
import PropTypes from 'prop-types';
import React, { Component } from 'react';

import BpkButton from '../../packages/bpk-component-button';
import BpkSelect from '../../packages/bpk-component-select';
import BpkCheckbox from '../../packages/bpk-component-checkbox';
import BpkTextarea from '../../packages/bpk-component-textarea';
import BpkInput from '../../packages/bpk-component-input';
import { cssModules } from '../../packages/bpk-react-utils';
import BpkFormValidation from '../../packages/bpk-component-form-validation';

import STYLES from './examples.module.scss';

const getClassName = cssModules(STYLES);

const formClassName = getClassName('bpkdocs-forms-page__form');

class FormValidationContainer extends Component {
  constructor() {
    super();

    this.state = {
      expanded: true,
    };
  }

  toggleExpanded = () => {
    this.setState((prevState) => ({
      expanded: !prevState.expanded,
    }));
  };

  render() {
    return (

          <BpkButton onClick={this.toggleExpanded}>Toggle</BpkButton>

        <BpkFormValidation expanded={this.state.expanded} {...this.props} />

    );
  }
}

class InputContainer extends Component {
  constructor(props) {
    super(props);

    const valueProp = props.FormComponent === BpkCheckbox ? 'checked' : 'value';

    this.state = {
      value: props[valueProp],
    };
  }

  render() {
    const { FormComponent, ...rest } = this.props;

    let overrideProps = {};

    if (FormComponent === BpkCheckbox) {
      overrideProps = {
        checked: this.state.value,
        onChange: (e) => this.setState({ value: e.target.checked }),
      };
    } else {
      overrideProps = {
        value: this.state.value,
        onChange: (e) => this.setState({ value: e.target.value }),
      };
      if (FormComponent === BpkInput) {
        overrideProps.onClear = () => this.setState({ value: '' });
      }
    }
    return <FormComponent {...rest} {...overrideProps} />;
  }
}

InputContainer.propTypes = {
  FormComponent: PropTypes.elementType.isRequired,
};

const DefaultExample = () => (
  <FormValidationContainer id="my-validation-message">
    A validation message
  </FormValidationContainer>
);

const FormsExample = () => (

    <form className={formClassName}>
      <InputContainer
        FormComponent={BpkInput}
        id="input_invalid"
        name="input_invalid"
        value="Edinbrvgh"
        placeholder="Country, city or airport"
        onChange={() => null}
        valid={false}
      />
      <BpkFormValidation id="form_validation" expanded>
        Please enter a valid name
      </BpkFormValidation>
    </form>
    <form className={formClassName}>
      <InputContainer
        FormComponent={BpkSelect}
        id="select_invalid"
        name="select_invalid"
        value=""
        onChange={() => null}
        valid={false}
      >
        <option value="" hidden>
          Please select...
        </option>
        <option value="economy">Economy</option>
        <option value="premium_economy">Premium Economy</option>
        <option value="business">Business class</option>
        <option value="first">First class</option>
      </InputContainer>
      <BpkFormValidation id="form_validation" expanded isCheckbox>
        This option is required
      </BpkFormValidation>
    </form>
    <form className={formClassName}>
      <InputContainer
        FormComponent={BpkCheckbox}
        name="checkbox"
        label="Apples"
      />
      <BpkFormValidation id="form_validation" expanded isCheckbox>
        This checkbox is required
      </BpkFormValidation>
    </form>
    <form className={formClassName}>
      <InputContainer
        FormComponent={BpkTextarea}
        id="textarea"
        name="textarea"
        value="@text 123 /}"
        placeholder="@text 123 /}"
        onChange={() => null}
        valid={false}
      />
      <BpkFormValidation id="form_validation" expanded>
        Please enter valid input
      </BpkFormValidation>
    </form>

);

export { DefaultExample, FormsExample };


text:
"use strict";

/**
 * Requirements
 */
let JinjaParser = require(SOURCE_ROOT + '/parser/documentation/JinjaParser.js').JinjaParser;
let DocumentationCallable = require(SOURCE_ROOT + '/model/documentation/DocumentationCallable.js').DocumentationCallable;
let DocumentationParameter = require(SOURCE_ROOT + '/model/documentation/DocumentationParameter.js').DocumentationParameter;
let ContentType = require(SOURCE_ROOT + '/model/ContentType.js');

/**
 * Spec
 */
describe(JinjaParser.className, function()
{
    beforeEach(function()
    {
        fixtures = {};
    });

    describe('#className', function()
    {
        it('should return the namespaced class name', function()
        {
            let testee = new JinjaParser();
            expect(testee.className).to.be.equal('parser.documentation/JinjaParser');
        });
    });

    describe('#parse()', function()
    {
        it('should parse macros without a valid docblock', function()
        {
            let testee = new JinjaParser();
            let docblock = `{% macro one(name='unnamed', id = 5) %}{% endmacro %}`;

            let promise = testee.parse(docblock).then(function(documentation)
            {
                expect(documentation).to.have.length(1);
                let macro = documentation.find(doc => doc.name == 'one');
                expect(macro.parameters).to.have.length(2);
                expect(macro.parameters.find(param => param.name == 'name')).to.be.ok;
                expect(macro.parameters.find(param => param.name == 'name').defaultValue).to.be.equal("'unnamed'");
                expect(macro.parameters.find(param => param.name == 'id')).to.be.ok;
                expect(macro.parameters.find(param => param.name == 'id').defaultValue).to.be.equal("5");
            });
            return promise;
        });

        it('should parse macros with a valid docblock', function()
        {
            let testee = new JinjaParser();
            let docblock = `
            {##
                @param {string} name
                @param {number} id
             #}
            {% macro one(name, id) %}{% endmacro %}`;

            let promise = testee.parse(docblock).then(function(documentation)
            {
                expect(documentation).to.have.length(1);
                let macro = documentation.find(doc => doc.name == 'one');
                expect(macro.parameters).to.have.length(2);
                expect(macro.parameters.find(param => param.name == 'name')).to.be.ok;
                expect(macro.parameters.find(param => param.name == 'name').type).to.contain('String');
                expect(macro.parameters.find(param => param.name == 'id')).to.be.ok;
                expect(macro.parameters.find(param => param.name == 'id').type).to.contain('Number');
            });
            return promise;
        });

        it('should parse macros with mixed identation', function()
        {
            let testee = new JinjaParser();
            let docblock = `
            {##
                @param {string} name
                @param {number} id
             #}
                {% macro one(name, id) %}{% endmacro %}
                    {##
                        @param {string} name
                     #}
        {% macro two(name) %}{% endmacro %}
                `;

            let promise = testee.parse(docblock).then(function(documentation)
            {
                expect(documentation).to.have.length(2);
                expect(documentation.find(doc => doc.name == 'one')).to.be.ok;
                expect(documentation.find(doc => doc.name == 'two')).to.be.ok;
            });
            return promise;
        });

        it('should enhance infos from docblock with macro infos', function()
        {
            let testee = new JinjaParser();
            let docblock = `
            {##
                @param {string} name
                @param {number} id
             #}
            {% macro one(name, id = 1, class = 'one') %}{% endmacro %}`;

            let promise = testee.parse(docblock).then(function(documentation)
            {
                expect(documentation).to.have.length(1);
                let macro = documentation.find(doc => doc.name == 'one');
                expect(macro.parameters).to.have.length(3);
                expect(macro.parameters.find(param => param.name == 'name')).to.be.ok;
                expect(macro.parameters.find(param => param.name == 'name').type).to.contain('String');
                expect(macro.parameters.find(param => param.name == 'id')).to.be.ok;
                expect(macro.parameters.find(param => param.name == 'id').type).to.contain('Number');
                expect(macro.parameters.find(param => param.name == 'id').defaultValue).to.be.equal('1');
                expect(macro.parameters.find(param => param.name == 'class')).to.be.ok;
                expect(macro.parameters.find(param => param.name == 'class').type).to.contain('*');
                expect(macro.parameters.find(param => param.name == 'class').defaultValue).to.be.equal("'one'");
            });
            return promise;
        });

        it('should allow to document maps/objects', function()
        {
            let testee = new JinjaParser();
            let docblock = `
            {##
                @param {String} model.href
                @param {String} model.title
            #}
            {% macro e001_link(model) %}
            {%  endmacro %}
            `;

            let promise = testee.parse(docblock).then(function(documentation)
            {
                expect(documentation).to.have.length(1);
                let macro = documentation.find(doc => doc.name == 'e001_link');
                expect(macro.parameters).to.have.length(1);
            });
            return promise;
        });

        it('should always parse macros as callables', function()
        {
            let testee = new JinjaParser();
            let docblock = `
            {##
                Description
             #}
            {% macro one(name, id) %}{% endmacro %}`;

            let promise = testee.parse(docblock).then(function(documentation)
            {
                expect(documentation).to.have.length(1);
                expect(documentation.find(doc => doc.name == 'one')).to.be.instanceof(DocumentationCallable);
            });
            return promise;
        });

        it('should allow markdown in the docblock', function()
        {
            let testee = new JinjaParser();
            let docblock = `
            {##
                # Headline
                * List 1
                  * List 1.1
                * List 2
             #}
            {% macro one(name, id) %}{% endmacro %}`;
            let expected =
`# Headline
* List 1
  * List 1.1
* List 2`;

            let promise = testee.parse(docblock).then(function(documentation)
            {
                expect(documentation).to.have.length(1);
                let macro = documentation.find(doc => doc.name == 'one');
                expect(macro.description).to.be.equal(expected);
            });
            return promise;
        });

        it('should allow comment within macro', function()
        {
            let testee = new JinjaParser();
            let docblock = `
            {##
                @param {String} href - Link url
            #}
            {% macro e001_link(type, href, title, target, data, class) %}
                {# Render #}

            {%  endmacro %}
            `;

            let promise = testee.parse(docblock).then(function(documentation)
            {
                expect(documentation).to.have.length(1);
            });
            return promise;
        });
    });

    describe('performance', function()
    {
        it('should parse a macro within 20ms', function()
        {
            let testee = new JinjaParser();
            let docblock = `

            {##
                Add sanity checks for dumb queries like

                @param {String} name
                @param {String} mode
            #}
            {% macro one(name, id = 1, mode = 'one', ignore=false) %}{% endmacro %}
            `;

            this.timeout(20);
            let promise = testee.parse(docblock).then(function(documentation)
            {
                expect(documentation).to.have.length(1);
            });
            return promise;
        });
    });

    describe('bugs', function()
    {
        it('should not get stuck when comment is in wrong place', function()
        {
            let testee = new JinjaParser();
            let docblock = `
            {##
                Add sanity checks for dumb queries like

                @param {String} name
                @param {String} mode
            #}
            {% include 'some/thing' %}
            {% macro one(name, id = 1, mode = 'one', ignore=false) %}{% endmacro %}
            `;

            let promise = testee.parse(docblock).then(function(documentation)
            {
                expect(documentation).to.have.length(1);
            });
            return promise;
        });
    });
});


text:
title: Blog 4 2018
layout: post
author: jacob.mellows
permalink: /blog-4-2018/
source-id: 14GEXNIH8XjubWokuzWVIcDREjtwJk5ntw0PBQ_W-1r0
published: true
---

    Title
    Shift Ciphers
    Date
    13/09/18

    Starting point:
    Shift Ciphers

    Target for this lesson?
    Start adding an ASCII  table

    Did I reach my target?
    I have completed the table with binary and octal and hexadecimal

    How did you use your learning habits this week?

    Persevering

    Questioning?
    When in was typing in the binary i questioned to myself there must be a quicker way and realised that i could copy and paste them in.

    Independence
    Our class was one our own as Mr Keen was out of the room doing important things. I managed to get the table gown and not get distracted by other things

    Reflecting
    I reflected on how i layed out the code with my ciphers and did it the same way

    Engagement
    I engaged in are task and followed it and completed it

    What could have gone better in your learning?

    I could have incorporated some other pieces of ascii code like what character the decimal stands for. However, there was not much lesson time as there were other things going on and we started very late

    What changes do you need to make to improve your learning next time?

    I am happy with what i did in the lesson however i could have done a bit more to my table and could of had a go at trying to use it using different functions in sheets.


text:
#import "MBSplitDialogContentBuilder.h"
#import "MBSplitViewController.h"
#import "MBDialogController.h"

@implementation MBSplitDialogContentBuilder

-(UIViewController *)buildDialogContentViewControllerForDialog:(MBDialogController *)dialogController {
    MBSplitViewController *containerViewController = [[[MBSplitViewController alloc] initWithLeftViewControllerVisibleInPortraitMode:YES] autorelease];
    if (dialogController.pageStackControllers.count > 1) {
        MBPageStackController *leftPageStackController = [dialogController.pageStackControllers objectAtIndex:0];
        [containerViewController setMasterViewController:leftPageStackController.navigationController];
        MBPageStackController *rightPageStackController = [dialogController.pageStackControllers objectAtIndex:1];
        [containerViewController setDetailViewController:rightPageStackController.navigationController];
    }
    return containerViewController;
}

@end


text:
title: CategoriesCloud
date: 2017-07-11 17:03:09
type: categories
---


text:
<?php

namespace UthandoNewsletterTest\Form;

use UthandoNewsletter\Form\Element\SubscriptionList;
use UthandoNewsletter\Form\SubscriberFormUserEdit;
use UthandoNewsletterTest\Framework\TestCase;
use Zend\Form\Element\Csrf;
use Zend\Form\Element\DateTime;
use Zend\Form\Element\Email;
use Zend\Form\Element\Hidden;
use Zend\Form\Element\Submit;
use Zend\Form\Element\Text;

class SubscriberUserEditTest extends TestCase
{
    public function testCanCreateFromServiceManager()
    {
        $form = $this->serviceManager
            ->get('FormElementManager')
            ->get('UthandoNewsletterSubscriberUserEdit');

        $this->assertInstanceOf(SubscriberFormUserEdit::class, $form);

        $this->assertInstanceOf(Hidden::class, $form->get('subscriberId'));
        $this->assertInstanceOf(Text::class, $form->get('name'));
        $this->assertInstanceOf(Email::class, $form->get('email'));
        $this->assertInstanceOf(SubscriptionList::class, $form->get('subscribe'));
        $this->assertInstanceOf(DateTime::class, $form->get('dateCreated'));
        $this->assertInstanceOf(Submit::class, $form->get('submit'));
    }
}


text:
package main

import (
	"fmt"
	"github.com/aviddiviner/docopt-go"
)

func main() {
	usage := `usage: type_assert [-x] [-y]`

	arguments, err := docopt.ParseDoc(usage)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println(arguments)

	var x = arguments["-x"].(bool) // type assertion required
	if x == true {
		fmt.Println("x is true")
	}

	y := arguments["-y"] // no type assertion needed
	if y == true {
		fmt.Println("y is true")
	}
	y2 := arguments["-y"]
	if y2 == 10 { // this will never be true, a type assertion would have produced a build error
		fmt.Println("y is 10")
	}
}


text:
<resources>
    <string name="app_name">LejosSample</string>

    <string name="recognized_command">Recognized command</string>
    <string name="action_settings">Settings</string>
    <string name="connectButtonText">connect</string>
    <string name="addressHint">Robot IP like 192.168.0.9</string>
    <string name="title_activity_settings">SettingsActivity</string>

    <string name="hello_world">Hello world!</string>
</resources>


text:
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"path/filepath"

	homedir "github.com/mitchellh/go-homedir"
	"github.com/spf13/viper"
)

var cfgFile string

func init() {
	flag.StringVar(&cfgFile, "config", "$HOME/.yummy.yaml", "config file (default is $HOME/.yummy.yaml)")
	flag.Parse()
}

// initConfig parses the config file and ENV variables, if set.
func initConfig() yummyConfiguration {

	// Find home directory.
	home, err := homedir.Dir()
	if err != nil {
		log.Fatal(err)
	}

	// Search config in home directory
	viper.AddConfigPath(home)

	// Search config parallel to executable
	executable, err := os.Executable()
	if err != nil {
		log.Fatal(err)
	}

	executablePath := filepath.Dir(executable)
	viper.AddConfigPath(executablePath)

	// Search for config file with name ".yummy" (without extension).
	viper.SetConfigName(".yummy")

	viper.AutomaticEnv() // read in environment variables that match

	if cfgFile != "$HOME/.yummy.yaml" {
		// Use config file from the flag.
		fmt.Println("Checking config file:", cfgFile)
		viper.SetConfigFile(cfgFile)
	}

	// If config file is found, parse it.
	if err = viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}

	// store configurations in a variables, as we use them quite often
	return yummyConfiguration{
		repoPath:         viper.GetString("yum.repoPath"),
		createrepoBinary: viper.GetString("yum.createrepoBinary"),
		rpmBinary:        viper.GetString("yum.rpmBinary"),
		helpFile:         viper.GetString("yum.helpFile"),
		port:             viper.GetString("yum.port"),
	}
}


text:
class ProxyRoute(object):
  def __init__(self,
               locations,
               source_group_manager):
    self._locations = locations
    self._source_group_manager = source_group_manager

  @property
  def blueprints(self):
    return self._source_group_manager.blueprints

  @property
  def locations(self):
    return self._locations

  @property
  def endpoints(self):
    return self._source_group_manager.endpoints

  @property
  def slug(self):
    return self._source_group_manager.slug

  def start(self, weight_adjustment_start):
    self._source_group_manager.start(weight_adjustment_start)


text:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ProjectPhoto extends Model
{
    protected $table = 'project_photos';

    protected $fillable = ['path'];

    public function project(){
        return $this->belongsTo('App\Models\Project');
    }

}


text:
		<title>Spaceship Samurai Services</title>
		<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
		<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/3.1.1/slate/bootstrap.min.css">
		<link rel="stylesheet" href="/css/font-awesome.min.css">
		<link rel="stylesheet" href="/css/site.css">
		<link rel="icon" href="//spaceshipsamurai.com/favicon.ico" type="image/x-icon">

					Spaceship Samurai

						Auth

						Forums

						Killboards


text:
package org.apache.ignite;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;

import org.apache.ignite.spi.tracing.Scope;
import org.apache.ignite.spi.tracing.TracingConfigurationCoordinates;
import org.apache.ignite.spi.tracing.TracingConfigurationParameters;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;

import static org.apache.ignite.spi.tracing.Scope.COMMUNICATION;
import static org.apache.ignite.spi.tracing.Scope.DISCOVERY;
import static org.apache.ignite.spi.tracing.Scope.EXCHANGE;
import static org.apache.ignite.spi.tracing.Scope.TX;

/**
 * Tests for tracing configuration validation rules.
 */
@SuppressWarnings("ThrowableNotThrown")
public class TracingConfigurationValidationTest extends GridCommonAbstractTest {
    /**
     * Ensure that in case of null scope as part of tracing coordinates {@code IllegalArgumentException} is thrown with
     * message "Null scope is not valid for tracing coordinates."
     */
    @Test
    public void testThatItsNotPossibleToSetNullAsScopeForTracingCoordinates() {
        GridTestUtils.assertThrows(
            log,
            () -> new TracingConfigurationCoordinates.Builder(null).build(),
            IllegalArgumentException.class,
            "Null scope is not valid for tracing coordinates.");
    }

    /**
     * Ensure that it's possible to set any non-null {@link Scope} as part of TracingConfigurationCoordinates.
     */
    @Test
    public void testThatItsPossibleToSpecifyAnyScopeAsPartOfTracingConfigurationCoordinates() {
        for (Scope scope : Scope.values())
            new TracingConfigurationCoordinates.Builder(scope).build();
    }

    /**
     * Ensure that it's possible to set any string as label as part of TracingConfigurationCoordinates.
     */
    @Test
    public void testThatItsPossibleToSpecifyAnyStringAsLabelAsPartOfTracingConfigurationCoordinates() {
        Stream.of(
            null,
            "",
            "label", "Some really long label with spaces, Some really long label with spaces," +
                " Some really long label with spaces, Some really long label with spaces," +
                " Some really long label with spaces"
        ).forEach(lb -> new TracingConfigurationCoordinates.Builder(TX).withLabel(lb).build());
    }

    /**
     * Ensure that it's possible to set any 0<= double <= 1 as sampling rate as part of TracingConfigurationParameters.
     */
    @Test
    public void testThatItsPossibleToSpecifyAnyDoubleBetweenZeroAndOneIncludingAsSamplingRate() {
        for (double validSamplingRate : new double[] {
            0,
            0.1,
            0.11,
            0.1234567890,
            1})
            new TracingConfigurationParameters.Builder().withSamplingRate(validSamplingRate).build();
    }

    /**
     * Ensure that in case of invalid sampling rate {@code IllegalArgumentException} is thrown with message "Specified
     * sampling rate=[invalidVal] has invalid value.Should be between 0 and 1 including boundaries."
     */
    @Test
    public void testThatItsPossibleToSpecifyOnlyValidSamplingRate() {
        for (Double invalidSamplingRate : new double[] {-1d, 10d}) {
            GridTestUtils.assertThrows(
                log,
                () -> new TracingConfigurationParameters.Builder().withSamplingRate(invalidSamplingRate).build(),
                IllegalArgumentException.class,
                "Specified sampling rate=[" + invalidSamplingRate +
                    "] has invalid value. Should be between 0 and 1 including boundaries.");
        }
    }

    /**
     * Ensure that it's possible to set any set of {@code Scope} as included scopes as part of
     * {@link TracingConfigurationParameters}.
     */
    @Test @SuppressWarnings("unchecked")
    public void testThatItsPossibleToSpecifyAnySetincludedScopesAsPartOfTracingConfigurationParameters() {
        for (Set<Scope> validincludedScopes : new Set[] {
            null,
            Collections.emptySet(),
            Collections.singleton(COMMUNICATION),
            new HashSet<>(Arrays.asList(COMMUNICATION, DISCOVERY, TX, EXCHANGE))})
            new TracingConfigurationParameters.Builder().withIncludedScopes(validincludedScopes).build();
    }
}


text:
using namespace led::widget;

BoxPort::BoxPort(QString const& name)
    : m_name(name)
{
    setPen(QPen(DefaultPen));
    setBrush(DefaultPen);
    setFlags(ItemIsSelectable);
    setAcceptHoverEvents(true);
}

void BoxPort::attach(BoxWidget *parent, int y_position)
{
    prepareGeometryChange();
    setParentItem(dynamic_cast<QGraphicsItem*>(parent));
    auto current_rectangle = rect();
    setRect(current_rectangle.x(), y_position, current_rectangle.width(), BoxPort::HEIGHT);
}

void BoxPort::updateSize(int x, int width)
{
    prepareGeometryChange();
    auto current_rectangle = rect();

    setRect(x, current_rectangle.y(), width, current_rectangle.height());
}

void BoxPort::hoverEnterEvent ( QGraphicsSceneHoverEvent * event )
{
    setPen(QPen(HoverPen));
    setBrush(HoverPen);
}

void BoxPort::hoverLeaveEvent ( QGraphicsSceneHoverEvent * event )
{
    setPen(QPen(DefaultPen));
    setBrush(DefaultPen);
}

 QRectF BoxPort::boundingRect() const
{
    auto crect = rect();
    crect.adjust(-MARGIN, -MARGIN, MARGIN, MARGIN);

    return crect;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace Core.Admin.Models.ManageViewModels
{
    public class ConfigureTwoFactorViewModel
    {
        public string SelectedProvider { get; set; }

        public ICollection<SelectListItem> Providers { get; set; }
    }
}


text:
using Genus.Migrator.Model;
using Genus.Migrator.Model.Builder;
using Moq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Xunit;

namespace Genus.Migrator.Tests.Model
{
    public class IndexBuilderTest
    {
        [Theory]
        [InlineData("a", new[] { "field"}, false)]
        [InlineData("a", new[] { "field", "field2"}, false)]
        public void build_index(string name, string[] fields, bool unique)
        {
            var tablebuilder = new TableBuilder();
            var target = new IndexBuilder();
            bool desc = false;
            foreach (var f in fields)
            {
                tablebuilder.Field(f).HasType(DbType.Int32);
                target.OnColumn(f, desc);
                desc = !desc;
            }
            if (unique)
                target.IsUnique();

            var res = target.Build(name, tablebuilder.Build("none", null));

            Assert.NotNull(res);
            Assert.Equal(name, res.DbName);
            Assert.Equal(fields.Length, res.Fields.Count());
            Assert.False(res.Fields.Select(_ => _.Field.ClrName).Except(fields).Any());
            Assert.Equal(unique, res.IsUnique);
        }

        [Fact]
        public void throw_if_fields_not_set()
        {
            var table = new Mock<ITable>().Object;
            var target = new IndexBuilder();

            Assert.Throws<InvalidOperationException>(()=>target.Build("name", table));
        }
    }
}


text:
#pragma once

#define PACKET_SIZE 1024

namespace kl {

class WritePacket {
public:
	WritePacket() {
		Clear();
	}

	int Size() const {
		return writePos;
	}

	void Clear() {
		memset( buffer, 0, PACKET_SIZE );
		writePos = 0;
		WriteHeader();
	}

	const char *Data() const {
		return buffer;
	}

	template <typename T>
	void WriteNative( const T &value ) {
		// Prevent overflow
		assert( writePos + sizeof( T ) <= PACKET_SIZE );

		// Convert T to char array
		union {
			T value;
			char data[sizeof( T )];
		} c;
		c.value = value;

		// Write data
		memcpy( buffer + writePos, c.data, sizeof( T ) );

		// Increment write position
		writePos += sizeof( T );
	}

	void WriteString( const char *msg ) {
		int length = ( int ) strlen( msg ) + 1;
		assert( writePos + length <= PACKET_SIZE );
		// Write data
		memcpy( buffer + writePos, msg, length );
		writePos += length;
	}

	void WriteHeader();

	void WriteU8( uint8_t value ) {
		WriteNative( value );
	}

	void WriteU16( uint16_t value ) {
		WriteNative( htons( value ) );
	}

	void WriteU32( uint32_t value ) {
		WriteNative( htonl( value ) );
	}

	void WriteU64( uint64_t value ) {
		WriteNative( htonll( value ) );
	}

	void WriteFloat( float value ) {
		WriteNative( htonf( value ) );
	}

	void WriteVec3( const glm::vec3 &vec ) {
		WriteFloat( vec.x );
		WriteFloat( vec.y );
		WriteFloat( vec.z );
	}

private:

	char buffer[PACKET_SIZE];
	int writePos;
};

class ReadPacket {
public:
	ReadPacket() {
		Clear();
	}

	void SetSize( int pos ) {
		this->size = pos;
	}

	size_t GetSize() const {
		return size;
	}

	size_t GetReadPos() const {
		return readPos;
	}

	void Clear() {
		memset( buffer, 0, PACKET_SIZE );
		size = 0;
		readPos = 0;
	}

	char *DataWritable() {
		return buffer;
	}

	/************************************************************************/
	/* Read                                                                 */
	// FIXME: Perhaps pass out variable by reference and return bool for success?
	/************************************************************************/
	uint8_t ReadU8() {
		return ReadNative<uint8_t>();
	}

	uint16_t ReadU16() {
		return ntohs( ReadNative<uint16_t>() );
	}

	uint32_t ReadU32() {
		return ntohl( ReadNative<uint32_t>() );
	}

	uint64_t ReadU64() {
		return ntohll( ReadNative<uint64_t>() );
	}

	float ReadFloat() {
		return ntohf( ReadNative<uint32_t>() );
	}

	void ReadString( char *dest ) {
		// strlen does not count \0, so we need to add 1 every time
		int length = ( int ) strlen( buffer + readPos ) + 1;
		memcpy( dest, buffer + readPos, length );
		readPos += length;
	}

	glm::vec2 ReadVec2() {
		float x = ReadFloat();
		float y = ReadFloat();
		return glm::vec2( x, y );
	}

	glm::vec3 ReadVec3() {
		float x = ReadFloat();
		float y = ReadFloat();
		float z = ReadFloat();
		return glm::vec3( x, y, z );
	}

	template <typename T>
	T ReadNative() {
		union coercion {
			T value;
			char data[sizeof( T )];
		};

		coercion c;

		memcpy( &c.data, buffer + readPos, sizeof( T ) );
		readPos += sizeof( T );

		return c.value;
	}

	void Print() {
		uint8_t *buf = ( uint8_t * ) buffer;
		for ( int i = 0; i < size; i++ ) {
			printf( "%02X ", buf[i] );
		}
		printf( "\n" );
	}

private:
	char buffer[PACKET_SIZE];
	int readPos; // Number of bytes already read
	int size; // Size of contents
};

class Address {
public:

	Address() :
		address( 0 ),
		port( 0 ) {}

#if 0
	Address( const char *address, unsigned short port ) {
		unsigned long addr;
		inet_pton( AF_INET, address, &addr );
		this->address = htonl( addr );
		this->port = port;
	}
#endif

	Address( unsigned char a, unsigned char b, unsigned char c, unsigned char d, unsigned short port ) :
		address( ( a << 24 ) | ( b << 16 ) | ( c << 8 ) | d ),
		port( port ) {}

	Address( unsigned int address, unsigned short port ) :
		address( address ),
		port( port ) {}

	unsigned int GetAddress() const {
		return address;
	}

	unsigned char GetA() const {
		return static_cast<uint8_t>( address >> 24 );
	}

	unsigned char GetB() const {
		return static_cast<uint8_t>( address >> 16 );
	}

	unsigned char GetC() const {
		return static_cast<uint8_t>( address >> 8 );
	}

	unsigned char GetD() const {
		return static_cast<uint8_t>( address );
	}

	unsigned short GetPort() const {
		return port;
	}

	bool operator == ( const Address &other ) const {
		return address == other.address && port == other.port;
	}

	bool operator != ( const Address &other ) const {
		return !( *this == other );
	}

	bool operator < ( const Address &other ) const {
		// note: this is so we can use address as a key in std::map
		if ( address < other.address )
			return true;
		if ( address > other.address )
			return false;
		else
			return port < other.port;
	}

private:

	unsigned int address;
	unsigned short port;
};

// RAII implementation of a UDP socket
class Socket {
public:

	Socket() {
		socket = 0;
	}

	~Socket() {
		Close();
	}

	bool Open( unsigned short port ) {
		assert( !IsOpen() );

		// create socket

		// ::socket is a WinSock2 function
		socket = ::socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );

		if ( socket <= 0 ) {
			printf( "Network: failed to create socket\n" );
			socket = 0;
			return false;
		}

		// bind to port

		sockaddr_in address;
		address.sin_family = AF_INET;
		address.sin_addr.s_addr = INADDR_ANY;
		address.sin_port = htons( port );

		if ( bind( socket, ( const sockaddr * ) &address, sizeof( sockaddr_in ) ) < 0 ) {
			printf( "Network: failed to bind socket\n" );
			Close();
			return false;
		}

		// set non-blocking io
		DWORD nonBlocking = 1;
		if ( ioctlsocket( socket, FIONBIO, &nonBlocking ) != 0 ) {
			printf( "Network: failed to set non-blocking socket\n" );
			Close();
			return false;
		}

		return true;
	}

	void Close() {
		if ( socket != 0 ) {
			closesocket( socket );
			socket = 0;
		}
	}

	bool IsOpen() const {
		return socket != 0;
	}

	bool Send( const Address &destination, const WritePacket &packet );

	int Receive( Address &sender, ReadPacket &packet ) {
		if ( socket == 0 )
			return false;

		sockaddr_in from;
		socklen_t fromLength = sizeof( from );

		int received_bytes = recvfrom( socket, packet.DataWritable(), PACKET_SIZE, 0, ( sockaddr * ) &from, &fromLength );
		packet.SetSize( received_bytes );

		if ( received_bytes <= 0 )
			return 0;

		unsigned int address = ntohl( from.sin_addr.s_addr );
		unsigned short port = ntohs( from.sin_port );

		sender = Address( address, port );

		return received_bytes;
	}

private:
	SOCKET socket;
};

class PacketHandler;

class Connection {
public:

	enum Mode {
		None,
		Client,
		Server
	};

	Connection() {}

	Connection( unsigned int protocolId, float timeout ) {
		this->protocolId = protocolId;
		this->timeout = timeout;
		mode = None;
		running = false;
		ClearData();
	}

	~Connection() {
		if ( running )
			Stop();
	}

	bool Start( unsigned short port ) {
		if ( running ) {
			Stop();
		}
		if ( !socket.Open( port ) )
			return false;
		running = true;
		return true;
	}

	void Stop() {
		assert( running );
		printf( "Network: stop connection\n" );
		mode = None;
		ClearData();
		socket.Close();
		running = false;
	}

	void Listen() {
		ClearData();
		mode = Server;
		state = Listening;
	}

	void Connect( const Address &address ) {
		printf( "Network: client connecting to %d.%d.%d.%d:%d\n",
				address.GetA(), address.GetB(), address.GetC(), address.GetD(), address.GetPort() );
		ClearData();
		mode = Client;
		state = Connecting;
		this->address = address;
		recipients[address] = ClientInfo();
	}

	bool IsConnecting() const {
		return state == Connecting;
	}

	bool ConnectFailed() const {
		return state == ConnectFail;
	}

	bool IsConnected() const {
		return state == Connected;
	}

	bool IsListening() const {
		return state == Listening;
	}

	Mode GetMode() const {
		return mode;
	}

	void Update( float deltaTime );

	bool SendPackets() {
		switch ( mode ) {
		case Client:
		case Server: {
			bool success = false;
			if ( running ) {
				for ( auto &pair : recipients ) {
					if ( socket.Send( pair.first, pair.second.packet ) ) {
						success = true;
					}
				}
			} else return false;
			return success;
			break;
		}
		default:
			return false;
			break;
		}
	}

	int ReceivePacket( Address &sender, ReadPacket &packet );

	void SetPacketHandler( PacketHandler *handler ) {
		this->packetHandler = handler;
	}

	void WriteString( const Address &address, const char *msg ) {
		recipients[address].packet.WriteString( msg );
	}

	template <typename T>
	void WriteNative( const Address &address, const T &value ) {
		recipients[address].packet.WriteNative( value );
	}

	void WriteString( const char *msg ) {
		for ( auto &pair : recipients ) {
			pair.second.packet.WriteString( msg );
		}
	}

	template <typename T>
	void WriteNative( const T &value ) {
		for ( auto &pair : recipients ) {
			pair.second.packet.WriteNative( value );
		}
	}

	void ClearPackets();
protected:

	void ClearData() {
		state = Disconnected;
		timeoutAccumulator = 0.0f;
		address = Address();
#if 1
		recipients.clear();
#endif
	}
private:

	enum State {
		Disconnected,
		Listening,
		Connecting,
		ConnectFail,
		Connected
	};

	struct ClientInfo {
		State state = Disconnected;
		float timeoutAccumulator = 0.0f;
		WritePacket packet;
	};

	unsigned int protocolId;
	float timeout;

	bool running;
	Mode mode;
	State state;
	Socket socket;

	float timeoutAccumulator;
	Address address;
	std::map<Address, ClientInfo> recipients;
	PacketHandler *packetHandler = nullptr;
}; // !class Connection

class PacketHandler;
class NetworkManager {
public:
	static void Init();
	static void Update();
	static void Destroy();

	static void StartServer();
	static void StartClient( const char *address );
	static Connection::Mode GetMode() { return connection.GetMode(); }
	static bool IsServer();
	static void SetPacketHandler( PacketHandler *handler ) { packetHandler = handler; connection.SetPacketHandler( handler ); }
	static void Send();
	static bool IsConnected() { return connection.IsConnected(); }

	/************************************************************************/
	/* Write                                                                */
	/************************************************************************/
	static void WriteU8( const Address &address, uint8_t value ) {
		connection.WriteNative( address, value );
	}

	static void WriteU16( const Address &address, uint16_t value ) {
		connection.WriteNative( address, htons( value ) );
	}

	static void WriteU32( const Address &address, uint32_t value ) {
		connection.WriteNative( address, htonl( value ) );
	}

	static void WriteU64( const Address &address, uint64_t value ) {
		connection.WriteNative( address, htonll( value ) );
	}

	static void WriteFloat( const Address &address, float value ) {
		connection.WriteNative( address, htonf( value ) );
	}

	static void WriteString( const Address &address, const char *msg ) {
		connection.WriteString( address, msg );
	}

	static void WriteVec3( const Address &address, const glm::vec3 &vec ) {
		WriteFloat( address, vec.x );
		WriteFloat( address, vec.y );
		WriteFloat( address, vec.z );
	}

	static void WriteVec2( const Address &address, const glm::vec2 &vec ) {
		WriteFloat( address, vec.x );
		WriteFloat( address, vec.y );
	}

	/************************************************************************/
	/* BROADCAST                                                            */
	/************************************************************************/

	static void BroadcastU8( uint8_t value ) {
		connection.WriteNative( value );
	}

	static void BroadcastU16( uint16_t value ) {
		connection.WriteNative( htons( value ) );
	}

	static void BroadcastU32( uint32_t value ) {
		connection.WriteNative( htonl( value ) );
	}

	static void BroadcastU64( uint64_t value ) {
		connection.WriteNative( htonll( value ) );
	}

	static void BroadcastFloat( float value ) {
		connection.WriteNative( htonf( value ) );
	}

	static void BroadcastString( const char *msg ) {
		connection.WriteString( msg );
	}

	static void BroadcastVec3( const glm::vec3 &vec ) {
		BroadcastFloat( vec.x );
		BroadcastFloat( vec.y );
		BroadcastFloat( vec.z );
	}

	static void BroadcastVec2( const glm::vec2 &vec ) {
		BroadcastFloat( vec.x );
		BroadcastFloat( vec.y );
	}

	static void ResetCounters() {
		numBytesSentInclusive = 0;
		numBytesSentExclusive = 0;
	}

	static void IncrementBytesSentInclusive(int numBytes) {
		numBytesSentInclusive += numBytes;
	}

	static void IncrementBytesSentExclusive(int numBytes) {
		numBytesSentExclusive += numBytes;
	}
	static void PrintCounters() {
		printf("numBytesSentInclusive: %d\n", numBytesSentInclusive);
		printf("numBytesSentExclusive: %d\n", numBytesSentExclusive);
	}
private:
	static bool shouldSend;
	static float time;
	static Connection connection;
	static bool connected;
	static PacketHandler *packetHandler;

	static int64_t numBytesSentInclusive;
	static int64_t numBytesSentExclusive;
};
}


text:
module USPS::Request
  class DeliveryConfirmation < Base
    config(
      :api => 'DeliveryConfirmationV3',
      :tag => 'DeliveryConfirmationV3.0Request',
      :response => USPS::Response::DeliveryConfirmation
    )

    attr_reader :to, :from, :weight, :options, :format

    DEFAULTS = {
      :type    => 1,
      :format  => 'TIF',
      :service => 'Priority'
    }.freeze

    # List of valid options and their mapping to their tag
    OPTIONS = {
      :type               => 'Option',
      :service            => 'ServiceType',
      :po_zip_code        => 'PoZipCode',
      :label_date         => 'LabelDate',
      :customer_reference => 'CustomerRefNo',
      :separate_receipt   => 'SeparateReceiptPage',
      :address_service    => 'AddressServiceRequested',
      :sender_name        => 'SenderName',
      :sender_email       => 'SenderEMail',
      :recipient_name     => 'RecipientName',
      :recipient_email    => 'RecipientEMail'
    }.freeze

    FORMATS = %w(TIF PDF).freeze

    # === Options:
    # * <tt>:
    def initialize(to, from, weight, options = {})
      @to = to
      @from = from
      @weight = weight
      @options = DEFAULTS.merge(options)

      @type = @options.delete(:type)
      self.format = @options.delete(:format)
    end

    def format=(format)
      format = format.upcase

      unless(FORMATS.include?(format))
        raise ArgumentError, "Format must be one of #{FORMATS.join(',')}"
      end

      @format = format.upcase
    end

    def build
      super do |builder|
        builder.tag!('Option', @type)
        builder.tag!('ImageParameters')

        [
          [self.from, 'From'],
          [self.to,   'To']
        ].each do |address, prefix|
          builder.tag!("#{prefix}Name",  address.name)
          builder.tag!("#{prefix}Firm",  address.company)
          builder.tag!("#{prefix}Address1", address.extra_address)
          builder.tag!("#{prefix}Address2", address.address)
          builder.tag!("#{prefix}City",  address.city)
          builder.tag!("#{prefix}State", address.state)
          builder.tag!("#{prefix}Zip5",  address.zip5)
          builder.tag!("#{prefix}Zip4",  address.zip4)
        end

        builder.tag!('WeightInOunces', self.weight)

        @options.each_pair do |k,v|
          OPTIONS[k].tap do |tag|
            builder.tag!(tag, v.to_s) if tag
          end
        end

        builder.tag!('ImageType', @format)
      end
    end
  end
end


text:
import { Directive, ElementRef, AfterViewInit } from '@angular/core';

@Directive({
  selector: 'code[highlight]'
})
export class HightlightDirective implements AfterViewInit {

  constructor(private elementRef: ElementRef) {
  }

  ngAfterViewInit() {
    try {
      let hljs: any = window['hljs'];
      if (hljs) {
        hljs.highlightBlock(this.elementRef.nativeElement);
      }
    } catch (err) {
      console.log(err);
    }
  }
}


text:
Atom K
======

A documentation prototype for next generation messaging

Core concepts
-------------

* Interoperability
  * A general messaging interface for messaging systems, not just email. Twitter, facebook, et al. should be optional means for messaging.
  * Backwards compatible with email.
* Messages and calendar events are one in the same.
  * Time has proven that email and calendar need to consistently work together, so why should their particles be different things?
* Supports the sending of HTML5 content.
* Possibility for a commercial standard in addition to open standard, just as Twitter is the commercial standard for tweets.
* Streams as subscribable endpoints
  * Replaces the awkwardness of periodical emails.
  * Vendors can write periodicals to streams, which users can attach (subscribe) to or detach (unsubscribe) from.

Syntax
------

Slashes (/) are used for separating a user from the domain, just as email separates with an @.
* to: john/example.com
* to: jane.doe/example.com
* to: alex-miller/example.com

For the commercial standard, user could use extensionless domains
* to: john/example
* to: jane.doe/example
* to: alex-miller/example
* The owner of example.com would need to successfully register "example" as a domain in the commercial application.

3rd party non-email messaging systems tap into the "@" prefix
* to: @username/twitter.com
* Default domains can be set via client app to omit the domain
  * to: @username

Message Types
-------------

      Example Subject
      Email Type
      Email Meta Keyword

      "Hi, Sweetie"
      Message
      None, default

      "Charity News Weekly"
      Periodical
      periodical

      "Confirm your registration"
      Account-Website Handshake
      handshake

      "Payment Accepted"
      Read-only notification
      notification

      "Note to self"
      Personal note, file, or snippet sent to self to be saved or transfered between devices
      storage

How this is solved
------------------

    <meta
      name="email-handshake"
      content="
        description: 'Please confirm your account with Lab95',
        url: 'http://lab95.com/confirm/SX29Sfd948dfjWss301LK'
      "
    >

    <meta name="email-meta-version" content="0.9.0">

With a simple <meta> tag denoting the type of email, email programs can sort by this universal protocol.
Read-only messages can be put in little dialogue boxes. Periodicals can be grouped into newsstand organizers.
It's really up to the email client.

Why would anyone do this?
-------------------------

- Better for senders
- Better for users
- Backwards compatible
- Unobtrusive
- Pretty cool implications (below)

Greater visibility is a collary of better organization.
A sender including this meta tag isn't necessary, but would move their message into the user's field of relevance.
And, of course, it's better for the user that emails are put into context. Instead of relying on an email program that
"sniffs" the content of the email to guess a proper category, each message can register itself to the right place.
Because this is valid usage of HTML meta data, it's unobtrusive and
shows itself only to the discretion of the email client.

Potential User Experience Improvements
--------------------------------------

Here are some ideas for ways email clients could take advantage of the syntax:

periodicals can be set to automatically archive all but the last unread.

Emailing a photo to oneself could automatically be sent to a companion online storage folder, instead of mixed in with other messages and junk mail.

handshake emails could prompt desktop clients to open a UI element such as a Growl message to take the user right to the confirmation page. No need to check the email itself

Different types can be sorted into respective feeds. This means you can read through all your periodicals on the subway, your messages at work, and clear all notifications at once.

Unsubscription to newsletters can be delegated to an actual UI element in the client program. On the same token, being less annoying, users will be less likely to want to unsubscribe.

Where to go from here?
----------------------

This is an open source project made for the advancement of humankind.
It's a simple two way street: Email senders can start writing this meta data automatically. Email clients can impress their users with the ability to read these kind of emails.
Just use the syntax in the API document of this repo.

Contributing
------------

This branch is a starting point. Please send pull request to the 1.0 branch
where a stable version of the API is in the works. Senders and sendees can
still use 0.9.0 but should version using ``email-meta-version``. (See API.md)


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="ivy-report.xsl"?>
<ivy-report version="1.0">
	<info
		organisation="mongo-app"
		module="mongo-app_2.10"
		revision="1.0-SNAPSHOT"
		conf="atmos-sigar"
		confs="compile, runtime, test, provided, optional, compile-internal, runtime-internal, test-internal, plugin, sources, docs, pom, scala-tool, atmos-trace-compile, atmos-trace-test, atmos-dev, atmos-console, atmos-weave, atmos-sigar"
		date="20140312010527"/>
	<dependencies>
		<module organisation="com.typesafe.atmos" name="atmos-sigar-libs">
			<revision name="1.3.1" status="release" pubdate="20131001165510" resolver="sbt-chain" artresolver="sbt-chain" homepage="" downloaded="false" searched="false" default="false" conf="default(compile), default, compile, runtime, master" position="0">
				<metadata-artifact status="no" details="" size="2245" time="0" location="/home/dev/Downloads/play-2.2.2/repository/cache/com.typesafe.atmos/atmos-sigar-libs/ivy-1.3.1.xml" searched="false" origin-is-local="false" origin-location="http://repo.typesafe.com/typesafe/releases/com/typesafe/atmos/atmos-sigar-libs/1.3.1/atmos-sigar-libs-1.3.1.pom"/>
				<caller organisation="mongo-app" name="mongo-app_2.10" conf="atmos-sigar" rev="1.3.1" rev-constraint-default="1.3.1" rev-constraint-dynamic="1.3.1" callerrev="1.0-SNAPSHOT"/>
				<artifacts>
					<artifact name="atmos-sigar-libs" type="jar" ext="jar" status="no" details="" size="2099397" time="0" location="/home/dev/Downloads/play-2.2.2/repository/cache/com.typesafe.atmos/atmos-sigar-libs/jars/atmos-sigar-libs-1.3.1.jar">
						<origin-location is-local="false" location="http://repo.typesafe.com/typesafe/releases/com/typesafe/atmos/atmos-sigar-libs/1.3.1/atmos-sigar-libs-1.3.1.jar"/>
					</artifact>
				</artifacts>
			</revision>
		</module>
	</dependencies>
</ivy-report>


text:
"""Exceptions raised by this package."""

class ARPAException(Exception):
    """Common base class for all package exceptions."""

    pass

class FatalException(ARPAException):
    """This should not have happened."""

    pass

class FrozenException(ARPAException):
    """Language model is frozen."""

    pass

class ParseException(ARPAException):
    """ARPA file could not be parsed."""

    pass


text:
package org.jgroups.protocols;

import org.jgroups.*;
import org.jgroups.protocols.pbcast.NAKACK2;
import org.jgroups.util.Digest;
import org.jgroups.util.TimeScheduler;
import org.jgroups.util.TimeScheduler3;
import org.jgroups.util.Util;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.concurrent.TimeoutException;

/**
 * Tests setting of digest NAKACK.down(SET_DIGEST), JIRA issue is https://jira.jboss.org/jira/browse/JGRP-1060
 * @author Bela Ban
 */
@Test(groups=Global.FUNCTIONAL)
public class NAKACK_SET_DIGEST_Test {
    private NAKACK2   nak;
    private Digest    d1, d2;
    private Address   a, b, c;
    private View      v1, v2;

    private static final short TP_ID=101;

    @BeforeMethod
    protected void setUp() throws Exception {
        a=Util.createRandomAddress("A");
        b=Util.createRandomAddress("B");
        c=Util.createRandomAddress("C");
        v1=View.create(a, 1, a, b);
        v2=View.create(a, 2, a, b, c);

        nak=new NAKACK2();
        d1=new Digest(v1.getMembersRaw(), new long[]{11,11, 30,35});
        d2=new Digest(v2.getMembersRaw(), new long[]{10,10, 30,30, 50,50});

        TP transport=new TP() {
            public boolean supportsMulticasting() {return false;}
            public void sendMulticast(byte[] data, int offset, int length) throws Exception {}
            public void sendUnicast(PhysicalAddress dest, byte[] data, int offset, int length) throws Exception {}
            public String getInfo() {return null;}
            public Object down(Event evt) {return null;}
            public Object down(Message msg) {return null;}
            protected PhysicalAddress getPhysicalAddress() {return null;}
            public TimeScheduler getTimer() {return new TimeScheduler3();}
        };
        transport.setId(TP_ID);
        nak.setDownProtocol(transport);
        nak.start();
    }

    @AfterMethod
    protected void tearDown() {
        nak.stop();
    }

    public void testSetDigest() throws TimeoutException {
        System.out.println("d1: " + d1);
        System.out.println("d2: " + d2);

        System.out.println("setting d2:");
        nak.down(new Event(Event.SET_DIGEST, d2));
        Digest digest=(Digest)nak.down(Event.GET_DIGEST_EVT);
        System.out.println("digest = " + digest);
        assert digest.capacity() == 3;
        assert digest.containsAll(a, b, c);

        System.out.println("setting d1:");
        nak.down(new Event(Event.SET_DIGEST, d1));
        digest=(Digest)nak.down(Event.GET_DIGEST_EVT);
        System.out.println("digest = " + digest);
        assert digest.capacity() == 3; // https://jira.jboss.org/jira/browse/JGRP-1060
        assert digest.containsAll(a, b, c);
    }

}


text:
#include "stm32f10x_rcc.h"
#include "stm32f10x_nvic.h"
#include "stm32f10x_exti.h"
#include "stm32f10x_gpio.h"
#include "gpio.h"

//=========================== defines =========================================

//=========================== variables =======================================

//=========================== public ===========================================
/**
  * @brief  Configures the different GPIO ports as Analog Inputs.
  * @param  None
  * @retval : None
  */
void GPIO_Config_ALL_AIN(void)
{
  GPIO_InitTypeDef GPIO_InitStructure;

  /* Enable GPIOD and GPIOE clock */
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB
                         | RCC_APB2Periph_GPIOC | RCC_APB2Periph_GPIOD
                         | RCC_APB2Periph_AFIO, ENABLE);

    /* PA  */
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
  GPIO_Init(GPIOA, &GPIO_InitStructure);
      /* PB  */
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
  GPIO_Init(GPIOB, &GPIO_InitStructure);
      /* PC  */
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
  GPIO_Init(GPIOC, &GPIO_InitStructure);
        /* PD  */
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
  GPIO_Init(GPIOD, &GPIO_InitStructure);
}

/**
  * @brief  Configures the GPIO PD0.2 port.
  * @param  None
  * @retval : None
  */
void GPIO_Configuration(void)
{
  GPIO_InitTypeDef GPIO_InitStructure;

  /* Enable GPIOD clock */
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE);

  /* Configure PD.02 as Output push-pull 50MHz */
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
  GPIO_Init(GPIOD, &GPIO_InitStructure);

    /* Enable GPIOC clock */
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);

  /* Configure PC.04 as Output push-pull 50MHz */
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
  GPIO_Init(GPIOC, &GPIO_InitStructure);

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: boshurik
 * Date: 15.02.16
 * Time: 13:37
 */

namespace BoShurik\Payum\YandexMoney\Action;

use Payum\Core\Action\ActionInterface;
use Payum\Core\Request\GetStatusInterface;
use Payum\Core\Bridge\Spl\ArrayObject;
use Payum\Core\Exception\RequestNotSupportedException;
use BoShurik\Payum\YandexMoney\Api;

class StatusAction implements ActionInterface
{
    /**
     * {@inheritDoc}
     *
     * @param GetStatusInterface $request
     */
    public function execute($request)
    {
        RequestNotSupportedException::assertSupports($this, $request);

        $model = ArrayObject::ensureArrayObject($request->getModel());

        if (!isset($model[Api::FIELD_STATUS]) || Api::STATUS_NEW == $model[Api::FIELD_STATUS]) {
            $request->markNew();

            return;
        }

        if (Api::STATUS_PENDING == $model[Api::FIELD_STATUS]) {
            $request->markPending();

            return;
        }

        if (Api::STATUS_CAPTURED == $model[Api::FIELD_STATUS]) {
            $request->markCaptured();

            return;
        }

        $request->markUnknown();
    }

    /**
     * {@inheritDoc}
     */
    public function supports($request)
    {
        return
            $request instanceof GetStatusInterface &&
            $request->getModel() instanceof \ArrayAccess
        ;
    }
}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="48dp"
    android:height="48dp"
    android:viewportWidth="48"
    android:viewportHeight="48"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M18,35.7 L6.3,24 18,12.25 28.6,22.9H42.9V25.1H28.6Z"/>
</vector>


text:
#import "NSObject.h"

// Not exported
@interface OADPathElement : NSObject
{
}

@end


text:
package com.atomikos.jms;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.XATopicConnectionFactory;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.atomikos.datasource.TransactionalResource;
import com.atomikos.datasource.xa.DefaultXidFactory;
import com.atomikos.datasource.xa.XidFactory;
import com.atomikos.icatch.system.Configuration;

/**
 *
 *
 * Use this class to access JMS topics within your JTA transactions: rollback of
 * the transaction will also cancel any messages sent or received. Instances of
 * this class need a JMS vendor-specific instance of XATopicConnectionFactory to
 * work with. Check your JMS-vendor's documentation on how to do that. Instances
 * can be set up in a GUI wizard tool and saved on disk or in JNDI. No explicit
 * registration with the transaction engine is necessary: this class does
 * everything automatically. As soon as an instance is created, it is fully
 * capable of interacting with the Atomikos transaction manager, and will
 * transparently take part in active transactions.
 *
 *

 * Note: any property changes made AFTER getting the first connection
 * will NOT have any effect!
 *

 * Topic functionality in this product was sponsored by Webtide.
 */

public class TopicConnectionFactoryBean
extends AbstractConnectionFactoryBean
implements TopicConnectionFactory
{
	private transient JtaTopicConnectionFactory factory_;

	private XATopicConnectionFactory xaFactory_;
	//where to get the XA connections from

	   protected synchronized void checkSetup () throws JMSException
	    {
	        factory_ = JtaTopicConnectionFactory.getInstance ( resourceName_ );

	        if ( factory_ != null )
	            return;
	        else {
	            // ONLY attempt getOrCreate if getInstance fails; to avoid
	            // overhead of synchronization of getOrCreate

	            XidFactory xidFactory = null;

	            xidFactory = new DefaultXidFactory ();

	            if ( xaFactory_ == null && "".equals ( xaFactoryJndiName_ ) )
	                throw new JMSException (
	                        "TopicConnectionFactoryBean: XATopicConnectionFactory not set?" );
	            if ( !"".equals ( xaFactoryJndiName_ ) ) {
	                try {

	                    // lookup factory in JNDI
	                    Context ctx = new InitialContext ();
	                    Context env = (Context) ctx.lookup ( "java:comp/env" );
	                    xaFactory_ = (XATopicConnectionFactory) env
	                            .lookup ( xaFactoryJndiName_ );

	                } catch ( NamingException ne ) {
	                    throw new JMSException (
	                            "TopicConnectionFactoryBean: error retrieving factory: "
	                                    + ne.getMessage () );
	                }
	            }

	            factory_ = JtaTopicConnectionFactory.getOrCreate ( resourceName_,
	                    xaFactory_, xidFactory );
	            TransactionalResource res = factory_.getTransactionalResource ();
	            if ( Configuration.getResource ( res.getName () ) == null )
	                Configuration.addResource ( res );

	            StringBuffer msg = new StringBuffer();
	            msg.append ( "TopicConnectionFactoryBean configured with [" );
	            msg.append ( "resourceName=" ).append(resourceName_).append (", ");
	            msg.append ( "xaFactoryJndiName=" ).append( xaFactoryJndiName_ );
	            msg.append ( "]" );
	            Configuration.logDebug ( msg.toString() );

	            Configuration.logWarning ( "WARNING: class " + getClass().getName() + " is deprecated!" );
	        }
	    }

    /**
     * Sets the XATopicConnectionFactory to use.
     * This method is optional and an
     * alternative to setXaFactoryJndiName.
     *
     * @param xaFactory
     *            The object to use.
     */

	public void setXaTopicConnectionFactory ( XATopicConnectionFactory factory )
	{
		this.xaFactory_ = factory;
	}

    /**
     * Get the XATopicConnectionFactory as previously set.
     *
     * @return XATopicConnectionFactory The factory, or null if only the JNDI
     *         name was set.
     */

	public XATopicConnectionFactory getXaTopicConnectionFactory()
	{
		return xaFactory_;
	}

	/**
	 * Creates a default topic connection.
	 */
	public TopicConnection createTopicConnection() throws JMSException
	{
		checkSetup ();
        return factory_.createTopicConnection ();
	}

	/**
	 * Creates a topic connection with given user credentials.
	 */
	public TopicConnection createTopicConnection (
			String userName , String password )
			throws JMSException
	{
		checkSetup ();
        return factory_.createTopicConnection ( userName , password );
	}

	/**
	 * Creates a default connection.
	 */
	public Connection createConnection() throws JMSException
	{
		return createTopicConnection();
	}

	/**
	 * Creates a default connection with given user credentials.
	 */
	public Connection createConnection (
			String userName , String password )
			throws JMSException
	{
		return createTopicConnection ( userName , password );
	}

	public boolean equals ( Object o )
	{
		boolean ret = false;
		if ( o instanceof TopicConnectionFactoryBean ) {
			TopicConnectionFactoryBean other = ( TopicConnectionFactoryBean ) o;
			if ( resourceName_ != null ) {
				ret = resourceName_.equals( other.resourceName_ );
			}
			else {
				//without a resource name we can't compare here
				ret = super.equals ( o );
			}
		}
		return ret;
	}

	public int hashCode()
	{
		int ret = 0;
		if ( resourceName_ != null ) ret = resourceName_.hashCode();
		else ret = super.hashCode();
		return ret;
	}

}


text:
namespace blink {

std::ostream& operator<<(std::ostream& out, const StyleDifference& diff) {
  out << "StyleDifference{layoutType=";

  switch (diff.layout_type_) {
    case StyleDifference::kNoLayout:
      out << "NoLayout";
      break;
    case StyleDifference::kPositionedMovement:
      out << "PositionedMovement";
      break;
    case StyleDifference::kFullLayout:
      out << "FullLayout";
      break;
    default:
      NOTREACHED();
      break;
  }

  out << ", collectInlines=" << diff.needs_collect_inlines_;
  out << ", reshape=" << diff.needs_reshape_;
  out << ", paintInvalidation=" << diff.needs_paint_invalidation_;
  out << ", recomputeVisualOverflow=" << diff.recompute_visual_overflow_;
  out << ", visualRectUpdate=" << diff.visual_rect_update_;

  out << ", propertySpecificDifferences=";
  int diff_count = 0;
  for (int i = 0; i < StyleDifference::kPropertyDifferenceCount; i++) {
    unsigned bit_test = 1 << i;
    if (diff.property_specific_differences_ & bit_test) {
      if (diff_count++ > 0)
        out << "|";
      switch (bit_test) {
        case StyleDifference::kTransformChanged:
          out << "TransformChanged";
          break;
        case StyleDifference::kOpacityChanged:
          out << "OpacityChanged";
          break;
        case StyleDifference::kZIndexChanged:
          out << "ZIndexChanged";
          break;
        case StyleDifference::kFilterChanged:
          out << "FilterChanged";
          break;
        case StyleDifference::kBackdropFilterChanged:
          out << "BackdropFilterChanged";
          break;
        case StyleDifference::kCSSClipChanged:
          out << "CSSClipChanged";
          break;
        case StyleDifference::kTextDecorationOrColorChanged:
          out << "TextDecorationOrColorChanged";
          break;
        case StyleDifference::kBlendModeChanged:
          out << "BlendModeChanged";
          break;
        default:
          NOTREACHED();
          break;
      }
    }
  }

  out << ", scrollAnchorDisablingPropertyChanged="
      << diff.scroll_anchor_disabling_property_changed_;

  return out << "}";
}

}  // namespace blink


text:
package scouter.server.netio.service.handle;

import scouter.io.DataInputX
import scouter.io.DataOutputX
import scouter.lang.pack.MapPack
import scouter.lang.pack.StatusPack
import scouter.net.TcpFlag
import scouter.server.db.StatusRD
import scouter.server.netio.service.anotation.ServiceHandler
import scouter.util.DateUtil
import scouter.net.RequestCmd

class StatusService {

  @ServiceHandler(RequestCmd.STATUS_AROUND_VALUE)
  def statusAroundValue(din: DataInputX, dout: DataOutputX, login: Boolean): Unit = {
    val param = din.readPack().asInstanceOf[MapPack];
    val objHash = param.getInt("objHash");
    val key = param.getText("key");
    val time = param.getLong("time");

    val date = DateUtil.yyyymmdd(time);

    val handler = (time: Long, data: Array[Byte]) => {
      val pk = new DataInputX(data).readPack().asInstanceOf[StatusPack];
        if (pk.key == key && pk.objHash == objHash) {
          dout.writeByte(TcpFlag.HasNEXT);
          dout.writePack(pk);
          return
        }
    }
    StatusRD.readByTime(date, time, time + DateUtil.MILLIS_PER_MINUTE, handler);
  }
}


text:
/*
 * decaffeinate suggestions:
 * DS102: Remove unnecessary code created because of implicit returns
 * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
 */
const _ = require("underscore")
const benv = require("benv")
const sinon = require("sinon")
const Backbone = require("backbone")
const CurrentUser = require("../../../models/current_user")
const Artwork = require("../../../models/artwork.coffee")
const Artworks = require("../../../collections/artworks.coffee")
const { fabricate } = require("@artsy/antigravity")
const { resolve } = require("path")

let ArtworkColumnsView = null

xdescribe("ArtworkColumns", function () {
  before(done =>
    benv.setup(function () {
      benv.expose({
        $: benv.require("jquery"),
        jQuery: benv.require("jquery"),
      })
      ArtworkColumnsView = benv.requireWithJadeify(
        resolve(__dirname, "../view"),
        ["artworkColumns", "artworkItem"]
      )
      Backbone.$ = $
      return done()
    })
  )

  after(() => benv.teardown())

  beforeEach(function () {
    this.artworks = new Artworks([
      new Artwork(fabricate("artwork")),
      new Artwork(fabricate("artwork")),
      new Artwork(fabricate("artwork")),
      new Artwork(fabricate("artwork")),
      new Artwork(fabricate("artwork")),
      new Artwork(fabricate("artwork")),
      new Artwork(fabricate("artwork")),
      new Artwork(fabricate("artwork")),
    ])

    return (this.view = new ArtworkColumnsView({
      el: $("body"),
      collection: this.artworks,
      user: new CurrentUser(),
    }))
  })

  describe("#initialize", () =>
    it("sets up internal state", function () {
      sinon
        .stub(CurrentUser, "orNull")
        .returns(new CurrentUser(fabricate("user")))
      this.view.seeMore.should.be.false()
      this.view.columns[0].should.have.property("height")
      this.view.columns[0].should.have.property("artworkCount")
      return CurrentUser.orNull.restore()
    }))

  describe("#length", () =>
    it("reports the number of rendered elements", function () {
      this.view.length().should.equal(0)
      this.view.appendArtworks(
        _.times(4, () => new Artwork(fabricate("artwork")))
      )
      this.view.length().should.equal(4)
      this.view.appendArtworks(
        _.times(4, () => new Artwork(fabricate("artwork")))
      )
      return this.view.length().should.equal(8)
    }))

  describe("#_columnWidth", function () {
    beforeEach(() => sinon.stub($.fn, "width").returns(1280))

    afterEach(() => $.fn.width.restore())

    return it("total width of columns should be less than container width", function () {
      const totalWidth =
        this.view._columnWidth() * this.view.numberOfColumns +
        (this.view.numberOfColumns - 1) * this.view.gutterWidth
      return totalWidth.should.be.below(this.view.$el.width())
    })
  })

  describe("#setUserSavedArtworks", function () {
    describe("with a current user", () =>
      it("inits the saved artworks collection", function () {
        sinon
          .stub(CurrentUser, "orNull")
          .returns(new CurrentUser(fabricate("user")))
        this.view = new ArtworkColumnsView({
          el: $("body"),
          collection: this.artworks,
        })
        this.view.currentUser.should.be.instanceOf(CurrentUser)
        this.view.artworkCollection.should.be.ok()
        return CurrentUser.orNull.restore()
      }))

    return describe("without a current user", () =>
      it("leaves the collection undefined", function () {
        _.isNull(this.view.currentUser).should.be.true()
        return _.isUndefined(this.view.artworkCollection).should.be.true()
      }))
  })

  describe("#rebalance", () =>
    beforeEach(function () {
      // Create a short left column
      const dims = [
        { original_width: 900, original_height: 200, aspect_ratio: 4.5 }, // col 1, 200
        { original_width: 900, original_height: 900, aspect_ratio: 1 }, // col 2, 900
        { original_width: 200, original_height: 900, aspect_ratio: 0.222 }, // col 3, 900
        { original_width: 1000, original_height: 200, aspect_ratio: 5 }, // col 1, 400
        { original_width: 1100, original_height: 900, aspect_ratio: 1.222 }, // col 1, 1300
        { original_width: 600, original_height: 900, aspect_ratio: 0.667 }, // col 2, 1800
        { original_width: 600, original_height: 900, aspect_ratio: 0.6667 }, // col 3, 1800
        { original_width: 700, original_height: 200, aspect_ratio: 3.5 }, // col 1, 1500
      ]
      this.artworks.each((artwork, index) =>
        _.extend(artwork.get("images")[0], dims[index])
      )
      $("body").empty()
      this.view = new ArtworkColumnsView({
        el: $("body"),
        collection: this.artworks,
        isOrdered: true,
        allowDuplicates: true,
      })

      return it("removes artworks from the last column and redistributes to the shortest column", function () {
        $(".artwork-column:eq(0) .artwork-item").should.have.lengthOf(3)
        $(".artwork-column:eq(1) .artwork-item").should.have.lengthOf(3)
        $(".artwork-column:eq(2) .artwork-item").should.have.lengthOf(2)
        this.view.rebalance(800, 2)
        $(".artwork-column:eq(0) .artwork-item").should.have.lengthOf(4)
        $(".artwork-column:eq(1) .artwork-item").should.have.lengthOf(3)
        return $(".artwork-column:eq(2) .artwork-item").should.have.lengthOf(1)
      })
    }))

  return describe("#appendArtworks", function () {
    beforeEach(function () {
      // Create a short left column
      const dims = [
        { original_width: 900, original_height: 200, aspect_ratio: 4.5 }, // col 1, 200
        { original_width: 900, original_height: 900, aspect_ratio: 1 }, // col 2, 900
        { original_width: 200, original_height: 900, aspect_ratio: 0.222 }, // col 3, 900
        { original_width: 1000, original_height: 200, aspect_ratio: 5 }, // col 1, 400
        { original_width: 1100, original_height: 900, aspect_ratio: 1.222 }, // col 1, 1300
        { original_width: 600, original_height: 900, aspect_ratio: 0.667 }, // col 2, 1800
        { original_width: 600, original_height: 900, aspect_ratio: 0.6667 }, // col 3, 1800
        { original_width: 700, original_height: 200, aspect_ratio: 3.5 }, // col 1, 1500
      ]
      this.artworks.each((artwork, index) =>
        _.extend(artwork.get("images")[0], dims[index])
      )
      return $("body").empty()
    })

    describe("when columns are ordered", () =>
      it("adds artworks to the next column from left to right", function () {
        this.view = new ArtworkColumnsView({
          el: $("body"),
          collection: this.artworks,
          isOrdered: true,
          allowDuplicates: true,
        })
        $(".artwork-column:eq(0) .artwork-item").should.have.lengthOf(3)
        $(".artwork-column:eq(1) .artwork-item").should.have.lengthOf(3)
        $(".artwork-column:eq(2) .artwork-item").should.have.lengthOf(2)
        let artwork = new Artwork(fabricate("artwork"))
        this.view.appendArtworks([artwork])
        $(".artwork-column:eq(2) .artwork-item").should.have.lengthOf(3)
        artwork = new Artwork(fabricate("artwork"))
        this.view.appendArtworks([artwork])
        $(".artwork-column:eq(0) .artwork-item").should.have.lengthOf(4)
        artwork = new Artwork(fabricate("artwork"))
        this.view.appendArtworks([artwork])
        return $(".artwork-column:eq(1) .artwork-item").should.have.lengthOf(4)
      }))

    describe("when columns are not ordered", function () {
      it("adds artworks to the shortest column", function () {
        this.view = new ArtworkColumnsView({
          el: $("body"),
          collection: this.artworks,
          totalWidth: 1120,
          allowDuplicates: true,
        })
        this.view
          .$(".artwork-column:eq(0) .artwork-item")
          .should.have.lengthOf(3)
        this.view
          .$(".artwork-column:eq(1) .artwork-item")
          .should.have.lengthOf(3)
        this.view
          .$(".artwork-column:eq(2) .artwork-item")
          .should.have.lengthOf(2)
        this.view.shortestColumn.should.equal(2)

        // Add a work to verify it goes to the shortest column
        let artwork = new Artwork(fabricate("artwork"))
        _.extend(artwork.get("images")[0], {
          original_width: 700,
          original_height: 200,
          aspect_ratio: 3.5,
        })
        this.view.appendArtworks([artwork])
        this.view
          .$(".artwork-column:eq(2) .artwork-item")
          .should.have.lengthOf(3)
        this.view.shortestColumn.should.equal(2)

        artwork = new Artwork(fabricate("artwork"))
        _.extend(artwork.get("images")[0], {
          original_width: 700,
          original_height: 200,
          aspect_ratio: 3.5,
        })
        this.view.appendArtworks([artwork])
        this.view
          .$(".artwork-column:eq(2) .artwork-item")
          .should.have.lengthOf(4)
        return this.view.shortestColumn.should.equal(0)
      })

      return describe("#addToShortestColumn", function () {
        beforeEach(function () {
          this.view = new ArtworkColumnsView({
            el: $("body"),
            collection: this.artworks,
            totalWidth: 1120,
            allowDuplicates: true,
          })

          return sinon.stub($.fn, "height").returns(160)
        })

        afterEach(() => $.fn.height.restore())

        it("can accept normal Artwork models", function () {
          const artwork = new Artwork(fabricate("artwork"))
          _.extend(artwork.get("images")[0], {
            original_width: 700,
            original_height: 160,
            aspect_ratio: 3.5,
          })
          this.view.shortestColumn.should.equal(2)
          this.view.addToShortestColumn(artwork)
          this.view.shortestColumn.should.equal(2)
          this.view.addToShortestColumn(artwork)
          this.view.shortestColumn.should.equal(0)
          this.view.addToShortestColumn(artwork)
          return this.view.shortestColumn.should.equal(1)
        })

        return it("can accept jQuery objects directly", function () {
          const $column = this.view.$(
            `.artwork-column:eq(${this.view.shortestColumn})`
          )
          const $artwork = $column.find(".artwork-item").last().clone()
          this.view.shortestColumn.should.equal(2)
          this.view.addToShortestColumn($artwork)
          this.view.shortestColumn.should.equal(2)
          this.view.addToShortestColumn($artwork)
          this.view.shortestColumn.should.equal(0)
          this.view.addToShortestColumn($artwork)
          return this.view.shortestColumn.should.equal(1)
        })
      })
    })

    return it("doesnt add duplicates", function () {
      this.view = new ArtworkColumnsView({
        el: $("body"),
        collection: this.artworks,
        isOrdered: true,
      })
      this.view.collection.reset([
        fabricate("artwork", { id: "bar" }),
        fabricate("artwork", { id: "foo" }),
      ])
      this.view.appendArtworks([
        new Artwork(fabricate("artwork", { id: "foo" })),
      ])
      return this.view.collection.length.should.equal(2)
    })
  })
})