text:
kube-template
===============

Inspired by HashiCorp's [Consul Template][], `kube-template` is a utility that queries a [Kubernetes][] API server and uses its objects as input data for specified set of templates. Also it can run arbitrary commands for templates with updated output.

**Please note this is a work in progress.**

[![Build Status](https://travis-ci.org/3cky/kube-template.svg?branch=master)](https://travis-ci.org/3cky/kube-template)

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

Go 1.13+ is required to build `kube-template`. Check your version with `go version` before build.
- `git pull https://github.com/3cky/kube-template.git`
- `cd kube-template`
- `make install`

Docker

If you want to create a Docker image
- adjust Dockerfile in contrib/docker directory to fit your needs
- configure settings files in contrib/docker/conf directory
- issue `make docker`

Note - the built image is already configured to automatically locate Kubernetes API along with everything is needed to connect (e.g. Certificate Authority file, security token and so on).

Usage
-----

### Options

```
      --alsologtostderr                  log to standard error as well as files
      --command-timeout duration         Default command execution timeout (0 to execute commands without timeout checking) (default 15s)
  -c, --config string                    config file (default is ./kube-template.(yaml|json))
      --dry-run                          don't write template output, dump result to stdout
      --guess-kube-api-settings          guess Kubernetes API settings from POD environment
      --help-md                          get help in Markdown format
  -k, --kube-config string               Kubernetes config file to use
  -l, --left-delimiter string            templating left delimiter (default "{{")
      --log-backtrace-at traceLocation   when logging hits line file:N, emit a stack trace (default :0)
      --log-dir string                   If non-empty, write log files in this directory
      --log-flush-frequency duration     Maximum number of seconds between log flushes (default 5s)
      --logtostderr                      log to standard error instead of files (default true)
      --master string                    Kubernetes API server address (default is http://127.0.0.1:8080/)
      --once                             run template processing once and exit
  -p, --poll-period duration             Kubernetes API server poll period (0 disables server polling) (default 15s)
  -r, --right-delimiter string           templating right delimiter (default "}}")
      --stderrthreshold severity         logs at or above this threshold go to stderr (default 2)
  -t, --template stringSlice             adds a new template to watch on disk in the format
		'templatePath:outputPath[:command]'. This option is additive
		and may be specified multiple times for multiple templates
  -v, --v Level                          log level for V logs
      --version                          display the version number and build timestamp
      --vmodule moduleSpec               comma-separated list of pattern=N settings for file-filtered logging
```

### Command Line

Process single template using data from remote Kubernetes API server and exit:

```shell
$ kube-template \
    --master="http://kube-api.server.com:8080" \
    --template="/tmp/input.tmpl:/tmp/output.txt" \
    --once
```

Monitor local Kubernetes API server for updates every 30 seconds and update nginx and haproxy configuration files with reload:

```shell
$ kube-template \
    --template="/tmp/nginx.tmpl:/etc/nginx/nginx.conf:service nginx reload" \
    --template="/tmp/haproxy.tmpl:/etc/haproxy/haproxy.conf:service haproxy reload" \
    --poll-time=30s
```

### Configuration File

`kube-template` looks for `kube-template.json` or `kube-template.yaml` configuration file in current working directory or file name specified by `--config` command line option.

 YAML configuration file example:

```yaml
 master: http://localhost:8080
 poll-period: 10s
 command-timeout: 30s

 templates:
   - path: in.txt.tmpl
     output: out.txt
     command: action.sh
     command-timeout: 60s

   - path: in.html.tmpl
     output: out.html
```

___Please note___: templates specified on the command line take precedence over those defined in a config file.

### Signals

- **TERM, QUIT, INT:** graceful shutdown
- **HUP:** reload configuration file

### Templating Language

`kube-template` works with templates in the [Go Template][] format. In addition to the [standard template functions][Go Template], `kube-template` provides the following functions:

#### Kubernetes API

##### `pods`
```
{{pods "selector" "namespace"}}
```
Query Kubernetes API server for [pods](https://kubernetes.io/docs/concepts/workloads/pods/pod/) from given `namespace` (`default` if not specified) matching given `selector` (empty to get all pods).

Example:
```
{{range pods}}
{{.Name}}: {{.Status.Phase}}
{{end}}
```

##### `services`
```
{{services "selector" "namespace"}}
```
Query Kubernetes API server for [services](https://kubernetes.io/docs/concepts/services-networking/service/) from given `namespace` (`default` if not specified) matching given `selector` (empty to get all services).

##### `replicationcontrollers`
```
{{replicationcontrollers "selector" "namespace"}}
```
Query Kubernetes API server for [replication controllers](https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller/) from given `namespace` (`default` if not specified) matching given `selector` (empty to get all replication controllers).

##### `events`
```
{{events "selector" "namespace"}}
```
Query Kubernetes API server for events from given `namespace` (`default` if not specified) matching given `selector` (empty to get all events).

##### `endpoints`
```
{{endpoints "selector" "namespace"}}
```
Query Kubernetes API server for endpoints from given `namespace` (`default` if not specified) matching given `selector` (empty to get all endpoints).

##### `nodes`
```
{{nodes "selector"}}
```
Query Kubernetes API server for nodes matching given `selector` (empty to get all nodes).

##### `namespaces`
```
{{namespaces "selector"}}
```
Query Kubernetes API server for namespaces matching given `selector` (empty to get all namespaces).

##### `componentstatuses`
```
{{componentstatuses "selector"}}
```
Query Kubernetes API server for component statuses matching given `selector` (empty to get all componentstatuses).

##### `configmaps`
```
{{configmaps "selector" "namespace"}}
```
Query Kubernetes API server for config maps from given `namespace` (`default` if not specified) matching given `selector` (empty to get all configmaps).

##### `limitranges`
```
{{limitranges "selector" "namespace"}}
```
Query Kubernetes API server for limit ranges from given `namespace` (`default` if not specified) matching given `selector` (empty to get all limitranges).

##### `persistentvolumes`
```
{{persistentvolumes "selector"}}
```
Query Kubernetes API server for persistent volumes matching given `selector` (empty to get all persistentvolumes).

##### `persistentvolumeclaims`
```
{{persistentvolumeclaims "selector" "namespace"}}
```
Query Kubernetes API server for persistent volume claims from given `namespace` (`default` if not specified) matching given `selector` (empty to get all persistentvolumeclaims).

##### `podtemplates`
```
{{podtemplates "selector" "namespace"}}
```
Query Kubernetes API server for pod templates from given `namespace` (`default` if not specified) matching given `selector` (empty to get all podtemplates).

##### `resourcequotas`
```
{{resourcequotas "selector" "namespace"}}
```
Query Kubernetes API server for resource quotas from given `namespace` (`default` if not specified) matching given `selector` (empty to get all resourcequotas).

##### `secrets`
```
{{secrets "selector" "namespace"}}
```
Query Kubernetes API server for secrets from given `namespace` (`default` if not specified) matching given `selector` (empty to get all secrets).

##### `serviceaccounts`
```
{{serviceaccounts "selector" "namespace"}}
```
Query Kubernetes API server for service accounts from given `namespace` (`default` if not specified) matching given `selector` (empty to get all serviceaccounts).
- - -

#### Helper Functions

All [Sprig library](http://masterminds.github.io/sprig/) template functions (string/math/date/etc) are supported (thanks @bpineau).

### EXAMPLES
Populate nginx upstream with pods labeled 'name=test-pod':
```
upstream test-pod-upstream {
{{with $pods := pods "name=test-pod"}}
    ip_hash;
    {{range $pods}}
    server {{.Status.PodIP}}:8080;
    {{end}}
{{else}}
    # No pods with given label were found, use stub server
    server 127.0.0.1:8081;
{{end}}
}
```

Create haproxy TCP balancer for pods listening on container port 9000:
```
{{with $pods := pods "name=test-pod"}}
{{$maxconn := 1000}}
listen test-pod-balancer
    bind *:9000
    mode tcp
    maxconn {{mul $maxconn (len $pods)}}
    balance roundrobin
    {{range $pods}}
    server {{.Name}} {{.Status.PodIP}}:9000 maxconn {{$maxconn}} check inter 5000 rise 3 fall 3
    {{end}}
    server stub 127.0.0.1:7690 backup
{{end}}
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## License

`kube-template` is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/3cky/kube-template/blob/master/LICENSE.txt)

[Kubernetes]: http://kubernetes.io/ "Manage a cluster of Linux containers as a single system to accelerate Dev and simplify Ops"
[Consul Template]: https://github.com/hashicorp/consul-template "A convenient way to populate values from Consul into the filesystem using the consul-template daemon"
[Go Template]: http://golang.org/pkg/text/template/ "Go Template"
[Go vendor tool]: https://github.com/kardianos/govendor "Go vendor tool that works with the standard vendor file."


text:
export {default as formatDefaultLocale, format, formatPrefix} from "./defaultLocale.js";
export {default as formatLocale} from "./locale.js";
export {default as formatSpecifier, FormatSpecifier} from "./formatSpecifier.js";
export {default as precisionFixed} from "./precisionFixed.js";
export {default as precisionPrefix} from "./precisionPrefix.js";
export {default as precisionRound} from "./precisionRound.js";

redpajama_set_name: RedPajamaGithub


text:
============
Installation
============

Before you start
================

A basic Wagtail setup can be installed on your machine with only a few prerequisites - see `A basic Wagtail installation`_. However, there are various optional components that will improve the performance and feature set of Wagtail, and our recommended software stack includes the PostgreSQL database, ElasticSearch (for free-text searching), the OpenCV library (for image feature detection), and Redis (as a cache and message queue backend). This would be a lot to install in one go, and for this reason, we provide a virtual machine image, for use with `Vagrant <http://www.vagrantup.com/>`__, with all of these components ready installed.

Whether you just want to try out the demo site, or you're ready to dive in and create a Wagtail site with all bells and whistles enabled, we strongly recommend the Vagrant approach. Nevertheless, if you're the sort of person who balks at the idea of downloading a whole operating system just to run a web app, we've got you covered too. Start from `A basic Wagtail installation`_ below.

The demo site (a.k.a. the no-installation route)
================================================

We provide a demo site containing a set of standard templates and page types - if you're new to Wagtail, this is the best way to try it out and familiarise yourself with how Wagtail works from the point of view of an editor.

If you're happy to use Vagrant, and you just want to set up the Wagtail demo site, or any other pre-existing Wagtail site that ships with Vagrant support, you don't need to install Wagtail at all. Install `Vagrant <http://www.vagrantup.com/>`__ and `VirtualBox <https://www.virtualbox.org/>`__, and run::

    git clone https://github.com/torchbox/wagtaildemo.git
    cd wagtaildemo
    vagrant up
    vagrant ssh

Then, within the SSH session::

    ./manage.py createsuperuser
    ./manage.py runserver 0.0.0.0:8000

This will make the demo site available on your host machine at the URL http://localhost:8111/ - you can access the Wagtail admin interface at http://localhost:8111/admin/ . Further instructions can be found at :ref:`editor_manual`.

Once you've experimented with the demo site and are ready to build your own site, it's time to install Wagtail on your host machine. Even if you intend to do all further Wagtail work within Vagrant, installing the Wagtail package on your host machine will provide the ``wagtail start`` command that sets up the initial file structure for your project.

A basic Wagtail installation
============================

This provides everything you need to create a new Wagtail project from scratch, containing no page definitions or templates other than a basic homepage as a starting point for building your site. (For a gentler introduction to Wagtail, you may wish to try out the demo site first!)

You will need Python's `pip <http://pip.readthedocs.org/en/latest/installing.html>`__ package manager. We also recommend `virtualenvwrapper <http://virtualenvwrapper.readthedocs.org/en/latest/>`_ so that you can manage multiple independent Python environments for different projects - although this is not strictly necessary if you intend to do all your development under Vagrant.

Wagtail is based on the Django web framework and various other Python libraries. Most of these are pure Python and will install automatically using ``pip``, but there are a few native-code components that require further attention:

 * libsass-python (for compiling SASS stylesheets) - requires a C++ compiler and the Python development headers.
 * Pillow (for image processing) - additionally requires libjpeg and zlib.

On Debian or Ubuntu, these can be installed with the command::

    sudo apt-get install python-dev python-pip g++ libjpeg62-dev zlib1g-dev

With these dependencies installed, Wagtail can then be installed with the command::

    pip install wagtail

(or if you're not using virtualenvwrapper: ``sudo pip install wagtail``.)

You will now be able to run the following command to set up an initial file structure for your Wagtail project (replace ``myprojectname`` with a name of your choice)::

    wagtail start myprojectname

**Without Vagrant:** Run the following steps to complete setup of your project (the ``migrate`` step will prompt you to set up a superuser account)::

    cd myprojectname
    pip install -r requirements.txt
    python manage.py syncdb
    python manage.py migrate
    python manage.py runserver

Your site is now accessible at http://localhost:8000, with the admin backend available at http://localhost:8000/admin/ .

**With Vagrant:** Run the following steps to bring up the virtual machine and complete setup of your project (the ``createsuperuser`` step will prompt you to set up a superuser account)::

    cd myprojectname
    vagrant up
    vagrant ssh
    ./manage.py createsuperuser
    ./manage.py runserver 0.0.0.0:8000

Your site is now accessible at http://localhost:8111, with the admin backend available at http://localhost:8111/admin/ .

Optional extras
===============

For the best possible performance and feature set, we recommend setting up the following components. If you're using Vagrant, these are provided as part of the virtual machine image and just need to be enabled in the settings for your project. If you're using Wagtail without Vagrant, this will involve additional installation.

PostgreSQL
----------
PostgreSQL is a mature database engine suitable for production use, and is recommended by the Django development team. Non-Vagrant users will need to install the PostgreSQL development headers in addition to Postgres itself; on Debian or Ubuntu, this can be done with the following command::

    sudo apt-get install postgresql postgresql-server-dev-all

To enable Postgres for your project, uncomment the ``psycopg2`` line from your project's requirements.txt, and in ``myprojectname/settings/base.py``, uncomment the DATABASES section for PostgreSQL, commenting out the SQLite one instead. Then run::

    pip install -r requirements.txt
    createdb -Upostgres myprojectname
    ./manage.py syncdb
    ./manage.py migrate

This assumes that your PostgreSQL instance is configured to allow you to connect as the 'postgres' user - if not, you'll need to adjust the ``createdb`` line and the database settings in settings/base.py accordingly.

ElasticSearch
-------------
Wagtail integrates with ElasticSearch to provide full-text searching of your content, both within the Wagtail interface and on your site's front-end. If ElasticSearch is not available, Wagtail will fall back to much more basic search functionality using database queries. ElasticSearch is pre-installed as part of the Vagrant virtual machine image; non-Vagrant users can use the `debian.sh <https://github.com/torchbox/wagtail/blob/master/scripts/install/debian.sh>`__ or `ubuntu.sh <https://github.com/torchbox/wagtail/blob/master/scripts/install/ubuntu.sh>`__ installation scripts as a guide.

To enable ElasticSearch for your project, uncomment the ``elasticsearch`` line from your project's requirements.txt, and in ``myprojectname/settings/base.py``, uncomment the WAGTAILSEARCH_BACKENDS section. Then run::

    pip install -r requirements.txt
    ./manage.py update_index

Image feature detection
-----------------------
Wagtail can use the OpenCV computer vision library to detect faces and other features in images, and use this information to select the most appropriate centre point when cropping the image. OpenCV is pre-installed as part of the Vagrant virtual machine image, and Vagrant users can enable this by setting ``WAGTAILIMAGES_FEATURE_DETECTION_ENABLED`` to True in ``myprojectname/settings/base.py``. For installation outside of Vagrant, see :ref:`image_feature_detection`.

Alternative installation methods
================================

Ubuntu
------

If you have a fresh instance of Ubuntu 13.04 or later, you can install Wagtail,
along with a demonstration site containing a set of standard templates and page
types, in one step. As the root user::

  curl -O https://wagtail.io/ubuntu.sh; bash ubuntu.sh

This script installs all the dependencies for a production-ready Wagtail site,
including PostgreSQL, Redis, Elasticsearch, Nginx and uwsgi. We
recommend you check through the script before running it, and adapt it according
to your deployment preferences. The canonical version is at
`github.com/torchbox/wagtail/blob/master/scripts/install/ubuntu.sh
<https://github.com/torchbox/wagtail/blob/master/scripts/install/ubuntu.sh>`_.

Debian
------

If you have a fresh instance of Debian 7, you can install Wagtail, along with a
demonstration site containing a set of standard templates and page types, in one
step. As the root user::

  curl -O https://wagtail.io/debian.sh; bash debian.sh

This script installs all the dependencies for a production-ready Wagtail site,
including PostgreSQL, Redis, Elasticsearch, Nginx and uwsgi. We
recommend you check through the script before running it, and adapt it according
to your deployment preferences. The canonical version is at
`github.com/torchbox/wagtail/blob/master/scripts/install/debian.sh
<https://github.com/torchbox/wagtail/blob/master/scripts/install/debian.sh>`_.

Docker
------

`@oyvindsk <https://github.com/oyvindsk>`_ has built a Dockerfile for the Wagtail demo. Simply run::

	docker run -p 8000:8000 -d oyvindsk/wagtail-demo

then access the site at http://your-ip:8000 and the admin
interface at http://your-ip:8000/admin using admin / test.

See https://index.docker.io/u/oyvindsk/wagtail-demo/ for more details.


text:
package org.apache.ivyde.internal.eclipse.retrieve;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.ivyde.eclipse.cp.RetrieveSetup;
import org.apache.ivyde.eclipse.cp.SettingsSetup;
import org.eclipse.core.resources.IProject;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class StandaloneRetrieveSerializer {

    private static final String ROOT = "setuplist";

    private static final String SETUP = "setup";

    private static final String SETUP_NAME = "name";

    private static final String IVYSETTINGS = "ivysettings";

    private static final String IVYSETTING_PATH = "path";

    private static final String IVYSETTING_LOADONDEMAND = "loadondemand";

    private static final String IVY_USER_DIR = "ivyUserDir";

    private static final String PROPERTYFILE = "propertyfile";

    private static final String PROPERTYFILE_PATH = "path";

    private static final String IVYXML = "ivyxml";

    private static final String IVYXML_PATH = "path";

    private static final String RETRIEVE = "retrieve";

    private static final String RETRIEVE_SYNC = "sync";

    private static final String RETRIEVE_TYPES = "types";

    private static final String RETRIEVE_CONFS = "confs";

    private static final String RETRIEVE_PATTERN = "pattern";

    private static final String RESOLVE_IN_WORKSPACE = "resolveInWorkspace";

    public void write(OutputStream out, List<StandaloneRetrieveSetup> setuplist)
            throws IOException {
        try {
            StreamResult result = new StreamResult(out);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();

            Node root = document.createElement(ROOT);
            document.appendChild(root);

            for (StandaloneRetrieveSetup setup : setuplist) {

                Node node = document.createElement(SETUP);
                root.appendChild(node);
                NamedNodeMap attributes = node.getAttributes();
                Attr attr = document.createAttribute(SETUP_NAME);
                attr.setValue(setup.getName());
                attributes.setNamedItem(attr);

                attr = document.createAttribute(RESOLVE_IN_WORKSPACE);
                attr.setValue(Boolean.toString(setup.isResolveInWorkspace()));
                attributes.setNamedItem(attr);

                if (setup.isSettingProjectSpecific()) {
                    Node settingsNode = document.createElement(IVYSETTINGS);
                    node.appendChild(settingsNode);
                    writeSettingsSetup(document, settingsNode, setup.getSettingsSetup());
                }

                Node ivyxmlNode = document.createElement(IVYXML);
                node.appendChild(ivyxmlNode);
                writeIvyXmlPath(document, ivyxmlNode, setup.getIvyXmlPath());

                Node retrieveNode = document.createElement(RETRIEVE);
                node.appendChild(retrieveNode);
                writeRetrieveSetup(document, retrieveNode, setup.getRetrieveSetup());
            }

            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            DOMSource source = new DOMSource(document);

            transformer.transform(source, result);

        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (TransformerException e) {
            if (e.getException() instanceof IOException) {
                throw (IOException) e.getException();
            }
            throw new IOException(e.getMessage(), e);
        }
    }

    private void writeSettingsSetup(Document document, Node settingsNode,
            SettingsSetup settingsSetup) {
        NamedNodeMap attributes = settingsNode.getAttributes();

        Attr attr = document.createAttribute(IVYSETTING_PATH);
        attr.setValue(settingsSetup.getRawIvySettingsPath());
        attributes.setNamedItem(attr);

        attr = document.createAttribute(IVYSETTING_LOADONDEMAND);
        attr.setValue(Boolean.toString(settingsSetup.isLoadSettingsOnDemand()));
        attributes.setNamedItem(attr);

        attr = document.createAttribute(IVY_USER_DIR);
        attr.setValue(settingsSetup.getRawIvyUserDir());
        attributes.setNamedItem(attr);

        for (String file : settingsSetup.getRawPropertyFiles()) {
            Node pathNode = document.createElement(PROPERTYFILE);
            settingsNode.appendChild(pathNode);
            attributes = pathNode.getAttributes();
            attr = document.createAttribute(PROPERTYFILE_PATH);
            attr.setValue(file);
            attributes.setNamedItem(attr);
        }
    }

    private void writeIvyXmlPath(Document document, Node ivyxmlNode, String ivyXmlPath) {
        NamedNodeMap attributes = ivyxmlNode.getAttributes();
        Attr attr = document.createAttribute(IVYXML_PATH);
        attr.setValue(ivyXmlPath);
        attributes.setNamedItem(attr);
    }

    private void writeRetrieveSetup(Document document, Node retrieveNode,
            RetrieveSetup retrieveSetup) {
        NamedNodeMap attributes = retrieveNode.getAttributes();

        Attr attr = document.createAttribute(RETRIEVE_PATTERN);
        attr.setValue(retrieveSetup.getRetrievePattern());
        attributes.setNamedItem(attr);

        attr = document.createAttribute(RETRIEVE_CONFS);
        attr.setValue(retrieveSetup.getRetrieveConfs());
        attributes.setNamedItem(attr);

        attr = document.createAttribute(RETRIEVE_TYPES);
        attr.setValue(retrieveSetup.getRetrieveTypes());
        attributes.setNamedItem(attr);

        attr = document.createAttribute(RETRIEVE_SYNC);
        attr.setValue(Boolean.toString(retrieveSetup.isRetrieveSync()));
        attributes.setNamedItem(attr);
    }

    public List<StandaloneRetrieveSetup> read(InputStream in, IProject project)
            throws IOException {
        try {
            InputSource source = new InputSource(in);

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder parser = factory.newDocumentBuilder();
            Document document = parser.parse(source);

            NodeList elements = document.getElementsByTagName(SETUP);

            List<StandaloneRetrieveSetup> setupList = new ArrayList<>();

            int count = elements.getLength();
            for (int i = 0; i != count; i++) {
                Node node = elements.item(i);

                StandaloneRetrieveSetup setup = new StandaloneRetrieveSetup();
                setup.setProject(project);

                NamedNodeMap attributes = node.getAttributes();
                setup.setName(getAttribute(attributes, SETUP_NAME));

                Node attr = attributes.getNamedItem(RESOLVE_IN_WORKSPACE);
                if (attr != null) {
                    setup.setResolveInWorkspace(Boolean.valueOf(attr.getNodeValue()));
                }

                NodeList children = node.getChildNodes();
                for (int j = 0; j < children.getLength(); j++) {
                    Node item = children.item(j);
                    switch (item.getNodeName()) {
                        case IVYSETTINGS:
                            SettingsSetup settingsSetup = readSettingsSetup(item);
                            setup.setSettingsSetup(settingsSetup);
                            setup.setSettingsProjectSpecific(true);
                            break;
                        case IVYXML:
                            String ivyXmlPath = readIvyXmlPath(item);
                            setup.setIvyXmlPath(ivyXmlPath);
                            break;
                        case RETRIEVE:
                            RetrieveSetup retrieveSetup = readRetrieveSetup(item);
                            setup.setRetrieveSetup(retrieveSetup);
                            break;
                    }
                }

                setupList.add(setup);
            }
            return setupList;
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (SAXException e) {
            Throwable t = e.getCause();
            if (t instanceof IOException) {
                throw (IOException) t;
            }
            if (t == null) {
                t = e;
            }
            throw new IOException(t.getMessage(), t);
        }

    }

    private String getAttribute(NamedNodeMap attributes, String name) throws SAXException {
        Node node = attributes.getNamedItem(name);
        if (node == null) {
            throw new SAXException("Attribute '" + name + "' not found");
        }
        return node.getNodeValue();
    }

    private SettingsSetup readSettingsSetup(Node node) throws SAXException {
        NamedNodeMap attributes = node.getAttributes();

        SettingsSetup settingsSetup = new SettingsSetup();

        String path = getAttribute(attributes, IVYSETTING_PATH);
        settingsSetup.setIvySettingsPath(path);

        String loadOnDemand = getAttribute(attributes, IVYSETTING_LOADONDEMAND);
        settingsSetup.setLoadSettingsOnDemand(Boolean.valueOf(loadOnDemand));

        String ivyUserDir = getAttribute(attributes, IVY_USER_DIR);
        settingsSetup.setIvyUserDir(ivyUserDir);

        List<String> propertyFiles = new ArrayList<>();

        NodeList children = node.getChildNodes();
        for (int j = 0; j != children.getLength(); j++) {
            Node item = children.item(j);
            if (item.getNodeName().equals(PROPERTYFILE)) {
                attributes = item.getAttributes();

                path = getAttribute(attributes, PROPERTYFILE_PATH);
                propertyFiles.add(path);
            }
        }

        settingsSetup.setPropertyFiles(propertyFiles);

        return settingsSetup;
    }

    private String readIvyXmlPath(Node node) throws SAXException {
        NamedNodeMap attributes = node.getAttributes();
        return getAttribute(attributes, IVYXML_PATH);
    }

    private RetrieveSetup readRetrieveSetup(Node node) throws SAXException {
        NamedNodeMap attributes = node.getAttributes();

        RetrieveSetup retrieveSetup = new RetrieveSetup();

        String pattern = getAttribute(attributes, RETRIEVE_PATTERN);
        retrieveSetup.setRetrievePattern(pattern);

        String confs = getAttribute(attributes, RETRIEVE_CONFS);
        retrieveSetup.setRetrieveConfs(confs);

        String types = getAttribute(attributes, RETRIEVE_TYPES);
        retrieveSetup.setRetrieveTypes(types);

        String sync = getAttribute(attributes, RETRIEVE_SYNC);
        retrieveSetup.setRetrieveSync(Boolean.valueOf(sync));

        return retrieveSetup;
    }

}


text:
<?php
  $options = getopt('b:w:r:v:o:h', [
    'base-url:',
    'wordlist:',
    'response-codes:',
    'verb:',
    'option:',
    'help',
    ]);

  if (array_key_exists('h', $options) || array_key_exists('help', $options)) {
    echo "PHP URL Fuzzer\n";
    echo "\n";
    echo "Usage: php url-fuzzer.php --base-url [base-url] --wordlist [path-to-wordlist] --response-codes [response-codes] --help\n";
    echo "-b, --base-url: Base URL to fuzz against.  Use the string 'FUZZ' where words from the word list need to be inserted.\n";
    echo "-w, --word-list: Word list to fuzz.\n";
    echo "-r, --response-codes: Response codes to return results for.\n";
    echo "-v, --verb: Which HTTP Verb to use.  Defaults to GET.\n";
    echo "-o, --body: Request body to use.\n";
    echo "-h, --help: Show this menu.\n";
    echo "\n";

    exit();
  }

  $baseUrl = '';
  $wordListPath = '';
  $responseCodes = [];
  $verb = 'GET';
  $body = '';

  if (array_key_exists('base-url', $_GET)) {
    $baseUrl = $_GET['base-url'];
  } else if (array_key_exists('b', $options)) {
    $baseUrl = $options['b'];
  } else if (array_key_exists('base-url', $options)) {
    $baseUrl = $options['base-url'];
  }

  if (array_key_exists('wordlist', $_GET)) {
      $wordListPath = $_GET['wordlist'];
  } else if (array_key_exists('w', $options)) {
      $wordListPath = $options['w'];
  } else if (array_key_exists('wordlist', $options)) {
      $wordListPath = $options['wordlist'];
  }

  if (array_key_exists('response-codes', $_GET)) {
      $responseCodes = split(',', $_GET['response-codes']);
  } else if (array_key_exists('r', $options)) {
      $responseCodes = split(',', $options['r']);
  } else if (array_key_exists('response-codes', $options)) {
      $responseCodes = split(',', $options['response-codes']);
  }

  if (array_key_exists('verb', $_GET)) {
      $verb = $_GET['verb'];
  } else if (array_key_exists('v', $options)) {
    $verb = $options['v'];
  } else if (array_key_exists('verb', $options)) {
      $verb = $options['verb'];
  }

  if (array_key_exists('body', $_GET)) {
    $body = $_GET['body'];
  } else if (array_key_exists('o', $options)) {
    $body = $options['o'];
  } else if (array_key_exists('body', $options)){
    $body = $options['body'];
  }

  $startErrors = [];

  if (strlen($baseUrl) == 0) {
      $startErrors[] = "Base Url must be set.";
  }

  if (strlen($wordListPath) == 0) {
      $startErrors[] = "Word List path must be set.";
  }

  if (count($responseCodes) == 0) {
      $startErrors[] = "At least one response code must be set.";
  }

  if (count($startErrors) > 0) {
    echo join("\n", $startErrors);
    exit(1);
  }

  stream_context_set_default(
    array(
        'http' => array(
            'method' => $verb
        )
    )
  );

  $handle = fopen($wordListPath, 'r');

  if ($handle) {
    while (($line = fgets($handle)) !== false) {
      if (strpos($line, '#') === false) {
        $full = str_replace('FUZZ', urlencode(trim($line)), $baseUrl);
        $code = 0;
        if (strlen($body) == 0) {
          $code = get_headers($full, 1)[0];
        } else {
          $reqOptions = array('http' => array('content' => $body, 'ignore_errors' => true, 'method' => $verb));
          $context = stream_context_create($reqOptions);
          $code = @file_get_contents($full, false, $context);
        }
        foreach ($responseCodes as $responseCode) {
          if (strpos($code, $responseCode) != false) {
            echo $full . "\n";
            break;
          }
        }
      }
    }
    fclose($handle);
  } else {
    echo "Word list file not found\n";
  }
?>


text:
<?php

namespace Nitrapi\Services\Gameservers\Games;

class Arkse extends Game
{
    protected $game = "arkse";

    /**
     * Returns the installed ark mods as list
     *
     * @return array
     */
    public function getModList() {
        $url = "services/" . $this->service->getId() . "/gameservers/games/arkse/modlist";
        return $this->service->getApi()->dataGet($url)['modlist'];
    }
}


text:
package scalaxy.react

import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
import scala.xml._

package object jsx extends jsx.WithJSXStringContext[ReactElement, ReactClass, React.type] {

  // implicit class JSXStringContext(val context: StringContext) {
  //   object jsx {
  //     def apply(args: Any*): JValue =
  //       macro impl.jsxApply[ReactElement, ReactClass, React.type]
  //   }
  // }
}

package jsx {

  trait WithJSXStringContext[E, C, F <: ElementFactory[E, C]] {
    implicit class JSXStringContext(val context: StringContext) {
      object jsx {
        def apply(args: Any*): E =
          macro impl.jsxApply[E, C, F]
      }
    }
  }
  // trait ElementFactory {

  // }
  object impl {
    // private[this] val paramRx = "\\$\\{.*?\\}".r

    def jsxApply[E : c.WeakTypeTag,
                 C : c.WeakTypeTag,
                 F <: ElementFactory[E, C] : c.WeakTypeTag]
                (c: Context)
                (args: c.Expr[Any]*)
                : c.Expr[E] = {
      import c.universe._

      // println("PREFIX: " + c.prefix)
      val q"${_}(scala.StringContext.apply(..$fragmentTrees)).jsx" = c.prefix.tree
      val fragmentsPosAndStrings: List[(Position, String)] = fragmentTrees map {
        case t @ Literal(Constant(s: String)) =>
          t.pos -> s
      }

      val argNamesAndTrees: List[(String, Tree)] =
        for ((((_, fragment), arg), i) <- fragmentsPosAndStrings.zip(args).zipWithIndex) yield {
          val name = "arg" + i
          (if (fragment.endsWith("\"")) name else name + "=\"...\"") -> arg.tree
        }

      val argTreesByName = argNamesAndTrees.toMap

      val SingleType(_, factorySymbol) = weakTypeOf[F]
      // println(s"SingleType($pre, $sym)")
      println(s"""
        Fragments:
          ${fragmentsPosAndStrings.mkString(",\n        ")}
        Args:
          ${argNamesAndTrees.mkString(",\n        ")}
        C:
          ${weakTypeOf[C]}
        E:
          ${weakTypeOf[E]}
        F:
          ${weakTypeOf[F]}: ${weakTypeOf[F].getClass}
      """)
      //c.Expr[E](q"null.asInstanceOf[${weakTypeOf[E]}]")
      //
      val src =
        fragmentsPosAndStrings.map(_._2)
          .zip(argNamesAndTrees.map(_._1) :+ "").map({
             case (f, a) => f + a
          }).mkString

      println(src)

      def processNode(node: Node): List[Tree] = node match {
        case t: Text =>
          val txt = t.data.trim
          if (txt.isEmpty)
            Nil
          else {

            List(Literal(Constant(txt)))
          }

        case e: Elem =>
          val children = node.child.flatMap(processNode(_))
          // println(node.attributes)

          def getAttrs(m: MetaData): List[Tree] = {
            val nextAttrs = Option(m.next).map(getAttrs(_)).getOrElse(Nil)

            Option(m.value).map {
              case Seq(value: Text) =>
                val res = argTreesByName.get(value.data).getOrElse(q"${value.data}")
                q"${m.key} -> $res" :: nextAttrs
            } getOrElse {
              nextAttrs
            }
          }

          val attrsArg = getAttrs(e.attributes) match {
            case Nil =>
              q"null"

            case attrs =>
              q"scala.scalajs.js.Dynamic.literal(..$attrs)"
          }

          val args = List(q"${e.label}", attrsArg) ++ children
          List(q"$factorySymbol.createElement(..$args)")

        case _ =>
          println("EMPTY NODE: " + node)
          Nil
      }

      val node = XML.loadString(src)

      val List(tree) = processNode(node)
      // println(processNode(node))
      val res = c.Expr[E](tree)
      // val res = c.Expr[E](q"""
      //   $factorySymbol.createElement("div", null)
      // """)
      println("RES: " + res)
      res
    }
  }

}


text:
<?php

/**
 * The "projects" collection of methods.
 * Typical usage is:
 *  <code>
 *   $firebaseService = new Google_Service_FirebaseManagement(...);
 *   $projects = $firebaseService->projects;
 *  </code>
 */
class Google_Service_FirebaseManagement_Resource_Projects extends Google_Service_Resource
{
  /**
   * Adds Firebase resources to the specified existing [Google Cloud Platform
   * (GCP) `Project`] (https://cloud.google.com/resource-
   * manager/reference/rest/v1/projects).
   *
   * Since a FirebaseProject is actually also a GCP `Project`, a `FirebaseProject`
   * uses underlying GCP identifiers (most importantly, the `projectId`) as its
   * own for easy interop with GCP APIs.
   *
   * The result of this call is an [`Operation`](../../v1beta1/operations). Poll
   * the `Operation` to track the provisioning process by calling GetOperation
   * until [`done`](../../v1beta1/operations#Operation.FIELDS.done) is `true`.
   * When `done` is `true`, the `Operation` has either succeeded or failed. If the
   * `Operation` succeeded, its
   * [`response`](../../v1beta1/operations#Operation.FIELDS.response) is set to a
   * FirebaseProject; if the `Operation` failed, its
   * [`error`](../../v1beta1/operations#Operation.FIELDS.error) is set to a
   * google.rpc.Status. The `Operation` is automatically deleted after completion,
   * so there is no need to call DeleteOperation.
   *
   * This method does not modify any billing account information on the underlying
   * GCP `Project`.
   *
   * All fields listed in the [request body](#request-body) are required.
   *
   * To call `AddFirebase`, a member must be an Editor or Owner for the existing
   * GCP `Project`. Service accounts cannot call `AddFirebase`.
   * (projects.addFirebase)
   *
   * @param string $project The resource name of the GCP `Project` to which
   * Firebase resources will be added, in the format: projects/projectId After
   * calling `AddFirebase`, the [`projectId`](https://cloud.google.com/resource-
   * manager/reference/rest/v1/projects#Project.FIELDS.project_id) of the GCP
   * `Project` is also the `projectId` of the FirebaseProject.
   * @param Google_Service_FirebaseManagement_AddFirebaseRequest $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_FirebaseManagement_Operation
   */
  public function addFirebase($project, Google_Service_FirebaseManagement_AddFirebaseRequest $postBody, $optParams = array())
  {
    $params = array('project' => $project, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('addFirebase', array($params), "Google_Service_FirebaseManagement_Operation");
  }
  /**
   * Gets the FirebaseProject identified by the specified resource name.
   * (projects.get)
   *
   * @param string $name The fully qualified resource name of the Project, in the
   * format: projects/projectId
   * @param array $optParams Optional parameters.
   * @return Google_Service_FirebaseManagement_FirebaseProject
   */
  public function get($name, $optParams = array())
  {
    $params = array('name' => $name);
    $params = array_merge($params, $optParams);
    return $this->call('get', array($params), "Google_Service_FirebaseManagement_FirebaseProject");
  }
  /**
   * Gets the configuration artifact used by servers to simplify initialization.
   *
   * Typically, this configuration is used with the Firebase Admin SDK [initialize
   * App](https://firebase.google.com/docs/admin/setup#initialize_the_sdk)
   * command. (projects.getAdminSdkConfig)
   *
   * @param string $name The fully qualified resource name of the Project, in the
   * format: projects/projectId/adminSdkConfig
   * @param array $optParams Optional parameters.
   * @return Google_Service_FirebaseManagement_AdminSdkConfig
   */
  public function getAdminSdkConfig($name, $optParams = array())
  {
    $params = array('name' => $name);
    $params = array_merge($params, $optParams);
    return $this->call('getAdminSdkConfig', array($params), "Google_Service_FirebaseManagement_AdminSdkConfig");
  }
  /**
   * Lists each FirebaseProject accessible to the caller.
   *
   * The elements are returned in no particular order, but they will be a
   * consistent view of the Projects when additional requests are made with a
   * `pageToken`.
   *
   * This method is eventually consistent with Project mutations, which means
   * newly provisioned Projects and recent modifications to existing Projects
   * might not be reflected in the set of Projects. The list will include only
   * ACTIVE Projects.
   *
   * Use GetFirebaseProject for consistent reads as well as for additional Project
   * details. (projects.listProjects)
   *
   * @param array $optParams Optional parameters.
   *
   * @opt_param string pageToken Token returned from a previous call to
   * `ListFirebaseProjects` indicating where in the set of Projects to resume
   * listing.
   * @opt_param int pageSize The maximum number of Projects to return in the
   * response.
   *
   * The server may return fewer than this at its discretion. If no value is
   * specified (or too large a value is specified), the server will impose its own
   * limit.
   *
   * This value cannot be negative.
   * @return Google_Service_FirebaseManagement_ListFirebaseProjectsResponse
   */
  public function listProjects($optParams = array())
  {
    $params = array();
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "Google_Service_FirebaseManagement_ListFirebaseProjectsResponse");
  }
  /**
   * Updates the attributes of the FirebaseProject identified by the specified
   * resource name.
   *
   * All [query parameters](#query-parameters) are required. (projects.patch)
   *
   * @param string $name The fully qualified resource name of the Project, in the
   * format: projects/projectId
   * @param Google_Service_FirebaseManagement_FirebaseProject $postBody
   * @param array $optParams Optional parameters.
   *
   * @opt_param string updateMask Specifies which fields to update.
   *
   * If this list is empty, then no state will be updated. Note that the fields
   * `name`, `project_id`, and `project_number` are all immutable.
   * @return Google_Service_FirebaseManagement_FirebaseProject
   */
  public function patch($name, Google_Service_FirebaseManagement_FirebaseProject $postBody, $optParams = array())
  {
    $params = array('name' => $name, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('patch', array($params), "Google_Service_FirebaseManagement_FirebaseProject");
  }
  /**
   * A convenience method that lists all available Apps for the specified
   * FirebaseProject.
   *
   * Typically, interaction with an App should be done using the platform-specific
   * service, but some tool use-cases require a summary of all known Apps (such as
   * for App selector interfaces). (projects.searchApps)
   *
   * @param string $parent The parent Project for which to list Apps, in the
   * format: projects/projectId
   * @param array $optParams Optional parameters.
   *
   * @opt_param string pageToken Token returned from a previous call to
   * `SearchFirebaseApps` indicating where in the set of Apps to resume listing.
   * @opt_param int pageSize The maximum number of Apps to return in the response.
   *
   * The server may return fewer than this value at its discretion. If no value is
   * specified (or too large a value is specified), then the server will impose
   * its own limit.
   *
   * This value cannot be negative.
   * @return Google_Service_FirebaseManagement_SearchFirebaseAppsResponse
   */
  public function searchApps($parent, $optParams = array())
  {
    $params = array('parent' => $parent);
    $params = array_merge($params, $optParams);
    return $this->call('searchApps', array($params), "Google_Service_FirebaseManagement_SearchFirebaseAppsResponse");
  }
}


text:
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

namespace ExtendedCells.Forms.Plugin.iOSUnified
{
	public static class UILabelExtensions
	{
		public static void UpdateFromFormsControl (this UILabel uiLabel, string text, Xamarin.Forms.TextAlignment textAlignment, Color textColor, Font font)
		{
			uiLabel.Text = text;

			switch (textAlignment) {
			case TextAlignment.Start:
				uiLabel.TextAlignment = UITextAlignment.Left;
				break;
			case TextAlignment.Center:
				uiLabel.TextAlignment = UITextAlignment.Center;
				break;
			case TextAlignment.End:
				uiLabel.TextAlignment = UITextAlignment.Right;
				break;
			}

			uiLabel.TextColor = textColor.ToUIColor ();
			uiLabel.Font = font.ToUIFont ();
		}
	}
}


text:
// Generated on 2013-12-23 using generator-angular 0.6.0
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: {
      // configurable paths
      app: require('./bower.json').appPath || 'app'
    },

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      js: {
        files: ['{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all', 'karma']
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost'
      },
      test: {
        options: {
          port: 9001,
          base: [
            '.tmp',
            'test',
            '<%= yeoman.app %>'
          ]
        }
      }
    },

    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: [
        'Gruntfile.js',
        '<%= yeoman.app %>/scripts/{,*/}*.js'
      ],
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      server: '.tmp'
    }
  });

  grunt.registerTask('test', [
    'clean:server',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('test:watch', [
    'clean:server',
    'connect:test',
    'karma',
    'watch'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test'
  ]);
};


text:
package routes

import (
	"github.com/G-Node/gogs/pkg/context"
	"github.com/G-Node/gogs/pkg/setting"
	"fmt"
	"net/http"
)

func RequestDoi(c *context.Context) {
	if !c.Repo.IsAdmin(){
		c.Status(http.StatusUnauthorized)
		return
	}

	token := c.GetCookie(setting.SessionConfig.CookieName)
	c.Redirect(fmt.Sprintf("https://doi.gin.g-node.org/?repo=%s&user=%s&token=%s", c.Repo.Repository.FullName(),
		c.User.Name, token))
}


text:
package org.apache.sling.testing.tools.junit;

import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.slf4j.MDC;

/**
 * Junit rule which exposes the current executing test's description as a thread local instance
 */
public class TestDescriptionRule extends TestWatcher {
    @Override
    protected void starting(Description description) {
        MDC.put(RemoteLogDumper.TEST_CLASS, description.getClassName());
        MDC.put(RemoteLogDumper.TEST_NAME, description.getMethodName());
    }

    @Override
    protected void finished(Description description) {
        MDC.remove(RemoteLogDumper.TEST_CLASS);
        MDC.remove(RemoteLogDumper.TEST_NAME);
    }
}


text:
package com.shanbay.model;

public class App extends Model
{
  public String description;
  public String domain;
  public String identifier;
  public String imageUrl;
  public int platform;
  public String rateUrl;
  public String schemeUrl;
  public String targetUrl;
  public String title;
}


text:
#include <memory>
// Taylor–Hood
#include "Triangle_P2_Lagrange.hpp"
#include "Triangle_P1_Lagrange.hpp"
// MINI
#include "Triangle_Pt3_LagrangeBubble.hpp"
#include "Triangle_P1_Lagrange.hpp"
// assemblers
#include "MixedFEM.hpp"
#include "DivGradFEM.hpp"
// saddle point system
#include "SymmetricBlockMatrix.hpp"
// solvers
#include "ProjectionSolvers.hpp"
// precond
#include "Multigrid.hpp"
// interpolant for wind field
#include "FEInterpolant.hpp"
// interpolant for inflow amplitude
#include "SegmentMesh.hpp"
#include "Segment_P3_Hermite.hpp"

using std::vector;
using std::string;
using std::shared_ptr;
using boost::get;
using namespace ProjectionSolvers;
using namespace FEM;

int main() {
	string iPath("Mathematica/preprocessing/"), oPath("Mathematica/postprocessing/");
	auto& logger = SingletonLogger::instance();
	try {
		// current time and time step
		double t = 0., delta_t;
		Index final_frame_index;
		logger.inp("set time step", delta_t);
		logger.inp("final time frame number", final_frame_index);
		logger.beg("set up mesh");
			vector<string> meshType { "mesh_fine.ntn", "mesh_coarse.ntn" };
			auto meshTypeIndex = logger.opt("mesh type", meshType);
			Triangulation Omega_0;
			Omega_0.import(iPath + meshType[meshTypeIndex]);
			Omega_0.enumerateRibs();
			auto Omega = Omega_0;
			struct MeshData {
				Index numb_of_levels;
			} meshData;
			logger.inp("numb of mesh levels", meshData.numb_of_levels);
		logger.end();
		logger.beg("set up units");
			// blood parameters
			struct BloodParameters {
				double mu, rho; // pascals-seconds, kgs per meter cubed
				double v_min, v_max; // meters
			} const bloodParameters {
				3.3e-03, // dynamic viscocity
				1060, // density
				.7, 1.5 // systolic and diastolic velocities
			};
			// geometry
			struct VesselsGeometry {
				double length, radius;
			} const vesselsGeometry { 16., .002 };
			// units
			struct Units {
				double length, velocity, time; // meters, meters per second, seconds
			} const units {
				vesselsGeometry.radius, // radius of the aurtery
				bloodParameters.v_max, // systolic velocity
				.875 // cardiac cycle
			};
			// Reynolds number

			double const Re = units.velocity * units.length * bloodParameters.rho / bloodParameters.mu;
			//double const Re = 100;

			// Strouhal number
			double const St = units.length / (units.time * units.velocity);
			logger.buf
				<< "Reynolds number: " << Re << '\n'
				<< "Strouhal number: " << St;
			logger.log();
		logger.end();
		logger.beg("set up PDE and BCs");
			auto approxEqual = [](double x, double y) { return fabs(x - y) < 1e-12; };
			// Stokes problem for (u_0, p_0)
			OseenProblem2D Oseen {
				0.,
				[](Node2D const &) -> Node2D { return { 0., 0. }; },
				1. / Re,
				[](Node2D const &) -> Node2D { return { 0., 0. }; },
				[](Node2D const &) { return 0.; }
			};
			// natural BCs for outflow boundary
			auto GammaOut = [&](Node2D const & p) { return approxEqual(p[0], vesselsGeometry.length / 2.); };
			auto h = [&](Node2D const &) -> Node2D { return { 0., 0.}; };
			VectorBoundaryCondition2D NeumannBC { h, GammaOut };
			// essential BCs for inflow boundary and no-slip boundary
			auto GammaIn = [&](Node2D const & p) { return approxEqual(p[0], -vesselsGeometry.length / 2.); };
			// systolic / diastolic amplitude
			SegmentMesh hermiteNodes {
				{ 0., units.time / 7., units.time }
			};
			SegmentFEInterpolant interp { {
					bloodParameters.v_min,
					bloodParameters.v_max,
					bloodParameters.v_min,
					0., 0., 0.
				}, Segment_P3_Hermite::instance(), hermiteNodes
			};
			SmartScalarField1D ampl = [&](double const & t) {
				// s := units.time * t, [s] = seconds
				return interp(fmod(units.time * t, units.time)) / bloodParameters.v_max;
			};
			auto g = [&](Node2D const & p) -> Node2D {
				if (GammaIn(p)) return { ampl(t) * (1 - p[1] * p[1]), 0. };
				return { 0., 0. };
			};
			VectorBoundaryCondition2D DirichletBC { g };
		logger.end();
		auto FEPairIndex = logger.opt("choose FE pair", { "Taylor-Hood", "MINI" });
		// Taylor—Hood family
		TriangularScalarFiniteElement
			*velocityFE = &Triangle_P2_Lagrange::instance(),
			*pressureFE = &Triangle_P1_Lagrange::instance();
		// MINI element
		if (FEPairIndex == 1) {
			velocityFE = &Triangle_Pt3_LagrangeBubble::instance();
			pressureFE = &Triangle_P1_Lagrange::instance();
		};
		logger.beg("set solver options");
			struct SolverOptions {
				Index outer_iters_max, inner_iters, smoothing_iters, precond_index, i_log, cycle, smoother_index;
				double eps;
				StoppingCriterion stop;
			} opt;
			opt.precond_index = logger.opt("choose precond for BiCGStab", { "I", "P_BD", "P_BT" });
			logger.inp("max numb of iterations for outer solver", opt.outer_iters_max);
			logger.inp("log every nth iteration, n", opt.i_log);
			logger.inp("set eps for solver", opt.eps);
			opt.stop = (StoppingCriterion)logger.opt("stopping criterion", { "absolute", "relative" });
			logger.inp("numb of iterations for inner solver", opt.inner_iters);
			opt.smoother_index = logger.opt("choose smoother", { "forwSOR", "SSOR", "ILU(0)" });
			logger.inp("numb of smoothing iters", opt.smoothing_iters);
			opt.cycle = logger.opt("set recursive calls type", { "V-cycle", "W-cycle" }) + 1;
		logger.end();
		logger.beg("build preconditioner and assemble system");
			Preconditioner P;
			struct {
				CSlCMatrix<double> A11;
				CSCMatrix<double> B1, B2;
				vector<double> b;
			} system;
			Index n, m;
			shared_ptr<Multigrid<CSlCMatrix<double>>> MG;
			SymmetricCSlCMatrix<double> pressureMassMatrix;
			Smoother<CSlCMatrix<double>> smoother;
			vector<CSlCMatrix<double>> ILU0;
			ILU0.reserve(meshData.numb_of_levels);
			if (opt.precond_index == 0) {
				P = [](vector<double> const & x) { return x; }; // do nothing
				logger.beg("refine mesh");
					Omega.refine(meshData.numb_of_levels);
				logger.end();
				auto res = Mixed::assembleSystem(Oseen, Omega, NeumannBC, DirichletBC, *velocityFE, *pressureFE);
				system.A11 = get<0>(res);
				system.B1  = get<1>(res);
				system.B2  = get<2>(res);
				system.b   = get<3>(res);
			}
			else {
				logger.beg("(1) MG for Laplace block");
					MG = std::make_shared<Multigrid<CSlCMatrix<double>>>(
						Multigrid<CSlCMatrix<double>> {
							*velocityFE, Omega, meshData.numb_of_levels,
							[&](Triangulation const & Omega) {
								auto res = Mixed::assembleSystem(Oseen, Omega, NeumannBC, DirichletBC, *velocityFE, *pressureFE);
								system.A11 = get<0>(res);
								system.B1  = get<1>(res);
								system.B2  = get<2>(res);
								system.b   = get<3>(res);
								return system.A11; // return Laplace block
							}
						}
					);
				logger.end();
				logger.beg("(2) pressure mass matrix for Schur complement");
					ConvectionDiffusionEqn2D ReactionEqn {
						[](Node2D const &) { return 0.; },
						[](Node2D const &) { return 1.; },
						[](Node2D const &) { return 0.; }
					};
					ScalarBoundaryCondition2D rBC { {
								[](Node2D const &) { return 0.; },
								[](Node2D const &) { return 0.; }
							},
							[](Node2D const & p) { return true; }
						}, dBC { [](Node2D const &) { return 0.; } };
					pressureMassMatrix = get<0>(DivGrad::assembleSystem(ReactionEqn, Omega, rBC, dBC, *pressureFE));
				logger.end();
				logger.beg("define smoother");
					if (opt.smoother_index == 0)
						smoother = [&](CSlCMatrix<double>& A, vector<double> const & b, vector<double> const & x_0, Index meshLevel) {
							return Smoothers::forwSOR(A, b, x_0, 1., opt.smoothing_iters, 0., StoppingCriterion::absolute, 0);
						};
					else if (opt.smoother_index == 1)
						smoother = [&](CSlCMatrix<double>& A, vector<double> const & b, vector<double> const & x_0, Index meshLevel) {
							return Smoothers::SSOR(A, b, x_0, 1., opt.smoothing_iters, 0., StoppingCriterion::absolute, 0);
						};
					else if (opt.smoother_index == 2) {
						logger.beg("compute ILU0's");
							for (Index i = 0; i < meshData.numb_of_levels; ++i) {
								auto ILU0i = MG->A(i + 1);
								ILU0.emplace_back(ILU0i.decompose());
							}
						logger.end();
						smoother = [&](CSlCMatrix<double>& A, vector<double> const & b, vector<double> const & x_0, Index meshLevel) {
							auto& d = ILU0[meshLevel - 1];
							return d.backSubst(d.diagSubst(d.forwSubst(b, 0.)), 0.);
						};
					}
				logger.end();
				if (opt.precond_index == 1) // BD
					P = [&](vector<double> const & x) {
						vector<double>
							x1(x.begin(), x.begin() + n),
							x2(x.begin() + n, x.begin() + 2 * n),
							x3(x.begin() + 2 * n, x.end()),
							y1(n), y2(n);
						// (1) Laplace block
						logger.mute = true;
						for (Index i = 0; i < opt.inner_iters; ++i) {
							y1 = (*MG)(meshData.numb_of_levels, x1, y1, smoother, opt.cycle);
							y2 = (*MG)(meshData.numb_of_levels, x2, y2, smoother, opt.cycle);
						}
						logger.mute = false;
						// (2) Schur complement
						auto y3 = pressureMassMatrix.diagSubst(x3);
						y3 *= -1.;
						// final vector
						vector<double> y;
						y.reserve(2 * n + m);
						y.insert(y.end(), y1.begin(), y1.end());
						y.insert(y.end(), y2.begin(), y2.end());
						y.insert(y.end(), y3.begin(), y3.end());
						return y;
					};
				else if (opt.precond_index == 2) // BT
					P = [&](vector<double> const & x) {
						vector<double>
							x1(x.begin(), x.begin() + n),
							x2(x.begin() + n, x.begin() + 2 * n),
							x3(x.begin() + 2 * n, x.end()),
							y1(n), y2(n);
						// (1) Schur complement
						auto y3 = pressureMassMatrix.diagSubst(x3);
						y3 *= -1.;
						// (1) Laplace block
						auto f1 = x1 - system.B1.t() * y3;
						auto f2 = x2 - system.B2.t() * y3;
						logger.mute = true;
						for (Index i = 0; i < opt.inner_iters; ++i) {
							y1 = (*MG)(meshData.numb_of_levels, f1, y1, smoother, opt.cycle);
							y2 = (*MG)(meshData.numb_of_levels, f2, y2, smoother, opt.cycle);
						}
						logger.mute = false;
						// final vector
						vector<double> y;
						y.reserve(2 * n + m);
						y.insert(y.end(), y1.begin(), y1.end());
						y.insert(y.end(), y2.begin(), y2.end());
						y.insert(y.end(), y3.begin(), y3.end());
						return y;
					};
			}
			n = system.A11.getOrder();
			m = system.B1.numbOfRows();
			SymmetricBlockMatrix<double> A {
				{ &system.A11, &system.A11, nullptr }, // diag
				{ // lval
					nullptr,
					&system.B1, &system.B2
				}, BlockSymmetryType::antisymmetric
			};
			for (Index i = 2 * n; i < system.b.size(); ++i) system.b[i] = -system.b[i];
		logger.end();
		logger.beg("Stokes problem for (u_0, p_0)");
			logger.beg("solve");
				auto x_0 = Krylov::BiCGStab(A, system.b, boost::none, 10, 1., StoppingCriterion::absolute, 1);
				x_0 = Krylov::PBiCGStab(
					P, A, system.b, x_0,
					opt.outer_iters_max, opt.eps, opt.stop, opt.i_log
				);
			logger.end();
			logger.beg("export soln vector");
				export(x_0, oPath + "x_0.dat");
			logger.end();
			auto exportMatrix = logger.yes("export matrix blocks");
			if (exportMatrix) {
				logger.beg("export blocks of matrix and rhs vector");
					static_cast<CSCMatrix<double>>(system.A11).exportHarwellBoeing(oPath + "system/A11_0.rua");
					system.B1.exportHarwellBoeing(oPath + "system/B1_0.rra");
					system.B2.exportHarwellBoeing(oPath + "system/B2_0.rra");
					export(system.b, oPath + "system/b_0.dat");
				logger.end();
			}
		logger.end();
		if (final_frame_index) {
			logger.beg("Oseen Problem for (u_1, p_1)");
				logger.beg("update parameters");
					t = delta_t;
					Oseen.massCoef() = St / delta_t;
					logger.buf << "alpha = " << Oseen.massCoef();
					logger.log();
					// wind
					Index activeElementIndex;
					TriangularScalarFEInterpolant
						u_0_x_interp { std::vector<double>(x_0.begin(), x_0.begin() + n), *velocityFE, Omega },
						u_0_y_interp { std::vector<double>(x_0.begin() + n, x_0.begin() + 2 * n), *velocityFE, Omega };
					Oseen.windField() = [&](Node2D const & p) -> Node2D {
						return { u_0_x_interp(p, activeElementIndex), u_0_y_interp(p, activeElementIndex) };
					};
					// force
					Oseen.forceTerm() = [&](Node2D const & p) -> Node2D {
						return { St * u_0_x_interp(p, activeElementIndex) / delta_t, St * u_0_y_interp(p, activeElementIndex) / delta_t };
					};
				logger.end();
				if (opt.precond_index == 0) {
					auto res = Mixed::assembleSystem(Oseen, Omega, NeumannBC, DirichletBC, *velocityFE, *pressureFE, activeElementIndex);
					system.A11 = get<0>(res);
					system.B1  = get<1>(res);
					system.B2  = get<2>(res);
					system.b   = get<3>(res);
				}
				else {
					logger.beg("REDEFINE MG for Laplace block");
						Omega = Omega_0;
						MG = std::make_shared<Multigrid<CSlCMatrix<double>>>(
							Multigrid<CSlCMatrix<double>> {
								*velocityFE, Omega, meshData.numb_of_levels,
								[&](Triangulation const & Omega) {
									auto res = Mixed::assembleSystem(Oseen, Omega, NeumannBC, DirichletBC, *velocityFE, *pressureFE, activeElementIndex);
									system.A11 = get<0>(res);
									system.B1  = get<1>(res);
									system.B2  = get<2>(res);
									system.b   = get<3>(res);
									return system.A11; // return Laplace block
								}
							}
						);
					logger.end();
					if (opt.smoother_index == 2) {
						logger.beg("REDEFINE smoother");
							ILU0.resize(0);
							ILU0.reserve(meshData.numb_of_levels);
							logger.beg("compute ILU0's");
								for (Index i = 0; i < meshData.numb_of_levels; ++i) {
									auto ILU0i = MG->A(i + 1);
									ILU0.emplace_back(ILU0i.decompose());
								}
							logger.end();
							smoother = [&](CSlCMatrix<double>& A, vector<double> const & b, vector<double> const & x_0, Index meshLevel) {
								auto& d = ILU0[meshLevel - 1];
								return d.backSubst(d.diagSubst(d.forwSubst(b, 0.)), 0.);
							};
						logger.end();
					}
				}
				for (Index i = 2 * n; i < system.b.size(); ++i) system.b[i] = -system.b[i];
				logger.beg("solve");
					auto x_1 = Krylov::BiCGStab(A, system.b, x_0, 10, 1., StoppingCriterion::absolute, 1);
					x_1 = Krylov::PBiCGStab(
						P, A, system.b, x_1,
						opt.outer_iters_max, opt.eps, opt.stop, opt.i_log
					);
				logger.end();
				logger.beg("export soln vector");
					export(x_1, oPath + "x_1.dat");
				logger.end();
				if (exportMatrix) {
					logger.beg("export blocks of matrix and rhs vector");
						static_cast<CSCMatrix<double>>(system.A11).exportHarwellBoeing(oPath + "system/A11_1.rua");
						system.B1.exportHarwellBoeing(oPath + "system/B1_1.rra");
						system.B2.exportHarwellBoeing(oPath + "system/B2_1.rra");
						export(system.b, oPath + "system/b_1.dat");
					logger.end();
				}
			logger.end();
		}
		logger.beg("export mesh");
			Omega.export(oPath + "mesh.ntnr", { { "format", "NTNR" } });
		logger.end();
		logger.exp("stdin.txt");
	}
	catch (std::exception const & e) {
		logger.err(e.what());
	}
	return 0;
}


text:
import kerberos
import logging

from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend

logger = logging.getLogger(__name__)

class KrbBackend(ModelBackend):
    """
    Django Authentication backend using Kerberos for password checking.
    """

    def authenticate(self, username=None, password=None):
        UserModel = get_user_model()
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)

        if not self.check_password(username, password):
            return None

        UserModel = get_user_model()
        if getattr(settings, "KRB5_CREATE_USER", True):
            if getattr(settings, "KRB5_USERNAME_MATCH_IEXACT", True):
                user, created = UserModel.objects.get_or_create(**{
                    UserModel.USERNAME_FIELD+"__iexact": username,
                    "defaults": { UserModel.USERNAME_FIELD: username }
                })
                return user
            else:
                user, created = UserModel.objects.get_or_create(**{
                    UserModel.USERNAME_FIELD: username,
                    "defaults": { UserModel.USERNAME_FIELD: username }
                })
                return user
        else:
            try:
                if getattr(settings, "KRB5_USERNAME_MATCH_IEXACT", True):
                     return UserModel.objects.get(**{UserModel.USERNAME_FIELD+"__iexact": username})
                else:
                    return UserModel._default_manager.get_by_natural_key(username)
            except UserModel.DoesNotExist:
                return None
        return None

    def check_password(self, username, password):
        """The actual password checking logic. Separated from the authenticate code from Django for easier updating"""
        try:
            kerberos.checkPassword(username.lower(), password, getattr(settings, "KRB5_SERVICE", ""), settings.KRB5_REALM)
            return True
        except kerberos.BasicAuthError:
            if getattr(settings, "KRB5_DEBUG", False):
                logger.exception("Failure during authentication")
            return False
        except:
            if getattr(settings, "KRB5_DEBUG", False):
                logger.exception("Failure during authentication")
            # for all other execptions also deny access
            return False


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <parent>
    <artifactId>drools-impact-analysis</artifactId>
    <groupId>org.drools</groupId>
    <version>8.15.0-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>

  <artifactId>drools-impact-analysis-parser</artifactId>

  <name>Drools :: Impact Analysis :: Parser</name>

  <properties>
    <java.module.name>org.drools.impact.analysis.parser</java.module.name>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.drools</groupId>
      <artifactId>drools-engine</artifactId>
    </dependency>
    <dependency>
      <groupId>org.drools</groupId>
      <artifactId>drools-impact-analysis-model</artifactId>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
package org.apache.wicket.model;

import org.apache.wicket.Component;

/**
 * A simple compound model which uses the component's name as the property expression to retrieve
 * properties on the nested model object.
 *
 * CompoundPropertyModel is a chaining model so it will call get/setobject on the given object if
 * the object is an instanceof IModel itself.
 *
 * @see org.apache.wicket.model.IModel
 * @see org.apache.wicket.model.Model
 * @see org.apache.wicket.model.LoadableDetachableModel
 * @see IChainingModel
 *
 * @author Jonathan Locke
 *
 * @param <T>
 *            The model object type
 */
public class CompoundPropertyModel<T> extends ChainingModel<T> implements IComponentInheritedModel<T>
{
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor
	 *
	 * @param model
	 *            The model
	 */
	public CompoundPropertyModel(final IModel<T> model)
	{
		super(model);
	}

	/**
	 * Constructor
	 *
	 * @param object
	 *            The model object
	 */
	public CompoundPropertyModel(final T object)
	{
		super(object);
	}

	/**
	 * Returns the property expression that should be used against the target object
	 *
	 * @param component
	 * @return property expression that should be used against the target object
	 */
	protected String propertyExpression(Component component)
	{
		return component.getId();
	}

	/**
	 * @see org.apache.wicket.model.IComponentInheritedModel#wrapOnInheritance(org.apache.wicket.Component)
	 */
	@Override
	public <C> IWrapModel<C> wrapOnInheritance(Component component)
	{
		return new AttachedCompoundPropertyModel<C>(component);
	}

	/**
	 * Binds this model to a special property by returning a model that has this compound model as
	 * its nested/wrapped model and the property which should be evaluated. This can be used if the
	 * id of the Component isn't a valid property for the data object.
	 *
	 * @param property
	 *      the name that will be used to find
	 * @return The IModel that is a wrapper around the current model and the property
	 * @param <S>
	 *            the type of the property
	 */
	public <S> IModel<S> bind(String property)
	{
		return new PropertyModel<>(this, property);
	}

	/**
	 * Component aware variation of the {@link CompoundPropertyModel} that components that inherit
	 * the model get
	 *
	 * @author ivaynberg
	 * @param <C>
	 *            The model object type
	 */
	private class AttachedCompoundPropertyModel<C> extends AbstractPropertyModel<C>
		implements
			IWrapModel<C>
	{
		private static final long serialVersionUID = 1L;

		private final Component owner;

		/**
		 * Constructor
		 *
		 * @param owner
		 *            component that this model has been attached to
		 */
		public AttachedCompoundPropertyModel(Component owner)
		{
			super(CompoundPropertyModel.this);
			this.owner = owner;
		}

		/**
		 * @see org.apache.wicket.model.AbstractPropertyModel#propertyExpression()
		 */
		@Override
		protected String propertyExpression()
		{
			return CompoundPropertyModel.this.propertyExpression(owner);
		}

		/**
		 * @see org.apache.wicket.model.IWrapModel#getWrappedModel()
		 */
		@Override
		public IModel<T> getWrappedModel()
		{
			return CompoundPropertyModel.this;
		}

		/**
		 * @see org.apache.wicket.model.AbstractPropertyModel#detach()
		 */
		@Override
		public void detach()
		{
			super.detach();
			CompoundPropertyModel.this.detach();
		}
	}

	/**
	 * Type-infering factory method
	 *
	 * @param <Z>
	 *     the type of the model's object
	 * @param model
	 *            model
	 * @return {@link CompoundPropertyModel} instance
	 */
	public static <Z> CompoundPropertyModel<Z> of(IModel<Z> model)
	{
		return new CompoundPropertyModel<>(model);
	}
}


text:
#ifndef __MOD_DOCUMENT_H__
#define __MOD_DOCUMENT_H__

#include <dirent.h>

#define DOCUMENT_DIRLISTING 0x01
#define DOCUMENT_SENDFILE 0x02
#define DOCUMENT_RANGE 0x04
#define DOCUMENT_REST 0x08
#define DOCUMENT_HOME 0x10
#define DOCUMENT_TLS 0x20

#include "ouistiti.h"

#ifdef __cplusplus
extern "C"
{
#endif
typedef struct mod_document_s
{
	const char *docroot;
	const char *dochome;
	const char *allow;
	const char *deny;
	const char *defaultpage;
	int options;
} mod_document_t;

extern const module_t mod_document;

/**
 * interface to change the data transfer function
 */
#define CONTENTCHUNK 64

typedef struct _mod_document_mod_s _mod_document_mod_t;
typedef struct _document_connector_s document_connector_t;
typedef int (*mod_transfer_t)(document_connector_t *private, http_message_t *response);

struct _mod_document_mod_s
{
	mod_document_t *config;
	void *vhost;
	mod_transfer_t transfer;
	int fdroot;
	int fdhome;
};

struct _document_connector_s
{
	_mod_document_mod_t *mod;
	http_client_t *ctl;
	void *previous;
	const char *url;
	const char *mime;
	int fdfile;
	int fdroot;
	int type;
	DIR *dir;
	http_connector_t func;
	unsigned long long size;
	unsigned long long offset;
#ifdef DEBUG
	struct timespec start;
	unsigned long long datasize;
#endif
};

/**
 * specific connectors
 */
#ifdef RANGEREQUEST
int range_connector(void *arg, http_message_t *request, http_message_t *response);
#endif
#ifdef DIRLISTING
int dirlisting_connector(void *arg, http_message_t *request, http_message_t *response);
#endif
int getfile_connector(void *arg, http_message_t *request, http_message_t *response);

#ifdef DOCUMENTREST
int _document_getconnnectorput(_mod_document_mod_t *mod,
		int fdroot, const char *url, const char **mime,
		http_message_t *request, http_message_t *response,
		http_connector_t *connector);
int _document_getconnnectorpost(_mod_document_mod_t *mod,
		int fdroot, const char *url, const char **mime,
		http_message_t *request, http_message_t *response,
		http_connector_t *connector);
int _document_getconnnectordelete(_mod_document_mod_t *mod,
		int fdroot, const char *url, const char **mime,
		http_message_t *request, http_message_t *response,
		http_connector_t *connector);
#endif

void document_close(document_connector_t *private, http_message_t *request);

#ifdef __cplusplus
}
#endif

#endif


text:
/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50628
Source Host           : localhost:3306
Source Database       : commerce_data

Target Server Type    : MYSQL
Target Server Version : 50628
File Encoding         : 65001

Date: 2016-04-21 18:21:34
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for country
-- ----------------------------
DROP TABLE IF EXISTS `country`;
CREATE TABLE `country` (
  `country_id` int(11) NOT NULL,
  PRIMARY KEY (`country_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of country
-- ----------------------------


text:
define(['./_getNative', './_root'], function(getNative, root) {

  /* Built-in method references that are verified to be native. */
  var Map = getNative(root, 'Map');

  return Map;
});


text:
import React from 'react';
import styled from '@emotion/styled';
import PropTypes from 'prop-types';

import PluginIcon, {DEFAULT_ICON, ICON_PATHS} from 'app/plugins/components/pluginIcon';
import {Integration} from 'app/types';

type Props = {
  integration: Integration;
  size?: number;
};

type IconProps = Pick<Props, 'size'>;

const StyledIcon = styled('img')<IconProps>`
  height: ${p => p.size}px;
  width: ${p => p.size}px;
  border-radius: 2px;
  display: block;
`;

class Icon extends React.Component<Props> {
  state = {
    imgSrc: this.props.integration.icon,
  };

  render() {
    const {integration, size} = this.props;

    return (
      <StyledIcon
        size={size}
        src={this.state.imgSrc}
        onError={() => {
          this.setState({imgSrc: ICON_PATHS[integration.provider.key] || DEFAULT_ICON});
        }}
      />
    );
  }
}

const IntegrationIcon = ({integration, size = 32}: Props) =>
  integration.icon ? (
    <Icon size={size} integration={integration} />
  ) : (
    <PluginIcon size={size} pluginId={integration.provider.key} />
  );

IntegrationIcon.propTypes = {
  integration: PropTypes.object.isRequired,
  size: PropTypes.number,
};

export default IntegrationIcon;


text:
{-# LANGUAGE OverloadedStrings #-}

module Haskell.Ide.Engine.Utils
  (
    validatePlugins
  , PluginDescriptionError(..)
  , ParamCollision(..)
  , ParamOccurence(..)
  ) where

import           Data.List
import           Haskell.Ide.Engine.PluginDescriptor
import qualified Data.Map as Map

-- |For all the plugins, validate that parameter names are unique within each
-- command. Otherwise return an error, describing the collisions.
validatePlugins :: Plugins -> Maybe PluginDescriptionError
validatePlugins plugins =
 case paramNameCollisions plugins of
    [] -> Nothing
    collisions -> Just PluginDescriptionError {
         pdeCollisions = collisions
       , pdeErrorMsg = formatParamNameCollisionErrorMsg collisions
     }

data PluginDescriptionError =
  PluginDescriptionError {
      pdeCollisions :: [ParamCollision]
    , pdeErrorMsg :: String
    } deriving (Eq, Show)

data ParamCollision = ParamCollision PluginId CommandName ParamName [ParamOccurence] deriving (Eq, Show)
data ParamOccurence = AdditionalParam ParamDescription
                    | ContextParam ParamDescription AcceptedContext
                    deriving (Eq, Show)

paramNameCollisions :: Plugins -> [ParamCollision]
paramNameCollisions plugins =
  concatMap (\(plId, plDesc) ->
    concatMap (paramNameCollisionsForCmd plId . cmdDesc) (pdCommands plDesc)) (Map.toList plugins)

paramNameCollisionsForCmd :: PluginId -> UntaggedCommandDescriptor -> [ParamCollision]
paramNameCollisionsForCmd plId cmdDescriptor =
  let collidingParamNames = findCollidingParamNames cmdDescriptor
      collisionSources = map (\param -> ParamCollision plId (cmdName cmdDescriptor) param (paramsByName cmdDescriptor param)) collidingParamNames
   in collisionSources

-- |Find all the parameters within the CommandDescriptor that goes by the given ParamName
paramsByName :: UntaggedCommandDescriptor -> ParamName -> [ParamOccurence]
paramsByName cmdDescriptor paramName =
  let matchingParamName param = pName param == paramName
      additionalParams = map AdditionalParam $ filter matchingParamName (cmdAdditionalParams cmdDescriptor)
      cmdContextParams = concatMap
                           (\accContext -> map
                                             (\param -> (param, accContext))
                                           (contextMapping accContext))
                         (cmdContexts cmdDescriptor)
      cmdContextParamsWithCollisions = map (uncurry ContextParam) $ filter (\(param, _) -> matchingParamName param) cmdContextParams
   in additionalParams ++ cmdContextParamsWithCollisions

findCollidingParamNames :: UntaggedCommandDescriptor -> [ParamName]
findCollidingParamNames cmdDescriptor =
  let cmdContextPNames = nub $ concatMap (map pName . contextMapping) (cmdContexts cmdDescriptor) -- collisions within AcceptedContext should not count
      additionalPNames = map pName (cmdAdditionalParams cmdDescriptor)
      allPNames = cmdContextPNames ++ additionalPNames
      uniquePNames = nub allPNames
   in nub (allPNames \\ uniquePNames)

formatParamNameCollisionErrorMsg :: [ParamCollision] -> String
formatParamNameCollisionErrorMsg paramCollisions =
  "Error: Parameter name collision in plugin description\n" ++
  "Parameter names must be unique for each command. The following collisions were found:\n" ++
    concatMap (\(ParamCollision plId cmd paramName occurences) ->
      ("In " ++ show plId ++ ":" ++ show cmd ++ " the parameter " ++ show paramName ++ " is defined in:\n" ++ unlines (map formatOccurence occurences)))
    paramCollisions
  where formatOccurence (AdditionalParam paramDesc)         = "    cmdAdditionalParams = " ++ show paramDesc
        formatOccurence (ContextParam paramDesc accContext) = "    cmdContexts = [" ++ show accContext ++ "]: " ++ show paramDesc


text:
package org.ohdsi.webapi.conceptset;

import com.opencsv.CSVWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.ohdsi.webapi.vocabulary.Concept;
import org.ohdsi.webapi.vocabulary.ConceptSetExpression;

/**
 *
 * @author Chris Knoll <cknoll@ohdsi.org>
 */
public class ExportUtil {

  public static ByteArrayOutputStream writeConceptSetExportToCSVAndZip(ArrayList<ConceptSetExport> conceptSetExportList) throws RuntimeException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    StringWriter sw;
    CSVWriter csvWriter;
    String[] headings;
    try {
      // Write Concept Set Expression to a CSV
      sw = new StringWriter();
      csvWriter = new CSVWriter(sw);
      ArrayList<String[]> allLines = new ArrayList<String[]>();
      headings = "Concept Set ID#Name#Concept ID#Concept Code#Concept Name#Domain#Vocabulary#Standard Concept#Exclude#Descendants#Mapped".split("#");
      allLines.add(headings);
      for (ConceptSetExport cs : conceptSetExportList) {
        for (ConceptSetExpression.ConceptSetItem item : cs.csExpression.items) {
          ArrayList<String> csItem = new ArrayList<String>();
          csItem.add(String.valueOf(cs.ConceptSetId));
          csItem.add(cs.ConceptSetName);
          csItem.add(String.valueOf(item.concept.conceptId));
          csItem.add(String.valueOf(item.concept.conceptCode));
          csItem.add(item.concept.conceptName);
          csItem.add(item.concept.domainId);
          csItem.add(item.concept.vocabularyId);
          csItem.add(item.concept.standardConcept);
          csItem.add(String.valueOf(item.isExcluded));
          csItem.add(String.valueOf(item.includeDescendants));
          csItem.add(String.valueOf(item.includeMapped));
          allLines.add(csItem.toArray(new String[0]));
        }
      }
      csvWriter.writeAll(allLines);
      csvWriter.flush();

      ZipEntry resultsEntry = new ZipEntry("conceptSetExpression.csv");
      zos.putNextEntry(resultsEntry);
      zos.write(sw.getBuffer().toString().getBytes());

      // Write included concepts to a CSV
      sw = new StringWriter();
      csvWriter = new CSVWriter(sw);
      allLines = new ArrayList<>();
      headings = "Concept Set ID#Name#Concept ID#Concept Code#Concept Name#Concept Class ID#Domain#Vocabulary".split("#");
      allLines.add(headings);
      for (ConceptSetExport cs : conceptSetExportList) {
        for (Concept c : cs.identifierConcepts) {
          ArrayList<String> csItem = new ArrayList<>();
          csItem.add(String.valueOf(cs.ConceptSetId));
          csItem.add(cs.ConceptSetName);
          csItem.add(String.valueOf(c.conceptId));
          csItem.add(String.valueOf(c.conceptCode));
          csItem.add(c.conceptName);
          csItem.add(c.conceptClassId);
          csItem.add(c.domainId);
          csItem.add(c.vocabularyId);
          allLines.add(csItem.toArray(new String[0]));
        }
      }
      csvWriter.writeAll(allLines);
      csvWriter.flush();

      resultsEntry = new ZipEntry("includedConcepts.csv");
      zos.putNextEntry(resultsEntry);
      zos.write(sw.getBuffer().toString().getBytes());

      // Write mapped concepts to a CSV
      sw = new StringWriter();
      csvWriter = new CSVWriter(sw);
      allLines = new ArrayList<>();
      headings = "Concept Set ID#Name#Concept ID#Concept Code#Concept Name#Concept Class ID#Domain#Vocabulary".split("#");
      allLines.add(headings);
      for (ConceptSetExport cs : conceptSetExportList) {
        for (Concept c : cs.mappedConcepts) {
          ArrayList<String> csItem = new ArrayList<>();
          csItem.add(String.valueOf(cs.ConceptSetId));
          csItem.add(cs.ConceptSetName);
          csItem.add(String.valueOf(c.conceptId));
          csItem.add(String.valueOf(c.conceptCode));
          csItem.add(c.conceptName);
          csItem.add(c.conceptClassId);
          csItem.add(c.domainId);
          csItem.add(c.vocabularyId);
          allLines.add(csItem.toArray(new String[0]));
        }
      }
      csvWriter.writeAll(allLines);
      csvWriter.flush();

      resultsEntry = new ZipEntry("mappedConcepts.csv");
      zos.putNextEntry(resultsEntry);
      zos.write(sw.getBuffer().toString().getBytes());

      zos.closeEntry();
      zos.close();
      baos.flush();
      baos.close();
      return baos;
    } catch (IOException ex) {
      throw new RuntimeException(ex);
    }

  }
}


text:
Lightweight js library for detecting collisions between circles and rectangles (2d)

## Usage ##
```
// Creates a new Rectangle at (0, 0) with (100x100) dimensions.
var myRect = new Crash2D.Rect(0, 0, 100, 100);
// Creates a new Circle at (50, 50) with a radius of 30
var myCircle = new Crash2D.Circle(50, 50, 30);

// The collides() can be used from any Crash2D polygon and accepts any other Crash2D polygon as an argument
if (myRect.collides(myCricle)){
  // Collision code
}
```

## Docs ##

### Crash2D.Rect Class###

#### Constructor ####

**Crash2D.Rect** *(x, y, width, height)*

#### Properties ####

- x: **(Number)** *X coord*
- y: **(Number)** *Y coord*
- width: **(Number)** *Rectangle's width*
- height: **(Number)** *Rectangle's height*

#### Methods ####

  - ***collides (polygon) boolean*** Checks if the object is colliding with *polygon* (can be any Crash2D polygon).

### Crash2D.Circle Class###

#### Constructor ####

**Crash2D.Circle** *(x, y, radius)*

#### Properties ####

- x: **(Number)** *X coord of the center*
- y: **(Number)** *Y coord of the center*
- radius: **(Number)** *Circle's radius*

#### Methods ####

  - ***collides (polygon) boolean*** Checks if the object is colliding with *polygon* (can be any Crash2D polygon).


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;

namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
    internal class HiddenKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
    {
        public HiddenKeywordRecommender()
            : base(SyntaxKind.HiddenKeyword, isValidInPreprocessorContext: true)
        {
        }

        protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
        {
            // cases:
            //   #line |
            //   #line h|
            //   # line |
            //   # line h|

            var previousToken1 = context.TargetToken;
            var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true);

            return
                previousToken1.Kind() == SyntaxKind.LineKeyword &&
                previousToken2.Kind() == SyntaxKind.HashToken;
        }
    }
}