text:
package edu.ucsf.lava.core.session;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import edu.ucsf.lava.core.session.model.LavaSession;
import edu.ucsf.lava.core.type.LavaDateUtils;

public class LavaSessionPolicyHandler {
	public static final Long DEFAULT_EXPIRATION_MINUTES = new Long(30);
	public static final Long DEFAULT_WARNING_MINUTES = new Long(5);
	public static final long MILLIS_PER_MINUTE = 60000;
	// note: this is overridden by bean configuration in core-session.xml
	protected Long expireMinutes = DEFAULT_EXPIRATION_MINUTES;  // number of seconds until a session expires
	protected Long warningMinutes = DEFAULT_WARNING_MINUTES;
	private static  Timestamp defaultExpDate;
	private SessionManager sessionManager; //reference back to calling session monitor

	//override in subclass to identify those sessions that are handled in a custom manner
	public boolean handlesSession(LavaSession session, HttpServletRequest request){
		return true;
	}

	public final boolean hasSessionExpired(LavaSession session,HttpServletRequest request){

		if (session.getCurrentStatus().equals(LavaSession.LAVASESSION_STATUS_EXPIRED)){
			return true;
		}

		session.setExpireTimestamp(determineExpireTime(session, request));
		if (session.isExpireTimeBeforeNow()){
			return true;
		}
		return false;
	}

	public final boolean shouldSessionDisconnect(LavaSession session,HttpServletRequest request){
		if (session.getCurrentStatus().equals(LavaSession.LAVASESSION_STATUS_DISCONNECTED)){
			return true;
		}

		session.setDisconnectDateTime(determineDisconnectDateTime(session,request));
		session.setDisconnectMessage(determineDisconnectMessage(session,request));

		if (session.isDisconnectTimeBeforeNow()){
			return true;
		}

		return false;
	}

	//override in subclass for custom  functionality
	public Date determineDisconnectDateTime(LavaSession session,HttpServletRequest request){
		return session.getDisconnectDateTime();
	}

	//override in subclass for custom  functionality
	public String determineDisconnectMessage(LavaSession session,HttpServletRequest request){
		return session.getDisconnectMessage();
	}

	//override in subclass for custom  functionality
	public Timestamp determineExpireTime(LavaSession session,HttpServletRequest request){
		if(session == null){ return new Timestamp(new Date().getTime()+(DEFAULT_EXPIRATION_MINUTES * MILLIS_PER_MINUTE));}
		Date now = new Date();

		if(session.getExpireTimestamp()!= null &&
				session.getExpireTimestamp().before(now)){
			return session.getExpireTimestamp();
		}

		if (session.getAccessTimestamp()!=null){
			return new Timestamp(session.getAccessTimestamp().getTime() + (expireMinutes * MILLIS_PER_MINUTE));
		}
		return new Timestamp(now.getTime() + (expireMinutes * MILLIS_PER_MINUTE));

	}
	public boolean isDisconnectTimeWithinWarningWindow(LavaSession session,HttpServletRequest request){
		if(session.getDisconnectDateTime() == null) {return false;} // no disconnect time
		if(session.isDisconnectTimeBeforeNow()){return false;} //already disconnected

		Date warningTime = new Date(session.getDisconnectTime().getTime() - (warningMinutes * MILLIS_PER_MINUTE));
		if(warningTime.before(new Date())){
			return true;
		}
		return false;
	}

	public int getSecondsUntilExpiration(LavaSession session,HttpServletRequest request){

		if(session.getExpireTimestamp() == null){
			return getExpireMinutes().intValue();
		}else if (session.isExpireTimeBeforeNow()){
			return 0;
		}else{
			return new Long(((session.getExpireTimestamp().getTime() - new Date().getTime())/1000)).intValue();
		}
	}

	public  Long getWarningMinutes() {
		return warningMinutes;
	}

	public  void setWarningMinutes(Long warningMinutes) {
		this.warningMinutes = warningMinutes;
	}

	public Long getExpireMinutes() {
		return expireMinutes;
	}

	public void setExpireMinutes(Long expireMinutes) {
		this.expireMinutes = expireMinutes;
	}

	public SessionManager getSessionMonitor() {
		return sessionManager;
	}

	public void setSessionMonitor(SessionManager sessionManager) {
		this.sessionManager = sessionManager;
	}

}


text:
package unquietcode.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Ben
 * @version 0.1
 * Date: 12/11/10
 */
@java.lang.annotation.Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE,
		 ElementType.METHOD, ElementType.PACKAGE, ElementType.PARAMETER, ElementType.TYPE})
public @interface Warning {
	public String value();
}

redpajama_set_name: RedPajamaGithub


text:
# Ember WeakMap

