text:
#!/bin/sh
#/****************************************************************************
# * TEST                                                                     *
# * Test that tesseract is working correctly by running OCR on a few things. *
# * The final digit in the exit code counts the number of tests where the    *
# * tesseract output failed to match the expected output. If there are two   *
# * digits in the exit code, the first digit counts the number of tests      *
# * where tesseract failed to run correctly or produce output.               *
# ****************************************************************************/
EXIT_CODE=0
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

echo
echo

# JPEG test
echo "************************ JPEG TEST ************************"
tesseract $DIR/files/samples/Dr._Jekyll_and_Mr._Hyde_Text.jpg /tmp/jekyll
if [ $? -ne 0 ]; then
  let EXIT_CODE+=10
fi
diff /tmp/jekyll.txt /tmp/jekyll-correct.txt
if [ $? -ne 0 ]; then
  let EXIT_CODE+=1
else
  echo "PASS"
fi
echo
echo

# TIFF test
echo "************************ TIFF TEST ************************"
tesseract $DIR/files/samples/lazydog.tiff /tmp/lazydog
if [ $? -ne 0 ]; then
  let EXIT_CODE+=10
fi
diff /tmp/lazydog.txt /tmp/lazydog-correct.txt
if [ $? -ne 0 ]; then
  let EXIT_CODE+=1
else
  echo "PASS"
fi
echo
echo

## TODO: png files don't work -- something to look into perhaps
## PNG test
# echo "************************ PNG  TEST ************************"
# tesseract $DIR/files/samples/Dan'l_Druce,_Blacksmith_-_Illustrated_London_News,_November_18,_1876_-_text.png /tmp/druce
# if [ $? -ne 0 ]; then
#   let EXIT_CODE+=10
# fi
# diff /tmp/druce.txt /tmp/druce-correct.txt
# if [ $? -ne 0 ]; then
#   let EXIT_CODE+=1
#else
#  echo "PASS"
# fi
# echo
# echo

exit $EXIT_CODE


text:
<?xml version="1.0"?>

<phpunit
        bootstrap="vendor/autoload.php"
        backupGlobals="false"
        backupStaticAttributes="false"
        colors="true"
        convertErrorsToExceptions="true"
        convertNoticesToExceptions="true"
        convertWarningsToExceptions="true"
        processIsolation="false"
        stopOnFailure="false"
        syntaxCheck="false"
        >
    <testsuites>
        <testsuite name="EventSource Test Suite">
            <directory>./test/</directory>
        </testsuite>
    </testsuites>
</phpunit>

redpajama_set_name: RedPajamaGithub


text:
from Bank import Bank, g
import re

def reset():
    try:
        reload(Bank)
        return True
    except Exception as e:
        print(e)
        return False

class Empty:
    pass

class Channel:

    def __init__(self, chan, donald, swift=None, private=False):
        self.channel = chan
        self.nick = g.nick
        self.socket = g.ircsock
        self.cursor = g.cursor
        self.db = g.db
        self.donald = donald
        self.swift = swift
        self.private = private
        self.loggedIn = self.private
        self.clients = []

        if not self.private:
            self.socket.send("JOIN {0}\r\n".format(self.channel))

    def listen(self, msg):
        if msg.find("353") != -1:
            self.loggedIn = True
            groups = re.search("353 {0} . {1} :(.*)".format(self.nick, self.channel), msg)
            try:
                for uname in groups.group(1).split():
                    uname = uname.strip(':+@')
                    if uname.isalpha():
                        self.clients.append(uname)
            except:
                pass
            print(self.clients)

        if self.loggedIn:
            # XXX should we strip the preceding channel info here?
            parts = msg.rsplit()
            privmsg = ""
            sender = parts[0]
            sender = sender[1:sender.find("!")]

            if parts[1] == "PRIVMSG":
                privmsg = ' '.join(parts[2:])

                if self.swift:
                    try:
                        self.swift.put("{0} {1}".format(sender, privmsg))
                    except Exception as e:
                        # swift is broken, hangups probably crashed
                        print("Could not write to Swift. Hangouts has likely crashed.", e)
                        self.swift = None

                Bank.operands(msg, privmsg, sender if self.private else self.channel,
                              self.clients, sender, self.donald)

            if parts[1] == "JOIN":
                new = parts[0]
                n_user = new[1:new.find("!")].lower()
                if n_user.isalpha() and n_user != self.nick:
                    self.clients.append(n_user)
                    print("Added client %s (JOIN)" % n_user)

            if parts[1] == ("PART" or "QUIT"):
                old = parts[0]
                o_user = old[1:old.find("!")].lower()
                if o_user.isalpha() and o_user in self.clients and o_user != self.nick:
                    self.clients.remove(o_user)
                    print("Removed client %s from channel list." % o_user)

            if parts[1] == "KICK":
                kicked_user = parts[3].lower()
                if kicked_user.isalpha() and kicked_user in self.clients and kicked_user != self.nick:
                    self.clients.remove(kicked_user)
                    print("Removed client %s from channel list. (KICKED)" % kicked_user)


text:
//This script causes an image to flash into view and then fade away. It does this by adjusting the alpha value of the image

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class FlashFade : MonoBehaviour
{
	[SerializeField] Image image;										//The image to flash
	[SerializeField] Color flashColor = new Color(1f, 0f, 0f, 0.1f);	//The color to flash the image (default is red)
	[SerializeField] float flashSpeed = 5f;								//How fast to flash the image

	void Reset ()
	{
		//Grab the needed reference
		image = GetComponent<Image> ();
	}

	//Called by the PlayerHealth script when the player takes damage
	public void Flash ()
	{
		//If the image is currently flashing, stop it
		StopCoroutine("Fade");
		//Set the image to the desired color (which causes it to appear)
		image.color = flashColor;
		//Start the Fade() coroutine
		StartCoroutine("Fade");
	}

	//This coroutine fades an image out over time
	IEnumerator Fade()
	{
		//While the alpha of the image is greater than .01f (very small, we use this value instead of
		//0 because it can take a very long time for a Lerp method to reach true 0)...
		while (image.color.a > 0.01f)
		{
			//...Reduce the alpha using a Lerp (short for linear interpolation)...
			image.color = Color.Lerp(image.color, Color.clear, flashSpeed * Time.deltaTime);
			//...and then wait a frame before looping
			yield return null;
		}
		//Set the alpha of the image to 0 in case there is still a small alpha value
		image.color = Color.clear;
	}
}


text:
<?php
namespace CrudGenerator\Tests\General\FileConflict\FileConflictManagerFactory;

use CrudGenerator\FileConflict\FileConflictManagerFactory;
use CrudGenerator\Tests\TestCase;

class GetInstanceTest extends TestCase
{
    public function testInstance()
    {
        $context = $this->createMock('CrudGenerator\Context\CliContext');

        $this->assertInstanceOf(
            'CrudGenerator\FileConflict\FileConflictManager',
            FileConflictManagerFactory::getInstance($context)
        );
    }
}


text:
from evernote.api.client import EvernoteClient

# Define access token either:
# Developer Tokens (https://dev.evernote.com/doc/articles/dev_tokens.php)
# or OAuth (https://dev.evernote.com/doc/articles/authentication.php)
access_token = "insert dev or oauth token here"

# Setup the client
client = EvernoteClient(token = access_token, sandbox = True)

# Get note store object
note_store = client.get_note_store()

# Get a list of personal notebooks
notebooks = note_store.listNotebooks()

# Get a notebook object
# If you already have on in your code you can start here
notebook = notebooks[0]

# Make updates to the notebook object
notebook.name = "this is a new name for the notebook"
notebook.stack = "this is a test stack"

#Returns the usn (update service number) of the update
usn = note_store.updateNotebook(notebook)

print "The notebook with the name '%s' has been updated (USN %s)." % (notebook.name, usn)


text:
package com.yourtion.Pattern11;

import com.yourtion.Pattern11.ex1.FavoritesService;
import com.yourtion.Pattern11.ex1.MovieDao;

/**
 * Created by Yourtion on 30/03/2017.
 */
public class MovieService {

