text:
/*	$Id: brsearch.c,v 1.8 2009/08/09 23:47:53 nis Exp $	*/

/*-
 * Copyright (c) 2001 Shingo Nishioka.
 * All rights reserved.
 *
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 *
 */

#if ! defined lint
static char rcsid[] = "$Id: brsearch.c,v 1.8 2009/08/09 23:47:53 nis Exp $";
#endif

#include <config.h>

#include <sys/types.h>
#include <sys/time.h>

#include <stdio.h>
#include <stdlib.h>

#include "util.h"

#include <gifnoc.h>

int
brsearch(key, base, nmemb, size, compar, left, right)
const void *key, *base;
size_t nmemb, size;
int (*compar)(const void *, const void *);
size_t *left, *right;
{
	size_t l, m, r;
	int e;
#define	BASE(m)	((char *)base + (m) * size)

	if (nmemb == 0) {
		*left = *right = 0;
		return -1;
	}

	for (l = 0, r = nmemb; l < r-1;) {
		m = (l + r - 1) / 2;
		if ((*compar)(key, BASE(m)) > 0) {
			l = m + 1;
		}
		else {
			r = m + 1;
		}
	}
	e = (*compar)(key, BASE(l));
	if (e < 0) {
		*left = *right = l;
		return -1;
	}
	else if (e > 0) {
		*left = *right = r;
		return -1;
	}
	*left = l;
	for (r = nmemb; l < r - 1; ) {
		m = (l + r) / 2;
		if ((*compar)(key, BASE(m)) >= 0) {
			l = m;
		}
		else {
			r = m;
		}
	}
	*right = r;
	return 0;
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Class impl</title>
<link rel="stylesheet" href="../../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../../index.html" title="Chapter 1. Boost.Log v2">
<link rel="up" href="../counter.html#idm31933" title="Description">
<link rel="prev" href="../counter.html" title="Class template counter">
<link rel="next" href="../current_process_id.html" title="Class current_process_id">

Class impl

boost::log::attributes::counter::impl — Factory implementation.

Synopsis

// In header: <boost/log/attributes/counter.hpp>

// Factory implementation.

class impl : public attribute::impl {
public:
  // construct/copy/destruct
  impl(value_type, value_type) noexcept;

  // public member functions
  virtual attribute_value get_value();
};

Description

impl
        public
       construct/copy/destruct

impl(value_type initial, value_type step) noexcept;

impl public member functions

virtual attribute_value get_value();

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

Returns:

The actual attribute value. It shall not return empty values (exceptions shall be used to indicate errors).

Copyright © 2007-2021 Andrey Semashev

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).

redpajama_set_name: RedPajamaGithub


text:
CREATE DATABASE company;

-- Create table company
CREATE TABLE company(
  id integer NOT NULL,
  name character varying,
  CONSTRAINT company_pkey PRIMARY KEY (id)
);
INSERT INTO company(id, name) VALUES (1, 'Tele2');
INSERT INTO company(id, name) VALUES (5, 'MTS');

-- Create table person
CREATE TABLE person(
  id integer NOT NULL,
  name character varying,
  company_id integer,
  CONSTRAINT person_pkey PRIMARY KEY (id)
);

INSERT INTO person(id, name, company_id ) VALUES (1, 'Kevin', (SELECT id FROM company c WHERE c.name='MTS'));
INSERT INTO person(id, name, company_id ) VALUES (2, 'Mark', (SELECT id FROM company c WHERE c.name='MTS'));
INSERT INTO person(id, name, company_id ) VALUES (3, 'Paul', (SELECT id FROM company c WHERE c.name='Tele2'));
INSERT INTO person(id, name, company_id ) VALUES (4, 'John', (SELECT id FROM company c WHERE c.name='MTS'));
INSERT INTO person(id, name, company_id ) VALUES (5, 'Adam', (SELECT id FROM company c WHERE c.name='Tele2'));
INSERT INTO person(id, name, company_id ) VALUES (6, 'Carl', (SELECT id FROM company c WHERE c.name='MTS'));

-- Select
-- 1
SELECT p.name, c.name  FROM person AS p
  JOIN company AS c ON p.company_id=c.id
  WHERE NOT c.id = 5;

-- 2
SELECT t1.name, count_persone FROM (SELECT c.name, count(p) as count_persone FROM person AS p
  JOIN company AS c On p.company_id=c.id
  GROUP BY c.name) AS t1 WHERE count_persone = (SELECT max(count_persone) FROM (SELECT c.name, count(p) as count_persone FROM person AS p
  JOIN company AS c On p.company_id=c.id
GROUP BY c.name) t2);


text:
package ua.com.fielden.platform.web.centre.api.resultset;

import ua.com.fielden.platform.basic.IValueMatcherWithContext;
import ua.com.fielden.platform.entity.AbstractEntity;

public interface IResultSetAutocompleterWithMatcher<T extends AbstractEntity<?>> extends IResultSetAutocompleterConfigAdditionalProps<T>{

    /**
     * A method to provide custom value matcher type.
     *
     * @param matcher
     * @return
     */
    IResultSetAutocompleterConfigAdditionalProps<T> withMatcher(final Class<? extends IValueMatcherWithContext<T, ?>> matcherType);
}


text:
using content::InterstitialPage;
using content::WebContents;
using content::WebContentsTester;

static const char* kURL1 = "http://www.google.com/";
static const char* kURL2 = "http://www.gmail.com/";

namespace chromeos {

class OfflineLoadPageTest;

// An OfflineLoadPage class that does not create windows.
class TestOfflineLoadPage :  public chromeos::OfflineLoadPage {
 public:
  TestOfflineLoadPage(WebContents* web_contents,
                      const GURL& url,
                      OfflineLoadPageTest* test_page)
    : chromeos::OfflineLoadPage(web_contents, url, CompletionCallback()),
      test_page_(test_page) {
    interstitial_page_->DontCreateViewForTesting();
  }

  // chromeos::OfflineLoadPage override.
  virtual void NotifyBlockingPageComplete(bool proceed) OVERRIDE;

 private:
  OfflineLoadPageTest* test_page_;

  DISALLOW_COPY_AND_ASSIGN(TestOfflineLoadPage);
};

class OfflineLoadPageTest : public ChromeRenderViewHostTestHarness {
 public:
  // The decision the user made.
  enum UserResponse {
    PENDING,
    OK,
    CANCEL
  };

  virtual void SetUp() {
    ChromeRenderViewHostTestHarness::SetUp();
    user_response_ = PENDING;
  }

  void OnBlockingPageComplete(bool proceed) {
    if (proceed)
      user_response_ = OK;
    else
      user_response_ = CANCEL;
  }

  void Navigate(const char* url, int page_id) {
    WebContentsTester::For(web_contents())->TestDidNavigate(
        web_contents()->GetRenderViewHost(), page_id, GURL(url),
        content::PAGE_TRANSITION_TYPED);
  }

  void ShowInterstitial(const char* url) {
    (new TestOfflineLoadPage(web_contents(), GURL(url), this))->Show();
  }

  // Returns the OfflineLoadPage currently showing or NULL if none is
  // showing.
  InterstitialPage* GetOfflineLoadPage() {
    return InterstitialPage::GetInterstitialPage(web_contents());
  }

  UserResponse user_response() const { return user_response_; }

 private:
  friend class TestOfflineLoadPage;

  UserResponse user_response_;

  // Initializes / shuts down a stub CrosLibrary.
  chromeos::ScopedStubCrosEnabler stub_cros_enabler_;
};

void TestOfflineLoadPage::NotifyBlockingPageComplete(bool proceed) {
  test_page_->OnBlockingPageComplete(proceed);
}

TEST_F(OfflineLoadPageTest, OfflinePageProceed) {
  // Start a load.
  Navigate(kURL1, 1);
  // Load next page.
  controller().LoadURL(GURL(kURL2), content::Referrer(),
                       content::PAGE_TRANSITION_TYPED, std::string());

  // Simulate the load causing an offline browsing interstitial page
  // to be shown.
  ShowInterstitial(kURL2);
  InterstitialPage* interstitial = GetOfflineLoadPage();
  ASSERT_TRUE(interstitial);
  base::MessageLoop::current()->RunUntilIdle();

  // Simulate the user clicking "proceed".
  interstitial->Proceed();
  base::MessageLoop::current()->RunUntilIdle();

  EXPECT_EQ(OK, user_response());

  // The URL remains to be URL2.
  EXPECT_EQ(kURL2, web_contents()->GetURL().spec());

  // Commit navigation and the interstitial page is gone.
  Navigate(kURL2, 2);
  EXPECT_FALSE(GetOfflineLoadPage());
}

// Tests showing an offline page and not proceeding.
TEST_F(OfflineLoadPageTest, OfflinePageDontProceed) {
  // Start a load.
  Navigate(kURL1, 1);
  controller().LoadURL(GURL(kURL2), content::Referrer(),
                       content::PAGE_TRANSITION_TYPED, std::string());

  // Simulate the load causing an offline interstitial page to be shown.
  ShowInterstitial(kURL2);
  InterstitialPage* interstitial = GetOfflineLoadPage();
  ASSERT_TRUE(interstitial);
  base::MessageLoop::current()->RunUntilIdle();

  // Simulate the user clicking "don't proceed".
  interstitial->DontProceed();

  // The interstitial should be gone.
  EXPECT_EQ(CANCEL, user_response());
  EXPECT_FALSE(GetOfflineLoadPage());
  // We did not proceed, the pending entry should be gone.
  EXPECT_FALSE(controller().GetPendingEntry());
  // the URL is set back to kURL1.
  EXPECT_EQ(kURL1, web_contents()->GetURL().spec());
}

}  // namespace chromeos


text:
select KYLIN_SALES.lstg_format_name,sum(KYLIN_SALES.price) as GMV
 , count(*) as TRANS_CNT
 from

 KYLIN_SALES

 inner JOIN kylin_category_groupings
 ON KYLIN_SALES.leaf_categ_id = kylin_category_groupings.leaf_categ_id AND KYLIN_SALES.lstg_site_id = kylin_category_groupings.site_id

 inner JOIN (select cal_dt,week_beg_dt from KYLIN_CAL_DT  where week_beg_dt >= DATE '2012-04-10'  ) xxx
 ON KYLIN_SALES.PART_DT = xxx.cal_dt

inner JOIN (select cal_dt,week_beg_dt from KYLIN_CAL_DT  where week_beg_dt >= DATE '2013-01-01'  ) xxx2
ON KYLIN_SALES.PART_DT = xxx2.cal_dt

  where kylin_category_groupings.meta_categ_name <> 'Baby'

 group by KYLIN_SALES.lstg_format_name


