text:
Network AutoSwitch will automatically disable or enable wired and wireless network adapters according to network connection. Depending on the priority selected (Wired or Wireless), when you disconnect your computer from the wireless network it will enable wired adapters automatically or it will enable wireless network adapters when wired network is disabled.

Proxy AutoSwitch will automatically disable or enable IE proxy server according to network connection. When you disconnect your computer from the wireless network or the wired network adapters are disabled, it will enable or disable IE proxy server depending on the chosen configuration.

## [Download now](https://github.com/Tulpep/Network-AutoSwitch/releases/latest)

Network AutoSwitch and Proxy AutoSwitch can run in interactive mode for your testing purposes and also can run as Windows Service. In Windows Service mode it will work in background without user interaction. You can distribute it using Active Directory or your current deployment software solution to use it as part of your networking hardening strategy.

# How to use it
-p or --priority flag are mandatory to choose the right configuration, passing "Wired" or "Wireless" parameters. Administrative rights are neccesary to enable or disable network interfaces. Run using a command prompt with administative rights as:
```bash
NetworkAutoSwitch.exe -p Wired
```
or

```bash
NetworkAutoSwitch.exe -p Wireless
```
When using as a Windows Service it will work for all users in the machine, even it they dont have Windows administrative rights. It will start automatically with your System. You must choose also the priority when
To install it run it as:
```bash
NetworkAutoSwitch.exe --install -p Wired
```

To uninstall it run as:
```bash
NetworkAutoSwitch.exe --uninstall
```

Proxy AutoSwitch can be used in the same way as NetworkAutoSwitch. The priority flag is also mandatory.

```bash
ProxyAutoSwitch.exe -p Wired
```
or

```bash
ProxyAutoSwitch.exe -p Wireless
```

and

To install it run it as:
```bash
ProxyAutoSwitch.exe --install -p Wireless
```

To uninstall it run as:
```bash
ProxyAutoSwitch.exe --uninstall
```

**This project is supported. Your issues will be handle by our team and we are open to your PRs!**


text:
require 'tmpdir'
require 'csv'
require 'rspec/expectations'
require 'posix/spawn'
require 'active_support/core_ext'

redpajama_set_name: RedPajamaGithub


text:
namespace _04.GeneratePermutations
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    /// <summary>
    /// Write a recursive program for generating and printing all permutations of the numbers 1, 2, ..., n for given integer number n. Example:
    /// n=3  {1, 2, 3}, {1, 3, 2}, {2, 1, 3},					{2, 3, 1}, {3, 1, 2},{3, 2, 1}
    /// </summary>
    public class Program
    {
        private static int[] array;
        private static int[] checkArray;

        public static void Main(string[] args)
        {
            int n = 3;
            array = new int[n];
            checkArray = new int[n];

            Permutate(0);
        }

        private static void Permutate(int index)
        {
            if (index >= array.Length)
            {
                Console.WriteLine(string.Join(" ", array));
                return;
            }

            for (int i = 0; i < checkArray.Length; i++)
            {
                if (checkArray[i] == 1)
                {
                    continue;
                }

                array[index] = i + 1;
                checkArray[i] = 1;
                Permutate(index + 1);
                checkArray[i] = 0;
            }
        }
    }
}


text:
{% extends 'layout.html' %}

	{% block pageTitle %}
		State Pension Activation
	{% endblock %}

	{% block content %}

			{% include 'includes/parts/phase-banner.html' %}

Come back when you want your State Pension

Choosing to delay your claim by more than 9 weeks means you could earn extra State Pension.

					You can only claim your State Pension using this service if you want to
					claim from your State Pension age and up to 9 weeks after this date.

					Come back when you want to make your claim.

Want your State Pension as soon as possible?

          {% include 'includes/parts/help.html' %}

	{% endblock %}


text:
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include <xercesc/sax2/DefaultHandler.hpp>
#include <xercesc/util/XMLString.hpp>

#include <iostream>
#include <list>
#include "scene.hh"
#include "xmlparser4scene.hh"

using namespace std;
using namespace xercesc;

/*!
 * Czyta z pliku opis sceny i zapisuje stan sceny do parametru,
 * który ją reprezentuje.
 * \param sFileName - (\b we.) nazwa pliku z opisem poleceń.
 * \param Scn - (\b we.) reprezentuje scenę, na której ma działać robot.
 * \retval true - jeśli wczytanie zostało zrealizowane poprawnie,
 * \retval false - w przeciwnym przypadku.
 */
bool ReadFile(const char* sFileName, Scene& Scn)
{
   try {
            XMLPlatformUtils::Initialize();
   }
   catch (const XMLException& toCatch) {
            char* message = XMLString::transcode(toCatch.getMessage());
            cerr << "Error during initialization! :\n";
            cerr << "Exception message is: \n"
                 << message << "\n";
            XMLString::release(&message);
            return 1;
   }

   SAX2XMLReader* pParser = XMLReaderFactory::createXMLReader();

   pParser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
   pParser->setFeature(XMLUni::fgSAX2CoreValidation, true);
   pParser->setFeature(XMLUni::fgXercesDynamic, false);
   pParser->setFeature(XMLUni::fgXercesSchema, true);
   pParser->setFeature(XMLUni::fgXercesSchemaFullChecking, true);

   pParser->setFeature(XMLUni::fgXercesValidationErrorAsFatal, true);

   DefaultHandler* pHandler = new XMLParser4Scene(Scn);
   pParser->setContentHandler(pHandler);
   pParser->setErrorHandler(pHandler);

   try {

     if (!pParser->loadGrammar("grammar/opis_sceny.xsd",
                              xercesc::Grammar::SchemaGrammarType,true)) {
       cerr << "!!! Plik grammar/twarz_robota.xsd, '" << endl
            << "!!! ktory zawiera opis gramatyki, nie moze zostac wczytany."
            << endl;
       return false;
     }
     pParser->setFeature(XMLUni::fgXercesUseCachedGrammarInParse,true);
     pParser->parse(sFileName);
   }
   catch (const XMLException& Exception) {
            char* sMessage = XMLString::transcode(Exception.getMessage());
            cerr << "Informacja o wyjatku: \n"
                 << "   " << sMessage << "\n";
            XMLString::release(&sMessage);
            return false;
   }
   catch (const SAXParseException& Exception) {
            char* sMessage = XMLString::transcode(Exception.getMessage());
            char* sSystemId = xercesc::XMLString::transcode(Exception.getSystemId());

            cerr << "Blad! " << endl
                 << "    Plik:  " << sSystemId << endl
                 << "   Linia: " << Exception.getLineNumber() << endl
                 << " Kolumna: " << Exception.getColumnNumber() << endl
                 << " Informacja: " << sMessage
                 << endl;

            XMLString::release(&sMessage);
            XMLString::release(&sSystemId);
            return false;
   }
   catch (...) {
            cout << "Zgloszony zostal nieoczekiwany wyjatek!\n" ;
            return false;
   }

   delete pParser;
   delete pHandler;
   return true;
}

int main (int argc, char* args[])
{
   Scene  Scn;

   if (!ReadFile("opis_sceny.xml",Scn)) return 1;

   cout << endl;
}


text:
package de.niklasfauth.litewave.objects;

import java.io.Serializable;

import com.oceanoptics.omnidriver.api.wrapper.Wrapper;

public class SpectrometerSettings implements Serializable {

	private static Wrapper wrapper;
	private static int[] settings = {1, 0};
	/*
	private static LinkedList<Double> wavelength;
	private static LinkedList<Double> rawValues;

	private static LinkedList<Double> wavelengthPeak;
	private static LinkedList<Double> valuesPeak;

	private static float offset;
	private static float maxOffset;
	private static float perPeak;

	private static String resultString = "";

	private static String peakResultString = "[]";

	private static String peakResultList = "";

	private static LinkedList<Double> peakWavelength = new LinkedList<Double>();
*/

	public SpectrometerSettings(Wrapper configWrapper) {
		this.wrapper = configWrapper;
	}

	public static Wrapper getSpectrometerWrapper() {
		return wrapper;
	}

	public static void setSpectrometerSettings(int avgct, int integrationTime) {
		settings[0] = avgct;
		settings[1] = integrationTime;
	}

	public static int[] getSpectrometerSettings() {
		return settings;
	}

}


text:
import pytest
from graphapi.schema import schema
from openstates.data.models import Organization, Person
from .utils import populate_db

@pytest.mark.django_db
def setup():
    populate_db()

@pytest.mark.django_db
def test_jurisdictions(django_assert_num_queries):
    with django_assert_num_queries(2):
        result = schema.execute(
            """ {
            jurisdictions {
                edges {
                    node {
                        name
                    }
            }
        }
        }
    """
        )
    assert result.errors is None
    assert result.data["jurisdictions"]["edges"][0]["node"]["name"] == "Alaska"
    assert result.data["jurisdictions"]["edges"][1]["node"]["name"] == "Wyoming"

@pytest.mark.django_db
def test_jurisdictions_num_queries(django_assert_num_queries):
    with django_assert_num_queries(4):
        result = schema.execute(
            """ {
            jurisdictions {
                edges {
                    node {
                        name
                        legislativeSessions {
                            edges { node { identifier } }
                        }
                        organizations(first: 50) {
                            edges { node { name } }
                        }
                    }
            }
        }
        }
    """
        )
    assert result.errors is None
    assert (
        len(
            result.data["jurisdictions"]["edges"][0]["node"]["legislativeSessions"][
                "edges"
            ]
        )
        == 2
    )
    assert (
        len(result.data["jurisdictions"]["edges"][0]["node"]["organizations"]["edges"])
        == 3
    )

@pytest.mark.django_db
def test_jurisdictions_num_queries_subquery(django_assert_num_queries):
    # same as test_jurisdictions_num_queries but with slightly more complex filtering on nodes
    with django_assert_num_queries(4):
        result = schema.execute(
            """ {
            jurisdictions {
                edges {
                    node {
                        name
                        legislativeSessions(first: 1) {
                            edges { node { identifier } }
                        }
                        organizations(classification: "legislature", first: 50) {
                            edges { node { name } }
                        }
                    }
            }
        }
        }
    """
        )
    assert result.errors is None
    assert (
        len(
            result.data["jurisdictions"]["edges"][0]["node"]["legislativeSessions"][
                "edges"
            ]
        )
        == 1
    )
    assert (
        len(result.data["jurisdictions"]["edges"][0]["node"]["organizations"]["edges"])
        == 1
    )