    private MovieDao movieDao;
    private FavoritesService favoritesService;
    public MovieService(MovieDao movieDao, FavoritesService favoritesService){
        this.movieDao = movieDao;
        this.favoritesService = favoritesService;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Agaricus heterogeneus Britzelm.

### Remarks
null


text:
package org.apache.directory.api.ldap.trigger;

import antlr.TokenStream;

/**
 * A reusable lexer class extended from antlr generated parser for an LDAP
 * Trigger Specification as defined at
 * The ABNF grammar for LDAP Triggers.
 *
 *
This class enables the reuse of the antlr lexer without having to recreate
 * the it every time as stated in
 * an ANTLR Interest Group mail .
 *
 * @author Apache Directory Project
 */
class ReusableAntlrTriggerSpecificationParser extends AntlrTriggerSpecificationParser
{
    /**
     * Creates a ReusableAntlrTriggerSpecificationParser instance.
     */
    public ReusableAntlrTriggerSpecificationParser( TokenStream lexer )
    {
        super( lexer );
    }

    /**
     * Resets the state of an antlr parser.
     */
    public void resetState()
    {
        // no set method for this protected field.
        this.traceDepth = 0;

        this.getInputState().reset();
    }
}


text:
/* -*- mode: c; tab-width: 4; c-basic-offset: 3; c-file-style: "linux" -*- */
//
// Copyright (c) 2009, Wei Mingzhi <whistler_wmz@users.sf.net>.
// All rights reserved.
//
// This file is part of SDLPAL.
//
// SDLPAL is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

#ifndef RNGPLAY_H
#define RNGPLAY_H

#ifdef __cplusplus
extern "C"
{
#endif

#include "_common.h"

VOID
PAL_RNGPlay(
   INT           iNumRNG,
   INT           iStartFrame,
   INT           iNumFrames,
   INT           iSpeed
);

#ifdef __cplusplus
}
#endif

#endif


text:
<title>FFTW Execution in Fortran - FFTW 3.3.4</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="FFTW 3.3.4">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Calling-FFTW-from-Legacy-Fortran.html#Calling-FFTW-from-Legacy-Fortran" title="Calling FFTW from Legacy Fortran">
<link rel="prev" href="FFTW-Constants-in-Fortran.html#FFTW-Constants-in-Fortran" title="FFTW Constants in Fortran">
<link rel="next" href="Fortran-Examples.html#Fortran-Examples" title="Fortran Examples">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: Fortran Examples,
Previous: FFTW Constants in Fortran,
Up: Calling FFTW from Legacy Fortran

8.3 FFTW Execution in Fortran

In C, in order to use a plan, one normally calls fftw_execute,
which executes the plan to perform the transform on the input/output
arrays passed when the plan was created (see Using Plans).  The
corresponding subroutine call in legacy Fortran is:

             call dfftw_execute(plan)

However, we have had reports that this causes problems with some
recent optimizing Fortran compilers.  The problem is, because the
input/output arrays are not passed as explicit arguments to
dfftw_execute, the semantics of Fortran (unlike C) allow the
compiler to assume that the input/output arrays are not changed by
dfftw_execute.  As a consequence, certain compilers end up
optimizing out or repositioning the call to dfftw_execute,
assuming incorrectly that it does nothing.

There are various workarounds to this, but the safest and simplest
thing is to not use dfftw_execute in Fortran.  Instead, use the
functions described in New-array Execute Functions, which take
the input/output arrays as explicit arguments.  For example, if the
plan is for a complex-data DFT and was created for the arrays
in and out, you would do:

             call dfftw_execute_dft(plan, in, out)

There are a few things to be careful of, however:

You must use the correct type of execute function, matching the way
the plan was created.  Complex DFT plans should use
dfftw_execute_dft, Real-input (r2c) DFT plans should use use
dfftw_execute_dft_r2c, and real-output (c2r) DFT plans should
use dfftw_execute_dft_c2r.  The various r2r plans should use
dfftw_execute_r2r.

You should normally pass the same input/output arrays that were used when
creating the plan.  This is always safe.

If you pass different input/output arrays compared to
those used when creating the plan, you must abide by all the
restrictions of the new-array execute functions (see New-array Execute Functions).  The most difficult of these, in Fortran, is the
requirement that the new arrays have the same alignment as the
original arrays, because there seems to be no way in legacy Fortran to obtain
guaranteed-aligned arrays (analogous to fftw_malloc in C).  You
can, of course, use the FFTW_UNALIGNED flag when creating the
plan, in which case the plan does not depend on the alignment, but
this may sacrifice substantial performance on architectures (like x86)
with SIMD instructions (see SIMD alignment and fftw_malloc).


text:
layout: post
title: Where To?
author: steve_jarvis
excerpt: "An extension to see where Safari links lead."
tags: [safari, url, hover, mouse, link]
comments: true
---

Safari seems to be the only modern browser that doesn't display the destination
of links when hovering with the cursor (by default). "Where To?" is an extension
that adds that functionality in a very simple manner.

After page load, Where To? processes all the links and displays their
href destinations in a small status bar as they're moused over.

Where To? adds a subtle yellow status box in the bottom left of
    the window.

It's available on [GitHub](https://github.com/stevejarvis/whereto), just
[download](https://github.com/stevejarvis/whereto/blob/master/bld/whereto.safariextz?raw=true)
and double-click to install.

Even before I started I figured this feature must be available somehow; it's too
widely used and available almost everywhere else. But I decided it'd be more fun
to learn how to write a Safari extension than search for other solutions.
Afterwards, I realized that this feature is, in fact, already available in
Safari, it's just disabled by default (see View -> Show Status Bar). Where To?
still has its merits, though, like taking minimal browser real estate and
displaying action hrefs in addition to full URLs.

So that's that, it's a simple extension to add a feature I was wishing for.


text:
unsigned int counter = 60; //Counter for 3 seconds delay
// Freq = 1MHZ, therefore T = 1/freq = 1us
// To count 1 second, need to multiply 1us by 1000000(10 ^6), but the
// counter(CCR0) is just 16 bits wide, so the maximum that it can count is 2^16
// therfore dividing 10^6 with 2^16(1000000/65535) yields ~15 which means if the
// CCR0 counter has to overflow about 20 times to generate a delay of 1 second.
// Therefore to generate a delay of 3 seconds, the counter needs to be set to 60

unsigned int timer = 0;
void setup_delay();
void caliberate_clock(void);

int main(void)
{
	// Stop Watchdog timer
	WDTCTL = WDTPW + WDTHOLD;

	// Configure CPU clock
	caliberate_clock();

	setup_delay();

	// greeen LED, set as output port
	// green LED is located at port 1.6
	P1DIR |= BIT6;

	// Enter LPM0 w/ interrupt
	_BIS_SR(LPM0_bits + GIE);
}

void caliberate_clock(void)
{
	// If calibration constant erased
	if (CALBC1_1MHZ==0xFF)
	{
		// do not load, trap CPU
		while(1);
	}
}

void setup_delay()
{
	// Select lowest DCOx and MODx settings
	DCOCTL = 0;
	// Set DCO
	BCSCTL1 = CALBC1_1MHZ;
	DCOCTL = CALDCO_1MHZ;

	// Configure Timer_A to generate interrupt, when overflow occurs
	// CCR0 interrupt enabled
	CCTL0 = CCIE;
	CCR0 = 65535;

	// Count from 1 to CCR0, SMCLK, up mode
	TACTL = TASSEL_2 + MC_1;
}

// Use interrupt routine, to keep changing the led status
#pragma vector=TIMER0_A0_VECTOR
__interrupt void Timer_A (void)
{
	// Re initialize CCR0 for the next interrupt
	CCR0 += 65535;

	// Increase timer1 value
	timer++;

	if (timer >= counter) {
		// Blink green LED(LED2)
		P1OUT ^= BIT6;
		timer = 0;
	}
}


text:
using Bifrost.Configuration;
using Microsoft.ServiceBus.Messaging;

namespace TenantCoordinator
{
    public class EventProcessorFactory : IEventProcessorFactory
    {
        public IEventProcessor CreateEventProcessor(PartitionContext context)
        {
            var processor = Configure.Instance.Container.Get<EventProcessor>();
            return processor;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
  xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="brews" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>java:jboss/datasources/BrewsDS</jta-data-source>
    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
      <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy" />
    </properties>
  </persistence-unit>
</persistence>


text:
import unittest
from lelei import parser as sp

class TestStructureAutoSizing(unittest.TestCase):

    def test_bitsAreCalculatedCorrectly(self):
        self.assertEqual(sp.bitsForStructure("uint8",  3),  3)
        self.assertEqual(sp.bitsForStructure("uint8",  8),  8)

    def test_uint(self):
        for i in range(1, 32):
            self.assertEqual(sp.bitsForStructure("uint%d"%i, 0), i)
        self.assertEqual(sp.bitsForStructure("uint40", 0), 40)
        self.assertEqual(sp.bitsForStructure("uint48", 0), 48)
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("uint64", 0))

    def test_int(self):
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("int1", 0))
        for i in range(2, 32):
            self.assertEqual(sp.bitsForStructure("int%d"%i, 0), i)
        self.assertEqual(sp.bitsForStructure("int40", 0), 40)
        self.assertEqual(sp.bitsForStructure("int48", 0), 48)

    def test_oversizedTypes(self):
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("uint8", 13))
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("uint16", 17))
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("uint32", 33))
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("uint64", 65))

    def test_negativesizedTypes(self):
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("uint8", -1))
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("uint16", -1))
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("uint32", -1))
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("uint64", -1))

    def test_fieldTypeIsNotDefined(self):
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("float", 0))
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("int", 0))
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("uint", 0))
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("uint128", 0))
        #### this is a possible value! ###
        #self.assertRaises(ValueError, lambda : sp.bitsForStructure("uint3", 0))

class TestFloatSizing(unittest.TestCase):

    def test_floatXX_AutoSizing(self):
        self.assertEqual(sp.bitsForStructure("float32", 0), 32)
        self.assertEqual(sp.bitsForStructure("float32", 0), 32)

    def test_floatXX_sizing(self):
        self.assertEqual(sp.bitsForStructure("float32", 32), 32)
        self.assertEqual(sp.bitsForStructure("float64", 64), 64)

    def test_floatXX_incorrectSizing(self):
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("float32", -1))
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("float32", 16))
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("float32", 33))
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("float64", -1))
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("float64", 33))
        self.assertRaises(ValueError, lambda : sp.bitsForStructure("float64", 65))


text:
'''
This script
- reads the TIOBE index from a local file or via Internet
- writes a markdown table for languages and,
- draws a parete chart by R

usage (to parse a local HTML file)
$ python3 language_ratings.py html-filename table-filename png-filename
- html-filename (input) : a local HTML file
- table-filename (output) : a markdown table file that contains the TIOBE
  index rating for selected languages
- png-filename (output) : a parete chart for the table

usage (to read TIOBE official website)
$ python3 language_ratings.py web table-filename png-filename

Copyright (C) 2017 Zettsu Tatsuya
'''

import subprocess
import sys
from collections import OrderedDict
import requests
from bs4 import BeautifulSoup

# Programming languages to extract TIOBE index ratings
LANGUAGE_SET = ['Ruby', 'JavaScript', 'Java', 'C#', 'Visual Basic .NET',
                'Perl', 'Python', 'Groovy', 'Scala', "R", 'Bash',
                'C++', 'C', 'Assembly language', 'Haskell',
                'Elixir', 'Erlang',
                'PHP', 'Clojure', 'Scheme', 'OCaml', 'F#',
                'Rust', 'Makefile', 'Kuin']

# If a HTML filename is same as the special keyword,
# this script downloads from the URL instead of reading a local file.
REMOTE_KEYWORD = 'web'
REMOTE_URL = 'https://www.tiobe.com/tiobe-index/'

# Usage
USAGE_TEXT = 'usage : python3 language_ratings.py ' \
             '(html-filename|web) table-filename png-filename'

# Launched R script name without directories
RSCRIPT_BASENAME = 'language_ratings.R'

# Headers of tables
CSV_HEADER = 'TIOBE index rank,Programming Language,Ratings[%]\n'
MARKDOWN_HEADER = '|TIOBE index rank|Programming Language' \
                  '|Ratings[%]|Cumulative Ratings[%]|\n' \
                  '|:--|:------|:------|:------|\n'