text:
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta charset="utf-8" />

  <title>WebGL Orrery - Student ID: 110059875</title>

  <canvas id="canvas" style="width:100%;height:80%">
    Your browser does not support HTML5 Canvas! :(
  </canvas>

Loading Textures

Click and drag to pan around,
scroll to zoom!

      Zoom: -10

        <input id="zoomSlider" type="range" min="-100" max="0" value="-10" />

      Field of View: 45 degrees

        <input id="fovSlider" type="range" min="10" max="120" value="45" />

      Simulation Speed: 100%

        <input id="simSpeedSlider" type="range" min="0" max="1000" value="100" step="10" />

      Ambient Lighting:

      R: 0.2
        <input id="ambientR" type="range" min="0" max="1" value="0.2" step="0.1" />

      G: 0.2
        <input id="ambientG" type="range" min="0" max="1" value="0.2" step="0.1" />

      B: 0.2
        <input id="ambientB" type="range" min="0" max="1" value="0.2" step="0.1" />

    Point Lighting:

        R: 1.0
          <input id="pointR" type="range" min="0" max="1" value="1.0" step="0.1" />

        G: 1.0
          <input id="pointG" type="range" min="0" max="1" value="1.0" step="0.1" />

        B: 1.0
          <input id="pointB" type="range" min="0" max="1" value="1.0" step="0.1" />

        X: 0
          <input id="pointX" type="range" min="-10" max="10" value="0" step="0.1" />

        Y: 0
          <input id="pointY" type="range" min="-10" max="10" value="0" step="0.1" />

        Z: 0
          <input id="pointZ" type="range" min="-10" max="10" value="0" step="0.1" />


text:
// Generated by xsd compiler for android/java
// DO NOT CHANGE!
package ebay.apis.eblbasecomponents;

import java.io.Serializable;
import com.leansoft.nano.annotation.*;
import java.util.List;
import java.util.Date;

/**
 *
 * Returns the item ID and the estimated fees for the re-listed item.
 *
 */
@RootElement(name = "RelistFixedPriceItemResponse", namespace = "urn:ebay:apis:eBLBaseComponents")
public class RelistFixedPriceItemResponseType extends AbstractResponseType implements Serializable {

    private static final long serialVersionUID = -1L;

	@Element(name = "ItemID")
	private String itemID;

	@Element(name = "SKU")
	private String sku;

	@Element(name = "Fees")
	private FeesType fees;

	@Element(name = "StartTime")
	private Date startTime;

	@Element(name = "EndTime")
	private Date endTime;

	@Element(name = "CategoryID")
	private String categoryID;

	@Element(name = "Category2ID")
	private String category2ID;

	@Element(name = "DiscountReason")
	private List<DiscountReasonCodeType> discountReason;

	@Element(name = "ProductSuggestions")
	private ProductSuggestionsType productSuggestions;

	/**
     * public getter
     *
     *
     * Unique item ID for the relisted item.
     *
     *
     * @returns java.lang.String
	 */
	public String getItemID() {
	    return this.itemID;
	}

	/**
	 * public setter
	 *
     *
     * Unique item ID for the relisted item.
     *
     *
     * @param java.lang.String
	 */
	public void setItemID(String itemID) {
	    this.itemID = itemID;
	}
	/**
     * public getter
     *
     *
     * Item-level SKU for the new listing, if the seller specified
     * Item.SKU in the listing. Variation SKUs are not returned
     * (see GetItem instead).
     *
     *
     * @returns java.lang.String
	 */
	public String getSku() {
	    return this.sku;
	}

	/**
	 * public setter
	 *
     *
     * Item-level SKU for the new listing, if the seller specified
     * Item.SKU in the listing. Variation SKUs are not returned
     * (see GetItem instead).
     *
     *
     * @param java.lang.String
	 */
	public void setSku(String sku) {
	    this.sku = sku;
	}
	/**
     * public getter
     *
     *
     * Child elements contain the estimated listing fees for the relisted item.
     * The fees do not include the Final Value Fee (FVF), which cannot
     * be determined until an item is sold.
     *
     *
     * @returns ebay.apis.eblbasecomponents.FeesType
	 */
	public FeesType getFees() {
	    return this.fees;
	}

	/**
	 * public setter
	 *
     *
     * Child elements contain the estimated listing fees for the relisted item.
     * The fees do not include the Final Value Fee (FVF), which cannot
     * be determined until an item is sold.
     *
     *
     * @param ebay.apis.eblbasecomponents.FeesType
	 */
	public void setFees(FeesType fees) {
	    this.fees = fees;
	}
	/**
     * public getter
     *
     *
     * Date and time the relisting became active on the eBay site.
     *
     *
     * @returns java.util.Date
	 */
	public Date getStartTime() {
	    return this.startTime;
	}

	/**
	 * public setter
	 *
     *
     * Date and time the relisting became active on the eBay site.
     *
     *
     * @param java.util.Date
	 */
	public void setStartTime(Date startTime) {
	    this.startTime = startTime;
	}
	/**
     * public getter
     *
     *
     * Date and time when the relisted item ends. This is the starting time plus
     * the listing duration.
     *
     *
     * @returns java.util.Date
	 */
	public Date getEndTime() {
	    return this.endTime;
	}

	/**
	 * public setter
	 *
     *
     * Date and time when the relisted item ends. This is the starting time plus
     * the listing duration.
     *
     *
     * @param java.util.Date
	 */
	public void setEndTime(Date endTime) {
	    this.endTime = endTime;
	}
	/**
     * public getter
     *
     *
     * ID of the primary category in which the item was listed.
     * Only returned if you set Item.CategoryMappingAllowed to true in the request
     * and the ID passed in Item.PrimaryCategory was mapped to a new ID by eBay.
     * If the primary category has not changed or it has expired with no replacement,
     * CategoryID does not return a value.
     *
     *
     * @returns java.lang.String
	 */
	public String getCategoryID() {
	    return this.categoryID;
	}

	/**
	 * public setter
	 *
     *
     * ID of the primary category in which the item was listed.
     * Only returned if you set Item.CategoryMappingAllowed to true in the request
     * and the ID passed in Item.PrimaryCategory was mapped to a new ID by eBay.
     * If the primary category has not changed or it has expired with no replacement,
     * CategoryID does not return a value.
     *
     *
     * @param java.lang.String
	 */
	public void setCategoryID(String categoryID) {
	    this.categoryID = categoryID;
	}
	/**
     * public getter
     *
     *
     * ID of the secondary category in which the item was listed.
     * Only returned if you set Item.CategoryMappingAllowed to true in the request
     * and the ID passed in Item.SecondaryCategory was mapped to a new ID by eBay.
     * If the secondary category has not changed or it has expired with no replacement,
     * Category2ID does not return a value.
     *
     *
     * @returns java.lang.String
	 */
	public String getCategory2ID() {
	    return this.category2ID;
	}

	/**
	 * public setter
	 *
     *
     * ID of the secondary category in which the item was listed.
     * Only returned if you set Item.CategoryMappingAllowed to true in the request
     * and the ID passed in Item.SecondaryCategory was mapped to a new ID by eBay.
     * If the secondary category has not changed or it has expired with no replacement,
     * Category2ID does not return a value.
     *
     *
     * @param java.lang.String
	 */
	public void setCategory2ID(String category2ID) {
	    this.category2ID = category2ID;
	}
	/**
     * public getter
     *
     *
     * The nature of the discount, if a discount applied.
     *
     *
     * @returns java.util.List<ebay.apis.eblbasecomponents.DiscountReasonCodeType>
	 */
	public List<DiscountReasonCodeType> getDiscountReason() {
	    return this.discountReason;
	}

	/**
	 * public setter
	 *
     *
     * The nature of the discount, if a discount applied.
     *
     *
     * @param java.util.List<ebay.apis.eblbasecomponents.DiscountReasonCodeType>
	 */
	public void setDiscountReason(List<DiscountReasonCodeType> discountReason) {
	    this.discountReason = discountReason;
	}
	/**
     * public getter
     *
     *
     * Provides a list of products recommended by eBay which match the item information
     * provided by the seller.
     * Not applicable to Half.com.
     *
     *
     * @returns ebay.apis.eblbasecomponents.ProductSuggestionsType
	 */
	public ProductSuggestionsType getProductSuggestions() {
	    return this.productSuggestions;
	}

	/**
	 * public setter
	 *
     *
     * Provides a list of products recommended by eBay which match the item information
     * provided by the seller.
     * Not applicable to Half.com.
     *
     *
     * @param ebay.apis.eblbasecomponents.ProductSuggestionsType
	 */
	public void setProductSuggestions(ProductSuggestionsType productSuggestions) {
	    this.productSuggestions = productSuggestions;
	}

}


text:
import { expect } from 'chai';
import { Role, User } from '../../models';
import helper from '../test-helper';

const userParams = helper.firstUser;
const roleParams = helper.adminRole;

const notNullAttrs = ['firstName', 'lastName', 'email', 'password', 'roleId'];
const uniqueAttrs = ['username', 'email'];

let user;

describe('User model', () => {
  before(() =>
    Role.create(roleParams)
      .then((role) => {
        userParams.roleId = role.id;
      }));

  beforeEach(() => {
    user = User.build(userParams);
  });

  // clear DB after each test
  after(() => User.sequelize.sync({ force: true }));

  afterEach(() => User.destroy({ where: {} }));

  describe('Create user', () => {
    it('creates a User instance', () =>
      expect(user).to.exist);

    it('has both first name and last name', () => {
      expect(user.firstName).to.equal(userParams.firstName);
      expect(user.lastName).to.equal(userParams.lastName);
    });

    it('saves user with valid attributes', () =>
      user.save().then((newUser) => {
        expect(newUser.username).to.equal(user.username);
        expect(newUser.firstName).to.equal(user.firstName);
        expect(newUser.lastName).to.equal(user.lastName);
        expect(newUser.email).to.equal(user.email);
        expect(newUser.roleId).to.equal(user.roleId);
      })
    );
    it('has a role defined', () =>
      user.save().then(newUser =>
        User.findById(newUser.id, { include: [Role] })
          .then((foundUser) => {
            expect(foundUser.Role.title).to.equal(roleParams.title);
          })));
  });

  describe('Validations', () => {
    describe('NOT NULL attributes', () => {
      notNullAttrs.forEach((attr) => {
        it(`fails without ${attr}`, () => {
          user[attr] = null;

          return user.save()
            .then(newUser => expect(newUser).to.not.exist)
            .catch(err =>
              expect(/notNull/.test(err.message)).to.be.true);
        });
      });
    });

    describe('UNIQUE attributes', () => {
      uniqueAttrs.forEach((attr) => {
        it(`fails for non unique ${attr}`, () =>
          user.save()
            .then(newUser => User.build(userParams).save()
            )
            .then(newUser2 => expect(newUser2).to.not.exist)
            .catch(err =>
              expect(/UniqueConstraintError/.test(err.name)).to.be.true));
      });
    });

    it('fails for invalid email', () => {
      user.email = 'invalid email';
      return user.save()
        .then(newUser => expect(newUser).to.not.exist)
        .catch(err =>
          expect(/isEmail failed/.test(err.message)).to.be.true);
    });
  });
});


text:
namespace Climbing.Web.Tests.Unit
{
    using System;
    using Climbing.Web.Utilities.Mapper;
    using Xunit;

    public class AutoMapperTests
    {
        [Theory]
        [AutoMoqData]
        public void ShouldMap(ClassFrom from)
        {
            // Arrange
            AutoMapper.Setup((ClassFrom cf) => cf.Field).To((ClassTo ct) => ct.FieldTo);
            AutoMapper.Setup((ClassFrom cf) => cf.Property).To((ClassTo ct) => ct.Property1);
            AutoMapper.Setup((ClassFrom cf) => $"{cf.Field}|{cf.Property}").To((ClassTo ct) => ct.Property2);

            // Act
            var res = AutoMapper.Map<ClassTo>(from);

            // Assert
            Assert.Equal(from.Field, res.FieldTo);
            Assert.Equal(from.Property, res.Property1);
            Assert.Equal($"{from.Field}|{from.Property}", res.Property2);
        }

        public sealed class ClassFrom
        {
#pragma warning disable SA1401 // Fields should be private
            internal string Field = Guid.NewGuid().ToString();
#pragma warning restore SA1401 // Fields should be private

            public string Property { get; set; }
        }

        public sealed class ClassTo
        {
#pragma warning disable SA1401 // Fields should be private
            public string FieldTo = "11";
#pragma warning restore SA1401 // Fields should be private

            public string Property1 { get; set; }

            public string Property2 { get; set; }
        }
    }
}


text:
/**
 * Create view for tagging captured image.
 * This view is used on the CameraWindow
 */

var navbars = require('/ui/common/navbars');
var buttons = require('/ui/common/buttons');
var dProcess = require('/data/designProcess');

var _ = require('/lib/underscore');

var CURRENT_STAGE = 'define';

exports.createView = function(event) {

   var container = Ti.UI.createView({
      top: 0,
      left: 0,
      width: Ti.UI.FILL,
      height: Ti.UI.FILL,
      backgroundColor: 'white',
      layout: 'vertical'
   });

   var imageView = Ti.UI.createImageView({
       image: event.media,
       top: 0,
       left:0,
       height: '50%',
   });

   var topBar = navbars.topBar();
   var tagBar = tagSelection();

   container.add(topBar);
   container.add(imageView);
   container.add(tagBar);

   return container;
};

var tagSelection = function() {

   var tagSelectionBar = Ti.UI.createView({
      width: Ti.UI.FILL,
      height: '50dp',
      layout: 'horizontal',
      opacity: '0.8'
   });

   //var buttons =
      //_.map(dProcess.process[CURRENT_STAGE],
            //buttons.tagButton);

   for (var activity in dProcess.process[CURRENT_STAGE]) {
      tagSelectionBar.add(
            buttons.tagButton({
               title: dProcess.process[CURRENT_STAGE][activity]
            }));
   }

   return tagSelectionBar;
};


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">

		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<meta name="author" content="José Rafael Vieira">
		<meta name="description" content="Liberal inheritance JavaScript micro library for OOP.">
		<meta name="keywords" content="chainchainchain, javascript, library, inheritance">

		<meta name="viewport" content="width=420">

		<title>
			chainchainchain
		</title>
		<link type="image/png" rel="shortcut icon" href="img/icon.png">
		<link type="text/css" rel="stylesheet" href="chainchainchain.css">
		<link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

					chainchainchain

|

						Documentation

|

						Demo

chainchainchain

A liberal inheritance JavaScript micro library for object oriented programming. It elegantly avoids the diamond problem and is compatible with any inheritance pattern and other class systems. Take this example:

I want both objects joe and alex to inherit from cop. However, since an object can only inherit from one prototype, I had to create two different cops in order to make joe's parent inherit from human and alex's parent to inherit from robot. But I want the changes I make to cop to be reflected on joe and alex's behaviour. I want them to inherit from the same cop:

Not only do I want both to inherit from the same cop, I want joe chained to cop, human and being while alex is chained to cop, robot and being. I don't want robot to affect joe nor human to affect alex.

This library allows for efficient and safe multiple inheritance, avoiding inefficient property copy or observer type patterns. Taking advantage of metaprogramming and dynamic dispatch, it elegantly allows for independent lineage:

This means I can define the lineage of any object as I like, not interfering with any other objects' lineage. I can have all sorts of forks, loops and paradoxes in the inheritance tree. It's simpler than it looks, consider the following tree:

Take object A. Its chain has been defined as B C I P R. These are the objects in A's chain. But each one of these objects can also have its own chain, branching the chain tree. When getting a property from A, you can choose to look only in its chain or you can choose to look up the entire tree. If you choose the latter you must be aware of precedence, signified here by alphabetical order. As you can see, younger chained objects's whole chains are considered younger than older chained objects.

Mind that in spite of every object being represented with a different letter here, objects can repeat themselves throughout the chain tree. This means that (B===F) can be true, allowing for tridimensional inheritance chains to be designed. All the connections between chained objects are live, wich means that if I make changes to N, A will retrieve N's updated value when required.

While B and C are in A's chain, C doesn't necessarily have to be on B's chain, as every object has its own independent chain and therefore its own tree.

					About me

					I am a Portuguese web developer, designer and drummer from the city of Porto. If you have any doubts, suggestions or a will to buy me a beer get in touch. Also check out my portfolio.


text:
namespace Bakery.Cqrs
{
	public interface ICommandHandler
	{ }
}


text:
import React from 'react';
import {
  Flex,
  Text,
  Box,
  Button,
  Link,
  Divider,
} from '@chakra-ui/react';

import { MdPlayArrow, MdOutlineSchedule, MdOutlineAccountTree } from 'react-icons/md';
import { RiArrowGoBackFill } from 'react-icons/ri';

import { SimpleStatus } from '../../../components/StatusBox';
import { ClipboardText } from '../../../components/Clipboard';
import { formatDuration, getDuration } from '../../../../datetime_utils';
import Time from '../../../components/Time';
import MarkFailedRun from './MarkFailedRun';
import MarkSuccessRun from './MarkSuccessRun';
import QueueRun from './QueueRun';
import ClearRun from './ClearRun';
import { useGridData } from '../../../api';
import { appendSearchParams, getMetaValue } from '../../../../utils';
import type { DagRun as DagRunType } from '../../../types';

const dagId = getMetaValue('dag_id');
const graphUrl = getMetaValue('graph_url');
const dagRunDetailsUrl = getMetaValue('dagrun_details_url');

interface Props {
  runId: DagRunType['runId'];
}

const DagRun = ({ runId }: Props) => {
  const { data: { dagRuns } } = useGridData();
  const run = dagRuns.find((dr) => dr.runId === runId);
  if (!run) return null;
  const {
    executionDate,
    state,
    runType,
    lastSchedulingDecision,
    dataIntervalStart,
    dataIntervalEnd,
    startDate,
    endDate,
  } = run;
  const detailsParams = new URLSearchParams({
    run_id: runId,
  }).toString();
  const graphParams = new URLSearchParams({
    execution_date: executionDate,
  }).toString();
  const graphLink = appendSearchParams(graphUrl, graphParams);
  const detailsLink = appendSearchParams(dagRunDetailsUrl, detailsParams);

  return (
    <Box py="4px">
      <Flex justifyContent="space-between" alignItems="center">
        <Button as={Link} variant="ghost" colorScheme="blue" href={detailsLink}>DAG Run Details</Button>
        <Button as={Link} variant="ghost" colorScheme="blue" href={graphLink} leftIcon={<MdOutlineAccountTree />}>
          Graph
        </Button>
        <MarkFailedRun dagId={dagId} runId={runId} />
        <MarkSuccessRun dagId={dagId} runId={runId} />
      </Flex>
      <Divider my={3} />
      <Flex justifyContent="flex-end" alignItems="center">
        <Text fontWeight="bold" mr={2}>Re-run:</Text>
        <ClearRun dagId={dagId} runId={runId} />
        <QueueRun dagId={dagId} runId={runId} />
      </Flex>
      <Divider my={3} />
      <Flex alignItems="center">
        <Text as="strong">Status:</Text>
        <SimpleStatus state={state} mx={2} />
        {state || 'no status'}
      </Flex>

      <Text whiteSpace="nowrap">
        Run Id:
        {' '}
        <ClipboardText value={runId} />
      </Text>
      <Text>
        Run Type:
        {' '}
        {runType === 'manual' && <MdPlayArrow style={{ display: 'inline' }} />}
        {runType === 'backfill' && <RiArrowGoBackFill style={{ display: 'inline' }} />}
        {runType === 'scheduled' && <MdOutlineSchedule style={{ display: 'inline' }} />}
        {runType}
      </Text>
      <Text>
        Duration:
        {' '}
        {formatDuration(getDuration(startDate, endDate))}
      </Text>
      {lastSchedulingDecision && (
      <Text>
        Last Scheduling Decision:
        {' '}
        <Time dateTime={lastSchedulingDecision} />
      </Text>
      )}

      {startDate && (
      <Text>
        Started:
        {' '}
        <Time dateTime={startDate} />
      </Text>
      )}
      {endDate && (
      <Text>
        Ended:
        {' '}
        <Time dateTime={endDate} />
      </Text>
      )}
      {dataIntervalStart && dataIntervalEnd && (
        <>

          <Text as="strong">Data Interval:</Text>
          <Text>
            Start:
            {' '}
            <Time dateTime={dataIntervalStart} />
          </Text>
          <Text>
            End:
            {' '}
            <Time dateTime={dataIntervalEnd} />
          </Text>
        </>
      )}
    </Box>
  );
};

export default DagRun;


text:
FOUNDATION_EXPORT double Pods_scswift_exampleUITestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_scswift_exampleUITestsVersionString[];


text:
if ENV['HONEYBADGER_API_KEY']
  require 'honeybadger'

  Honeybadger.configure do |config|
    config.api_key = ENV['HONEYBADGER_API_KEY']
  end
end


text:
package org.apache.cassandra.cql3.statements;

import org.apache.cassandra.auth.Permission;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.schema.Schema;
import org.apache.cassandra.cql3.IndexName;
import org.apache.cassandra.cql3.QueryOptions;
import org.apache.cassandra.db.KeyspaceNotDefinedException;
import org.apache.cassandra.exceptions.*;
import org.apache.cassandra.schema.KeyspaceMetadata;
import org.apache.cassandra.service.ClientState;
import org.apache.cassandra.schema.MigrationManager;
import org.apache.cassandra.service.QueryState;
import org.apache.cassandra.transport.Event;
import org.apache.cassandra.transport.messages.ResultMessage;

public class DropIndexStatement extends SchemaAlteringStatement
{
    public final String indexName;
    public final boolean ifExists;

    public DropIndexStatement(IndexName indexName, boolean ifExists)
    {
        super(indexName.getCfName());
        this.indexName = indexName.getIdx();
        this.ifExists = ifExists;
    }

    public String columnFamily()
    {
        TableMetadata metadata = lookupIndexedTable();
        return metadata == null ? null : metadata.name;
    }

    public void checkAccess(ClientState state) throws UnauthorizedException, InvalidRequestException
    {
        TableMetadata metadata = lookupIndexedTable();
        if (metadata == null)
            return;

        state.hasColumnFamilyAccess(metadata.keyspace, metadata.name, Permission.ALTER);
    }

    public void validate(ClientState state)
    {
        // validated in lookupIndexedTable()
    }

    @Override
    public ResultMessage execute(QueryState state, QueryOptions options, long queryStartNanoTime) throws RequestValidationException
    {
        Event.SchemaChange ce = announceMigration(state, false);
        return ce == null ? null : new ResultMessage.SchemaChange(ce);
    }

    public Event.SchemaChange announceMigration(QueryState queryState, boolean isLocalOnly) throws InvalidRequestException, ConfigurationException
    {
        TableMetadata current = lookupIndexedTable();
        if (current == null)
            return null;

        TableMetadata updated =
            current.unbuild()
                   .indexes(current.indexes.without(indexName))
                   .build();

        MigrationManager.announceTableUpdate(updated, isLocalOnly);
        // Dropping an index is akin to updating the CF
        // Note that we shouldn't call columnFamily() at this point because the index has been dropped and the call to lookupIndexedTable()
        // in that method would now throw.
        return new Event.SchemaChange(Event.SchemaChange.Change.UPDATED, Event.SchemaChange.Target.TABLE, current.keyspace, current.name);
    }

    /**
     * The table for which the index should be dropped, or null if the index doesn't exist
     *
     * @return the metadata for the table containing the dropped index, or {@code null}
     * if the index to drop cannot be found but "IF EXISTS" is set on the statement.
     *
     * @throws InvalidRequestException if the index cannot be found and "IF EXISTS" is not
     * set on the statement.
     */
    private TableMetadata lookupIndexedTable()
    {
        KeyspaceMetadata ksm = Schema.instance.getKeyspaceMetadata(keyspace());
        if (ksm == null)
            throw new KeyspaceNotDefinedException("Keyspace " + keyspace() + " does not exist");

        return ksm.findIndexedTable(indexName)
                  .orElseGet(() -> {
                      if (ifExists)
                          return null;
                      else
                          throw new InvalidRequestException(String.format("Index '%s' could not be found in any " +
                                                                          "of the tables of keyspace '%s'",
                                                                          indexName, keyspace()));
                  });
    }
}


text:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals

from django.test import TestCase

from ..models import Facility
from ..models import FacilityUser
from .helpers import create_superuser

class UserSanityTestCase(TestCase):
    """
    Sanity checks basic functionality of user models.
    """

    def setUp(self):
        self.facility = Facility.objects.create()
        self.user = FacilityUser.objects.create(
            username="mike",
            full_name="Mike Gallaspy",
            password="###",
            facility=self.facility,
        )
        self.do = create_superuser(self.facility)

    def test_facility_user(self):
        self.assertFalse(self.user.is_superuser)

    def test_device_owner(self):
        self.assertTrue(self.do.is_superuser)

    def test_short_name(self):
        self.assertEqual(self.user.get_short_name(), "Mike")


text:
SYNONYM

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

#### Published in
Monogr. Chalara Allied Genera (Waterloo) 154 (1975)

#### Original name
Chaetochalara ramosa Nag Raj & W.B. Kendr., 1975

### Remarks
null


text:
@implementation FinanceCell

- (void)awakeFromNib {
    // Initialization code
}

- (void)fetchFinace:(Finance *)finance
{
    self.nameLabel.text = finance.name;
    self.tagsLabel.text = finance.industry;
    self.financeTargetLabel.text = finance.financeTarget;
    self.briefLabel.text = finance.brief;
    [self.logoImageView sd_setImageWithURL:[NSURL URLWithString:finance.logo]];

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = differenceInCalendarYears;

var _index = _interopRequireDefault(require("../toDate/index.js"));

var _index2 = _interopRequireDefault(require("../_lib/requiredArgs/index.js"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * @name differenceInCalendarYears
 * @category Year Helpers
 * @summary Get the number of calendar years between the given dates.
 *
 * @description
 * Get the number of calendar years between the given dates.
 *
 * ### v2.0.0 breaking changes:
 *
 * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
 *
 * @param {Date|Number} dateLeft - the later date
 * @param {Date|Number} dateRight - the earlier date
 * @returns {Number} the number of calendar years
 * @throws {TypeError} 2 arguments required
 *
 * @example
 * // How many calendar years are between 31 December 2013 and 11 February 2015?
 * const result = differenceInCalendarYears(
 *   new Date(2015, 1, 11),
 *   new Date(2013, 11, 31)
 * )
 * //=> 2
 */
function differenceInCalendarYears(dirtyDateLeft, dirtyDateRight) {
  (0, _index2.default)(2, arguments);
  var dateLeft = (0, _index.default)(dirtyDateLeft);
  var dateRight = (0, _index.default)(dirtyDateRight);
  return dateLeft.getFullYear() - dateRight.getFullYear();
}

module.exports = exports.default;


text:
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var abstractSelector_1 = require("./abstractSelector");
var MinuteSelector = (function (_super) {
    __extends(MinuteSelector, _super);
    function MinuteSelector() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    MinuteSelector.prototype.minutes = function () {
        var result = [];
        for (var i = 0; i < 60; i = i + 5) {
            result.push(this.value.clone().minute(i));
        }
        return result;
    };
    return MinuteSelector;
}(abstractSelector_1.AbstractSelector));
__decorate([
    core_1.Input(),
    __metadata("design:type", Object)
], MinuteSelector.prototype, "date", void 0);
__decorate([
    core_1.Output(),
    __metadata("design:type", core_1.EventEmitter)
], MinuteSelector.prototype, "dateChange", void 0);
__decorate([
    core_1.Output(),
    __metadata("design:type", core_1.EventEmitter)
], MinuteSelector.prototype, "dateSelected", void 0);
__decorate([
    core_1.Output(),
    __metadata("design:type", core_1.EventEmitter)
], MinuteSelector.prototype, "modeChanged", void 0);
MinuteSelector = __decorate([
    core_1.Component({
        selector: "minute-selector",
        styles: [
            ".date-set{line-height:2em;text-align:center;vertical-align:middle}.date-set.hidden{display:none}.date-set__dates{display:flex;flex-direction:row;margin:0;padding:0;list-style-type:none;flex-wrap:wrap;justify-content:space-between;align-items:stretch}.date-set__date{cursor:pointer;flex-grow:1;flex-shrink:0;flex-basis:33%}"
        ],
        template: "\n
\n
\n
\n                    {{ minute.format(\"mm\") }}\n
\n
\n
\n    "
    })
], MinuteSelector);
exports.MinuteSelector = MinuteSelector;
//# sourceMappingURL=minuteSelector.js.map


text:
* Grid (simple)
* Grid (SlickGrid)
* Map
* Choropleth Map
* Graph
* Timeline
* Multiview (combines views)


text:
module Api
  module V1
    class TouchController < ApplicationController
      respond_to :json

      # just for setting cookie
      def index
        render :json => { info: '', status: :success }
      end
    end
  end
end


text:
import EmitterFactory from './EmitterFactory';
import EventAggregator from '../src/index';

describe('EventAggregator#onAll', () => {
  it('fires an event when all constituent events have fired', (done) => {
    EmitterFactory.reset();
    const triggers = EmitterFactory.create(4);
    const aggregator = new EventAggregator(triggers);

    const eventSpy = sinon.spy();

    aggregator.onAll('alpha', eventSpy);

    triggers[0].alpha();

    tick()
      .then(() => {
        expect(eventSpy).not.to.have.been.called();
        triggers[1].alpha();
        triggers[2].alpha();
        triggers[3].alpha();

        return tick();
      })
      .then(() => {
        expect(eventSpy).to.have.been.calledOnce();
        expect(eventSpy).to.have.been.calledWith([[0], [1], [2], [3]]);

        triggers[3].alpha();
        triggers[2].alpha();
        triggers[1].alpha();
        triggers[0].alpha();

        return tick();
      })
      .then(() => {
        expect(eventSpy).to.have.been.calledTwice();
        expect(eventSpy).to.have.been.calledWith([[0], [1], [2], [3]]);
        done();
      });
  });

  it('fires an event if the only emitter in the set that hasn\'t fired is removed', (done) => {
    EmitterFactory.reset();
    const triggers = EmitterFactory.create(4);
    const aggregator = new EventAggregator(triggers);

    const eventSpy = sinon.spy();

    aggregator.onAll('alpha', eventSpy);

    triggers[0].alpha();
    triggers[1].alpha();
    triggers[3].alpha();

    aggregator.removeSource(triggers[2]);

    process.nextTick(() => {
      expect(eventSpy).to.have.been.calledOnce();
      expect(eventSpy).to.have.been.calledWith([[0], [1], [3]]);
      done();
    });
  });

  it('does not fire an event if the last emitter is removed', (done) => {
    EmitterFactory.reset();
    const triggers = EmitterFactory.create(1);
    const aggregator = new EventAggregator(triggers);

    const eventSpy = sinon.spy();

    aggregator.onAll('alpha', eventSpy);

    aggregator.removeSource(triggers[0]);

    process.nextTick(() => {
      expect(eventSpy).not.to.have.been.called();
      done();
    });
  });

  it('can be reset so that previous catches are ignored', (done) => {
    EmitterFactory.reset();
    const triggers = EmitterFactory.create(4);
    const aggregator = new EventAggregator(triggers);

    const eventSpy = sinon.spy();

    aggregator.onAll('alpha', eventSpy);

    triggers[0].alpha();
    triggers[1].alpha();
    triggers[3].alpha();

    aggregator.reset();
    triggers[2].alpha();

    tick()
      .then(() => {
        expect(eventSpy).not.to.have.been.called();

        triggers[0].alpha();
        triggers[1].alpha();
        triggers[3].alpha();

        return tick();
      })
      .then(() => {
        expect(eventSpy).to.have.been.calledOnce();
        expect(eventSpy).to.have.been.calledWith([[0], [1], [2], [3]]);
        done();
      });
  });

  it('supports listeners being added and removed', (done) => {
    EmitterFactory.reset();
    const triggers = EmitterFactory.create(2);
    const aggregator = new EventAggregator(triggers);

    const alphaSpy = sinon.spy();
    const betaSpy = sinon.spy();

    aggregator.onAny('alpha', alphaSpy);
    aggregator.onAny('beta', betaSpy);

    triggers[0].alpha();
    triggers[1].beta();

    tick()
      .then(() => {
        expect(alphaSpy).to.have.been.calledOnce();
        expect(betaSpy).to.have.been.calledOnce();

        aggregator.removeListener('alpha', alphaSpy);

        triggers[0].alpha();
        triggers[1].beta();

        return tick();
      })
      .then(() => {
        expect(alphaSpy).to.have.been.calledOnce();
        expect(betaSpy).to.have.been.calledTwice();

        aggregator.removeListener('beta', betaSpy);

        triggers[0].alpha();
        triggers[1].beta();

        return tick();
      })
      .then(() => {
        expect(alphaSpy).to.have.been.calledOnce();
        expect(betaSpy).to.have.been.calledTwice();
        done();
      });
  });
});


text:
import { expect } from 'chai';
import test from 'ava';

import SchemaType from '../../../../lib/schema/type/abstract';
import DateSchemaType from '../../../../lib/schema/type/date';

test('Should extends SchemaType', () => expect(DateSchemaType.prototype).to.be.instanceof(SchemaType));

let emptyDescriptor;
let afterDescriptor;
let beforeDescriptor;

const createEmpty      = () => { emptyDescriptor  = new DateSchemaType(); };
const createWithAfter  = () => { afterDescriptor   = new DateSchemaType({ min: new Date('2015-01-01') }); };
const createWithBefore = () => { beforeDescriptor = new DateSchemaType({ max: new Date('2015-01-01') }); };

test('Should instanciate without a descriptor', () => expect(createEmpty).to.not.throw());
test('Should instanciate with a after',         () => expect(createWithAfter).to.not.throw());
test('Should instanciate with a before',        () => expect(createWithBefore).to.not.throw());

test('Should handle no validator correctly', () => {
	expect(emptyDescriptor.validate()).to.be.true;
	expect(emptyDescriptor.validate(false)).to.be.an.instanceof(Error);
	expect(emptyDescriptor.validate(null)).to.be.an.instanceof(Error);
	expect(emptyDescriptor.validate('2015-12-01')).to.be.true;
	expect(emptyDescriptor.validate(0)).to.be.true;
	expect(emptyDescriptor.validate(1)).to.be.true;
	expect(emptyDescriptor.validate(new Date('2015-12-01'))).to.be.true;
});

test('Should handle after validator correctly', () => {
	expect(afterDescriptor.validate()).to.be.true;
	expect(afterDescriptor.validate(false)).to.be.an.instanceof(Error);
	expect(afterDescriptor.validate(null)).to.be.an.instanceof(Error);
	expect(afterDescriptor.validate('2015-12-01')).to.be.true;
	expect(afterDescriptor.validate('2014-12-01')).to.be.an.instanceof(Error);
	expect(afterDescriptor.validate(0)).to.be.an.instanceof(Error);
	expect(afterDescriptor.validate(1)).to.be.an.instanceof(Error);
	expect(afterDescriptor.validate(new Date('2015-12-01'))).to.be.true;
	expect(afterDescriptor.validate(new Date('2014-12-01'))).to.be.an.instanceof(Error);
});

test('Should handle before validator correctly', () => {
	expect(beforeDescriptor.validate()).to.be.true;
	expect(beforeDescriptor.validate(false)).to.be.an.instanceof(Error);
	expect(beforeDescriptor.validate(null)).to.be.an.instanceof(Error);
	expect(beforeDescriptor.validate('2014-12-01')).to.be.true;
	expect(beforeDescriptor.validate('2015-12-01')).to.be.an.instanceof(Error);
	expect(beforeDescriptor.validate(0)).to.be.true;
	expect(beforeDescriptor.validate(1)).to.be.true;
	expect(beforeDescriptor.validate(new Date('2014-12-01'))).to.be.true;
	expect(beforeDescriptor.validate(new Date('2015-12-01'))).to.be.an.instanceof(Error);
});


text:
package com.intellij.lang.jsgraphql.types.execution;

import com.intellij.lang.jsgraphql.types.Internal;
import com.intellij.lang.jsgraphql.types.language.ListType;
import com.intellij.lang.jsgraphql.types.language.NonNullType;
import com.intellij.lang.jsgraphql.types.language.Type;
import com.intellij.lang.jsgraphql.types.language.TypeName;
import com.intellij.lang.jsgraphql.types.schema.GraphQLSchema;
import com.intellij.lang.jsgraphql.types.schema.GraphQLType;

import static com.intellij.lang.jsgraphql.types.schema.GraphQLList.list;
import static com.intellij.lang.jsgraphql.types.schema.GraphQLNonNull.nonNull;

@Internal
public class TypeFromAST {

    public static GraphQLType getTypeFromAST(GraphQLSchema schema, Type type) {
        GraphQLType innerType;
        if (type instanceof ListType) {
            innerType = getTypeFromAST(schema, ((ListType) type).getType());
            return innerType != null ? list(innerType) : null;
        } else if (type instanceof NonNullType) {
            innerType = getTypeFromAST(schema, ((NonNullType) type).getType());
            return innerType != null ? nonNull(innerType) : null;
        }

        return schema.getType(((TypeName) type).getName());
    }
}


text:
package javassist.bytecode;

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

public class BootstrapMethodsAttribute extends AttributeInfo {
    /**
     * The name of this attribute "BootstrapMethods".
     */
    public static final String tag = "BootstrapMethods";

    /**
     * An element of bootstrap_methods.
     */
    public static class BootstrapMethod {
        /**
         * Constructs an element of bootstrap_methods.
         *
         * @param method        bootstrap_method_ref.
         * @param args          bootstrap_arguments.
         */
        public BootstrapMethod(int method, int[] args) {
            methodRef = method;
            arguments = args;
        }

        /**
         * bootstrap_method_ref.
         * The value at this index must be a CONSTANT_MethodHandle_info.
         */
        public int methodRef;

        /**
         * bootstrap_arguments.
         */
        public int[] arguments;
    }

    BootstrapMethodsAttribute(ConstPool cp, int n, DataInputStream in)
        throws IOException
    {
        super(cp, n, in);
    }

    /**
     * Constructs a BootstrapMethods attribute.
     *
     * @param cp                a constant pool table.
     * @param methods           the contents.
     */
    public BootstrapMethodsAttribute(ConstPool cp, BootstrapMethod[] methods) {
        super(cp, tag);
        int size = 2;
        for (int i = 0; i < methods.length; i++)
            size += 4 + methods[i].arguments.length * 2;

        byte[] data = new byte[size];
        ByteArray.write16bit(methods.length, data, 0);    // num_bootstrap_methods
        int pos = 2;
        for (int i = 0; i < methods.length; i++) {
            ByteArray.write16bit(methods[i].methodRef, data, pos);
            ByteArray.write16bit(methods[i].arguments.length, data, pos + 2);
            int[] args = methods[i].arguments;
            pos += 4;
            for (int k = 0; k < args.length; k++) {
                ByteArray.write16bit(args[k], data, pos);
                pos += 2;
            }
        }

        set(data);
    }

    /**
     * Obtains bootstrap_methods in this attribute.
     *
     * @return an array of BootstrapMethod.  Since it
     *          is a fresh copy, modifying the returned array does not
     *          affect the original contents of this attribute.
     */
    public BootstrapMethod[] getMethods() {
        byte[] data = this.get();
        int num = ByteArray.readU16bit(data, 0);
        BootstrapMethod[] methods = new BootstrapMethod[num];
        int pos = 2;
        for (int i = 0; i < num; i++) {
            int ref = ByteArray.readU16bit(data, pos);
            int len = ByteArray.readU16bit(data, pos + 2);
            int[] args = new int[len];
            pos += 4;
            for (int k = 0; k < len; k++) {
                args[k] = ByteArray.readU16bit(data, pos);
                pos += 2;
            }

            methods[i] = new BootstrapMethod(ref, args);
        }

        return methods;
    }

    /**
     * Makes a copy.  Class names are replaced according to the
     * given Map object.
     *
     * @param newCp     the constant pool table used by the new copy.
     * @param classnames        pairs of replaced and substituted
     *                          class names.
     */
    public AttributeInfo copy(ConstPool newCp, Map classnames) {
        BootstrapMethod[] methods = getMethods();
        ConstPool thisCp = getConstPool();
        for (int i = 0; i < methods.length; i++) {
            BootstrapMethod m = methods[i];
            m.methodRef = thisCp.copy(m.methodRef, newCp, classnames);
            for (int k = 0; k < m.arguments.length; k++)
                m.arguments[k] = thisCp.copy(m.arguments[k], newCp, classnames);
        }

        return new BootstrapMethodsAttribute(newCp, methods);
    }
}


text:
package gov.hhs.onc.dcdt.service.dns;

import gov.hhs.onc.dcdt.dns.DnsTransportProtocol;
import gov.hhs.onc.dcdt.service.ToolService;
import gov.hhs.onc.dcdt.service.dns.config.DnsServerConfig;
import gov.hhs.onc.dcdt.service.dns.server.DnsServer;

public interface DnsService extends ToolService<DnsTransportProtocol, DnsServerConfig, DnsServer> {
}


text:
package com.louji.bookread;

import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.WindowManager;

import com.louji.base.R;

/**
 * ÏÂÔغóÔĶÁ
 *
 * @author Ê¢ÔÂï
 *
 */
public class ReadBookActivity extends Activity
{
	ScanView scanview;
	ScanViewAdapter adapter;
	int screenWidth;
	int screenHeight;
	View rootView;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		rootView = LayoutInflater.from(this).inflate(
				R.layout.activity_readbook, null);
		setContentView(rootView);

		// »ñÈ¡ÆÁÄ»³ß´ç
		getScreenSize();

		// ´ò¿ªÊé¼®
		openbook();

		rootView.setOnLongClickListener(new OnLongClickListener()
		{

			@Override
			public boolean onLongClick(View v)
			{
				return false;
			}
		});

	}

	private void openbook()
	{
		String filePath = getIntent().getExtras().getString("filePath");

		scanview = (ScanView) findViewById(R.id.scanview);

		try
		{
			adapter = new ScanViewAdapter(this, filePath, screenWidth,
					screenHeight);
			adapter.openbook(filePath);
			scanview.setAdapter(adapter);

		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@SuppressWarnings("deprecation")
	private void getScreenSize()
	{
		screenWidth = getWindowManager().getDefaultDisplay().getWidth();
		screenHeight = getWindowManager().getDefaultDisplay().getHeight();
	}

}


text:
class AddCorpseRefToLines < ActiveRecord::Migration[5.0]
  def change
    add_reference :lines, :corpse, foreign_key: true
  end
end


text:
layout: page
title: "Value Object"
date:  2016-04-14 11:19:48
---

- values of the instance variables never change once they have been set in the
  constructor
- equality is not based on identity
  - two value objects are equal when their values are equal, not necessarily
    being the same object.
- this protects from aliasing problems, ie. bugs caused by changing an object
  is being referred in two different places.

Money is a good example of value object:

{% highlight ruby %}
a = Money.new(5)
b = Money.new(5)

a == b #=> true
{% endhighlight %}


text:
import random
import re

from streamlink.plugin import Plugin
from streamlink.plugin.api import http
from streamlink.plugin.api import validate
from streamlink.compat import urlparse, parse_qsl
from streamlink.stream import HLSStream
from streamlink.stream import HTTPStream

class LiveMe(Plugin):
    url_re = re.compile(r"https?://(www.)?liveme\.com/live\.html\?videoid=(\d+)")
    api_url = "https://live.ksmobile.net/live/queryinfo"
    api_schema = validate.Schema(validate.all({
        "status": "200",
        "data": {
            "video_info": {
                "videosource": validate.any('', validate.url()),
                "hlsvideosource": validate.any('', validate.url()),
            }
        }
    }, validate.get("data")))

    @classmethod
    def can_handle_url(cls, url):
        return cls.url_re.match(url) is not None

    def _random_t(self, t):
        return "".join(random.choice("ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678") for _ in range(t))

    def _make_stream(self, url):
        if url and url.endswith("flv"):
            return HTTPStream(self.session, url)
        elif url and url.endswith("m3u8"):
            return HLSStream(self.session, url)

    def _get_streams(self):
        url_params = dict(parse_qsl(urlparse(self.url).query))
        video_id = url_params.get("videoid")

        if video_id:
            vali = '{0}l{1}m{2}'.format(self._random_t(4), self._random_t(4), self._random_t(5))
            data = {
                'userid': 1,
                'videoid': video_id,
                'area': '',
                'h5': 1,
                'vali': vali
            }
            self.logger.debug("Found Video ID: {0}".format(video_id))
            res = http.post(self.api_url, data=data)
            data = http.json(res, schema=self.api_schema)
            hls = self._make_stream(data["video_info"]["hlsvideosource"])
            video = self._make_stream(data["video_info"]["videosource"])
            if hls:
                yield "live", hls
            if video:
                yield "live", video

__plugin__ = LiveMe


text:
<?php

namespace mdm\admin\controllers;

use Yii;
use mdm\admin\models\Menu;
use mdm\admin\models\searchs\Menu as MenuSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use mdm\admin\components\Helper;
use yii\filters\AccessControl;

/**
 * MenuController implements the CRUD actions for Menu model.
 *
 * @author Misbahul D Munir <misbahuldmunir@gmail.com>
 * @since 1.0
 */
class MenuController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
//                        'actions' => ['index', 'view', 'create', 'update', 'delete'],
                        'roles' => [ '超级管理员'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Menu models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new MenuSearch;
        $dataProvider = $searchModel->search(Yii::$app->request->getQueryParams());

        return $this->render('index', [
                'dataProvider' => $dataProvider,
                'searchModel' => $searchModel,
        ]);
    }

    /**
     * Displays a single Menu model.
     * @param  integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
                'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Menu model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Menu;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Helper::invalidate();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                    'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Menu model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param  integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if ($model->menuParent) {
            $model->parent_name = $model->menuParent->name;
        }
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Helper::invalidate();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                    'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Menu model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param  integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        Helper::invalidate();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Menu model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param  integer $id
     * @return Menu the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Menu::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
from . import test_settings
from django.conf import settings
from django.urls import include, path
from django.conf.urls.static import static
from django.contrib import admin

# the DEBUG setting in test_settings is not respected
settings.DEBUG = True

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('wooey.urls')),
    path('', include('django.contrib.auth.urls')),
]

urlpatterns += static(test_settings.MEDIA_URL, document_root=test_settings.MEDIA_ROOT)
urlpatterns += static(test_settings.STATIC_URL, document_root=test_settings.STATIC_ROOT)


text:
package com.example.rth.moneyrecord;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;

import com.example.rth.data.MoneyRecord;
import com.example.rth.fragments.CreateRecordFragment;

/**
 * Created by rth on 15-9-11.
 */
public class CreateRecordActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_record);
        Intent intent = getIntent();
        MoneyRecord record = null;
        if(intent != null) {
            record = intent.getParcelableExtra("record");
        }
        initView(record);
    }

    /**
     * 初始化视图
     */
    private void initView(MoneyRecord record) {
        Fragment fragment = CreateRecordFragment.getInstance(record);
        getSupportFragmentManager().beginTransaction().add(R.id.activity_create_rl_container,fragment)
                .commit();
    }
}


text:
require "forwardable"

module HTTP
  class Headers
    # Provides shared behavior for {HTTP::Request} and {HTTP::Response}.
    # Expects `@headers` to be an instance of {HTTP::Headers}.
    #
    # @example Usage
    #
    #   class MyHttpRequest
    #     include HTTP::Headers::Mixin
    #
    #     def initialize
    #       @headers = HTTP::Headers.new
    #     end
    #   end
    module Mixin
      extend Forwardable

      # @return [HTTP::Headers]
      attr_reader :headers

      # @!method []
      #   (see HTTP::Headers#[])
      def_delegator :headers, :[]

      # @!method []=
      #   (see HTTP::Headers#[]=)
      def_delegator :headers, :[]=
    end
  end
end


text:
/**
 *
 * Emerald (kbi/elude @2014-2016)
 *
 * Private functions only.
 */
#ifndef COLLADA_DATA_SOURCE_H
#define COLLADA_DATA_SOURCE_H

#include "collada/collada_types.h"
#include "collada/collada_data_float_array.h"
#include "tinyxml2.h"

enum collada_data_source_property
{
    COLLADA_DATA_SOURCE_PROPERTY_ID,

    /* Always last */
    COLLADA_DATA_SOURCE_PROPERTY_COUNT
};

/** TODO */
PUBLIC collada_data_source collada_data_source_create(tinyxml2::XMLElement*     element_ptr,
                                                      collada_data              data,
                                                      system_hashed_ansi_string parent_geometry_name);

/** TODO */
PUBLIC void collada_data_source_get_source_float_data(collada_data_source       source,
                                                      collada_data_float_array* out_float_array_ptr);

/** TODO */
PUBLIC void collada_data_source_get_source_name_data(collada_data_source      source,
                                                     collada_data_name_array* out_name_array_ptr);

/** TODO */
PUBLIC void collada_data_source_get_property(collada_data_source          source,
                                             collada_data_source_property property,
                                             void*                        result_ptr);

/** TODO */
PUBLIC void collada_data_source_release(collada_data_source source);

#endif /* COLLADA_DATA_SOURCE_H */


text:
package org.apache.camel.component.reactor.engine;

import java.io.Closeable;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.camel.Exchange;
import org.apache.camel.component.reactive.streams.ReactiveStreamsBackpressureStrategy;
import org.apache.camel.component.reactive.streams.ReactiveStreamsDiscardedException;
import org.apache.camel.component.reactive.streams.ReactiveStreamsHelper;
import org.apache.camel.component.reactive.streams.ReactiveStreamsProducer;
import org.apache.camel.util.ObjectHelper;
import org.reactivestreams.Publisher;
import reactor.core.publisher.EmitterProcessor;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import reactor.core.publisher.SynchronousSink;
import reactor.util.concurrent.Queues;

final class ReactorCamelProcessor implements Closeable {
    private final String name;
    private final EmitterProcessor<Exchange> publisher;
    private final AtomicReference<FluxSink<Exchange>> camelSink;

    private final ReactorStreamsService service;
    private ReactiveStreamsProducer camelProducer;

    ReactorCamelProcessor(ReactorStreamsService service, String name) {
        this.service = service;
        this.name = name;

        this.camelProducer = null;
        this.camelSink = new AtomicReference<>();

        // TODO: The perfect emitter processor would have no buffer (0 sized)
        // The chain caches one more item than expected.
        // This implementation has (almost) full control over backpressure, but it's too chatty.
        // There's a ticket to improve chattiness of the reactive-streams internal impl.
        this.publisher = EmitterProcessor.create(1, false);
    }

    @Override
    public void close() throws IOException {
    }

    Publisher<Exchange> getPublisher() {
        return publisher;
    }

    synchronized void attach(ReactiveStreamsProducer producer) {
        Objects.requireNonNull(producer, "producer cannot be null, use the detach method");

        if (this.camelProducer != null) {
            throw new IllegalStateException("A producer is already attached to the stream '" + name + "'");
        }

        if (this.camelProducer != producer) {
            detach();

            ReactiveStreamsBackpressureStrategy strategy = producer.getEndpoint().getBackpressureStrategy();
            Flux<Exchange> flux = Flux.create(camelSink::set, FluxSink.OverflowStrategy.IGNORE);

            if (ObjectHelper.equal(strategy, ReactiveStreamsBackpressureStrategy.OLDEST)) {
                // signal item emitted for non-dropped items only
                flux = flux.onBackpressureDrop(this::onBackPressure).handle(this::onItemEmitted);
            } else if (ObjectHelper.equal(strategy, ReactiveStreamsBackpressureStrategy.LATEST)) {
                // Since there is no callback for dropped elements on backpressure "latest", item emission is signaled before dropping
                // No exception is reported back to the exchanges
                flux = flux.handle(this::onItemEmitted).onBackpressureLatest();
            } else {
                // Default strategy is BUFFER
                flux = flux.onBackpressureBuffer(Queues.SMALL_BUFFER_SIZE, this::onBackPressure).handle(this::onItemEmitted);
            }

            flux.subscribe(this.publisher);

            camelProducer = producer;
        }
    }

    synchronized void detach() {

        this.camelProducer = null;
        this.camelSink.set(null);
    }

    void send(Exchange exchange) {
        if (service.isRunAllowed()) {
            FluxSink<Exchange> sink = ObjectHelper.notNull(camelSink.get(), "FluxSink");
            sink.next(exchange);
        }
    }

    // **************************************
    // Helpers
    // **************************************

    private void onItemEmitted(Exchange exchange, SynchronousSink<Exchange> sink) {
        if (service.isRunAllowed()) {
            sink.next(exchange);
            ReactiveStreamsHelper.invokeDispatchCallback(exchange);
        }
    }

    private void onBackPressure(Exchange exchange) {
        ReactiveStreamsHelper.invokeDispatchCallback(
                exchange,
                new ReactiveStreamsDiscardedException("Discarded by back pressure strategy", exchange, name));
    }
}


text:
// NOTE: This file was generated by the ServiceGenerator.

// ----------------------------------------------------------------------------
// API:
//   Ad Experience Report API (adexperiencereport/v1)
// Description:
//   Views Ad Experience Report data, and gets a list of sites that have a
//   significant number of annoying ads.
// Documentation:
//   https://developers.google.com/ad-experience-report/

#import <GoogleAPIClientForREST/GTLRService.h>

#if GTLR_RUNTIME_VERSION != 3000
#error This file was generated by a different version of ServiceGenerator which is incompatible with this GTLR library source.
#endif

// Generated comments include content from the discovery document; avoid them
// causing warnings since clang's checks are some what arbitrary.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdocumentation"

NS_ASSUME_NONNULL_BEGIN

/**
 *  Service for executing Ad Experience Report API queries.
 *
 *  Views Ad Experience Report data, and gets a list of sites that have a
 *  significant number of annoying ads.
 */
@interface GTLRAdExperienceReportService : GTLRService

// No new methods

// Clients should create a standard query with any of the class methods in
// GTLRAdExperienceReportQuery.h. The query can the be sent with GTLRService's
// execute methods,
//
//   - (GTLRServiceTicket *)executeQuery:(GTLRQuery *)query
//                     completionHandler:(void (^)(GTLRServiceTicket *ticket,
//                                                 id object, NSError *error))handler;
// or
//   - (GTLRServiceTicket *)executeQuery:(GTLRQuery *)query
//                              delegate:(id)delegate
//                     didFinishSelector:(SEL)finishedSelector;
//
// where finishedSelector has a signature of:
//
//   - (void)serviceTicket:(GTLRServiceTicket *)ticket
//      finishedWithObject:(id)object
//                   error:(NSError *)error;
//
// The object passed to the completion handler or delegate method
// is a subclass of GTLRObject, determined by the query method executed.

@end

NS_ASSUME_NONNULL_END

#pragma clang diagnostic pop


text:
"""
This module provide Serving backend, that use <werkzeug>.
"""

from ..utils import *

class servBackend:
   """

   """
   _id='werkzeug'
   _supportRawSocket=False
   _supportGevent=True
   _supportNative=True
   _supportMultiple=False

   def __init__(self, id=None):
      #check importing
      from werkzeug.serving import make_server
      #init settings and _id
      self.settings=magicDict({})
      self._id=id or self._id

   def create(self, bind_addr, wsgiApp, log=True, sslArgs=None, backlog=1000, threaded=True):
      from werkzeug.serving import make_server as werkzeug
      if not log:
         import logging
         log=logging.getLogger('werkzeug')
         log.setLevel(logging.ERROR)
      sslContext=None
      if sslArgs:
         import ssl
         sslContext=ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) #SSL.Context(SSL.SSLv23_METHOD)
         sslContext.load_cert_chain(sslArgs[1], sslArgs[0])
      server=werkzeug(bind_addr[0], bind_addr[1], wsgiApp, threaded=threaded, ssl_context=sslContext)
      return server

   def start(self, bindAdress, wsgiApp, server, joinLoop):
      if not hasattr(server, '_server'): server._server=[]
      if not hasattr(server, '_serverThread'): server._serverThread=[]
      s=self.create(bindAdress, wsgiApp, log=server.setts.debug, sslArgs=server.setts.ssl, backlog=server.setts.backlog, threaded=True)
      sThread=server._thread(s.serve_forever)
      server._server.append(s)
      server._serverThread.append(sThread)
      if joinLoop:
         try:
            while server.started: server._sleep(1000)
         except KeyboardInterrupt: pass

   def stop(self, serverInstance, serverIndex, server, timeout=5):
      serverInstance._BaseServer__shutdown_request=True
      serverInstance._BaseServer__serving=False
      server._serverThread[serverIndex].join(timeout)


text:
export DEBIAN_FRONTEND=noninteractive
export DEBIAN_PRIORITY=critical

apt-get -q -y --force-yes update
#below are needed for ruby perhaps
#apt-get -y install linux-headers-$(uname -r) build-essential
#apt-get -y install zlib1g-dev libssl-dev libreadline-gplv2-dev
apt-get -q -y --force-yes install curl unzip
apt-get clean

# Set up sudo, TODO: Check security concerns
echo 'cloud ALL=NOPASSWD:ALL' > /etc/sudoers.d/cloud

# Tweak sshd to prevent DNS resolution (speed up logins)
echo 'UseDNS no' >> /etc/ssh/sshd_config

# Remove 5s grub timeout to speed up booting
cat <<EOF > /etc/default/grub
# If you change this file, run 'update-grub' afterwards to update
# /boot/grub/grub.cfg.

GRUB_DEFAULT=0
GRUB_TIMEOUT=0
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="quiet"
GRUB_CMDLINE_LINUX="debian-installer=en_US"
EOF

update-grub


text:
/**
 * This barrel file provides the exports for shared resources
 */
export * from './ng4-twitter-timeline/index';


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;
using System.Globalization;

namespace Newtonsoft.Json.Utilities
{
    internal delegate T Creator<T>();

    internal static class MiscellaneousUtils
    {
        public static bool ValueEquals(object objA, object objB)
        {
            if (objA == objB)
            {
                return true;
            }
            if (objA == null || objB == null)
            {
                return false;
            }

            // comparing an Int32 and Int64 both of the same value returns false
            // make types the same then compare
            if (objA.GetType() != objB.GetType())
            {
                if (ConvertUtils.IsInteger(objA) && ConvertUtils.IsInteger(objB))
                {
                    return Convert.ToDecimal(objA, CultureInfo.CurrentCulture).Equals(Convert.ToDecimal(objB, CultureInfo.CurrentCulture));
                }
                else if ((objA is double || objA is float || objA is decimal) && (objB is double || objB is float || objB is decimal))
                {
                    return MathUtils.ApproxEquals(Convert.ToDouble(objA, CultureInfo.CurrentCulture), Convert.ToDouble(objB, CultureInfo.CurrentCulture));
                }
                else
                {
                    return false;
                }
            }

            return objA.Equals(objB);
        }

        public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(string paramName, object actualValue, string message)
        {
            string newMessage = message + Environment.NewLine + @"Actual value was {0}.".FormatWith(CultureInfo.InvariantCulture, actualValue);

            return new ArgumentOutOfRangeException(paramName, newMessage);
        }

        public static string ToString(object value)
        {
            if (value == null)
            {
                return "{null}";
            }

            return (value is string) ? @"""" + value.ToString() + @"""" : value.ToString();
        }

        public static int ByteArrayCompare(byte[] a1, byte[] a2)
        {
            int lengthCompare = a1.Length.CompareTo(a2.Length);
            if (lengthCompare != 0)
            {
                return lengthCompare;
            }

            for (int i = 0; i < a1.Length; i++)
            {
                int valueCompare = a1[i].CompareTo(a2[i]);
                if (valueCompare != 0)
                {
                    return valueCompare;
                }
            }

            return 0;
        }

        public static string GetPrefix(string qualifiedName)
        {
            string prefix;
            string localName;
            GetQualifiedNameParts(qualifiedName, out prefix, out localName);

            return prefix;
        }

        public static string GetLocalName(string qualifiedName)
        {
            string prefix;
            string localName;
            GetQualifiedNameParts(qualifiedName, out prefix, out localName);

            return localName;
        }

        public static void GetQualifiedNameParts(string qualifiedName, out string prefix, out string localName)
        {
            int colonPosition = qualifiedName.IndexOf(':');

            if ((colonPosition == -1 || colonPosition == 0) || (qualifiedName.Length - 1) == colonPosition)
            {
                prefix = null;
                localName = qualifiedName;
            }
            else
            {
                prefix = qualifiedName.Substring(0, colonPosition);
                localName = qualifiedName.Substring(colonPosition + 1);
            }
        }

        internal static string FormatValueForPrint(object value)
        {
            if (value == null)
            {
                return "{null}";
            }

            if (value is string)
            {
                return @"""" + value + @"""";
            }

            return value.ToString();
        }
    }
}


text:
window.addEventListener("load", function(){
setTimeout(function(){
	function captureEditElements(){
		var registrar = document.getElementById("register");
		var password1 = document.getElementById("password");
		var password2 = document.getElementById("password2");
		var mail = document.getElementById("mail");
		var date = document.getElementById("birthdate");
		var address = document.getElementById("address");
		var error = document.getElementById("error");
		var regExPassword = /^[_a-z0-9-]{8,}$/;
		var regExMail = /^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/;
		var regExDate = /^\d{2}-\d{2}-\d{4}$/;
		var errorValidatePassword = true;
		var errorValidateMail = true;
		var errorValidateDate = true;
	}

	function captureSiembraElements(){
		var publishSiembra = document.getElementById("publish");
		var dateSiembra = document.getElementById("date");
		var error = document.getElementById("error");
		var regExSiembra = /^\d{2}-\d{2}-\d{4}$/;
		var errorValidateSiembra = true;
	}

	function validatePassword(){
		if(!regExPassword.test(password1.value.trim())){
			error.innerHTML = "Password incorrecto. Debe tener al menos 8 carácteres";
			errorValidatePassword = true;
		}
	    else{
	        error.innerHTML = "";
	        errorValidatePassword = false;
	    }
	}

	function validateMail(){
		if(!regExMail.test(mail.value.trim())){
			error.innerHTML = "Mail incorrecto";
			errorValidateMail = true;
		}
	    else{
	        error.innerHTML = "";
	        errorValidateMail = false;
	    }
	}

	function validateDate(){
		if(!regExFecha.test(date.value.trim())){
			error.innerHTML = "El formato para la fecha debe ser dd-mm-aaaa.";
			errorValidateDate = true;
		}
		else{
			var arrayDate = date.value.split("-");
			var day = parseInt(arrayDate[0]);
			var month = parseInt(arrayDate[1] - 1);
			var year = parseInt(arrayDate[2]);
			var aDate = new Date(year, month, day);
			if(aDate.getDate() == day){
				if(aDate.getMonth() == month){
					if(aDate.getFullYear() == year){
						errorValidateDate = false;
						error.innerHTML = "";
					}
				}
			}
			else{
				error.innerHTML = "El formato es correcto pero la fecha no es válida.";
				errorValidateDate = true;
			}
		}
	}

	function validateFutureSiembra(){
		if(!regExSiembra.test(dateSiembra.value.trim())){
			error.innerHTML = "El formato para la fecha debe ser dd-mm-aaaa.";
			errorValidateSiembra = true;
		}
		else{
			var arrayDate = dateSiembra.value.split("-");
			var day = parseInt(arrayDate[0]);
			var month = parseInt(arrayDate[1] - 1);
			var year = parseInt(arrayDate[2]);
			var aDate = new Date(year, month, day);
			if(aDate.getDate() == day){
				if(aDate.getMonth() == month){
					if(aDate.getFullYear() == year){
						errorValidateSiembra = false;
						error.innerHTML = "";
					}
				}
			}
			else{
				error.innerHTML = "El formato es correcto pero la fecha no es válida.";
				errorValidateSiembra = true;
			}
		}
	}

	function validateInfo(){
		captureEditElements();
		password2.addEventListener("blur", validatePassword);
		date.addEventListener("blur", validateMail);
		address.addEventListener("blur", validateDate);
		register.addEventListener("click", function(){
			validateDate();
			validateMail();
			validatePassword();
			if(!errorValidateMail && !errorValidateDate && !errorValidatePassword){
				register.disabled = false;
			}
		});
	}

	function validateSiembra(){
		captureSiembraElements;
		publishSiembra.addEventListener("click", function(){
			validateFutureSiembra();
			if(!errorValidateSiembra){
				publishSiembra.disabled = false;
			}
		});
	}

	// ZONA QUE TRABAJA LA OCULTAR/MOSTRAR DE CADA SECTION EN FUNCIÓN DE LA PESTAÑA PULSADA

	function hideSections(){
		infoSection.style.display = 'none';
		imageSection.style.display = 'none';
		publishSection.style.display = 'none';
		tipSection.style.display = 'none';
		closeSection.style.display = 'none';
	}

	function showSelectedSection(section){
		hideSections();
		section.style.display = 'inline-block';
	}

	var infoTabSm = document.getElementById("info-tab-sm");
	var imageTabSm = document.getElementById("image-tab-sm");
	var publishTabSm = document.getElementById("publish-tab-sm");
	var tipTabSm = document.getElementById("tip-tab-sm");
	var closeTabSm = document.getElementById("close-tab-sm");
	var infoTabLg = document.getElementById("info-tab-lg");
	var imageTabLg = document.getElementById("image-tab-lg");
	var publishTabLg = document.getElementById("publish-tab-lg");
	var tipTabLg = document.getElementById("tip-tab-lg");
	var closeTabLg = document.getElementById("close-tab-lg");
	var infoSection = document.getElementById("info");
	var imageSection = document.getElementById("image");
	var tipSection = document.getElementById("tip");
	var publishSection = document.getElementById("publish");
	var closeSection = document.getElementById("close");

	console.log(infoTabSm);

	document.getElementById("error").innerHTML = "";

	infoTabLg.addEventListener("click", function(){
		showSelectedSection(infoSection);
	});

	infoTabSm.addEventListener("click", function(){
		showSelectedSection(infoSection);
	});

	imageTabLg.addEventListener("click", function(){
		showSelectedSection(imageSection);
	});

	imageTabSm.addEventListener("click", function(){
		showSelectedSection(imageSection);
	});

	publishTabLg.addEventListener("click", function(){
		showSelectedSection(publishSection);
	});

	publishTabSm.addEventListener("click", function(){
		showSelectedSection(publishSection);
	});

	tipTabLg.addEventListener("click", function(){
		showSelectedSection(tipSection);
	});

	tipTabSm.addEventListener("click", function(){
		showSelectedSection(tipSection);
	});

	closeTabLg.addEventListener("click", function(){
		showSelectedSection(closeSection);
	});

	closeTabSm.addEventListener("click", function(){
		showSelectedSection(closeSection);
	});
}, 1);
});


text: <!doctype html>


text:
import datetime
import os
import logging
import time

import pytz

from fedlearner.common import fl_logging

class Config(object):
    DATA_JOIN_METRICS_SAMPLE_RATE = \
        float(os.environ.get('DATA_JOIN_METRICS_SAMPLE_RATE', 0.3))
    RAW_DATA_METRICS_SAMPLE_RATE = \
        float(os.environ.get('RAW_DATA_METRICS_SAMPLE_RATE', 0.0))
    ES_BATCH_SIZE = int(float(os.environ.get('ES_BATCH_SIZE', 1000)))
    TZ = pytz.timezone(os.environ.get('TZ', 'UTC'))
    ES_USERNAME = os.environ.get('ES_USERNAME', 'elastic')
    ES_PASSWORD = os.environ.get('ES_PASSWORD', 'Fedlearner123')
    METRICS_TO_STDOUT = int(float(os.environ.get('METRICS_TO_STDOUT', 0)))

INVALID_DATETIME = datetime.datetime.fromtimestamp(0)
# YYYY-MM-DD'T'hh:mm:ss.SSSSSSZ
_es_datetime_format = 'strict_date_optional_time'
# WARNING: MAPPINGS BELOW ARE COMPATIBILITY MEASURES AND SHOULD NOT BE MODIFIED.
RAW_DATA_MAPPINGS = {
    "dynamic": True,
    "dynamic_templates": [
        {
            "strings": {
                "match_mapping_type": "string",
                "mapping": {
                    "type": "keyword"
                }
            }
        }
    ],
    "properties": {
        "tags": {
            "properties": {
                "partition": {
                    "type": "short"
                },
                "application_id": {
                    "ignore_above": 128,
                    "type": "keyword"
                },
                "event_time": {
                    "format": _es_datetime_format,
                    "type": "date"
                },
                "process_time": {
                    "format": _es_datetime_format,
                    "type": "date"
                }
            }
        }
    }
}
DATA_JOIN_MAPPINGS = {
    "dynamic": True,
    # for dynamically adding string fields, use keyword to reduce space
    "dynamic_templates": [
        {
            "strings": {
                "match_mapping_type": "string",
                "mapping": {
                    "type": "keyword"
                }
            }
        }
    ],
    "properties": {
        "tags": {
            "properties": {
                "partition": {
                    "type": "short"
                },
                "joined": {
                    "type": "byte"
                },
                "label": {
                    "ignore_above": 32,
                    "type": "keyword"
                },
                "type": {
                    "ignore_above": 32,
                    "type": "keyword"
                },
                "has_click_id": {
                    "type": "boolean"
                },
                "has_example_id": {
                    "type": "boolean"
                },
                "application_id": {
                    "ignore_above": 128,
                    "type": "keyword"
                },
                "process_time": {
                    "format": _es_datetime_format,
                    "type": "date"
                },
                "event_time": {
                    "format": _es_datetime_format,
                    "type": "date"
                }
            }
        }
    }
}
METRICS_MAPPINGS = {
    "dynamic": True,
    "dynamic_templates": [
        {
            "strings": {
                "match_mapping_type": "string",
                "mapping": {
                    "type": "keyword"
                }
            }
        }
    ],
    "properties": {
        "name": {
            "type": "keyword"
        },
        "value": {
            "type": "float"
        },
        "tags": {
            "properties": {
                "partition": {
                    "type": "short"
                },
                "application_id": {
                    "ignore_above": 128,
                    "type": "keyword"
                },
                "data_source_name": {
                    "ignore_above": 128,
                    "type": "keyword"
                },
                "joiner_name": {
                    "ignore_above": 32,
                    "type": "keyword"
                },
                "role": {
                    "ignore_above": 32,
                    "type": "keyword"
                },
                "event_time": {
                    "type": "date",
                    "format": _es_datetime_format
                },
                "process_time": {
                    "format": _es_datetime_format,
                    "type": "date"
                }
            }
        }
    }
}
INDEX_NAME = {'metrics': 'metrics_v2',
              'raw_data': 'raw_data',
              'data_join': 'data_join'}
INDEX_TYPE = INDEX_NAME.keys()
INDEX_MAP = {'metrics': METRICS_MAPPINGS,
             'raw_data': RAW_DATA_MAPPINGS,
             'data_join': DATA_JOIN_MAPPINGS}

def get_es_template(index_type, es_version):
    index_name = INDEX_NAME[index_type]
    template = {
        "index_patterns": ["{}-*".format(index_name), index_name],
        "settings": {
            "index": {
                "codec": "best_compression",
                "routing": {
                    "allocation": {
                        "total_shards_per_node": "1"
                    }
                },
                "refresh_interval": "60s",
                "number_of_shards": "1",
                "number_of_replicas": "1",
            }
        }
    }
    if es_version == 6:
        template['mappings'] = {'_doc': INDEX_MAP[index_type]}
    else:
        template['mappings'] = INDEX_MAP[index_type]
    return template

def convert_to_datetime(value, enable_tz=False):
    """
    Args:
        value: datetime object | bytes | str | int | float.
            Value to be converted. Expected to be a numeric in the format of
            yyyymmdd or yyyymmddhhnnss, or a datetime object.
        enable_tz: bool. whether converts to UTC and contains timezone info

    Returns: str.
    Try to convert a datetime str or numeric to a UTC iso format str.
        1. Try to convert based on the length of str.
        2. Try to convert assuming it is a timestamp.
        3. If it does not match any pattern, return iso format of timestamp=0.
        Timezone will be set according to system TZ env if unset and
        then converted back to UTC if enable_tz is True.
    """
    assert isinstance(value, (bytes, str, int, float))
    if isinstance(value, bytes):
        value = value.decode()
    elif isinstance(value, (int, float)):
        value = str(value)
    # 1. try to parse datetime from value
    try:
        date_time = convert_time_string_to_datetime(value)
    except ValueError:  # Not fitting any of above patterns
        # 2. try to convert assuming it is a timestamp
        # not in the same `try` block b/c the length of some strings might
        # be equal to 8 or 14 but it does not match any of the patterns
        try:
            date_time = datetime.datetime.fromtimestamp(float(value))
        except ValueError:  # might be a non-number str
            # 3. default to 0
            fl_logging.warning('Unable to parse time %s to iso format, '
                               'defaults to 0.', value)
            date_time = INVALID_DATETIME
    if enable_tz:
        date_time = set_timezone(date_time)
    return date_time

def set_timezone(date_time):
    if date_time.tzinfo is None:
        date_time = Config.TZ.localize(date_time)
    date_time = pytz.utc.normalize(date_time)
    return date_time

def convert_time_string_to_datetime(value):
    if len(value) == 8:
        date_time = datetime.datetime.strptime(value, '%Y%m%d')
    elif len(value) == 14:
        date_time = datetime.datetime.strptime(value, '%Y%m%d%H%M%S')
    else:
        raise ValueError
    return date_time

def set_logger():
    verbosity = int(os.environ.get('VERBOSITY', 1))
    if verbosity == 0:
        logging.getLogger().setLevel(logging.WARNING)
    elif verbosity == 1:
        logging.getLogger().setLevel(logging.INFO)
    elif verbosity > 1:
        logging.getLogger().setLevel(logging.DEBUG)
    logging.basicConfig(format="%(asctime)s %(filename)s "
                                "%(lineno)s %(levelname)s - %(message)s")

def time_diff(minuend, sub):
    """minuend and sub should be same time format and must be legal numeric.
    """
    ts_minuend = convert_to_datetime(minuend, enable_tz=False).timestamp()
    ts_sub = convert_to_datetime(sub, enable_tz=False).timestamp()
    return ts_minuend - ts_sub

class Timer:
    def __init__(self, content):
        self._content = content
        self._start_time = 0

    def __enter__(self):
        self._start_time = time.time()

    def __exit__(self, exc_type, exc_val, exc_tb):
        logging.info("%s takes %s second", self._content,
                     time.time() - self._start_time)


text:
// RTM.Tools
// RTM.Component.HarrisCornerDetector
// IHarrisDetector.cs
//
// Created by Bartosz Rachwal.
// Copyright (c) 2015 Bartosz Rachwal. The National Institute of Advanced Industrial Science and Technology, Japan. All rights reserved.

using System;
using OpenRTM.Core;

namespace RTM.Component.HarrisCornerDetector.Detector
{
    public interface IHarrisDetector
    {
        CameraImage Image { get; set; }
        void Detect(CameraImage image);
        event EventHandler NewImage;
    }
}


text:
<launch>

  <arg name="invalid" value="$(arg missing)"/>

</launch>