text:
import docker
import ports
import os
import pandas as pd
import time
import common

class Memcached:
    """
            A memcached setup consisting of 1 client and 4 servers.

            User must set up the class attributes and call launch.

    """

    def memcached_client_cmd(self, name="dc-client", cpu_set='56-66'):
        """
                Construct the command to start memcached client.
        """
        cmd = (
            "docker run -dit "
            "--name {} "
            "--net none "
            "--cpuset-cpus {} "
            "-u root "
            "--privileged "
            "cloudsuite/data-caching:client bash"
        ).format(str(name), str(cpu_set))

        return cmd

    def memcached_server_cmd(self, name=None, cpu_set=None,
                             memcached_server_thread=4,
                             memcached_server_mem=4096,
                             memcached_min_obj_sz=550):
        """
                Construct the command to start memcached server.
        """
        cmd = (
            "docker run "
            "--name {} "
            "--net none "
            "--cpuset-cpus {} "
            "-d "
            "cloudsuite/data-caching:server "
            "-t {} "
            "-m {} "
            "-n {} "
        ).format(str(name), str(cpu_set),
                 str(memcached_server_thread),
                 str(memcached_server_mem),
                 str(memcached_min_obj_sz))

        return cmd

    def launch(self, experiment_config):
        """
                Start the docker containers.

                Input:
                        - An array where the experiment config will be appended to.
        """

        # launch the clients.
        client_cmd = \
            self.memcached_client_cmd(cpu_set=self.client_cpu_set,
                                      name=self.client_name)

        memcached_client = \
            docker.start_container(	command=client_cmd,
                                    port_name=self.client_port_name,
                                    name=self.client_name)

        memcached_client['cpu_set'] = self.client_cpu_set
        memcached_client['port'] = self.client_port_name
        experiment_config.append(memcached_client)

        # TODO: update the memcached server file.

        # Make this mutable (memcached servers).
        n_servers = 4

        # launch the servers.
        assert len(self.server_list_cpu_set) == n_servers
        assert len(self.server_list_port_name) == n_servers
        assert len(self.server_list_name) == n_servers

        for i in range(n_servers):
            server_cmd = \
                self.memcached_server_cmd(name=self.server_list_name[i],
                                          cpu_set=self.server_list_cpu_set[i])

            memcached_server = \
                docker.start_container(command=server_cmd,
                                       port_name=self.server_list_port_name[i],
                                       name=self.server_list_name[i])

            memcached_server['cpu_set'] = self.server_list_cpu_set[i]
            memcached_server['port'] = self.server_list_port_name[i]
            experiment_config.append(memcached_server)

            # Setup the connectivity.
            docker.connect(memcached_client, memcached_server)
            docker.dns(memcached_client, memcached_server)

        # Warm up the memcached.
        warmup_cmd = (
            "docker exec -dit {} "
            "/usr/src/memcached/memcached_client/loader -a "
            "/usr/src/memcached/twitter_dataset/twitter_dataset_unscaled -o "
            "/usr/src/memcached/twitter_dataset/twitter_dataset_30x -s "
            "/usr/src/memcached/memcached_client/docker_servers.txt "
            "-w 4 -S 30 -D 4096 -j -T 1"
        ).format(self.client_name)

        common.run_local_cmd(warmup_cmd)

    def __init__(self):

        self.client_cpu_set = None
        self.client_port_name = None
        self.client_name = None

        self.server_list_cpu_set = None
        self.server_list_port_name = None
        self.server_list_name = None

class WebSearch:
    """
            A websearch setup consisting of 1 client and 1 server.

            User must set up the class attributes and call launch.

    """

    def websearch_client_cmd(self, name=None, cpu_set=None):
        """
                Construct the command to start websearch client.
        """
        cmd = (
            "docker run "
            "-dit "
            "--entrypoint /bin/bash "
            "--name {} "
            "--cpuset-cpus {} "
            "--net none "
            "cloudsuite3/web-search:client "
        ).format(str(name), str(cpu_set))

        return cmd

    def websearch_server_cmd(self, name=None, cpu_set=None,
                             webserver_mem=12,
                             n_index_nodes=1):
        """
                Construct the command to start websearch server.
        """
        cmd = (
            "docker run "
            "-dit "
            "--name {} "
            "--net none "
            "--cpuset-cpus {} "
            "cloudsuite3/web-search:server "
            "{}g {}"
        ).format(str(name), str(cpu_set),
                 str(webserver_mem),
                 str(n_index_nodes))

        return cmd

    def launch(self, experiment_config):
        """
                Start the docker containers.

                Input:
                        - An array where the experiment config will be appended to.
        """

        # launch the server.
        server_cmd = \
            self.websearch_server_cmd(name=self.server_name,
                                      cpu_set=self.server_cpu_set)

        websearch_server = \
            docker.start_container(	command=server_cmd,
                                    port_name=self.server_port_name,
                                    name=self.server_name)

        websearch_server['cpu_set'] = self.server_cpu_set
        websearch_server['port'] = self.server_port_name
        experiment_config.append(websearch_server)

        # launch the client.
        client_cmd = \
            self.websearch_client_cmd(cpu_set=self.client_cpu_set,
                                      name=self.client_name)

        websearch_client = \
            docker.start_container(	command=client_cmd,
                                    port_name=self.client_port_name,
                                    name=self.client_name)

        websearch_client['cpu_set'] = self.client_cpu_set
        websearch_client['port'] = self.client_port_name
        experiment_config.append(websearch_client)

        # Setup the connectivity.
        docker.connect(websearch_server, websearch_client)

    def __init__(self):

        self.client_cpu_set = None
        self.client_port_name = None
        self.client_name = None

        self.server_cpu_set = None
        self.server_port_name = None
        self.server_name = None


text:
set -euo pipefail
IFS=$'\n\t'

jdeps="jdeps"

if ! hash ${jdeps} 2>/dev/null; then
  echo "No jdeps found - is it installed and on your PATH?"; exit 1
fi

fastutil_regex='it\.unimi\.dsi\.fastutil\..*'

function check_exec()  {
  for exec in $@; do
    if ! hash "$exec"; then
      echo "$exec not found"; exit 1
    fi
  done
}

function print_synopsis() {
  >&2
  #    |                                                                               |
  echo "Synopsis: \"$(basename $0) <command> <args>\", where command is"
  echo "  - \"find\" (searches for usages of fastutil in your project) or"
  echo "  - \"minimize\" (creates a jar containing transitive dependencies of fastutil)"
  echo ""
  echo "Arguments:"
  echo " find:"
  echo "   <paths to analyse> - Analyses the given path (jar or directory for usages"
  echo "       of fastutil classes"
  echo "   --cp <path> - Adds the given path (jar or directory) to the searched class-"
  echo "       path. This is useful if you have a big library making use of a lot of"
  echo "       fastutil, but you only use a small subset of that library. Make sure"
  echo "       not to include fastutil itself here!"
  echo "   --src - Output paths to the .java files"
  echo "   --cls - Output paths to the .class files"
  echo " minimize: <path to fastutil.jar> <path to class list>"
}

function print_usage() {
  >&2
  #    |                                                                               |
  echo "Usage: Typically, you want to first create the list of fastutil dependencies by"
  echo "running this script with \"find\" on your project classes and write this"
  echo "dependency list into a file:"
  echo ""
  echo "  $(basename $0) find path-to-project > dependencies.txt"
  echo ""
  echo "Then call \"minimize\" onto the matching fastutil jar to create a compact"
  echo "version, containing only the necessary classes:"
  echo ""
  echo "  $(basename $0) minimize fastutil.jar dependencies.txt"
  echo ""
  echo "A more advanced usage would be to build a minimized jar based on manually"
  echo "written \"dependencies.txt\" which can be directly passed to \"minimize\"."
}

function invalid_argument() {
  print_synopsis
  exit 1
}

