text:
layout: post
title: "How do websites communicate securely?"
author_github: nishanthebbar2011
date: 2017-12-28 23:33:44
image: '/assets/img/'
description: 'How cryptography ensures secure communication'
tags:
- SSL
- Public Key Cryptography
categories:
- CompSoc
github_username: 'nishanthebbar2011'
comments: true
---

The inherent need for human beings has always been to communicate and share information,albeit selectively. For this purpose, the information is to be coded in such a way that it can be deciphered only by the recipient, regardless of whether the recipient is right next to the sender or on the other side of the world. __*The communication channel is assumed to be plagued with adversaries.*__.These adversaries have access to this coded information and are constantly trying to pry.So, the basic problem has always been to:
__*transfer secure information over such insecure channels.*__

So, how DO you communicate when everyone is an adversary and nobody is trustworthy?
The answer is simple.

## Cryptography

> "Cryptography is the art and science of making a crypto system that is capable of providing information security."

The primary objective of cryptography is to provide basic security services like data integrity, confidentiality, user-authenticity and non-repudiation.

## Crypto-systems

Given below is a simple model of a crypto-system

![Crypto-system](/blog/assets/img/Public-key-crypto/cryptosystem.jpg)

There are two types of crypto-systems,based on how the encryption is carried out.

### 1.Symmetric key encryption

Here, a single key is used for both encryption and decryption of the messages and such a key is established in advance by both the sender and the recipient.Thus,there has to exist "trust" between both sender and receiver, so as to not divulge the key.This was the most common method of encryption before the 1970's.

![Symmetric key](/blog/assets/img/Public-key-crypto/symmetric_key_encryption.jpg)

Suppose Alex wants to send a message to Carl using symmetric key encryption , then both of them will have to agree upon a key beforehand and use it to encrypt and decrypt the messages.

### 2. Asymmetric key encryption/Public Key Cryptography

Here, two different keys are used for both encryption and decryption purposes and there exists some mathematical relation between the keys and thus decryption is possible.One of them is the private key and the other one is the public key.It is assumed that the private key is kept secret by a particular individual.

An individual(recipient) makes one of his keys public.A sender can encrypt a message with the help of this public key and such an encrypted message is transmitted over the insecure channel. Only the recipient can decrypt this message with the help of his private key, since he alone possesses it. This is clearly a more elegant solution than symmetric key encryption, that relies on "trust".

![Asymmetric key ](/blog/assets/img/Public-key-crypto/asymmetric_key_encryption.jpg)