# Exit status for make
EXIT_STATUS_SUCCESS = 0
EXIT_STATUS_ERROR = 1

class ErrorInR(Exception):
    '''Tells a runtime error which occurred in R'''
    pass

class LanguageRatings():
    '''Makes a table for a subset of languages from the TIOBE index'''

    def __init__(self, command_line_arguments):
        self.html_path = command_line_arguments[1]
        self.table_filename = command_line_arguments[2]
        self.png_filename = command_line_arguments[3]

    def generate(self):
        '''Generates a chart and a markdown table file from a HTML document'''

        soup = self.fetch(self.html_path)
        partial_table, full_table = self.make_table(self.parse_file(soup))

        rscript_name = RSCRIPT_BASENAME
        self.make_chart(partial_table, self.table_filename,
                        self.png_filename, rscript_name)
        with open(self.table_filename, 'w') as file:
            file.write(full_table)

        return EXIT_STATUS_SUCCESS

    @staticmethod
    def fetch(html_path):
        '''Downloads or loads a HTML document'''

        if html_path == REMOTE_KEYWORD:
            # Set environment variables HTTP_PROXY and HTTPS_PROXY
            # to use HTTP proxies.
            # To avoid 'certificate verify failed', set verify=False
            html_response = requests.get(REMOTE_URL, verify=False)
            html_text = html_response.text
        else:
            html_text = open(html_path)

        return BeautifulSoup(html_text, 'html.parser')

    @staticmethod
    def get_unique_name(name):
        '''Returns a unique name for a language'''

        return name.replace(' ', '').lower()

    def parse_file(self, soup):
        '''Parses a HTML document that contains a TIOBE index table'''

        languages = []

        # Parses HTML table tags
        for tr_tag in soup.find_all('tr'):
            td_tags = tr_tag.find_all('td')
            columns = []

            # Popular languages
            if len(td_tags) == 6:
                columns = [0, 3, 4]
            elif len(td_tags) == 3:
                columns = [0, 1, 2]
            else:
                continue

            try:
                rank = int(td_tags[columns[0]].string)
                language = td_tags[columns[1]].string.strip()
                ratings = float(td_tags[columns[2]].string.replace('%', ''))
                name = self.get_unique_name(language)
                languages.append([name, rank, language, ratings])
            except ValueError:
                pass

        return languages

    def make_table(self, languages):
        '''Makes a markdown table'''

        partial_table = CSV_HEADER
        full_table = MARKDOWN_HEADER
        cumulative_ratings = 0.000

        # Keep an order for languages not ranked
        language_map = OrderedDict()
        for language in LANGUAGE_SET:
            name = self.get_unique_name(language)
            language_map[name] = language

        for name, rank, language, ratings in languages:
            if name in language_map:
                cumulative_ratings += ratings
                partial_table += '{0},{1},{2:f}\n'. \
                                 format(rank, language, ratings)
                full_table += '|{0}|{1}|{2:5.3f}|{3:5.3f}|\n'.format(
                    rank, language, ratings, cumulative_ratings)
                language_map[name] = ''

        for _, language in language_map.items():
            if language:
                full_table += '|-|{0:s}|||\n'.format(language)

        return partial_table, full_table

    @staticmethod
    def make_chart(partial_table, table_filename, png_filename, rscript_name):
        '''Makes a parete chat by R'''

        # Creates a CSV file of which name is table_filename
        # If it succeeded, overwrite the file later.
        # If it failed, the CSV file remains and can be checekd in debugging.
        with open(table_filename, 'w') as file:
            file.write(partial_table)

        arguments = ['Rscript', rscript_name, '--args',
                     table_filename, png_filename]
        result = subprocess.run(arguments)

        if result.returncode:
            raise ErrorInR

        return None

if __name__ == "__main__":
    if len(sys.argv) < 4:
        print(USAGE_TEXT)
        sys.exit(EXIT_STATUS_ERROR)

    sys.exit(LanguageRatings(sys.argv).generate())


text:
#include <vector>
using std::vector;
#include <pack_stl.h>
#include <netcomplexity.h>

class array2
{
  CLASSDESC_ACCESS(array2);
  int rows, cols;
  array<double> val;
public:
  array2(int r=1, int c=0): rows(r), cols(c), val(r*c) {}
  array2& operator=(double& x) {val=x; return *this;}
  double& operator() (int i, int j) {return val[i+j*rows];}

  /* conversions to/from sparse_mats */
  array2(sparse_mat& x): rows(x.rowsz), cols(x.colsz), val(x.rowsz*x.colsz)
  {
    val=0;
    for (size_t i=0; i<x.val.size(); i++) (*this)(x.row[i],x.col[i])=x.val[i];
  }
  operator sparse_mat()
  {
    sparse_mat r;
    for (int i=0; i<rows; i++)
      for (int j=0; j<cols; j++)
	if ((*this)(i,j)!=0)
	  {
	    r.val<<=(*this)(i,j);
	    r.row<<=i;
	    r.col<<=j;
	  }
    return r;
  }

};

class webworld_t: public TCL_obj_t
{
  CLASSDESC_ACCESS(webworld_t);
  /* utility members for generate */
  array<double> sumaSfN(array2& a, sparse_mat& f);
  void compute_g(sparse_mat& g);

  /* utility for mutate */
  bool genotype_exists(const array<int>& g);
public:
  int K; /* poolsize of attributes */
  int L;  /* number of attributes of a species */
  array2 M; /* matrix of payoffs between one feature and another */
  vector<array<int> > genotype;
  sparse_mat S, f, g; /* interaction matrix */
  void initM(TCL_args);
  void init_interaction(TCL_args);

  gaussrand grand; /* random generator used for generating M */
  urand unirand;  /* used for mutate algorithm */

  double t;     /* time */
  array<double> N;   /* population counts */
  array<int> species; /* tags */
  array<double> create;   /* creation time */
  double lambda;  /* ecological efficiency */
  double  b, c;
  double R; /* Resource productivity */
  double fmin; /* minimum effort */

  /* set some default parameters */
  webworld_t(): K(500), L(10), t(0), lambda(0.1), b(5E-3), c(0.5), R(10E5),
		fmin(1E-6) {}

  void generate(TCL_args);
  double dissipation();

  int condense();
  void mutate();

  array<double> lifetimes();
  double conn();
  sparse_mat_graph foodweb;

  double complexity()
  {
    return ::complexity(foodweb);
  }
};


text:
package logic.elements;

import core.Game;
import processing.core.PImage;
import util.FileUtils;

public class Tile {
	String name;
	PImage tileTexture;
	int type;

	public Tile(String _name, String path, int _type){
		name = _name;
		tileTexture = FileUtils.readExternalPImage(path);
		type = _type;
	}

	public void render(int layer, int x, int y){
		Game.getInstance().getLayer(layer).image(tileTexture, x, y);
	}
}


text:
const path = require('path');
const ghpages = require('gh-pages');

const basePath = path.join(__dirname, './docs');
const repoUrl = require('./package.json').repository.url;

const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
const tokenRegex = GITHUB_TOKEN ? new RegExp(GITHUB_TOKEN, 'g') : null;

const log = function (message) {
  // eslint-disable-next-line no-console
  console.log(
    tokenRegex ? message.replace(tokenRegex, '[GITHUB_TOKEN]') : message,
  );
};

const makeConfig = function () {
  return {
    repo: GITHUB_TOKEN
      ? repoUrl.replace('https://', `https://${GITHUB_TOKEN}@`)
      : repoUrl,
    logger: log,
    dotfiles: true,
  };
};

ghpages.publish(basePath, makeConfig(), function (err) {
  if (err) {
    log('Deployment error');
    log(JSON.stringify(err));
    // eslint-disable-next-line no-process-exit
    process.exit(1);
  } else {
    log('Deployment complete!');
  }
});


text:
var requestCache = new Array();

/*
 * Ajax requests function
 * performs post and get asynchronous requests
 *
 * Arguments
 * method - (string) The method can be either post or get
 * url - (string) The requested url
 * data - (string) The datas of the request in the form 'var1=value1&var2=value2'
 * target - (mixed) The element DOM Object or the element id of the DOM element that have to be updated with the request response
 *
 * Options (object)
 * cache - (bool default to false) Whether to cache the request result or not
 * cacheTime - (int default 3600000 [1hr]) The time in milliseconds to keep the request in cache
 * load - (mixed default null) The element DOM Object or the element id of the DOM element to use to show the loading image
 * script - (bool default false) True if scripts have to be executed, false if not
 * setvalue - (bool default false) True if script response must be set as the target value
 * callback - (function dafault null) The function to call after the request has been executed
 * callback_params - (string default null) The params passed to the callback function
 *
 * if the called method has to return an error, must return a string like:
 * request error:Error description
 * this way the method is not executed and an alert is displayed with the message "Error description"
 *
 */
function ajaxRequest(method, url, data, target, options) {
	var opt = {
		cache: false,
		cacheTime: 3600000,
		load: null,
		script: false,
		setvalue: false,
		callback: null,
		callback_params: null
	};
	Object.append(opt, options);
	var loading = new Element('div', {'class': 'loading'});
	target = typeof target == 'element'
		? target
		: typeof $(target) != undefined
			? $(target)
			: null;
	if(opt.cache && typeof requestCache[url+data] != undefined && (Date.now - requestCache[url+data][0] < opt.cacheTime)) {
		if(opt.setvalue) target.value = requestCache[url+data][1];
		else target.set('html', requestCache[url+data][1]);
		return true;
	}

	var opt_load = opt.load != null ? (typeof opt.load == 'element' ? opt.load : $(opt.load)) : null;
	var request = new Request.HTML({
		evalScripts: opt.script,
		url: url,
		method:	method,
		data: data,
		onRequest: function() {
			if(opt_load) loading.inject(opt_load);
		},
		onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
			if(opt_load) opt_load.set('html', '');
			rexp = /request error:(.*)/;
			var err_match = rexp.exec(responseHTML);
			if(err_match) alert(err_match[1]);
			else {
				if(opt.setvalue && target) target.setProperty('value',responseHTML);
				else if(target) target.set('html', responseHTML);
				if(opt.cache) requestCache[url+data] = new Array(Date.now, responseHTML);
				if(opt.callback && opt.callback_params) opt.callback(opt.callback_params);
				else if(opt.callback != null) opt.callback();
			}
		}
	}).send();

}