@pytest.mark.django_db
def test_jurisdiction_by_id(django_assert_num_queries):
    with django_assert_num_queries(5):
        result = schema.execute(
            """ {
            jurisdiction(id:"ocd-jurisdiction/country:us/state:wy/government") {
                name
                legislativeSessions(first: 1) {
                    edges { node { identifier } }
                }
                organizations(classification: "legislature", first: 50) {
                    edges { node { name } }
                }
            }
        }
    """
        )
    assert result.errors is None
    assert len(result.data["jurisdiction"]["legislativeSessions"]["edges"]) == 1
    assert len(result.data["jurisdiction"]["organizations"]["edges"]) == 1

@pytest.mark.django_db
def test_jurisdiction_by_name(django_assert_num_queries):
    with django_assert_num_queries(5):
        result = schema.execute(
            """ {
            jurisdiction(name:"Wyoming") {
                name
                legislativeSessions(first: 1) {
                    edges { node { identifier } }
                }
                organizations(classification: "legislature", first: 50) {
                    edges { node { name } }
                }
            }
        }
    """
        )
    assert result.errors is None
    assert len(result.data["jurisdiction"]["legislativeSessions"]["edges"]) == 1
    assert len(result.data["jurisdiction"]["organizations"]["edges"]) == 1

@pytest.mark.django_db
def test_jurisdiction_chambers_current_members(django_assert_num_queries):
    with django_assert_num_queries(5):
        result = schema.execute(
            """ {
            jurisdiction(name:"Wyoming") {
                chambers: organizations(classification:["upper", "lower"], first:2)
                { edges { node {
                    name
                    currentMemberships {
                        person { name }
                    }
                } }
                }
            }
        }
    """
        )
    assert result.errors is None
    assert len(result.data["jurisdiction"]["chambers"]["edges"]) == 2
    assert set(("Wyoming House", "Wyoming Senate")) == set(
        edge["node"]["name"]
        for edge in result.data["jurisdiction"]["chambers"]["edges"]
    )
    people = []
    for chamber in result.data["jurisdiction"]["chambers"]["edges"]:
        for m in chamber["node"]["currentMemberships"]:
            people.append(m["person"]["name"])
    assert len(people) == 2

@pytest.mark.django_db
def test_people_by_member_of(django_assert_num_queries):
    ak_house = Organization.objects.get(
        jurisdiction__name="Alaska", classification="lower"
    )
    with django_assert_num_queries(2):
        result = schema.execute(
            """ {
            people(memberOf: "%s", first: 50) {
                edges {
                    node {
                        name
                    }
                }
            }
        }
    """
            % ak_house.id
        )
    assert result.errors is None
    assert len(result.data["people"]["edges"]) == 4

@pytest.mark.django_db
def test_variable_people_by_member_of(django_assert_num_queries):
    ak_house = Organization.objects.get(
        jurisdiction__name="Alaska", classification="lower"
    )
    with django_assert_num_queries(2):
        result = schema.execute(
            """
            query peeps($f: Int){
                people(memberOf: "%s", first: $f) {
                    edges {
                        node {
                            name
                        }
                    }
                }
            }
        """
            % ak_house.id,
            variable_values={"f": 3},
        )
    assert result.errors is None
    assert len(result.data["people"]["edges"]) == 3

@pytest.mark.django_db
def test_people_by_ever_member_of(django_assert_num_queries):
    ak_house = Organization.objects.get(
        jurisdiction__name="Alaska", classification="lower"
    )
    with django_assert_num_queries(2):
        result = schema.execute(
            """ {
            people(everMemberOf: "%s", first:50) {
                edges {
                    node {
                        name
                    }
                }
            }
        }
    """
            % ak_house.id
        )
    assert result.errors is None
    # one extra person (Ellen Evil) is added as a former member of the House
    assert len(result.data["people"]["edges"]) == 5

@pytest.mark.django_db
def test_people_by_district():
    ak_house = Organization.objects.get(
        jurisdiction__name="Alaska", classification="lower"
    )
    result = schema.execute(
        """ {
        ones: people(memberOf: "%s", district: "1", first: 50) {
            edges { node { name } }
        }
        fives: people(everMemberOf: "%s", district: "5", first: 50) {
            edges { node { name } }
        }
        bad: people(district: "1", first: 50) {
            edges { node { name } }
        }
    }
    """
        % (ak_house.id, ak_house.id)
    )
    assert "'district' parameter requires" in result.errors[0].message
    assert len(result.data["ones"]["edges"]) == 1
    assert len(result.data["fives"]["edges"]) == 1
    assert result.data["bad"] is None

@pytest.mark.django_db
def test_people_by_division_id():
    # Note: uses a fake divisionId that has two reps (one retired), only one should be returned
    result = schema.execute(
        """ {
        people(divisionId: "ocd-division/country:us/state:ak/sldu:b", first: 50) {
            edges { node { name } }
        }
    }
    """
    )
    assert len(result.data["people"]["edges"]) == 1

@pytest.mark.django_db
def test_people_by_name():
    result = schema.execute(
        """ {
        people(name: "Hank", first: 50) {
            edges { node { name } }
        }
    }
    """
    )
    assert result.errors is None
    assert len(result.data["people"]["edges"]) == 1

@pytest.mark.django_db
def test_people_by_party():
    result = schema.execute(
        """ {
        dems: people(memberOf: "Democratic", first: 50) {
            edges { node { name } }
        }
        reps: people(memberOf: "Republican", first: 50) {
            edges { node { name } }
        }
    }
    """
    )
    assert result.errors is None
    assert len(result.data["dems"]["edges"]) == 3
    assert len(result.data["reps"]["edges"]) == 4

# @pytest.mark.django_db
# def test_people_by_location():
#     # TODO: need data to test with
#     pass

@pytest.mark.django_db
def test_people_num_queries(django_assert_num_queries):
    with django_assert_num_queries(8):
        result = schema.execute(
            """ {
        people(first: 50) {
            edges {
                node {
                    name
                    image
                    identifiers { identifier }
                    otherNames { name }
                    links { url }
                    sources { url }
                    contactDetails { value label }
                    offices { classification displayName voice fax address }
                    currentMemberships {
                        post {
                            label
                            division {
                                id
                            }
                        }
                        organization { name }
                    }
                }
            }
        }
        }"""
        )
    assert result.errors is None
    assert len(result.data["people"]["edges"]) == 9
    total_memberships = 0
    for person in result.data["people"]["edges"]:
        total_memberships += len(person["node"]["currentMemberships"])
    assert total_memberships == 16  # 8 chambers + 8 parties

@pytest.mark.django_db
def test_people_total_count(django_assert_num_queries):
    with django_assert_num_queries(2):
        result = schema.execute(
            """ {
        people(first: 50) {
            totalCount
            edges {
                node {
                    name
                }
            }
        }
        }"""
        )
    assert result.errors is None
    assert result.data["people"]["totalCount"] == 9
    assert len(result.data["people"]["edges"]) == 9

    with django_assert_num_queries(2):
        result = schema.execute(
            """ {
        people(first: 50, name: "Amanda") {
            totalCount
            edges {
                node {
                    name
                }
            }
        }
        }"""
        )
    assert result.errors is None
    assert result.data["people"]["totalCount"] == 1
    assert len(result.data["people"]["edges"]) == 1

@pytest.mark.django_db
def test_people_current_memberships_classification(django_assert_num_queries):
    with django_assert_num_queries(3):
        result = schema.execute(
            """ {
        people(first: 50) {
            edges {
                node {
                    currentMemberships(classification: "party") {
                        organization { name }
                    }
                }
            }
        }
        }"""
        )
    assert result.errors is None
    total_memberships = 0
    for person in result.data["people"]["edges"]:
        total_memberships += len(person["node"]["currentMemberships"])
    assert total_memberships == 8  # Only the 8 parties should be returned

@pytest.mark.django_db
def test_people_old_memberships(django_assert_num_queries):
    with django_assert_num_queries(3):
        result = schema.execute(
            """{
        people(first: 50) {
            edges {
                node {
                    oldMemberships {
                        organization { name }
                    }
                }
            }
        }
        }"""
        )
    assert result.errors is None
    old_memberships = 0
    for person in result.data["people"]["edges"]:
        old_memberships += len(person["node"]["oldMemberships"])
    assert old_memberships == 3  # three old memberships in test data right now

@pytest.mark.django_db
def test_person_by_id(django_assert_num_queries):
    person = Person.objects.get(name="Bob Birch")
    with django_assert_num_queries(7):
        result = schema.execute(
            """ {
        person(id:"%s") {
            name
            image
            primaryParty
            email
            identifiers { identifier }
            otherNames { name }
            links { url }
            sources { url }
            offices { classification displayName voice fax address }
            currentMemberships {
                post {
                    label
                    division {
                        id
                    }
                }
                organization { name }
            }
        }
        }"""
            % person.id
        )
    assert result.errors is None
    assert result.data["person"]["name"] == "Bob Birch"
    assert result.data["person"]["primaryParty"] == "Republican"
    assert len(result.data["person"]["currentMemberships"]) == 2

    division = None
    for membership in result.data["person"]["currentMemberships"]:
        if membership["post"]:
            division = membership["post"]["division"]
            break
    assert division["id"] == "ocd-division/country:us/state:ak/sldl:2"

@pytest.mark.django_db
def test_person_email_shim(django_assert_num_queries):
    # email used to be available in contact_details, make sure they can still find it there
    person = Person.objects.get(name="Bob Birch")
    person.email = "bob@example.com"
    person.save()
    result = schema.execute(
        """ {
    person(id:"%s") {
        name
        email
        contactDetails { value note type }
    }
    }"""
        % person.id
    )
    assert result.errors is None
    assert result.data["person"]["name"] == "Bob Birch"
    assert result.data["person"]["email"] == "bob@example.com"
    assert result.data["person"]["contactDetails"][0] == {
        "value": "bob@example.com",
        "type": "email",
        "note": "Capitol Office",
    }

@pytest.mark.django_db
def test_person_contact_details_shim(django_assert_num_queries):
    # make sure contactDetails populates properly from office data
    person = Person.objects.get(name="Bob Birch")
    person.offices.create(
        classification="district",
        voice="123-456-7890",
        address="123 Boogie Woogie Ave",
    )
    result = schema.execute(
        """ {
    person(id:"%s") {
        name
        email
        contactDetails { value note type }
    }
    }"""
        % person.id
    )
    assert result.errors is None
    assert result.data["person"]["name"] == "Bob Birch"
    assert result.data["person"]["contactDetails"] == [
        {"value": "123-456-7890", "type": "voice", "note": "District Office"},
        {
            "value": "123 Boogie Woogie Ave",
            "type": "address",
            "note": "District Office",
        },
    ]