The crux of this system is to ensure that it is computationally infeasible to deduce the private key from the public key and the encrypted message.Obviously, it is important to ensure that the public key actually belongs to the recipient. This is usually accomplished with the help of a trusted third party, that hands out digital certificates.These parties are called __*Certificate Authorities(CA's)*__.The public key is usually huge and is stored on such digital certificates whereas, the private key is stored on the system itself.

Also with public-key encryption systems, authenticity of digital systems or documents can also be ascertained with the help of Digital signatures. The content is signed with an individual's private key , and since the public key is easily available, the identity of the user is easily verified.

Suppose Alex sends a message(Using Carl's public key) and a digitally signed document to Carl, using a public-key encryption system, these are the advantages,in a nutshell:

__1.__ It is possible to ascertain Alex's identity from his public key and digital signature on the document.

__2.__ Only Alex could have signed the document,since he alone possesses the private key. Therefore it is not plausible for him to deny   sending it.

__3.__ Only Carl possesses the private key for decrypting the message. He,alone can decrypt the message.

__4.__ When the signature is verified by Carl, it checks that the contents of the document or message match what was in there when the signature was applied. Thus, integrity of the data is preserved.

## The SSL Protocol

 One of the major applications of public key cryptography is it's use in Secure Sockets Layer(SSL) protocol to ensure secure transactions   between web browsers and servers.The protocol uses a CA to identify one or both end of the transactions.This,in short, is how it works:

__1.__ A browser requests a secure page (usually https://).

__2.__ The web server sends its public key with its certificate.

__3.__ The browser checks that the certificate was issued by a trusted party (usually a trusted root CA), that the certificate is still valid and that the certificate is related to the site contacted.

__4.__ The browser then uses the public key, to encrypt a random symmetric encryption key and sends it to the server with the encrypted URL required as well as other encrypted http data.

__5.__ The web server decrypts the symmetric encryption key using its private key and uses the symmetric key to decrypt the URL and htp data.

__6.__ The web server sends back the requested html document and http data encrypted with the symmetric key.

__7.__ The browser decrypts the http data and html document using the symmetric key and displays the information.

Thus, as long as the CA is trustworthy, it is possible for the web browsers and servers to communicate securely and that is how all the information that is continuously exchanged on the internet stays safe and secure.


text:
	Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean congue urna at lacus adipiscing
	sollicitudin. Quisque quis venenatis leo. Etiam eu risus sit amet lectus auctor congue ut quis felis.
	Suspendisse eu velit mattis elit dignissim adipiscing at dapibus ipsum. Curabitur pellentesque diam
	non sapien elementum nec rutrum ligula egestas. Ut a sapien eget mauris elementum dignissim. Fusce
	eu urna odio, vitae accumsan nisl. Suspendisse vel luctus lorem. Mauris mattis eros a ligula lacinia
	sagittis. Ut faucibus tincidunt condimentum. Praesent lacus purus, ultrices ac fringilla a,
	vestibulum eu enim. Fusce est ligula, suscipit a pellentesque vel, ornare sit amet turpis.
	Suspendisse blandit blandit nibh ac pharetra. Nam ultrices consequat ipsum, non imperdiet quam
	venenatis vel. Vivamus eros magna, feugiat quis bibendum nec, lobortis quis libero. Aenean elementum
	condimentum tortor, et tempus turpis pulvinar at. Aliquam sed eros quam, eget tristique arcu.

redpajama_set_name: RedPajamaGithub


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CreateOrUpdateFeatureFlagsComponent } from './create-or-update-feature-flags.component';
import {UserDataService} from '../../../../services/user-data.service';
import {NgbActiveModal, NgbModule} from '@ng-bootstrap/ng-bootstrap';
import {FormBuilder, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {CommonModule} from '@angular/common';
import {HttpClientTestingModule} from '@angular/common/http/testing';

describe('CreateOrUpdateFeatureFlagsComponent', () => {
  let component: CreateOrUpdateFeatureFlagsComponent;
  let fixture: ComponentFixture<CreateOrUpdateFeatureFlagsComponent>;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CreateOrUpdateFeatureFlagsComponent ],
      providers: [UserDataService, FormBuilder, NgbActiveModal],
      imports: [ReactiveFormsModule, NgbModule, FormsModule, CommonModule, HttpClientTestingModule]
    })
      .compileComponents();
  }));
  beforeEach(() => {
    fixture = TestBed.createComponent(CreateOrUpdateFeatureFlagsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
  it('should create', () => {
    expect(component).toBeTruthy();
  });
  it('should create a from ', () => {
    component.ngOnInit();
    expect(component.featureFlagForm).toBeTruthy();
  });
  it('should hit flags edit statements', () => {
    const flags = {
      agileTool: 'false',
      artifact: 'false',
      build: 'false',
      codeQuality: 'false',
      deployment: 'false',
      libraryPolicy: 'false',
      scm: 'false',
      staticSecurityScan: 'false',
      test: 'false',
    };
    const submitTest = {
      name: 'name',
      description: 'description',
      flags
    };
    setTimeout(() => {
      component.featureFlagForm.get('name').setValue(submitTest.name);
      component.featureFlagForm.get('description').setValue(submitTest.description);
      component.id = '123';
      component.submit();
      expect(component.featureFlagForm.valid).toBeTruthy();
    }, 500);
  });
  it('should hit flags post statements', () => {
    const flags1 = {
      agileTool: undefined,
      artifact: undefined,
      build: undefined,
      codeQuality: undefined,
      deployment: undefined,
      libraryPolicy: undefined,
      scm: undefined,
      staticSecurityScan: undefined,
      test: undefined,
    };
    const submitTest = {
      name: 'name',
      description: 'description',
      flags: flags1
    };
    setTimeout(() => {
      component.featureFlagForm.get('name').setValue(submitTest.name);
      component.featureFlagForm.get('description').setValue(submitTest.description);
      component.submit();
      expect(component.featureFlagForm.valid).toBeTruthy();
    }, 500);
  });
});


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

/**
 * @fileoverview Utilities for using the Tabs component during
 * end-to-end testing with Protractor.js
 */

var forms = require('../../../core/tests/protractor_utils/forms.js');

// The 'tabArray' arg should be an array of dictionaries with keys:
//   'title': a string
//   'content': a function that gives rich text editing instructions
var customizeComponent = function(modal, tabArray) {
  var listEditor = forms.ListEditor(modal);

  listEditor.setLength(tabArray.length);
  for (var i = 0; i < tabArray.length; i++) {
    var dictionaryEditor = listEditor.editItem(i, 'Dictionary');
    dictionaryEditor.editEntry(0, 'UnicodeString').setValue(tabArray[i].title);
    var richTextEditor = dictionaryEditor.editEntry(1, 'RichText');
    richTextEditor.clear();
    tabArray[i].content(richTextEditor);
  }
};

var expectComponentDetailsToMatch = function(elem, tabArray) {
  elem.element(by.tagName('ul')).all(by.tagName('li')).then(
    function(titleElems) {
      expect(titleElems.length).toEqual(tabArray.length);
      elem.element(by.css('.tab-content')).all(by.xpath('./*')).
          then(function(contentElems) {
        for (var i = 0; i < tabArray.length; i++) {
          // Click on each tab in turn to check its contents
          expect(titleElems[i].getText()).toMatch(tabArray[i].title);
          titleElems[i].click();
          forms.expectRichText(
            contentElems[i].element(by.xpath('./span'))
          ).toMatch(tabArray[i].content);
        }
      });
    }
  );
};

exports.customizeComponent = customizeComponent;
exports.expectComponentDetailsToMatch = expectComponentDetailsToMatch;


text:
package org.belle.topit.visio.base  ;

import com4j.*;

@IID("{000D0202-0000-0000-C000-000000000046}")
public interface IVUIObject extends Com4jObject {
  // Methods:
  /**
   */

  @DISPID(1610743808) //= 0x60020000. The runtime will prefer the VTID if present
  @VTID(7)
  void delete();

  /**
   *

   * Getter method for the COM property "Default"
   *

   * @return  Returns a value of type java.lang.String
   */

  @DISPID(1610743809) //= 0x60020001. The runtime will prefer the VTID if present
  @VTID(8)
  java.lang.String _default();

  /**
   *

   * Setter method for the COM property "Name"
   *

   * @param pName Mandatory java.lang.String parameter.
   */

  @DISPID(0) //= 0x0. The runtime will prefer the VTID if present
  @VTID(9)
  @DefaultMethod
  void name(
    java.lang.String pName);

  /**
   *

   * Getter method for the COM property "Name"
   *

   * @return  Returns a value of type java.lang.String
   */

  @DISPID(0) //= 0x0. The runtime will prefer the VTID if present
  @VTID(10)
  @DefaultMethod
  java.lang.String name();

  /**
   *

   * Visio versions 5.0 and later no longer support UIObject flavors.
   *

   *

   * Setter method for the COM property "Flavor"
   *

   * @param pFlavor Mandatory short parameter.
   */

  @DISPID(1610743812) //= 0x60020004. The runtime will prefer the VTID if present
  @VTID(11)
  void flavor(
    short pFlavor);

  /**
   *

   * Visio versions 5.0 and later no longer support UIObject flavors.
   *

   *

   * Getter method for the COM property "Flavor"
   *

   * @return  Returns a value of type short
   */

  @DISPID(1610743812) //= 0x60020004. The runtime will prefer the VTID if present
  @VTID(12)
  short flavor();

  /**
   *

   * Getter method for the COM property "MenuSets"
   *

   * @return  Returns a value of type test.IVMenuSets
   */

  @DISPID(1610743814) //= 0x60020006. The runtime will prefer the VTID if present
  @VTID(13)
  org.belle.topit.visio.base.IVMenuSets menuSets();

  @VTID(13)
  @ReturnValue(defaultPropertyThrough={org.belle.topit.visio.base.IVMenuSets.class})
  org.belle.topit.visio.base.IVMenuSet menuSets(
    int lIndex);

  /**
   *

   * Getter method for the COM property "ToolbarSets"
   *

   * @return  Returns a value of type test.IVToolbarSets
   */

  @DISPID(1610743815) //= 0x60020007. The runtime will prefer the VTID if present
  @VTID(14)
  org.belle.topit.visio.base.IVToolbarSets toolbarSets();

  @VTID(14)
  @ReturnValue(defaultPropertyThrough={org.belle.topit.visio.base.IVToolbarSets.class})
  org.belle.topit.visio.base.IVToolbarSet toolbarSets(
    int lIndex);

  /**
   *

   * StatusBars is obsolete as of Visio 2002.
   *

   *

   * Getter method for the COM property "StatusBars"
   *

   * @return  Returns a value of type test.IVStatusBars
   */

  @DISPID(1610743816) //= 0x60020008. The runtime will prefer the VTID if present
  @VTID(15)
  org.belle.topit.visio.base.IVStatusBars statusBars();

  @VTID(15)
  @ReturnValue(defaultPropertyThrough={org.belle.topit.visio.base.IVStatusBars.class})
  org.belle.topit.visio.base.IVStatusBar statusBars(
    int lIndex);

  /**
   *

   * Getter method for the COM property "AccelTables"
   *

   * @return  Returns a value of type test.IVAccelTables
   */

  @DISPID(1610743817) //= 0x60020009. The runtime will prefer the VTID if present
  @VTID(16)
  org.belle.topit.visio.base.IVAccelTables accelTables();

  @VTID(16)
  @ReturnValue(defaultPropertyThrough={org.belle.topit.visio.base.IVAccelTables.class})
  org.belle.topit.visio.base.IVAccelTable accelTables(
    int lIndex);

  /**
   * @param fileName Mandatory java.lang.String parameter.
   */

  @DISPID(1610743818) //= 0x6002000a. The runtime will prefer the VTID if present
  @VTID(17)
  void saveToFile(
    java.lang.String fileName);

  /**
   * @param fileName Mandatory java.lang.String parameter.
   */

  @DISPID(1610743819) //= 0x6002000b. The runtime will prefer the VTID if present
  @VTID(18)
  void loadFromFile(
    java.lang.String fileName);

  /**
   */

  @DISPID(1610743820) //= 0x6002000c. The runtime will prefer the VTID if present
  @VTID(19)
  void updateUI();

  /**
   *

   * Getter method for the COM property "DisplayKeysInTooltips"
   *

   * @return  Returns a value of type boolean
   */

  @DISPID(1610743821) //= 0x6002000d. The runtime will prefer the VTID if present
  @VTID(20)
  boolean displayKeysInTooltips();

  /**
   *

   * Setter method for the COM property "DisplayKeysInTooltips"
   *

   * @param pbShow Mandatory boolean parameter.
   */

  @DISPID(1610743821) //= 0x6002000d. The runtime will prefer the VTID if present
  @VTID(21)
  void displayKeysInTooltips(
    boolean pbShow);

  /**
   *

   * Getter method for the COM property "DisplayTooltips"
   *

   * @return  Returns a value of type boolean
   */

  @DISPID(1610743823) //= 0x6002000f. The runtime will prefer the VTID if present
  @VTID(22)
  boolean displayTooltips();

  /**
   *

   * Setter method for the COM property "DisplayTooltips"
   *

   * @param pbShow Mandatory boolean parameter.
   */

  @DISPID(1610743823) //= 0x6002000f. The runtime will prefer the VTID if present
  @VTID(23)
  void displayTooltips(
    boolean pbShow);

  /**
   *

   * Getter method for the COM property "LargeButtons"
   *

   * @return  Returns a value of type boolean
   */

  @DISPID(1610743825) //= 0x60020011. The runtime will prefer the VTID if present
  @VTID(24)
  boolean largeButtons();

  /**
   *

   * Setter method for the COM property "LargeButtons"
   *

   * @param pbLarge Mandatory boolean parameter.
   */

  @DISPID(1610743825) //= 0x60020011. The runtime will prefer the VTID if present
  @VTID(25)
  void largeButtons(
    boolean pbLarge);

  /**
   *

   * Getter method for the COM property "MenuAnimationStyle"
   *

   * @return  Returns a value of type short
   */

  @DISPID(1610743827) //= 0x60020013. The runtime will prefer the VTID if present
  @VTID(26)
  short menuAnimationStyle();

  /**
   *

   * Setter method for the COM property "MenuAnimationStyle"
   *

   * @param pAnim Mandatory short parameter.
   */

  @DISPID(1610743827) //= 0x60020013. The runtime will prefer the VTID if present
  @VTID(27)
  void menuAnimationStyle(
    short pAnim);

  /**
   *

   * Getter method for the COM property "Clone"
   *

   * @return  Returns a value of type test.IVUIObject
   */

  @DISPID(1610743829) //= 0x60020015. The runtime will prefer the VTID if present
  @VTID(28)
  org.belle.topit.visio.base.IVUIObject clone();

  // Properties:
}


text:
Template.topbar.helpers({
	playlistDuration: function() {
      var Songs = Playlist.find({'position': {$gte: 1}});
      // the total duration
      var totalDuration = 0;
      Songs.forEach(function (song) {
        totalDuration += song.duration;
      });
      // return the formatted timestring
      return timeFormat(totalDuration, totalDuration);
    }
});

Template.topbar.events({
	'click #OptionsButton': function (event) {
		$('#OptionsModal').addClass('active');
	}
});

Template.topbar.onCreated(function() {
	// subscribe to the playlist
	this.autorun(function() {
		this.subscribe('playlist');
	}.bind(this));
});


text:
from twisted.trial import unittest

from twisted.words.xish.domish import Element
from twisted.words.xish.xpath import XPathQuery
from twisted.words.xish import xpath

class XPathTests(unittest.TestCase):
    def setUp(self):
        # Build element:
        # <foo xmlns='testns' attrib1='value1' attrib3="user@host/resource">
        #     somecontent
        #     <bar>
        #        <foo>
        #         <gar>DEF</gar>
        #        </foo>
        #     </bar>
        #     somemorecontent
        #     <bar attrib2="value2">
        #        <bar>
        #          <foo/>
        #          <gar>ABC</gar>
        #        </bar>
        #     <bar/>
        #     <bar attrib4='value4' attrib5='value5'>
        #        <foo/>
        #        <gar>JKL</gar>
        #     </bar>
        #     <bar attrib4='value4' attrib5='value4'>
        #        <foo/>
        #        <gar>MNO</gar>
        #     </bar>
        #     <bar attrib4='value4' attrib5='value6'/>
        # </foo>
        self.e = Element(("testns", "foo"))
        self.e["attrib1"] = "value1"
        self.e["attrib3"] = "user@host/resource"
        self.e.addContent("somecontent")
        self.bar1 = self.e.addElement("bar")
        self.subfoo = self.bar1.addElement("foo")
        self.gar1 = self.subfoo.addElement("gar")
        self.gar1.addContent("DEF")
        self.e.addContent("somemorecontent")
        self.bar2 = self.e.addElement("bar")
        self.bar2["attrib2"] = "value2"
        self.bar3 = self.bar2.addElement("bar")
        self.subfoo2 = self.bar3.addElement("foo")
        self.gar2 = self.bar3.addElement("gar")
        self.gar2.addContent("ABC")
        self.bar4 = self.e.addElement("bar")
        self.bar5 = self.e.addElement("bar")
        self.bar5["attrib4"] = "value4"
        self.bar5["attrib5"] = "value5"
        self.subfoo3 = self.bar5.addElement("foo")
        self.gar3 = self.bar5.addElement("gar")
        self.gar3.addContent("JKL")
        self.bar6 = self.e.addElement("bar")
        self.bar6["attrib4"] = "value4"
        self.bar6["attrib5"] = "value4"
        self.subfoo4 = self.bar6.addElement("foo")
        self.gar4 = self.bar6.addElement("gar")
        self.gar4.addContent("MNO")
        self.bar7 = self.e.addElement("bar")
        self.bar7["attrib4"] = "value4"
        self.bar7["attrib5"] = "value6"

    def test_staticMethods(self):
        """
        Test basic operation of the static methods.
        """
        self.assertEqual(xpath.matches("/foo/bar", self.e),
                          True)
        self.assertEqual(xpath.queryForNodes("/foo/bar", self.e),
                          [self.bar1, self.bar2, self.bar4,
                           self.bar5, self.bar6, self.bar7])
        self.assertEqual(xpath.queryForString("/foo", self.e),
                          "somecontent")
        self.assertEqual(xpath.queryForStringList("/foo", self.e),
                          ["somecontent", "somemorecontent"])

    def test_locationFooBar(self):
        """
        Test matching foo with child bar.
        """
        xp = XPathQuery("/foo/bar")
        self.assertEqual(xp.matches(self.e), 1)

    def test_locationFooBarFoo(self):
        """
        Test finding foos at the second level.
        """
        xp = XPathQuery("/foo/bar/foo")
        self.assertEqual(xp.matches(self.e), 1)
        self.assertEqual(xp.queryForNodes(self.e), [self.subfoo,
                                                     self.subfoo3,
                                                     self.subfoo4])

    def test_locationNoBar3(self):
        """
        Test not finding bar3.
        """
        xp = XPathQuery("/foo/bar3")
        self.assertEqual(xp.matches(self.e), 0)

    def test_locationAllChilds(self):
        """
        Test finding childs of foo.
        """
        xp = XPathQuery("/foo/*")
        self.assertEqual(xp.matches(self.e), True)
        self.assertEqual(xp.queryForNodes(self.e), [self.bar1, self.bar2,
                                                     self.bar4, self.bar5,
                                                     self.bar6, self.bar7])

    def test_attribute(self):
        """
        Test matching foo with attribute.
        """
        xp = XPathQuery("/foo[@attrib1]")
        self.assertEqual(xp.matches(self.e), True)

    def test_attributeWithValueAny(self):
        """
        Test find nodes with attribute having value.
        """
        xp = XPathQuery("/foo/*[@attrib2='value2']")
        self.assertEqual(xp.matches(self.e), True)
        self.assertEqual(xp.queryForNodes(self.e), [self.bar2])

    def test_namespaceFound(self):
        """
        Test matching node with namespace.
        """
        xp = XPathQuery("/foo[@xmlns='testns']/bar")
        self.assertEqual(xp.matches(self.e), 1)

    def test_namespaceNotFound(self):
        """
        Test not matching node with wrong namespace.
        """
        xp = XPathQuery("/foo[@xmlns='badns']/bar2")
        self.assertEqual(xp.matches(self.e), 0)

    def test_attributeWithValue(self):
        """
        Test matching node with attribute having value.
        """
        xp = XPathQuery("/foo[@attrib1='value1']")
        self.assertEqual(xp.matches(self.e), 1)

    def test_queryForString(self):
        """
        Test for queryForString and queryForStringList.
        """
        xp = XPathQuery("/foo")
        self.assertEqual(xp.queryForString(self.e), "somecontent")
        self.assertEqual(xp.queryForStringList(self.e),
                          ["somecontent", "somemorecontent"])

    def test_queryForNodes(self):
        """
        Test finding nodes.
        """
        xp = XPathQuery("/foo/bar")
        self.assertEqual(xp.queryForNodes(self.e), [self.bar1, self.bar2,
                                                     self.bar4, self.bar5,
                                                     self.bar6, self.bar7])

    def test_textCondition(self):
        """
        Test matching a node with given text.
        """
        xp = XPathQuery("/foo[text() = 'somecontent']")
        self.assertEqual(xp.matches(self.e), True)

    def test_textNotOperator(self):
        """
        Test for not operator.
        """
        xp = XPathQuery("/foo[not(@nosuchattrib)]")
        self.assertEqual(xp.matches(self.e), True)

    def test_anyLocationAndText(self):
        """
        Test finding any nodes named gar and getting their text contents.
        """
        xp = XPathQuery("//gar")
        self.assertEqual(xp.matches(self.e), True)
        self.assertEqual(xp.queryForNodes(self.e), [self.gar1, self.gar2,
                                                     self.gar3, self.gar4])
        self.assertEqual(xp.queryForStringList(self.e), ["DEF", "ABC",
                                                          "JKL", "MNO"])

    def test_anyLocation(self):
        """
        Test finding any nodes named bar.
        """
        xp = XPathQuery("//bar")
        self.assertEqual(xp.matches(self.e), True)
        self.assertEqual(xp.queryForNodes(self.e), [self.bar1, self.bar2,
                                                     self.bar3, self.bar4,
                                                     self.bar5, self.bar6,
                                                     self.bar7])

    def test_anyLocationQueryForString(self):
        """
        L{XPathQuery.queryForString} should raise a L{NotImplementedError}
        for any location.
        """
        xp = XPathQuery("//bar")
        self.assertRaises(NotImplementedError, xp.queryForString, None)

    def test_andOperator(self):
        """
        Test boolean and operator in condition.
        """
        xp = XPathQuery("//bar[@attrib4='value4' and @attrib5='value5']")
        self.assertEqual(xp.matches(self.e), True)
        self.assertEqual(xp.queryForNodes(self.e), [self.bar5])

    def test_orOperator(self):
        """
        Test boolean or operator in condition.
        """
        xp = XPathQuery("//bar[@attrib5='value4' or @attrib5='value5']")
        self.assertEqual(xp.matches(self.e), True)
        self.assertEqual(xp.queryForNodes(self.e), [self.bar5, self.bar6])

    def test_booleanOperatorsParens(self):
        """
        Test multiple boolean operators in condition with parens.
        """
        xp = XPathQuery("""//bar[@attrib4='value4' and
                                 (@attrib5='value4' or @attrib5='value6')]""")
        self.assertEqual(xp.matches(self.e), True)
        self.assertEqual(xp.queryForNodes(self.e), [self.bar6, self.bar7])

    def test_booleanOperatorsNoParens(self):
        """
        Test multiple boolean operators in condition without parens.
        """
        xp = XPathQuery("""//bar[@attrib5='value4' or
                                 @attrib5='value5' or
                                 @attrib5='value6']""")
        self.assertEqual(xp.matches(self.e), True)
        self.assertEqual(xp.queryForNodes(self.e), [self.bar5, self.bar6, self.bar7])


text:
/*
 * InputSelectDate Messages
 *
 * This contains all the text for the InputSelectDate component.
 */
import { defineMessages } from 'react-intl';

export default defineMessages({
  january: {
    id: 'ui.form.InputSelectDate.january',
    defaultMessage: 'Janvier',
  },
  february: {
    id: 'ui.form.InputSelectDate.february',
    defaultMessage: 'Février',
  },
  march: {
    id: 'ui.form.InputSelectDate.march',
    defaultMessage: 'Mars',
  },
  april: {
    id: 'ui.form.InputSelectDate.april',
    defaultMessage: 'Avril',
  },
  may: {
    id: 'ui.form.InputSelectDate.may',
    defaultMessage: 'Mai',
  },
  june: {
    id: 'ui.form.InputSelectDate.june',
    defaultMessage: 'Juin',
  },
  july: {
    id: 'ui.form.InputSelectDate.july',
    defaultMessage: 'Juillet',
  },
  august: {
    id: 'ui.form.InputSelectDate.august',
    defaultMessage: 'Aout',
  },
  september: {
    id: 'ui.form.InputSelectDate.september',
    defaultMessage: 'Septembre',
  },
  october: {
    id: 'ui.form.InputSelectDate.october',
    defaultMessage: 'Octobre',
  },
  november: {
    id: 'ui.form.InputSelectDate.november',
    defaultMessage: 'Novembre',
  },
  december: {
    id: 'ui.form.InputSelectDate.december',
    defaultMessage: 'Décembre',
  },
});


text:
/*
Functions that calculate the gravitational potential and its first and second
derivatives for the tesseroid.

The gravity gradients can be calculated using the general formula of
Grombein et al. (2010).
The integrals are solved using the Gauss-Legendre Quadrature rule
(Asgharzadeh et al., 2007).

The derivatives of the potential are made with respect to the local coordinate
system x->North, y->East, z->Up (away from center of the Earth).

To maintain the standard convention, only for component gz the z axis is
inverted, so a positive density results in positive gz.

Example
-------

To calculate the gzz component due to a tesseroid on a regular grid:

    #include <stdio.h>
    #include "glq.h"r
    #include "constants.h"
    #include "grav_tess.h"

    int main()
    {
        TESSEROID tess = {1000, 44, 46, -1, 1, MEAN_EARTH_RADIUS - 100000,
                          MEAN_EARTH_RADIUS};
        GLQ *glqlon, *glqlat, *glqr;
        double lon, lat, r = MEAN_EARTH_RADIUS + 1500000, res;
        int order = 8;

        glqlon = glq_new(order, tess.w, tess.e);
        glqlat = glq_new(order, tess.s, tess.n);
        glqr = glq_new(order, tess.r1, tess.r2);

        for(lat = 20; lat <= 70; lat += 0.5)
        {
            for(lon = -25; lon <= 25; lon += 0.5)
            {
                res = tess_gzz(tess, lon, lat, r, *glqlon, *glqlat, *glqr);
                printf("%g %g %g\n", lon, lat, res);
            }
        }

        glq_free(glqlon);
        glq_free(glqlat);
        glq_free(glqr);

        return 0;
    }

References
----------

Asgharzadeh, M.F., von Frese, R.R.B., Kim, H.R., Leftwich, T.E. & Kim, J.W.
(2007): Spherical prism gravity effects by Gauss-Legendre quadrature integration.
Geophysical Journal International, 169, 1-11.

Grombein, T.; Seitz, K.; Heck, B. (2010): Untersuchungen zur effizienten
Berechnung topographischer Effekte auf den Gradiententensor am Fallbeispiel der
Satellitengradiometriemission GOCE.
KIT Scientific Reports 7547, ISBN 978-3-86644-510-9, KIT Scientific Publishing,
Karlsruhe, Germany.
*/

#ifndef _TESSEROIDS_GRAV_TESS_H_
#define _TESSEROIDS_GRAV_TESS_H_

/* Needed for definition of TESSEROID */
#include "geometry.h"
/* Needed for definition of GLQ */
#include "glq.h"

/** Calculates the field of a tesseroid model at a given point.

Uses a function pointer to call one of the apropriate field calculating
functions:
    - tess_gx()
    - tess_gy()
    - tess_gz()
    - tess_gxx()
    - tess_gxy()
    - tess_gxz()
    - tess_gyy()
    - tess_gyz()
    - tess_gzz()

To pass a function pointer to a function use something like:

\verbatim
calc_tess_model(my_model, 10, 0, 10, 1, glqlon, glqlat, glqr, &tess_gx);
\endverbatim

This would calculate the gx effect of the model my_model with 10 tesseroids
at lon=0 lat=10 r=1.

Will re-use the same GLQ structures, and therefore the same order, for all
the tesseroids.

@param model TESSEROID array defining the model
@param size number of tesseroids in the model
@param lonp longitude of the computation point P
@param latp latitude of the computation point P
@param rp radial coordinate of the computation point P
@param glq_lon pointer to GLQ structure used for the longitudinal integration
@param glq_lat pointer to GLQ structure used for the latitudinal integration
@param glq_r pointer to GLQ structure used for the radial integration
@param field pointer to one of the field calculating functions

@return the sum of the fields of all the tesseroids in the model
*/
extern double calc_tess_model(TESSEROID *model, int size, double lonp,
    double latp, double rp, GLQ *glq_lon, GLQ *glq_lat, GLQ *glq_r,
    double (*field)(TESSEROID, double, double, double, GLQ, GLQ, GLQ));

/** Adaptatively calculate the field of a tesseroid model at a given point by
splitting the tesseroids if necessary to maintain GLQ stability.

See calc_tess_model() for more details.

Will re-use the same GLQ structures, and therefore the same order, for all
the tesseroids.

@param model TESSEROID array defining the model
@param size number of tesseroids in the model
@param lonp longitude of the computation point P
@param latp latitude of the computation point P
@param rp radial coordinate of the computation point P
@param glq_lon pointer to GLQ structure used for the longitudinal integration
@param glq_lat pointer to GLQ structure used for the latitudinal integration
@param glq_r pointer to GLQ structure used for the radial integration
@param field pointer to one of the field calculating functions
@param ratio distance-to-size ratio for doing adaptative resizing

@return the sum of the fields of all the tesseroids in the model
*/
extern double calc_tess_model_adapt(TESSEROID *model, int size, double lonp,
    double latp, double rp, GLQ *glq_lon, GLQ *glq_lat, GLQ *glq_r,
    double (*field)(TESSEROID, double, double, double, GLQ, GLQ, GLQ),
    double ratio);

/** Calculates potential caused by a tesseroid.

\f[
V(r_p,\phi_p,\lambda_p) = G \rho \displaystyle\int_{\lambda_1}^{\lambda_2}
    \displaystyle\int_{\phi_1}^{\phi_2} \displaystyle\int_{r_1}^{r_2}
    \frac{1}{\ell}\kappa \ d r' d \phi' d \lambda'
\f]

Input and output values in SI units and degrees!

Use function glq_new() to create the GLQ parameters required. The integration
limits should be set to:
    - glq_lon: lower = tess.w and upper = tess.e  (in degrees)
    - glq_lat: lower = tess.s and upper = tess.n  (in degrees)
    - glq_r: lower = tess.r1 and upper = tess.r2

@param tess data structure describing the tesseroid
@param lonp longitude of the computation point P
@param latp latitude of the computation point P
@param rp radial coordinate of the computation point P
@param glq_lon GLQ structure with the nodes, weights and integration limits set
    for the longitudinal integration
@param glq_lat GLQ structure with the nodes, weights and integration limits set
    for the latitudinal integration
@param glq_r GLQ structure with the nodes, weights and integration limits set
    for the radial integration

@return field calculated at P
*/
extern double tess_pot(TESSEROID tess, double lonp, double latp, double rp,
                       GLQ glq_lon, GLQ glq_lat, GLQ glq_r);

/** Calculates gx caused by a tesseroid (Grombein et al., 2010).

\f[
g_x(r_p,\phi_p,\lambda_p) = G \rho \displaystyle\int_{\lambda_1}^{\lambda_2}
    \displaystyle\int_{\phi_1}^{\phi_2} \displaystyle\int_{r_1}^{r_2}
    \frac{r'K_{\phi}}{\ell^3}\kappa \ d r' d \phi' d \lambda'
\f]

The derivatives of the potential are made with respect to the local coordinate
system x->North, y->East, z->out

Input values in SI units and degrees and returns values in mGal!

Use function glq_new() to create the GLQ parameters required. The integration
limits should be set to:
    - glq_lon: lower = tess.w and upper = tess.e  (in degrees)
    - glq_lat: lower = tess.s and upper = tess.n  (in degrees)
    - glq_r: lower = tess.r1 and upper = tess.r2

@param tess data structure describing the tesseroid
@param lonp longitude of the computation point P
@param latp latitude of the computation point P
@param rp radial coordinate of the computation point P
@param glq_lon GLQ structure with the nodes, weights and integration limits set
    for the longitudinal integration
@param glq_lat GLQ structure with the nodes, weights and integration limits set
    for the latitudinal integration
@param glq_r GLQ structure with the nodes, weights and integration limits set
    for the radial integration

@return field calculated at P
*/
extern double tess_gx(TESSEROID tess, double lonp, double latp, double rp,
                      GLQ glq_lon, GLQ glq_lat, GLQ glq_r);

/** Calculates gy caused by a tesseroid (Grombein et al., 2010).

\f[
g_y(r_p,\phi_p,\lambda_p) = G \rho \displaystyle\int_{\lambda_1}^{\lambda_2}
    \displaystyle\int_{\phi_1}^{\phi_2} \displaystyle\int_{r_1}^{r_2}
    \frac{r'\cos\phi'\sin(\lambda'-\lambda)}{\ell^3}\kappa
    \ d r' d \phi' d \lambda'
\f]

The derivatives of the potential are made with respect to the local coordinate
system x->North, y->East, z->out

Input values in SI units and degrees and returns values in mGal!

Use function glq_new() to create the GLQ parameters required. The integration
limits should be set to:
    - glq_lon: lower = tess.w and upper = tess.e  (in degrees)
    - glq_lat: lower = tess.s and upper = tess.n  (in degrees)
    - glq_r: lower = tess.r1 and upper = tess.r2

@param tess data structure describing the tesseroid
@param lonp longitude of the computation point P
@param latp latitude of the computation point P
@param rp radial coordinate of the computation point P
@param glq_lon GLQ structure with the nodes, weights and integration limits set
    for the longitudinal integration
@param glq_lat GLQ structure with the nodes, weights and integration limits set
    for the latitudinal integration
@param glq_r GLQ structure with the nodes, weights and integration limits set
    for the radial integration

@return field calculated at P
*/
extern double tess_gy(TESSEROID tess, double lonp, double latp, double rp,
                      GLQ glq_lon, GLQ glq_lat, GLQ glq_r);

/** Calculates gz caused by a tesseroid (Grombein et al., 2010).

\f[
g_z(r_p,\phi_p,\lambda_p) = G \rho \displaystyle\int_{\lambda_1}^{\lambda_2}
    \displaystyle\int_{\phi_1}^{\phi_2} \displaystyle\int_{r_1}^{r_2}
    \frac{r'\cos\psi - r_p}{\ell^3}\kappa \ d r' d \phi' d \lambda'
\f]

The derivatives of the potential are made with respect to the local coordinate
system x->North, y->East, z->out

Input values in SI units and degrees and returns values in mGal!

Use function glq_new() to create the GLQ parameters required. The integration
limits should be set to:
    - glq_lon: lower = tess.w and upper = tess.e  (in degrees)
    - glq_lat: lower = tess.s and upper = tess.n  (in degrees)
    - glq_r: lower = tess.r1 and upper = tess.r2

@param tess data structure describing the tesseroid
@param lonp longitude of the computation point P
@param latp latitude of the computation point P
@param rp radial coordinate of the computation point P
@param glq_lon GLQ structure with the nodes, weights and integration limits set
    for the longitudinal integration
@param glq_lat GLQ structure with the nodes, weights and integration limits set
    for the latitudinal integration
@param glq_r GLQ structure with the nodes, weights and integration limits set
    for the radial integration

@return field calculated at P
*/
extern double tess_gz(TESSEROID tess, double lonp, double latp, double rp,
                      GLQ glq_lon, GLQ glq_lat, GLQ glq_r);

/** Calculates gxx caused by a tesseroid (Grombein et al., 2010).

\f[
g_{xx}(r_p,\phi_p,\lambda_p) = G \rho \displaystyle\int_{\lambda_1}^{\lambda_2}
    \displaystyle\int_{\phi_1}^{\phi_2} \displaystyle\int_{r_1}^{r_2}
    \frac{3(r' K_{\phi})^2 - \ell^2}{\ell^5}\kappa \ d r' d \phi' d \lambda'
\f]

The derivatives of the potential are made with respect to the local coordinate
system x->North, y->East, z->out

Input values in SI units and degrees and returns values in Eotvos!

Use function glq_new() to create the GLQ parameters required. The integration
limits should be set to:
    - glq_lon: lower = tess.w and upper = tess.e  (in degrees)
    - glq_lat: lower = tess.s and upper = tess.n  (in degrees)
    - glq_r: lower = tess.r1 and upper = tess.r2

@param tess data structure describing the tesseroid
@param lonp longitude of the computation point P
@param latp latitude of the computation point P
@param rp radial coordinate of the computation point P
@param glq_lon GLQ structure with the nodes, weights and integration limits set
    for the longitudinal integration
@param glq_lat GLQ structure with the nodes, weights and integration limits set
    for the latitudinal integration
@param glq_r GLQ structure with the nodes, weights and integration limits set
    for the radial integration

@return field calculated at P
*/
extern double tess_gxx(TESSEROID tess, double lonp, double latp, double rp,
                      GLQ glq_lon, GLQ glq_lat, GLQ glq_r);

/** Calculates gxy caused by a tesseroid (Grombein et al., 2010).

\f[
g_{xy}(r_p,\phi_p,\lambda_p) = G \rho \displaystyle\int_{\lambda_1}^{\lambda_2}
    \displaystyle\int_{\phi_1}^{\phi_2} \displaystyle\int_{r_1}^{r_2}
    \frac{3{r'}^2 K_{\phi}\cos\phi'\sin(\lambda' - \lambda_p)}{\ell^5}
    \kappa \ d r' d \phi' d \lambda'
\f]

The derivatives of the potential are made with respect to the local coordinate
system x->North, y->East, z->out

Input values in SI units and degrees and returns values in Eotvos!

Use function glq_new() to create the GLQ parameters required. The integration
limits should be set to:
    - glq_lon: lower = tess.w and upper = tess.e  (in degrees)
    - glq_lat: lower = tess.s and upper = tess.n  (in degrees)
    - glq_r: lower = tess.r1 and upper = tess.r2

@param tess data structure describing the tesseroid
@param lonp longitude of the computation point P
@param latp latitude of the computation point P
@param rp radial coordinate of the computation point P
@param glq_lon GLQ structure with the nodes, weights and integration limits set
    for the longitudinal integration
@param glq_lat GLQ structure with the nodes, weights and integration limits set
    for the latitudinal integration
@param glq_r GLQ structure with the nodes, weights and integration limits set
    for the radial integration

@return field calculated at P
*/
extern double tess_gxy(TESSEROID tess, double lonp, double latp, double rp,
                      GLQ glq_lon, GLQ glq_lat, GLQ glq_r);

/** Calculates gxz caused by a tesseroid (Grombein et al., 2010).

\f[
g_{xz}(r_p,\phi_p,\lambda_p) = G \rho \displaystyle\int_{\lambda_1}^{\lambda_2}
    \displaystyle\int_{\phi_1}^{\phi_2} \displaystyle\int_{r_1}^{r_2}
    \frac{3 r' K_{\phi}(r' \cos\psi - r_p)}{\ell^5}\kappa
    \ d r' d \phi' d \lambda'
\f]

The derivatives of the potential are made with respect to the local coordinate
system x->North, y->East, z->out

Input values in SI units and degrees and returns values in Eotvos!

Use function glq_new() to create the GLQ parameters required. The integration
limits should be set to:
    - glq_lon: lower = tess.w and upper = tess.e  (in degrees)
    - glq_lat: lower = tess.s and upper = tess.n  (in degrees)
    - glq_r: lower = tess.r1 and upper = tess.r2

@param tess data structure describing the tesseroid
@param lonp longitude of the computation point P
@param latp latitude of the computation point P
@param rp radial coordinate of the computation point P
@param glq_lon GLQ structure with the nodes, weights and integration limits set
    for the longitudinal integration
@param glq_lat GLQ structure with the nodes, weights and integration limits set
    for the latitudinal integration
@param glq_r GLQ structure with the nodes, weights and integration limits set
    for the radial integration

@return field calculated at P
*/
extern double tess_gxz(TESSEROID tess, double lonp, double latp, double rp,
                      GLQ glq_lon, GLQ glq_lat, GLQ glq_r);

/** Calculates gyy caused by a tesseroid (Grombein et al., 2010).

\f[
g_{yy}(r_p,\phi_p,\lambda_p) = G \rho \displaystyle\int_{\lambda_1}^{\lambda_2}
    \displaystyle\int_{\phi_1}^{\phi_2} \displaystyle\int_{r_1}^{r_2}
    \frac{3(r'\cos\phi'\sin(\lambda' - \lambda_p))^2 - \ell^2}{\ell^5}
    \kappa \ d r' d \phi' d \lambda'
\f]

The derivatives of the potential are made with respect to the local coordinate
system x->North, y->East, z->out

Input values in SI units and degrees and returns values in Eotvos!

Use function glq_new() to create the GLQ parameters required. The integration
limits should be set to:
    - glq_lon: lower = tess.w and upper = tess.e  (in degrees)
    - glq_lat: lower = tess.s and upper = tess.n  (in degrees)
    - glq_r: lower = tess.r1 and upper = tess.r2

@param tess data structure describing the tesseroid
@param lonp longitude of the computation point P
@param latp latitude of the computation point P
@param rp radial coordinate of the computation point P
@param glq_lon GLQ structure with the nodes, weights and integration limits set
    for the longitudinal integration
@param glq_lat GLQ structure with the nodes, weights and integration limits set
    for the latitudinal integration
@param glq_r GLQ structure with the nodes, weights and integration limits set
    for the radial integration

@return field calculated at P
*/
extern double tess_gyy(TESSEROID tess, double lonp, double latp, double rp,
                      GLQ glq_lon, GLQ glq_lat, GLQ glq_r);

/** Calculates gyz caused by a tesseroid (Grombein et al., 2010).

\f[
g_{yz}(r_p,\phi_p,\lambda_p) = G \rho \displaystyle\int_{\lambda_1}^{\lambda_2}
    \displaystyle\int_{\phi_1}^{\phi_2} \displaystyle\int_{r_1}^{r_2}
    \frac{3 r' \cos\phi' \sin(\lambda' - \lambda_p)(r'\cos\psi - r_p)}{\ell^5}
    \kappa \ d r' d \phi' d \lambda'
\f]

The derivatives of the potential are made with respect to the local coordinate
system x->North, y->East, z->out

Input values in SI units and degrees and returns values in Eotvos!

Use function glq_new() to create the GLQ parameters required. The integration
limits should be set to:
    - glq_lon: lower = tess.w and upper = tess.e  (in degrees)
    - glq_lat: lower = tess.s and upper = tess.n  (in degrees)
    - glq_r: lower = tess.r1 and upper = tess.r2

@param tess data structure describing the tesseroid
@param lonp longitude of the computation point P
@param latp latitude of the computation point P
@param rp radial coordinate of the computation point P
@param glq_lon GLQ structure with the nodes, weights and integration limits set
    for the longitudinal integration
@param glq_lat GLQ structure with the nodes, weights and integration limits set
    for the latitudinal integration
@param glq_r GLQ structure with the nodes, weights and integration limits set
    for the radial integration

@return field calculated at P
*/
extern double tess_gyz(TESSEROID tess, double lonp, double latp, double rp,
                      GLQ glq_lon, GLQ glq_lat, GLQ glq_r);

/** Calculates gzz caused by a tesseroid (Grombein et al., 2010).

\f[
g_{zz}(r_p,\phi_p,\lambda_p) = G \rho \displaystyle\int_{\lambda_1}^{\lambda_2}
    \displaystyle\int_{\phi_1}^{\phi_2} \displaystyle\int_{r_1}^{r_2}
    \frac{3(r'\cos\psi-r_p)^2 - \ell^2}{\ell^5}\kappa \ d r' d \phi' d \lambda'
\f]

The derivatives of the potential are made with respect to the local coordinate
system x->North, y->East, z->out

Input values in SI units and degrees and returns values in Eotvos!

Use function glq_new() to create the GLQ parameters required. The integration
limits should be set to:
    - glq_lon: lower = tess.w and upper = tess.e  (in degrees)
    - glq_lat: lower = tess.s and upper = tess.n  (in degrees)
    - glq_r: lower = tess.r1 and upper = tess.r2

@param tess data structure describing the tesseroid
@param lonp longitude of the computation point P
@param latp latitude of the computation point P
@param rp radial coordinate of the computation point P
@param glq_lon GLQ structure with the nodes, weights and integration limits set
    for the longitudinal integration
@param glq_lat GLQ structure with the nodes, weights and integration limits set
    for the latitudinal integration
@param glq_r GLQ structure with the nodes, weights and integration limits set
    for the radial integration

@return field calculated at P
*/
extern double tess_gzz(TESSEROID tess, double lonp, double latp, double rp,
                      GLQ glq_lon, GLQ glq_lat, GLQ glq_r);

#endif


text:
(api-compatibility)=

# API compatibility

JAX is constantly evolving, and we want to be able to make improvements to its
APIs. That said, we want to minimize churn for the JAX user community, and we
try to make breaking changes rarely.

JAX follows a 3 month deprecation policy. When an incompatible change is made
to an API, we will make our best effort to obey the following procedure:
* the change will be announced in `CHANGELOG.md` and in the doc string for the
  deprecated API, and the old API will issue a `DeprecationWarning`.
* three months after the `jax` release that deprecated an API, we may remove the
  deprecated API at any time. Note that three months is a *lower* bound, and is
  intentionally chosen to be faster than that of many more mature projects. In
  practice, deprecations may take considerably longer, particularly if there are
  many users of a feature. If a three month deprecation period becomes
  problematic, please raise this with us.

We reserve the right to change this policy at any time.

## What is covered?

Only public JAX APIs are covered, which includes the following modules:

* `jax`
* `jax.dlpack`
* `jax.image`
* `jax.lax`
* `jax.nn`
* `jax.numpy`
* `jax.ops`
* `jax.profiler`
* `jax.random`
* `jax.scipy`
* `jax.tree_util`

Not everything in these modules is public. Over time, we are working to separate
public and private APIs. Public APIs are documented in the JAX documentation.
Additionally, our goal is that all non-public APIs should have names
prefixed with underscores, although we do not entirely comply with this yet.

## What is not covered?

*  anything prefixed with an underscore.
* `jax._src`
* `jax.core`
* `jax.linear_util`
* `jax.lib`
* `jax.interpreters`
* `jax.experimental`
* `jax.example_libraries`
* `jax.test_util`

These lists are not exhaustive.


text:
package org.wso2.developerstudio.eclipse.artifact.registry.editor;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.editor.FormEditor;

public class ResourceFormEditor extends FormEditor  {

	private  RegistryResourcePage resourcePage;
    private  boolean isDirty;

	public ResourceFormEditor() {
		 super();
	}

	protected void addPages() {
		resourcePage = new RegistryResourcePage(
				this,
				"org.wso2.developerstudio.eclipse.artifact.registry.editor.FormEditor",
				"Design");
		 try {
			 addPage(resourcePage);

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

	public  void updateDirtyState() {
		isDirty = resourcePage.isDirty();
		firePropertyChange(PROP_DIRTY);
		editorDirtyStateChanged();
    }

	public boolean isDirty() {

		return isDirty;
	}

	public void setDirty(boolean isDirty) {
		this.isDirty = isDirty;
	}

	public void doSave(IProgressMonitor monitor) {

		resourcePage.doPageSave();
	 	}

	public void doSaveAs() {
		// TODO Auto-generated method stub

	}

	public boolean isSaveAsAllowed() {
		return false;
	}

	public void setResourceEditor(RegistryResourcePage resourceEditor) {
		this.resourcePage = resourceEditor;
	}

	public RegistryResourcePage getResourceEditor() {
		return resourcePage;
	}

}


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

  <title>Editing Maps with the Brush</title>

Editing Maps with the Brush.

It is possible to edit the different map types directly using the
brush. This is something I really wanted to include into this
application, but many of the ideas that I had regarding how this should
be done didn't work very well. You should be able to do whatever you
might want to do, but it's not as easy or intuitive as I would have
liked it to be. I will try to use this section to explain some of the
issues you might face while using the brush.

What the brush is useful for.

The brush is most useful for making small edits to maps that you have
made with the generation functions. If you want to connect two oceans
by a channel, or extend a mountain range, or create a mysterious forest
in the middle of a desert, you can do that easily.

However, if you want to paint the entire map from scratch, you might
find the system clunky, confusing and altogether way too much work.
First I will explain some of the basic brush functions and the options
they have and how they work, and then I will explain some of the
confusion that comes with relying only on the brush.

Options for the brush.

The 'Brush Value' control determines the value that is painted with the
brush. If you are not using a
'Smoothing Brush' as indicated by the check box, then the whole brush
will use the value set by the control. If you are using a smoothing
brush, then the brush value selected will be weighted by 100% at the
center of the brush, and 0% at the edge of the brush along a cosine
curve. When the brush weight is 100% it paints the value of the brush,
when the weight is 0% it leaves the underlying values unchanged.
Everything in between will be a smooth blend between your current brush
value and the values that existed before. To demonstrate this curve
better look at the following graph. For a brush of radius 8, this graph
represents the weight of the brush as the distance from the center
increases:

The brush size options are Point, Small, and Large. The reason that you
don't have direct access to the brushes radius, is because I wanted the
cursor to represent the extent of the brushes effect, and I couldn't do
that at every zoom level with a Windows cursor, for complicated reasons
that I won't go into. In any case, the actual size of the brush also
depends upon the zoom level of the map you are painting on. The higher
the zoom, the smaller the brush in terms of tile radius. For the small
and large brush sizes, the extent of the brushes effect is what you see
on the screen no matter the zoom level. The point size brush is a
single map tile no matter what the zoom level, and is weighted 100% on
a smoothing brush or a flat brush.

Painting a map on a blank canvas.

This is where the painting work flow falls a bit short. One problem is
that the final map that combines all the different map inputs is
normalized to values between 0.0 and 1.0. The lowest value on the map
is always 0.0 and the highest value is always 1.0 and everything else
is scaled to be between them. As soon as you start painting on a blank
map with a value of 0.5, as soon as you release the mouse button all
the values you painted will jump to 1.0 as the highest values on the
map. Internally however, the edit value in memory is still 0.5, so if
you then raise the brush value to 0.75 and paint with it, those values
will become 1.0 and the painting you did earlier will fall down to 0.66
or so.

One way to mitigate this confusion somewhat is to decide where you want
your highest mountain and paint a 1.0 there. That will stabilize the
brush values from there on out to make things more predictable, but
there is another item of confusion you will run into. Painting by hand
tends to lead to much of the map having 3 or 4 discrete values, rather
than the full spectrum of highs to lows. This wreaks havoc with the
threshold sliders. The sliders used to adjust the different thresholds
respond to your brush painting to try to maintain an accurate
percentage and they will jump around, wildly changing the colors on the
map as you paint. It takes considerable mental discipline to paint when
colors you are using change with every stroke.

These reasons are why it is easier to edit an existing map than to
paint a new one from scratch.

How the system works.

Edits are not stored on a map in the way other map data stored. There
is no two-dimensional array for the storage of editing data. Each time
you press and release the left mouse button over a map an 'edit'
 containing a list of all the map tiles altered and how they are
altered is pushed onto an undo stack. There is no specific limit to the
levels of undo. You can undo all of your edits at any time, even after
a save and reload. When the final map is built from the input of the
various noise maps etc. the edits are then added to it from the bottom
of the undo stack.


text:
<?php

    $API    = new PerchAPI(1.0, 'content');
    $HTML   = $API->get('HTML');
    $Lang   = $API->get('Lang');
    $Paging = $API->get('Paging');

    $Regions = new PerchContent_Regions;
    $Items   = new PerchContent_Items;
    $Region  = false;

    // Find the region
    if (isset($_GET['id']) && is_numeric($_GET['id'])) {
        $id = (int) $_GET['id'];
        $Region = $Regions->find($id);
    }

    // Check we have a region
    if (!$Region || !is_object($Region)) {
        PerchUtil::redirect(PERCH_LOGINPATH . '/core/apps/content/');
    }

    // Check permissions
    if (!$Region->role_may_edit($CurrentUser)) {
        PerchUtil::redirect(PERCH_LOGINPATH . '/core/apps/content/edit/denied/');
    }

    $Form = new PerchForm('reorder');

    if ($Form->posted() && $Form->validate()) {
        $items = $Form->find_items('item_');
        if (PerchUtil::count($items)) {
            foreach($items as $itemID=>$itemOrder) {
                $Item = $Items->find_item($Region->id(), $itemID, $Region->regionLatestRev());
                if (is_object($Item)) {
                    $data = array();
                    $data['itemOrder'] = (int) $itemOrder;
                    $Item->update($data);
                }
            }
            $Region->set_option('sortField', '');
            if (!$Region->has_draft()) {
                $Region->publish();
                $Region->index();
            }
            $Alert->set('success', PerchLang::get('Item orders successfully updated.'));

            PerchUtil::redirect(PERCH_LOGINPATH.'/core/apps/content/edit/?id='.$Region->id());
        }
    }

    $items = $Region->get_items_for_editing();

	$cols = $Region->get_edit_columns();


text:
package org.guvnor.ala.ui.backend.service;

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

import org.guvnor.ala.config.ProviderConfig;
import org.guvnor.ala.config.RuntimeConfig;
import org.guvnor.ala.pipeline.Input;
import org.guvnor.ala.ui.model.ProviderKey;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class PipelineInputBuilderTest {

    private static final String RUNTIME = "RUNTIME";

    private static final String PROVIDER = "PROVIDER";

    private Map<String, String> params;

    private static final int PARAMS_COUNT = 5;

    @Mock
    private ProviderKey providerKey;

    @Before
    public void setUp() {
        when(providerKey.getId()).thenReturn(PROVIDER);
        params = mockParams(PARAMS_COUNT);
    }

    @Test
    public void testBuild() {
        Input result = PipelineInputBuilder.newInstance()
                .withProvider(providerKey)
                .withParams(params)
                .withRuntimeName(RUNTIME).build();

        assertNotNull(result);
        assertEquals(RUNTIME,
                     result.get(RuntimeConfig.RUNTIME_NAME));
        assertEquals(PROVIDER,
                     result.get(ProviderConfig.PROVIDER_NAME));
        params.forEach((name, value) -> assertEquals(value,
                                                     result.get(name)));
    }

    public static Map<String, String> mockParams(int count) {
        HashMap<String, String> params = new HashMap<>();
        for (int i = 0; i < count; i++) {
            params.put("param.name." + i,
                       "param.value." + i);
        }
        return params;
    }
}


text:
module Filter
  module Matchers
    class Symbol < Base
      def initialize(pattern)
        @pattern = pattern.to_proc
      end

      def ===(other)
        pattern.call(other)
      end
    end
  end
end


text:
package com.github.keenon.loglinear;

import com.github.keenon.loglinear.inference.CliqueTree;
import com.github.keenon.loglinear.model.ConcatVector;
import com.github.keenon.loglinear.model.ConcatVectorNamespace;
import com.github.keenon.loglinear.model.GraphicalModel;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by keenon on 9/11/15.
 *
 * This simulates game-player-like activity, with a few CoNLL CliqueTrees playing host to lots and lots of manipulations
 * by adding and removing human "observations". In real life, this kind of behavior occurs during sampling lookahead for
 * LENSE-like systems.
 *
 * In order to measure only the realistic parts of behavior, and not the random generation of numbers, we pre-cache a
 * few hundred ConcatVectors representing human obs features, then our feature function is just indexing into that cache.
 * The cache is designed to require a bit of L1 cache eviction to page through, so that we don't see artificial speed
 * gains during dot products b/c we already have both features and weights in L1 cache.
 */
public class GamePlayerBenchmark {
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        //////////////////////////////////////////////////////////////
        // Generate the CoNLL CliqueTrees to use during gameplay
        //////////////////////////////////////////////////////////////

        CoNLLBenchmark coNLL = new CoNLLBenchmark();
        String prefix = System.getProperty("user.dir")+"/";
        if (prefix.endsWith("platform")) prefix = prefix+"learning/";

        List<CoNLLBenchmark.CoNLLSentence> train = coNLL.getSentences(prefix + "src/benchmark/data/conll.iob.4class.train");
        List<CoNLLBenchmark.CoNLLSentence> testA = coNLL.getSentences(prefix + "src/benchmark/data/conll.iob.4class.testa");
        List<CoNLLBenchmark.CoNLLSentence> testB = coNLL.getSentences(prefix + "src/benchmark/data/conll.iob.4class.testb");

        List<CoNLLBenchmark.CoNLLSentence> allData = new ArrayList<>();
        allData.addAll(train);
        allData.addAll(testA);
        allData.addAll(testB);

        Set<String> tagsSet = new HashSet<>();
        for (CoNLLBenchmark.CoNLLSentence sentence : allData) for (String nerTag : sentence.ner) tagsSet.add(nerTag);
        List<String> tags = new ArrayList<>();
        tags.addAll(tagsSet);

        coNLL.embeddings = coNLL.getEmbeddings(prefix + "src/benchmark/data/google-300-trimmed.ser.gz", allData);

        System.err.println("Making the training set...");

        ConcatVectorNamespace namespace = new ConcatVectorNamespace();

        int trainSize = train.size();
        GraphicalModel[] trainingSet = new GraphicalModel[trainSize];
        for (int i = 0; i < trainSize; i++) {
            if (i % 10 == 0) {
                System.err.println(i+"/"+trainSize);
            }
            trainingSet[i] = coNLL.generateSentenceModel(namespace, train.get(i), tags);
        }

        //////////////////////////////////////////////////////////////
        // Generate the random human observation feature vectors that we'll use
        //////////////////////////////////////////////////////////////

        Random r = new Random(10);
        int numFeatures = 5;
        int featureLength = 30;
        ConcatVector[] humanFeatureVectors = new ConcatVector[1000];
        for (int i = 0; i < humanFeatureVectors.length; i++) {
            humanFeatureVectors[i] = new ConcatVector(numFeatures);
            for (int j = 0; j < numFeatures; j++) {
                if (r.nextBoolean()) {
                    humanFeatureVectors[i].setSparseComponent(j, r.nextInt(featureLength), r.nextDouble());
                }
                else {
                    double[] dense = new double[featureLength];
                    for (int k = 0; k < dense.length; k++) {
                        dense[k] = r.nextDouble();
                    }
                    humanFeatureVectors[i].setDenseComponent(j, dense);
                }
            }
        }

        ConcatVector weights = new ConcatVector(numFeatures);
        for (int i = 0; i < numFeatures; i++) {
            double[] dense = new double[featureLength];
            for (int j = 0; j < dense.length; j++) dense[j] = r.nextDouble();
            weights.setDenseComponent(i, dense);
        }

        //////////////////////////////////////////////////////////////
        // Actually perform gameplay-like random mutations
        //////////////////////////////////////////////////////////////

        System.err.println("Warming up the JIT...");

        for (int i = 0; i < 10; i++) {
            System.err.println(i);
            gameplay(r, trainingSet[i], weights, humanFeatureVectors);
        }

        System.err.println("Timing actual run...");

        long start = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            System.err.println(i);
            gameplay(r, trainingSet[i], weights, humanFeatureVectors);
        }
        long duration = System.currentTimeMillis() - start;

        System.err.println("Duration: "+duration);
    }

    //////////////////////////////////////////////////////////////
    // This is an implementation of something like MCTS, trying to take advantage of the general speed gains due to fast
    // CliqueTree caching of dot products. It doesn't actually do any clever selection, preferring to select observations
    // at random.
    //////////////////////////////////////////////////////////////

    private static void gameplay(Random r, GraphicalModel model, ConcatVector weights, ConcatVector[] humanFeatureVectors) {
        List<Integer> variablesList = new ArrayList<>();
        List<Integer> variableSizesList = new ArrayList<>();
        for (GraphicalModel.Factor f : model.factors) {
            for (int i = 0; i < f.neigborIndices.length; i++) {
                int j = f.neigborIndices[i];
                if (!variablesList.contains(j)) {
                    variablesList.add(j);
                    variableSizesList.add(f.featuresTable.getDimensions()[i]);
                }
            }
        }

        int[] variables = variablesList.stream().mapToInt(i->i).toArray();
        int[] variableSizes = variableSizesList.stream().mapToInt(i->i).toArray();

        List<SampleState> childrenOfRoot = new ArrayList<>();

        CliqueTree tree = new CliqueTree(model, weights);

        int initialFactors = model.factors.size();

        // Run some "samples"
        long start = System.currentTimeMillis();
        long marginalsTime = 0;
        for (int i = 0; i < 1000; i++) {
            System.err.println("\tTaking sample "+i);
            Stack<SampleState> stack = new Stack<>();
            SampleState state = selectOrCreateChildAtRandom(r, model, variables, variableSizes, childrenOfRoot, humanFeatureVectors);
            long localMarginalsTime = 0;
            // Each "sample" is 10 moves deep
            for (int j = 0; j < 10; j++) {
                // System.err.println("\t\tFrame "+j);
                state.push(model);
                assert(model.factors.size() == initialFactors+j+1);

                ///////////////////////////////////////////////////////////
                // This is the thing we're really benchmarking
                ///////////////////////////////////////////////////////////
                if (state.cachedMarginal == null) {
                    long s = System.currentTimeMillis();
                    state.cachedMarginal = tree.calculateMarginalsJustSingletons();
                    localMarginalsTime += System.currentTimeMillis() - s;
                }

                stack.push(state);
                state = selectOrCreateChildAtRandom(r, model, variables, variableSizes, state.children, humanFeatureVectors);
            }
            System.err.println("\t\t"+localMarginalsTime+" ms");
            marginalsTime += localMarginalsTime;

            while (!stack.empty()) {
                stack.pop().pop(model);
            }
            assert(model.factors.size() == initialFactors);
        }

        System.err.println("Marginals time: "+marginalsTime+" ms");
        System.err.println("Avg time per marginal: "+(marginalsTime / 200)+" ms");
        System.err.println("Total time: "+(System.currentTimeMillis() - start));
    }

    private static SampleState selectOrCreateChildAtRandom(Random r,
                                                           GraphicalModel model,
                                                           int[] variables,
                                                           int[] variableSizes,
                                                           List<SampleState> children,
                                                           ConcatVector[] humanFeatureVectors) {
        int i = r.nextInt(variables.length);
        int variable = variables[i];
        int observation = r.nextInt(variableSizes[i]);

        for (SampleState s : children) {
            if (s.variable == variable && s.observation == observation) return s;
        }

        int humanObservationVariable = 0;
        for (GraphicalModel.Factor f : model.factors) {
            for (int j : f.neigborIndices) {
                if (j >= humanObservationVariable) humanObservationVariable = j+1;
            }
        }

        GraphicalModel.Factor f = model.addFactor(new int[]{variable, humanObservationVariable}, new int[]{variableSizes[i], variableSizes[i]}, (assn) -> {
            int j = (assn[0]*variableSizes[i])+assn[1];
            return humanFeatureVectors[j];
        });
        model.factors.remove(f);

        SampleState newState = new SampleState(f, variable, observation);
        children.add(newState);
        return newState;
    }

    public static class SampleState {
        public GraphicalModel.Factor addedFactor;
        public int variable;
        public int observation;
        public List<SampleState> children = new ArrayList<>();

        public double[][] cachedMarginal = null;

        public SampleState(GraphicalModel.Factor addedFactor, int variable, int observation) {
            this.addedFactor = addedFactor;
            this.variable = variable;
            this.observation = observation;
        }

        /**
         * This applies this SampleState to the model. The name comes from an analogy to a stack. If we take a sample
         * path, involving a number of steps through the model, we push() each SampleState onto the model one at a time,
         * then when we return from the sample we can pop() each SampleState off the model, and be left with our
         * original model state.
         *
         * @param model the model to push this SampleState onto
         */
        public void push(GraphicalModel model) {
            assert(!model.factors.contains(addedFactor));
            model.factors.add(addedFactor);
            model.getVariableMetaDataByReference(variable).put(CliqueTree.VARIABLE_OBSERVED_VALUE, ""+observation);
        }

        /**
         * See push() for an explanation.
         *
         * @param model the model to pop this SampleState from
         */
        public void pop(GraphicalModel model) {
            assert(model.factors.contains(addedFactor));
            model.factors.remove(addedFactor);
            model.getVariableMetaDataByReference(variable).remove(CliqueTree.VARIABLE_OBSERVED_VALUE);
        }
    }
}


text:
class AddTimezoneAndLanguageToUsers < ActiveRecord::Migration

  def self.connection
    User.connection
  end

  def self.up
    add_column :users, :time_zone, :string, :default => 'UTC'
    add_column :users, :language, :string, :default => 'en'
  end

  def self.down
    remove_column :users, :language
    remove_column :users, :time_zone
  end
end


text:
class System::Admin::CoursesController < System::Admin::Controller
  around_action :unscope_resources
  add_breadcrumb :index, :admin_courses_path

  def index
    @courses = Course.includes(:instance).search(search_param).calculated(:active_user_count, :user_count)
    @courses = @courses.active_in_past_7_days.order('active_user_count DESC, user_count') if params[:active]
    @courses = @courses.ordered_by_title.page(page_param)

    @owner_preload_service = Course::CourseOwnerPreloadService.new(@courses.map(&:id))
  end

  def destroy
    @course ||= Course.find(params[:id])

    if @course.destroy
      redirect_to admin_courses_path, success: t('.success', course: @course.title)
    else
      redirect_to admin_courses_path,
                  danger: t('.failure', error: @course.errors.full_messages.to_sentence)
    end
  end

  private

  def search_param
    params.permit(:search)[:search]
  end

  def unscope_resources
    Course.unscoped do
      yield
    end
  end
end


text:
package org.jacp.test.main;

/**
 * Created with IntelliJ IDEA.
 * User: ady
 * Date: 15.10.13
 * Time: 10:19
 * To change this template use File | Settings | File Templates.
 */

import sun.misc.Unsafe;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Benchmarks {

    private static Unsafe getUnsafe() {
        try {
            Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            return (Unsafe) f.get(null);
        } catch (Exception e) {
            return null;
        }
    }

    public static class Employee {

        private String name = "Rick";

        public String getName() {
            return name + "##";
        }

        public void setName(String name) {
            this.name = name;
        }

        public String name() {
            return name;
        }

    }

    public static void main(String[] arg) throws Throwable {
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        Class thisClass = lookup.lookupClass();  // (who am I?)
        Employee employee = new Employee();
        Field fieldName = null;
        String name;
        MethodType methodType;
        MethodHandle methodHandle;

        for (Field field : Employee.class.getDeclaredFields()) {
            if (field.getName().equals("name")) {
                fieldName = field;
                fieldName.setAccessible(true);
                break;
            }
        }
        MethodHandle methodHandleFieldDirect = lookup.unreflectGetter(fieldName);
        name = (String) methodHandleFieldDirect.invokeExact(new Employee());
        System.out.println("method handle for field direct " + name);

        //Lookup invoke dynamic
        methodType = MethodType.methodType(String.class);
        methodHandle = lookup.findVirtual(Employee.class, "getName", methodType);
        name = (String) methodHandle.invokeExact(new Employee());
        System.out.println("invoke dynamic " + name);

        //Lookup reflection
        Method method = Employee.class.getMethod("getName", new Class[]{});
        name = (String) method.invoke(new Employee());
        System.out.println("reflection " + name);

        //Now let's be unsafe
        Unsafe unsafe = getUnsafe();
        long offset = unsafe.objectFieldOffset(fieldName);
        name = (String) unsafe.getObject(new Employee(), offset);

        long[] timesArray = {1_000L,
                10_1000L,
                100_000L,
                1_000_000L,
                10_000_000L,
                100_000_000L
        };

        for (long times : timesArray) {
            long start = 0;
            long end = 0;
            long regularTime;
            long invokeDynamicTime;
            long reflectionTime;
            long invokeDynamicTimeUsingField;
            long fieldDirect;
            long unsafeField;
            long direct;

            System.out.printf("
 %,d
 \n", times);
            //warm up
            for (int index = 0; index < times; index++) {
                employee.getName();
                name = (String) methodHandle.invokeExact(employee);
                name = (String) method.invoke(employee);
                name = (String) methodHandleFieldDirect.invokeExact(employee);
                name = (String) fieldName.get(employee);
                name = (String) unsafe.getObject(new Employee(), offset);

            }

            System.out.printf("\n    \n");

            start = System.nanoTime();
            for (int index = 0; index < times; index++) {
                name = employee.getName();
            }
            end = System.nanoTime();
            regularTime = end - start;
            System.out.printf("\n    \n" +
                    "                  \n" +
                    "                      \n" +
                    "                      \n" +
                    "                  \n", regularTime / times);

            start = System.nanoTime();
            for (int index = 0; index < times; index++) {
                name = (String) methodHandle.invokeExact(employee);
            }
            end = System.nanoTime();
            invokeDynamicTime = end - start;

            System.out.printf("\n    \n" +
                    "                  \n" +
                    "                      \n" +
                    "                      \n" +
                    "                  \n", invokeDynamicTime / times);

            start = System.nanoTime();
            for (int index = 0; index < times; index++) {
                name = (String) method.invoke(employee);
            }
            end = System.nanoTime();
            reflectionTime = end - start;
            System.out.printf("\n    \n" +
                    "                  \n" +
                    "                      \n" +
                    "                      \n" +
                    "                  \n", reflectionTime / times);

            start = System.nanoTime();
            for (int index = 0; index < times; index++) {
                name = (String) methodHandleFieldDirect.invokeExact(employee);
            }
            end = System.nanoTime();
            invokeDynamicTimeUsingField = end - start;
            System.out.printf("\n    \n" +
                    "                  \n" +
                    "                      \n" +
                    "                      \n" +
                    "                  \n", invokeDynamicTimeUsingField / times);

            //old school reflection
            start = System.nanoTime();
            for (int index = 0; index < times; index++) {
                name = (String) fieldName.get(employee);
            }
            end = System.nanoTime();
            fieldDirect = end - start;
            System.out.printf("\n    \n" +
                    "                  \n" +
                    "                      \n" +
                    "                      \n" +
                    "                  \n", fieldDirect / times);

            //unsafe refection
            start = System.nanoTime();
            for (int index = 0; index < times; index++) {
                name = (String) unsafe.getObject(employee, offset);
            }
            end = System.nanoTime();
            unsafeField = end - start;
            System.out.printf("\n    \n" +
                    "                  \n" +
                    "                      \n" +
                    "                      \n" +
                    "                  \n", unsafeField / times);

            //unsafe refection
            start = System.nanoTime();
            for (int index = 0; index < times; index++) {
                name = employee.name;
            }
            end = System.nanoTime();
            direct = end - start;
            System.out.printf("\n    \n" +
                    "                  \n" +
                    "                      \n" +
                    "                      \n" +
                    "                  \n", direct / times);

            // System.out.printf("\n

description	duration in nanoseconds

regular method call time	%d

invoke dynamic method call time	%d

reflection method call time	%d

field method invoke dynamic call time	%d

field method invoke reflection call time	%d

unsafe field access time	%d

direct	%d

\n");

        }
    }
}


text:
datetimestats
=============
.. image:: https://travis-ci.org/JimHaughwout/datetimestats.svg?branch=master
    :target: https://travis-ci.org/JimHaughwout/datetimestats

Useful math stats functions for collections of datetime objects.

Ever had a list or set of datetimes and needed to perform some basic
statistical functions to find the median, mean, minimum, or maximum?
datetimestats provides some basic utilities to do this without the
overhead of converting to a numeric data type (e.g., unix timestamps at
millisecond-level) or pandas data frames (in order to employ pandas time
series functionality).

datetimestats takes any iterable of datetime objects (including panda
Series). It supports naive and non-naive datetimes, including iterables
of objects with different `Olson
timezones <https://en.wikipedia.org/wiki/Tz_database>`__. However, it
does not support iterables that contain both naive *and* non-naive
datetime objects.

Currently, datetimestats is supported for use with Python 2.7.

Installation
------------

Install using `pip <http://www.pip-installer.org/en/latest/>`__ with:

.. code:: sh

    pip install datetimestats

Or download a wheel or source archive from PyPI.

Usage
-----

datatimestats currently supports obtaining the the mean, median, min, or
max of an Iterable of datetime objects. The functions are designed to
minimize time complexity where possible.

Caluclating Means
~~~~~~~~~~~~~~~~~

Mean is calculated as the the arithmetic mean across datetime objects
with micro-second precision.

When given a list of naive datetimes, mean returns a naive datetime
object

.. code:: python

    >>> import datetime as dt
    >>> naive_1 = dt.datetime(2015, 9, 10, 12, 30, 0)
    >>> naive_2 = dt.datetime(2015, 9, 10, 12, 0, 0)
    >>> from datetimestats import mean
    >>> mean([naive_1, naive_2])
    datetime.datetime(2015, 9, 10, 12, 15)

When given a list of non-naive datetimes, it returns the mean as a
datetime object in ``UTC`` time:

.. code:: python

    >>> import datetime as dt
    >>> import pytz
    >>> nyc_noon = dt.datetime(2014, 1, 1, 12, 0, 0, tzinfo=pytz.timezone('America/New_York'))
    >>> print nyc_noon # Curiosity of pytz, it does not convert to whole time zones
    2014-01-01 12:00:00-04:56
    >>> london_noon = dt.datetime(2014, 1, 1, 12, 0, 0, tzinfo=pytz.timezone('Europe/London'))
    >>> singapore_noon = dt.datetime(2014, 1, 1, 12, 0, 0, tzinfo=pytz.timezone('Asia/Singapore'))
    >>> from datetimestats import mean
    >>> mean([nyc_noon, london_noon, singapore_noon])
    datetime.datetime(2014, 1, 1, 11, 20, 40, tzinfo=<UTC>)

Calculating Medians
~~~~~~~~~~~~~~~~~~~

If an odd number of objects are provided, median is calculated is the
inner-most, sorted value. If an even number is provided, median is the
arithmetic-mean of the two inner-most, sorted values.

Odd number of values:

.. code:: python

    >>> import datetime as dt
    >>> import pytz
    >>> london_noon = dt.datetime(2014, 1, 1, 12, 0, 0, tzinfo=pytz.timezone('Europe/London'))
    >>> nyc_noon = dt.datetime(2014, 1, 1, 12, 0, 0, tzinfo=pytz.timezone('America/New_York'))
    >>> singapore_noon = dt.datetime(2014, 1, 1, 12, 0, 0, tzinfo=pytz.timezone('Asia/Singapore'))
    >>> from datetimestats import median
    >>> median([nyc_noon, london_noon, singapore_noon])
    datetime.datetime(2014, 1, 1, 12, 0, tzinfo=<DstTzInfo 'Europe/London' LMT-1 day, 23:59:00 STD>)
    >>> median([nyc_noon, london_noon, singapore_noon]) == london_noon # Noon in London does fall between Singapore and NYC
    True

Even number of values:

.. code:: python

    >>> import datetime as dt
    >>> naive_1 = dt.datetime(2015, 9, 10, 12, 0, 0)
    >>> naive_2 = dt.datetime(2015, 9, 10, 14, 0, 0)
    >>> naive_3 = dt.datetime(2015, 9, 10, 13, 0, 0)
    >>> naive_4 = dt.datetime(2015, 9, 10, 15, 0, 0)
    >>> from datetimestats import median
    >>> median([naive_1, naive_2, naive_3, naive_4])
    datetime.datetime(2015, 9, 10, 14, 30)

Calculating Min and Max datetime
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The min datetime is the *earliest* datetime. Conversely, the max is the
*latest*. This is most interesting when calculating across multiple
timezones:

.. code:: python

    >>> import datetime as dt
    >>> import pytz
    >>> london_noon = dt.datetime(2014, 1, 1, 12, 0, 0, tzinfo=pytz.timezone('Europe/London'))
    >>> nyc_noon = dt.datetime(2014, 1, 1, 12, 0, 0, tzinfo=pytz.timezone('America/New_York'))
    >>> singapore_noon = dt.datetime(2014, 1, 1, 12, 0, 0, tzinfo=pytz.timezone('Asia/Singapore'))
    >>> from datetimestats import min, max
    >>> min([nyc_noon, london_noon, singapore_noon])
    datetime.datetime(2014, 1, 1, 12, 0, tzinfo=<DstTzInfo 'Asia/Singapore' LMT+6:55:00 STD>)
    >>> min([nyc_noon, london_noon, singapore_noon]) == singapore # It is noon in Singapore EARLIEST
    True
    >>> max([nyc_noon, london_noon, singapore_noon])
    datetime.datetime(2014, 1, 1, 12, 0, tzinfo=<DstTzInfo 'America/New_York' LMT-1 day, 19:04:00 STD>)
    >>> max([nyc_noon, london_noon, singapore_noon]) == nyc_noon # It is noon in NYC LATEST
    True

Others
~~~~~~

Sets, tuples, numpy Arrays and pandas Series are also supported:

.. code:: python

    >>> import datetime as dt
    >>> naive_1 = dt.datetime(2015, 9, 10, 12, 0, 0)
    >>> naive_2 = dt.datetime(2015, 9, 10, 14, 0, 0)
    >>> from datetimestats import median
    >>> median([naive_1, naive_2])
    datetime.datetime(2015, 9, 10, 13, 0)
    >>> median((naive_1, naive_2))
    datetime.datetime(2015, 9, 10, 13, 0)
    >>> import numpy as np
    >>> median(np.asarray([naive_1, naive_2]))
    datetime.datetime(2015, 9, 10, 13, 0)
    >>> import pandas as pd
    >>> median(pd.Series([naive_1, naive_2]))
    datetime.datetime(2015, 9, 10, 13, 0)


text:
#ifndef DraggedIsolatedFileSystem_h
#define DraggedIsolatedFileSystem_h

#include "core/clipboard/DataObject.h"
#include "platform/heap/Handle.h"
#include "wtf/Forward.h"
#include "wtf/text/WTFString.h"

namespace blink {

class DOMFileSystem;

class DraggedIsolatedFileSystem final : public NoBaseWillBeGarbageCollectedFinalized<DraggedIsolatedFileSystem>, public WillBeHeapSupplement<DataObject> {
    WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(DraggedIsolatedFileSystem);
public:
    virtual ~DraggedIsolatedFileSystem();

    static PassOwnPtrWillBeRawPtr<DraggedIsolatedFileSystem> create(DataObject& host, const String& filesystemId)
    {
        return adoptPtrWillBeNoop(new DraggedIsolatedFileSystem(host, filesystemId));
    }

    static DOMFileSystem* getDOMFileSystem(DataObject* host, ExecutionContext*);

    static const char* supplementName();
    static DraggedIsolatedFileSystem* from(DataObject*);

    void trace(Visitor*);

private:
    DraggedIsolatedFileSystem(DataObject& host, const String& filesystemId);
    PersistentWillBeMember<DOMFileSystem> m_filesystem;
};

} // namespace blink

#endif // DraggedIsolatedFileSystem_h


text:
<?php

namespace Tests\Fixtures;

use Jet\Console\Command\AbstractCommand;
use Jet\Console\Command\Argument;

class TestCommand extends AbstractCommand
{
    /**
     * Add command with name, argument and description
     *
     * @return void
     */
    public function init()
    {
        $this
            ->setName('testCommand')
            ->setDescription('A test command for unit testing');

        $this->addArgument('argument1', Argument::REQUIRED, null, "A required test argument for the test command");
        $this->addArgument('argument2', Argument::OPTIONAL, null, "A optional test argument for the test command");
    }

    /**
     * Execute the command
     *
     * @return mixed
     */
    public function execute()
    {
        $this->display('this is a test command');

        $argument1 = $this->getArgument('argument1');

        $this->display("Argument1 value is {$argument1}");

        if($this->hasArgument('argument2')){
            $argument2 = $this->getArgument('argument2');
            $this->display("Argument2 defined and value is {$argument2}");
        }
    }
}


text:
namespace avalon{
	class ShaderResource:public Resource{
	friend class Material;
	public:
		ShaderResource(const string &name,const string &path,unsigned int handle);
		~ShaderResource();

	};
}

#endif


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W28581_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Amy

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">OXY USA Inc.
A Subsidiary of Occidental Peroleum Corporation

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">April 7, 2014

    <p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">This statement is being sent in order to comply with NDAC 43-02-03-16 (Application for permit to drill and recomplete) which states (in part that) "confirmation that a legal street address was requested for the well site, and well facility if separate from the well site, and the proposed road access to the nearest existing public roa ". On the date noted below a legal street address was
requested from the appropriate county office.

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Dunn County Denise Brew/LEPC
Well List and surface location:
Well Name Footages NEAL 2-33-28H-l44-95 628F N L 147] FW L TWIST 2-4—9H-l43—95 642 F N L 1434 FW L
FEDERAL ALINA TORMASCHY 266F S L 1685 FW L 2-29-32H-l43-96
FEDERAL ALINA TORMASCHY 264F S L 1725 FW L 3-29-32H-l43-96
EVELYN STROH 4-20-17H-143-96 262F S L 1765 FW L

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">STATE 4—21-16H—143—96 SCHNEIDER 2-28-33H-l43-96 SCHNEIDER 3-28-33H-143-96
MATTHEW SCHMIDT 4-2-35H143-97

    <p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Date submitted for request:

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">April 4, 2014

    <p class="styleSans29.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Elizabeth S. Bus -Ivie
Sr. Regulatory Adviser OXY USA Inc.

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">5 Greenway Plaza. Suite 110, Houston, TX 77046 P. 0. Box 27757. Houston, TX 7722717757 Telephone 713—215-7000,

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">STR Sec 4 T143N R95 w
Sec 4 T143 N R95W Sec 20 T143 N R96 W

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Sec 20 T143N R96W

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Sec 20 T143N R96W

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">606FSL 219OFEL 606FSL 2150FEL 606FSL 2110FEL 350FSL 2370 FEL

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Sec 21 T143N R96W Sec 21 Tl43N R96W Sec 21 T143N R96W Sec 2 T143N R97W


text:
@interface LeftTableViewCell ()
@property(nonatomic,strong)UIImageView *arrow;
@property(nonatomic,strong)UIView *cover;

@end

@implementation LeftTableViewCell

- (void)awakeFromNib {
    // Initialization code
}

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

    // Configure the view for the selected state
}
+(instancetype)cellWithTableView:(UITableView *)tableView identifier:(NSString *)identifier{
    LeftTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell==nil) {
        cell =[[LeftTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    return cell;
}
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self setUpSubViews];
    }
    return self;
}