text:
/*
============================================================================
  The Ohio State University Research Foundation, The University of Chicago -
  Argonne National Laboratory, Emory University, SemanticBits LLC,
  and Ekagra Software Technologies Ltd.

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/cagrid-portal/LICENSE.txt for details.
============================================================================
*/
alter table BookmarksEntry add priority int;

alter table Layout add description lvarchar;
alter table Layout add dlFolderId int8;

alter table Organization_ add location boolean;

update Organization_ set location = 'F';


text:
class RemoveContraFromAuthors < ActiveRecord::Migration
  def change
    remove_reference :authors, :contra, index: true, foreign_key: true
  end
end


text:
/* This file was generated by upbc (the upb compiler) from the input
 * file:
 *
 *     src/proto/grpc/gcp/transport_security_common.proto
 *
 * Do not edit -- your changes will be discarded when the file is
 * regenerated. */

#ifndef SRC_PROTO_GRPC_GCP_TRANSPORT_SECURITY_COMMON_PROTO_UPB_H_
#define SRC_PROTO_GRPC_GCP_TRANSPORT_SECURITY_COMMON_PROTO_UPB_H_

#include "upb/msg_internal.h"
#include "upb/decode.h"
#include "upb/decode_fast.h"
#include "upb/encode.h"

#include "upb/port_def.inc"

#ifdef __cplusplus
extern "C" {
#endif

struct grpc_gcp_RpcProtocolVersions;
struct grpc_gcp_RpcProtocolVersions_Version;
typedef struct grpc_gcp_RpcProtocolVersions grpc_gcp_RpcProtocolVersions;
typedef struct grpc_gcp_RpcProtocolVersions_Version grpc_gcp_RpcProtocolVersions_Version;
extern const upb_MiniTable grpc_gcp_RpcProtocolVersions_msginit;
extern const upb_MiniTable grpc_gcp_RpcProtocolVersions_Version_msginit;

typedef enum {
  grpc_gcp_SECURITY_NONE = 0,
  grpc_gcp_INTEGRITY_ONLY = 1,
  grpc_gcp_INTEGRITY_AND_PRIVACY = 2
} grpc_gcp_SecurityLevel;

/* grpc.gcp.RpcProtocolVersions */

UPB_INLINE grpc_gcp_RpcProtocolVersions* grpc_gcp_RpcProtocolVersions_new(upb_Arena* arena) {
  return (grpc_gcp_RpcProtocolVersions*)_upb_Message_New(&grpc_gcp_RpcProtocolVersions_msginit, arena);
}
UPB_INLINE grpc_gcp_RpcProtocolVersions* grpc_gcp_RpcProtocolVersions_parse(const char* buf, size_t size, upb_Arena* arena) {
  grpc_gcp_RpcProtocolVersions* ret = grpc_gcp_RpcProtocolVersions_new(arena);
  if (!ret) return NULL;
  if (upb_Decode(buf, size, ret, &grpc_gcp_RpcProtocolVersions_msginit, NULL, 0, arena) != kUpb_DecodeStatus_Ok) {
    return NULL;
  }
  return ret;
}
UPB_INLINE grpc_gcp_RpcProtocolVersions* grpc_gcp_RpcProtocolVersions_parse_ex(const char* buf, size_t size,
                           const upb_ExtensionRegistry* extreg,
                           int options, upb_Arena* arena) {
  grpc_gcp_RpcProtocolVersions* ret = grpc_gcp_RpcProtocolVersions_new(arena);
  if (!ret) return NULL;
  if (upb_Decode(buf, size, ret, &grpc_gcp_RpcProtocolVersions_msginit, extreg, options, arena) !=
      kUpb_DecodeStatus_Ok) {
    return NULL;
  }
  return ret;
}
UPB_INLINE char* grpc_gcp_RpcProtocolVersions_serialize(const grpc_gcp_RpcProtocolVersions* msg, upb_Arena* arena, size_t* len) {
  char* ptr;
  (void)upb_Encode(msg, &grpc_gcp_RpcProtocolVersions_msginit, 0, arena, &ptr, len);
  return ptr;
}
UPB_INLINE char* grpc_gcp_RpcProtocolVersions_serialize_ex(const grpc_gcp_RpcProtocolVersions* msg, int options,
                                 upb_Arena* arena, size_t* len) {
  char* ptr;
  (void)upb_Encode(msg, &grpc_gcp_RpcProtocolVersions_msginit, options, arena, &ptr, len);
  return ptr;
}
UPB_INLINE bool grpc_gcp_RpcProtocolVersions_has_max_rpc_version(const grpc_gcp_RpcProtocolVersions* msg) {
  return _upb_hasbit(msg, 1);
}
UPB_INLINE void grpc_gcp_RpcProtocolVersions_clear_max_rpc_version(const grpc_gcp_RpcProtocolVersions* msg) {
  *UPB_PTR_AT(msg, UPB_SIZE(4, 8), const upb_Message*) = NULL;
}
UPB_INLINE const grpc_gcp_RpcProtocolVersions_Version* grpc_gcp_RpcProtocolVersions_max_rpc_version(const grpc_gcp_RpcProtocolVersions* msg) {
  return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), const grpc_gcp_RpcProtocolVersions_Version*);
}
UPB_INLINE bool grpc_gcp_RpcProtocolVersions_has_min_rpc_version(const grpc_gcp_RpcProtocolVersions* msg) {
  return _upb_hasbit(msg, 2);
}
UPB_INLINE void grpc_gcp_RpcProtocolVersions_clear_min_rpc_version(const grpc_gcp_RpcProtocolVersions* msg) {
  *UPB_PTR_AT(msg, UPB_SIZE(8, 16), const upb_Message*) = NULL;
}
UPB_INLINE const grpc_gcp_RpcProtocolVersions_Version* grpc_gcp_RpcProtocolVersions_min_rpc_version(const grpc_gcp_RpcProtocolVersions* msg) {
  return *UPB_PTR_AT(msg, UPB_SIZE(8, 16), const grpc_gcp_RpcProtocolVersions_Version*);
}

UPB_INLINE void grpc_gcp_RpcProtocolVersions_set_max_rpc_version(grpc_gcp_RpcProtocolVersions *msg, grpc_gcp_RpcProtocolVersions_Version* value) {
  _upb_sethas(msg, 1);
  *UPB_PTR_AT(msg, UPB_SIZE(4, 8), grpc_gcp_RpcProtocolVersions_Version*) = value;
}
UPB_INLINE struct grpc_gcp_RpcProtocolVersions_Version* grpc_gcp_RpcProtocolVersions_mutable_max_rpc_version(grpc_gcp_RpcProtocolVersions* msg, upb_Arena* arena) {
  struct grpc_gcp_RpcProtocolVersions_Version* sub = (struct grpc_gcp_RpcProtocolVersions_Version*)grpc_gcp_RpcProtocolVersions_max_rpc_version(msg);
  if (sub == NULL) {
    sub = (struct grpc_gcp_RpcProtocolVersions_Version*)_upb_Message_New(&grpc_gcp_RpcProtocolVersions_Version_msginit, arena);
    if (!sub) return NULL;
    grpc_gcp_RpcProtocolVersions_set_max_rpc_version(msg, sub);
  }
  return sub;
}
UPB_INLINE void grpc_gcp_RpcProtocolVersions_set_min_rpc_version(grpc_gcp_RpcProtocolVersions *msg, grpc_gcp_RpcProtocolVersions_Version* value) {
  _upb_sethas(msg, 2);
  *UPB_PTR_AT(msg, UPB_SIZE(8, 16), grpc_gcp_RpcProtocolVersions_Version*) = value;
}
UPB_INLINE struct grpc_gcp_RpcProtocolVersions_Version* grpc_gcp_RpcProtocolVersions_mutable_min_rpc_version(grpc_gcp_RpcProtocolVersions* msg, upb_Arena* arena) {
  struct grpc_gcp_RpcProtocolVersions_Version* sub = (struct grpc_gcp_RpcProtocolVersions_Version*)grpc_gcp_RpcProtocolVersions_min_rpc_version(msg);
  if (sub == NULL) {
    sub = (struct grpc_gcp_RpcProtocolVersions_Version*)_upb_Message_New(&grpc_gcp_RpcProtocolVersions_Version_msginit, arena);
    if (!sub) return NULL;
    grpc_gcp_RpcProtocolVersions_set_min_rpc_version(msg, sub);
  }
  return sub;
}

/* grpc.gcp.RpcProtocolVersions.Version */