@pytest.mark.django_db
def test_organization_by_id(django_assert_num_queries):
    # get targets
    leg = Organization.objects.get(
        jurisdiction__name="Wyoming", classification="legislature"
    )
    sen = Organization.objects.get(jurisdiction__name="Wyoming", classification="upper")

    # 1 query for legislature, 1 query each for children
    # 1 query for senate w/ parent
    with django_assert_num_queries(4):
        result = schema.execute(
            """ {
            leg: organization(id: "%s") {
                name
                classification
                children(classification: "upper", first: 50) {
                    edges { node { classification } }
                }
                links { url }
                sources { url }
            }
            senate: organization(id: "%s") {
                name
                parent {
                    name
                }
            }
        }
    """
            % (leg.id, sen.id)
        )
    assert result.errors is None
    assert len(result.data["leg"]["children"]["edges"]) == 1
    assert result.data["senate"]["parent"]["name"] == "Wyoming Legislature"

@pytest.mark.django_db
def test_people_by_updated_since():
    middle_date = Person.objects.all().order_by("updated_at")[2].updated_at

    result = schema.execute(
        """{
        all: people(updatedSince: "2017-01-01T00:00:00Z", last:50) {
            edges { node { name } }
        }
        some: people(updatedSince: "%s", first:50) {
            edges { node { name } }
        }
        none: people(updatedSince: "2030-01-01T00:00:00Z", first:50) {
            edges { node { name } }
        }
    }"""
        % middle_date
    )

    assert result.errors is None
    assert len(result.data["all"]["edges"]) == 9
    assert len(result.data["some"]["edges"]) == 7
    assert len(result.data["none"]["edges"]) == 0

@pytest.mark.django_db
def test_jurisdiction_fragment(django_assert_num_queries):
    with django_assert_num_queries(3):
        result = schema.execute(
            """
    fragment JurisdictionFields on JurisdictionNode {
      id
      name
      url
      legislativeSessions {
        edges {
          node {
            name
            startDate
            endDate
            classification
            identifier
          }
        }
      }
    }

    query jurisdictionsQuery {
      jurisdictions {
        edges {
          node {
            ...JurisdictionFields
          }
        }
      }
    }"""
        )
    assert result.errors is None


text:
<?php

namespace dosamigos\ckeditor;

use yii\helpers\ArrayHelper;

/**
 * CKEditorTrait has common methods for both CKEditor and CKEditorInline widgets.
 *
 * @author Antonio Ramirez <amigo.cobos@gmail.com>
 * @link http://www.ramirezcobos.com/
 * @link http://www.2amigos.us/
 * @package dosamigos\ckeditor
 */
trait CKEditorTrait
{
    /**
     * @var string the toolbar preset. It can be any of the following:
     *
     * - basic: will load the configuration on presets/basic.php
     * - full: will load the configuration on presets/full.php
     * - standard: will load the configuration on presets/standard.php
     * - custom: configuration will be based on [[clientOptions]].
     *
     * Defaults to 'standard'. It is important to note that any configuration item of the loaded presets can be
     * overrided by [[clientOptions]]
     */
    public $preset = 'standard';

    /**
     * @var array the options for the CKEditor 4 JS plugin.
     * Please refer to the CKEditor 4 plugin Web page for possible options.
     * @see http://docs.ckeditor.com/#!/guide/dev_installation
     */
    public $clientOptions = [];

    /**
     * Initializes the widget options.
     * This method sets the default values for various options.
     */
    protected function initOptions()
    {
        $options = [];
        switch ($this->preset) {
            case 'custom':
                $preset = null;
                break;
            case 'basic':
            case 'full':
            case 'standard':
                $preset = __DIR__ . '/presets/' . $this->preset . '.php';
                break;
            default:
                $preset = __DIR__ . '/presets/standard.php';
        }
        if ($preset !== null) {
            $options = require($preset);
        }
        $this->clientOptions = ArrayHelper::merge($options, $this->clientOptions);
    }
}


text:
Sponsored by **us:**