-(void)setUpSubViews{
    CGFloat tableWW =0.256*SCREEN_WIDTH;
//    //背景
//    UIView *cover =[[UIView alloc]initWithFrame:CGRectMake(0, 0, tableWW, 50)];
//    cover.backgroundColor=RGB(53, 131, 203, 1);
//    [self.contentView addSubview:cover];
//    self.cover=cover;
//    //self.cover.hidden=YES;

    //部门名称
    self.positonBtn =[[UIButton alloc]initWithFrame:CGRectMake(0, 0, tableWW, 50)];
    [self.positonBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.positonBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [self.positonBtn setBackgroundImage:[self createImageWithColor:RGB(53, 131, 203, 1)] forState:UIControlStateSelected];
    self.positonBtn.userInteractionEnabled=NO;
    self.positonBtn.titleLabel.font=[UIFont systemFontOfSize:15];
    [self.contentView addSubview:self.positonBtn];

    //选中背景图
    UIView *back =[[UIView alloc]init];
    //back.backgroundColor=RGB(53, 131, 203, 1);
    back.backgroundColor=[UIColor clearColor];
    self.selectedBackgroundView=back;

    //right Line
    UIView *line =[[UIView alloc]initWithFrame:CGRectMake(tableWW-1, 0, 0.5, 50)];
    line.backgroundColor=[UIColor lightGrayColor];
    [self.contentView addSubview:line];

    //三角箭头16*23
    UIImageView *arrow =[[UIImageView alloc]initWithFrame:CGRectMake(tableWW-9.5, (50-14)/2.0f, 10, 14)];
    arrow.image =[UIImage imageNamed:@"sanjiao"];
    self.arrow=arrow;
    self.arrow.hidden=YES;
    [self.contentView addSubview:arrow];

}

//选中状态
-(void)selectedStatus{
    self.positonBtn.selected=YES;
    self.arrow.hidden=NO;
   // self.cover.hidden=NO;
}

//取消选中
-(void)desSelectedStatus{
    self.positonBtn.selected=NO;
    self.arrow.hidden=YES;
   // self.cover.hidden=YES;
}

-(UIImage *) createImageWithColor: (UIColor *) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

@end


text:
package io.elegie.luchess.pgn.impl.tokens;

import io.elegie.luchess.pgn.impl.tokens.helpers.OneMatchTokenTest;

@SuppressWarnings("javadoc")
public class MoveTextStartTokenTest extends OneMatchTokenTest {

    public MoveTextStartTokenTest() {
        super(MoveTextStartToken.class, null, '1');
    }

}