UPB_INLINE grpc_gcp_RpcProtocolVersions_Version* grpc_gcp_RpcProtocolVersions_Version_new(upb_Arena* arena) {
  return (grpc_gcp_RpcProtocolVersions_Version*)_upb_Message_New(&grpc_gcp_RpcProtocolVersions_Version_msginit, arena);
}
UPB_INLINE grpc_gcp_RpcProtocolVersions_Version* grpc_gcp_RpcProtocolVersions_Version_parse(const char* buf, size_t size, upb_Arena* arena) {
  grpc_gcp_RpcProtocolVersions_Version* ret = grpc_gcp_RpcProtocolVersions_Version_new(arena);
  if (!ret) return NULL;
  if (upb_Decode(buf, size, ret, &grpc_gcp_RpcProtocolVersions_Version_msginit, NULL, 0, arena) != kUpb_DecodeStatus_Ok) {
    return NULL;
  }
  return ret;
}
UPB_INLINE grpc_gcp_RpcProtocolVersions_Version* grpc_gcp_RpcProtocolVersions_Version_parse_ex(const char* buf, size_t size,
                           const upb_ExtensionRegistry* extreg,
                           int options, upb_Arena* arena) {
  grpc_gcp_RpcProtocolVersions_Version* ret = grpc_gcp_RpcProtocolVersions_Version_new(arena);
  if (!ret) return NULL;
  if (upb_Decode(buf, size, ret, &grpc_gcp_RpcProtocolVersions_Version_msginit, extreg, options, arena) !=
      kUpb_DecodeStatus_Ok) {
    return NULL;
  }
  return ret;
}
UPB_INLINE char* grpc_gcp_RpcProtocolVersions_Version_serialize(const grpc_gcp_RpcProtocolVersions_Version* msg, upb_Arena* arena, size_t* len) {
  char* ptr;
  (void)upb_Encode(msg, &grpc_gcp_RpcProtocolVersions_Version_msginit, 0, arena, &ptr, len);
  return ptr;
}
UPB_INLINE char* grpc_gcp_RpcProtocolVersions_Version_serialize_ex(const grpc_gcp_RpcProtocolVersions_Version* msg, int options,
                                 upb_Arena* arena, size_t* len) {
  char* ptr;
  (void)upb_Encode(msg, &grpc_gcp_RpcProtocolVersions_Version_msginit, options, arena, &ptr, len);
  return ptr;
}
UPB_INLINE void grpc_gcp_RpcProtocolVersions_Version_clear_major(const grpc_gcp_RpcProtocolVersions_Version* msg) {
  *UPB_PTR_AT(msg, UPB_SIZE(0, 0), uint32_t) = 0;
}
UPB_INLINE uint32_t grpc_gcp_RpcProtocolVersions_Version_major(const grpc_gcp_RpcProtocolVersions_Version* msg) {
  return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), uint32_t);
}
UPB_INLINE void grpc_gcp_RpcProtocolVersions_Version_clear_minor(const grpc_gcp_RpcProtocolVersions_Version* msg) {
  *UPB_PTR_AT(msg, UPB_SIZE(4, 4), uint32_t) = 0;
}
UPB_INLINE uint32_t grpc_gcp_RpcProtocolVersions_Version_minor(const grpc_gcp_RpcProtocolVersions_Version* msg) {
  return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), uint32_t);
}

UPB_INLINE void grpc_gcp_RpcProtocolVersions_Version_set_major(grpc_gcp_RpcProtocolVersions_Version *msg, uint32_t value) {
  *UPB_PTR_AT(msg, UPB_SIZE(0, 0), uint32_t) = value;
}
UPB_INLINE void grpc_gcp_RpcProtocolVersions_Version_set_minor(grpc_gcp_RpcProtocolVersions_Version *msg, uint32_t value) {
  *UPB_PTR_AT(msg, UPB_SIZE(4, 4), uint32_t) = value;
}

extern const upb_MiniTable_File src_proto_grpc_gcp_transport_security_common_proto_upb_file_layout;

#ifdef __cplusplus
}  /* extern "C" */
#endif

#include "upb/port_undef.inc"

#endif  /* SRC_PROTO_GRPC_GCP_TRANSPORT_SECURITY_COMMON_PROTO_UPB_H_ */


text:
package org.aying.echarts.feature;

import org.jetbrains.annotations.Contract;

import java.util.Objects;

/**
 * 配置项还原。
 *
 * @author Fuchun
 * @since 1.0
 */
public class Restore extends BaseFeature<Restore> {

    private static final long serialVersionUID = 563223472150722285L;

    public Restore() {
        super();
    }

    @Contract("null -> fail")
    public Restore title(String title) {
        Objects.requireNonNull(title, "title");
        return super.title(title);
    }

    @Override
    public String toString() {
        return "Restore{} " + super.toString();
    }
}


text:
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "tree.h"
#include "flags.h"
#include "rtl.h"
#include "tm_p.h"
#include "ggc.h"
#include "basic-block.h"
#include "cfgloop.h"
#include "output.h"
#include "expr.h"
#include "function.h"
#include "diagnostic.h"
#include "timevar.h"
#include "tree-dump.h"
#include "tree-flow.h"
#include "domwalk.h"
#include "real.h"
#include "tree-pass.h"
#include "tree-ssa-propagate.h"
#include "langhooks.h"
#include "params.h"

/* To avoid code explosion due to jump threading, we limit the
   number of statements we are going to copy.  This variable
   holds the number of statements currently seen that we'll have
   to copy as part of the jump threading process.  */
static int stmt_count;

/* Return TRUE if we may be able to thread an incoming edge into
   BB to an outgoing edge from BB.  Return FALSE otherwise.  */

bool
potentially_threadable_block (basic_block bb)
{
  block_stmt_iterator bsi;

  /* If BB has a single successor or a single predecessor, then
     there is no threading opportunity.  */
  if (single_succ_p (bb) || single_pred_p (bb))
    return false;

  /* If BB does not end with a conditional, switch or computed goto,
     then there is no threading opportunity.  */
  bsi = bsi_last (bb);
  if (bsi_end_p (bsi)
      || ! bsi_stmt (bsi)
      || (TREE_CODE (bsi_stmt (bsi)) != COND_EXPR
	  && TREE_CODE (bsi_stmt (bsi)) != GOTO_EXPR
	  && TREE_CODE (bsi_stmt (bsi)) != SWITCH_EXPR))
    return false;

  return true;
}

/* Return the LHS of any ASSERT_EXPR where OP appears as the first
   argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
   BB.  If no such ASSERT_EXPR is found, return OP.  */

static tree
lhs_of_dominating_assert (tree op, basic_block bb, tree stmt)
{
  imm_use_iterator imm_iter;
  tree use_stmt;
  use_operand_p use_p;

  FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
    {
      use_stmt = USE_STMT (use_p);
      if (use_stmt != stmt
          && TREE_CODE (use_stmt) == MODIFY_EXPR
          && TREE_CODE (TREE_OPERAND (use_stmt, 1)) == ASSERT_EXPR
          && TREE_OPERAND (TREE_OPERAND (use_stmt, 1), 0) == op
	  && dominated_by_p (CDI_DOMINATORS, bb, bb_for_stmt (use_stmt)))
	{
	  return TREE_OPERAND (use_stmt, 0);
	}
    }
  return op;
}

/* We record temporary equivalences created by PHI nodes or
   statements within the target block.  Doing so allows us to
   identify more jump threading opportunities, even in blocks
   with side effects.

   We keep track of those temporary equivalences in a stack
   structure so that we can unwind them when we're done processing
   a particular edge.  This routine handles unwinding the data
   structures.  */

static void
remove_temporary_equivalences (VEC(tree, heap) **stack)
{
  while (VEC_length (tree, *stack) > 0)
    {
      tree prev_value, dest;

      dest = VEC_pop (tree, *stack);

      /* A NULL value indicates we should stop unwinding, otherwise
	 pop off the next entry as they're recorded in pairs.  */
      if (dest == NULL)
	break;

      prev_value = VEC_pop (tree, *stack);
      SSA_NAME_VALUE (dest) = prev_value;
    }
}

/* Record a temporary equivalence, saving enough information so that
   we can restore the state of recorded equivalences when we're
   done processing the current edge.  */

static void
record_temporary_equivalence (tree x, tree y, VEC(tree, heap) **stack)
{
  tree prev_x = SSA_NAME_VALUE (x);

  if (TREE_CODE (y) == SSA_NAME)
    {
      tree tmp = SSA_NAME_VALUE (y);
      y = tmp ? tmp : y;
    }

  SSA_NAME_VALUE (x) = y;
  VEC_reserve (tree, heap, *stack, 2);
  VEC_quick_push (tree, *stack, prev_x);
  VEC_quick_push (tree, *stack, x);
}

/* Record temporary equivalences created by PHIs at the target of the
   edge E.  Record unwind information for the equivalences onto STACK.

   If a PHI which prevents threading is encountered, then return FALSE
   indicating we should not thread this edge, else return TRUE.  */

static bool
record_temporary_equivalences_from_phis (edge e, VEC(tree, heap) **stack)
{
  tree phi;

  /* Each PHI creates a temporary equivalence, record them.
     These are context sensitive equivalences and will be removed
     later.  */
  for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
    {
      tree src = PHI_ARG_DEF_FROM_EDGE (phi, e);
      tree dst = PHI_RESULT (phi);

      /* If the desired argument is not the same as this PHI's result
	 and it is set by a PHI in E->dest, then we can not thread
	 through E->dest.  */
      if (src != dst
	  && TREE_CODE (src) == SSA_NAME
	  && TREE_CODE (SSA_NAME_DEF_STMT (src)) == PHI_NODE
	  && bb_for_stmt (SSA_NAME_DEF_STMT (src)) == e->dest)
	return false;

      /* We consider any non-virtual PHI as a statement since it
	 count result in a constant assignment or copy operation.  */
      if (is_gimple_reg (dst))
	stmt_count++;

      record_temporary_equivalence (dst, src, stack);
    }
  return true;
}

/* Try to simplify each statement in E->dest, ultimately leading to
   a simplification of the COND_EXPR at the end of E->dest.

   Record unwind information for temporary equivalences onto STACK.

   Use SIMPLIFY (a pointer to a callback function) to further simplify
   statements using pass specific information.

   We might consider marking just those statements which ultimately
   feed the COND_EXPR.  It's not clear if the overhead of bookkeeping
   would be recovered by trying to simplify fewer statements.

   If we are able to simplify a statement into the form
   SSA_NAME = (SSA_NAME | gimple invariant), then we can record
   a context sensitive equivalency which may help us simplify
   later statements in E->dest.  */