This addon is a polyfil for the [Ember.WeakMap RFC](https://github.com/emberjs/rfcs/blob/weakmap/text/0066-template.md).

A WeakMap provides a mechanism for storing and retrieving private state. The WeakMap
itself does not retain a reference to the state, allowing the state to be reclaimed
when the key is reclaimed.

A traditional WeakMap (and the one that will be part of the ES2015 language) allows for
weakness from key -> map, and also from map -> key. This allows either the Map,
or the key being reclaimed to also release the state.

Unfortunately, this bi-directional weakness is problematic to polyfil.
Luckily, uni-directional weakness, in either direction, "just works". A polyfil
must just choose a direction.

Note: Just like ES2015 WeakMap, only non null Objects can be used as keys

## Installation

```shell
ember install ember-weakmap
```

## Usage

```js
import WeakMap from 'ember-weakmap/weak-map';

var myWeakMap = new WeakMap();
```

### Set

```js
/*
 * @method set
 * @param key {Object}
 * @param value {Any}
 * @return {Any} stored value
 */
```

```js
var emailObj = { id: 1, subject: 'Hello World' };

myWeakMap.set(emailObj, {read: true});
```

The key **must be an object**.

### Get

```js
/*
 * @method get
 * @param key {Object}
 * @return {*} stored value
*/
```

```js
myWeakMap.get(emailObj); // => { read: true }
myWeakMap.get(someObjThatWasNotSet); // => undefined
```

### Has

```js
/*
 * @method has
 * @param key {Object}
 * @return {Boolean} if the key exists
*/
```

```js
myWeakMap.has(emailObj); // => true
myWeakMap.has(someObjThatWasNotSet); // => false
```

### Delete

```js
/*
 * @method delete
 * @param key {Object}
 */
 ```

```js
myWeakMap.delete(emailObj);
myWeakMap.get(emailObj); // => undefined
myWeakMap.has(emailObj); // false
```


text:
// @ts-check
const insert = require("gulp-insert");

/**
 * @param {string | RegExp} searchValue
 * @param {string | ((...args: string[]) => string)} replacer
 */
function replace(searchValue, replacer) {
    return insert.transform(content => content.replace(searchValue, /**@type {string}*/(replacer)));
}

module.exports = replace;


text:
{# Stuff that's common to every non-error-page on the site #}
{% load compress i18n %}
{% load static from staticfiles %}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="{% block meta-description %}{% endblock %}">
  <meta name="author" content="{% block meta-author %}{% endblock %}">

  <title>{% block title %}{% trans "IRC CTS" %}{% endblock %} {% if settings.ENVIRONMENT != 'production' %}{{ settings.ENVIRONMENT }} {% endif %}{{ settings.INSTANCE_NAME }}</title>

  <meta name="keywords" content="{% block meta-keywords %}{% endblock %}">
  {% block extra-meta %}{% endblock %}

  {% block css %}

  <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet" type="text/css" media="all">

  <link href="{% static 'css/Source_Sans_Pro.css' %}" rel='stylesheet' type='text/css' media="all">
  <link href="{% static 'css/font-awesome.min.css' %}"  rel='stylesheet' type="text/css" media="all">

  <link href="{% static 'css/site.css' %}" rel="stylesheet" type="text/css" media="all">
  <link href="{% static 'css/simple-sidebar.css' %}" rel="stylesheet" type="text/css" media="all">
  {% endblock css %}

  {% block extra-css %}{% endblock %}

  {% block modals %}
  {% endblock modals %}

            {{ settings.INSTANCE|capfirst }} CTS

        {% if perms.catalog %}

              Catalog

        {% endif %}
        {% if perms.shipments %}

            Shipments

        {% endif %}
        {% if perms.catalog %}

          Entities

                            {% if perms.catalog.add_itemcategory %}

Categories

                            {% endif %}
                            {% if perms.catalog.add_donor %}

Donors

                            {% endif %}
                            {% if perms.catalog.add_donorcode %}

Donor Codes

                            {% endif %}
                            {% if perms.catalog.add_supplier %}

Suppliers

                            {% endif %}
                            {% if perms.catalog.add_transporter %}

Transporters

                            {% endif %}

        {% endif %}
        {% if perms.accounts %}

            Users

        {% endif %}
        {% if user.is_authenticated %}{# FIXME - check specific permissions #}

            Reports

        {% endif %}
        {% if user.is_authenticated %}

Docs

        {% endif %}
        {% if user.is_authenticated and user.is_staff %}

Admin docs

API docs

Admin

        {% endif %}
        {% if user.is_authenticated %}

{% trans "Password" %}

{% trans "Logout" %}

        {% else %}

{% trans "Login" %}

        {% endif %}

    {# second sidebar, to the right of the global one #}
    {% block second-sidebar %}
    {% endblock second-sidebar %}

    {% block page_content_wrapper %}{# in case template needs to override #}

        {# All page content (right side) must be inside page-content inset #}
        {% block messages %}
        {# This div has messages to the user. It will often be empty. #}

            {% for message in messages %}
              {# FIXME - map django message levels to bootstrap message levels #}

                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                {{ message }}

            {% endfor %}

            {# see modals.js ajax_alert() #}

                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

MESSAGE

        {% endblock messages %}
        {# This row has the usual page content #}
        {% block content %}This page needs some content.{% endblock %}

    {% endblock page_content_wrapper %}

  {% block js %}

  {% include 'cts/session_security.html' %}

  {% endblock js %}

  {% block extra-js %}{% endblock %}


text:
import {ajax} from '../src/ajax.js';
import adapter from '../src/AnalyticsAdapter.js';
import CONSTANTS from '../src/constants.json';
import adapterManager from '../src/adapterManager.js';
import { targeting } from '../src/targeting.js';
import { auctionManager } from '../src/auctionManager.js';
import * as utils from '../src/utils.js';

const ANALYTICS_CODE = 'yieldone';
const analyticsType = 'endpoint';
// const VERSION = '1.0.0';
const defaultUrl = 'https://pool.tsukiji.iponweb.net/hba';
const requestedBidders = {};
const requestedBids = {};
const referrers = {};
const ignoredEvents = {};
ignoredEvents[CONSTANTS.EVENTS.BID_ADJUSTMENT] = true;
ignoredEvents[CONSTANTS.EVENTS.BIDDER_DONE] = true;
ignoredEvents[CONSTANTS.EVENTS.AUCTION_END] = true;

let currentAuctionId = '';
let url = defaultUrl;
let pubId = '';

function makeAdUnitNameMap() {
  if (window.googletag && window.googletag.pubads) {
    // eslint-disable-next-line no-undef
    const p = googletag.pubads();
    if (p && p.getSlots) {
      const slots = p.getSlots();
      if (slots && slots.length) {
        const map = {};
        slots.forEach((slot) => {
          const id = slot.getSlotElementId();
          const name = (slot.getAdUnitPath() || '').split('/').pop();
          map[id] = name;
        });
        return map;
      }
    }
  }
}

function addAdUnitNameForArray(ar, map) {
  if (utils.isArray(ar)) {
    ar.forEach((it) => { addAdUnitName(it, map) });
  }
}

function addAdUnitName(params, map) {
  if (params.adUnitCode && map[params.adUnitCode]) {
    params.adUnitName = map[params.adUnitCode];
  }
  if (utils.isArray(params.adUnits)) {
    params.adUnits.forEach((adUnit) => {
      if (adUnit.code && map[adUnit.code]) {
        adUnit.name = map[adUnit.code];
      }
    });
  }
  if (utils.isArray(params.adUnitCodes)) {
    params.adUnitNames = params.adUnitCodes.map((code) => map[code]);
  }
  ['bids', 'bidderRequests', 'bidsReceived', 'noBids'].forEach((it) => {
    addAdUnitNameForArray(params[it], map);
  });
}

const yieldoneAnalytics = Object.assign(adapter({analyticsType}), {
  getUrl() { return url; },
  track({eventType, args = {}}) {
    if (eventType === CONSTANTS.EVENTS.BID_REQUESTED) {
      const reqBidderId = `${args.bidderCode}_${args.auctionId}`;
      requestedBidders[reqBidderId] = utils.deepClone(args);
      requestedBidders[reqBidderId].bids = [];
      args.bids.forEach((bid) => {
        requestedBids[`${bid.bidId}_${bid.auctionId}`] = bid;
      });
    }
    if (eventType === CONSTANTS.EVENTS.BID_TIMEOUT && utils.isArray(args)) {
      const eventsStorage = yieldoneAnalytics.eventsStorage;
      const reqBidders = {};
      args.forEach((bid) => {
        const reqBidId = `${bid.bidId}_${bid.auctionId}`;
        const reqBidderId = `${bid.bidder}_${bid.auctionId}`;
        if (!eventsStorage[bid.auctionId]) eventsStorage[bid.auctionId] = {events: []};
        if ((requestedBidders[reqBidderId] || reqBidders[bid.bidder]) && requestedBids[reqBidId]) {
          if (!reqBidders[bid.bidder]) {
            reqBidders[bid.bidder] = requestedBidders[reqBidderId];
            eventsStorage[bid.auctionId].events.push({eventType, params: reqBidders[bid.bidder]});
            delete requestedBidders[reqBidderId];
          }
          reqBidders[bid.bidder].bids.push(requestedBids[reqBidId]);
          delete requestedBids[reqBidId];
        }
      });
    } else {
      currentAuctionId = args.auctionId || currentAuctionId;
      if (currentAuctionId) {
        const eventsStorage = yieldoneAnalytics.eventsStorage;
        if (!eventsStorage[currentAuctionId]) eventsStorage[currentAuctionId] = {events: []};
        const referrer = args.refererInfo && args.refererInfo.referer;
        if (referrer && referrers[currentAuctionId] !== referrer) {
          referrers[currentAuctionId] = referrer;
        }
        const params = Object.assign({}, args);
        delete params.ad;
        if (params.bidsReceived) {
          params.bidsReceived = params.bidsReceived.map((bid) => {
            const res = Object.assign({}, bid);
            delete res.ad;
            return res;
          });
        }
        if (!ignoredEvents[eventType]) {
          eventsStorage[currentAuctionId].events.push({eventType, params});
        }

        if (
          eventType === CONSTANTS.EVENTS.AUCTION_END || eventType === CONSTANTS.EVENTS.BID_WON
        ) {
          params.adServerTargeting = targeting.getAllTargeting(
            auctionManager.getAdUnitCodes(),
            auctionManager.getBidsReceived()
          );
          if (yieldoneAnalytics.eventsStorage[currentAuctionId] && yieldoneAnalytics.eventsStorage[currentAuctionId].events.length) {
            yieldoneAnalytics.eventsStorage[currentAuctionId].page = {url: referrers[currentAuctionId]};
            yieldoneAnalytics.eventsStorage[currentAuctionId].pubId = pubId;
            yieldoneAnalytics.eventsStorage[currentAuctionId].wrapper_version = '$prebid.version$';
            const adUnitNameMap = makeAdUnitNameMap();
            if (adUnitNameMap) {
              yieldoneAnalytics.eventsStorage[currentAuctionId].events.forEach((it) => {
                addAdUnitName(it.params, adUnitNameMap);
              });
            }
          }
          yieldoneAnalytics.sendStat(yieldoneAnalytics.eventsStorage[currentAuctionId], currentAuctionId);
        }
      }
    }
  },
  sendStat(data, auctionId) {
    if (!data || !data.events || !data.events.length) return;
    delete yieldoneAnalytics.eventsStorage[auctionId];
    ajax(
      url,
      {
        success: function() {},
        error: function() {}
      },
      JSON.stringify(data),
      {
        method: 'POST'
      }
    );
  }
});

yieldoneAnalytics.eventsStorage = {};

// save the base class function
yieldoneAnalytics.originEnableAnalytics = yieldoneAnalytics.enableAnalytics;

// override enableAnalytics so we can get access to the config passed in from the page
yieldoneAnalytics.enableAnalytics = function (config) {
  const options = config && config.options;
  if (options) {
    if (typeof options.url === 'string') {
      url = options.url;
    }
    if (options.pubId) {
      pubId = options.pubId.toString();
    }
  }
  yieldoneAnalytics.originEnableAnalytics(config); // call the base class function
};

adapterManager.registerAnalyticsAdapter({
  adapter: yieldoneAnalytics,
  code: ANALYTICS_CODE
});

export default yieldoneAnalytics;


text:
package org.neo4j.ogm.persistence.transaction;

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

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.neo4j.ogm.domain.gh868.Actor;
import org.neo4j.ogm.domain.gh868.Movie;
import org.neo4j.ogm.domain.music.Album;
import org.neo4j.ogm.domain.music.Artist;
import org.neo4j.ogm.domain.music.Recording;
import org.neo4j.ogm.domain.music.Studio;
import org.neo4j.ogm.exception.TransactionException;
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;
import org.neo4j.ogm.testutil.TestContainersTestBase;
import org.neo4j.ogm.transaction.Transaction;

/**
 * @author Luanne Misquitta
 */
public class TransactionTest extends TestContainersTestBase {

    private Session session;

    @Before
    public void init() throws IOException {
        SessionFactory sessionFactory = new SessionFactory(getDriver(), "org.neo4j.ogm.domain.music", "org.neo4j.ogm.domain.gh868");
        session = sessionFactory.openSession();
        session.purgeDatabase();
    }

    @After
    public void clearDatabase() {
        session.purgeDatabase();
    }

    @Test
    public void shouldNotCommitWhenTransactionIsManaged() {
        Transaction tx = session.beginTransaction();
        Studio emi = new Studio("EMI Studios, London");

        Artist theBeatles = new Artist("The Beatles");
        Album please = new Album("Please Please Me");
        Recording pleaseRecording = new Recording(please, emi, 1963);
        please.setRecording(pleaseRecording);
        theBeatles.getAlbums().add(please);
        please.setArtist(theBeatles);
        session.save(theBeatles);

        tx.rollback(); //the previous saves shouldn't have been committed

        assertThat(session.countEntitiesOfType(Artist.class)).isEqualTo(0);
    }

    @Test // GH-126
    public void shouldBeAbleToRetrySaveOnTransactionRollback() {

        Transaction tx = session.beginTransaction();

        Studio emi = new Studio("EMI Studios, London");
        Artist theBeatles = new Artist("The Beatles");
        Album please = new Album("Please Please Me");
        Recording pleaseRecording = new Recording(please, emi, 1963);

        please.setRecording(pleaseRecording);
        theBeatles.getAlbums().add(please);
        please.setArtist(theBeatles);
        session.save(theBeatles);

        tx.rollback();

        session.save(theBeatles);

        session.clear();

        theBeatles = session.loadAll(Artist.class, -1).iterator().next();
        assertThat(theBeatles.getName()).isEqualTo("The Beatles");
        assertThat(theBeatles.getAlbums()).hasSize(1);
        assertThat(theBeatles.getAlbums().iterator().next().getName()).isEqualTo("Please Please Me");
        assertThat(theBeatles.getAlbums().iterator().next().getRecording().getStudio().getName())
            .isEqualTo("EMI Studios, London");
    }

    @Test
    public void shouldNotBeReadOnlyByDefault() {

        try (Transaction tx = session.beginTransaction()) {
            assertThat(tx.isReadOnly()).isFalse();
        }
    }

    @Test
    public void shouldBeAbleToCreateReadOnlyTransaction() {

        try (Transaction tx = session.beginTransaction(Transaction.Type.READ_ONLY)) {
            assertThat(tx.isReadOnly()).isTrue();
        }
    }

    @Test
    public void shouldNotBeAbleToExtendAReadTransactionWithAReadWriteInnerTransaction() {

        try (
            Transaction tx1 = session.beginTransaction(Transaction.Type.READ_ONLY);
            Transaction tx2 = session.beginTransaction(Transaction.Type.READ_WRITE)) {
            fail("Should not have allowed transaction extension of different type");
        } catch (TransactionException tme) {
            assertThat(tme.getLocalizedMessage())
                .isEqualTo("Incompatible transaction type specified: must be 'READ_ONLY'");
        }
    }

    @Test
    public void shouldNotBeAbleToExtendAReadWriteTransactionWithAReadOnlyInnerTransaction() {

        try (
            Transaction tx1 = session.beginTransaction(Transaction.Type.READ_WRITE);
            Transaction tx2 = session.beginTransaction(Transaction.Type.READ_ONLY)) {
            fail("Should not have allowed transaction extension of different type");
        } catch (TransactionException tme) {
            assertThat(tme.getLocalizedMessage())
                .isEqualTo("Incompatible transaction type specified: must be 'READ_WRITE'");
        }
    }

    @Test
    public void shouldAutomaticallyExtendAReadOnlyTransactionWithAReadOnlyExtension() {

        try (
            Transaction tx1 = session.beginTransaction(Transaction.Type.READ_ONLY);
            Transaction tx2 = session.beginTransaction()) {
            assertThat(tx2.isReadOnly()).isTrue();
        }
    }

    @Test
    public void shouldAutomaticallyExtendAReadWriteTransactionWithAReadWriteExtension() {

        try (Transaction tx1 = session.beginTransaction(Transaction.Type.READ_WRITE);
            Transaction tx2 = session.beginTransaction()) {
            assertThat(tx2.isReadOnly()).isFalse();
        }
    }

    @Test
    public void defaultTransactionShouldWorkAfterManagedTransaction() {
        Transaction tx = session.beginTransaction();
        Studio emi = new Studio("EMI Studios, London");
        session.save(emi);

        tx.commit();
        tx.close();

        session.purgeDatabase();
    }

    @Test
    public void defaultTransactionShouldWorkAfterDefaultTransaction() {
        Studio emi = new Studio("EMI Studios, London");
        session.save(emi);

        session.purgeDatabase();
    }

    @Test // GH-868
    public void shouldNotLoadAlreadyLoadedRelationshipEntityAgain() {

        Movie movie = new Movie("Lord of the rings");
        Actor actor = new Actor("Christopher Lee");
        actor.addPlayedIn("Saruman", movie);

        session.save(actor);
        assertThat(actor).isNotNull();
        assertThat(actor.getId()).isNotNull();
        assertThat(actor.getPlayedIn()).hasSize(1);

        runReadQuery(actor);
        assertThat(actor.getPlayedIn()).hasSize(1);

        // this second save detaches an entity or relationshipEntity
        // we'll get a bad result on next query
        actor.setName("name changed");
        session.save(actor);
        assertThat(actor).isNotNull();
        assertThat(actor.getId()).isNotNull();
        assertThat(actor.getPlayedIn()).hasSize(1);

        runReadQuery(actor);
        // fails, we return childs = 2
        assertThat(actor.getPlayedIn()).hasSize(1);
    }

    private void runReadQuery(Actor entity) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", entity.getId());
        session.query("MATCH /*+ OGM_READ_ONLY */ path = (a:Actor)-[:PLAYED_IN*0..]->()"
            + " WHERE id(a) = $id"
            + " RETURN nodes(path), relationships(path)", params);
    }
}


text:
module Api
  module V2
    class ScheduleSerializer < ApiSerializer

      attributes :day, :start_time, :end_time

    end
  end
end


text:
import codecs
import os
import re
from setuptools import setup
from setuptools.command.test import test as TestCommand
import sys

HERE = os.path.abspath(os.path.dirname(__file__))

class Tox(TestCommand):
    user_options = [('tox-args=', 'a', "Arguments to pass to tox")]

    def initialize_options(self):
        TestCommand.initialize_options(self)
        self.tox_args = None

    def finalize_options(self):
        TestCommand.finalize_options(self)
        self.test_args = []
        self.test_suite = True

    def run_tests(self):
        # import here, cause outside the eggs aren't loaded
        import tox
        import shlex
        args = self.tox_args
        if args:
            args = shlex.split(self.tox_args)
        errno = tox.cmdline(args=args)
        sys.exit(errno)

def read(*parts):
    # intentionally *not* adding an encoding option to open
    # see: https://github.com/pypa/virtualenv/issues/201#issuecomment-3145690
    return codecs.open(os.path.join(HERE, *parts), 'r').read()

def find_version(*file_paths):
    version_file = read(*file_paths)
    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
                              version_file, re.M)
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.")

def read_long_description():
    long_description = ""
    with open('README.rst', 'r') as f:
        long_description = f.read()
    return long_description

setup(
    author="Marko Samastur",
    author_email="markos@gaivo.net",
    name='pyimagediet',
    version=find_version('pyimagediet', '__init__.py'),
    description='Python wrapper around image optimisations tools',
    long_description=read_long_description(),
    url='https://github.com/samastur/pyimagediet/',
    platforms=['OS Independent'],
    license='MIT License',
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Topic :: Multimedia :: Graphics',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: Utilities',
    ],
    install_requires=[
        'PyYAML>=3.11',
        'python-magic>=0.4.10',
        'Click>=6.2',
    ],
    include_package_data=True,
    packages=['pyimagediet'],
    entry_points={
        'console_scripts': ['diet=pyimagediet.cli:diet']
    },
    tests_require=['tox'],
    cmdclass={'test': Tox},
    zip_safe=False
)


text:
require_relative './excel2csv'

module CartoDB
  module Importer2
    class Xlsx2Csv < Excel2Csv

      SUPPORTED_EXTENSION = 'xlsx'

      def self.supported?(extension)
        extension == ".#{SUPPORTED_EXTENSION}"
      end

      def initialize(filepath, job = nil, importer_config = nil)
        super(SUPPORTED_EXTENSION, filepath, job, nil, importer_config)
      end

    end
  end
end


text:
package org.apache.flink.connector.testframe.external.sink;

import org.apache.flink.annotation.Experimental;
import org.apache.flink.api.java.typeutils.ResultTypeQueryable;
import org.apache.flink.connector.testframe.external.ExternalContext;
import org.apache.flink.connector.testframe.external.ExternalSystemDataReader;

import java.util.List;

/**
 * External context for DataStream sinks.
 *
 * @param <T> Type of elements before serialization by sink
 */
@Experimental
public interface DataStreamSinkExternalContext<T> extends ExternalContext, ResultTypeQueryable<T> {

    /** Create a reader for consuming data written to the external system by sink. */
    ExternalSystemDataReader<T> createSinkDataReader(TestingSinkSettings sinkSettings);

    /**
     * Generate test data.
     *
     *
These test data will be sent to sink via a special source in Flink job, write to external
     * system by sink, consume back via {@link ExternalSystemDataReader}, and make comparison with
     * {@link T#equals(Object)} for validating correctness.
     *
     *
Make sure that the {@link T#equals(Object)} returns false when the records in different
     * splits.
     *
     * @param sinkSettings settings of the sink
     * @param seed Seed for generating random test data set.
     * @return List of generated test data.
     */
    List<T> generateTestData(TestingSinkSettings sinkSettings, long seed);
}


text:
require "pokemon/gem/version"
require "unirest"

module Pokemon
  class Damage
    attr_reader :name
    def initialize(options)
      @name = options["name"]
    end

    def self.all
      data = []
      Unirest.get("http://pokeapi.co/api/v2/pokemon/?limit=151").body["results"].map {|pokemon| data << Damage.new(pokemon)}
      data.map {|pokemon| pokemon.name}
    end

    def self.name(name)
      data = []
      Unirest.get("http://pokeapi.co/api/v2/pokemon/?limit=151").body["results"].map {|pokemon| data << Damage.new(pokemon)}
      pokemon_names = data.map {|pokemon| pokemon.name}
      pokemon_index = pokemon_names.index(name) + 1
      pokemon_object = self.get_pokemon(pokemon_index)
      types = self.get_types(pokemon_object)
      dmg_arr = []
      types.each {|type_obj| dmg_arr << self.get_dmg(type_obj)}
      dmg_arr.unshift(pokemon_names.first)
    end

  private
    def self.get_pokemon(pokemon_index)
      Unirest.get("http://pokeapi.co/api/v2/pokemon/#{pokemon_index}").body
    end

    def self.get_types(pokemon)
      types = []
      pokemon["types"].each {|type_obj| types << type_obj["type"]}
      types
    end

    def self.get_dmg(type_obj)
      all_dmg = {
      no_damage_to: [],
      no_damage_from: [],
      half_damage_to: [],
      half_damage_from: [],
      double_damage_to: [],
      double_damage_from: []
      }
      type_data = Unirest.get("#{type_obj['url']}").body

      all_dmg.keys.each {|key| type_data["damage_relations"][key.to_s].each do |dmg_amount|
          all_dmg[key] << dmg_amount["name"]
        end
      }
      all_dmg[:type_name] = type_data["name"]
      all_dmg

    end
  end
end
# Pokemon::Damage.name("jigglypuff")


text:
<teki-app-layout>

      <teki-widget>
        <teki-widget-body>

          <calendar
            [calendarMode] ="calendarMode"
            [currentDate]  ="currentDate"
          ></calendar>
        </teki-widget-body>
      </teki-widget>

</teki-app-layout>


text:
using AVF.MemberManagement.StandardLibrary.Interfaces;
using Newtonsoft.Json;

namespace AVF.MemberManagement.StandardLibrary.Tbo
{
    public class Test : IIntId
    {
        public const string PrimaryKey = "ID";

        [JsonIgnore]
        public string PrimaryKeyName { get; set; } = PrimaryKey;

        [JsonProperty(PropertyName = PrimaryKey)]
        public int Id
        {
            get;
            set;
        }

        public string Text
        {
            get;
            set;
        }
    }
}


text:
/* eslint react/no-multi-comp: 0, react/prop-types: 0 */
import React from 'react';
import { PrismCode } from 'react-prism';
import { Button } from 'reactstrap';
import Helmet from 'react-helmet';
import PosterImageExample from '../examples/PosterImage';
const PosterImageExampleSource = require('!!raw-loader!../examples/PosterImage');

export default class PosterImagePage extends React.Component {
  render() {
    return (

        <Helmet title="PosterImage" />

PosterImage

          The PosterImage specifies an image to be shown while the
          video is downloading, or until the user hits the play button. If this
          is not included, the first frame of the video will be used instead.

          <PosterImageExample />

          <PrismCode className="language-jsx">
            {PosterImageExampleSource}
          </PrismCode>

Properties

          <PrismCode className="language-jsx">
            {`
PosterImage.propTypes = {

  // The poster image url
  poster: PropTypes.string,

}`}
          </PrismCode>

    );
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <sysu.mobile.limk.library.MapView
        android:id="@+id/dialog_mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:debug="true"
        app:max_scale="4"
        app:min_scale="0.2" />
    <TextView
        android:id="@+id/dialog_infoTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true" />
    <Button
        android:id="@+id/dialog_saveBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:textAllCaps="false"
        android:text="Save"/>
</RelativeLayout>


text:
"use strict";

const { runWatch } = require("../../utils/test-utils");

describe('"analyze" option', () => {
  it("should load webpack-bundle-analyzer plugin with --analyze flag", async () => {
    const { stderr, stdout } = await runWatch(__dirname, ["--analyze"], {
      killString: /Webpack Bundle Analyzer is started at/,
    });

    expect(stderr).toBeFalsy();
    expect(stdout).toContain("Webpack Bundle Analyzer is started at");
  });
});


text:
id: text
title: Text
---

A React component for displaying text.

`Text` supports nesting, styling, and touch handling.

In the following example, the nested title and body text will inherit the `fontFamily` from `styles.baseText`, but the title provides its own additional styles. The title and body will stack on top of each other on account of the literal newlines:

```js
import React, { useState } from 'react';
import { Text, StyleSheet } from 'react-native';

const TextInANest = () => {
  const [titleText, setTitleText] = useState("Bird's Nest");
  const bodyText = useState('This is not really a bird nest.');

  const onPressTitle = () => {
    setTitleText("Bird's Nest [pressed]");
  };

  return (
    <Text style={styles.baseText}>
      <Text style={styles.titleText} onPress={onPressTitle}>
        {titleText}
        {'\n'}
        {'\n'}
      </Text>
      <Text numberOfLines={5}>{bodyText}</Text>
    </Text>
  );
};

const styles = StyleSheet.create({
  baseText: {
    fontFamily: 'Cochin',
  },
  titleText: {
    fontSize: 20,
    fontWeight: 'bold',
  },
});

export default TextInANest;
```

## Nested text

Both Android and iOS allow you to display formatted text by annotating ranges of a string with specific formatting like bold or colored text (`NSAttributedString` on iOS, `SpannableString` on Android). In practice, this is very tedious. For React Native, we decided to use web paradigm for this where you can nest text to achieve the same effect.

```js
import React from 'react';
import { Text, StyleSheet } from 'react-native';

const BoldAndBeautiful = () => {
  return (
    <Text style={styles.baseText}>
      I am bold
      <Text style={styles.innerText}> and red</Text>
    </Text>
  );
};

const styles = StyleSheet.create({
  baseText: {
    fontWeight: 'bold',
  },
  innerText: {
    color: 'red',
  },
});

export default BoldAndBeautiful;
```

Behind the scenes, React Native converts this to a flat `NSAttributedString` or `SpannableString` that contains the following information:

```js
"I am bold and red"
0-9: bold
9-17: bold, red
```

## Containers

The `<Text>` element is unique relative to layout: everything inside is no longer using the Flexbox layout but using text layout. This means that elements inside of a `<Text>` are no longer rectangles, but wrap when they see the end of the line.

```js
<Text>
  <Text>First part and </Text>
  <Text>second part</Text>
</Text>
// Text container: the text will be inline if the space allowed it
// |First part and second part|

// otherwise, the text will flow as if it was one
// |First part |
// |and second |
// |part       |

<View>
  <Text>First part and </Text>
  <Text>second part</Text>
</View>
// View container: each text is its own block
// |First part and|
// |second part   |

// otherwise, the text will flow in its own block
// |First part |
// |and        |
// |second part|
```

## Limited Style Inheritance

On the web, the usual way to set a font family and size for the entire document is to take advantage of inherited CSS properties like so:

```css
html {
  font-family: 'lucida grande', tahoma, verdana, arial, sans-serif;
  font-size: 11px;
  color: #141823;
}
```

All elements in the document will inherit this font unless they or one of their parents specifies a new rule.

In React Native, we are more strict about it: **you must wrap all the text nodes inside of a `<Text>` component**. You cannot have a text node directly under a `<View>`.

```js
// BAD: will raise exception, can't have a text node as child of a <View>
<View>
  Some text
</View>

// GOOD
<View>
  <Text>
    Some text
  </Text>
</View>
```

You also lose the ability to set up a default font for an entire subtree. Meanwhile, `fontFamily` only accepts a single font name, which is different from `font-family` in CSS. The recommended way to use consistent fonts and sizes across your application is to create a component `MyAppText` that includes them and use this component across your app. You can also use this component to make more specific components like `MyAppHeaderText` for other kinds of text.

```js
<View>
  <MyAppText>Text styled with the default font for the entire application</MyAppText>
  <MyAppHeaderText>Text styled as a header</MyAppHeaderText>
</View>
```

Assuming that `MyAppText` is a component that only renders out its children into a `Text` component with styling, then `MyAppHeaderText` can be defined as follows:

```js
class MyAppHeaderText extends Component {
  render() {
    return (
      <MyAppText>
        <Text style={{ fontSize: 20 }}>{this.props.children}</Text>
      </MyAppText>
    );
  }
}
```

Composing `MyAppText` in this way ensures that we get the styles from a top-level component, but leaves us the ability to add / override them in specific use cases.

React Native still has the concept of style inheritance, but limited to text subtrees. In this case, the second part will be both bold and red.

```js
<Text style={{ fontWeight: 'bold' }}>
  I am bold
  <Text style={{ color: 'red' }}>and red</Text>
</Text>
```

We believe that this more constrained way to style text will yield better apps:

- (Developer) React components are designed with strong isolation in mind: You should be able to drop a component anywhere in your application, trusting that as long as the props are the same, it will look and behave the same way. Text properties that could inherit from outside of the props would break this isolation.

- (Implementor) The implementation of React Native is also simplified. We do not need to have a `fontFamily` field on every single element, and we do not need to potentially traverse the tree up to the root every time we display a text node. The style inheritance is only encoded inside of the native Text component and doesn't leak to other components or the system itself.

---

# Reference

## Props

### `accessibilityHint`

An accessibility hint helps users understand what will happen when they perform an action on the accessibility element when that result is not clear from the accessibility label.

| Type   |
| ------ |
| string |

---

### `accessibilityLabel`

Overrides the text that's read by the screen reader when the user interacts with the element. By default, the label is constructed by traversing all the children and accumulating all the `Text` nodes separated by space.

| Type   |
| ------ |
| string |

---

### `accessibilityRole`

Tells the screen reader to treat the currently focused on element as having a specific role.

On iOS, these roles map to corresponding Accessibility Traits. Image button has the same functionality as if the trait was set to both 'image' and 'button'. See the [Accessibility guide](https://reactnative.dev/docs/0.64/accessibility#accessibilitytraits-ios) for more information.

On Android, these roles have similar functionality on TalkBack as adding Accessibility Traits does on Voiceover in iOS

| Type                                                                                |
| -------------------------------------------------------------------------------------- |
| [AccessibilityRole](https://reactnative.dev/docs/0.64/accessibility#accessibilityrole) |

---

### `accessibilityState`

Tells the screen reader to treat the currently focused on element as being in a specific state.

You can provide one state, no state, or multiple states. The states must be passed in through an object. Ex: `{selected: true, disabled: true}`.

| Type                                                                                |
| ---------------------------------------------------------------------------------------- |
| [AccessibilityState](https://reactnative.dev/docs/0.64/accessibility#accessibilitystate) |

---

### `accessible`

When set to `true`, indicates that the view is an accessibility element.

See the [Accessibility guide](https://reactnative.dev/docs/0.64/accessibility#accessible-ios-android) for more information.

| Type    | Default |
| ------- | ------- |
| boolean | `true`  |

---

### `adjustsFontSizeToFit`

Specifies whether fonts should be scaled down automatically to fit given style constraints.

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

---

### `allowFontScaling`

Specifies whether fonts should scale to respect Text Size accessibility settings.

| Type    | Default |
| ------- | ------- |
| boolean | `true`  |

---

### `android_hyphenationFrequency` **(Android)**

Sets the frequency of automatic hyphenation to use when determining word breaks on Android API Level 23+.

| Type                                             | Default  |
| ------------------------------------------------ | -------- |
| enum(`'none'`, `'full'`, `'balanced'`, `'high'`) | `'none'` |

---

### `dataDetectorType` **(Android)**

Determines the types of data converted to clickable URLs in the text element. By default no data types are detected.

You can provide only one type.

| Type                                                          | Default  |
| ------------------------------------------------------------- | -------- |
| enum(`'phoneNumber'`, `'link'`, `'email'`, `'none'`, `'all'`) | `'none'` |

---

### `disabled` **(Android)**

Specifies the disabled state of the text view for testing purposes.

| Type | Default |
| ---- | ------- |
| bool | `false` |

---

### `ellipsizeMode`

When `numberOfLines` is set, this prop defines how text will be truncated. `numberOfLines` must be set in conjunction with this prop.

This can be one of the following values:

- `head` - The line is displayed so that the end fits in the container and the missing text at the beginning of the line is indicated by an ellipsis glyph. e.g., "...wxyz"
- `middle` - The line is displayed so that the beginning and end fit in the container and the missing text in the middle is indicated by an ellipsis glyph. "ab...yz"
- `tail` - The line is displayed so that the beginning fits in the container and the missing text at the end of the line is indicated by an ellipsis glyph. e.g., "abcd..."
- `clip` - Lines are not drawn past the edge of the text container.

> On Android, when `numberOfLines` is set to value higher then `1`, only `tail` value will work correctly.

| Type                                           | Default |
| ---------------------------------------------- | ------- |
| enum(`'head'`, `'middle'`, `'tail'`, `'clip'`) | `tail`  |

---

### `maxFontSizeMultiplier`

Specifies largest possible scale a font can reach when `allowFontScaling` is enabled. Possible values:

- `null/undefined`: inherit from the parent node or the global default (0)
- `0`: no max, ignore parent/global default
- `>= 1`: sets the `maxFontSizeMultiplier` of this node to this value

| Type   | Default     |
| ------ | ----------- |
| number | `undefined` |

---

### `minimumFontScale` **(iOS)**

Specifies smallest possible scale a font can reach when `adjustsFontSizeToFit` is enabled. (values 0.01-1.0).

| Type   |
| ------ |
| number |

---

### `nativeID`

Used to locate this view from native code.

| Type   |
| ------ |
| string |

---

### `numberOfLines`

Used to truncate the text with an ellipsis after computing the text layout, including line wrapping, such that the total number of lines does not exceed this number. Setting this property to `0` will result in unsetting this value, which means that no lines restriction will be applied.

This prop is commonly used with `ellipsizeMode`.

| Type   | Default |
| ------ | ------- |
| number | `0`     |

---

### `onLayout`

Invoked on mount and on layout changes.

| Type                                    |
| --------------------------------------- |
| ([LayoutEvent](layoutevent.md)) => void |

---

### `onLongPress`

This function is called on long press.

| Type                                  |
| ------------------------------------- |
| ([PressEvent](pressevent.md)) => void |

---

### `onMoveShouldSetResponder`

Does this view want to "claim" touch responsiveness? This is called for every touch move on the `View` when it is not the responder.

| Type                                     |
| ---------------------------------------- |
| ([PressEvent](pressevent.md)) => boolean |

---

### `onPress`

This function is called on press.

| Type                                  |
| ------------------------------------- |
| ([PressEvent](pressevent.md)) => void |

---

### `onResponderGrant`

The View is now responding for touch events. This is the time to highlight and show the user what is happening.

| Type                                  |
| ------------------------------------- |
| ([PressEvent](pressevent.md)) => void |

---

### `onResponderMove`

The user is moving their finger.

| Type                                  |
| ------------------------------------- |
| ([PressEvent](pressevent.md)) => void |

---

### `onResponderRelease`

Fired at the end of the touch.

| Type                                  |
| ------------------------------------- |
| ([PressEvent](pressevent.md)) => void |

---

### `onResponderTerminate`

The responder has been taken from the `View`. Might be taken by other views after a call to `onResponderTerminationRequest`, or might be taken by the OS without asking (e.g., happens with control center/ notification center on iOS)

| Type                                  |
| ------------------------------------- |
| ([PressEvent](pressevent.md)) => void |

---

### `onResponderTerminationRequest`

Some other `View` wants to become responder and is asking this `View` to release its responder. Returning `true` allows its release.

| Type                                     |
| ---------------------------------------- |
| ([PressEvent](pressevent.md)) => boolean |

---

### `onStartShouldSetResponderCapture`

If a parent `View` wants to prevent a child `View` from becoming responder on a touch start, it should have this handler which returns `true`.

| Type                                     |
| ---------------------------------------- |
| ([PressEvent](pressevent.md)) => boolean |

---

### `onTextLayout`

Invoked on Text layout change.

| Type                                             |
| ------------------------------------------------ |
| ([`TextLayoutEvent`](#textlayoutevent)) => mixed |

---

### `pressRetentionOffset`

When the scroll view is disabled, this defines how far your touch may move off of the button, before deactivating the button. Once deactivated, try moving it back and you'll see that the button is once again reactivated! Move it back and forth several times while the scroll view is disabled. Ensure you pass in a constant to reduce memory allocations.

| Type                    |
| ----------------------- |
| [Rect](rect.md), number |

---

### `selectable`

Lets the user select text, to use the native copy and paste functionality.

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

---

### `selectionColor` **(Android)**

The highlight color of the text.

| Type                                              |
| ------------------------------------------------- |
| [color](https://reactnative.dev/docs/0.64/colors) |

---

### `style`

| Type                                                                       |
| -------------------------------------------------------------------------- |
| [Text Style](text-style-props.md), [View Style Props](view-style-props.md) |

---

### `suppressHighlighting` **(iOS)**

When `true`, no visual change is made when text is pressed down. By default, a gray oval highlights the text on press down.

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

---

### `testID`

Used to locate this view in end-to-end tests.

| Type   |
| ------ |
| string |

---

### `textBreakStrategy` **(Android)**

Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced`.

| Type                                            | Default       |
| ----------------------------------------------- | ------------- |
| enum(`'simple'`, `'highQuality'`, `'balanced'`) | `highQuality` |

## Type Definitions

### TextLayout

`TextLayout` object is a part of [`TextLayoutEvent`](#textlayoutevent) callback and contains the measurement data for `Text` line.

#### Example

```js
{
  capHeight: 10.496,
  ascender: 14.624,
  descender: 4,
  width: 28.224,
  height: 18.624,
  xHeight: 6.048,
  x: 0,
  y: 0
}
```

#### Properties

| Name      | Type   | Optional | Description                                                         |
| --------- | ------ | -------- | ------------------------------------------------------------------- |
| ascender  | number | No       | The line ascender height after the text layout changes.             |
| capHeight | number | No       | Height of capital letter above the baseline.                        |
| descender | number | No       | The line descender height after the text layout changes.            |
| height    | number | No       | Height of the line after the text layout changes.                   |
| width     | number | No       | Width of the line after the text layout changes.                    |
| x         | number | No       | Line X coordinate inside the Text component.                        |
| xHeight   | number | No       | Distance between the baseline and median of the line (corpus size). |
| y         | number | No       | Line Y coordinate inside the Text component.                        |

### TextLayoutEvent

`TextLayoutEvent` object is returned in the callback as a result of component layout change. It contains a key called `lines` with a value which is an array containing [`TextLayout`](#textlayout) object corresponeded to every rendered text line.

#### Example

```js
{
  lines: [
    TextLayout,
    TextLayout,
    // ...
  ];
  target: 1127;
}
```

#### Properties

| Name   | Type                                | Optional | Description                                           |
| ------ | ----------------------------------- | -------- | ----------------------------------------------------- |
| lines  | array of [TextLayout](#textlayout)s | No       | Provides the TextLayout data for every rendered line. |
| target | number                              | No       | The node id of the element.                           |


text:
mkdir -p target
rm -rf target/images
rm -rf target/assets
rm -rf target/reveal.js
cp -r src/docs/images target/
cp -r src/docs/assets target/
cp -r .reveal.js/ target/reveal.js/
echo "Building src/docs/understanding-oss-gcc-2016.adoc (reveal.js)"
asciidoctor -a allow-uri-read -b revealjs -T .asciidoctor-reveal.js/templates/slim -o target/understanding-oss-gcc-2016.html src/docs/understanding-oss-gcc-2016.adoc
echo "Building src/docs/understanding-oss-all.adoc (reveal.js)"
asciidoctor -a allow-uri-read -b revealjs -T .asciidoctor-reveal.js/templates/slim -o target/understanding-oss-all.html src/docs/understanding-oss-all.adoc


text:
angular.module('grabs').controller('HomepageCtrl', ['$scope', '$route', 'languageService', function ($scope, $route, languageService) {
    'use strict';

    $scope.lang = $route.current.key;

    languageService.getLanguageFile('homepage/' + $scope.lang).then(function (response) {
        $scope.ln = response.data;
    });
}]);


text:
package GROUPID.tests.perf;

import org.testng.annotations.Test;

/**
 * Placeholder for Perf tests.
 */
public class LoginTest {

    @Test
    public void sampleTest() {

    }
}


text:
#if SIMPLE_PICKLIST
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sage.SalesLogix.PickLists;
using Sage.SalesLogix.Web.Controls.PickList;

namespace OpenSlx.Lib.Web.Controls.Impl
{
    /// <summary>
    /// Renders the picklist as a regular Saleslogix picklist control
    /// </summary>
    public class PicklistPicklistAdapter : IPicklistAdapter
    {
        private PickListControl _picklist;
        private String _picklistName;
        private PickListAttributes _attr;
        private PicklistStorageMode _storageMode;

        /// <summary>
        /// Create adapter
        /// </summary>
        /// <param name="picklistName"></param>
        /// <param name="attr"></param>
        /// <param name="storageMode"></param>
        public PicklistPicklistAdapter(String picklistName, PickListAttributes attr, PicklistStorageMode storageMode)
        {
            _picklistName = picklistName;
            _attr = attr;
            _storageMode = storageMode;
        }

        #region IPicklistAdapter Members

        /// <summary>
        /// Get underlying value.
        /// </summary>
        /// <returns></returns>
        public string GetValue()
        {
            return _picklist.PickListValue;
        }

        /// <summary>
        /// Set value on the underlying control.
        /// </summary>
        /// <param name="value"></param>
        public void SetValue(string value)
        {
            _picklist.PickListValue = value;
        }

        /// <summary>
        /// Create the control representing the picklist.
        /// </summary>
        /// <param name="parentControl"></param>
        public void CreateChildControls(SimplePicklist parentControl)
        {
            _picklist = new PickListControl();
            if ((_storageMode & PicklistStorageMode.Id) != 0)
                _picklist.StorageMode = Sage.Platform.Controls.StorageModeEnum.ID;
            else if ((_storageMode & PicklistStorageMode.Code) != 0)
                _picklist.StorageMode = Sage.Platform.Controls.StorageModeEnum.Code;
            _picklist.PickListName = _picklistName;
            _picklist.AllowMultiples = _attr.AllowMultiples;
            _picklist.AlphaSort = _attr.AlphaSorted;
            _picklist.NoneEditable = _attr.NoneEditable;
            // do not set this attribute - the default validator created is too limited
            //_picklist.Required = _attr.Required;
            _picklist.MustExistInList = _attr.ValueMustExist;
            _picklist.PickListValueChanged += delegate
            {
                if (TextChanged != null)
                    TextChanged(this, EventArgs.Empty);
            };
            _picklist.AutoPostBack = parentControl.AutoPostBack;
            parentControl.Controls.Add(_picklist);
        }

        /// <summary>
        /// Disable / enable the picklist.
        /// </summary>
        public bool ReadOnly
        {
            set
            {
                if (_picklist != null)
                {
                    _picklist.Enabled = !value;
                    _picklist.ReadOnly = value;
                }
            }
        }

        /// <summary>
        /// Text may have changed.
        /// </summary>
        public event EventHandler TextChanged;

        #endregion
    }
}
#endif


text:
#include "queue_type.h"

#include <vector>
#include <algorithm>

// Multi-threaded queue push/pop test
namespace {

    static size_t s_nConsumerThreadCount = 4;
    static size_t s_nProducerThreadCount = 4;
    static size_t s_nQueueSize = 4000000;

    static std::atomic<size_t> s_nProducerDone( 0 );

    class queue_push_pop: public cds_test::stress_fixture
    {
    protected:
        struct value_type
        {
            size_t      nNo;
            size_t      nWriterNo;
        };

        enum {
            producer_thread,
            consumer_thread
        };

        template <class Queue>
        class Producer: public cds_test::thread
        {
            typedef cds_test::thread base_class;

        public:
            Producer( cds_test::thread_pool& pool, Queue& queue, size_t nPushCount )
                : base_class( pool, producer_thread )
                , m_Queue( queue )
                , m_nPushFailed( 0 )
                , m_nPushCount( nPushCount )
            {}

            Producer( Producer& src )
                : base_class( src )
                , m_Queue( src.m_Queue )
                , m_nPushFailed( 0 )
                , m_nPushCount( src.m_nPushCount )
            {}

            virtual thread * clone()
            {
                return new Producer( *this );
            }

            virtual void test()
            {
                size_t const nPushCount = m_nPushCount;
                value_type v;
                v.nWriterNo = id();
                v.nNo = 0;
                m_nPushFailed = 0;

                while ( v.nNo < nPushCount ) {
                    if ( m_Queue.push( v ))
                        ++v.nNo;
                    else
                        ++m_nPushFailed;
                }

                s_nProducerDone.fetch_add( 1 );
            }

        public:
            Queue&              m_Queue;
            size_t              m_nPushFailed;
            size_t const        m_nPushCount;
        };

        template <class Queue>
        class Consumer: public cds_test::thread
        {
            typedef cds_test::thread base_class;

        public:
            Queue&              m_Queue;
            size_t const        m_nPushPerProducer;
            size_t              m_nPopEmpty;
            size_t              m_nPopped;
            size_t              m_nBadWriter;

            typedef std::vector<size_t> popped_data;
            typedef std::vector<size_t>::iterator       data_iterator;
            typedef std::vector<size_t>::const_iterator const_data_iterator;

            std::vector<popped_data>        m_WriterData;

        private:
            void initPoppedData()
            {
                const size_t nProducerCount = s_nProducerThreadCount;
                m_WriterData.resize( nProducerCount );
                for ( size_t i = 0; i < nProducerCount; ++i )
                    m_WriterData[i].reserve( m_nPushPerProducer );
            }

        public:
            Consumer( cds_test::thread_pool& pool, Queue& queue, size_t nPushPerProducer )
                : base_class( pool, consumer_thread )
                , m_Queue( queue )
                , m_nPushPerProducer( nPushPerProducer )
                , m_nPopEmpty( 0 )
                , m_nPopped( 0 )
                , m_nBadWriter( 0 )
            {
                initPoppedData();
            }
            Consumer( Consumer& src )
                : base_class( src )
                , m_Queue( src.m_Queue )
                , m_nPushPerProducer( src.m_nPushPerProducer )
                , m_nPopEmpty( 0 )
                , m_nPopped( 0 )
                , m_nBadWriter( 0 )
            {
                initPoppedData();
            }

            virtual thread * clone()
            {
                return new Consumer( *this );
            }

            virtual void test()
            {
                m_nPopEmpty = 0;
                m_nPopped = 0;
                m_nBadWriter = 0;
                const size_t nTotalWriters = s_nProducerThreadCount;
                value_type v;
                while ( true ) {
                    if ( m_Queue.pop( v )) {
                        ++m_nPopped;
                        if ( v.nWriterNo < nTotalWriters )
                            m_WriterData[ v.nWriterNo ].push_back( v.nNo );
                        else
                            ++m_nBadWriter;
                    }
                    else {
                        ++m_nPopEmpty;

                        if ( s_nProducerDone.load() >= nTotalWriters ) {
                            if ( m_Queue.empty())
                                break;
                        }
                    }
                }
            }
        };

    protected:
        size_t m_nThreadPushCount;

    protected:
        template <class Queue>
        void analyze( Queue& q, size_t /*nLeftOffset*/ = 0, size_t nRightOffset = 0 )
        {
            cds_test::thread_pool& pool = get_pool();

            typedef Consumer<Queue> Consumer;
            typedef Producer<Queue> Producer;

            size_t nPostTestPops = 0;
            {
                value_type v;
                while ( q.pop( v ))
                    ++nPostTestPops;
            }

            size_t nTotalPops = 0;
            size_t nPopFalse = 0;
            size_t nPoppedItems = 0;
            size_t nPushFailed = 0;

            std::vector< Consumer * > arrConsumer;

            for ( size_t i = 0; i < pool.size(); ++i ) {
                cds_test::thread& thr = pool.get(i);
                if ( thr.type() == consumer_thread ) {
                    Consumer& consumer = static_cast<Consumer&>( thr );
                    nTotalPops += consumer.m_nPopped;
                    nPopFalse += consumer.m_nPopEmpty;
                    arrConsumer.push_back( &consumer );
                    EXPECT_EQ( consumer.m_nBadWriter, 0u ) << "consumer_thread_no " << i;

                    size_t nPopped = 0;
                    for ( size_t n = 0; n < s_nProducerThreadCount; ++n )
                        nPopped += consumer.m_WriterData[n].size();

                    nPoppedItems += nPopped;
                }
                else {
                    assert( thr.type() == producer_thread );

                    Producer& producer = static_cast<Producer&>( thr );
                    nPushFailed += producer.m_nPushFailed;
                    EXPECT_EQ( producer.m_nPushFailed, 0u ) << "producer_thread_no " << i;
                }
            }
            EXPECT_EQ( nTotalPops, nPoppedItems );

            EXPECT_EQ( nTotalPops + nPostTestPops, s_nQueueSize ) << "nTotalPops=" << nTotalPops << ", nPostTestPops=" << nPostTestPops;
            EXPECT_TRUE( q.empty());

            // Test consistency of popped sequence
            for ( size_t nWriter = 0; nWriter < s_nProducerThreadCount; ++nWriter ) {
                std::vector<size_t> arrData;
                arrData.reserve( m_nThreadPushCount );
                for ( size_t nReader = 0; nReader < arrConsumer.size(); ++nReader ) {
                    auto it = arrConsumer[nReader]->m_WriterData[nWriter].begin();
                    auto itEnd = arrConsumer[nReader]->m_WriterData[nWriter].end();
                    if ( it != itEnd ) {
                        auto itPrev = it;
                        for ( ++it; it != itEnd; ++it ) {
                            EXPECT_LT( *itPrev, *it + nRightOffset ) << "consumer=" << nReader << ", producer=" << nWriter;
                            itPrev = it;
                        }
                    }

                    for ( it = arrConsumer[nReader]->m_WriterData[nWriter].begin(); it != itEnd; ++it )
                        arrData.push_back( *it );
                }

                std::sort( arrData.begin(), arrData.end());
                for ( size_t i=1; i < arrData.size(); ++i ) {
                    EXPECT_EQ( arrData[i - 1] + 1, arrData[i] ) << "producer=" << nWriter;
                }

                EXPECT_EQ( arrData[0], 0u ) << "producer=" << nWriter;
                EXPECT_EQ( arrData[arrData.size() - 1], m_nThreadPushCount - 1 ) << "producer=" << nWriter;
            }
        }

        template <class Queue>
        void test_queue( Queue& q )
        {
            m_nThreadPushCount = s_nQueueSize / s_nProducerThreadCount;

            cds_test::thread_pool& pool = get_pool();
            pool.add( new Producer<Queue>( pool, q, m_nThreadPushCount ), s_nProducerThreadCount );
            pool.add( new Consumer<Queue>( pool, q, m_nThreadPushCount ), s_nConsumerThreadCount );

            s_nProducerDone.store( 0 );
            s_nQueueSize = m_nThreadPushCount * s_nProducerThreadCount;

            propout() << std::make_pair( "producer_count", s_nProducerThreadCount )
                << std::make_pair( "consumer_count", s_nConsumerThreadCount )
                << std::make_pair( "push_count", s_nQueueSize );

            std::chrono::milliseconds duration = pool.run();

            propout() << std::make_pair( "duration", duration );
        }

        template <class Queue>
        void test( Queue& q )
        {
            test_queue( q );
            analyze( q );
            propout() << q.statistics();
        }

    public:
        static void SetUpTestCase()
        {
            cds_test::config const& cfg = get_config( "queue_push_pop" );

            s_nConsumerThreadCount = cfg.get_size_t( "ConsumerCount", s_nConsumerThreadCount );
            s_nProducerThreadCount = cfg.get_size_t( "ProducerCount", s_nProducerThreadCount );
            s_nQueueSize = cfg.get_size_t( "QueueSize", s_nQueueSize );

            if ( s_nConsumerThreadCount == 0u )
                s_nConsumerThreadCount = 1;
            if ( s_nProducerThreadCount == 0u )
                s_nProducerThreadCount = 1;
            if ( s_nQueueSize == 0u )
                s_nQueueSize = 1000;
        }

        //static void TearDownTestCase();
    };

    CDSSTRESS_MSQueue( queue_push_pop )
    CDSSTRESS_MoirQueue( queue_push_pop )
    CDSSTRESS_BasketQueue( queue_push_pop )
    CDSSTRESS_OptimsticQueue( queue_push_pop )
    CDSSTRESS_FCQueue( queue_push_pop )
    CDSSTRESS_FCDeque( queue_push_pop )
    CDSSTRESS_RWQueue( queue_push_pop )
    CDSSTRESS_StdQueue( queue_push_pop )

#undef CDSSTRESS_Queue_F
#define CDSSTRESS_Queue_F( test_fixture, type_name, level ) \
    TEST_F( test_fixture, type_name ) \
    { \
        if ( !check_detail_level( level )) return; \
        typedef queue::Types< value_type >::type_name queue_type; \
        queue_type queue( s_nQueueSize ); \
        test( queue ); \
    }

    CDSSTRESS_VyukovQueue( queue_push_pop )

#undef CDSSTRESS_Queue_F

    // ********************************************************************
    // SegmentedQueue test

    class segmented_queue_push_pop
        : public queue_push_pop
        , public ::testing::WithParamInterface< size_t >
    {
        typedef queue_push_pop base_class;

    protected:

        template <typename Queue>
        void test()
        {
            size_t quasi_factor = GetParam();

            Queue q( quasi_factor );
            propout() << std::make_pair( "quasi_factor", quasi_factor );
            base_class::test_queue( q );
            analyze( q, quasi_factor * 2, quasi_factor );
            propout() << q.statistics();
        }

    public:
        static std::vector< size_t > get_test_parameters()
        {
            cds_test::config const& cfg = cds_test::stress_fixture::get_config( "queue_push_pop" );
            bool bIterative = cfg.get_bool( "SegmentedQueue_Iterate", false );
            size_t quasi_factor = cfg.get_size_t( "SegmentedQueue_SegmentSize", 256 );

            std::vector<size_t> args;
            if ( bIterative && quasi_factor > 4 ) {
                for ( size_t qf = 4; qf <= quasi_factor; qf *= 2 )
                    args.push_back( qf );
            }
            else {
                if ( quasi_factor > 2 )
                    args.push_back( quasi_factor );
                else
                    args.push_back( 2 );
            }

            return args;
        }
    };

#define CDSSTRESS_Queue_F( test_fixture, type_name, level ) \
    TEST_P( test_fixture, type_name ) \
    { \
        if ( !check_detail_level( level )) return; \
        typedef typename queue::Types<value_type>::type_name queue_type; \
        test< queue_type >(); \
    }

    CDSSTRESS_SegmentedQueue( segmented_queue_push_pop )

    INSTANTIATE_TEST_CASE_P( SQ,
        segmented_queue_push_pop,
        ::testing::ValuesIn( segmented_queue_push_pop::get_test_parameters()));

} // namespace


text:
<?php

namespace MtHaml\NodeVisitor;

use MtHaml\Node\Tag;

class Autoclose extends NodeVisitorAbstract
{
    protected $autocloseTags;

    public function __construct(array $autocloseTags)
    {
        $this->autocloseTags = $autocloseTags;
    }

    public function enterTag(Tag $tag)
    {
        if ($tag->hasChilds() || $tag->hasContent()) {
            return;
        }
        if (in_array($tag->getTagName(), $this->autocloseTags)) {
            $tag->setFlag(Tag::FLAG_SELF_CLOSE);
        }
    }
}


text:
bool regions_are_disjoint(struct Stack*restrict local_stack_a, struct Stack*restrict local_stack_b,
    struct Region*a, struct Region*b)
{
    return float_intervals_are_disjoint(local_stack_a, local_stack_b, &a->real_interval,
        &b->real_interval) ||
        float_intervals_are_disjoint(local_stack_a, local_stack_b, &a->imaginary_interval,
            &b->imaginary_interval);
}

bool region_a_contains_b(struct Stack*restrict local_stack_a, struct Stack*restrict local_stack_b,
    struct Region*a, struct Region*b)
{
    return float_interval_a_contains_b(local_stack_a, local_stack_b, &a->real_interval,
        &b->real_interval) &&
        float_interval_a_contains_b(local_stack_a, local_stack_b, &a->imaginary_interval,
            &b->imaginary_interval);
}


text:
package md53052d9c2a86af750b51b35ac708b39bc;

public class BackgroundMonitor
	extends mono.android.app.Application
	implements
		mono.android.IGCUserPeer,
		com.estimote.sdk.BeaconManager.ServiceReadyCallback
{
	static final String __md_methods;
	static {
		__md_methods =
			"n_onCreate:()V:GetOnCreateHandler\n" +
			"n_onTerminate:()V:GetOnTerminateHandler\n" +
			"n_onServiceReady:()V:GetOnServiceReadyHandler:EstimoteSdk.BeaconManager/IServiceReadyCallbackInvoker, Xamarin.Estimote.Android\n" +
			"";
	}

	public BackgroundMonitor () throws java.lang.Throwable
	{
		super ();
	}

	public void onCreate ()
	{
		mono.android.Runtime.register ("RetailBeacon.Droid.BackgroundMonitor, RetailBeacon.Droid, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", BackgroundMonitor.class, __md_methods);
		n_onCreate ();
	}

	private native void n_onCreate ();

	public void onTerminate ()
	{
		n_onTerminate ();
	}

	private native void n_onTerminate ();

	public void onServiceReady ()
	{
		n_onServiceReady ();
	}

	private native void n_onServiceReady ();

	java.util.ArrayList refList;
	public void monodroidAddReference (java.lang.Object obj)
	{
		if (refList == null)
			refList = new java.util.ArrayList ();
		refList.add (obj);
	}

	public void monodroidClearReferences ()
	{
		if (refList != null)
			refList.clear ();
	}
}


text:
//
// Created by Zrs_y on 4/18/16.
//

#ifndef PELOTON_SQLITE_H
#define PELOTON_SQLITE_H

#include "database.h"
#include <stdlib.h>
#include <sqlite3.h>
#include <stdio.h>

namespace peloton {
namespace wiredb {

#define UNUSED __attribute__((unused))
class Sqlite : public DataBase {

public:
  Sqlite() {
    // sqlite3_open(filename, sqlite3 **db)
    // filename is null for in memory db
    auto rc = sqlite3_open_v2("ycsb.db", &db, SQLITE_OPEN_NOMUTEX|SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, NULL);
    if (rc) {
      fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
      LOG_ERROR("Can't open database %s", sqlite3_errmsg(db));
      exit(0);
    } else {
      fprintf(stderr, "Opened database successfully\n");
    }

    // TODO: remove test
    //test();
  }

  virtual ~Sqlite() {
    sqlite3_close(db);
  }

  /*
   * PortalExec - Execute query string
   */
  virtual int PortalExec(const char *query,
                         std::vector<ResType> &res,
                         std::vector<FieldInfoType> &info,
                         int &rows_change,
                         std::string &err_msg) {
    LOG_INFO("receive %s", query);
    sqlite3_stmt *sql_stmt;
    sqlite3_prepare_v2(db, query, -1, &sql_stmt, NULL);
    GetRowDesc(sql_stmt, info);
    return ExecPrepStmt(sql_stmt, true, res, rows_change, err_msg);
  }
/*

  int PortalDesc(const char *table_name, std::vector<FieldInfoType> &field_info, std::string &err_msg) {

    char *zErrMsg = 0;

    std::string query = "PRAGMA table_info(" + std::string(table_name) + ");";
    LOG_INFO("describle query %s", query.c_str());
    auto rc = sqlite3_exec(db, query.c_str(), descCallback, (void *) &field_info, &zErrMsg);
    if (rc != SQLITE_OK) {
      LOG_INFO("error in des %s", zErrMsg);
      if (zErrMsg != NULL)
        err_msg = std::string(zErrMsg);
        sqlite3_free(zErrMsg);
      return 1;
    } else {
      return 0;
    }
  }
*/

  /*
   * InitBindPrepStmt - Prepare and bind a query from a query string
   */
  int PrepareStmt(const char *query, sqlite3_stmt **stmt, std::string &err_msg) {
    int rc = sqlite3_prepare_v2(db, query, -1, stmt, NULL);
    if (rc != SQLITE_OK) {
      err_msg = std::string(sqlite3_errmsg(db));
      return 1;
    }

    return 0;
  }

  int BindStmt(std::vector<std::pair<int, std::string>> &parameters,
               sqlite3_stmt **stmt, std::string &err_msg) {

    int paramno = 1;
    for (auto &param : parameters) {
      auto wire_type = param.first;
      auto &wire_val = param.second;
      int rc;
      switch (wire_type) {
        case WIRE_INTEGER: {
          int int_val = std::stoi(wire_val);
          LOG_INFO("BIND INT: %d", int_val);
          rc = sqlite3_bind_int(*stmt, paramno, int_val);
        } break;
        case WIRE_FLOAT: {
          double double_val = std::stod(wire_val);
          LOG_INFO("BIND FLOAT: %lf", double_val);
          rc = sqlite3_bind_double(*stmt, paramno, double_val);
        } break;
        case WIRE_TEXT: {
          const char *str_val = wire_val.c_str();
          size_t str_len = wire_val.size();
          LOG_INFO("BIND TEXT: %s", str_val);
          rc = sqlite3_bind_text(*stmt, paramno, str_val, (int) str_len,
                                 SQLITE_TRANSIENT);
        } break;

        case WIRE_NULL: {
          LOG_INFO("BIND NULL");
          rc = sqlite3_bind_null(*stmt, paramno);
          break;
        }
        default: {
          LOG_INFO("Unknown bind type");
          return 1;
        }
      }
      if (rc != SQLITE_OK) {
        LOG_INFO("Error in binding: %s", sqlite3_errmsg(db));
        err_msg = std::string(sqlite3_errmsg(db));
        return 1;
      }
      paramno++;
    }

    return 0;
  }

  /*
   * GetRowDesc - Get RowDescription of a query
   */
  void GetRowDesc(void *stmt, std::vector<FieldInfoType> &info) {
    auto sql_stmt = (sqlite3_stmt *)stmt;
    auto col_num = sqlite3_column_count(sql_stmt);
    for (int i = 0; i < col_num; i++) {
      int t = sqlite3_column_type(sql_stmt, i);
      const char *name = sqlite3_column_name(sql_stmt, i);
      LOG_INFO("name: %s", name);
      switch (t) {
        case SQLITE_INTEGER: {
          LOG_INFO("col int");
          info.push_back(std::make_tuple(name, 23, 4));
          break;
        }
        case SQLITE_FLOAT: {
          LOG_INFO("col float");
          info.push_back(std::make_tuple(name, 701, 8));
          break;
        }
        case SQLITE_TEXT: {
          LOG_INFO("col text");
          info.push_back(std::make_tuple(name, 25, 255));
          break;
        }
        default: {
          // Workaround for empty results, should still return something
          LOG_ERROR("Unrecognized column type: %d", t);
          info.push_back(std::make_tuple(name, 25, 255));
          break;
        }
      }
    }
  }

  /*
   * ExecPrepStmt - Execute a statement from a prepared and bound statement
   */
  int ExecPrepStmt(void *stmt, bool unnamed, std::vector<ResType> &res,
                   int &rows_change,
                   std::string &err_msg) {

    LOG_INFO("Executing statement......................");
    auto sql_stmt = (sqlite3_stmt *)stmt;
    auto ret = sqlite3_step(sql_stmt);
    LOG_INFO("ret: %d", ret);
    auto col_num = sqlite3_column_count(sql_stmt);
    LOG_INFO("column count: %d", col_num);

    while (ret == SQLITE_ROW) {
      for (int i = 0; i < col_num; i++) {
        int t = sqlite3_column_type(sql_stmt, i);
        const char *name = sqlite3_column_name(sql_stmt, i);
        std::string value;
        switch (t) {
          case SQLITE_INTEGER: {
            int v = sqlite3_column_int(sql_stmt, i);
            value = std::to_string(v);
            break;
          }
          case SQLITE_FLOAT: {
            double v = (double) sqlite3_column_double(sql_stmt, i);
            value = std::to_string(v);
            break;
          }
          case SQLITE_TEXT: {
            const char *v = (char *) sqlite3_column_text(sql_stmt, i);
            value = std::string(v);
            break;
          }
          default: break;
        }
        // TODO: refactor this
        res.push_back(ResType());
        //LOG_INFO("res from exeStmt %s %s", name, value.c_str());
        copyFromTo(name, res.back().first);
        copyFromTo(value.c_str(), res.back().second);
      }
      ret = sqlite3_step(sql_stmt);
    }

    if (unnamed)
      sqlite3_finalize(sql_stmt);
    else
      sqlite3_reset(sql_stmt);
    sqlite3_db_release_memory(db);
    // sql_stmt = nullptr;
    if (ret != SQLITE_DONE) {
      LOG_INFO("ret num %d, err is %s", ret, sqlite3_errmsg(db));
      err_msg = std::string(sqlite3_errmsg(db));
      return 1;
    }
    rows_change = sqlite3_changes(db);
    return 0;
  }

private:
  void test() {
      LOG_INFO("RUN TEST");

      std::vector<ResType> res;
      std::vector<FieldInfoType> info;
      std::string err;
      int rows;

      // create table
      PortalExec("DROP TABLE IF EXISTS AA", res, info, rows, err);
      PortalExec("CREATE TABLE AA (id INT PRIMARY KEY, data TEXT);", res, info, rows, err);
      res.clear();

      // test simple insert
      PortalExec("INSERT INTO AA VALUES (1, 'abc'); ", res, info, rows, err);
      std::vector<std::pair<int, std::string>> parameters;
      parameters.push_back(std::make_pair(WIRE_TEXT, std::string("12")));
      parameters.push_back(std::make_pair(WIRE_TEXT, std::string("abc")));

      // test bind
      sqlite3_stmt *s;
      PrepareStmt("insert into AA (id, data) values ( ?, ? )", &s, err);
      BindStmt(parameters, &s, err);
      GetRowDesc(s, info);
      ExecPrepStmt(s, false, res, rows, err);
      BindStmt(parameters, &s, err);
      GetRowDesc(s, info);
      ExecPrepStmt(s, false, res, rows, err);
      res.clear();

      // select all
      sqlite3_stmt *sql_stmt;
      sqlite3_prepare_v2(db, "select * from AA;", -1, &sql_stmt, NULL);
      res.clear();
      info.clear();
      GetRowDesc(s, info);
      ExecPrepStmt(sql_stmt, false, res, rows, err);

      // res.size() should be 4
      // info.size() should be 2
      LOG_INFO("col %ld, info %ld", res.size(), info.size());

      res.clear();
  }

  static inline void copyFromTo(const char *src, std::vector<unsigned char> &dst) {
    if (src == nullptr) {
      return;
    }
    //LOG_INFO("ENTER: strlen: %zu", strlen(src));
    for(unsigned int i = 0; i < strlen(src); i++){
      dst.push_back((unsigned char)src[i]);
    }
    //LOG_INFO("EXIT: strlen: %zu", strlen(src));
  }

  static int execCallback(void *res, int argc, char **argv, char **azColName){
    auto output = (std::vector<ResType> *)res;
    for(int i = 0; i < argc; i++){
      output->push_back(ResType());
      if (argv[i] == NULL) {
        LOG_INFO("value is null");
      }else if(azColName[i] == NULL) {
        LOG_INFO("name is null");
      }else {
        LOG_INFO("res %s %s", azColName[i], argv[i]);
      }
      copyFromTo(azColName[i], output->at(i).first);
      copyFromTo(argv[i], output->at(i).second);
    }

    return 0;
  }

  static int getSize(const std::string& type UNUSED) {
    return 0;
  }
  /*
  static int descCallback(void *res, int argc, char **argv, char **azColName){
    auto output = (std::vector<FieldInfoType> *)res;
    std::string name, type;
    for(int i = 0; i < argc; i++){
      output->push_back(FieldInfoType());
      if (argv[i] == NULL) {
        LOG_INFO("value is null");
      }else if(azColName[i] == NULL) {
        LOG_INFO("name is null");
      }else {
        if(strcmp(azColName[i], "name") == 0) {
          LOG_INFO("name is %s", argv[i]);
          name = std::string(argv[i]);
        }else if(strcmp(azColName[i], "type") == 0) {
          LOG_INFO("type is %s", argv[i]);
          type = std::string(argv[i]);
        }
      }

      int size = getSize(type);
      output->push_back(std::make_tuple(name, type, size));
      return 0;
    }

    return 0;
  }
   */

private:
  sqlite3 *db;
};
}
}

#endif //PELOTON_SQLITE_H


text:
import Data.List (maximumBy)

-- Computes the multiplicative order of a number. It just so happens that the
-- multiplicative order of n and 10 is equal to the length of the decimal period of
-- m/n :)
multOrder :: Int -> Int -> Int
multOrder n a = f n a 1 1
  where
    f n a a' c = if a'' == 1 then c else f n a a'' (c+1)
      where a'' = a*a' `mod` n

solve :: Int
solve = fst $ maximumBy (\(_,x) (_,y) -> compare x y) $ map (\(n,x) -> (n,multOrder x 10)) $ filter (\(_,x) -> gcd x 10 == 1) $ zip [2..999] [2..999]

main = putStrLn $ show solve


text:
package jp.co.ctc_g.jfw.test.unit;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.ResourceBundle;

import jp.co.ctc_g.jfw.core.internal.InternalException;
import jp.co.ctc_g.jfw.core.internal.InternalMessages;
import jp.co.ctc_g.jfw.core.util.Maps;
import jp.co.ctc_g.jfw.core.util.Strings;

import org.apache.commons.io.IOUtils;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.io.Files;

/**
 *

 * このクラスは、テスト時にファイルの内容を確認する際に指定されたファイルの内容をコピーします。
 *

 *

 * 読込対象のファイルはこのクラスのインスタンス生成時に指定されたクラスのクラスパスよりロードします。
 * つまり、テスト対象のクラスがjp/co/ctc_g/jfw/sample/FooServiceTestの場合は
 * jp/co/ctc_g/jfw/sampleにテスト用のファイルを配置されたものをロードします。
 *

 *

 * このクラスを利用した単純なテストの実施方法を以下に示します。
 *

 *

 * public class FooServiceTest {
 *   @Autowired
 *   protected FooService service;
 *
 *   @Rule
 *   public FileInitailize file = new FileInitailize(FooService.class);
 *
 *   @Test
 *   public void test() {
 *     File f = file.copy("test.csv", "temp.csv");
 *     String content = FileUtils.readFileToString(tmp, "MS932");
 *     assertThat(content, is(file.load("test.csv")));
 *   }
 * }
 *

 * @author ITOCHU Techno-Solutions Corporation.
 */
public class FileInitailize extends TemporaryFolder {

    private static final Logger L = LoggerFactory.getLogger(FileInitailize.class);
    private static final ResourceBundle R = InternalMessages.getBundle(FileInitailize.class);
    private static final String DEFAULT_FILE_ENCODE = "MS932";
    private static final String URL_ENCODE = "UTF-8";
    private Class<?> target;
    private String encode = DEFAULT_FILE_ENCODE;

    /**
     * デフォルトコンストラクタです。
     */
    public FileInitailize() {}

    /**
     * コンストラクタです。
     * @param target 読込ファイルパスのターゲットとなるクラス
     */
    public FileInitailize(Class<?> target) {
        this.target = target;
    }

    /**
     * コンストラクタです。
     * @param target 読込ファイルパスのターゲットとなるクラス
     * @param encode ファイルエンコード
     */
    public FileInitailize(Class<?> target, String encode) {
        this(target);
        this.encode = encode;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void before() throws Throwable {
        super.before();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void after() {
        super.after();
    }

    /**
     * 指定されたファイルのデータを指定されたファイルへコピーする処理です。
     * @param src コピー元ファイル名
     * @param dest コピー先ファイル名
     * @return ファイルのインスタンス
     */
    public File copy(String src, String dest) {
        L.debug(Strings.substitute(R.getString("D-TEST#0002"), Maps.hash("src", src).map("dest", dest)));
        InputStream is = null;
        File destFile = null;
        InternalException exception = null;
        try {
            is = target.getResourceAsStream(URLDecoder.decode(src, URL_ENCODE));
            String contents = IOUtils.toString(is, encode);
            destFile = super.newFile(dest);
            Files.write(contents, destFile, Charset.forName(encode));
        } catch (IOException e) {
            exception = new InternalException(FileInitailize.class, "E-TEST#0018");
        } finally {
            try {
                if (is != null) is.close();
            } catch(IOException e) {
                if (exception == null) {
                    exception = new InternalException(FileInitailize.class, "E-TEST#0019");
                }
            }
            if (exception != null) throw exception;
        }
        return destFile;
    }

    /**
     * ファイルのデータをロードします。
     * @param src ファイルパス
     * @return ファイルデータ
     */
    public String load(String src) {
        L.debug(Strings.substitute(R.getString("D-TEST#0003"), Maps.hash("src", src)));
        InputStream is = null;
        String content = "";
        InternalException exception = null;
        try {
            is = target.getResourceAsStream(URLDecoder.decode(src, URL_ENCODE));
            content = IOUtils.toString(is, encode);
        } catch (IOException e) {
            exception = new InternalException(FileInitailize.class, "E-TEST#0020");
        } finally {
            try {
                if (is != null) is.close();
            } catch(IOException e) {
                if (exception == null) {
                    exception = new InternalException(FileInitailize.class, "E-TEST#0019");
                }
            }
            if (exception != null) throw exception;
        }
        return content;
    }

}


text:
.. Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project
   All rights reserved.

   This file is part of NeuroM <https://github.com/BlueBrain/NeuroM>

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

       1. Redistributions of source code must retain the above copyright
          notice, this list of conditions and the following disclaimer.
       2. Redistributions in binary form must reproduce the above copyright
          notice, this list of conditions and the following disclaimer in the
          documentation and/or other materials provided with the distribution.
       3. Neither the name of the copyright holder nor the names of
          its contributors may be used to endorse or promote products
          derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Dependencies
============

Build and runtime
-----------------

.. _pre-dep-label:

``NeuroM`` requires Python version 2.6 or higher (but not version 3.x).
When installed using `pip <https://pip.pypa.io/en/stable/>`_, ``NeuroM``
will take care of installing unmet dependencies, although it is also possible
to pre-install before ``NeuroM``.

* `numpy <http://www.numpy.org/>`_ >= 1.8.0
* `scipy <http://www.scipy.org/>`_ >= 0.13.3
* `matplotlib <http://www.matplotlib.org/>`_ >= 1.3.1
* `h5py <http://www.h5py.org/>`_ >= 2.2.1
* `enum34 <https://pypi.python.org/pypi/enum34/>`_ >= 1.0.4
* `pyyaml <http://www.pyyaml.org/>`_ >= 3.10.0
* `tqdm <https://pypi.python.org/pypi/tqdm/>`_ tqdm >= 4.8.4

Installing and building
-----------------------

* `pip <https://pip.pypa.io/en/stable/>`_ version 8.1.0 or higher.
* `virtualenv <https://virtualenv.pypa.io/en/stable/>`_

Testing and documentation
-------------------------

These dependencies are not needed for installing and running ``NeuroM``,
but are useful for those who want to contribute to its development.

* `GNU Make <https://www.gnu.org/software/make/>`_
* `nose <https://nose.readthedocs.org/en/latest/>`_
* `coverage <https://coverage.readthedocs.org/en/latest/>`_
* `sphinx <http://sphinx-doc.org/>`_


text:
import contextlib
from dcos import config

@contextlib.contextmanager
def dcos_config():
    """ Context manager for altering the toml
    """

    toml_config_o = config.get_config()
    try:
        yield
    finally:
        # return config to previous state
        config.save(toml_config_o)


text:
title: Running calico/node with an init system
canonical_url: 'https://docs.projectcalico.org/v3.2/usage/configuration/as-service'
---

This guide explains how to run `{{site.nodecontainer}}` with an init system like
systemd, inside either of the following container types:
- [Docker](#running-caliconode-in-a-docker-container)
- [rkt](#running-caliconode-in-a-rkt-container)

## Running `{{site.nodecontainer}}` in a Docker container

This section describes how to run `{{site.nodecontainer}}` as a Docker container.

> **Note**: We include examples for systemd, but the commands can be
> applied to other init daemons such as upstart.
{: .alert .alert-info}

Included here is an `EnvironmentFile` that defines the environment
variables for {{site.prodname}} and a sample systemd service file that uses the
environment file and starts the `{{site.nodecontainer}}` image as a service.

`calico.env` - the `EnvironmentFile`:

```shell
ETCD_ENDPOINTS=http://localhost:2379
ETCD_CA_FILE=""
ETCD_CERT_FILE=""
ETCD_KEY_FILE=""
CALICO_NODENAME=""
CALICO_NO_DEFAULT_POOLS=""
CALICO_IP=""
CALICO_IP6=""
CALICO_AS=""
CALICO_NETWORKING_BACKEND=bird
```

Be sure to update this environment file as necessary, such as modifying
ETCD_ENDPOINTS to point at the correct etcd cluster endpoints.

> **Note**: The `ETCD_CA_FILE`, `ETCD_CERT_FILE`, and `ETCD_KEY_FILE`
> environment variables are required when using etcd with SSL/TLS. The values
> here are standard values for a non-SSL version of etcd, but you can use this
> template to define your SSL values if desired.
>
> If `CALICO_NODENAME` is blank, the compute server hostname will be used
> to identify the {{site.prodname}} node.
>
> If `CALICO_IP` or `CALICO_IP6` are left blank, {{site.prodname}} will use the currently
> configured values for the next hop IP addresses for this node—these can
> be configured through the node resource.  If no next hop addresses have
> been configured, {{site.prodname}} will automatically determine an IPv4 next hop address
> by querying the host interfaces (and it will configure this value in the
> node resource). You may set `CALICO_IP` to `autodetect` to force
> auto-detection of IP address every time the node starts. If you set IP
> addresses through these environments it will reconfigure any values currently
> set through the node resource.
>
> If `CALICO_AS` is left blank, {{site.prodname}} will use the currently configured value
> for the AS Number for the node BGP client—this can be configured through
> the node resource. If no value is set, {{site.prodname}} will inherit the AS Number
> from the global default value. If you set a value through this environment
> it will reconfigure any value currently set through the node resource.
>
> The `CALICO_NETWORKING_BACKEND` defaults to use BIRD as the routing daemon.
> This may also be set to `gobgp` (to use GoBGP as the routing daemon, but note
> that this does not support IP-in-IP), or `none` (if routing is handled by an
> alternative mechanism).
{: .alert .alert-info}

### systemd service example

`{{site.noderunning}}.service` - the systemd service:

```shell
[Unit]
Description={{site.noderunning}}
After=docker.service
Requires=docker.service

[Service]
EnvironmentFile=/etc/calico/calico.env
ExecStartPre=-/usr/bin/docker rm -f {{site.noderunning}}
ExecStart=/usr/bin/docker run --net=host --privileged \
 --name={{site.noderunning}} \
 -e NODENAME=${CALICO_NODENAME} \
 -e IP=${CALICO_IP} \
 -e IP6=${CALICO_IP6} \
 -e CALICO_NETWORKING_BACKEND=${CALICO_NETWORKING_BACKEND} \
 -e AS=${CALICO_AS} \
 -e NO_DEFAULT_POOLS=${CALICO_NO_DEFAULT_POOLS} \
 -e ETCD_ENDPOINTS=${ETCD_ENDPOINTS} \
 -e ETCD_CA_CERT_FILE=${ETCD_CA_CERT_FILE} \
 -e ETCD_CERT_FILE=${ETCD_CERT_FILE} \
 -e ETCD_KEY_FILE=${ETCD_KEY_FILE} \
 -v /var/log/calico:/var/log/calico \
 -v /run/docker/plugins:/run/docker/plugins \
 -v /lib/modules:/lib/modules \
 -v /var/run/calico:/var/run/calico \
 {{site.imageNames["node"]}}:{{site.data.versions[page.version].first.title}}

ExecStop=-/usr/bin/docker stop {{site.noderunning}}

Restart=on-failure
StartLimitBurst=3
StartLimitInterval=60s

[Install]
WantedBy=multi-user.target
```

The systemd service above does the following on start:
  - Confirm Docker is installed under the `[Unit]` section
  - Get environment variables from the environment file above
  - Remove existing `{{site.nodecontainer}}` container (if it exists)
  - Start `{{site.nodecontainer}}`

The script will also stop the `{{site.nodecontainer}}` container when the service is stopped.

> **Note**: Depending on how you've installed Docker, the name of the Docker service
> under the `[Unit]` section may be different (such as `docker-engine.service`).
> Be sure to check this before starting the service.
{: .alert .alert-info}

## Running `{{site.nodecontainer}}` in a rkt container

Each {{site.prodname}}-rkt enabled node requires the `{{site.nodecontainer}}` container to be running.

The `{{site.nodecontainer}}` container can be run directly through rkt and needs to be run as
as a fly stage-1 container.

```shell
sudo rkt run --stage1-path=/usr/share/rkt/stage1-fly.aci \
  --set-env=ETCD_ENDPOINTS=http://<ETCD_IP>:<ETCD_PORT> \
  --set-env=IP=autodetect \
  --insecure-options=image \
  --volume=birdctl,kind=host,source=/var/run/calico,readOnly=false \
  --mount=volume=birdctl,target=/var/run/calico \
  --volume=mods,kind=host,source=/lib/modules,readOnly=false  \
  --mount=volume=mods,target=/lib/modules \
  --volume=logs,kind=host,source=/var/log/calico,readOnly=false \
  --mount=volume=logs,target=/var/log/calico \
  --net=host \
  {{site.imageNames["node"]}}:{{site.data.versions[page.version].first.title}} &
```

> **Note**: Replace `<ETCD_IP>:<ETCD_PORT>` with your etcd configuration. The `ETCD_ENDPOINTS`
> environment may contain a comma separated list of endpoints of your etcd cluster.
{: .alert .alert-info}

You can check that it's running using `sudo rkt list`.

```shell
$ sudo rkt list
UUID      APP	IMAGE NAME                  STATE   CREATED         STARTED         NETWORKS
b52bba11  node  {{site.imageNames["node"]}}:{{site.data.versions[page.version].first.title}}  running 10 seconds ago  10 seconds ago
```


text:
<?php

namespace PictureArchiveBundle\Service\Import;

use PictureArchiveBundle\Component\Configuration;
use PictureArchiveBundle\Component\FileInfo;
use PictureArchiveBundle\Event\ImportAnalysisFailedEvent;
use PictureArchiveBundle\Event\ImportFileEvent;

/**
 *
 * @package PictureArchiveBundle\Service\Import
 * @author Moki <picture-archive@mokis-welt.de>
 */
class FailedHandler
{
    /**
     * @var Configuration
     */
    private $configuration;

    /**
     * Report constructor.
     * @param Configuration $configuration
     */
    public function __construct(Configuration $configuration)
    {
        $this->configuration = $configuration;
    }

    /**
     * @param ImportFileEvent $importEvent
     * @throws \RuntimeException
     */
    public function moveFile(ImportFileEvent $importEvent): void
    {
        if ($importEvent instanceof ImportAnalysisFailedEvent) {
            if (FileInfo::STATUS_WAIT === $importEvent->getFileInfo()->getStatus()) {
                return;
            }
        }

        $importFile = $importEvent->getFileInfo();

        $failedDirectory = new \SplFileInfo($this->configuration->getImportFailedDirectory());

        if (!$failedDirectory->isDir() && !mkdir($failedDirectory->getPathname(), 0775, true)) {
            throw new \RuntimeException("could not create directory '{$failedDirectory->getPathname()}'");
        }

        if (!$failedDirectory->isWritable()) {
            throw new \RuntimeException("directory '{$failedDirectory->getPathname()}' is not writable");
        }

        $targetPathname = $failedDirectory->getPathname() . '/' . $importFile->getFilename();

        rename($importFile->getPathname(), $targetPathname);
    }
}


text:
const {createAddColumnMigration} = require('../../utils');

module.exports = createAddColumnMigration('products', 'yearly_price_id', {
    type: 'string',
    maxlength: 24,
    nullable: true
});