[ ${#} -ge 1 ] || invalid_argument
command="$1"

case "$command" in
  "find")
  shift

  output_mode="class"
  declare -a class_paths=()
  declare -a analyse_paths=()

  while [ ${#} -gt 0 ]; do
    case "$1" in
      "--classpath"|"--cp")
        [ ${#} -ge 1 ] || invalid_argument
        class_paths+=("$2")
        shift
      ;;
      "--source"|"--src")
         output_mode="source"
      ;;
      "--class"|"--cls")
         output_mode="class"
      ;;
      *)
        analyse_paths+=("$1")
    esac
    shift
  done

  [ ${#analyse_paths[@]} -ge 1 ] || invalid_argument

  for path in "${class_paths[@]+"${class_paths[@]}"}" "${analyse_paths[@]}"; do
    if [ ! -e "$path" ]; then
      >&2 echo "Path \"$path\" does not exist"; exit 1
    fi
    case "$path" in
      *"fastutil"*)
        >&2 echo "Path $path looks like a fastutil jar - you probably don't want to include this" ;;
    esac
  done

  if [ $(find "${analyse_paths[@]}" -name "*.class" | wc -l) -eq 0 ]; then
    echo "No *.class files found in any of the specified paths"; exit 1
  fi

  if [ ${#class_paths[@]} -gt 0 ]; then
    function join_by { local IFS="$1"; shift; echo "$*"; }
    declare -a classpath_argument=("-cp" $(join_by ':' "${class_paths[@]}"))
  fi

  if ! dependencies=$(jdeps -recursive -verbose:class \
    "${classpath_argument[@]+"${classpath_argument[@]}"}" "${analyse_paths[@]}" |\
    grep '^      -> it\.unimi\.dsi\.fastutil\..*not found$' | sed 's!      -> \(\S*\) \+not found$!\1!' | sort | uniq) \
    || [ -z "$dependencies" ]
  then
    >&2 echo "No unresolved references found - is fastutil on the classpath?"
    exit 1
  fi

  if [ "$output_mode" == "class" ]; then
    echo "$dependencies" | sed 's!\.!/!g' | sed 's!^\(.*\)$!\1.class!'
  else
    echo "$dependencies" | grep -v '\$' | sed 's!\.!/!g' | sed 's!^\(.*\)$!\1.java!'
  fi
  exit 0
  ;;

  "minimize")
  shift
  check_exec "zip" "unzip"

  [ ${#} -ge 2 ] || invalid_argument

  jar_path="$(realpath $1)"
  if [ ! -f "$jar_path" ]; then
    >&2 echo "No file at \"$jar_path\""
    exit 1
  fi

  class_list_path="$(realpath $2)"
  if [ ! -f "$class_list_path" ]; then
    >&2 echo "No file at \"$class_list_path\""
    exit 1
  fi

  dest_path="${jar_path%\.jar}-min.jar"
  if [ -e "$dest_path" ]; then
    >&2 echo "Destination path $dest_path exists"
    exit 1
  fi

  jar_name="$(basename ${dest_path})"

  tmp_dir=$(mktemp -t -d "fastutil-min.XXXX")
  trap "{ rm -rf \"${tmp_dir}\"; exit 255; }" EXIT

  ( >&2 echo "Resolving transitive dependencies" )

  class_paths=$(cat "$class_list_path" | grep '.class$')
  if [ -z "$class_paths" ]; then
    >&2 echo "No classes found in $class_list_path - make sure they are proper paths to .class files"
    exit 1
  fi

  class_list=${class_paths//.class/}
  class_list=${class_list//\//.}

  if ! transitive_dependencies=$(cd ${tmp_dir} && jdeps -recursive -regex "$fastutil_regex" \
    -verbose:class -cp "$jar_path" ${class_list} | grep '      -> ' |\
    sed 's!      -> \(\S*\) \+\S*!\1!' | sort | uniq | sed 's!\.!/!g' | sed 's!$!.class!')\
    || [ -z "$transitive_dependencies" ]
  then
    >&2 echo "Could not resolve dependencies with $jar_path - probably not a complete fastutil jar."
    exit 1
  fi

  ( >&2 echo "Unpacking jar from $jar_path" )
  if ! output=$(unzip -q "$jar_path" "META-INF/*" $(printf '%s\n' $class_paths $transitive_dependencies | sort | uniq) -d "$tmp_dir" 2>&1); then
    >&2 echo "Error: $output"; exit 1
  fi

  ( >&2 echo "Creating minimized jar at $dest_path" )
  if ! output=$(cd "$tmp_dir" && zip -9 -q -r "$dest_path" "it" "META-INF" 2>&1); then
    >&2 echo "Error: $output"; exit 1
  fi
  ;;
  "-h"|"--help")
  print_synopsis
  >&2 echo ""
  print_usage
  ;;
  *)
  invalid_argument
  ;;
esac

redpajama_set_name: RedPajamaGithub


text:
import { remote } from 'electron';

if (remote.getGlobal('DEV_MODE')) {
  try {
    require('devtron').install();
  } catch (e) {
    // Who cares
  }

  window.addEventListener('load', () => {
    const webview = document.querySelector('webview');
    if (!webview) {
      return;
    }
    window.openGPMDevTools = () => {
      webview.openDevTools();
    };
  });
}


text:
FROM ubuntu:20.04

################### METADATA #######################
LABEL base_image="ubuntu:20.04"
LABEL version="4"
LABEL software="autoclassweb"
LABEL software.version="1.2.0"
LABEL about.summary="A web app to run AutoClass C Bayesian clustering"
LABEL about.home="https://github.com/pierrepo/autoclassweb"
LABEL about.documentation="https://github.com/pierrepo/autoclassweb"
LABEL about.license_file="https://github.com/pierrepo/autoclassweb/blob/master/LICENSE.txt"
LABEL about.license="SPDX:BSD-3-Clause"
LABEL extra.identifiers.biotools="autoclassweb"
LABEL about.tags="Genomics Proteomics Omics"

################## MAINTAINER ######################
LABEL maintainer="Pierre Poulain <pierre.poulain@cupnet.net>"

# Change default shell
SHELL ["/bin/bash", "-c"]

ENV LC_ALL C.UTF-8
ENV LANG C.UTF-8

RUN apt update && \
    apt -y upgrade && \
    apt install -y git && \
    apt install -y wget && \
    apt install -y libc6-i386 && \
    apt autoremove -y && \
    apt clean && \
    rm -rf /var/lib/apt/lists/* /var/log/dpkg.log

# Create app directory
WORKDIR /app

# Download source code
RUN git clone --depth 1 https://github.com/pierrepo/autoclassweb.git /app

# Install conda
# See https://hub.docker.com/r/conda/miniconda3/dockerfile
ENV PATH /opt/miniconda3/bin:$PATH
RUN wget --quiet https://repo.anaconda.com/miniconda/Miniconda3-py38_4.8.3-Linux-x86_64.sh -O /tmp/miniconda.sh && \
    /bin/bash /tmp/miniconda.sh -b -p /opt/miniconda3 && \
    rm -f /tmp/miniconda.sh && \
    conda update conda

# Install conda env
ARG conda_env=autoclassweb
RUN conda env create -f environment-lock.yml && \
    conda clean -afy
ENV PATH /opt/miniconda3/envs/${conda_env}/bin:$PATH

# Install autoclass-c binary
# https://ti.arc.nasa.gov/tech/rse/synthesis-projects-applications/autoclass/autoclass-c/
RUN wget --quiet https://ti.arc.nasa.gov/m/project/autoclass/autoclass-c-3-3-6.tar.gz && \
    tar zxvf autoclass-c-3-3-6.tar.gz && \
    mv autoclass-c/autoclass /usr/local/bin/ && \
    rm -rf autoclass-c/ autoclass-c-3-3-6.tar.gz

# Create shared directories
RUN mkdir -p /app/{config,logs,results}

# Expose volumes and port
VOLUME /app/config
VOLUME /app/logs
VOLUME /app/results
EXPOSE 5000

# Run the web app
#CMD ["gunicorn", "--config", "gunicorn.py", "flaskapp:app"]


text:
namespace WatiN.Core.Native.Chrome
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;

    using Logging;

    using UtilityClasses;

    /// <summary>
    /// Handles telnet communication to the Chrome browser shell.
    /// </summary>
    public class ChromeClientPort : ClientPortBase
    {
        /// <summary>
        /// List of known errors  that the Google remote port might return.
        /// </summary>
        private static readonly List<string> knownResponseErrors = new List<string> { "unknown command", "TypeError", "SyntaxError", "\"Uncaught SyntaxError", "Uncaught ReferenceError", "true\r\r\n\"Not allowed to load local resource: file:///" };

        /// <summary>
        /// The port used to connect to chrome.
        /// </summary>
        private const int ChromePort = 9999;

        /// <summary>
        /// <c>true</c> if the <see cref="Dispose()"/> method has been called to release resources.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Underlying socket used to create a <see cref="NetworkStream"/>.
        /// </summary>
        private Socket telnetSocket;

        /// <summary>
        /// Finalizes an instance of the <see cref="ChromeClientPort"/> class.
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="FireFox"/> is reclaimed by garbage collection.
        /// </summary>
        ~ChromeClientPort()
        {
            this.Dispose(false);
        }

        /// <summary>
        /// Gets a value indicating whether this <see cref="ChromeClientPort"/> is connected.
        /// </summary>
        /// <value><c>true</c> if connected; otherwise, <c>false</c>.</value>
        public bool Connected { get; private set; }

        /// <summary>
        /// Gets the name of the javascript variable that references the DOM:document object.
        /// </summary>
        public override string DocumentVariableName
        {
            get
            {
                return "document";
            }
        }

        /// <summary>
        /// Gets the type of java script engine.
        /// </summary>
        /// <value>The type of java script engine.</value>
        public override JavaScriptEngineType JavaScriptEngine
        {
            get
            {
                return JavaScriptEngineType.WebKit;
            }
        }

        /// <summary>
        /// Gets the name of the browser variable.
        /// </summary>
        /// <value>The name of the browser variable.</value>
        public override string BrowserVariableName
        {
            get
            {
                throw new System.NotImplementedException();
            }
        }

        /// <summary>
        /// Gets or sets the last command send to the chrome client.
        /// </summary>
        /// <value>The last command send.</value>
        private string LastCommandSend
        {
            get;
            set;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public override void Dispose()
        {
            this.Dispose(true);

            // This object will be cleaned up by the Dispose method.
            // Therefore, you should call GC.SupressFinalize to
            // take this object off the finalization queue
            // and prevent finalization code for this object
            // from executing a second time.
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Connects to the Chrome browser and navigates to the specified URL.
        /// </summary>
        /// <param name="url">The URL to connect to.</param>
        public override void Connect(string url)
        {
            this.ValidateCanConnect();
            this.disposed = false;

            Logger.LogDebug(string.Format("Attempting to connect to chrome on localhost port {0}.", ChromePort));

            this.LastResponse = string.Empty;
            this.Response = new StringBuilder();

            this.Process = Core.Chrome.CreateProcess(string.Format("--disable-hang-monitor --remote-shell-port={0} \"{1}\"", ChromePort, url), true);

            this.telnetSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { Blocking = true };

            try
            {
                this.telnetSocket.Connect(IPAddress.Parse("127.0.0.1"), ChromePort);
            }
            catch (SocketException sockException)
            {
                Logger.LogDebug(string.Format("Failed connecting to jssh server.\nError code:{0}\nError message:{1}", sockException.ErrorCode, sockException.Message));
                throw new ChromeException("Unable to connect to jssh server, please make sure you have correctly installed the jssh.xpi plugin", sockException);
            }

            this.Connected = true;
            this.WaitForConnectionEstablished();
            Logger.LogDebug(string.Format("Successfully connected to Chrome on port.{0}", ChromePort));

            //DefineDefaultJSVariables();
        }

        /// <summary>
        /// Initializes the document.
        /// </summary>
        public override void InitializeDocument()
        {
        }

        /// <summary>
        /// Writes the specified data to the remote server.
        /// </summary>
        /// <param name="data">The data to write.</param>
        /// <param name="resultExpected"><c>true</c> if a result is expected.</param>
        /// <param name="checkForErrors"><c>true</c> if error checking should be applied.</param>
        /// <param name="args">Arguments to format with the data.</param>
        protected override void SendAndRead(string data, bool resultExpected, bool checkForErrors, params object[] args)
        {
            if (string.IsNullOrEmpty(data))
            {
                return;
            }

            var command = UtilityClass.StringFormat(data, args);

            if (!command.StartsWith("debug()") && !command.StartsWith("exit"))
            {
                command = "print " + command;
            }

            this.SendCommand(command);
            this.ReadResponse(resultExpected, checkForErrors);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this.disposed)
            {
                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    // Dispose managed resources.
                    if (this.telnetSocket != null && this.telnetSocket.Connected && !this.Process.HasExited)
                    {
                        try
                        {
                            Logger.LogDebug("Closing connection to chrome");
                            this.SendCommand("print window.close()");
                            this.telnetSocket.Close();
                            this.Process.WaitForExit(5000);
                        }
                        catch (IOException ex)
                        {
                            Logger.LogDebug("Error communicating with chrome to innitiate shut down, message: {0}", ex.Message);
                        }
                    }
                }

                // Call the appropriate methods to clean up
                // unmanaged resources here.
                if (this.Process != null)
                {
                    if (!this.Process.HasExited)
                    {
                        Logger.LogDebug("Closing Chrome");
                        this.Process.Kill();
                    }
                }
            }

            this.disposed = true;
            this.Connected = false;
        }

        /// <summary>
        /// Writes the specified data to the remote server.
        /// </summary>
        /// <param name="data">The data to write.</param>
        /// <param name="resultExpected"><c>true</c> if a result is expected.</param>
        /// <param name="checkForErrors"><c>true</c> if error checking should be applied.</param>
        /// <param name="args">Arguments to format with the data.</param>
        private void SendRawAndRead(string data, bool resultExpected, bool checkForErrors, params object[] args)
        {
            var command = UtilityClass.StringFormat(data, args);
            this.SendCommand(command);
            this.ReadResponse(resultExpected, checkForErrors);
        }

        /// <summary>
        /// Checks the response for an error.
        /// </summary>
        /// <param name="response">The response.</param>
        private static void CheckForError(string response)
        {
            if (string.IsNullOrEmpty(response))
            {
                return;
            }

            foreach (string knownResponseError in knownResponseErrors)
            {
                if (response.StartsWith(knownResponseError, StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new ChromeException(string.Format("Error sending last message to chrome remote server: {0}", response));
                }
            }
        }

        /// <summary>
        /// Cleans the telnet response.
        /// </summary>
        /// <param name="data">The data to clean.</param>
        /// <returns>Cleaned response data</returns>
        private string CleanTelnetResponse(string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                return string.Empty;
            }

            return data
                    .Replace(string.Format("{0}\r", this.LastCommandSend), string.Empty)
                    .Replace(string.Format("{0}v8(running)> ", Environment.NewLine), string.Empty)
                    .Replace(string.Format("{0}v8(paused)> ", Environment.NewLine), string.Empty)
                    .Trim();
        }

        /// <summary>
        /// Sends the command.
        /// </summary>
        /// <param name="data">The data to send.</param>
        private void SendCommand(string data)
        {
            if (!this.Connected)
            {
                throw new ChromeException("You must connect before writing to the server.");
            }

            this.LastCommandSend = data;
            var bytes = Encoding.ASCII.GetBytes(data + Environment.NewLine);

            Logger.LogDebug("sending: {0}", data);
            using (var networkStream = new NetworkStream(this.telnetSocket))
            {
                networkStream.Write(bytes, 0, bytes.Length);
                networkStream.Flush();
            }
        }

        /// <summary>
        /// Reads the response from the Chrome telnet server.
        /// </summary>
        /// <param name="resultExpected">if set to <c>true</c> a result is expected.</param>
        /// <param name="checkForErrors">if set to <c>true</c> check for errors.</param>
        private void ReadResponse(bool resultExpected, bool checkForErrors)
        {
            var stream = new NetworkStream(this.telnetSocket);

            this.LastResponse = string.Empty;
            this.LastResponseRaw = string.Empty;

            var bufferSize = 4096;
            var buffer = new byte[bufferSize];

            // HACK Thread.Sleep beginning of ReadResponse.
            // Problem is that if you start to read straight away we don't get all the data
            System.Threading.Thread.Sleep(100);

            string readData;
            do
            {
                var read = stream.Read(buffer, 0, bufferSize);
                readData = Encoding.UTF8.GetString(buffer, 0, read);

                Logger.LogDebug("chrome says: '{0}'", readData.Replace("\n", "[newline]"));
                this.LastResponseRaw += readData;
                this.LastResponse += this.CleanTelnetResponse(readData);
            }
            while (!readData.EndsWith("> ") && !readData.Trim().EndsWith("lost connection to tab") || stream.DataAvailable || (resultExpected && string.IsNullOrEmpty(this.LastResponse)));

            // Convert \n to newline
            if (this.LastResponse != null)
            {
                this.LastResponse = this.LastResponse.Replace("\n", Environment.NewLine);
            }

            this.Response.Append(this.LastResponse);

            if (checkForErrors)
            {
                CheckForError(this.LastResponse);
            }
        }

        /// <summary>
        /// Validates the we can connect to chrome.
        /// </summary>
        private void ValidateCanConnect()
        {
            if (this.Connected)
            {
                throw new ChromeException("Already connected to chrome session.");
            }

            if (Core.Chrome.CurrentProcessCount > 0 && !Settings.CloseExistingFireFoxInstances)
            {
                throw new ChromeException("Existing instances of FireFox detected.");
            }

            if (Core.Chrome.CurrentProcessCount > 0)
            {
                Core.Chrome.CurrentProcess.Kill();
            }
        }

        /// <summary>
        /// Waits for connection established.
        /// </summary>
        private void WaitForConnectionEstablished()
        {
            this.SendCommand("\n");

            var rawResponse = string.Empty;
            var responseToWaitFor = "Chrome>";

            while (!rawResponse.Trim().EndsWith(responseToWaitFor))
            {
                this.ReadResponse(false, true);
                rawResponse += this.LastResponseRaw;
            }

            this.SendRawAndRead("debug()", true, true);
            Debug.WriteLine(this.LastResponse);
        }
    }
}
#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen android:id="@+id/prefs" xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory
        android:title="@string/prefs_link_category">

        <EditTextPreference
            android:title="@string/prefs_link_name"
            android:defaultValue="Android"
            android:key="link.name"
            android:summary="@string/prefs_link_name_summary"/>

        <EditTextPreference
            android:title="@string/prefs_broker_url"
            android:defaultValue=""
            android:key="broker.url"
            android:summary="@string/prefs_broker_url_summary"/>
    </PreferenceCategory>

    <PreferenceCategory
        android:title="@string/prefs_control_category">
        <CheckBoxPreference
            android:title="@string/prefs_start_on_boot"
            android:defaultValue="false"
            android:key="start.on.boot"
            android:summary="@string/prefs_start_on_boot_summary"/>

        <CheckBoxPreference
            android:title="@string/prefs_stop_low_memory"
            android:defaultValue="false"
            android:key="stop.on.low.memory"
            android:summary="@string/prefs_stop_low_memory_summary"/>
    </PreferenceCategory>

    <PreferenceCategory
        android:title="Features">
        <CheckBoxPreference
            android:title="@string/android_wear"
            android:defaultValue="false"
            android:key="feature.wear"
            android:summary="@string/prefs_android_wear_summary"/>

        <CheckBoxPreference
            android:title="Fitness"
            android:defaultValue="false"
            android:key="feature.fitness"
            android:summary="Enables Fitness Support"/>
    </PreferenceCategory>

    <PreferenceCategory
        android:title="@string/prefs_nodes_category"
        android:key="nodes"/>

    <PreferenceCategory
        android:title="@string/advanced_pref_category">
        <ListPreference
            android:title="@string/location_update_type"
            android:key="advanced.location.update"
            android:defaultValue="102"
            android:entries="@array/location_update_labels"
            android:entryValues="@array/location_update_types"/>
    </PreferenceCategory>
</PreferenceScreen>


text:
<!DOCTYPE html>

    {% load staticfiles %}

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <title>AIS | BYU</title>

    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

    <link rel="shortcut icon" href="{% static 'favicon.ico' %}">

    <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700,600,800' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="{% static 'css/font-awesome.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/main.css' %} ">

                {% with url="/" %}

                        Home

                {% endwith %}
                {% with url="/about/" %}

                        About

                {% endwith %}
                {% with url="/sponsors/" %}

                        Sponsors

                {% endwith %}
                {% with url="/calendar/" %}

                        Calendar

                {% endwith %}

                        Pages +

Events

WAIS

Officers

Newsletter

                        Join

    {% block notification %}

 Work In Progress. The site is still in development so watch out for new features in the near future!

    {% endblock %}

    {% block breadcrumb %}
    {% endblock %}

    {% block slider %}
    {% endblock %}

    {% block body %}
    {% endblock %}

    {% block footer %}

Stay Connected with AIS

© 2015 | BYU Association for Information Systems

    {% endblock %}


text:
function ShippingCarrier() {
    this.id = 0;

    // the human readable identifier for this shipping carrier
    this.code = '';

    // the collection of language specific descriptors
    this.descriptors = [];

    // the name of the shipping carrier
    this.name = '';

    // a collection of shipping methods this carrier supports
    this.shippingMethods = [];

    // the status of the shipping carrier
    this.status = new Status();

    this.created = null;
    this.modified = null;
}

module.exports = ShippingCarrier;


text:
using System;
using System.Security.Cryptography;

namespace Jose
{
    public class HmacUsingSha : IJwsAlgorithm
    {
        private string hashMethod;

        public HmacUsingSha(string hashMethod)
        {
            this.hashMethod = hashMethod;
        }

        public byte[] Sign(byte[] securedInput, object key)
        {
            var sharedKey = Ensure.Type<byte[]>(key, "HmacUsingSha alg expectes key to be byte[] array.");

            using (var sha = KeyedHash(sharedKey))
            {
                return sha.ComputeHash(securedInput);
            }
        }

        public bool Verify(byte[] signature, byte[] securedInput, object key)
        {
            byte[] expected = Sign(securedInput, key);

            return Arrays.ConstantTimeEquals(signature, expected);
        }

        private KeyedHashAlgorithm KeyedHash(byte[] key)
        {
            if ("SHA256".Equals(hashMethod))
                return new HMACSHA256(key);
            if ("SHA384".Equals(hashMethod))
                return new HMACSHA384(key);
            if ("SHA512".Equals(hashMethod))
                return new HMACSHA512(key);

            throw new ArgumentException("Unsupported hashing algorithm: '{0}'", hashMethod);
        }
    }
}


text:
"""
This module provides classes and methods for working with molecular substructure
patterns. These enable molecules to be searched for common motifs (e.g.
reaction sites).

.. _atom-types:

We define the following basic atom types:

    =============== ============================================================
    Atom type       Description
    =============== ============================================================
    *General atom types*
    ----------------------------------------------------------------------------
    ``R``           any atom with any local bond structure
    ``R!H``         any non-hydrogen atom with any local bond structure
    *Carbon atom types*
    ----------------------------------------------------------------------------
    ``C``           carbon atom with any local bond structure
    ``Cs``          carbon atom with four single bonds
    ``Cd``          carbon atom with one double bond (to carbon) and two single bonds
    ``Cdd``         carbon atom with two double bonds
    ``Ct``          carbon atom with one triple bond and one single bond
    ``CO``          carbon atom with one double bond (to oxygen) and two single bonds
    ``Cb``          carbon atom with two benzene bonds and one single bond
    ``Cbf``         carbon atom with three benzene bonds
    *Hydrogen atom types*
    ----------------------------------------------------------------------------
    ``H``           hydrogen atom with one single bond
    *Oxygen atom types*
    ----------------------------------------------------------------------------
    ``O``           oxygen atom with any local bond structure
    ``Os``          oxygen atom with two single bonds
    ``Od``          oxygen atom with one double bond
    ``Oa``          oxygen atom with no bonds
    *Silicon atom types*
    ----------------------------------------------------------------------------
    ``Si``          silicon atom with any local bond structure
    ``Sis``         silicon atom with four single bonds
    ``Sid``         silicon atom with one double bond (to carbon) and two single bonds
    ``Sidd``        silicon atom with two double bonds
    ``Sit``         silicon atom with one triple bond and one single bond
    ``SiO``         silicon atom with one double bond (to oxygen) and two single bonds
    ``Sib``         silicon atom with two benzene bonds and one single bond
    ``Sibf``        silicon atom with three benzene bonds
    *Sulfur atom types*
    ----------------------------------------------------------------------------
    ``S``           sulfur atom with any local bond structure
    ``Ss``          sulfur atom with two single bonds
    ``Sd``          sulfur atom with one double bond
    ``Sa``          sulfur atom with no bonds
    =============== ============================================================

.. _bond-types:

We define the following bond types:

    =============== ============================================================
    Bond type       Description
    =============== ============================================================
    ``S``           a single bond
    ``D``           a double bond
    ``T``           a triple bond
    ``B``           a benzene bond
    =============== ============================================================

.. _reaction-recipe-actions:

We define the following reaction recipe actions:

    ============= ============================= ================================
    Action name   Arguments                     Action
    ============= ============================= ================================
    CHANGE_BOND   `center1`, `order`, `center2` change the bond order of the bond between `center1` and `center2` by `order`; do not break or form bonds
    FORM_BOND     `center1`, `order`, `center2` form a new bond between `center1` and `center2` of type `order`
    BREAK_BOND    `center1`, `order`, `center2` break the bond between `center1` and `center2`, which should be of type `order`
    GAIN_RADICAL  `center`, `radical`           increase the number of free electrons on `center` by `radical`
    LOSE_RADICAL  `center`, `radical`           decrease the number of free electrons on `center` by `radical`
    ============= ============================= ================================

"""

import cython

from graph import Vertex, Edge, Graph
from exception import ChemPyError

################################################################################

class AtomType:
    """
    A class for internal representation of atom types. Using unique objects
    rather than strings allows us to use fast pointer comparisons instead of
    slow string comparisons, as well as store extra metadata if desired.
    The attributes are:

    =================== =================== ====================================
    Attribute           Type                Description
    =================== =================== ====================================
    `label`             ``str``             A unique string label for the atom type
    =================== =================== ====================================
    """

    def __init__(self, label, generic, specific):
        self.label = label
        self.generic = generic
        self.specific = specific
        self.incrementBond = []
        self.decrementBond = []
        self.formBond = []
        self.breakBond = []
        self.incrementRadical = []
        self.decrementRadical = []

    def __repr__(self):
        return '<AtomType "%s">' % self.label

    def setActions(self, incrementBond, decrementBond, formBond, breakBond, incrementRadical, decrementRadical):
        self.incrementBond = incrementBond
        self.decrementBond = decrementBond
        self.formBond = formBond
        self.breakBond = breakBond
        self.incrementRadical = incrementRadical
        self.decrementRadical = decrementRadical

    def equivalent(self, other):
        """
        Returns ``True`` if two atom types `atomType1` and `atomType2` are
        equivalent or ``False``  otherwise. This function respects wildcards,
        e.g. ``R!H`` is equivalent to ``C``.
        """
        return self is other or self in other.specific or other in self.specific

    def isSpecificCaseOf(self, other):
        """
        Returns ``True`` if atom type `atomType1` is a specific case of
        atom type `atomType2` or ``False``  otherwise.
        """
        return self is other or self in other.specific

atomTypes = {}
atomTypes['R']    = AtomType(label='R', generic=[], specific=[
    'R!H',
    'C','Cs','Cd','Cdd','Ct','CO','Cb','Cbf',
    'H',
    'O','Os','Od','Oa',
    'Si','Sis','Sid','Sidd','Sit','SiO','Sib','Sibf',
    'S','Ss','Sd','Sa']
)
atomTypes['R!H']  = AtomType(label='R!H', generic=['R'], specific=[
    'C','Cs','Cd','Cdd','Ct','CO','Cb','Cbf',
    'O','Os','Od','Oa',
    'Si','Sis','Sid','Sidd','Sit','SiO','Sib','Sibf',
    'S','Ss','Sd','Sa']
)
atomTypes['C']    = AtomType('C', generic=['R','R!H'], specific=['Cs','Cd','Cdd','Ct','CO','Cb','Cbf'])
atomTypes['Cs']   = AtomType('Cs', generic=['R','R!H', 'C'], specific=[])
atomTypes['Cd']   = AtomType('Cd', generic=['R','R!H', 'C'], specific=[])
atomTypes['Cdd']  = AtomType('Cdd', generic=['R','R!H', 'C'], specific=[])
atomTypes['Ct']   = AtomType('Ct', generic=['R','R!H', 'C'], specific=[])
atomTypes['CO']   = AtomType('CO', generic=['R','R!H', 'C'], specific=[])
atomTypes['Cb']   = AtomType('Cb', generic=['R','R!H', 'C'], specific=[])
atomTypes['Cbf']  = AtomType('Cbf', generic=['R','R!H', 'C'], specific=[])
atomTypes['H']    = AtomType('H', generic=['R','R!H'], specific=[])
atomTypes['O']    = AtomType('O', generic=['R','R!H'], specific=['Os','Od','Oa'])
atomTypes['Os']   = AtomType('Os', generic=['R','R!H','O'], specific=[])
atomTypes['Od']   = AtomType('Od', generic=['R','R!H','O'], specific=[])
atomTypes['Oa']   = AtomType('Oa', generic=['R','R!H','O'], specific=[])
atomTypes['Si']   = AtomType('Si', generic=['R','R!H'], specific=['Sis','Sid','Sidd','Sit','SiO','Sib','Sibf'])
atomTypes['Sis']  = AtomType('Sis', generic=['R','R!H','Si'], specific=[])
atomTypes['Sid']  = AtomType('Sid', generic=['R','R!H','Si'], specific=[])
atomTypes['Sidd'] = AtomType('Sidd', generic=['R','R!H','Si'], specific=[])
atomTypes['Sit']  = AtomType('Sit', generic=['R','R!H','Si'], specific=[])
atomTypes['SiO']  = AtomType('SiO', generic=['R','R!H','Si'], specific=[])
atomTypes['Sib']  = AtomType('Sib', generic=['R','R!H','Si'], specific=[])
atomTypes['Sibf'] = AtomType('Sibf', generic=['R','R!H','Si'], specific=[])
atomTypes['S']    = AtomType('S', generic=['R','R!H'], specific=['Ss','Sd','Sa'])
atomTypes['Ss']   = AtomType('Ss', generic=['R','R!H','S'], specific=[])
atomTypes['Sd']   = AtomType('Sd', generic=['R','R!H','S'], specific=[])
atomTypes['Sa']   = AtomType('Sa', generic=['R','R!H','S'], specific=[])

atomTypes['R'   ].setActions(incrementBond=['R'],            decrementBond=['R'],         formBond=['R'],     breakBond=['R'],     incrementRadical=['R'],     decrementRadical=['R'])
atomTypes['R!H' ].setActions(incrementBond=['R!H'],          decrementBond=['R!H'],       formBond=['R!H'],   breakBond=['R!H'],   incrementRadical=['R!H'],   decrementRadical=['R!H'])

atomTypes['C'   ].setActions(incrementBond=['C'],            decrementBond=['C'],         formBond=['C'],     breakBond=['C'],     incrementRadical=['C'],     decrementRadical=['C'])
atomTypes['Cs'  ].setActions(incrementBond=['Cd','CO'],      decrementBond=[],            formBond=['Cs'],    breakBond=['Cs'],    incrementRadical=['Cs'],    decrementRadical=['Cs'])
atomTypes['Cd'  ].setActions(incrementBond=['Cdd','Ct'],     decrementBond=['Cs'],        formBond=['Cd'],    breakBond=['Cd'],    incrementRadical=['Cd'],    decrementRadical=['Cd'])
atomTypes['Cdd' ].setActions(incrementBond=[],               decrementBond=['Cd','CO'],   formBond=[],        breakBond=[],        incrementRadical=[],        decrementRadical=[])
atomTypes['Ct'  ].setActions(incrementBond=[],               decrementBond=['Cd'],        formBond=['Ct'],    breakBond=['Ct'],    incrementRadical=['Ct'],    decrementRadical=['Ct'])
atomTypes['CO'  ].setActions(incrementBond=['Cdd'],          decrementBond=['Cs'],        formBond=['CO'],    breakBond=['CO'],    incrementRadical=['CO'],    decrementRadical=['CO'])
atomTypes['Cb'  ].setActions(incrementBond=[],               decrementBond=[],            formBond=['Cb'],    breakBond=['Cb'],    incrementRadical=['Cb'],    decrementRadical=['Cb'])
atomTypes['Cbf' ].setActions(incrementBond=[],               decrementBond=[],            formBond=[],        breakBond=[],        incrementRadical=[],        decrementRadical=[])

atomTypes['H'   ].setActions(incrementBond=[],               decrementBond=[],            formBond=['H'],     breakBond=['H'],     incrementRadical=['H'],     decrementRadical=['H'])

atomTypes['O'   ].setActions(incrementBond=['O'],            decrementBond=['O'],         formBond=['O'],     breakBond=['O'],     incrementRadical=['O'],     decrementRadical=['O'])
atomTypes['Os'  ].setActions(incrementBond=['Od'],           decrementBond=[],            formBond=['Os'],    breakBond=['Os'],    incrementRadical=['Os'],    decrementRadical=['Os'])
atomTypes['Od'  ].setActions(incrementBond=[],               decrementBond=['Os'],        formBond=[],        breakBond=[],        incrementRadical=[],        decrementRadical=[])
atomTypes['Oa'  ].setActions(incrementBond=[],               decrementBond=[],            formBond=[],        breakBond=[],        incrementRadical=[],        decrementRadical=[])

atomTypes['Si'   ].setActions(incrementBond=['Si'],          decrementBond=['Si'],        formBond=['Si'],    breakBond=['Si'],    incrementRadical=['Si'],    decrementRadical=['Si'])
atomTypes['Sis'  ].setActions(incrementBond=['Sid','SiO'],   decrementBond=[],            formBond=['Sis'],   breakBond=['Sis'],   incrementRadical=['Sis'],   decrementRadical=['Sis'])
atomTypes['Sid'  ].setActions(incrementBond=['Sidd','Sit'],  decrementBond=['Sis'],       formBond=['Sid'],   breakBond=['Sid'],   incrementRadical=['Sid'],   decrementRadical=['Sid'])
atomTypes['Sidd' ].setActions(incrementBond=[],              decrementBond=['Sid','SiO'], formBond=[],        breakBond=[],        incrementRadical=[],        decrementRadical=[])
atomTypes['Sit'  ].setActions(incrementBond=[],              decrementBond=['Sid'],       formBond=['Sit'],   breakBond=['Sit'],   incrementRadical=['Sit'],   decrementRadical=['Sit'])
atomTypes['SiO'  ].setActions(incrementBond=['Sidd'],        decrementBond=['Sis'],       formBond=['SiO'],   breakBond=['SiO'],   incrementRadical=['SiO'],   decrementRadical=['SiO'])
atomTypes['Sib'  ].setActions(incrementBond=[],              decrementBond=[],            formBond=['Sib'],   breakBond=['Sib'],   incrementRadical=['Sib'],   decrementRadical=['Sib'])
atomTypes['Sibf' ].setActions(incrementBond=[],              decrementBond=[],            formBond=[],        breakBond=[],        incrementRadical=[],        decrementRadical=[])

atomTypes['S'   ].setActions(incrementBond=['S'],            decrementBond=['S'],         formBond=['S'],     breakBond=['S'],     incrementRadical=['S'],     decrementRadical=['S'])
atomTypes['Ss'  ].setActions(incrementBond=['Sd'],           decrementBond=[],            formBond=['Ss'],    breakBond=['Ss'],    incrementRadical=['Ss'],    decrementRadical=['Ss'])
atomTypes['Sd'  ].setActions(incrementBond=[],               decrementBond=['Ss'],        formBond=[],        breakBond=[],        incrementRadical=[],        decrementRadical=[])
atomTypes['Sa'  ].setActions(incrementBond=[],               decrementBond=[],            formBond=[],        breakBond=[],        incrementRadical=[],        decrementRadical=[])

for atomType in atomTypes.values():
    for items in [atomType.generic, atomType.specific,
      atomType.incrementBond, atomType.decrementBond, atomType.formBond,
      atomType.breakBond, atomType.incrementRadical, atomType.decrementRadical]:
        for index in range(len(items)):
            items[index] = atomTypes[items[index]]

def getAtomType(atom, bonds):
    """
    Determine the appropriate atom type for an :class:`Atom` object `atom`
    with local bond structure `bonds`, a ``dict`` containing atom-bond pairs.
    """

    cython.declare(atomType=str)
    cython.declare(double=cython.double, double0=cython.double, triple=cython.double, benzene=cython.double)

    atomType = ''

    # Count numbers of each higher-order bond type
    double = 0; doubleO = 0; triple = 0; benzene = 0
    for atom2, bond12 in bonds.iteritems():
        if bond12.isDouble():
            if atom2.isOxygen(): doubleO +=1
            else:                double += 1
        elif bond12.isTriple(): triple += 1
        elif bond12.isBenzene(): benzene += 1

    # Use element and counts to determine proper atom type
    if atom.symbol == 'C':
        if   double == 0 and doubleO == 0 and triple == 0 and benzene == 0: atomType = 'Cs'
        elif double == 1 and doubleO == 0 and triple == 0 and benzene == 0: atomType = 'Cd'
        elif double + doubleO == 2        and triple == 0 and benzene == 0: atomType = 'Cdd'
        elif double == 0 and doubleO == 0 and triple == 1 and benzene == 0: atomType = 'Ct'
        elif double == 0 and doubleO == 1 and triple == 0 and benzene == 0: atomType = 'CO'
        elif double == 0 and doubleO == 0 and triple == 0 and benzene == 2: atomType = 'Cb'
        elif double == 0 and doubleO == 0 and triple == 0 and benzene == 3: atomType = 'Cbf'
    elif atom.symbol == 'H':
        atomType = 'H'
    elif atom.symbol == 'O':
        if   double + doubleO == 0 and triple == 0 and benzene == 0: atomType = 'Os'
        elif double + doubleO == 1 and triple == 0 and benzene == 0: atomType = 'Od'
        elif len(bonds) == 0:                                        atomType = 'Oa'
    elif atom.symbol == 'Si':
        if   double == 0 and doubleO == 0 and triple == 0 and benzene == 0: atomType = 'Sis'
        elif double == 1 and doubleO == 0 and triple == 0 and benzene == 0: atomType = 'Sid'
        elif double + doubleO == 2        and triple == 0 and benzene == 0: atomType = 'Sidd'
        elif double == 0 and doubleO == 0 and triple == 1 and benzene == 0: atomType = 'Sit'
        elif double == 0 and doubleO == 1 and triple == 0 and benzene == 0: atomType = 'SiO'
        elif double == 0 and doubleO == 0 and triple == 0 and benzene == 2: atomType = 'Sib'
        elif double == 0 and doubleO == 0 and triple == 0 and benzene == 3: atomType = 'Sibf'
    elif atom.symbol == 'S':
        if   double + doubleO == 0 and triple == 0 and benzene == 0: atomType = 'Ss'
        elif double + doubleO == 1 and triple == 0 and benzene == 0: atomType = 'Sd'
        elif len(bonds) == 0:                                        atomType = 'Sa'
    elif atom.symbol == 'N' or atom.symbol == 'Ar' or atom.symbol == 'He' or atom.symbol == 'Ne':
        return None

    # Raise exception if we could not identify the proper atom type
    if atomType == '':
        raise ChemPyError('Unable to determine atom type for atom %s.' % atom)

    return atomTypes[atomType]

################################################################################

class AtomPattern(Vertex):
    """
    An atom pattern. This class is based on the :class:`Atom` class, except that
    it uses :ref:`atom types <atom-types>` instead of elements, and all
    attributes are lists rather than individual values. The attributes are:

    =================== =================== ====================================
    Attribute           Type                Description
    =================== =================== ====================================
    `atomType`          ``list``            The allowed atom types (as strings)
    `radicalElectrons`  ``list``            The allowed numbers of radical electrons (as short integers)
    `spinMultiplicity`  ``list``            The allowed spin multiplicities (as short integers)
    `charge`            ``list``            The allowed formal charges (as short integers)
    `label`             ``str``             A string label that can be used to tag individual atoms
    =================== =================== ====================================

    Each list represents a logical OR construct, i.e. an atom will match the
    pattern if it matches *any* item in the list. However, the
    `radicalElectrons`, `spinMultiplicity`, and `charge` attributes are linked
    such that an atom must match values from the same index in each of these in
    order to match. Unlike an :class:`Atom` object, an :class:`AtomPattern`
    cannot store implicit hydrogen atoms.
    """

    def __init__(self, atomType=None, radicalElectrons=None, spinMultiplicity=None, charge=None, label=''):
        Vertex.__init__(self)
        self.atomType = atomType or []
        for index in range(len(self.atomType)):
            if isinstance(self.atomType[index], str):
                self.atomType[index] = atomTypes[self.atomType[index]]
        self.radicalElectrons = radicalElectrons or []
        self.spinMultiplicity = spinMultiplicity or []
        self.charge = charge or []
        self.label = label

    def __str__(self):
        """
        Return a human-readable string representation of the object.
        """
        return "<AtomPattern '%s'>" % (self.atomType)

    def __repr__(self):
        """
        Return a representation that can be used to reconstruct the object.
        """
        return "AtomPattern(atomType=%s, radicalElectrons=%s, spinMultiplicity=%s, charge=%s, label='%s')" % (self.atomType, self.radicalElectrons, self.spinMultiplicity, self.charge, self.label)

    def copy(self):
        """
        Return a deep copy of the :class:`AtomPattern` object. Modifying the
        attributes of the copy will not affect the original.
        """
        return AtomPattern(self.atomType[:], self.radicalElectrons[:], self.spinMultiplicity[:], self.charge[:], self.label)

    def __changeBond(self, order):
        """
        Update the atom pattern as a result of applying a CHANGE_BOND action,
        where `order` specifies whether the bond is incremented or decremented
        in bond order, and should be 1 or -1.
        """
        atomType = []
        for atom in self.atomType:
            if order == 1:
                atomType.extend(atom.incrementBond)
            elif order == -1:
                atomType.extend(atom.decrementBond)
            else:
                raise ChemPyError('Unable to update AtomPattern due to CHANGE_BOND action: Invalid order "%g".' % order)
        if len(atomType) == 0:
            raise ChemPyError('Unable to update AtomPattern due to CHANGE_BOND action: Unknown atom type produced from set "%s".' % (self.atomType))
        # Set the new atom types, removing any duplicates
        self.atomType = list(set(atomType))

    def __formBond(self, order):
        """
        Update the atom pattern as a result of applying a FORM_BOND action,
        where `order` specifies the order of the forming bond, and should be
        'S' (since we only allow forming of single bonds).
        """
        if order != 'S':
            raise ChemPyError('Unable to update AtomPattern due to FORM_BOND action: Invalid order "%s".' % order)
        atomType = []
        for atom in self.atomType:
            atomType.extend(atom.formBond)
        if len(atomType) == 0:
            raise ChemPyError('Unable to update AtomPattern due to FORM_BOND action: Unknown atom type produced from set "%s".' % (self.atomType))
        # Set the new atom types, removing any duplicates
        self.atomType = list(set(atomType))

    def __breakBond(self, order):
        """
        Update the atom pattern as a result of applying a BREAK_BOND action,
        where `order` specifies the order of the breaking bond, and should be
        'S' (since we only allow breaking of single bonds).
        """
        if order != 'S':
            raise ChemPyError('Unable to update AtomPattern due to BREAK_BOND action: Invalid order "%s".' % order)
        atomType = []
        for atom in self.atomType:
            atomType.extend(atom.breakBond)
        if len(atomType) == 0:
            raise ChemPyError('Unable to update AtomPattern due to BREAK_BOND action: Unknown atom type produced from set "%s".' % (self.atomType))
        # Set the new atom types, removing any duplicates
        self.atomType = list(set(atomType))

    def __gainRadical(self, radical):
        """
        Update the atom pattern as a result of applying a GAIN_RADICAL action,
        where `radical` specifies the number of radical electrons to add.
        """
        radicalElectrons = []
        spinMultiplicity = []
        for electron, spin in zip(self.radicalElectrons, self.spinMultiplicity):
            radicalElectrons.append(electron + radical)
            spinMultiplicity.append(spin + radical)
        # Set the new radical electron counts and spin multiplicities
        self.radicalElectrons = radicalElectrons
        self.spinMultiplicity = spinMultiplicity

    def __loseRadical(self, radical):
        """
        Update the atom pattern as a result of applying a LOSE_RADICAL action,
        where `radical` specifies the number of radical electrons to remove.
        """
        radicalElectrons = []
        spinMultiplicity = []
        for electron, spin in zip(self.radicalElectrons, self.spinMultiplicity):
            if electron - radical < 0:
                raise ChemPyError('Unable to update AtomPattern due to LOSE_RADICAL action: Invalid radical electron set "%s".' % (self.radicalElectrons))
            radicalElectrons.append(electron - radical)
            if spin - radical < 0:
                spinMultiplicity.append(spin - radical + 2)
            else:
                spinMultiplicity.append(spin - radical)
        # Set the new radical electron counts and spin multiplicities
        self.radicalElectrons = radicalElectrons
        self.spinMultiplicity = spinMultiplicity

    def applyAction(self, action):
        """
        Update the atom pattern as a result of applying `action`, a tuple
        containing the name of the reaction recipe action along with any
        required parameters. The available actions can be found
        :ref:`here <reaction-recipe-actions>`.
        """
        if action[0].upper() == 'CHANGE_BOND':
            self.__changeBond(action[2])
        elif action[0].upper() == 'FORM_BOND':
            self.__formBond(action[2])
        elif action[0].upper() == 'BREAK_BOND':
            self.__breakBond(action[2])
        elif action[0].upper() == 'GAIN_RADICAL':
            self.__gainRadical(action[2])
        elif action[0].upper() == 'LOSE_RADICAL':
            self.__loseRadical(action[2])
        else:
            raise ChemPyError('Unable to update AtomPattern: Invalid action %s".' % (action))

    def equivalent(self, other):
        """
        Returns ``True`` if `other` is equivalent to `self` or ``False`` if not,
        where `other` can be either an :class:`Atom` or an :class:`AtomPattern`
        object. When comparing two :class:`AtomPattern` objects, this function
        respects wildcards, e.g. ``R!H`` is equivalent to ``C``.
        """

        if not isinstance(other, AtomPattern):
            # Let the equivalent method of other handle it
            # We expect self to be an Atom object, but can't test for it here
            # because that would create an import cycle
            return other.equivalent(self)

        # Compare two atom patterns for equivalence
        # Each atom type in self must have an equivalent in other (and vice versa)
        for atomType1 in self.atomType:
            for atomType2 in other.atomType:
                if atomType1.equivalent(atomType2): break
            else:
                return False
        for atomType1 in other.atomType:
            for atomType2 in self.atomType:
                if atomType1.equivalent(atomType2): break
            else:
                return False
        # Each free radical electron state in self must have an equivalent in other (and vice versa)
        for radical1, spin1 in zip(self.radicalElectrons, self.spinMultiplicity):
            for radical2, spin2 in zip(other.radicalElectrons, other.spinMultiplicity):
                if radical1 == radical2 and spin1 == spin2: break
            else:
                return False
        for radical1, spin1 in zip(other.radicalElectrons, other.spinMultiplicity):
            for radical2, spin2 in zip(self.radicalElectrons, self.spinMultiplicity):
                if radical1 == radical2 and spin1 == spin2: break
            else:
                return False
        # Otherwise the two atom patterns are equivalent
        return True

    def isSpecificCaseOf(self, other):
        """
        Returns ``True`` if `other` is the same as `self` or is a more
        specific case of `self`. Returns ``False`` if some of `self` is not
        included in `other` or they are mutually exclusive.
        """

        if not isinstance(other, AtomPattern):
            # Let the isSpecificCaseOf method of other handle it
            # We expect self to be an Atom object, but can't test for it here
            # because that would create an import cycle
            return other.isSpecificCaseOf(self)

        # Compare two atom patterns for equivalence
        # Each atom type in self must have an equivalent in other (and vice versa)
        for atomType1 in self.atomType: # all these must match
            for atomType2 in other.atomType: # can match any of these
                if atomType1.isSpecificCaseOf(atomType2): break
            else:
                return False
        # Each free radical electron state in self must have an equivalent in other (and vice versa)
        for radical1, spin1 in zip(self.radicalElectrons, self.spinMultiplicity): # all these must match
            for radical2, spin2 in zip(other.radicalElectrons, other.spinMultiplicity): # can match any of these
                if radical1 == radical2 and spin1 == spin2: break
            else:
                return False
        # Otherwise self is in fact a specific case of other
        return True

################################################################################

class BondPattern(Edge):
    """
    A bond pattern. This class is based on the :class:`Bond` class, except that
    all attributes are lists rather than individual values. The allowed bond
    types are given :ref:`here <bond-types>`. The attributes are:

    =================== =================== ====================================
    Attribute           Type                Description
    =================== =================== ====================================
    `order`             ``list``            The allowed bond orders (as character strings)
    =================== =================== ====================================

    Each list represents a logical OR construct, i.e. a bond will match the
    pattern if it matches *any* item in the list.
    """

    def __init__(self, order=None):
        Edge.__init__(self)
        self.order = order or []

    def __str__(self):
        """
        Return a human-readable string representation of the object.
        """
        return "<BondPattern %s>" % (self.order)

    def __repr__(self):
        """
        Return a representation that can be used to reconstruct the object.
        """
        return "BondPattern(order=%s)" % (self.order)

    def copy(self):
        """
        Return a deep copy of the :class:`BondPattern` object. Modifying the
        attributes of the copy will not affect the original.
        """
        return BondPattern(self.order[:])

    def __changeBond(self, order):
        """
        Update the bond pattern as a result of applying a CHANGE_BOND action,
        where `order` specifies whether the bond is incremented or decremented
        in bond order, and should be 1 or -1.
        """
        newOrder = []
        for bond in self.order:
            if order == 1:
                if bond == 'S':         newOrder.append('D')
                elif bond == 'D':       newOrder.append('T')
                else:
                    raise ChemPyError('Unable to update BondPattern due to CHANGE_BOND action: Invalid bond order "%s" in set %s".' % (bond, self.order))
            elif order == -1:
                if bond == 'D':         newOrder.append('S')
                elif bond == 'T':       newOrder.append('D')
                else:
                    raise ChemPyError('Unable to update BondPattern due to CHANGE_BOND action: Invalid bond order "%s" in set %s".' % (bond, self.order))
            else:
                raise ChemPyError('Unable to update BondPattern due to CHANGE_BOND action: Invalid order "%g".' % order)
        # Set the new bond orders, removing any duplicates
        self.order = list(set(newOrder))

    def applyAction(self, action):
        """
        Update the bond pattern as a result of applying `action`, a tuple
        containing the name of the reaction recipe action along with any
        required parameters. The available actions can be found
        :ref:`here <reaction-recipe-actions>`.
        """
        if action[0].upper() == 'CHANGE_BOND':
            self.__changeBond(action[2])
        else:
            raise ChemPyError('Unable to update BondPattern: Invalid action %s".' % (action))

    def equivalent(self, other):
        """
        Returns ``True`` if `other` is equivalent to `self` or ``False`` if not,
        where `other` can be either an :class:`Bond` or an :class:`BondPattern`
        object.
        """

        if not isinstance(other, BondPattern):
            # Let the equivalent method of other handle it
            # We expect self to be a Bond object, but can't test for it here
            # because that would create an import cycle
            return other.equivalent(self)

        # Compare two bond patterns for equivalence
        # Each atom type in self must have an equivalent in other (and vice versa)
        for order1 in self.order:
            for order2 in other.order:
                if order1 == order2: break
            else:
                return False
        for order1 in other.order:
            for order2 in self.order:
                if order1 == order2: break
            else:
                return False
        # Otherwise the two bond patterns are equivalent
        return True

    def isSpecificCaseOf(self, other):
        """
        Returns ``True`` if `other` is the same as `self` or is a more
        specific case of `self`. Returns ``False`` if some of `self` is not
        included in `other` or they are mutually exclusive.
        """

        if not isinstance(other, BondPattern):
            # Let the isSpecificCaseOf method of other handle it
            # We expect self to be a Bond object, but can't test for it here
            # because that would create an import cycle
            return other.isSpecificCaseOf(self)

        # Compare two bond patterns for equivalence
        # Each atom type in self must have an equivalent in other
        for order1 in self.order: # all these must match
            for order2 in other.order: # can match any of these
                if order1 == order2: break
            else:
                return False
        # Otherwise self is in fact a specific case of other
        return True

################################################################################

class MoleculePattern(Graph):
    """
    A representation of a molecular substructure pattern using a graph data
    type, extending the :class:`Graph` class. The `atoms` and `bonds` attributes
    are aliases for the `vertices` and `edges` attributes, and store
    :class:`AtomPattern` and :class:`BondPattern` objects, respectively.
    Corresponding alias methods have also been provided.
    """

    def __init__(self, atoms=None, bonds=None):
        Graph.__init__(self, atoms, bonds)

    def __getAtoms(self): return self.vertices
    def __setAtoms(self, atoms): self.vertices = atoms
    atoms = property(__getAtoms, __setAtoms)

    def __getBonds(self): return self.edges
    def __setBonds(self, bonds): self.edges = bonds
    bonds = property(__getBonds, __setBonds)

    def addAtom(self, atom):
        """
        Add an `atom` to the graph. The atom is initialized with no bonds.
        """
        return self.addVertex(atom)

    def addBond(self, atom1, atom2, bond):
        """
        Add a `bond` to the graph as an edge connecting the two atoms `atom1`
        and `atom2`.
        """
        return self.addEdge(atom1, atom2, bond)

    def getBonds(self, atom):
        """
        Return a list of the bonds involving the specified `atom`.
        """
        return self.getEdges(atom)

    def getBond(self, atom1, atom2):
        """
        Returns the bond connecting atoms `atom1` and `atom2`.
        """
        return self.getEdge(atom1, atom2)

    def hasAtom(self, atom):
        """
        Returns ``True`` if `atom` is an atom in the graph, or ``False`` if
        not.
        """
        return self.hasVertex(atom)

    def hasBond(self, atom1, atom2):
        """
        Returns ``True`` if atoms `atom1` and `atom2` are connected
        by an bond, or ``False`` if not.
        """
        return self.hasEdge(atom1, atom2)

    def removeAtom(self, atom):
        """
        Remove `atom` and all bonds associated with it from the graph. Does
        not remove atoms that no longer have any bonds as a result of this
        removal.
        """
        return self.removeVertex(atom)

    def removeBond(self, atom1, atom2):
        """
        Remove the bond between atoms `atom1` and `atom2` from the graph.
        Does not remove atoms that no longer have any bonds as a result of
        this removal.
        """
        return self.removeEdge(atom1, atom2)

    def sortAtoms(self):
        """
        Sort the atoms in the graph. This can make certain operations, e.g.
        the isomorphism functions, much more efficient.
        """
        return self.sortVertices()

    def copy(self, deep=False):
        """
        Create a copy of the current graph. If `deep` is ``True``, a deep copy
        is made: copies of the vertices and edges are used in the new graph.
        If `deep` is ``False`` or not specified, a shallow copy is made: the
        original vertices and edges are used in the new graph.
        """
        other = cython.declare(MoleculePattern)
        g = Graph.copy(self, deep)
        other = MoleculePattern(g.vertices, g.edges)
        return other

    def merge(self, other):
        """
        Merge two patterns so as to store them in a single
        :class:`MoleculePattern` object. The merged :class:`MoleculePattern`
        object is returned.
        """
        g = Graph.merge(self, other)
        molecule = MoleculePattern(atoms=g.vertices, bonds=g.edges)
        return molecule

    def split(self):
        """
        Convert a single :class:`MoleculePattern` object containing two or more
        unconnected patterns into separate class:`MoleculePattern` objects.
        """
        graphs = Graph.split(self)
        molecules = []
        for g in graphs:
            molecule = MoleculePattern(atoms=g.vertices, bonds=g.edges)
            molecules.append(molecule)
        return molecules

    def clearLabeledAtoms(self):
        """
        Remove the labels from all atoms in the molecular pattern.
        """
        for atom in self.vertices:
            atom.label = ''

    def containsLabeledAtom(self, label):
        """
        Return ``True`` if the pattern contains an atom with the label
        `label` and ``False`` otherwise.
        """
        for atom in self.vertices:
            if atom.label == label: return True
        return False

    def getLabeledAtom(self, label):
        """
        Return the atoms in the pattern that are labeled.
        """
        for atom in self.vertices:
            if atom.label == label: return atom
        return None

    def getLabeledAtoms(self):
        """
        Return the labeled atoms as a ``dict`` with the keys being the labels
        and the values the atoms themselves. If two or more atoms have the
        same label, the value is converted to a list of these atoms.
        """
        labeled = {}
        for atom in self.vertices:
            if atom.label != '':
                if atom.label in labeled:
                    labeled[atom.label] = [labeled[atom.label]]
                    labeled[atom.label].append(atom)
                else:
                    labeled[atom.label] = atom
        return labeled

    def fromAdjacencyList(self, adjlist, withLabel=True):
        """
        Convert a string adjacency list `adjlist` to a molecular structure.
        Skips the first line (assuming it's a label) unless `withLabel` is
        ``False``.
        """
        self.vertices, self.edges = fromAdjacencyList(adjlist, pattern=True, addH=False, withLabel=withLabel)
        self.updateConnectivityValues()
        return self

    def toAdjacencyList(self, label=''):
        """
        Convert the molecular structure to a string adjacency list.
        """
        return toAdjacencyList(self, label='', pattern=True)

    def isIsomorphic(self, other, initialMap=None):
        """
        Returns ``True`` if two graphs are isomorphic and ``False``
        otherwise. The `initialMap` attribute can be used to specify a required
        mapping from `self` to `other` (i.e. the atoms of `self` are the keys,
        while the atoms of `other` are the values). The `other` parameter must
        be a :class:`MoleculePattern` object, or a :class:`TypeError` is raised.
        """
        # It only makes sense to compare a MoleculePattern to a MoleculePattern for full
        # isomorphism, so raise an exception if this is not what was requested
        if not isinstance(other, MoleculePattern):
            raise TypeError('Got a %s object for parameter "other", when a MoleculePattern object is required.' % other.__class__)
        # Do the isomorphism comparison
        return Graph.isIsomorphic(self, other, initialMap)

    def findIsomorphism(self, other, initialMap=None):
        """
        Returns ``True`` if `other` is isomorphic and ``False``
        otherwise, and the matching mapping. The `initialMap` attribute can be
        used to specify a required mapping from `self` to `other` (i.e. the
        atoms of `self` are the keys, while the atoms of `other` are the
        values). The returned mapping also uses the atoms of `self` for the keys
        and the atoms of `other` for the values. The `other` parameter must
        be a :class:`MoleculePattern` object, or a :class:`TypeError` is raised.
        """
        # It only makes sense to compare a MoleculePattern to a MoleculePattern for full
        # isomorphism, so raise an exception if this is not what was requested
        if not isinstance(other, MoleculePattern):
            raise TypeError('Got a %s object for parameter "other", when a MoleculePattern object is required.' % other.__class__)
        # Do the isomorphism comparison
        return Graph.findIsomorphism(self, other, initialMap)

    def isSubgraphIsomorphic(self, other, initialMap=None):
        """
        Returns ``True`` if `other` is subgraph isomorphic and ``False``
        otherwise. The `initialMap` attribute can be used to specify a required
        mapping from `self` to `other` (i.e. the atoms of `self` are the keys,
        while the atoms of `other` are the values). The `other` parameter must
        be a :class:`MoleculePattern` object, or a :class:`TypeError` is raised.
        """
        # It only makes sense to compare a MoleculePattern to a MoleculePattern for subgraph
        # isomorphism, so raise an exception if this is not what was requested
        if not isinstance(other, MoleculePattern):
            raise TypeError('Got a %s object for parameter "other", when a MoleculePattern object is required.' % other.__class__)
        # Do the isomorphism comparison
        return Graph.isSubgraphIsomorphic(self, other, initialMap)

    def findSubgraphIsomorphisms(self, other, initialMap=None):
        """
        Returns ``True`` if `other` is subgraph isomorphic and ``False``
        otherwise. Also returns the lists all of valid mappings. The
        `initialMap` attribute can be used to specify a required mapping from
        `self` to `other` (i.e. the atoms of `self` are the keys, while the
        atoms of `other` are the values). The returned mappings also use the
        atoms of `self` for the keys and the atoms of `other` for the values.
        The `other` parameter must be a :class:`MoleculePattern` object, or a
        :class:`TypeError` is raised.
        """
        # It only makes sense to compare a MoleculePattern to a MoleculePattern for subgraph
        # isomorphism, so raise an exception if this is not what was requested
        if not isinstance(other, MoleculePattern):
            raise TypeError('Got a %s object for parameter "other", when a MoleculePattern object is required.' % other.__class__)
        # Do the isomorphism comparison
        return Graph.findSubgraphIsomorphisms(self, other, initialMap)

################################################################################

class InvalidAdjacencyListError(Exception):
    """
    An exception used to indicate that an RMG-style adjacency list is invalid.
    Pass a string giving specifics about the particular exceptional behavior.
    """
    pass

def fromAdjacencyList(adjlist, pattern=False, addH=False, withLabel=True):
    """
    Convert a string adjacency list `adjlist` into a set of :class:`Atom` and
    :class:`Bond` objects (if `pattern` is ``False``) or a set of
    :class:`AtomPattern` and :class:`BondPattern` objects (if `pattern` is
    ``True``). Only adds hydrogen atoms if `addH` is ``True``. Skips the first
    line (assuming it's a label) unless `withLabel` is ``False``.
    """

    from molecule import Atom, Bond

    atoms = []; atomdict = {}; bonds = {}

    lines = adjlist.splitlines()
    # Skip the first line if it contains a label
    if withLabel: label = lines.pop(0)
    # Iterate over the remaining lines, generating Atom or AtomPattern objects
    for line in lines:

        data = line.split()

        # Skip if blank line
        if len(data) == 0: continue

        # First item is index for atom
        # Sometimes these have a trailing period (as if in a numbered list),
        # so remove it just in case
        aid = int(data[0].strip('.'))

        # If second item starts with '*', then atom is labeled
        label = ''; index = 1
        if data[1][0] == '*':
            label = data[1]; index = 2

        # Next is the element or functional group element
        # A list can be specified with the {,} syntax
        atomType = data[index]
        if atomType[0] == '{':
            atomType = atomType[1:-1].split(',')
        else:
            atomType = [atomType]

        # Next is the electron state
        radicalElectrons = []; spinMultiplicity = []
        elecState = data[index+1].upper()
        if elecState[0] == '{':
            elecState = elecState[1:-1].split(',')
        else:
            elecState = [elecState]
        for e in elecState:
            if e == '0':
                radicalElectrons.append(0); spinMultiplicity.append(1)
            elif e == '1':
                radicalElectrons.append(1); spinMultiplicity.append(2)
            elif e == '2':
                radicalElectrons.append(2); spinMultiplicity.append(1)
                radicalElectrons.append(2); spinMultiplicity.append(3)
            elif e == '2S':
                radicalElectrons.append(2); spinMultiplicity.append(1)
            elif e == '2T':
                radicalElectrons.append(2); spinMultiplicity.append(3)
            elif e == '3':
                radicalElectrons.append(3); spinMultiplicity.append(4)
            elif e == '4':
                radicalElectrons.append(4); spinMultiplicity.append(5)

        # Create a new atom based on the above information
        if pattern:
            atom = AtomPattern(atomType, radicalElectrons, spinMultiplicity, [0 for e in radicalElectrons], label)
        else:
            atom = Atom(atomType[0], radicalElectrons[0], spinMultiplicity[0], 0, 0, label)

        # Add the atom to the list
        atoms.append(atom)
        atomdict[aid] = atom

        # Process list of bonds
        bonds[atom] = {}
        for datum in data[index+2:]:

            # Sometimes commas are used to delimit bonds in the bond list,
            # so strip them just in case
            datum = datum.strip(',')

            aid2, comma, order = datum[1:-1].partition(',')
            aid2 = int(aid2)

            if order[0] == '{':
                order = order[1:-1].split(',')
            else:
                order = [order]

            if aid2 in atomdict:
                if pattern:
                    bond = BondPattern(order)
                else:
                    bond = Bond(order[0])
                bonds[atom][atomdict[aid2]] = bond
                bonds[atomdict[aid2]][atom] = bond

    # Check consistency using bonddict
    for atom1 in bonds:
        for atom2 in bonds[atom1]:
            if atom2 not in bonds:
                raise ChemPyError(label)
            elif atom1 not in bonds[atom2]:
                raise ChemPyError(label)
            elif bonds[atom1][atom2] != bonds[atom2][atom1]:
                raise ChemPyError(label)

    # Add explicit hydrogen atoms to complete structure if desired
    if addH and not pattern:
        valences = {'H': 1, 'C': 4, 'O': 2}
        orders = {'S': 1, 'D': 2, 'T': 3, 'B': 1.5}
        newAtoms = []
        for atom in atoms:
            try:
                valence = valences[atom.symbol]
            except KeyError:
                raise ChemPyError('Cannot add hydrogens to adjacency list: Unknown valence for atom "%s".' % atom.symbol)
            radical = atom.radicalElectrons
            order = 0
            for atom2, bond in bonds[atom].iteritems():
                order += orders[bond.order]
            count = valence - radical - int(order)
            for i in range(count):
                a = Atom('H', 0, 1, 0, 0, '')
                b = Bond('S')
                newAtoms.append(a)
                bonds[atom][a] = b
                bonds[a] = {atom: b}
        atoms.extend(newAtoms)

    return atoms, bonds

def toAdjacencyList(molecule, label='', pattern=False, removeH=False):
    """
    Convert the `molecule` object to an adjacency list. `pattern` specifies
    whether the graph object is a complete molecule (if ``False``) or a
    substructure pattern (if ``True``). The `label` parameter is an optional
    string to put as the first line of the adjacency list; if set to the empty
    string, this line will be omitted. If `removeH` is ``True``, hydrogen atoms
    (that do not have labels) will not be printed; this is a valid shorthand,
    as they can usually be inferred as long as the free electron numbers are
    accurate.
    """

    adjlist = ''

    if label != '': adjlist += label + '\n'

    molecule.updateConnectivityValues() # so we can sort by them
    atoms = molecule.atoms
    bonds = molecule.bonds

    for i, atom in enumerate(atoms):
        if removeH and atom.isHydrogen() and atom.label=='': continue

        # Atom number
        adjlist += '%-2d ' % (i+1)

        # Atom label
        adjlist += "%-2s " % (atom.label)

        if pattern:
            # Atom type(s)
            if len(atom.atomType) == 1:
                adjlist += atom.atomType[0].label + ' '
            else:
                adjlist += '{%s} ' % (','.join([a.label for a in atom.atomType]))
            # Electron state(s)
            if len(atom.radicalElectrons) > 1: adjlist += '{'
            for radical, spin in zip(atom.radicalElectrons, atom.spinMultiplicity):
                if radical == 0: adjlist += '0'
                elif radical == 1: adjlist += '1'
                elif radical == 2 and spin == 1: adjlist += '2S'
                elif radical == 2 and spin == 3: adjlist += '2T'
                elif radical == 3: adjlist += '3'
                elif radical == 4: adjlist += '4'
                if len(atom.radicalElectrons) > 1: adjlist += ','
            if len(atom.radicalElectrons) > 1: adjlist = adjlist[0:-1] + '}'
        else:
            # Atom type
            adjlist += "%-5s " % atom.symbol
            # Electron state(s)
            if atom.radicalElectrons == 0: adjlist += '0'
            elif atom.radicalElectrons == 1: adjlist += '1'
            elif atom.radicalElectrons == 2 and atom.spinMultiplicity == 1: adjlist += '2S'
            elif atom.radicalElectrons == 2 and atom.spinMultiplicity == 3: adjlist += '2T'
            elif atom.radicalElectrons == 3: adjlist += '3'
            elif atom.radicalElectrons == 4: adjlist += '4'

        # Bonds list
        atoms2 = bonds[atom].keys()
        # sort them the same way as the atoms
        #atoms2.sort(key=atoms.index)

        for atom2 in atoms2:
            if removeH and atom2.isHydrogen(): continue
            bond = bonds[atom][atom2]
            adjlist += ' {' + str(atoms.index(atom2)+1) + ','

            # Bond type(s)
            if pattern:
                if len(bond.order) == 1:
                    adjlist += bond.order[0]
                else:
                    adjlist += '{%s}' % (','.join(bond.order))
            else:
                adjlist += bond.order
            adjlist += '}'

        # Each atom begins on a new line
        adjlist += '\n'

    return adjlist


text:
namespace Stumps.Server.Data
{
    using System.Collections.Generic;

    /// <summary>
    ///     A class that provides the foundation for persisted HTTP requests and responses.
    /// </summary>
    public abstract class HttpContextPartEntity
    {
        /// <summary>
        ///     Gets or sets the name of the resource containing the body.
        /// </summary>
        /// <value>
        ///     The name of the resource containing the body.
        /// </value>
        public string BodyResourceName
        {
            get;
            set;
        }

        /// <summary>
        ///     Gets or sets the collection of HTTP headers.
        /// </summary>
        /// <value>
        ///     The collection of HTTP headers.
        /// </value>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Entity is only for persistence.")]
        public IList<NameValuePairEntity> Headers
        {
            get;
            set;
        }
    }
}


text:
import argparse
import requests
import sys
import traceback
from pathlib import Path

home = str(Path.home())
parser = argparse.ArgumentParser(
  description='Get github license info from github APIs.')
parser.add_argument(
  'repo_list',
  nargs='?',
  default='repo.txt',
  help=
  'GitHub repo list file with one line per github repo. Format: org/repo. (default: %(default)s)',
)
parser.add_argument(
  '-o',
  '--output',
  dest='output_file',
  nargs='?',
  default='license_info.csv',
  help=
  'Output file with one line per github repo. Line format: '
  +'org/repo,license_html_url,license_name,license_download_url. (default: %(default)s)',
)
parser.add_argument(
  '--github-api-token-file',
  dest='github_api_token_file',
  default='{}/.github_api_token'.format(home),
  help='You need to create a github personal access token at https://github.com/settings/tokens, '
  +'because github has very strict limit on anonymous API usage. (default: %(default)s) Format: a '
  +'text file with one line. '
  +'"<40 characters string shown when a new personal access token is created>"'
)
args = parser.parse_args()

def main():
  token = None
  try:
    with open(args.github_api_token_file, 'r') as token_file:
      token = token_file.read().strip()
      print('Read github API token from {}, length {}.'.format(
        args.github_api_token_file, len(token)),
          file=sys.stderr)
  except FileNotFoundError:
    raise Exception((
        'Please put a github api token file at {}, or specify a different token file path by '
        +'--github-api-token-file. GitHub API token is needed because anonymous API access limit '
        +'is not enough.'
      ).format(args.github_api_token_file))

  # github personal access token is always 40 characters long
  assert len(token) == 40
  # reference: https://developer.github.com/v3/#oauth2-token-sent-in-a-header
  headers = {'Authorization': 'token {}'.format(token)}
  with open(args.repo_list,
          'r') as repo_list_file, open(args.output_file,
                                          'w') as output_file:
    repo_succeeded = []
    repo_failed = []
    for repo in repo_list_file:
      repo = repo.strip()
      print('Fetching license for {}'.format(repo), file=sys.stderr)
      try:
        url = 'https://api.github.com/repos/{}/license'.format(repo)
        response = requests.get(url, headers=headers)
        if not response.ok:
          print('Error response content:\n{}'.format(response.content), file=sys.stderr)
          raise Exception('fetching {} failed with {} {}'.format(
              url, response.status_code, response.reason))
        data = response.json()

        download_url = data['download_url']
        license_name = data['license']['name']
        html_url = data['html_url']
        print('{},{},{},{}'.format(repo, html_url, license_name, download_url), file=output_file)
        repo_succeeded.append(repo)
      except Exception as e: # pylint: disable=broad-except
        print('[failed]', e, file=sys.stderr)
        traceback.print_exc(file=sys.stderr)
        repo_failed.append(repo)
    print('Fetched github license info, {} succeeded, {} failed.'.format(
      len(repo_succeeded), len(repo_failed)), file=sys.stderr)
    if repo_failed:
      print('The following repos failed:', file=sys.stderr)
      for repo in repo_failed:
        print(repo, file=sys.stderr)

if __name__ == '__main__':
  main()


text:
namespace df {

template <typename Scalar>
pangolin::OpenGlMatrixSpec ProjectionMatrixRDF_TopLeft(const CameraBase<Scalar> & camera,
                                                       const Scalar zNear, const Scalar zFar);

template <typename Scalar>
pangolin::OpenGlMatrixSpec ProjectionMatrixRDF_BottomLeft(const CameraBase<Scalar> & camera,
                                                          const Scalar zNear, const Scalar zFar);

} // namespace df


text:
import {
  DocumentReference,
  Firestore,
  GeoPoint,
  Timestamp,
  doc,
} from 'firebase/firestore';

import {
  FieldType,
  FirestoreAny,
  FirestoreArray,
  FirestoreMap,
  FirestorePrimitive,
} from '../models';
import {
  ArrayChildren,
  DocumentPath,
  Fields,
  MapChildren,
  PrimitiveValue,
  Store,
  assertStoreHasRoot,
  isArrayField,
  isFirestoreArray,
  isFirestoreMap,
  isMapField,
} from './types';

let uuid = 0;
export function getUniqueId() {
  return uuid++;
}

function normalizeMap(data: FirestoreMap): Store {
  const uuid = getUniqueId();

  // reducer over object.entries -> childFields
  const children = Object.entries(data).reduce(
    (
      { mapChildren, fields }: { mapChildren: MapChildren; fields: Fields },
      [name, value]: [string, FirestoreAny]
    ) => {
      const child = normalize(value);
      assertStoreHasRoot(child);
      mapChildren.push({
        uuid: getUniqueId(),
        name,
        valueId: child.uuid,
      });
      return { mapChildren, fields: { ...fields, ...child.fields } };
    },
    { mapChildren: [], fields: {} }
  );
  return {
    uuid,
    fields: {
      ...children.fields,
      // add item for current node
      [uuid]: { mapChildren: children.mapChildren },
    },
  };
}

function normalizeArray(data: FirestoreArray): Store {
  const uuid = getUniqueId();

  // reducer over array elements -> childFields
  const children = data.reduce(
    (
      {
        arrayChildren,
        fields,
      }: { arrayChildren: ArrayChildren; fields: Fields },
      value: FirestoreMap | FirestorePrimitive
    ) => {
      const child = normalize(value);
      assertStoreHasRoot(child);
      arrayChildren.push({
        uuid: getUniqueId(),
        valueId: child.uuid,
      });
      return { arrayChildren, fields: { ...fields, ...child.fields } };
    },
    { arrayChildren: [], fields: {} }
  );
  return {
    uuid,
    fields: {
      ...children.fields,
      // add item for current node
      [uuid]: { arrayChildren: children.arrayChildren },
    },
  };
}

function normalizePrimitive(data: FirestorePrimitive): Store {
  const uuid = getUniqueId();

  if (data instanceof DocumentReference) {
    return {
      uuid,
      fields: { [uuid]: { value: new DocumentPath(data.path) } },
    };
  }
  return { uuid, fields: { [uuid]: { value: data } } };
}

export function normalize(data: FirestoreAny): Store {
  if (isFirestoreMap(data)) {
    return normalizeMap(data);
  } else if (isFirestoreArray(data)) {
    return normalizeArray(data);
  } else {
    return normalizePrimitive(data);
  }
}

export function denormalize(store: Store, firestore?: Firestore): FirestoreAny {
  assertStoreHasRoot(store);
  const field = store.fields[store.uuid];
  if (isMapField(field)) {
    return field.mapChildren.reduce((acc, curr) => {
      if (!curr.name) {
        // Skip fields with empty name (not allowed by Firestore SDK anyway).
        return acc;
      }
      acc[curr.name] = denormalize(
        {
          uuid: curr.valueId,
          fields: store.fields,
        },
        firestore
      );
      return acc;
    }, {} as any);
  } else if (isArrayField(field)) {
    return field.arrayChildren.reduce((acc, curr) => {
      acc.push(
        denormalize({ uuid: curr.valueId, fields: store.fields }, firestore)
      );
      return acc;
    }, [] as any);
  } else {
    if (field.value instanceof DocumentPath) {
      if (!firestore) {
        // TODO: Trying to reference a Firestore Document without a Firestore instance.
        return '';
      }
      try {
        return doc(firestore, field.value.path);
      } catch {
        // TODO: The store does not always have a valid DocRef, reconsider.
        return '';
      }
    }
    return field.value;
  }
}

export function defaultValueForPrimitiveType(type: FieldType): PrimitiveValue {
  switch (type) {
    case FieldType.BLOB:
      // TODO
      return '';
    case FieldType.BOOLEAN:
      return true;
    case FieldType.GEOPOINT:
      return new GeoPoint(0, 0);
    case FieldType.NULL:
      return null;
    case FieldType.NUMBER:
      return 0;
    case FieldType.REFERENCE:
      return new DocumentPath('');
    case FieldType.STRING:
      return '';
    case FieldType.TIMESTAMP:
      return Timestamp.fromDate(new Date());
  }
  return '';
}

export function getDescendantIds(fields: Fields, ids: number[]): number[] {
  return ids.reduce((acc, id) => {
    acc.push(id);
    const field = fields[id];
    if (isMapField(field)) {
      acc.push(
        ...getDescendantIds(
          fields,
          field.mapChildren.map((c) => c.valueId)
        )
      );
    } else if (isArrayField(field)) {
      acc.push(
        ...getDescendantIds(
          fields,
          field.arrayChildren.map((c) => c.valueId)
        )
      );
    }
    return acc;
  }, [] as number[]);
}


text:
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var EwsServiceJsonReader_1 = require("../EwsServiceJsonReader");
var FolderInfo_1 = require("../ServiceObjects/Folders/FolderInfo");
var EwsLogging_1 = require("../EwsLogging");
var XmlElementNames_1 = require("../XmlElementNames");
var ServiceResponse_1 = require("./ServiceResponse");
var GetFolderResponse = (function (_super) {
    __extends(GetFolderResponse, _super);
    function GetFolderResponse(folder, propertySet) {
        _super.call(this);
        this.folder = folder;
        this.propertySet = propertySet;
        EwsLogging_1.EwsLogging.Assert(this.propertySet != null, "GetFolderResponse.ctor", "PropertySet should not be null");
    }
    Object.defineProperty(GetFolderResponse.prototype, "Folder", {
        get: function () { return this.folder; },
        enumerable: true,
        configurable: true
    });
    GetFolderResponse.prototype.GetObjectInstance = function (service, xmlElementName) {
        if (this.Folder != null) {
            return this.Folder;
        }
        else {
            var flinfo = new FolderInfo_1.FolderInfo();
            return flinfo.CreateEwsObjectFromXmlElementName(service, xmlElementName);
        }
    };
    GetFolderResponse.prototype.ReadElementsFromXmlJsObject = function (responseObject, service) {
        if (responseObject[XmlElementNames_1.XmlElementNames.Folders]) {
            var folders = EwsServiceJsonReader_1.EwsServiceJsonReader.ReadServiceObjectsCollectionFromJson(responseObject, service, XmlElementNames_1.XmlElementNames.Folders, this.GetObjectInstance.bind(this), true, /* clearPropertyBag */ this.propertySet, /* requestedPropertySet */ false); /* summaryPropertiesOnly */
            this.folder = folders[0];
        }
    };
    return GetFolderResponse;
}(ServiceResponse_1.ServiceResponse));
exports.GetFolderResponse = GetFolderResponse;