static tree
record_temporary_equivalences_from_stmts_at_dest (edge e,
						  VEC(tree, heap) **stack,
						  tree (*simplify) (tree,
								    tree))
{
  block_stmt_iterator bsi;
  tree stmt = NULL;
  int max_stmt_count;

  max_stmt_count = PARAM_VALUE (PARAM_MAX_JUMP_THREAD_DUPLICATION_STMTS);

  /* Walk through each statement in the block recording equivalences
     we discover.  Note any equivalences we discover are context
     sensitive (ie, are dependent on traversing E) and must be unwound
     when we're finished processing E.  */
  for (bsi = bsi_start (e->dest); ! bsi_end_p (bsi); bsi_next (&bsi))
    {
      tree cached_lhs = NULL;

      stmt = bsi_stmt (bsi);

      /* Ignore empty statements and labels.  */
      if (IS_EMPTY_STMT (stmt) || TREE_CODE (stmt) == LABEL_EXPR)
	continue;

      /* If the statement has volatile operands, then we assume we
	 can not thread through this block.  This is overly
	 conservative in some ways.  */
      if (TREE_CODE (stmt) == ASM_EXPR && ASM_VOLATILE_P (stmt))
	return NULL;

      /* If duplicating this block is going to cause too much code
	 expansion, then do not thread through this block.  */
      stmt_count++;
      if (stmt_count > max_stmt_count)
	return NULL;

      /* If this is not a MODIFY_EXPR which sets an SSA_NAME to a new
	 value, then do not try to simplify this statement as it will
	 not simplify in any way that is helpful for jump threading.  */
      if (TREE_CODE (stmt) != MODIFY_EXPR
	  || TREE_CODE (TREE_OPERAND (stmt, 0)) != SSA_NAME)
	continue;

      /* At this point we have a statement which assigns an RHS to an
	 SSA_VAR on the LHS.  We want to try and simplify this statement
	 to expose more context sensitive equivalences which in turn may
	 allow us to simplify the condition at the end of the loop.

	 Handle simple copy operations as well as implied copies from
	 ASSERT_EXPRs.  */
      if (TREE_CODE (TREE_OPERAND (stmt, 1)) == SSA_NAME)
	cached_lhs = TREE_OPERAND (stmt, 1);
      else if (TREE_CODE (TREE_OPERAND (stmt, 1)) == ASSERT_EXPR)
	cached_lhs = TREE_OPERAND (TREE_OPERAND (stmt, 1), 0);
      else
	{
	  /* A statement that is not a trivial copy or ASSERT_EXPR.
	     We're going to temporarily copy propagate the operands
	     and see if that allows us to simplify this statement.  */
	  tree *copy, pre_fold_expr;
	  ssa_op_iter iter;
	  use_operand_p use_p;
	  unsigned int num, i = 0;

	  num = NUM_SSA_OPERANDS (stmt, (SSA_OP_USE | SSA_OP_VUSE));
	  copy = XCNEWVEC (tree, num);

	  /* Make a copy of the uses & vuses into USES_COPY, then cprop into
	     the operands.  */
	  FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE | SSA_OP_VUSE)
	    {
	      tree tmp = NULL;
	      tree use = USE_FROM_PTR (use_p);

	      copy[i++] = use;
	      if (TREE_CODE (use) == SSA_NAME)
		tmp = SSA_NAME_VALUE (use);
	      if (tmp && TREE_CODE (tmp) != VALUE_HANDLE)
		SET_USE (use_p, tmp);
	    }

	  /* Try to fold/lookup the new expression.  Inserting the
	     expression into the hash table is unlikely to help
	     Sadly, we have to handle conditional assignments specially
	     here, because fold expects all the operands of an expression
	     to be folded before the expression itself is folded, but we
	     can't just substitute the folded condition here.  */
	  if (TREE_CODE (TREE_OPERAND (stmt, 1)) == COND_EXPR)
	    {
	      tree cond = COND_EXPR_COND (TREE_OPERAND (stmt, 1));
	      cond = fold (cond);
	      if (cond == boolean_true_node)
		pre_fold_expr = COND_EXPR_THEN (TREE_OPERAND (stmt, 1));
	      else if (cond == boolean_false_node)
		pre_fold_expr = COND_EXPR_ELSE (TREE_OPERAND (stmt, 1));
	      else
		pre_fold_expr = TREE_OPERAND (stmt, 1);
	    }
	  else
	    pre_fold_expr = TREE_OPERAND (stmt, 1);

	  if (pre_fold_expr)
	    {
	      cached_lhs = fold (pre_fold_expr);
	      if (TREE_CODE (cached_lhs) != SSA_NAME
		  && !is_gimple_min_invariant (cached_lhs))
	        cached_lhs = (*simplify) (stmt, stmt);
	    }

	  /* Restore the statement's original uses/defs.  */
	  i = 0;
	  FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE | SSA_OP_VUSE)
	    SET_USE (use_p, copy[i++]);

	  free (copy);
	}

      /* Record the context sensitive equivalence if we were able
	 to simplify this statement.  */
      if (cached_lhs
	  && (TREE_CODE (cached_lhs) == SSA_NAME
	      || is_gimple_min_invariant (cached_lhs)))
	record_temporary_equivalence (TREE_OPERAND (stmt, 0),
				      cached_lhs,
				      stack);
    }
  return stmt;
}

/* Simplify the control statement at the end of the block E->dest.

   To avoid allocating memory unnecessarily, a scratch COND_EXPR
   is available to use/clobber in DUMMY_COND.

   Use SIMPLIFY (a pointer to a callback function) to further simplify
   a condition using pass specific information.

   Return the simplified condition or NULL if simplification could
   not be performed.  */

static tree
simplify_control_stmt_condition (edge e,
				 tree stmt,
				 tree dummy_cond,
				 tree (*simplify) (tree, tree),
				 bool handle_dominating_asserts)
{
  tree cond, cached_lhs;

  if (TREE_CODE (stmt) == COND_EXPR)
    cond = COND_EXPR_COND (stmt);
  else if (TREE_CODE (stmt) == GOTO_EXPR)
    cond = GOTO_DESTINATION (stmt);
  else
    cond = SWITCH_COND (stmt);

  /* For comparisons, we have to update both operands, then try
     to simplify the comparison.  */
  if (COMPARISON_CLASS_P (cond))
    {
      tree op0, op1;
      enum tree_code cond_code;

      op0 = TREE_OPERAND (cond, 0);
      op1 = TREE_OPERAND (cond, 1);
      cond_code = TREE_CODE (cond);

      /* Get the current value of both operands.  */
      if (TREE_CODE (op0) == SSA_NAME)
	{
          tree tmp = SSA_NAME_VALUE (op0);
	  if (tmp && TREE_CODE (tmp) != VALUE_HANDLE)
	    op0 = tmp;
	}

      if (TREE_CODE (op1) == SSA_NAME)
	{
	  tree tmp = SSA_NAME_VALUE (op1);
	  if (tmp && TREE_CODE (tmp) != VALUE_HANDLE)
	    op1 = tmp;
	}

      if (handle_dominating_asserts)
	{
	  /* Now see if the operand was consumed by an ASSERT_EXPR
	     which dominates E->src.  If so, we want to replace the
	     operand with the LHS of the ASSERT_EXPR.  */
	  if (TREE_CODE (op0) == SSA_NAME)
	    op0 = lhs_of_dominating_assert (op0, e->src, stmt);

	  if (TREE_CODE (op1) == SSA_NAME)
	    op1 = lhs_of_dominating_assert (op1, e->src, stmt);
	}

      /* We may need to canonicalize the comparison.  For
	 example, op0 might be a constant while op1 is an
	 SSA_NAME.  Failure to canonicalize will cause us to
	 miss threading opportunities.  */
      if (cond_code != SSA_NAME
	  && tree_swap_operands_p (op0, op1, false))
	{
	  tree tmp;
	  cond_code = swap_tree_comparison (TREE_CODE (cond));
	  tmp = op0;
	  op0 = op1;
	  op1 = tmp;
	}

      /* Stuff the operator and operands into our dummy conditional
	 expression.  */
      TREE_SET_CODE (COND_EXPR_COND (dummy_cond), cond_code);
      TREE_OPERAND (COND_EXPR_COND (dummy_cond), 0) = op0;
      TREE_OPERAND (COND_EXPR_COND (dummy_cond), 1) = op1;

      /* We absolutely do not care about any type conversions
         we only care about a zero/nonzero value.  */
      fold_defer_overflow_warnings ();

      cached_lhs = fold (COND_EXPR_COND (dummy_cond));
      while (TREE_CODE (cached_lhs) == NOP_EXPR
	     || TREE_CODE (cached_lhs) == CONVERT_EXPR
	     || TREE_CODE (cached_lhs) == NON_LVALUE_EXPR)
	cached_lhs = TREE_OPERAND (cached_lhs, 0);

      fold_undefer_overflow_warnings (is_gimple_min_invariant (cached_lhs),
				      stmt, WARN_STRICT_OVERFLOW_CONDITIONAL);

      /* If we have not simplified the condition down to an invariant,
	 then use the pass specific callback to simplify the condition.  */
      if (! is_gimple_min_invariant (cached_lhs))
	cached_lhs = (*simplify) (dummy_cond, stmt);
    }

  /* We can have conditionals which just test the state of a variable
     rather than use a relational operator.  These are simpler to handle.  */
  else if (TREE_CODE (cond) == SSA_NAME)
    {
      cached_lhs = cond;

      /* Get the variable's current value from the equivalency chains.

	 It is possible to get loops in the SSA_NAME_VALUE chains
	 (consider threading the backedge of a loop where we have
	 a loop invariant SSA_NAME used in the condition.  */
      if (cached_lhs
	  && TREE_CODE (cached_lhs) == SSA_NAME
	  && SSA_NAME_VALUE (cached_lhs))
	cached_lhs = SSA_NAME_VALUE (cached_lhs);

      /* If we're dominated by a suitable ASSERT_EXPR, then
	 update CACHED_LHS appropriately.  */
      if (handle_dominating_asserts && TREE_CODE (cached_lhs) == SSA_NAME)
	cached_lhs = lhs_of_dominating_assert (cached_lhs, e->src, stmt);

      /* If we haven't simplified to an invariant yet, then use the
	 pass specific callback to try and simplify it further.  */
      if (cached_lhs && ! is_gimple_min_invariant (cached_lhs))
        cached_lhs = (*simplify) (stmt, stmt);
    }
  else
    cached_lhs = NULL;

  return cached_lhs;
}

/* We are exiting E->src, see if E->dest ends with a conditional
   jump which has a known value when reached via E.

   Special care is necessary if E is a back edge in the CFG as we
   may have already recorded equivalences for E->dest into our
   various tables, including the result of the conditional at
   the end of E->dest.  Threading opportunities are severely
   limited in that case to avoid short-circuiting the loop
   incorrectly.

   Note it is quite common for the first block inside a loop to
   end with a conditional which is either always true or always
   false when reached via the loop backedge.  Thus we do not want
   to blindly disable threading across a loop backedge.  */