- Check out the [**courses over at Talk Python**](https://training.talkpython.fm/courses/all)
- And [**Brian's book too**](https://pythontest.com/pytest-book/)!

**Michael #1:** [**awesome-htmx**](https://github.com/rajasegar/awesome-htmx)

- An awesome list of resources about **htmx** such as articles, posts, videos, talks and more.
- Good for all sorts of examples and multiple languages
- We get a few nice shoutouts, thanks

**Brian #2:** [**Python 3.10 is here !!!!**](https://www.python.org/downloads/release/python-3100/)

- As of Monday. Of course I have it installed on Mac and Windows. Running like a charm.
- You can watch the [Release Party recording](https://t.co/sK5SmgXpif?amp=1). It's like 3 hours. And starts with hats. Pablo's is my fav.
- Also a [What's New video](https://www.youtube.com/watch?v=JteTO3EE7y0&t=1s) which aired before that with Brandt Bucher, Lukasz Llanga ,and Sebastian Ramirez (33 min)
	- Includes a deep dive into structural pattern matching that I highly recommend.
- Reminder of new features:
	- [PEP 623](https://www.python.org/dev/peps/pep-0623/) -- Deprecate and prepare for the removal of the wstr member in PyUnicodeObject.
	- PEP 604 -- Allow writing union types as X | Y
	- [PEP 612](https://www.python.org/dev/peps/pep-0612/) -- Parameter Specification Variables
	- [PEP 626](https://www.python.org/dev/peps/pep-0626/) -- Precise line numbers for debugging and other tools.
	- [PEP 618](https://www.python.org/dev/peps/pep-0618/) -- Add Optional Length-Checking To zip.
	- [bpo-12782](https://bugs.python.org/issue12782): Parenthesized context managers are now officially allowed.
	- [PEP 632](https://www.python.org/dev/peps/pep-0632/) -- Deprecate distutils module.
	- [PEP 613](https://www.python.org/dev/peps/pep-0613/) -- Explicit Type Aliases
	- [PEP 634](https://www.python.org/dev/peps/pep-0634/) -- Structural Pattern Matching: Specification
	- [PEP 635](https://www.python.org/dev/peps/pep-0635/) -- Structural Pattern Matching: Motivation and Rationale
	- [PEP 636](https://www.python.org/dev/peps/pep-0636/) -- Structural Pattern Matching: Tutorial
	- [PEP 644](https://www.python.org/dev/peps/pep-0644/) -- Require OpenSSL 1.1.1 or newer
	- [PEP 624](https://www.python.org/dev/peps/pep-0624/) -- Remove Py_UNICODE encoder APIs
	- [PEP 597](https://www.python.org/dev/peps/pep-0597/) -- Add optional EncodingWarning
- Takeaway I wasn't expecting: `black` doesn't handle Structural Pattern Matching yet.

**Yael #3:** [Prospector -](https://github.com/PyCQA/prospector) [(almost)](https://github.com/PyCQA/prospectors) [All Python analysis tools together](https://github.com/PyCQA/prospector)

- Instead of running pylint, pycodestyle, mccabe and other separately, prospector allows you to bundle them all together
- Includes the common [Pylint](https://www.pylint.org/) and [Pydocstyle / Pep257](https://github.com/PyCQA/pydocstyle), but also some other less common goodies, such as [Mccabe](https://github.com/PyCQA/mccabe), [Dodgy](https://github.com/landscapeio/dodgy), [Vulture](https://github.com/jendrikseipp/vulture), [Bandit](https://github.com/PyCQA/bandit), [Pyroma](https://github.com/regebro/pyroma) and many others
- Relatively easy configuration that supports profiles, for different cases
- Built-in support for celery, Flask and Django frameworks
- [https://soshace.com/how-to-use-prospector-for-python-static-code-analysis/](https://soshace.com/how-to-use-prospector-for-python-static-code-analysis/)

**Michael #****4****:** [**Rich Pandas DataFrames**](https://twitter.com/__aviperl__/status/1442542251817652228)

- via Avi Perl, by Khuyen Tran
- Create animated and pretty Pandas Dataframe or Pandas Series (in the terminal, using Rich)
- I just had Will over on Talk Python last week BTW: [**Terminal magic with Rich and Textual**](https://talkpython.fm/episodes/show/336/terminal-magic-with-rich-and-textual)
- Can limit rows, control the animation speed, show head or tail, go "full screen" with clear, etc.
- Example:
```
    from sklearn.datasets import fetch_openml
    from rich_dataframe import prettify

    speed_dating = fetch_openml(name='SpeedDating', version=1)['frame']
    table = prettify(speed_dating)
```

**Brian #5:**  **Union types, baby!**

- From Python 3.10: "[PEP 604](https://www.python.org/dev/peps/pep-0604/) -- Allow writing union types as X | Y"
- Use as possibly not intended, to avoid Optional:
```
    def foo(x: str | None = None) -> None:
      pass
```
- 3.9 example:
```
    from typing import Optional
    def foo(x: Optional[str] = None) -> None:
      pass
```
- But here's the issue. I need to support Python 3.9 at least, and probably early, what should I do?
- For 3.7 and above, you can use `from __future__ import annotations`.
- And of course Anthony Sottile worked this into `pyupgrade` and Adam Johnson wrote about it:
	- [Python Type Hints - How to Upgrade Syntax with pyupgrade](https://adamj.eu/tech/2021/05/21/python-type-hints-how-to-upgrade-syntax-with-pyupgrade/)
- This article covers:
	- [PEP 585](https://www.python.org/dev/peps/pep-0585/) added generic syntax to builtin types. This allows us to write e.g. `list[int]` instead of using `typing.List[int]`.
	- [PEP 604](https://www.python.org/dev/peps/pep-0604/) added the `|` operator as union syntax. This allows us to write e.g. `int | str` instead of `typing.Union[int, str]`, and `int | None` instead of `typing.Optional[int]`.
	- How to use these. What they look like. And how to use `pyupgrade` to just convert your code for you if you've already written it the old way. Awesome.

**Yael #6:** [**Make your code darker - Improving Python code incrementally**](https://dev.to/akaihola/improving-python-code-incrementally-3f7a)

- The idea behind [Darker](https://pypi.org/project/darker) is to reformat code using [Black](https://pypi.org/project/black) (and optionally [isort](https://pypi.org/project/isort)), but only apply new formatting to regions which have been modified by the developer
- Instead of having one huge PR,  darker allows you to reformat the code gradually, when you're touching the code for other reasons..
- Every modified line, will be black formatted
- Once added to [Git pre-commit-hook](https://github.com/akaihola/darker#using-as-a-pre-commit-hook), or added to [PyCharm](https://github.com/akaihola/darker#pycharmintellij-idea) [****](https://github.com/akaihola/darker#pycharmintellij-idea)/ [VScode](https://github.com/akaihola/darker#visual-studio-code) the formatting will happen automatically

**Extras**

Brian:

- I got a couple PRs accepted into pytest. So that's fun:
	- [9133: Add a deselected parameter to assert_outcomes()](https://github.com/pytest-dev/pytest/pull/9133)
	- [9134: Add a pythonpath setting to allow paths to be added to sys.path](https://github.com/pytest-dev/pytest/pull/9134)
	- I've tested, provided feedback, written about, and submitted issues to the project before. I've even contributed some test code. But these are the first source code contributions.
	- It was a cool experience. Great team there at pytest.

Michael:

- New htmx course: [**HTMX + Flask: Modern Python Web Apps, Hold the JavaScript**](https://training.talkpython.fm/courses/htmx-flask-modern-python-web-apps-hold-the-javascript?utm_source=pythonbytes)
- [**auto-optional**](https://pypi.org/project/auto-optional/): Due to the comments on the show I remembered to add support for `Union[X, None]` and python 10's `X | None` syntax.
- [Coverage 6.0 released](https://nedbatchelder.com/blog/202110/coverage_60.html)
- [Django 3.2.8 released](https://docs.djangoproject.com/en/3.2/releases/3.2.8/)

Yael:

- [data-oriented-programming](https://www.manning.com/books/data-oriented-programming) - an innovative approach to coding without OOP, with an emphasis on code and data separation, which simplifies state management and eases concurrency
- Help us to make [Cornell](https://github.com/hiredscorelabs/cornell) awesome 🙂 - contributors are warmly welcomed

**Joke:** [**Pair CAPTCHAing**](https://geek-and-poke.com/geekandpoke/2021/1/24/pair-captchaing)


text:
<?php
/**
 * New Install specific DB script
 *
 * @var modInstallRunner $this
 * @var modInstall $install
 * @var xPDO $modx
 * @var modInstallSettings $settings
 *
 * @package modx
 * @subpackage setup
 */
/* add settings_version */
$currentVersion = include MODX_CORE_PATH . 'docs/version.inc.php';

$settings_version = $modx->newObject('modSystemSetting');
$settings_version->set('key','settings_version');
$settings_version->set('value', $currentVersion['full_version']);
$settings_version->set('xtype','textfield');
$settings_version->set('namespace','core');
$settings_version->set('area','system');
$settings_version->save();

$settings_distro = $modx->newObject('modSystemSetting');
$settings_distro->set('key','settings_distro');
$settings_distro->set('value', trim($currentVersion['distro'], '@'));
$settings_distro->set('xtype','textfield');
$settings_distro->set('namespace','core');
$settings_distro->set('area','system');
$settings_distro->save();

/* add default admin user */
/** @var modUser $user */
$user = $modx->newObject('modUser');
$user->set('username', $settings->get('cmsadmin'));
$user->set('password', $settings->get('cmspassword'));
$user->setSudo(true);
$saved = $user->save();

if ($saved) {
    /** @var modUserProfile $userProfile */
    $userProfile = $modx->newObject('modUserProfile');
    $userProfile->set('internalKey', $user->get('id'));
    $userProfile->set('fullname', $install->lexicon('default_admin_user'));
    $userProfile->set('email', $settings->get('cmsadminemail'));
    $saved = $userProfile->save();
    if ($saved) {
        /** @var modUserGroupMember $userGroupMembership */
        $userGroupMembership = $modx->newObject('modUserGroupMember');
        $userGroupMembership->set('user_group', 1);
        $userGroupMembership->set('member', $user->get('id'));
        $userGroupMembership->set('role', 2);
        $saved = $userGroupMembership->save();

        $user->set('primary_group',1);
        $user->save();
    }
    if ($saved) {
        /** @var modSystemSetting $emailSender */
        $emailSender = $modx->getObject('modSystemSetting', array('key' => 'emailsender'));
        if ($emailSender) {
            $emailSender->set('value', $settings->get('cmsadminemail'));
            $saved = $emailSender->save();
        }
    }
}
if (!$saved) {
    $this->addResult(modInstallRunner::RESULT_ERROR,'
'.$install->lexicon('dau_err_save').'
' . print_r($modx->errorInfo(), true) . '
');
} else {
    $this->addResult(modInstallRunner::RESULT_SUCCESS,'
'.$install->lexicon('dau_saved').'
');
}

/* set new_folder_permissions/new_file_permissions if specified */
if ($install->settings->get('new_folder_permissions')) {
    /** @var modSystemSetting $settingsFolderPerms */
    $settingsFolderPerms = $modx->newObject('modSystemSetting');
    $settingsFolderPerms->set('key', 'new_folder_permissions');
    $settingsFolderPerms->set('value', $settings->get('new_folder_permissions'));
    $settingsFolderPerms->save();
}
if ($install->settings->get('new_file_permissions')) {
    /** @var modSystemSetting $settingsFilePerms */
    $settingsFilePerms = $modx->newObject('modSystemSetting');
    $settingsFilePerms->set('key', 'new_file_permissions');
    $settingsFilePerms->set('value', $settings->get('new_file_permissions'));
    $settingsFilePerms->save();
}

/* setup load only anonymous ACL */
/** @var modAccessPolicy $loadOnly */
$loadOnly = $modx->getObject('modAccessPolicy',array(
    'name' => 'Load Only',
));
if ($loadOnly) {
    /** @var modAccessContext $access */
    $access= $modx->newObject('modAccessContext');
    $access->fromArray(array(
      'target' => 'web',
      'principal_class' => 'modUserGroup',
      'principal' => 0,
      'authority' => 9999,
      'policy' => $loadOnly->get('id'),
    ));
    $access->save();
    unset($access);
}
unset($loadOnly);

/* setup default admin ACLs */
/** @var modAccessPolicy $adminPolicy */
$adminPolicy = $modx->getObject('modAccessPolicy',array(
    'name' => 'Administrator',
));
/** @var modUserGroup $adminGroup */
$adminGroup = $modx->getObject('modUserGroup',array(
    'name' => 'Administrator',
));
if ($adminPolicy && $adminGroup) {
    /** @var modAccessContext $access */
    $access= $modx->newObject('modAccessContext');
    $access->fromArray(array(
      'target' => 'mgr',
      'principal_class' => 'modUserGroup',
      'principal' => $adminGroup->get('id'),
      'authority' => 0,
      'policy' => $adminPolicy->get('id'),
    ));
    $access->save();
    unset($access);

    $access= $modx->newObject('modAccessContext');
    $access->fromArray(array(
      'target' => 'web',
      'principal_class' => 'modUserGroup',
      'principal' => $adminGroup->get('id'),
      'authority' => 0,
      'policy' => $adminPolicy->get('id'),
    ));
    $access->save();
    unset($access);
}
unset($adminPolicy,$adminGroup);

/* add base template and home resource */
$templateContent = file_get_contents(dirname(__DIR__) . '/templates/base_template.tpl');
/** @var modTemplate $template */
$template = $modx->newObject('modTemplate');
$template->fromArray(array(
    'templatename' => $install->lexicon('base_template'),
    'content' => $templateContent,
));
if ($template->save()) {

    /** @var modSystemSetting $setting */
    $setting = $modx->getObject('modSystemSetting',array(
        'key' => 'default_template',
    ));
    if (!$setting) {
        $setting = $modx->newObject('modSystemSetting');
        $setting->fromArray(array(
            'key' => 'default_template',
            'namespace' => 'core',
            'xtype' => 'modx-combo-template',
            'area' => 'site',
        ));
    }
    $setting->set('value', $template->get('id'));
    $setting->save();

    $resourceContent = file_get_contents(dirname(__DIR__) . '/templates/base_resource.tpl');
    /** @var modResource $resource */
    $resource = $modx->newObject('modResource');
    $resource->fromArray(array(
        'pagetitle' => $install->lexicon('home'),
        'longtitle' => $install->lexicon('congratulations'),
        'alias' => 'index',
        'contentType' => 'text/html',
        'type' => 'document',
        'published' => true,
        'content' => $resourceContent,
        'template' => $template->get('id'),
        'searchable' => true,
        'cacheable' => true,
        'createdby' => 1,
        'hidemenu' => false,
        'class_key' => 'modDocument',
        'context_key' => 'web',
        'content_type' => 1,
    ));

    if ($resource->save()) {

         /* site_start */
        $setting = $modx->getObject('modSystemSetting',array(
            'key' => 'site_start',
        ));
        if (!$setting) {
            $setting = $modx->newObject('modSystemSetting');
            $setting->fromArray(array(
                'key' => 'site_start',
                'namespace' => 'core',
                'xtype' => 'textfield',
                'area' => 'site',
            ));
        }
        $setting->set('value', $resource->get('id'));
        $setting->save();

    }

}

/* check for mb extension, set setting accordingly */
$usemb = function_exists('mb_strlen');
if ($usemb) {
    /** @var modSystemSetting $setting */
    $setting = $modx->getObject('modSystemSetting',array(
        'key' => 'use_multibyte',
    ));
    if (!$setting) {
        $setting = $modx->newObject('modSystemSetting');
        $setting->fromArray(array(
            'key' => 'use_multibyte',
            'namespace' => 'core',
            'xtype' => 'combo-boolean',
            'area' => 'language',
        ));
    }
    $setting->set('value',1);
    $setting->save();
}

/* if language != en, set cultureKey, manager_language, manager_lang_attribute to it */
$language = $settings->get('language','en');
if ($language != 'en') {
    /* cultureKey */
    $setting = $modx->getObject('modSystemSetting',array(
        'key' => 'cultureKey',
    ));
    if (!$setting) {
        $setting = $modx->newObject('modSystemSetting');
        $setting->fromArray(array(
            'key' => 'cultureKey',
            'namespace' => 'core',
            'xtype' => 'textfield',
            'area' => 'language',
        ));
    }
    $setting->set('value',$language);
    $setting->save();

    /* manager_language */
    $setting = $modx->getObject('modSystemSetting',array(
        'key' => 'manager_language',
    ));
    if (!$setting) {
        $setting = $modx->newObject('modSystemSetting');
        $setting->fromArray(array(
            'key' => 'manager_language',
            'namespace' => 'core',
            'xtype' => 'textfield',
            'area' => 'language',
        ));
    }
    $setting->set('value',$language);
    $setting->save();

    /* manager_lang_attribute */
    $setting = $modx->getObject('modSystemSetting',array(
        'key' => 'manager_lang_attribute',
    ));
    if (!$setting) {
        $setting = $modx->newObject('modSystemSetting');
        $setting->fromArray(array(
            'key' => 'manager_lang_attribute',
            'namespace' => 'core',
            'xtype' => 'textfield',
            'area' => 'language',
        ));
    }
    $setting->set('value',$language);
    $setting->save();
}

/* add ext_debug setting for sdk distro */
if ('sdk' === trim($currentVersion['distro'], '@')) {
    $setting = $modx->newObject('modSystemSetting');
    $setting->fromArray(
        array(
            'key' => 'ext_debug',
            'namespace' => 'core',
            'xtype' => 'combo-boolean',
            'area' => 'system',
            'value' => false
        ),
        '',
        true
    );
    $setting->save();
}

$maxFileSize = ini_get('upload_max_filesize');
$maxFileSize = trim($maxFileSize);
$last = strtolower($maxFileSize[strlen($maxFileSize)-1]);
switch ($last) {
    // The 'G' modifier is available since PHP 5.1.0
    case 'g':
        $maxFileSize *= 1024;
    case 'm':
        $maxFileSize *= 1024;
    case 'k':
        $maxFileSize *= 1024;
}

$settings_maxFileSize = $modx->getObject('modSystemSetting', array('key' => 'upload_maxsize'));
if (!$settings_maxFileSize) {
    $settings_maxFileSize = $modx->newObject('modSystemSetting');
    $settings_maxFileSize->fromArray(
        array(
            'key' => 'upload_maxsize',
            'namespace' => 'core',
            'area' => 'system',
            'xtype' => 'textfield'
        ),
        '',
        true
    );
}
$settings_maxFileSize->set('value', $maxFileSize);
$settings_maxFileSize->save();

return true;


text: Configurations used to implement Elastic Stack in a library environment.


text:
package azkaban.project;

import static azkaban.Constants.ConfigurationKeys.PROJECT_TEMP_DIR;
import static java.util.Objects.requireNonNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import azkaban.project.validator.ValidationReport;
import azkaban.project.validator.ValidationStatus;
import azkaban.storage.StorageManager;
import azkaban.test.executions.ExecutionsTestUtil;
import azkaban.user.User;
import azkaban.utils.Props;
import java.io.File;
import java.net.URL;
import java.util.Map;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

public class AzkabanProjectLoaderTest {

  private static final String DIRECTORY_FLOW_REPORT_KEY = "Directory Flow";
  private static final String BASIC_FLOW_YAML_DIR = "basicflowyamltest";
  private static final String BASIC_FLOW_FILE = "basic_flow.flow";
  private static final String PROJECT_ZIP = "Archive.zip";

  @Rule
  public final TemporaryFolder TEMP_DIR = new TemporaryFolder();

  private final int ID = 107;
  private final int VERSION = 10;
  private final Project project = new Project(this.ID, "project1");

  private AzkabanProjectLoader azkabanProjectLoader;
  private StorageManager storageManager;
  private ProjectLoader projectLoader;

  @Before
  public void setUp() throws Exception {
    final Props props = new Props();
    props.put(PROJECT_TEMP_DIR, this.TEMP_DIR.getRoot().getAbsolutePath());

    this.storageManager = mock(StorageManager.class);
    this.projectLoader = mock(ProjectLoader.class);

    this.azkabanProjectLoader = new AzkabanProjectLoader(props, this.projectLoader,
        this.storageManager, new FlowLoaderFactory(props));
  }

  @Test
  public void uploadProject() throws Exception {
    when(this.projectLoader.getLatestProjectVersion(this.project)).thenReturn(this.VERSION);

    final URL resource = requireNonNull(
        getClass().getClassLoader().getResource("sample_flow_01.zip"));
    final File projectZipFile = new File(resource.getPath());
    final User uploader = new User("test_user");

    checkValidationReport(this.azkabanProjectLoader
        .uploadProject(this.project, projectZipFile, "zip", uploader, null));

    verify(this.storageManager)
        .uploadProject(this.project, this.VERSION + 1, projectZipFile, uploader);
  }

  @Test
  public void getProjectFile() throws Exception {
    when(this.projectLoader.getLatestProjectVersion(this.project)).thenReturn(this.VERSION);

    // Run the code
    this.azkabanProjectLoader.getProjectFile(this.project, -1);

    verify(this.projectLoader).getLatestProjectVersion(this.project);
    verify(this.storageManager).getProjectFile(this.ID, this.VERSION);
  }

  @Test
  public void uploadProjectWithYamlFiles() throws Exception {
    final File projectZipFile = ExecutionsTestUtil.getFlowFile(BASIC_FLOW_YAML_DIR, PROJECT_ZIP);
    final int flowVersion = 0;
    final User uploader = new User("test_user");

    when(this.projectLoader.getLatestProjectVersion(this.project)).thenReturn(this.VERSION);
    when(this.projectLoader.getLatestFlowVersion(this.ID, this.VERSION, BASIC_FLOW_FILE))
        .thenReturn(flowVersion);

    checkValidationReport(this.azkabanProjectLoader
        .uploadProject(this.project, projectZipFile, "zip", uploader, null));

    verify(this.storageManager)
        .uploadProject(this.project, this.VERSION + 1, projectZipFile, uploader);
    verify(this.projectLoader)
        .uploadFlowFile(eq(this.ID), eq(this.VERSION + 1), any(File.class), eq(flowVersion + 1));

  }

  private void checkValidationReport(final Map<String, ValidationReport> validationReportMap) {
    assertThat(validationReportMap.size()).isEqualTo(1);
    assertThat(validationReportMap.containsKey(DIRECTORY_FLOW_REPORT_KEY)).isTrue();
    assertThat(validationReportMap.get(DIRECTORY_FLOW_REPORT_KEY).getStatus()).isEqualTo
        (ValidationStatus.PASS);
  }
}


text:
Run this Ansible playbook locally on a mac to setup a development Dataverse instance. The idea here is to get the project running locally, no matter what it takes.

After Dataverse is installed, it doesn't require root access to run locally. However, you will need sudo for a few of the installation steps below.

This playbook provides a way of setting Dataverse up in "development mode" -- making code changes and seeing them work, or not. This is different from the "bundle everything up for deployment mode." If you are interested in using Ansible for regular deployment, see: [Ansible role for installing and maintaining Dataverse] (https://github.com/IQSS/dataverse-ansible)

## Assumptions

  1. You have the [Java 1.8 JDK] (https://docs.oracle.com/javase/8/docs/technotes/guides/install/mac_jdk.html) installed
  2. You have git installed

## Installation

  1. Clone this repository to your local drive.
  2. [Install Ansible](http://docs.ansible.com/intro_installation.html)<sup>†</sup>.
  3. [Install Homebrew] (http://brew.sh/). (requires sudo)
  4. Run `ansible-playbook main.yml --tags "install"` from the same directory as this README file.
  5. Run `ansible-playbook main.yml --tags "start"` to launch postgresql, solr and glassfish.
  6. Deploy your Dataverse war file.
  7. Login as dataverseAdmin and publish the root dataverse.

† _Ansible install docs say: "Readers that use virtualenv can also install Ansible under virtualenv, though we'd recommend to not worry about it and just install Ansible globally. Do not use easy_install to install ansible directly."_

## Ansible tag options

  - Remove all components: _clean_
  - Remove components: _pg-clean_, _solr-clean_, _glassfish-clean_
  - Install components: _pg-install_, _solr-install_, _glassfish-install_
  - Start components: _pg-start_, _solr-start_, _glassfish-start_
  - Stop components: _pg-stop_, _solr-stop_, _glassfish-stop_

## How to start and stop components without using Ansible

All components can be controlled via launchctl

  - Glassfish: `launchctl start glassfish` and `launchctl stop glassfish`
  - Solr: `launchctl start solr` and `launchctl stop solr`
  - Postgresql: `launchctl start postgresql` and `launchctl stop postgresql`

Glassfish can be controlled via asadmin as well

  - `/usr/local/glassfish4/glassfish/bin/asadmin start-domain domain1`
  - `/usr/local/glassfish4/glassfish/bin/asadmin stop-domain domain1`

## Applications installed

  - postgresql (9.3 via Homebrew)
  - solr 4.6.0
  - glassfish 4.1
  - jq (latest via Homebrew)


text:
(function(angular, HttpStatus) {
  'use strict';

  angular
    .module('app')
    .controller('SignInController', SignInController);

  SignInController.$inject = ['$state', 'tokenApiService', 'userService'];

  function SignInController($state, tokenApiService, userService) {
    var vm = this;
    vm.signIn = signIn;

    function signIn(user) {
      vm.showMessageError = false;
      tokenApiService
        .generate(user)
        .then(successOnGenerateToken)
        .catch(errorOnGenerateToken);

      function successOnGenerateToken(response) {
        userService.register(response.data);
        $state.go('dashboard');
      }

      function errorOnGenerateToken(response) {
        if (response.status === HttpStatus.UNAUTHORIZED) {
          vm.showMessageError = true;
        }
      }
    }
  }
})(angular, httpStatusCode);


text:
package com.textocat.textokit.commons.cas;

import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import org.apache.uima.cas.*;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.cas.FSArray;
import org.apache.uima.jcas.cas.StringArray;

import java.util.*;

import static com.google.common.collect.Lists.newLinkedList;
import static com.google.common.collect.Sets.newHashSet;
import static java.lang.String.format;

/**
 * @author Rinat Gareev
 */
public class FSUtils {

    private FSUtils() {
    }

    public static JCas getJCas(FeatureStructure fs) {
        try {
            return fs.getCAS().getJCas();
        } catch (CASException e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean contain(ArrayFS arr, FeatureStructure targetFS) {
        if (arr == null) {
            return false;
        }
        for (int i = 0; i < arr.size(); i++) {
            if (Objects.equal(arr.get(i), targetFS)) {
                return true;
            }
        }
        return false;
    }

    public static FSArray toFSArray(JCas cas, Collection<? extends FeatureStructure> srcCol) {
        return toFSArray(cas, srcCol, srcCol.size());
    }

    public static FSArray toFSArray(JCas cas, FeatureStructure... srcArr) {
        return toFSArray(cas, Arrays.asList(srcArr), srcArr.length);
    }

    public static FSArray toFSArray(JCas cas, Iterable<? extends FeatureStructure> srcCol,
                                    int srcSize) {
        FSArray result = new FSArray(cas, srcSize);
        int i = 0;
        for (FeatureStructure fs : srcCol) {
            result.set(i, fs);
            i++;
        }
        return result;
    }

    public static StringArray toStringArray(JCas cas, String... srcArr) {
        return toStringArray(cas, Arrays.asList(srcArr));
    }

    public static StringArray toStringArray(JCas cas, Collection<String> srcCol) {
        StringArray result = new StringArray(cas, srcCol.size());
        int i = 0;
        for (String gr : srcCol) {
            result.set(i, gr);
            i++;
        }
        return result;
    }

    public static Set<String> toSet(StringArrayFS fsArr) {
        if (fsArr == null)
            return ImmutableSet.of();
        ImmutableSet.Builder<String> resultBuilder = ImmutableSet.builder();
        for (int i = 0; i < fsArr.size(); i++) {
            resultBuilder.add(fsArr.get(i));
        }
        return resultBuilder.build();
    }

    public static List<String> toList(StringArrayFS fsArr) {
        if (fsArr == null)
            return ImmutableList.of();
        ImmutableList.Builder<String> resultBuilder = ImmutableList.builder();
        for (int i = 0; i < fsArr.size(); i++) {
            resultBuilder.add(fsArr.get(i));
        }
        return resultBuilder.build();
    }

    public static FSTypeConstraint getTypeConstraint(Type firstType, Type... otherTypes) {
        FSTypeConstraint constr = ConstraintFactory.instance().createTypeConstraint();
        constr.add(firstType);
        for (Type t : otherTypes) {
            constr.add(t);
        }
        return constr;
    }

    public static FSTypeConstraint getTypeConstraint(String firstType, String... otherTypes) {
        FSTypeConstraint constr = ConstraintFactory.instance().createTypeConstraint();
        constr.add(firstType);
        for (String t : otherTypes) {
            constr.add(t);
        }
        return constr;
    }

    public static <FST extends FeatureStructure> List<FST> filterToList(CAS cas,
                                                                        FSIterator<FST> srcIter, FSMatchConstraint... constraints) {
        FSIterator<FST> resultIter = filter(cas, srcIter, constraints);
        return toList(resultIter);
    }

    public static <F extends FeatureStructure> FSIterator<F> filter(CAS cas,
                                                                    FSIterator<F> srcIter, FSMatchConstraint... constraints) {
        if (constraints.length == 0) {
            return srcIter;
        }
        FSMatchConstraint resultConstr = and(constraints);
        return cas.createFilteredIterator(srcIter, resultConstr);
    }

    public static <F extends FeatureStructure> List<F> filter(List<F> srcList,
                                                              FSMatchConstraint... constraints) {
        if (constraints.length == 0) {
            return ImmutableList.copyOf(srcList);
        }
        ArrayList<F> resultList = Lists.newArrayListWithCapacity(srcList.size());
        FSMatchConstraint conj = and(constraints);
        for (F fs : srcList) {
            if (conj.match(fs)) {
                resultList.add(fs);
            }
        }
        return Collections.unmodifiableList(resultList);
    }

    public static FSMatchConstraint and(FSMatchConstraint... constraints) {
        if (constraints.length == 0) {
            throw new IllegalArgumentException("Constraints array are empty");
        }
        ConstraintFactory cf = ConstraintFactory.instance();
        FSMatchConstraint resultConstr = constraints[0];
        for (int i = 1; i < constraints.length; i++) {
            resultConstr = cf.and(resultConstr, constraints[i]);
        }
        return resultConstr;
    }

    public static <FST extends FeatureStructure> List<FST> toList(FSIterator<FST> iter) {
        LinkedList<FST> result = newLinkedList();
        fill(iter, result);
        return result;
    }

    public static <FST extends FeatureStructure> Set<FST> toSet(FSIterator<FST> iter) {
        HashSet<FST> result = newHashSet();
        fill(iter, result);
        return result;
    }

    public static <FST extends FeatureStructure> void fill(FSIterator<FST> srcIter,
                                                           Collection<FST> destCol) {
        srcIter.moveToFirst();
        while (srcIter.isValid()) {
            destCol.add(srcIter.get());
            srcIter.moveToNext();
        }
    }

    /*
     * Note that getIntValue will return 0 if feature value is not set.
     */
    public static int intMinBy(Iterable<? extends FeatureStructure> fsCollection, Feature intFeat) {
        Integer min = Integer.MAX_VALUE;
        boolean hasResult = false;
        for (FeatureStructure fs : fsCollection) {
            int intValue = fs.getIntValue(intFeat);
            hasResult = true;
            if (intValue < min) {
                min = intValue;
            }
        }
        if (!hasResult) {
            throw new IllegalArgumentException("fsCollection is empty");
        }
        return min;
    }

    /*
     * Note that getIntValue will return 0 if feature value is not set.
     */
    public static int intMaxBy(Iterable<? extends FeatureStructure> fsCollection, Feature intFeat) {
        Integer max = Integer.MIN_VALUE;
        boolean hasResult = false;
        for (FeatureStructure fs : fsCollection) {
            int intValue = fs.getIntValue(intFeat);
            hasResult = true;
            if (intValue > max) {
                max = intValue;
            }
        }
        if (!hasResult) {
            throw new IllegalArgumentException("fsCollection is empty");
        }
        return max;
    }

    public static Function<FeatureStructure, String> stringFeatureFunction(Type fsType, String featName) {
        final Feature feat = fsType.getFeatureByBaseName(featName);
        if (feat == null) throw new IllegalStateException(
                format("%s does not have feature %s", fsType.getName(), featName));
        return new Function<FeatureStructure, String>() {
            @Override
            public String apply(FeatureStructure fs) {
                return fs.getStringValue(feat);
            }
        };
    }

    public static Function<FeatureStructure, String> stringFeaturePathFunc(
            CAS cas, Type inputFSType, String featurePath) throws CASException {
        final FeaturePath path = cas.createFeaturePath();
        path.initialize(featurePath);
        path.typeInit(inputFSType);
        return new Function<FeatureStructure, String>() {
            @Override
            public String apply(FeatureStructure fs) {
                return path.getStringValue(fs);
            }
        };
    }
}


text:
package armcdn

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strings"
)

// SecretsClient contains the methods for the Secrets group.
// Don't use this type directly, use NewSecretsClient() instead.
type SecretsClient struct {
	host           string
	subscriptionID string
	pl             runtime.Pipeline
}

// NewSecretsClient creates a new instance of SecretsClient with the specified values.
// subscriptionID - Azure Subscription ID.
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewSecretsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SecretsClient, error) {
	if options == nil {
		options = &arm.ClientOptions{}
	}
	ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
	if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
		ep = c.Endpoint
	}
	pl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)
	if err != nil {
		return nil, err
	}
	client := &SecretsClient{
		subscriptionID: subscriptionID,
		host:           ep,
		pl:             pl,
	}
	return client, nil
}

// BeginCreate - Creates a new Secret within the specified profile.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-06-01
// resourceGroupName - Name of the Resource group within the Azure subscription.
// profileName - Name of the Azure Front Door Standard or Azure Front Door Premium profile which is unique within the resource
// group.
// secretName - Name of the Secret under the profile.
// secret - The Secret properties.
// options - SecretsClientBeginCreateOptions contains the optional parameters for the SecretsClient.BeginCreate method.
func (client *SecretsClient) BeginCreate(ctx context.Context, resourceGroupName string, profileName string, secretName string, secret Secret, options *SecretsClientBeginCreateOptions) (*runtime.Poller[SecretsClientCreateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.create(ctx, resourceGroupName, profileName, secretName, secret, options)
		if err != nil {
			return nil, err
		}
		return runtime.NewPoller(resp, client.pl, &runtime.NewPollerOptions[SecretsClientCreateResponse]{
			FinalStateVia: runtime.FinalStateViaAzureAsyncOp,
		})
	} else {
		return runtime.NewPollerFromResumeToken[SecretsClientCreateResponse](options.ResumeToken, client.pl, nil)
	}
}

// Create - Creates a new Secret within the specified profile.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-06-01
func (client *SecretsClient) create(ctx context.Context, resourceGroupName string, profileName string, secretName string, secret Secret, options *SecretsClientBeginCreateOptions) (*http.Response, error) {
	req, err := client.createCreateRequest(ctx, resourceGroupName, profileName, secretName, secret, options)
	if err != nil {
		return nil, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated, http.StatusAccepted) {
		return nil, runtime.NewResponseError(resp)
	}
	return resp, nil
}

// createCreateRequest creates the Create request.
func (client *SecretsClient) createCreateRequest(ctx context.Context, resourceGroupName string, profileName string, secretName string, secret Secret, options *SecretsClientBeginCreateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if profileName == "" {
		return nil, errors.New("parameter profileName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{profileName}", url.PathEscape(profileName))
	if secretName == "" {
		return nil, errors.New("parameter secretName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{secretName}", url.PathEscape(secretName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-06-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, secret)
}

// BeginDelete - Deletes an existing Secret within profile.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-06-01
// resourceGroupName - Name of the Resource group within the Azure subscription.
// profileName - Name of the Azure Front Door Standard or Azure Front Door Premium profile which is unique within the resource
// group.
// secretName - Name of the Secret under the profile.
// options - SecretsClientBeginDeleteOptions contains the optional parameters for the SecretsClient.BeginDelete method.
func (client *SecretsClient) BeginDelete(ctx context.Context, resourceGroupName string, profileName string, secretName string, options *SecretsClientBeginDeleteOptions) (*runtime.Poller[SecretsClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, resourceGroupName, profileName, secretName, options)
		if err != nil {
			return nil, err
		}
		return runtime.NewPoller(resp, client.pl, &runtime.NewPollerOptions[SecretsClientDeleteResponse]{
			FinalStateVia: runtime.FinalStateViaAzureAsyncOp,
		})
	} else {
		return runtime.NewPollerFromResumeToken[SecretsClientDeleteResponse](options.ResumeToken, client.pl, nil)
	}
}

// Delete - Deletes an existing Secret within profile.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-06-01
func (client *SecretsClient) deleteOperation(ctx context.Context, resourceGroupName string, profileName string, secretName string, options *SecretsClientBeginDeleteOptions) (*http.Response, error) {
	req, err := client.deleteCreateRequest(ctx, resourceGroupName, profileName, secretName, options)
	if err != nil {
		return nil, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
		return nil, runtime.NewResponseError(resp)
	}
	return resp, nil
}

// deleteCreateRequest creates the Delete request.
func (client *SecretsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, profileName string, secretName string, options *SecretsClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if profileName == "" {
		return nil, errors.New("parameter profileName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{profileName}", url.PathEscape(profileName))
	if secretName == "" {
		return nil, errors.New("parameter secretName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{secretName}", url.PathEscape(secretName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-06-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Get - Gets an existing Secret within a profile.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-06-01
// resourceGroupName - Name of the Resource group within the Azure subscription.
// profileName - Name of the Azure Front Door Standard or Azure Front Door Premium profile which is unique within the resource
// group.
// secretName - Name of the Secret under the profile.
// options - SecretsClientGetOptions contains the optional parameters for the SecretsClient.Get method.
func (client *SecretsClient) Get(ctx context.Context, resourceGroupName string, profileName string, secretName string, options *SecretsClientGetOptions) (SecretsClientGetResponse, error) {
	req, err := client.getCreateRequest(ctx, resourceGroupName, profileName, secretName, options)
	if err != nil {
		return SecretsClientGetResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return SecretsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return SecretsClientGetResponse{}, runtime.NewResponseError(resp)
	}
	return client.getHandleResponse(resp)
}

// getCreateRequest creates the Get request.
func (client *SecretsClient) getCreateRequest(ctx context.Context, resourceGroupName string, profileName string, secretName string, options *SecretsClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets/{secretName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if profileName == "" {
		return nil, errors.New("parameter profileName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{profileName}", url.PathEscape(profileName))
	if secretName == "" {
		return nil, errors.New("parameter secretName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{secretName}", url.PathEscape(secretName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-06-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *SecretsClient) getHandleResponse(resp *http.Response) (SecretsClientGetResponse, error) {
	result := SecretsClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Secret); err != nil {
		return SecretsClientGetResponse{}, err
	}
	return result, nil
}

// NewListByProfilePager - Lists existing AzureFrontDoor secrets.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-06-01
// resourceGroupName - Name of the Resource group within the Azure subscription.
// profileName - Name of the Azure Front Door Standard or Azure Front Door Premium profile which is unique within the resource
// group.
// options - SecretsClientListByProfileOptions contains the optional parameters for the SecretsClient.ListByProfile method.
func (client *SecretsClient) NewListByProfilePager(resourceGroupName string, profileName string, options *SecretsClientListByProfileOptions) *runtime.Pager[SecretsClientListByProfileResponse] {
	return runtime.NewPager(runtime.PagingHandler[SecretsClientListByProfileResponse]{
		More: func(page SecretsClientListByProfileResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *SecretsClientListByProfileResponse) (SecretsClientListByProfileResponse, error) {
			var req *policy.Request
			var err error
			if page == nil {
				req, err = client.listByProfileCreateRequest(ctx, resourceGroupName, profileName, options)
			} else {
				req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink)
			}
			if err != nil {
				return SecretsClientListByProfileResponse{}, err
			}
			resp, err := client.pl.Do(req)
			if err != nil {
				return SecretsClientListByProfileResponse{}, err
			}
			if !runtime.HasStatusCode(resp, http.StatusOK) {
				return SecretsClientListByProfileResponse{}, runtime.NewResponseError(resp)
			}
			return client.listByProfileHandleResponse(resp)
		},
	})
}

// listByProfileCreateRequest creates the ListByProfile request.
func (client *SecretsClient) listByProfileCreateRequest(ctx context.Context, resourceGroupName string, profileName string, options *SecretsClientListByProfileOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/secrets"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if profileName == "" {
		return nil, errors.New("parameter profileName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{profileName}", url.PathEscape(profileName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-06-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByProfileHandleResponse handles the ListByProfile response.
func (client *SecretsClient) listByProfileHandleResponse(resp *http.Response) (SecretsClientListByProfileResponse, error) {
	result := SecretsClientListByProfileResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.SecretListResult); err != nil {
		return SecretsClientListByProfileResponse{}, err
	}
	return result, nil
}


text:
(function(_){
	var
		$window= $(window)
		,name
		,_isReady= false
		,_bindEvents= function(){
			var
				callback,
				oldHash,
				utils= require('broke/core/utils'),
				settings= require('broke/conf/settings').settings
			;

			/******************************** EVENTS BINDING ********************************/
			// elements binding
			if(settings.EVENT_TRIGGERING_METHOD === 'elements'){
				// --------- on elements ---------
				callback= function(e){
					var
						_this= $(this),
						tag= this.tagName.toLowerCase(),
						urlChangingElement= settings.URL_CHANGING_ELEMENTS[tag],
						urlAttribute= urlChangingElement.urlAttribute,
						url= _this.attr(urlAttribute),
						type= e.target.tagName.toLowerCase() == "form" ? 'POST' : 'GET'
					;

					if(urlChangingElement.preventDefault) {
						e.preventDefault();
					}

					if(url !== undefined && utils.contains(url, '#')) {
						request({
							event: e,
							path: url.split('#')[1],
							completeUrl: url,
							type: type
						});
					}
				};

				// collect all the url changing elements
				utils.forEach(settings.URL_CHANGING_ELEMENTS, function(key){
					$(key)[settings.EVENT_BINDING](this.events.join(','), callback);
				});

			// hash change binding
			} else if(settings.EVENT_TRIGGERING_METHOD === 'hashchange'){

				// if it does not exist, let's create it
				if(!('onhashchange' in window)){
					oldHash= location.hash;

					setInterval(function(){
						if(location.hash !== oldHash) {
							oldHash= location.hash;

							$window.trigger('hashchange');
						}
					}, settings.HASHCHANGE_INTERVAL);
				}

				// bind on hash change
				window.onhashchange= function(e){
					request({
						event: e,
						url: location.href.split('#')[1]
					});
				};
			}
		}
		,_searchNamedUrls= function(){
			/*
			 * Search for named urls on the page and swap them with full qualified urls
			 * Named urls on the page should look like this:
			 *     #entry-commit     ->    /blog/entry/commit/
			 *     #entry-view       ->    /blog/entry/view/2/
			 *     #entry-edit 21,2  ->    /blog/21/entry/edit/2/
			 *
			 * If any arguments are needed, they will have to be a comma separated
			 * series of values after the named url
			 *
			 */

			var
				settings= require('broke/conf/settings').settings,
				utils= require('broke/core/utils'),
				callback= function(urlChangingElement){

					var
						_this= $(this),
						urlAttribute= urlChangingElement.urlAttribute,
						urlToRender= _this.attr(urlAttribute).split('#')[1] || '',
						reverse= require('broke/core/urlresolvers').reverse,
						utils= require('broke/core/utils'),
						namedUrl,
						args,
						result
					;

					if(_this.attr(urlAttribute).contains('#')) {
						urlToRender= utils.trim(urlToRender).split(' ');

						namedUrl= urlToRender[0];
						args= urlToRender[1];
						if(args) {
							args= args.split(',');
						} else {
							args= [];
						}

						try {

							result= reverse(namedUrl, args, myProject.apps.blog.urlPatterns);
							_this.attr(urlAttribute, '#' + result);

						} catch(e) {
							if(e.name == "NoReverseMatch") {
								return;
							}
						}
					}
				}
			;

			utils.forEach(settings.URL_CHANGING_ELEMENTS, function(key){
				var elements= $(key),
					elementsLength= elements.length;

				while(elementsLength--) {
					callback.call(elements[elementsLength], this);
				}
			});
		}
		,_getLanguageFiles= function(){
			var
				settings= require('broke/conf/settings').settings,
				utils= require('broke/core/utils'),
				languageCode= settings.LANGUAGE_CODE,
				localePath= utils.interpolate('/locale/%s/LC_MESSAGES/broke.po', languageCode),
				localePaths= [
					settings.BASE_URL + '/conf'
				],
				translation= require('broke/utils/translation')
			;

			// projects' locale paths
			localePaths= localePaths.concat(utils.getattr(BROKE_SETTINGS_MODULE, window).LOCALE_PATHS);

			//localePaths.each(function(){
			utils.forEach(localePaths, function(){
				translation.init({
					url: this + localePath
				});
			});

			return;
		}
		,_preloadRemoteTemplates= function(app){
			// TODO
		}
		,_setLanguage= function(){
			// 1. look in the url
			var
				urlResolvers= require('broke/core/urlresolvers'),
				settings= require('broke/conf/settings').settings,
				queryString= urlResolvers.parseQueryString(window.location.href.split('?')[1]),
				cookie= $.cookie(settings.LANGUAGE_COOKIE_NAME),
				langCodeFromCookie
			;

			// check query string
			if('language' in queryString) {
				settings.LANGUAGE_CODE= queryString.language;

				// set cookie language
				$.cookie(settings.LANGUAGE_COOKIE_NAME, queryString.language, {
					expires: 30,
					domain: window.location.host,
					path: '/'
				});
			} else {
				// 2. check cookie
				langCodeFromCookie= $.cookie(settings.LANGUAGE_COOKIE_NAME);

				settings.LANGUAGE_CODE= langCodeFromCookie || settings.LANGUAGE_CODE;
			}
		}
		,_initProject= function(){
			var
				utils= require('broke/core/utils'),
				settings= require('broke/conf/settings').settings
			;

			// init installed apps' models
			utils.forEach(settings.INSTALLED_APPS, function(){
				var
					app= this
					,utils= require('broke/core/utils')
				;

				if(app.constructor == String) {
					app= utils.getattr(this, window);
				}

				// init model's storage
				utils.forEach(app.models, function(key){
					if(this.autoInit) {
						// TODO: check that
						initStorage(this);
					}
				});

				if(settings.PRELOAD_REMOTE_TEMPLATES) {
					_preloadRemoteTemplates(app);
				}
			});

			return settings;
		}
		,init= function(){
			var
				gettext= require('broke/utils/translation').gettext.gettext,
				exceptions= require('broke/core/exceptions'),
				cache= require('broke/core/cache/cache'),
				settings= require('broke/conf/settings').settings
			;

			if(_isReady) {
				// already initialized
				log('Broke has already been initialized! Fail silently...');
				return;
			}

			if(!BROKE_SETTINGS_MODULE) {
				// no settings object defined, fail out loud
				throw new exceptions.SettingsObjectNotDefined(gettext('Settings object not defined!'));
			}

			// init project
			_initProject();

			if(settings.USE_I18N) {
				// determine the language
				//_setLanguage();

				// get language files
				//_getLanguageFiles();
			}

			// search for named urls and swap them with fully qualified urls
			//_searchNamedUrls();

			// bind events
			//_bindEvents();

			// cache init
			//cache.cache= cache.getCache(settings.CACHE_BACKEND);

			// on broke init, check if there is an url to request
			if(window.location.hash !== '') {
				request(window.location.hash.split('#')[1]);
			}

			$window.trigger('broke.ready');
			_isReady= true;
		}
		,isReady= function(){
			return _isReady;
		}
		/************************* REQUEST SHORTCUT **************************/
		,request= function(args){
			var
				req= {}
			;

			if(typeof args == 'string') {
				// first case: broke.request('/entry/view/1/');
				req.path= args;
			} else {
				// second case: broke.request({
				//     url: '/entry/view/1/',
				//     fromReload: true
				// });
				req= args;
			}

			$window.trigger('broke.request', [req]);
		}

		/************************ RESPONSE SHORTCUT **************************/
		,response= function(args){
			$window.trigger('broke.response', [args]);
		}
		/*********************************************************************/
		,removeHash= function(){
			window.location.hash= '';
			return true;
		}
		,log= function(debugString, doNotAppendDate){
			var
				settings= require('broke/conf/settings').settings
			;

			if(settings.DEBUG && 'console' in window) {
				if(!doNotAppendDate) {
					var
						now= new Date()
					;

					now= utils.interpolate('%s:%s:%s:%s', [now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds()]);
					debugString= utils.interpolate('[%s] %s', [now, debugString]);
				}

				console.debug(debugString);
			}
		}
		,fetchData= function(args){
			var
				model= args.model
				,url= args.url || model.fetchDataUrl
				,utils= require('broke/core/utils')
				,result
			;

			$.ajax({
				async: false
				,url: url
				,dataType: 'json'
				,data: args.filter || {}
				,success: function(data, status, xhr){
					utils.storage[model.tableName]= (utils.storage[model.tableName] || []).concat(data);

					if(utils.isFunction(args.callback)) {
						args.callback(data, storage);
					}
				}
			});
		}
		,initStorage= function(model){
			fetchData({
				'model': model
			});
		}
		,extendUtils= function(){
			var
				utils= require('broke/core/utils')
			;

			utils.storage= {};

			return;

			utils.extend(utils, {
				storage: (function(){
					// mime or reference HTML 5's Local Storage
					var
						localStorageSetObject= function(key, value) {
							this.setItem(key, JSON.stringify(value));
						},
						localStorageGetObject= function(key) {
							return JSON.parse(this.getItem(key));
						},
						storage= {}
					;

					if('localStorage' in window) {
						extend(Storage.prototype, {
							setObject: localStorageSetObject,
							getObject: localStorageGetObject
						});

						return localStorage;
					}

					return {
						key: function(key){
							throw {
								name: "NotImplementedError",
								description: "Sorry, this version of localStorage is a fake and does not support key() method."
							};
						},
						setItem: function(key, value){
							storage[key]= value;
							return this;
						},
						getItem: function(key){
							return storage[key];
						},
						removeItem: function(key){
							delete storage[key];
							return this;
						},
						setObject: localStorageSetObject,
						getObject: localStorageGetObject,
						clear: function(){
							storage= {};
							return this;
						}
					};
				})()
			});
		}
		,extendSettings= function(){
			var
				utils= require('broke/core/utils'),
				settings= require('broke/conf/settings').settings
			;

			utils.extend(settings, {
				EVENT_BINDING: 'live',			// bind|live
												// it should always be set to 'live' but
												// at the current stage jQuery's live
												// method does not always work properly

				// 'EVENT_TRIGGERING_METHOD' determines the way to trigger the
				// broke.request event
				// WARNING: hashChange will work with an interval of 150ms on old browsers
				// on more recent browsers will make use of the 'onhashchange' event
				// which, by the time of the writing, it is only available on Firefox 3.6 and IE8
				// as for the 'elements' method please refer to the documentation under the
				// 'events' topic
				// choices are: elements, hashchange
				EVENT_TRIGGERING_METHOD: 'elements',

				FORM: null,						// default operation form

				HASHCHANGE_INTERVAL: 150,		// interval in milliseconds for the
												// hashchange method to check for a changed
												// url
												// it's effective only if you've selected
												// 'eventTriggeringMethod' as 'hashchange'
												// and your browser does not support
												// the 'onhashchange' event

				HIDE_HASH: false,				// whether you want the hash to be hidden
												// from the main url
												// careful: it will prevent any default action
												// from the browser from your event
												// equivalent of doing 'event.preventDefault();'

				'RETURN': window.location.href	// form return url
			});
		}
	;

	// make it compatible with nodejs (???)
	window.global= window;
	window.global.global= window.global;

	$window.bind('broke.request', function(e, requestData){
		var
			response= {}
			,BrowserHandler= require('broke/core/handlers/browser').BrowserHandler
			,requestHandler= new BrowserHandler()
		;
		debugger;
		response= requestHandler(requestData);

		$window.trigger('broke.response', [response]);
	});

	$window.bind('broke.response', function(e, response){
		var
			utils= require('broke/core/utils'),
			settings= require('broke/conf/settings').settings
		;

		if(response) {
			// apply additional properties
			if(response.additionalProperties !== undefined) {
				utils.forEach(response.additionalProperties, function(key){
					response.element[key]= this;
				});
			}

			// apply callback
			if(response.callback && utils.typeOf(response.callback) === 'function') {
				response.callback.apply(response.element, [response]);
			}

			// --------- middleware fetching in reverse order ---------
			utils.forEach(settings.MIDDLEWARE_CLASSES.reverse(), function(){

				var
					middleware= utils.getCallable(this)
				;

				if(middleware.processResponse !== undefined) {
					middleware.processResponse(response);
				}
			});
		}
	});

	// external interface
	exports.init= init;
	exports.isReady= isReady;
	exports.request= request;
	exports.response= response;
	exports.removeHash= removeHash;
	exports.log= log;
	exports.fetchData= fetchData;
	exports.initStorage= initStorage;
	exports.extendUtils= extendUtils;
	exports.extendSettings= extendSettings;
})(exports);


text:
"""
Maximum likelihood covariance estimator.

"""

# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#         Gael Varoquaux <gael.varoquaux@normalesup.org>
#         Virgile Fritsch <virgile.fritsch@inria.fr>
#
# License: BSD Style.

# avoid division truncation
from __future__ import division
import numpy as np
from scipy import linalg

from ..base import BaseEstimator
from ..utils.extmath import fast_logdet as exact_logdet

def log_likelihood(emp_cov, precision):
    """Computes the negative log_likelihood of the data

    Params
    ------
    emp_cov: 2D ndarray (n_features, n_features)
      Maximum Likelihood Estimator of covariance
    precision: 2D ndarray (n_features, n_features)
      The precision matrix of the covariance model to be tested

    """
    return -np.sum(emp_cov * precision) + exact_logdet(precision)

def empirical_covariance(X, assume_centered=False):
    """Computes the Maximum likelihood covariance estimator

    Parameters
    ----------
    X: 2D ndarray, shape (n_samples, n_features)
      Data from which to compute the covariance estimate

    assume_centered: Boolean
      If True, data are not centered before computation.
      Usefull to work with data whose mean is significantly equal to
      zero but is not exactly zero.
      If False, data are centered before computation.

    Returns
    -------
    covariance: 2D ndarray, shape (n_features, n_features)
      Empirical covariance (Maximum Likelihood Estimator)

    """
    X = np.asanyarray(X)
    if X.ndim == 1:
        X = np.atleast_2d(X).T

    if assume_centered:
        covariance = np.dot(X.T, X) / X.shape[0]
    else:
        covariance = np.cov(X.T, bias=1)

    return covariance

class EmpiricalCovariance(BaseEstimator):
    """Maximum likelihood covariance estimator

    Parameters
    ----------
    store_precision : bool
        Specifies if the estimated precision is stored

    Attributes
    ----------
    `covariance_` : 2D ndarray, shape (n_features, n_features)
        Estimated covariance matrix

    `precision_` : 2D ndarray, shape (n_features, n_features)
        Estimated pseudo inverse matrix.
        (stored only if store_precision is True)

    """
    def __init__(self, store_precision=True):
        self.store_precision = store_precision

    def _set_estimates(self, covariance):
        """Saves the covariance and precision estimates

        Storage is done accordingly to `self.store_precision`.
        Precision stored only if invertible.

        Params
        ------
        covariance: 2D ndarray, shape (n_features, n_features)
          Estimated covariance matrix to be stored, and from which
          the precision is computed.

        """
        covariance = np.atleast_2d(covariance)
        # set covariance
        self.covariance_ = covariance
        # set precision
        if self.store_precision:
            self.precision_ = linalg.pinv(covariance)
        else:
            self.precision_ = None

    def fit(self, X, assume_centered=False):
        """ Fits the Maximum Likelihood Estimator covariance model
        according to the given training data and parameters.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
          Training data, where n_samples is the number of samples
          and n_features is the number of features.

        assume_centered: Boolean
          If True, data are not centered before computation.
          Usefull to work with data whose mean is significantly equal to
          zero but is not exactly zero.
          If False, data are centered before computation.

        Returns
        -------
        self : object
            Returns self.

        """
        covariance = empirical_covariance(X, assume_centered=assume_centered)
        self._set_estimates(covariance)

        return self

    def score(self, X_test, assume_centered=False):
        """Computes the log-likelihood of a gaussian data set with
        `self.covariance_` as an estimator of its covariance matrix.

        Parameters
        ----------
        X_test : array-like, shape = [n_samples, n_features]
          Test data of which we compute the likelihood,
          where n_samples is the number of samples and n_features is
          the number of features.

        Returns
        -------
        res: float
          The likelihood of the data set with self.covariance_ as an estimator
          of its covariance matrix.

        """
        # compute empirical covariance of the test set
        test_cov = empirical_covariance(X_test,
                                        assume_centered=assume_centered)
        # compute log likelihood
        if self.store_precision:
            res = log_likelihood(test_cov, self.precision_)
        else:
            res = log_likelihood(test_cov, linalg.pinv(self.covariance_))

        return res

    def error_norm(self, comp_cov, norm='frobenius', scaling=True,
                   squared=True):
        """Computes the Mean Squared Error between two covariance estimators.
        (In the sense of the Frobenius norm)

        Parameters
        ----------
        comp_cov: array-like, shape = [n_features, n_features]
          The covariance which to be compared to.
        norm: str
          The type of norm used to compute the error. Available error types:
          - 'frobenius' (default): sqrt(tr(A^t.A))
          - 'spectral': sqrt(max(eigenvalues(A^t.A))
          where A is the error (comp_cov - self.covariance_).
        scaling: bool
          If True (default), the squared error norm is divided by n_features
          If False, the squared error norm is not rescaled
        squared: bool
          Whether to compute the squared error norm or the error norm.
          If True (default), the squared error norm is returned.
          If False, the error norm is returned.

        Returns
        -------
        The Mean Squared Error (in the sense of the Frobenius norm) between
        `self` and `comp_cov` covariance estimators.

        """
        # compute the error
        error = comp_cov - self.covariance_
        # compute the error norm
        if norm == "frobenius":
            squared_norm = np.sum(error ** 2)
        elif norm == "spectral":
            squared_norm = np.amax(linalg.svdvals(np.dot(error.T, error)))
        else:
            raise NotImplementedError(
                "Only spectral and frobenius norms are implemented")
        # optionaly scale the error norm
        if scaling:
            squared_norm = squared_norm / error.shape[0]
        # finally get either the squared norm or the norm
        if squared:
            result = squared_norm
        else:
            result = np.sqrt(squared_norm)

        return result


text:
package qiniu.happydns;

/**
 * Created by bailong on 15/7/23.
 */
public class DnspodEnterpriseTest {
//    @Test
//    public void testFound() throws IOException {
//        DnspodEnterprise resolver = new DnspodEnterprise("", "");
//        try {
//            Record[] records = resolver.resolve(new Domain("baidu.com"), null);
//            Assert.assertNotNull(records);
//            Assert.assertTrue(records.length > 0);
//        } catch (IOException e) {
//            Assert.fail(e.getMessage());
//        }
//    }
//
//    @Test
//    public void testNotFound() throws IOException {
//        DnspodEnterprise resolver = new DnspodEnterprise("007", "abcdef");
//        try {
//            Record[] records = resolver.resolve(new Domain("7777777.qiniu.com"), null);
//            Assert.assertNull(records);
//        } catch (IOException e) {
//            Assert.fail(e.getMessage());
//        }
//    }
}