void
thread_across_edge (tree dummy_cond,
		    edge e,
		    bool handle_dominating_asserts,
		    VEC(tree, heap) **stack,
		    tree (*simplify) (tree, tree))
{
  tree stmt;

  /* If E is a backedge, then we want to verify that the COND_EXPR,
     SWITCH_EXPR or GOTO_EXPR at the end of e->dest is not affected
     by any statements in e->dest.  If it is affected, then it is not
     safe to thread this edge.  */
  if (e->flags & EDGE_DFS_BACK)
    {
      ssa_op_iter iter;
      use_operand_p use_p;
      tree last = bsi_stmt (bsi_last (e->dest));

      FOR_EACH_SSA_USE_OPERAND (use_p, last, iter, SSA_OP_USE | SSA_OP_VUSE)
	{
	  tree use = USE_FROM_PTR (use_p);

          if (TREE_CODE (use) == SSA_NAME
	      && TREE_CODE (SSA_NAME_DEF_STMT (use)) != PHI_NODE
	      && bb_for_stmt (SSA_NAME_DEF_STMT (use)) == e->dest)
	    goto fail;
	}
    }

  stmt_count = 0;

  /* PHIs create temporary equivalences.  */
  if (!record_temporary_equivalences_from_phis (e, stack))
    goto fail;

  /* Now walk each statement recording any context sensitive
     temporary equivalences we can detect.  */
  stmt = record_temporary_equivalences_from_stmts_at_dest (e, stack, simplify);
  if (!stmt)
    goto fail;

  /* If we stopped at a COND_EXPR or SWITCH_EXPR, see if we know which arm
     will be taken.  */
  if (TREE_CODE (stmt) == COND_EXPR
      || TREE_CODE (stmt) == GOTO_EXPR
      || TREE_CODE (stmt) == SWITCH_EXPR)
    {
      tree cond;

      /* Extract and simplify the condition.  */
      cond = simplify_control_stmt_condition (e, stmt, dummy_cond, simplify, handle_dominating_asserts);

      if (cond && is_gimple_min_invariant (cond))
	{
	  edge taken_edge = find_taken_edge (e->dest, cond);
	  basic_block dest = (taken_edge ? taken_edge->dest : NULL);

	  if (dest == e->dest)
	    goto fail;

	  remove_temporary_equivalences (stack);
	  register_jump_thread (e, taken_edge);
	}
    }

 fail:
  remove_temporary_equivalences (stack);
}


text:
namespace Microsoft.Azure.Management.Network.Models
{
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// VpnConnection Resource.
    /// </summary>
    [Rest.Serialization.JsonTransformation]
    public partial class VpnConnection : Resource
    {
        /// <summary>
        /// Initializes a new instance of the VpnConnection class.
        /// </summary>
        public VpnConnection()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the VpnConnection class.
        /// </summary>
        /// <param name="id">Resource ID.</param>
        /// <param name="name">Resource name.</param>
        /// <param name="type">Resource type.</param>
        /// <param name="location">Resource location.</param>
        /// <param name="tags">Resource tags.</param>
        /// <param name="remoteVpnSite">Id of the connected vpn site.</param>
        /// <param name="routingWeight">routing weight for vpn
        /// connection.</param>
        /// <param name="connectionStatus">The connection status. Possible
        /// values include: 'Unknown', 'Connecting', 'Connected',
        /// 'NotConnected'</param>
        /// <param name="ingressBytesTransferred">Ingress bytes
        /// transferred.</param>
        /// <param name="egressBytesTransferred">Egress bytes
        /// transferred.</param>
        /// <param name="connectionBandwidthInMbps">Expected bandwidth in
        /// MBPS.</param>
        /// <param name="sharedKey">SharedKey for the vpn connection.</param>
        /// <param name="enableBgp">EnableBgp flag</param>
        /// <param name="ipsecPolicies">The IPSec Policies to be considered by
        /// this connection.</param>
        /// <param name="provisioningState">The provisioning state of the
        /// resource. Possible values include: 'Succeeded', 'Updating',
        /// 'Deleting', 'Failed'</param>
        /// <param name="etag">Gets a unique read-only string that changes
        /// whenever the resource is updated.</param>
        public VpnConnection(string id = default(string), string name = default(string), string type = default(string), string location = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), SubResource remoteVpnSite = default(SubResource), int? routingWeight = default(int?), string connectionStatus = default(string), long? ingressBytesTransferred = default(long?), long? egressBytesTransferred = default(long?), int? connectionBandwidthInMbps = default(int?), string sharedKey = default(string), bool? enableBgp = default(bool?), IList<IpsecPolicy> ipsecPolicies = default(IList<IpsecPolicy>), string provisioningState = default(string), string etag = default(string))
            : base(id, name, type, location, tags)
        {
            RemoteVpnSite = remoteVpnSite;
            RoutingWeight = routingWeight;
            ConnectionStatus = connectionStatus;
            IngressBytesTransferred = ingressBytesTransferred;
            EgressBytesTransferred = egressBytesTransferred;
            ConnectionBandwidthInMbps = connectionBandwidthInMbps;
            SharedKey = sharedKey;
            EnableBgp = enableBgp;
            IpsecPolicies = ipsecPolicies;
            ProvisioningState = provisioningState;
            Etag = etag;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets id of the connected vpn site.
        /// </summary>
        [JsonProperty(PropertyName = "properties.remoteVpnSite")]
        public SubResource RemoteVpnSite { get; set; }

        /// <summary>
        /// Gets or sets routing weight for vpn connection.
        /// </summary>
        [JsonProperty(PropertyName = "properties.routingWeight")]
        public int? RoutingWeight { get; set; }

        /// <summary>
        /// Gets or sets the connection status. Possible values include:
        /// 'Unknown', 'Connecting', 'Connected', 'NotConnected'
        /// </summary>
        [JsonProperty(PropertyName = "properties.connectionStatus")]
        public string ConnectionStatus { get; set; }

        /// <summary>
        /// Gets ingress bytes transferred.
        /// </summary>
        [JsonProperty(PropertyName = "properties.ingressBytesTransferred")]
        public long? IngressBytesTransferred { get; private set; }

        /// <summary>
        /// Gets egress bytes transferred.
        /// </summary>
        [JsonProperty(PropertyName = "properties.egressBytesTransferred")]
        public long? EgressBytesTransferred { get; private set; }

        /// <summary>
        /// Gets expected bandwidth in MBPS.
        /// </summary>
        [JsonProperty(PropertyName = "properties.connectionBandwidthInMbps")]
        public int? ConnectionBandwidthInMbps { get; private set; }

        /// <summary>
        /// Gets or sets sharedKey for the vpn connection.
        /// </summary>
        [JsonProperty(PropertyName = "properties.sharedKey")]
        public string SharedKey { get; set; }

        /// <summary>
        /// Gets or sets enableBgp flag
        /// </summary>
        [JsonProperty(PropertyName = "properties.enableBgp")]
        public bool? EnableBgp { get; set; }

        /// <summary>
        /// Gets or sets the IPSec Policies to be considered by this
        /// connection.
        /// </summary>
        [JsonProperty(PropertyName = "properties.ipsecPolicies")]
        public IList<IpsecPolicy> IpsecPolicies { get; set; }

        /// <summary>
        /// Gets or sets the provisioning state of the resource. Possible
        /// values include: 'Succeeded', 'Updating', 'Deleting', 'Failed'
        /// </summary>
        [JsonProperty(PropertyName = "properties.provisioningState")]
        public string ProvisioningState { get; set; }

        /// <summary>
        /// Gets a unique read-only string that changes whenever the resource
        /// is updated.
        /// </summary>
        [JsonProperty(PropertyName = "etag")]
        public string Etag { get; private set; }

    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package poseur.events.colors;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import poseur.TheAnimatedPoseur;
import poseur.gui.UserInterface;

/**
 * The BackgroundColorHanler will be called whenever the user
 * selects the background button to toggle it into the on position.  Once in
 * the on position, the user can change the color for shapes backgrounds.  The
 * class will also un-toggle the outline color button.
 * @author travis
 */
public class BackgroundColorHandler implements ActionListener {

    /**
     * Communicates with th user interface so that it can request the
     * background color button be switched to the on position.
     *
     * @param   e
     *          The event that requested the background button be toggled to
     *          the on position.
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        //  Request communication with the user interface
        TheAnimatedPoseur singleton = TheAnimatedPoseur.getAnimatedPoseur();
        UserInterface gui = singleton.getGUI();

        //  Toggles the background button to on
        gui.activateBackgroundToggleButton();;
    }

}


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you 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.

package org.openqa.selenium;

import org.openqa.selenium.internal.Require;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Mechanism used to locate elements within a document. In order to create your own locating
 * mechanisms, it is possible to subclass this class and override the protected methods as required,
 * though it is expected that all subclasses rely on the basic finding mechanisms provided
 * through static methods of this class:
 *
 *

 * public WebElement findElement(WebDriver driver) {
 *     WebElement element = driver.findElement(By.id(getSelector()));
 *     if (element == null)
 *       element = driver.findElement(By.name(getSelector());
 *     return element;
 * }
 *

 */
public abstract class By {
  /**
   * @param id The value of the "id" attribute to search for.
   * @return A By which locates elements by the value of the "id" attribute.
   */
  public static By id(String id) {
    return new ById(id);
  }

  /**
   * @param linkText The exact text to match against.
   * @return A By which locates A elements by the exact text it displays.
   */
  public static By linkText(String linkText) {
    return new ByLinkText(linkText);
  }

  /**
   * @param partialLinkText The partial text to match against
   * @return a By which locates elements that contain the given link text.
   */
  public static By partialLinkText(String partialLinkText) {
    return new ByPartialLinkText(partialLinkText);
  }

  /**
   * @param name The value of the "name" attribute to search for.
   * @return A By which locates elements by the value of the "name" attribute.
   */
  public static By name(String name) {
    return new ByName(name);
  }

  /**
   * @param tagName The element's tag name.
   * @return A By which locates elements by their tag name.
   */
  public static By tagName(String tagName) {
    return new ByTagName(tagName);
  }

  /**
   * @param xpathExpression The XPath to use.
   * @return A By which locates elements via XPath.
   */
  public static By xpath(String xpathExpression) {
    return new ByXPath(xpathExpression);
  }

  /**
   * Find elements based on the value of the "class" attribute. Only one class name should be
   * used. If an element has multiple classes, please use {@link By#cssSelector(String)}.
   *
   * @param className The value of the "class" attribute to search for.
   * @return A By which locates elements by the value of the "class" attribute.
   */
  public static By className(String className) {
    return new ByClassName(className);
  }

  /**
   * Find elements via the driver's underlying W3C Selector engine. If the browser does not
   * implement the Selector API, a best effort is made to emulate the API. In this case, we strive
   * for at least CSS2 support, but offer no guarantees.
   *
   * @param cssSelector CSS expression.
   * @return A By which locates elements by CSS.
   */
  public static By cssSelector(String cssSelector) {
    return new ByCssSelector(cssSelector);
  }

  /**
   * Find a single element. Override this method if necessary.
   *
   * @param context A context to use to find the element.
   * @return The WebElement that matches the selector.
   */
  public WebElement findElement(SearchContext context) {
    List<WebElement> allElements = findElements(context);
    if (allElements == null || allElements.isEmpty()) {
      throw new NoSuchElementException("Cannot locate an element using " + toString());
    }
    return allElements.get(0);
  }

  /**
   * Find many elements.
   *
   * @param context A context to use to find the elements.
   * @return A list of WebElements matching the selector.
   */
  public abstract List<WebElement> findElements(SearchContext context);

  protected WebDriver getWebDriver(SearchContext context) {
    if (context instanceof WebDriver) {
      return (WebDriver) context;
    }

    if (!(context instanceof WrapsDriver)) {
      throw new IllegalArgumentException("Context does not wrap a webdriver: " + context);
    }

    return ((WrapsDriver) context).getWrappedDriver();
  }

  protected JavascriptExecutor getJavascriptExecutor(SearchContext context) {
    WebDriver driver = getWebDriver(context);

    if (!(context instanceof JavascriptExecutor)) {
      throw new IllegalArgumentException("Context does not provide a mechanism to execute JS: " + context);
    }

    return (JavascriptExecutor) driver;
  }

  @Override
  public boolean equals(Object o) {
    if (!(o instanceof By)) {
      return false;
    }

    By that = (By) o;

    return this.toString().equals(that.toString());
  }

  @Override
  public int hashCode() {
    return toString().hashCode();
  }

  @Override
  public String toString() {
    // A stub to prevent endless recursion in hashCode()
    return "[unknown locator]";
  }

  public static class ById extends PreW3CLocator {

    private final String id;

    public ById(String id) {
      super(
        "id",
        Require.argument("Id", id).nonNull("Cannot find elements when id is null."),
        "#%s");

      this.id = id;
    }

    @Override
    public String toString() {
      return "By.id: " + id;
    }
  }

  public static class ByLinkText extends BaseW3CLocator {

    private final String linkText;

    public ByLinkText(String linkText) {
      super(
        "link text",
        Require.argument("Link text", linkText)
          .nonNull("Cannot find elements when the link text is null."));

      this.linkText = linkText;
    }

    @Override
    public String toString() {
      return "By.linkText: " + linkText;
    }
  }

  public static class ByPartialLinkText extends BaseW3CLocator {

    private final String partialLinkText;

    public ByPartialLinkText(String partialLinkText) {
      super(
        "partial link text",
        Require.argument("Partial link text", partialLinkText)
          .nonNull("Cannot find elements when the link text is null."));

      this.partialLinkText = partialLinkText;
    }

    @Override
    public String toString() {
      return "By.partialLinkText: " + partialLinkText;
    }
  }

  public static class ByName extends PreW3CLocator {
    private final String name;

    public ByName(String name) {
      super(
        "name",
        Require.argument("Name", name).nonNull("Cannot find elements when name text is null."),
        String.format("*[name='%s']", name.replace("'", "\\'")));

      this.name = name;
    }

    @Override
    public String toString() {
      return "By.name: " + name;
    }
  }

  public static class ByTagName extends BaseW3CLocator {

    private final String tagName;

    public ByTagName(String tagName) {
      super(
        "tag name",
        Require.argument("Tag name", tagName)
          .nonNull("Cannot find elements when the tag name is null."));

      if (tagName.isEmpty()) {
        throw new InvalidSelectorException("Tag name must not be blank");
      }

      this.tagName = tagName;
    }

    @Override
    public String toString() {
      return "By.tagName: " + tagName;
    }
  }

  public static class ByXPath extends BaseW3CLocator {

    private final String xpathExpression;

    public ByXPath(String xpathExpression) {
      super(
        "xpath",
        Require.argument("XPath", xpathExpression)
          .nonNull("Cannot find elements when the XPath is null."));

      this.xpathExpression = xpathExpression;
    }

    @Override
    public String toString() {
      return "By.xpath: " + xpathExpression;
    }
  }

  public static class ByClassName extends PreW3CLocator {

    private final String className;

    public ByClassName(String className) {
      super(
        "class name",
        Require.argument("Class name", className)
          .nonNull("Cannot find elements when the class name expression is null."),
      ".%s");

      if (className.matches(".*\\s.*")) {
        throw new InvalidSelectorException("Compound class names not permitted");
      }

      this.className = className;
    }

    @Override
    public String toString() {
      return "By.className: " + className;
    }
  }

  public static class ByCssSelector extends BaseW3CLocator {
    private final String cssSelector;

    public ByCssSelector(String cssSelector) {
      super(
        "css selector",
        Require.argument("CSS selector", cssSelector)
          .nonNull("Cannot find elements when the selector is null"));

      this.cssSelector = cssSelector;
    }

    @Override
    public String toString() {
      return "By.cssSelector: " + cssSelector;
    }
  }

  public interface Remotable {
    Parameters getRemoteParameters();

    class Parameters {
      private final String using;
      private final Object value;

      public Parameters(String using, Object value) {
        this.using = Require.nonNull("Search mechanism", using);
        // There may be subclasses where the value is optional. Allow for this.
        this.value = value;
      }

      public String using() {
        return using;
      }

      public Object value() {
        return value;
      }

      @Override
      public String toString() {
        return "[" + using + ": " + value + "]";
      }

      @Override
      public boolean equals(Object o) {
        if (!(o instanceof Parameters)) {
          return false;
        }
        Parameters that = (Parameters) o;
        return using.equals(that.using) && Objects.equals(value, that.value);
      }

      @Override
      public int hashCode() {
        return Objects.hash(using, value);
      }

      private Map<String, Object> toJson() {
        Map<String, Object> params = new HashMap<>();
        params.put("using", using);
        params.put("value", value);
        return Collections.unmodifiableMap(params);
      }
    }
  }

  private abstract static class BaseW3CLocator extends By implements Remotable {
    private final Parameters params;

    protected BaseW3CLocator(String using, String value) {
      this.params = new Parameters(using, value);
    }

    @Override
    public WebElement findElement(SearchContext context) {
      Require.nonNull("Search Context", context);
      return context.findElement(this);
    }

    @Override
    public List<WebElement> findElements(SearchContext context) {
      Require.nonNull("Search Context", context);
      return context.findElements(this);
    }

    @Override
    public final Parameters getRemoteParameters() {
      return params;
    }

    protected final Map<String, Object> toJson() {
      return getRemoteParameters().toJson();
    }
  }

  private abstract static class PreW3CLocator extends By implements Remotable {
    private final Parameters remoteParams;
    private final ByCssSelector fallback;

    private PreW3CLocator(String using, String value, String formatString) {
      this.remoteParams = new Remotable.Parameters(using, value);
      this.fallback = new ByCssSelector(String.format(formatString, cssEscape(value)));
    }

    @Override
    public WebElement findElement(SearchContext context) {
      return context.findElement(fallback);
    }

    @Override
    public List<WebElement> findElements(SearchContext context) {
      return context.findElements(fallback);
    }

    @Override
    public final Parameters getRemoteParameters() {
      return remoteParams;
    }

    protected final Map<String, Object> toJson() {
      return fallback.toJson();
    }

    private String cssEscape(String using) {
      using = using.replaceAll("([\\s'\"\\\\#.:;,!?+<>=~*^$|%&@`{}\\-\\/\\[\\]\\(\\)])", "\\\\$1");
      if (using.length() > 0 && Character.isDigit(using.charAt(0))) {
        using = "\\" + (30 + Integer.parseInt(using.substring(0,1))) + " " + using.substring(1);
      }
      return using;
    }
  }
}


text:
define(['exports', './constants'], function (exports, _constants) {
  'use strict';

  exports.__esModule = true;
  exports.addHyphenAndLower = addHyphenAndLower;
  exports._hyphenate = _hyphenate;
  exports._unhyphenate = _unhyphenate;
  exports.getBindablePropertyName = getBindablePropertyName;
  exports.getEventsFromAttributes = getEventsFromAttributes;
  var capitalMatcher = /([A-Z])/g;

  function addHyphenAndLower(char) {
    return '-' + char.toLowerCase();
  }

  function _hyphenate(name) {
    return (name.charAt(0).toLowerCase() + name.slice(1)).replace(capitalMatcher, addHyphenAndLower);
  }

  function _unhyphenate(name) {
    return name.replace(/-([a-z])/g, function (g) {
      return g[1].toUpperCase();
    });
  }

  function getBindablePropertyName(propertyName) {
    var name = '' + _constants.constants.bindablePrefix + propertyName;

    return _unhyphenate(name);
  }

  function getEventsFromAttributes(element) {
    var attributes = Array.prototype.slice.call(element.attributes);
    var events = [];

    for (var _iterator = attributes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
      var _ref;

      if (_isArray) {
        if (_i >= _iterator.length) break;
        _ref = _iterator[_i++];
      } else {
        _i = _iterator.next();
        if (_i.done) break;
        _ref = _i.value;
      }

      var attribute = _ref;

      var attributeName = attribute.name;
      if (!attributeName.startsWith(_constants.constants.eventPrefix)) continue;

      var hyphenatedEvent = attributeName.split(_constants.constants.eventPrefix)[1];

      var withoutTriggerDelegate = hyphenatedEvent.split('.')[0];

      var camelCased = _unhyphenate(withoutTriggerDelegate);

      events.push(camelCased);
    }

    return events;
  }
});