text:
import argparse
import os
import sys
from time import sleep

import kijiji_api
import generate_inf_file as generator

if sys.version_info < (3, 0):
    raise Exception("This program requires Python 3.0 or greater")

def main():
    parser = argparse.ArgumentParser(description="Post ads on Kijiji")
    parser.add_argument('-u', '--username', help='username of your kijiji account')
    parser.add_argument('-p', '--password', help='password of your kijiji account')

    subparsers = parser.add_subparsers(help='sub-command help')

    postParser = subparsers.add_parser('post', help='post a new ad')
    postParser.add_argument('inf_file', type=str, help='.inf file containing posting details')
    postParser.set_defaults(function=post_ad)

    folderParser = subparsers.add_parser('folder', help='post ad from folder')
    folderParser.add_argument('folderName', type=str, help='folder containing ad details')
    folderParser.set_defaults(function=post_folder)

    repostFolderParser = subparsers.add_parser('repost_folder', help='post ad from folder')
    repostFolderParser.add_argument('folderName', type=str, help='folder containing ad details')
    repostFolderParser.set_defaults(function=repost_folder)

    showParser = subparsers.add_parser('show', help='show currently listed ads')
    showParser.set_defaults(function=show_ads)

    deleteParser = subparsers.add_parser('delete', help='delete a listed ad')
    deleteParser.add_argument('id', type=str, help='id of the ad you wish to delete')
    deleteParser.set_defaults(function=delete_ad)

    nukeParser = subparsers.add_parser('nuke', help='delete all ads')
    nukeParser.set_defaults(function=nuke)

    checkParser = subparsers.add_parser('check_ad', help='check if ad is active')
    checkParser.add_argument('folderName', type=str, help='folder containing ad details')
    checkParser.set_defaults(function=check_ad)

    repostParser = subparsers.add_parser('repost', help='repost an existing ad')
    repostParser.add_argument('inf_file', type=str, help='.inf file containing posting details')
    repostParser.set_defaults(function=repost_ad)

    buildParser = subparsers.add_parser('build_ad', help='Generates the item.inf file for a new ad')
    buildParser.set_defaults(function=generate_inf_file)

    args = parser.parse_args()
    try:
        args.function(args)
    except AttributeError:
        parser.print_help()

def get_folder_data(args):
    """
    Set ad data inf file and extract login credentials from inf files
    """
    args.inf_file = "item.inf"
    cred_file = args.folderName + "/login.inf"
    creds = [line.strip() for line in open(cred_file, 'r')]
    args.username = creds[0]
    args.password = creds[1]

def get_inf_details(inf_file):
    """
    Extract ad data from inf file
    """
    with open(inf_file, 'rt') as infFileLines:
        data = {key: val for line in infFileLines for (key, val) in (line.strip().split("|"),)}
    files = [open(picture, 'rb').read() for picture in data['imageCsv'].split(",")]
    return [data, files]

def post_folder(args):
    """
    Post new ad from folder
    """
    get_folder_data(args)
    os.chdir(args.folderName)
    post_ad(args)

def post_ad(args):
    """
    Post new ad
    """
    [data, imageFiles] = get_inf_details(args.inf_file)
    attempts = 1
    while not check_ad(args) and attempts < 5:
        if attempts > 1:
            print("Failed Attempt #" + str(attempts) + ", trying again.")
        attempts += 1
        api = kijiji_api.KijijiApi()
        api.login(args.username, args.password)
        api.post_ad_using_data(data, imageFiles)
        sleep(180)
    if not check_ad(args):
        print("Failed Attempt #" + str(attempts) + ", giving up.")

def show_ads(args):
    """
    Print list of all ads
    """
    api = kijiji_api.KijijiApi()
    api.login(args.username, args.password)
    [print("{} '{}'".format(adId, adName)) for adName, adId in api.get_all_ads()]

def delete_ad(args):
    """
    Delete ad
    """
    api = kijiji_api.KijijiApi()
    api.login(args.username, args.password)
    api.delete_ad(args.id)

def delete_ad_using_title(name):
    """
    Delete ad based on ad title
    """
    api = kijiji_api.KijijiApi()
    api.delete_ad_using_title(name)

def repost_ad(args):
    """
    Repost ad

    Try to delete ad with same title if possible before reposting new ad
    """
    api = kijiji_api.KijijiApi()
    api.login(args.username, args.password)
    delAdName = ""
    for line in open(args.inf_file, 'rt'):
        [key, val] = line.strip().rstrip("\n").split("|")
        if key == "postAdForm.title":
            delAdName = val
    try:
        api.delete_ad_using_title(delAdName)
        print("Existing ad deleted before reposting")
    except kijiji_api.DeleteAdException:
        print("Did not find an existing ad with matching title, skipping ad deletion")
        pass
    # Must wait a bit before posting the same ad even after deleting it, otherwise Kijiji will automatically remove it
    sleep(180)
    post_ad(args)

def repost_folder(args):
    """
    Repost ad from folder
    """
    get_folder_data(args)
    os.chdir(args.folderName)
    repost_ad(args)

def check_ad(args):
    """
    Check if ad is live
    """
    api = kijiji_api.KijijiApi()
    api.login(args.username, args.password)
    AdName = ""
    for line in open(args.inf_file, 'rt'):
        [key, val] = line.strip().rstrip("\n").split("|")
        if key == "postAdForm.title":
            AdName = val
    allAds = api.get_all_ads()
    return [t for t, i in allAds if t == AdName]

def nuke(args):
    """
    Delete all ads
    """
    api = kijiji_api.KijijiApi()
    api.login(args.username, args.password)
    allAds = api.get_all_ads()
    [api.delete_ad(adId) for adName, adId in allAds]

def generate_inf_file(args):
    generator.run_program()

if __name__ == "__main__":
    main()


text:
"""Expose an app instance on import."""

from .app import create_app

application = create_app()

redpajama_set_name: RedPajamaGithub


text:
About
-----

This is a collection of [Jekyll](https://github.com/mojombo/jekyll) plugins and generators that I've written for use on [daveperrett.com](http://daveperrett.com/).

License
-------

The plugins are distributed under the [MIT License](http://en.wikipedia.org/wiki/MIT_license). See the [License](https://github.com/recurser/jekyll-plugins/blob/master/LICENSE) file for details.

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

To install the plugins simply put them in a directory named _\_plugins_ in your project directory.

Bug Reports
-----------

If you come across any problems, please [create a ticket](https://github.com/recurser/jekyll-plugins/issues) and we'll try to get it fixed as soon as possible.

Want to make your own plugins?
------------------------------

More information on the Jekyll plugin architecture is available from the [Jekyll wiki](https://github.com/mojombo/jekyll/wiki/Plugins).

generate_projects.rb
====================

A generator that creates project pages for Jekyll sites from git repositories.

This was inspired by the project pages on GitHub, which use the project _README_ file as the index page. It takes git repositories, and automatically builds project pages for them using the _README_ file, along with downloadable zipped copies of the projects themselves (for example, the project page for this [plugin repository](http://www.daveperrett.com/articles/2010/12/08/jekyll-plugins-for-categories-projects-and-sitemaps/) is auto-generated with this plugin).

Usage
-----

To use it, simply drop the _generate_projects.rb_ script into the _\_plugins_ directory of your Jekyll site. Next, create a _\_projects_ folder in the base of your Jekyll site. This folder should contain _.yml_ files describing how to build a page for your project. Here is an example _\_projects/jekyll-plugins.yml_):

``` yaml
layout:     default
title:      Jekyll Plugins
repository: git://daveperrett.com/jekyll-plugins.git
published:  true
```

How it works
------------

When you compile your Jekyll site, the plugin will download the git repository of each project in your _\_projects_ folder, create an index page from the _README_ file (using the specified layout), and create a downloadable _.zip_ file of the project. The goal is to automate the construction of online project pages, keep them in sync with _README_ documentation, and provide an up-to-date zip archive for download.

Required files
--------------

Your project's git repository should contain:

* _README_ : The contents of this will be used as the body of your project page will be created from. Any extension other than .markdown, .textile or .html will be treated as a .textile file.
* _versions.txt_ : Contains the version string (eg 1.0.0). Used when naming the downloadable zip-file (optional). If the _version.txt_ file is not available, a _YYYYMMDDHHMM_ timestamp will be used for the version instead.

Required gems
-------------

* git (>= 1.2.5)
* rubyzip (>= 0.9.4)

Available \_config.yml settings
------------------------------

* _project_dir_ : The subfolder to compile projects to (default is 'projects').

Available YAML settings
-----------------------

* _repository_ : Git repository of your project (required).
* _layout_ :     Layout to use when creating the project page.
* _title_ :      Project title, which can be accessed in the layout.
* _published_ :  Project won't be published if this is false.

There is also an optional _zip_folder_name_ setting, in case you want the unzipped folder to be named
something other than the project name. This is useful (for eaxmple) if you want it to unzip as an
OS X 'Something.app' application bundle.

generate_categories.rb
======================

A generator that creates category pages for Jekyll sites (for example our [plugin category](http://www.daveperrett.com/articles/categories/plugin/)).

Usage
-----

To use it, simply drop the _generate_categories.rb_ script into the _\_plugins_ directory of your Jekyll site.

You should also copy the [category_index.html](https://github.com/recurser/jekyll-plugins/blob/master/_layouts/category_index.html) file to the _\_layouts_ directory of your own project. This file is provided as an example layout, and obviously you can change the HTML as you see fit.

You can also (optionally) generate an _atom.xml_ feed for each category. To do this, copy the [category_feed.xml](https://github.com/recurser/jekyll-plugins/blob/master/_includes/custom/category_feed.xml) file to the _\_includes/custom_ directory of your own project. You'll also need to copy the [octopress_filters.rb](https://github.com/recurser/jekyll-plugins/blob/master/_plugins/octopress_filters.rb) file into the _\_plugins_ directory of your project, as the _category_feed.xml_ requires a couple of extra filters.

How it works
------------

When you compile your Jekyll site, this plugin will loop through the list of categories in your site, and use the layout above to generate a page for each one with a list of links to the individual posts.

Included filters
----------------

* _category_links_ : Outputs the list of categories as comma-separated links.
* _date_to_html_string_ : Outputs the post.date as formatted html, with hooks for CSS styling.

Available \_config.yml settings
------------------------------

* _category_dir_ : The subfolder to build category pages in (default is 'categories').
* _category_title_prefix_ : The string used before the category name in the page title (default is 'Category: ').

generate_sitemap.rb
===================

A simple generator that creates a _sitemap.xml_ page for Jekyll sites, suitable for submission to Google etc (for example the _sitemap.xml_ for [daveperrett.com](http://www.daveperrett.com/sitemap.xml).

Usage
-----

To use it, simply drop the _generate_sitemap.rb_ script into the _\_plugins_ directory of your Jekyll site.

How it works
------------

When you compile your Jekyll site, the plugin will loop through the list of pages in your site, and generate an entry in _sitemap.xml_ for each one.

Available YAML settings
-----------------------

* _changefreq_ : How often this page will change. This setting is optional, but if specified its value must be one of `always`, `hourly`, `daily`, `weekly`, `monthly`, `yearly`, or `never`. See [the sitemap specification](http://www.sitemaps.org/protocol.php#xmlTagDefinitions) for more details on what this is used for. By default, this property is omitted for static pages and `never` for the files in `_posts` (since these are typically blog entries or the like).

Change history
==============

* **Version 0.2.1 (2012-10-15)** : Merged some updates from [Octopress](https://github.com/imathis/octopress/blob/master/plugins/category_generator.rb) back in.
  * Add support for _atom.xml_ feed generation for categories.
  * Improved handling of multibyte and multi-word category names in URLs.
* **Version 0.2.0 (2012-10-14)** :
  * Add support for priority in _generate_sitemap.rb_ (thanks [hez](https://github.com/hez)!).
  * Remove hard-coded category directory in _generate_categories.rb_ (thanks [ghinda](https://github.com/ghinda) and [MrWerewolf](https://github.com/MrWerewolf)!).
  * Improved slash handling in _generate_sitemap.rb_.
* **Version 0.1.8 (2011-08-15)** : A bunch of fixes and improvements (thanks [bdesham](https://github.com/bdesham)!).
* **Version 0.1.7 (2011-07-19)** : Sitemap base URL fix (thanks [ojilles](https://github.com/ojilles)!).
* **Version 0.1.6 (2011-05-21)** : Added optional _zip_folder_name_ YAML config setting.
* **Version 0.1.5 (2011-05-21)** : Replace github-style code markup to pygments-compatible 'highlight' format.
* **Version 0.1.4 (2011-05-08)** : Applied patch to fix permalink problem in _generate_sitemap.rb_ (thanks [ejel](https://github.com/ejel)!).
* **Version 0.1.3 (2011-01-06)** : Fixed pygments code formatting bug introduced in _generate_projects.rb_ v0.1.2.
* **Version 0.1.2 (2011-01-06)** : Add generated pages to the Site::pages list, to stop them being deleted automatically by Site::cleanup(); Fixed a file extension problem with _generate_projects.rb_.
* **Version 0.1.1 (2010-12-10)** : Use _mtime_ instead of _ctime_ for sitemap modification dates; Fixed sitemap extension bug.
* **Version 0.1.0 (2010-12-08)** : Initial release.

Contributing
============

Once you've made your commits:

1. [Fork](http://help.github.com/fork-a-repo/) jekyll-plugins
2. Create a topic branch - `git checkout -b my_branch`
3. Push to your branch - `git push origin my_branch`
4. Create a [Pull Request](http://help.github.com/pull-requests/) from your branch
5. That's it!

Author
======

Dave Perrett :: hello@daveperrett.com :: [@daveperrett](http://twitter.com/daveperrett)

Copyright
=========

Copyright (c) 2010 Dave Perrett. See [License](https://github.com/recurser/jekyll-plugins/blob/master/LICENSE) for details.


text:
require "rubygem-with-test-unit/version"

module Rubygem
  module With
    module Test
      module Unit
        # Your code goes here...
      end
    end
  end
end


text:
package org.apache.jena.fuseki;

import static org.apache.jena.fuseki.ServerCtl.serviceQuery;
import static org.apache.jena.fuseki.ServerCtl.serviceUpdate;

import java.net.http.HttpRequest.BodyPublisher;
import java.net.http.HttpRequest.BodyPublishers;

import org.apache.jena.atlas.web.TypedInputStream;
import org.apache.jena.fuseki.test.FusekiTest;
import org.apache.jena.fuseki.test.HttpTest;
import org.apache.jena.http.HttpOp;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.sparql.exec.http.QueryExecutionHTTP;
import org.apache.jena.update.UpdateExecution;
import org.apache.jena.web.HttpSC;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

/** Tests on a read only server. */
public class TestWebappServerReadOnly
{
    // readonly server.
    @BeforeClass
    public static void allocServerForSuite() {
        ServerCtl.freeServer();
        //Manage ourselves.
        ServerCtl.setupServer(false);
    }

    @AfterClass
    public static void freeServerForSuite() {
        ServerCtl.freeServer();
    }

    @Test
    public void query_readonly() {
        Query query = QueryFactory.create("ASK{}");
        QueryExecutionHTTP.service(serviceQuery(), query).execAsk();
    }

    @Test()
    public void update_readonly() {
        HttpTest.expect404( () -> {
            UpdateExecution.service(serviceUpdate()).update("INSERT DATA {}").execute();
        });
    }

    @Test
    public void gsp_w_readonly_POST() {
        // Try to write
        HttpTest.execWithHttpException(HttpSC.METHOD_NOT_ALLOWED_405, ()->{
            BodyPublisher bodyPublisher = BodyPublishers.ofString("");
            HttpOp.httpPost(ServerCtl.serviceGSP()+"?default", null, bodyPublisher);
        });
    }

    @Test
    public void gsp_w_readonly_PUT() {
        // Try to write
        HttpTest.execWithHttpException(HttpSC.METHOD_NOT_ALLOWED_405, ()->{
            BodyPublisher bodyPublisher = BodyPublishers.ofString("");
            HttpOp.httpPut(ServerCtl.serviceGSP()+"?default", null, bodyPublisher);
        });
    }

    @Test
    public void gsp_w_readonly_DELETE() {
        // Try to write
        HttpTest.execWithHttpException(HttpSC.METHOD_NOT_ALLOWED_405, ()->{
            HttpOp.httpDelete(ServerCtl.serviceGSP()+"?default");
        });
    }

    @Test
    public void dataset_readonly_GET() {
        // Try to read
        try ( TypedInputStream in = HttpOp.httpGet(ServerCtl.urlDataset()) ) {}
    }

    @Test
    public void dataset_w_readonly_POST() {
        // Try to write
        HttpTest.execWithHttpException(HttpSC.METHOD_NOT_ALLOWED_405, ()->{
            BodyPublisher bodyPublisher = BodyPublishers.ofString("");
            HttpOp.httpPost(ServerCtl.urlDataset(), null, bodyPublisher);
        });
    }

    @Test
    public void dataset_w_readonly_PUT() {
        // Try to write
        HttpTest.execWithHttpException(HttpSC.METHOD_NOT_ALLOWED_405, ()->{
            BodyPublisher bodyPublisher = BodyPublishers.ofString("");
            HttpOp.httpPut(ServerCtl.urlDataset(), null, bodyPublisher);
        });
    }

    @Test
    public void dataset_w_readonly_DELETE() {
        // Try to write
        HttpTest.execWithHttpException(HttpSC.METHOD_NOT_ALLOWED_405, ()->{
            HttpOp.httpDelete(ServerCtl.urlDataset());
        });
    }

    @Test
    public void options_gsp_readonly() {
        String v = HttpOp.httpOptions(ServerCtl.serviceGSP()+"?default");
        FusekiTest.assertStringList(v, "GET", "OPTIONS", "HEAD");
    }

}


text:
from mollie.api.objects.payment import Payment

from .utils import assert_list_object

CUSTOMER_ID = "cst_8wmqcHMN4U"

def test_list_customer_payments(client, response):
    response.get(f"https://api.mollie.com/v2/customers/{CUSTOMER_ID}", "customer_single")
    response.get(f"https://api.mollie.com/v2/customers/{CUSTOMER_ID}/payments", "customer_payments_multiple")

    customer = client.customers.get(CUSTOMER_ID)
    payments = customer.payments.list()
    assert_list_object(payments, Payment)

def test_create_customer_payment(client, response):
    response.get(f"https://api.mollie.com/v2/customers/{CUSTOMER_ID}", "customer_single")
    response.post(f"https://api.mollie.com/v2/customers/{CUSTOMER_ID}/payments", "payment_single")

    customer = client.customers.get(CUSTOMER_ID)
    payment = customer.payments.create(
        {
            "amount": {"currency": "EUR", "value": "10.00"},
            "description": "Order #12345",
            "redirectUrl": "https://webshop.example.org/order/12345/",
            "webhookUrl": "https://webshop.example.org/payments/webhook/",
            "method": "ideal",
        }
    )
    assert isinstance(payment, Payment)
    assert payment.customer_id == CUSTOMER_ID


text:
    <title>eg3-1d</title>

    Bold
    Italic


text:
module Cryptoexchange::Exchanges
  module Zaif
    module Services
      class OrderBook < Cryptoexchange::Services::Market
        class << self
          def supports_individual_ticker_query?
            true
          end
        end

        def fetch(market_pair)
          output = super(ticker_url(market_pair))
          adapt(output, market_pair)
        end

        def ticker_url(market_pair)
          "#{Cryptoexchange::Exchanges::Zaif::Market::API_URL}/depth/#{market_pair.base.downcase}_#{market_pair.target.downcase}"
        end

        def adapt(output, market_pair)
          order_book = Cryptoexchange::Models::OrderBook.new

          order_book.base      = market_pair.base
          order_book.target    = market_pair.target
          order_book.market    = Zaif::Market::NAME
          order_book.asks      = adapt_orders output['asks']
          order_book.bids      = adapt_orders output['bids']
          order_book.timestamp = Time.now.to_i
          order_book.payload   = output
          order_book
        end

        def adapt_orders(orders)
          orders.collect do |order_entry|
            price, amount = order_entry
            Cryptoexchange::Models::Order.new(price: price,
                                              amount: amount,
                                              timestamp: nil)
          end
        end
      end
    end
  end
end


text:
var Stream = require("stream").Stream,
    EventEmitter = require("events").EventEmitter,
    strata = require("./index"),
    utils = require("./utils");

/**
 * A middleware that checks the arguments from upstream and downstream apps
 * for conformance with the Strata specification. See SPEC for more information.
 */
module.exports = function (app) {
    return function lint(env, callback) {
        assert(arguments.length == 2, "App must be called with exactly two arguments: environment and callback");

        checkEnv(env);
        checkCallback(callback);

        app(env, function (status, headers, body) {
            assert(arguments.length == 3, "Callback must be called with exactly three arguments: status, headers, and body");

            checkStatus(status);
            checkHeaders(headers);
            checkBody(body);

            checkContentType(status, headers);
            checkContentLength(status, headers, body);

            callback(status, headers, body);
        });
    }
};

function assert(condition, message) {
    if (!condition) {
        throw new strata.Error(message);
    }
}

function checkEnv(env) {
    assert(typeof env === "object", "Environment must be an object");

    var requiredStringProperties = [
        "protocol",
        "protocolVersion",
        "requestMethod",
        "remoteAddr",
        "remotePort",
        "serverName",
        "serverPort",
        "scriptName",
        "pathInfo",
        "queryString"
    ];

    requiredStringProperties.forEach(function (p) {
        assert(p in env, 'Environment missing required property "' + p + '"');
        assert(typeof env[p] === "string", 'Property "' + p + '" must be a string');
    });

    assert("requestTime" in env, 'Environment missing required property "requestTime"');
    assert(env.requestTime instanceof Date, 'requestTime must be a Date');

    // The environment must not contain the properties httpContentType or
    // httpContentLength (use contentType and contentLength instead).
    assert(typeof env.httpContentType === "undefined", 'Environment must not contain property "httpContentType", use "contentType" instead');
    assert(typeof env.httpContentLength === "undefined", 'Environment must not contain property "httpContentLength", use "contentLength" instead');

    var requiredStrataProperties = [
        "input",
        "error",
        "strataVersion"
    ];

    requiredStrataProperties.forEach(function (p) {
        assert(p in env, 'Environment missing required property "' + p + '"');
    });

    // - protocol must be either "http:" or "https:"
    assert(["http:", "https:"].indexOf(env.protocol) != -1, 'protocol must be either "http:" or "https:"');

    // - requestMethod must be a valid HTTP verb as an uppercase String
    assert((/^[A-Z]+$/).test(env.requestMethod), "Request method must be a valid HTTP verb");

    // - requestTime must be a Date
    assert(env.requestTime instanceof Date, "Request time must be a Date");

    // - scriptName, if not empty, should start with a "/"
    // - pathInfo should be "/" if scriptName is empty
    // - scriptName should never be "/" but instead be empty
    if (env.scriptName !== "") {
        assert(env.scriptName.charAt(0) == "/", 'scriptName must start with "/"');
        assert(env.scriptName !== "/", 'scriptName must not be "/", make it empty and pathInfo "/"');
    }

    // - pathInfo, if not empty, should start with a "/"
    if (env.pathInfo !== "") {
        assert(env.pathInfo.charAt(0) === "/", 'pathInfo must start with "/"');
    }

    // - contentLength, if given, must consist of digits only
    if (env.contentLength) {
        assert(typeof env.contentLength === "string", "contentLength must be a string");
        assert((/^\d+$/).test(env.contentLength), "contentLength must consist of digits only");
    }

    // - input must be a readable Stream
    assert(env.input instanceof Stream, "input must be a Stream");
    assert(env.input.readable, "input must be readable");

    // - error must be a writable Stream
    // TODO: process.stderr is not a true Stream!
    assert(env.error instanceof EventEmitter, "error must be a Stream");
    assert(env.error.writable, "error must be writable");

    // - session      An object containing session data
    var session = env.session;
    if (session) {
        assert(typeof env === "object", "session must be an object");
    }

    // - strataVersion must be an array of integers
    assert(Array.isArray(env.strataVersion), "strataVersion must be an array");
    assert(env.strataVersion.length == 3, "strataVersion must contain three values [major, minor, patch]");
    env.strataVersion.forEach(function (n, i) {
        assert(typeof n === "number", "Index " + i + " of strataVersion must be a number");
    });
}

function checkCallback(callback) {
    // The callback is used to issue a response to the client and must be called with
    // exactly three arguments: the response *status*, the HTTP *headers*, and the
    // *body*.
    assert(typeof callback === "function", "Callback must be a function");
    assert(callback.length == 3, "Callback must accept three arguments");
}

function checkStatus(status) {
    // The status must be an HTTP status code as a Number.
    assert(typeof status === "number", "Status must be a number");
    assert(status >= 100 && status < 600, "Status must be a valid HTTP status code");
}

function checkHeaders(headers) {
    // The headers must be a JavaScript object whose properties are the names of HTTP
    // headers in their canonical form (i.e. "Content-Type" instead of "content-type").
    // Header names may contain only letters, digits, -, and _ and must start with a
    // letter and must not end with a - or _. If more than one value for a header is
    // required, the value for that property must be an array.
    assert(typeof headers === "object", "Headers must be an object");

    for (var headerName in headers) {
        assert(typeof headers[headerName] === "string", 'Value for header "' + headerName + '" must be a string');
        assert((/^[0-9A-Za-z_-]+$/).test(headerName), 'Invalid header name "' + headerName + '"');
        assert((/^[A-Za-z]/).test(headerName), "Header name must start with a letter");
        assert(!(/[_-]$/).test(headerName), 'Header name must not end with a "_" or "-"');
    }
}

function checkBody(body) {
    // The body must be either a string or a readable Stream. If it is a Stream, the
    // response will be pumped through to the client.
    assert(typeof body === "string" || body instanceof EventEmitter, "Body must be a string or Stream");
}

function checkContentType(status, headers) {
    // There must be a Content-Type header, except for when the status is 1xx, 204, or
    // 304, in which case there must be none given.
    if (utils.STATUS_WITH_NO_ENTITY_BODY.indexOf(status) == -1) {
        assert("Content-Type" in headers, "Missing Content-Type header");
    } else {
        assert(!("Content-Type" in headers), "Content-Type header given for respons with no entity body");
    }
}

function checkContentLength(status, headers, body) {
    // There must not be a Content-Length header when the status is 1xx, 204, or 304,
    // or it must be "0".
    if (utils.STATUS_WITH_NO_ENTITY_BODY.indexOf(status) != -1 && "Content-Length" in headers) {
        assert(headers["Content-Length"] == "0", "Non-zero Content-Length header given for respons with no entity body");
    }
}


text:
package io.debezium.connector.oracle.logminer;

import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.debezium.DebeziumException;
import io.debezium.connector.oracle.OracleConnection;
import io.debezium.connector.oracle.Scn;
import io.debezium.relational.Column;
import io.debezium.relational.Table;
import io.debezium.util.DelayStrategy;
import io.debezium.util.Strings;

/**
 * This class contains methods to configure and manage LogMiner utility
 */
public class LogMinerHelper {

    private static final String CURRENT = "CURRENT";
    private static final Logger LOGGER = LoggerFactory.getLogger(LogMinerHelper.class);

    /**
     * This method substitutes CONTINUOUS_MINE functionality
     *
     * @param connection connection
     * @param lastProcessedScn current offset
     * @param archiveLogRetention the duration that archive logs will be mined
     * @param archiveLogOnlyMode true to mine only archive lgos, false to mine all available logs
     * @param archiveDestinationName configured archive log destination name to use, may be {@code null}
     * @param maxRetries the number of retry attempts before giving up and throwing an exception about log state
     * @param initialDelay the initial delay
     * @param maxDelay the maximum delay
     * @throws SQLException if anything unexpected happens
     * @return log files that were added to the current mining session
     */
    // todo: check RAC resiliency
    public static List<LogFile> setLogFilesForMining(OracleConnection connection, Scn lastProcessedScn, Duration archiveLogRetention,
                                                     boolean archiveLogOnlyMode, String archiveDestinationName, int maxRetries,
                                                     Duration initialDelay, Duration maxDelay)
            throws SQLException {
        removeLogFilesFromMining(connection);

        // Restrict max attempts to 0 or greater values (sanity-check)
        // the code will do at least 1 attempt and up to maxAttempts extra polls based on configuration
        final int maxAttempts = Math.max(maxRetries, 0);
        final DelayStrategy retryStrategy = DelayStrategy.exponential(initialDelay, maxDelay);

        // We perform a retry algorithm here as there is a race condition where Oracle may update the V$LOG table
        // but the V$ARCHIVED_LOG lags behind and a single-shot SQL query may return an inconsistent set of results
        // due to Oracle performing the operation non-atomically.
        List<LogFile> logFilesForMining = new ArrayList<>();
        for (int attempt = 0; attempt <= maxAttempts; ++attempt) {
            logFilesForMining.addAll(getLogFilesForOffsetScn(connection, lastProcessedScn, archiveLogRetention,
                    archiveLogOnlyMode, archiveDestinationName));
            // we don't need lastProcessedSCN in the logs, as that one was already processed, but we do want
            // the next SCN to be present, as that is where we'll start processing from.
            if (!hasLogFilesStartingBeforeOrAtScn(logFilesForMining, lastProcessedScn.add(Scn.ONE))) {
                LOGGER.info("No logs available yet (attempt {})...", attempt + 1);
                logFilesForMining.clear();
                retryStrategy.sleepWhen(true);
                continue;
            }

            List<String> logFilesNames = logFilesForMining.stream().map(LogFile::getFileName).collect(Collectors.toList());
            for (String file : logFilesNames) {
                LOGGER.trace("Adding log file {} to mining session", file);
                String addLogFileStatement = SqlUtils.addLogFileStatement("DBMS_LOGMNR.ADDFILE", file);
                executeCallableStatement(connection, addLogFileStatement);
            }

            LOGGER.debug("Last mined SCN: {}, Log file list to mine: {}", lastProcessedScn, logFilesNames);
            return logFilesForMining;
        }

        final Scn minScn = getMinimumScn(logFilesForMining);
        if ((minScn.isNull() || logFilesForMining.isEmpty()) && archiveLogOnlyMode) {
            throw new DebeziumException("The log.mining.archive.log.only mode was recently enabled and the offset SCN " +
                    lastProcessedScn + "is not yet in any available archive logs. " +
                    "Please perform an Oracle log switch and restart the connector.");
        }
        throw new IllegalStateException("None of log files contains offset SCN: " + lastProcessedScn + ", re-snapshot is required.");
    }

    private static boolean hasLogFilesStartingBeforeOrAtScn(List<LogFile> logs, Scn scn) {
        return logs.stream().anyMatch(l -> l.getFirstScn().compareTo(scn) <= 0);
    }

    private static Scn getMinimumScn(List<LogFile> logs) {
        return logs.stream().map(LogFile::getFirstScn).min(Scn::compareTo).orElse(Scn.NULL);
    }

    /**
     * Get all log files that should be mined.
     *
     * @param connection database connection
     * @param offsetScn offset system change number
     * @param archiveLogRetention duration that archive logs should be mined
     * @param archiveLogOnlyMode true to mine only archive logs, false to mine all available logs
     * @param archiveDestinationName archive destination to use, may be {@code null}
     * @return list of log files
     * @throws SQLException if a database exception occurs
     */
    public static List<LogFile> getLogFilesForOffsetScn(OracleConnection connection, Scn offsetScn, Duration archiveLogRetention,
                                                        boolean archiveLogOnlyMode, String archiveDestinationName)
            throws SQLException {
        LOGGER.trace("Getting logs to be mined for offset scn {}", offsetScn);

        final List<LogFile> logFiles = new ArrayList<>();
        final Set<LogFile> onlineLogFiles = new LinkedHashSet<>();
        final Set<LogFile> archivedLogFiles = new LinkedHashSet<>();

        connection.query(SqlUtils.allMinableLogsQuery(offsetScn, archiveLogRetention, archiveLogOnlyMode, archiveDestinationName), rs -> {
            while (rs.next()) {
                String fileName = rs.getString(1);
                Scn firstScn = getScnFromString(rs.getString(2));
                Scn nextScn = getScnFromString(rs.getString(3));
                String status = rs.getString(5);
                String type = rs.getString(6);
                BigInteger sequence = new BigInteger(rs.getString(7));
                int thread = rs.getInt(10);
                if ("ARCHIVED".equals(type)) {
                    // archive log record
                    LogFile logFile = new LogFile(fileName, firstScn, nextScn, sequence, LogFile.Type.ARCHIVE, thread);
                    if (logFile.getNextScn().compareTo(offsetScn) >= 0) {
                        LOGGER.trace("Archive log {} with SCN range {} to {} sequence {} to be added.", fileName, firstScn, nextScn, sequence);
                        archivedLogFiles.add(logFile);
                    }
                }
                else if ("ONLINE".equals(type)) {
                    LogFile logFile = new LogFile(fileName, firstScn, nextScn, sequence, LogFile.Type.REDO, CURRENT.equalsIgnoreCase(status), thread);
                    if (logFile.isCurrent() || logFile.getNextScn().compareTo(offsetScn) >= 0) {
                        LOGGER.trace("Online redo log {} with SCN range {} to {} ({}) sequence {} to be added.", fileName, firstScn, nextScn, status, sequence);
                        onlineLogFiles.add(logFile);
                    }
                    else {
                        LOGGER.trace("Online redo log {} with SCN range {} to {} ({}) sequence {} to be excluded.", fileName, firstScn, nextScn, status, sequence);
                    }
                }
            }
        });

        // DBZ-3563
        // To avoid duplicate log files (ORA-01289 cannot add duplicate logfile)
        // Remove the archive log which has the same sequence number.
        for (LogFile redoLog : onlineLogFiles) {
            archivedLogFiles.removeIf(f -> {
                if (f.getSequence().equals(redoLog.getSequence())) {
                    LOGGER.trace("Removing archive log {} with duplicate sequence {} to {}", f.getFileName(), f.getSequence(), redoLog.getFileName());
                    return true;
                }
                return false;
            });
        }
        logFiles.addAll(archivedLogFiles);
        logFiles.addAll(onlineLogFiles);

        return logFiles;
    }

    private static Scn getScnFromString(String value) {
        if (Strings.isNullOrEmpty(value)) {
            return Scn.MAX;
        }
        return Scn.valueOf(value);
    }

    /**
     * This method removes all added log files from mining
     * @param conn connection
     * @throws SQLException something happened
     */
    public static void removeLogFilesFromMining(OracleConnection conn) throws SQLException {
        try (PreparedStatement ps = conn.connection(false).prepareStatement("SELECT FILENAME AS NAME FROM V$LOGMNR_LOGS");
                ResultSet result = ps.executeQuery()) {
            Set<String> files = new LinkedHashSet<>();
            while (result.next()) {
                files.add(result.getString(1));
            }
            for (String fileName : files) {
                executeCallableStatement(conn, SqlUtils.deleteLogFileStatement(fileName));
                LOGGER.debug("File {} was removed from mining", fileName);
            }
        }
    }

    private static void executeCallableStatement(OracleConnection connection, String statement) throws SQLException {
        Objects.requireNonNull(statement);
        try (CallableStatement s = connection.connection(false).prepareCall(statement)) {
            s.execute();
        }
    }

    /**
     * Returns a 0-based index offset for the column name in the relational table.
     *
     * @param columnName the column name, should not be {@code null}.
     * @param table the relational table, should not be {@code null}.
     * @return the 0-based index offset for the column name
     */
    public static int getColumnIndexByName(String columnName, Table table) {
        final Column column = table.columnWithName(columnName);
        if (column == null) {
            throw new DebeziumException("No column '" + columnName + "' found in table '" + table.id() + "'");
        }
        // want to return a 0-based index and column positions are 1-based
        return column.position() - 1;
    }
}


text:
#import <AVFoundation/AVFoundation.h>

#import <React/RCTEventEmitter.h>
#import <React/RCTLog.h>
#import <WebRTC/WebRTC.h>

#import "JitsiAudioSession+Private.h"

// Audio mode
typedef enum {
    kAudioModeDefault,
    kAudioModeAudioCall,
    kAudioModeVideoCall
} JitsiMeetAudioMode;

// Events
static NSString * const kDevicesChanged = @"org.jitsi.meet:features/audio-mode#devices-update";

// Device types (must match JS and Java)
static NSString * const kDeviceTypeBluetooth  = @"BLUETOOTH";
static NSString * const kDeviceTypeCar        = @"CAR";
static NSString * const kDeviceTypeEarpiece   = @"EARPIECE";
static NSString * const kDeviceTypeHeadphones = @"HEADPHONES";
static NSString * const kDeviceTypeSpeaker    = @"SPEAKER";
static NSString * const kDeviceTypeUnknown    = @"UNKNOWN";

@interface AudioMode : RCTEventEmitter<RTCAudioSessionDelegate>

@property(nonatomic, strong) dispatch_queue_t workerQueue;

@end

@implementation AudioMode {
    JitsiMeetAudioMode activeMode;
    RTCAudioSessionConfiguration *defaultConfig;
    RTCAudioSessionConfiguration *audioCallConfig;
    RTCAudioSessionConfiguration *videoCallConfig;
    RTCAudioSessionConfiguration *earpieceConfig;
    BOOL forceSpeaker;
    BOOL forceEarpiece;
    BOOL isSpeakerOn;
    BOOL isEarpieceOn;
}

RCT_EXPORT_MODULE();

+ (BOOL)requiresMainQueueSetup {
    return NO;
}

- (NSArray<NSString *> *)supportedEvents {
    return @[ kDevicesChanged ];
}

- (NSDictionary *)constantsToExport {
    return @{
        @"DEVICE_CHANGE_EVENT": kDevicesChanged,
        @"AUDIO_CALL" : [NSNumber numberWithInt: kAudioModeAudioCall],
        @"DEFAULT"    : [NSNumber numberWithInt: kAudioModeDefault],
        @"VIDEO_CALL" : [NSNumber numberWithInt: kAudioModeVideoCall]
    };
};

- (instancetype)init {
    self = [super init];
    if (self) {
        dispatch_queue_attr_t attributes =
        dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, -1);
        _workerQueue = dispatch_queue_create("AudioMode.queue", attributes);

        activeMode = kAudioModeDefault;

        defaultConfig = [[RTCAudioSessionConfiguration alloc] init];
        defaultConfig.category = AVAudioSessionCategoryAmbient;
        defaultConfig.categoryOptions = 0;
        defaultConfig.mode = AVAudioSessionModeDefault;

        audioCallConfig = [[RTCAudioSessionConfiguration alloc] init];
        audioCallConfig.category = AVAudioSessionCategoryPlayAndRecord;
        audioCallConfig.categoryOptions = AVAudioSessionCategoryOptionAllowBluetooth | AVAudioSessionCategoryOptionDefaultToSpeaker;
        audioCallConfig.mode = AVAudioSessionModeVoiceChat;

        videoCallConfig = [[RTCAudioSessionConfiguration alloc] init];
        videoCallConfig.category = AVAudioSessionCategoryPlayAndRecord;
        videoCallConfig.categoryOptions = AVAudioSessionCategoryOptionAllowBluetooth;
        videoCallConfig.mode = AVAudioSessionModeVideoChat;

        // Manually routing audio to the earpiece doesn't quite work unless one disables BT (weird, I know).
        earpieceConfig = [[RTCAudioSessionConfiguration alloc] init];
        earpieceConfig.category = AVAudioSessionCategoryPlayAndRecord;
        earpieceConfig.categoryOptions = 0;
        earpieceConfig.mode = AVAudioSessionModeVoiceChat;

        forceSpeaker = NO;
        forceEarpiece = NO;
        isSpeakerOn = NO;
        isEarpieceOn = NO;

        RTCAudioSession *session = JitsiAudioSession.rtcAudioSession;
        [session addDelegate:self];
    }

    return self;
}

- (dispatch_queue_t)methodQueue {
    // Use a dedicated queue for audio mode operations.
    return _workerQueue;
}

- (BOOL)setConfigWithoutLock:(RTCAudioSessionConfiguration *)config
                       error:(NSError * _Nullable *)outError {
    RTCAudioSession *session = JitsiAudioSession.rtcAudioSession;

    return [session setConfiguration:config error:outError];
}

- (BOOL)setConfig:(RTCAudioSessionConfiguration *)config
            error:(NSError * _Nullable *)outError {

    RTCAudioSession *session = JitsiAudioSession.rtcAudioSession;
    [session lockForConfiguration];
    BOOL success = [self setConfigWithoutLock:config error:outError];
    [session unlockForConfiguration];

    return success;
}

#pragma mark - Exported methods

RCT_EXPORT_METHOD(setMode:(int)mode
                  resolve:(RCTPromiseResolveBlock)resolve
                   reject:(RCTPromiseRejectBlock)reject) {
    RTCAudioSessionConfiguration *config = [self configForMode:mode];
    NSError *error;

    if (config == nil) {
        reject(@"setMode", @"Invalid mode", nil);
        return;
    }

    // Reset.
    if (mode == kAudioModeDefault) {
        forceSpeaker = NO;
        forceEarpiece = NO;
    }

    activeMode = mode;

    if ([self setConfig:config error:&error]) {
        resolve(nil);
    } else {
        reject(@"setMode", error.localizedDescription, error);
    }

    [self notifyDevicesChanged];
}

RCT_EXPORT_METHOD(setAudioDevice:(NSString *)device
                  resolve:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    RCTLogInfo(@"[AudioMode] Selected device: %@", device);

    RTCAudioSession *session = JitsiAudioSession.rtcAudioSession;
    [session lockForConfiguration];
    BOOL success;
    NSError *error = nil;

    // Reset these, as we are about to compute them.
    forceSpeaker = NO;
    forceEarpiece = NO;

    // The speaker is special, so test for it first.
    if ([device isEqualToString:kDeviceTypeSpeaker]) {
        forceSpeaker = YES;
        success = [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];
    } else {
        // Here we use AVAudioSession because RTCAudioSession doesn't expose availableInputs.
        AVAudioSession *_session = [AVAudioSession sharedInstance];
        AVAudioSessionPortDescription *port = nil;

        // Find the matching input device.
        for (AVAudioSessionPortDescription *portDesc in _session.availableInputs) {
            if ([portDesc.UID isEqualToString:device]) {
                port = portDesc;
                break;
            }
        }

        if (port != nil) {
            // First remove the override if we are going to select a different device.
            if (isSpeakerOn) {
                [session overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
            }

            // Special case for the earpiece.
            if ([port.portType isEqualToString:AVAudioSessionPortBuiltInMic]) {
                forceEarpiece = YES;
                [self setConfigWithoutLock:earpieceConfig error:nil];
            } else if (isEarpieceOn) {
                // Reset the config.
                RTCAudioSessionConfiguration *config = [self configForMode:activeMode];
                [self setConfigWithoutLock:config error:nil];
            }

            // Select our preferred input.
            success = [session setPreferredInput:port error:&error];
        } else {
            success = NO;
            error = RCTErrorWithMessage(@"Could not find audio device");
        }
    }

    [session unlockForConfiguration];

    if (success) {
        resolve(nil);
    } else {
        reject(@"setAudioDevice", error != nil ? error.localizedDescription : @"", error);
    }
}

RCT_EXPORT_METHOD(updateDeviceList) {
    [self notifyDevicesChanged];
}

#pragma mark - RTCAudioSessionDelegate

- (void)audioSessionDidChangeRoute:(RTCAudioSession *)session
                            reason:(AVAudioSessionRouteChangeReason)reason
                     previousRoute:(AVAudioSessionRouteDescription *)previousRoute {
    RCTLogInfo(@"[AudioMode] Route changed, reason: %lu", (unsigned long)reason);

    // Update JS about the changes.
    [self notifyDevicesChanged];

    dispatch_async(_workerQueue, ^{
        switch (reason) {
            case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
            case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
                // If the device list changed, reset our overrides.
                self->forceSpeaker = NO;
                self->forceEarpiece = NO;
                break;
            case AVAudioSessionRouteChangeReasonCategoryChange:
                // The category has changed, re-apply our config.
                // NB: It's tempting to doa  category check here and skip the processing,
                // but that won't work. If the config changes but the category remains
                // the same we'll still find ourselves here.
                break;
            default:
                return;
        }

        // We don't want to touch the category when in default mode.
        // This is to play well with other components which could be integrated
        // into the final application.
        if (self->activeMode != kAudioModeDefault) {
            RCTLogInfo(@"[AudioMode] Route changed, reapplying RTCAudioSession config");
            RTCAudioSessionConfiguration *config = [self configForMode:self->activeMode];
            [self setConfig:config error:nil];
            if (self->forceSpeaker && !self->isSpeakerOn) {
                [session lockForConfiguration];
                [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
                [session unlockForConfiguration];
            }
        }
    });
}

- (void)audioSession:(RTCAudioSession *)audioSession didSetActive:(BOOL)active {
    RCTLogInfo(@"[AudioMode] Audio session didSetActive:%d", active);
}

#pragma mark - Helper methods

- (RTCAudioSessionConfiguration *)configForMode:(int) mode {
    if (mode != kAudioModeDefault && forceEarpiece) {
        return earpieceConfig;
    }

    switch (mode) {
        case kAudioModeAudioCall:
            return audioCallConfig;
        case kAudioModeDefault:
            return defaultConfig;
        case kAudioModeVideoCall:
            return videoCallConfig;
        default:
            return nil;
    }
}

// Here we convert input and output port types into a single type.
- (NSString *)portTypeToString:(AVAudioSessionPort) portType {
    if ([portType isEqualToString:AVAudioSessionPortHeadphones]
            || [portType isEqualToString:AVAudioSessionPortHeadsetMic]) {
        return kDeviceTypeHeadphones;
    } else if ([portType isEqualToString:AVAudioSessionPortBuiltInMic]
            || [portType isEqualToString:AVAudioSessionPortBuiltInReceiver]) {
        return kDeviceTypeEarpiece;
    } else if ([portType isEqualToString:AVAudioSessionPortBuiltInSpeaker]) {
        return kDeviceTypeSpeaker;
    } else if ([portType isEqualToString:AVAudioSessionPortBluetoothHFP]
            || [portType isEqualToString:AVAudioSessionPortBluetoothLE]
            || [portType isEqualToString:AVAudioSessionPortBluetoothA2DP]) {
        return kDeviceTypeBluetooth;
    } else if ([portType isEqualToString:AVAudioSessionPortCarAudio]) {
        return kDeviceTypeCar;
    } else {
        return kDeviceTypeUnknown;
    }
}

- (void)notifyDevicesChanged {
    dispatch_async(_workerQueue, ^{
        NSMutableArray *data = [[NSMutableArray alloc] init];
        // Here we use AVAudioSession because RTCAudioSession doesn't expose availableInputs.
        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSString *currentPort = @"";
        AVAudioSessionRouteDescription *currentRoute = session.currentRoute;

        // Check what the current device is. Because the speaker is somewhat special, we need to
        // check for it first.
        if (currentRoute != nil) {
            AVAudioSessionPortDescription *output = currentRoute.outputs.firstObject;
            AVAudioSessionPortDescription *input = currentRoute.inputs.firstObject;
            if (output != nil && [output.portType isEqualToString:AVAudioSessionPortBuiltInSpeaker]) {
                currentPort = kDeviceTypeSpeaker;
                self->isSpeakerOn = YES;
            } else if (input != nil) {
                currentPort = input.UID;
                self->isSpeakerOn = NO;
                self->isEarpieceOn = [input.portType isEqualToString:AVAudioSessionPortBuiltInMic];
            }
        }

        BOOL headphonesAvailable = NO;
        for (AVAudioSessionPortDescription *portDesc in session.availableInputs) {
            if ([portDesc.portType isEqualToString:AVAudioSessionPortHeadsetMic] || [portDesc.portType isEqualToString:AVAudioSessionPortHeadphones]) {
                headphonesAvailable = YES;
                break;
            }
        }

        for (AVAudioSessionPortDescription *portDesc in session.availableInputs) {
            // Skip "Phone" if headphones are present.
            if (headphonesAvailable && [portDesc.portType isEqualToString:AVAudioSessionPortBuiltInMic]) {
                continue;
            }
            id deviceData
                = @{
                    @"type": [self portTypeToString:portDesc.portType],
                    @"name": portDesc.portName,
                    @"uid": portDesc.UID,
                    @"selected": [NSNumber numberWithBool:[portDesc.UID isEqualToString:currentPort]]
                };
            [data addObject:deviceData];
        }

        // We need to manually add the speaker because it will never show up in the
        // previous list, as it's not an input.
        [data addObject:
            @{ @"type": kDeviceTypeSpeaker,
               @"name": @"Speaker",
               @"uid": kDeviceTypeSpeaker,
               @"selected": [NSNumber numberWithBool:[kDeviceTypeSpeaker isEqualToString:currentPort]]
        }];

        [self sendEventWithName:kDevicesChanged body:data];
    });
}

@end


text:
title: Blog Widgets
---

{{#extend "layout-default"}}
  {{#content "css_vendor" mode="append"}}
    <link rel="stylesheet" href="{{global}}/vendor/plyr/plyr.css">
  {{/content}}

  {{#content "js_vendor" mode="append"}}

  {{/content}}

  {{#content "js" mode="append"}}

  {{/content}}

  {{#content "body"}}

Blog Widgets

Home

Widgets

Blog

          <button type="button" class="btn btn-sm btn-outline btn-default btn-round">
            Settings

          </button>

Possumus fugiendum verborum

Jan 16, 2016

Munere dictum dissentio dicturam mediocriterne honesta, morbi delectus
                  rationibus periculum opinor propterea intuemur poetarum efficeretur
                  interpretaris, labefactant aeternum reformidans, laborum inquit
                  laus. Dolor fana conficiuntque efficerent persequeris quos dicas
                  essent. Aristippus tollunt nollem clamat similique corpore gerendarum
                  quas initiis, possum.

                  READ MORE

                      25

                      18

                      Previous

                      Next

Expleantur manu graecam

Feb 21, 2016

Adiungimus acutum iudicatum aliud aegritudinem, tritani ignavi
                  incidant quaeritur transferrem loqueretur delectatio, appetere,
                  eruditi. Eamque quaeso diuturnum. Atomis quietae quamquam cadere
                  arbitrantur magnam referuntur utramque aristippi, filium eidola,
                  iudicat veniamus, noctesque invenerit, alia factorum aristoteli
                  phaedrum parta quicquid morbi animadversionem.

                  READ MORE

                      63

                      24

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer
                    nec odio. Praesent libero. Sed cursus ante dapibus diam.

Mar 8, 2016

Haeret voluptatibus docere disciplina divitiarum erant certa libenter
                  dicere nollem, istam nutu rogatiuncula proficiscuntur viderer
                  versatur voluptas, litteras tamque, captet idque. Chaere definitiones
                  scriptorem expetendas. Futura sumitur, irridente operosam evertitur
                  personae successionem doctissimos, enim exaudita quoquo, terentii
                  cursu expediunt similia.

                  READ MORE

                      37

                      20

                <audio controls style="width: 100%">

                  <source type="audio/mp3" src="https://cdn.selz.com/plyr/1.0/logistics-96-sample.mp3">
                  <source type="audio/ogg" src="https://cdn.selz.com/plyr/1.0/logistics-96-sample.ogg">

                  Download
                </audio>

Fana graeca amentur

Apr 15, 2016

Appellantur possent inmensae meo beatus angoribus, philosophorum
                  terroribus quamvis aiunt praestabiliorem intellegere platone
                  falsarum inscientia imperio, synephebos clarorum notissima cognosci
                  odit insolens liberalitati saepti efficiat, laetetur motum incurreret.
                  Admissum aspernandum, esset filium putamus tuo cernantur vacillare
                  atomis referri prorsus aliquod.

                  READ MORE

                      123

                      66

                <video poster="{{assets}}/examples/images/poster.jpg" controls crossorigin>

                  <source type="video/mp4" src="https://cdn.selz.com/plyr/1.0/movie.mp4">
                  <source type="video/webm" src="https://cdn.selz.com/plyr/1.0/movie.webm">

                  <track kind="captions" label="English" srclang="en" src="//cdn.selz.com/plyr/1.0/en.vtt"
                  default>

                    Download
                </video>

Consistat conetur verborum

May 15, 2016

Metuamus repudiandae, temeritas multoque utilitate laudari declarant
                  inducitur cupiditates, illa maximisque parvam intellegitur cupio
                  copulationesque placet infinitum nullo bella. Iucundo voluptate
                  physico uterque videor sensus diligenter. Diuturnum graecos utuntur
                  voluerint durissimis. Consectetur.

                  READ MORE

                      19

                      71

Dolemus vero fames

Jun 15, 2016

Personae romano, deditum, diu veniam totam aequo, voluptaria maluisset
                  cotidie gravis quando liberiusque placatae, ars dicitis potius,
                  ordiamur aegritudo conquisitis sicine omnibus specie habendus
                  iuvaret contemnere brute, concedo potuimus tractatas inquam effici.
                  Praeclara responsum provocatus m domo desiderat. Quid natum.

                  Read More

                      63

                      26

                    5

                    8

Persequeris malorum Pariter

July 15, 2016

Magnus tuentur consuetudinum impediente praeterierunt volunt
                    noris aegritudo, ultimum macedonum minimum quoniam vocet habendus
                    sitne putet fortitudinem. Vocant equidem nos perfruique distinguique
                    torquatos fugiendus conturbamur, dolorem quisquam reiciat eorumque,
                    maledicta, amicitiae damna conspectum penitus chremes synephebos
                    suscipiantur conectitur. Approbantibus privamur.

                    READ MORE

                  By
                  Heather Harper
                  05, 2016

                    3 Comments

Singulos flagitem cupiditatibus

Geometria eae servare dicat, amicitiam, dixissem principio coniuncta
                  adhibuit quantumcumque placeat easque, fidem gloriatur statuat
                  perspecta ferantur greges propemodum quieti, turpius vituperatoribus
                  complectitur leguntur vidisse assiduitas insolens audeam urbes
                  futuris. Arbitrium dicere multavit. Sola nullas. Animus si orestem
                  distinguique geometriaque.

                      253

                      115

                     Read More

                  June Lane /
                  News /
                  Jun 21, 2016

Plurimum attico latine

Pervenias fatendum epicureis parentes tollit nostra levis homini
                  quietus affirmatis, temperantiamque suscepi electram effectrices
                  miser nomini expetendam istis. Aristippi idque, cohaerescent
                  servata constituto afficit voluptas debilitatem individua sequi,
                  metu cedentem obruamus ignavi motus exercendi partus corrumpit
                  lectorem, desideraturam officia incidant.

                      21

                      35

                     Read More

                      July 28, 2016

Iudicem fieri maximeque aliud vacuitate.

                    <button type="button" class="btn btn-outline btn-inverse">READ MORE</button>

  {{/content}}
{{/extend}}


text:
using namespace PaintsNow;

// Script interfaces
CREATE_MODULE(SpaceComponentModule);
SpaceComponentModule::SpaceComponentModule(Engine& engine) : BaseClass(engine) {}

TObject<IReflect>& SpaceComponentModule::operator ()(IReflect& reflect) {
	BaseClass::operator () (reflect);

	if (reflect.IsReflectMethod()) {
		ReflectMethod(RequestNew)[ScriptMethodLocked = "New"];
		ReflectMethod(RequestInsertEntity)[ScriptMethodLocked = "InsertEntity"];
		ReflectMethod(RequestRemoveEntity)[ScriptMethodLocked = "RemoveEntity"];
		ReflectMethod(RequestQueryEntities)[ScriptMethod = "QueryEntities"];
		ReflectMethod(RequestSetForwardMask)[ScriptMethodLocked = "SetForwardMask"];
		ReflectMethod(RequestGetEntityCount)[ScriptMethodLocked = "GetEntityCount"];
		ReflectMethod(RequestOptimize)[ScriptMethodLocked = "Optimize"];
	}

	return *this;
}

TShared<SpaceComponent> SpaceComponentModule::RequestNew(IScript::Request& request, int32_t warpIndex, bool sorted) {
	TShared<SpaceComponent> spaceComponent = TShared<SpaceComponent>::From(allocator->New(sorted));
	uint32_t currentWarpIndex = engine.GetKernel().GetCurrentWarpIndex();
	if (warpIndex < 0) {
		assert(currentWarpIndex != ~(uint32_t)0);
		spaceComponent->SetWarpIndex(currentWarpIndex);
	} else {
		spaceComponent->SetWarpIndex(warpIndex);
		if (warpIndex != currentWarpIndex) {
			spaceComponent->Flag().fetch_or(Component::COMPONENT_OVERRIDE_WARP);
		}
	}

	return spaceComponent;
}

void SpaceComponentModule::RequestSetForwardMask(IScript::Request& request, IScript::Delegate<SpaceComponent> spaceComponent, uint32_t forwardMask) {
	CHECK_REFERENCES_NONE();
	CHECK_DELEGATE(spaceComponent);
	CHECK_THREAD_IN_MODULE(spaceComponent);

	if (forwardMask != 0) {
		spaceComponent->Flag().fetch_or(SpaceComponent::SPACECOMPONENT_FORWARD_EVENT_TICK, std::memory_order_relaxed);
	} else {
		spaceComponent->Flag().fetch_and(~SpaceComponent::SPACECOMPONENT_FORWARD_EVENT_TICK, std::memory_order_relaxed);
	}
}

uint32_t SpaceComponentModule::RequestGetEntityCount(IScript::Request& request, IScript::Delegate<SpaceComponent> spaceComponent) {
	CHECK_REFERENCES_NONE();
	CHECK_DELEGATE(spaceComponent);
	CHECK_THREAD_IN_MODULE(spaceComponent);
	return spaceComponent->GetEntityCount();
}

void SpaceComponentModule::RequestOptimize(IScript::Request& request, IScript::Delegate<SpaceComponent> spaceComponent) {
	CHECK_REFERENCES_NONE();
	CHECK_DELEGATE(spaceComponent);
	CHECK_THREAD_IN_MODULE(spaceComponent);

	spaceComponent->Optimize();
}

void SpaceComponentModule::RequestInsertEntity(IScript::Request& request, IScript::Delegate<SpaceComponent> spaceComponent, IScript::Delegate<Entity> entity) {
	CHECK_REFERENCES_NONE();
	CHECK_DELEGATE(spaceComponent);
	CHECK_DELEGATE(entity);
	CHECK_THREAD_IN_MODULE(entity);

	if (spaceComponent->Flag().load(std::memory_order_acquire) & SpaceComponent::TINY_ACTIVATED) {
		spaceComponent->Insert(engine, entity.Get());
	} else {
		request.Error("Orphan SpaceComponent cannot hold entities.");
	}
}

void SpaceComponentModule::RequestRemoveEntity(IScript::Request& request, IScript::Delegate<SpaceComponent> spaceComponent, IScript::Delegate<Entity> entity) {
	CHECK_REFERENCES_NONE();
	CHECK_DELEGATE(spaceComponent);
	CHECK_DELEGATE(entity);
	CHECK_THREAD_IN_MODULE(entity);

	spaceComponent->Remove(engine, entity.Get());
}

void SpaceComponentModule::RequestQueryEntities(IScript::Request& request, IScript::Delegate<SpaceComponent> spaceComponent, const Float3Pair& box) {
	CHECK_REFERENCES_NONE();
	CHECK_DELEGATE(spaceComponent);
	CHECK_THREAD_IN_MODULE(spaceComponent);

	std::vector<TShared<Entity> > entityList;
	spaceComponent->QueryEntities(entityList, box);

	request.DoLock();
	for (size_t i = 0; i < entityList.size(); i++) {
		request << entityList[i];
	}
	request.UnLock();
}

void SpaceComponentModule::ScriptUninitialize(IScript::Request& request) {
	Module::ScriptUninitialize(request);
}


text:
  <link href="style.css" rel="stylesheet" type="text/css">

The binary clock

:

:

    Built by ben-holm.es
    Binary clock? Huh?
    How did you do that?


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2017 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef EIGEN_INDEXED_VIEW_HELPER_H
#define EIGEN_INDEXED_VIEW_HELPER_H

namespace Eigen {

namespace internal {
struct symbolic_last_tag {};
}

/** \var last
  * \ingroup Core_Module
  *
  * Can be used as a parameter to Eigen::seq and Eigen::seqN functions to symbolically reference the last element/row/columns
  * of the underlying vector or matrix once passed to DenseBase::operator()(const RowIndices&, const ColIndices&).
  *
  * This symbolic placeholder supports standard arithmetic operations.
  *
  * A typical usage example would be:
  * \code
  * using namespace Eigen;
  * using Eigen::last;
  * VectorXd v(n);
  * v(seq(2,last-2)).setOnes();
  * \endcode
  *
  * \sa end
  */
static const symbolic::SymbolExpr<internal::symbolic_last_tag> last; // PLEASE use Eigen::last   instead of Eigen::placeholders::last

/** \var lastp1
  * \ingroup Core_Module
  *
  * Can be used as a parameter to Eigen::seq and Eigen::seqN functions to symbolically
  * reference the last+1 element/row/columns of the underlying vector or matrix once
  * passed to DenseBase::operator()(const RowIndices&, const ColIndices&).
  *
  * This symbolic placeholder supports standard arithmetic operations.
  * It is essentially an alias to last+fix<1>.
  *
  * \sa last
  */
#ifdef EIGEN_PARSED_BY_DOXYGEN
static const auto lastp1 = last+fix<1>;
#else
// Using a FixedExpr<1> expression is important here to make sure the compiler
// can fully optimize the computation starting indices with zero overhead.
static const symbolic::AddExpr<symbolic::SymbolExpr<internal::symbolic_last_tag>,symbolic::ValueExpr<Eigen::internal::FixedInt<1> > > lastp1(last+fix<1>());
#endif

namespace internal {

 // Replace symbolic last/end "keywords" by their true runtime value
inline Index eval_expr_given_size(Index x, Index /* size */)   { return x; }

template<int N>
FixedInt<N> eval_expr_given_size(FixedInt<N> x, Index /*size*/)   { return x; }

template<typename Derived>
Index eval_expr_given_size(const symbolic::BaseExpr<Derived> &x, Index size)
{
  return x.derived().eval(last=size-1);
}

// Extract increment/step at compile time
template<typename T, typename EnableIf = void> struct get_compile_time_incr {
  enum { value = UndefinedIncr };
};

// Analogue of std::get<0>(x), but tailored for our needs.
template<typename T>
EIGEN_CONSTEXPR Index first(const T& x) EIGEN_NOEXCEPT { return x.first(); }

// IndexedViewCompatibleType/makeIndexedViewCompatible turn an arbitrary object of type T into something usable by MatrixSlice
// The generic implementation is a no-op
template<typename T,int XprSize,typename EnableIf=void>
struct IndexedViewCompatibleType {
  typedef T type;
};

template<typename T,typename Q>
const T& makeIndexedViewCompatible(const T& x, Index /*size*/, Q) { return x; }

//--------------------------------------------------------------------------------
// Handling of a single Index
//--------------------------------------------------------------------------------

struct SingleRange {
  enum {
    SizeAtCompileTime = 1
  };
  SingleRange(Index val) : m_value(val) {}
  Index operator[](Index) const { return m_value; }
  static EIGEN_CONSTEXPR Index size() EIGEN_NOEXCEPT { return 1; }
  Index first() const EIGEN_NOEXCEPT { return m_value; }
  Index m_value;
};

template<> struct get_compile_time_incr<SingleRange> {
  enum { value = 1 }; // 1 or 0 ??
};

// Turn a single index into something that looks like an array (i.e., that exposes a .size(), and operator[](int) methods)
template<typename T, int XprSize>
struct IndexedViewCompatibleType<T,XprSize,typename internal::enable_if<internal::is_integral<T>::value>::type> {
  // Here we could simply use Array, but maybe it's less work for the compiler to use
  // a simpler wrapper as SingleRange
  //typedef Eigen::Array<Index,1,1> type;
  typedef SingleRange type;
};

template<typename T, int XprSize>
struct IndexedViewCompatibleType<T, XprSize, typename enable_if<symbolic::is_symbolic<T>::value>::type> {
  typedef SingleRange type;
};

template<typename T>
typename enable_if<symbolic::is_symbolic<T>::value,SingleRange>::type
makeIndexedViewCompatible(const T& id, Index size, SpecializedType) {
  return eval_expr_given_size(id,size);
}

//--------------------------------------------------------------------------------
// Handling of all
//--------------------------------------------------------------------------------

struct all_t { all_t() {} };

// Convert a symbolic 'all' into a usable range type
template<int XprSize>
struct AllRange {
  enum { SizeAtCompileTime = XprSize };
  AllRange(Index size = XprSize) : m_size(size) {}
  EIGEN_CONSTEXPR Index operator[](Index i) const EIGEN_NOEXCEPT { return i; }
  EIGEN_CONSTEXPR Index size() const EIGEN_NOEXCEPT { return m_size.value(); }
  EIGEN_CONSTEXPR Index first() const EIGEN_NOEXCEPT { return 0; }
  variable_if_dynamic<Index,XprSize> m_size;
};

template<int XprSize>
struct IndexedViewCompatibleType<all_t,XprSize> {
  typedef AllRange<XprSize> type;
};

template<typename XprSizeType>
inline AllRange<get_fixed_value<XprSizeType>::value> makeIndexedViewCompatible(all_t , XprSizeType size, SpecializedType) {
  return AllRange<get_fixed_value<XprSizeType>::value>(size);
}

template<int Size> struct get_compile_time_incr<AllRange<Size> > {
  enum { value = 1 };
};

} // end namespace internal

/** \var all
  * \ingroup Core_Module
  * Can be used as a parameter to DenseBase::operator()(const RowIndices&, const ColIndices&) to index all rows or columns
  */
static const Eigen::internal::all_t all; // PLEASE use Eigen::all instead of Eigen::placeholders::all

namespace placeholders {
  typedef symbolic::SymbolExpr<internal::symbolic_last_tag> last_t;
  typedef symbolic::AddExpr<symbolic::SymbolExpr<internal::symbolic_last_tag>,symbolic::ValueExpr<Eigen::internal::FixedInt<1> > > end_t;
  typedef Eigen::internal::all_t all_t;

  EIGEN_DEPRECATED static const all_t  all  = Eigen::all;    // PLEASE use Eigen::all    instead of Eigen::placeholders::all
  EIGEN_DEPRECATED static const last_t last = Eigen::last;   // PLEASE use Eigen::last   instead of Eigen::placeholders::last
  EIGEN_DEPRECATED static const end_t  end  = Eigen::lastp1; // PLEASE use Eigen::lastp1 instead of Eigen::placeholders::end
}

} // end namespace Eigen

#endif // EIGEN_INDEXED_VIEW_HELPER_H


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>AEDA-2MIEIC1-T4: Referência à classe PortaEmbarquePtr</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Página principal

Namespaces

Classes

Ficheiros

Lista de componentes

Índice dos componentes

Hierarquia de classes

Componentes membro

Membros públicos |
Atributos Privados

Referência à classe PortaEmbarquePtr

Classe que contém apontador para a classe PortaEmbarque (usada na BST).
Mais...

#include <PortaEmbarque.h>

Mostrar lista completa dos membros

Membros públicos

 	PortaEmbarquePtr (PortaEmbarque *p)

virtual 	~PortaEmbarquePtr ()

string 	getNumero () const

string 	getLocalizacao () const

unsigned 	getCapacidadePass () const

unsigned 	getVagasPass () const

unsigned 	getCategoriaAvioes () const

PortaEmbarque * 	operator() ()

 	Operador que retorna o apontador para a PortaEmbarque.

bool 	operator== (const PortaEmbarquePtr &porta_embarque) const

 	Operador que permite verificar se duas portas de embarque são equivalentes, comparando o seu número e a sua localização.

bool 	operator< (const PortaEmbarquePtr &porta_embarque) const

 	Operador que verifica se o número de uma porta de embarque é menor do que outra.

Atributos Privados

PortaEmbarque * 	porta

Descrição detalhada

Classe que contém apontador para a classe PortaEmbarque (usada na BST).

Definido na linha 94 do ficheiro PortaEmbarque.h.

Documentação dos Construtores & Destrutor

          PortaEmbarquePtr::PortaEmbarquePtr
          (
          PortaEmbarque *
           p
           )
           [inline]

Definido na linha 98 do ficheiro PortaEmbarque.h.

          virtual PortaEmbarquePtr::~PortaEmbarquePtr
          (

           )
           [inline, virtual]

Definido na linha 99 do ficheiro PortaEmbarque.h.

Documentação dos métodos

          unsigned PortaEmbarquePtr::getCapacidadePass
          (

           )
           const [inline]

Definido na linha 103 do ficheiro PortaEmbarque.h.

Referências PortaEmbarque::getCapacidadePass() e porta.

          unsigned PortaEmbarquePtr::getCategoriaAvioes
          (

           )
           const [inline]

Definido na linha 105 do ficheiro PortaEmbarque.h.

Referências PortaEmbarque::getCategoriaAvioes() e porta.

Referenciado por operator<().

          string PortaEmbarquePtr::getLocalizacao
          (

           )
           const [inline]

Definido na linha 102 do ficheiro PortaEmbarque.h.

Referências PortaEmbarque::getLocalizacao() e porta.

Referenciado por operator==().

          string PortaEmbarquePtr::getNumero
          (

           )
           const [inline]

Definido na linha 101 do ficheiro PortaEmbarque.h.

Referências PortaEmbarque::getNumero() e porta.

Referenciado por operator<() e operator==().

          unsigned PortaEmbarquePtr::getVagasPass
          (

           )
           const [inline]

Definido na linha 104 do ficheiro PortaEmbarque.h.

Referências PortaEmbarque::getVagasPass() e porta.

Referenciado por operator<() e CRUD::updatePortaEmbarqueDisp().

          PortaEmbarque* PortaEmbarquePtr::operator()
          (

           )
           [inline]

Operador que retorna o apontador para a PortaEmbarque.

Definido na linha 108 do ficheiro PortaEmbarque.h.

Referências porta.

          bool PortaEmbarquePtr::operator<
          (
          const PortaEmbarquePtr &
           porta_embarque
           )
           const

Operador que verifica se o número de uma porta de embarque é menor do que outra.

Definido na linha 39 do ficheiro PortaEmbarque.cpp.

Referências getCategoriaAvioes(), PortaEmbarque::getCategoriaAvioes(), getNumero(), PortaEmbarque::getNumero(), getVagasPass(), PortaEmbarque::getVagasPass() e porta.

          bool PortaEmbarquePtr::operator==
          (
          const PortaEmbarquePtr &
           porta_embarque
           )
           const

Operador que permite verificar se duas portas de embarque são equivalentes, comparando o seu número e a sua localização.

Definido na linha 32 do ficheiro PortaEmbarque.cpp.

Referências getLocalizacao(), PortaEmbarque::getLocalizacao(), getNumero(), PortaEmbarque::getNumero() e porta.

Documentação dos dados membro

          PortaEmbarque* PortaEmbarquePtr::porta [private]

Definido na linha 96 do ficheiro PortaEmbarque.h.

Referenciado por getCapacidadePass(), getCategoriaAvioes(), getLocalizacao(), getNumero(), getVagasPass(), operator()(), operator<() e operator==().

A documentação para esta classe foi gerada a partir dos seguintes ficheiros:

PortaEmbarque.h

PortaEmbarque.cpp

<address class="footer">Gerado em Wed Dec 22 2010 04:57:39 para AEDA-2MIEIC1-T4 por

 1.7.1 </address>


text:
BINARIES=Xenstore
include ../../standard.mk

run: Xenstore
	-sudo xl destroy Xenstore
	sudo xl create Xenstore.config -c


text:
describe RubyXsd do
  describe "XMLSchema root validation" do
    it "rejects non-schema root" do
      ex = assert_raises RuntimeError do
        RubyXsd.models_from "<non-xs></non-xs>"
      end
      assert_equal "Invalid XMLSchema root", ex.message
    end

    it "rejects schema root without XMLSchema namespace" do
      ex = assert_raises RuntimeError do
        RubyXsd.models_from "<schema></schema>"
      end
      assert_equal "Missing XMLSchema namespace", ex.message
    end

    it "rejects schema with wrong XMLSchema namespace" do
      ex = assert_raises RuntimeError do
        RubyXsd.models_from "<xs:schema xmlns:xs='wrong'></xs:schema>"
      end
      assert_equal "Wrong XMLSchema namespace", ex.message
    end
  end

  let(:schema) {
    "<xs:schema xmlns:xs='#{ClassMaker::XMLSchemaNS}'>%s</xs:schema>"
  }

  describe "simple elements" do
    let(:template) {
      schema % "<xs:element name='%s' type='%s' />"
    }

    it "defines object attributes" do
      RubyXsd.models_from template % [ "xsd_attr", "xs:string" ]
      RubyXsd.new.must_respond_to :xsd_attr
      RubyXsd.new.must_respond_to :xsd_attr=
    end
  end

  describe "complex elements" do
    let(:template) {
      schema % "<xs:element name='%s'>%s</xs:element>"
    }

    let(:class_template) {
      template % [ "xsd_complex", "" ]
    }

    let(:class_with_attrs_template) {
      template % [ "xsd_complex_with_attr", %{
        <xs:complexType>
          <xs:sequence>
            <xs:element name="foo" type="xs:string" />
            <xs:element name="bar" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      }]
    }

    it "defines a new Class" do
      RubyXsd.models_from class_template
      defined?(XsdComplex).must_be :==, "constant"
      XsdComplex.class.must_be :==, Class
    end

    it "defines class attributes" do
      RubyXsd.models_from class_with_attrs_template

      defined?(XsdComplexWithAttr).must_be :==, "constant"
      XsdComplexWithAttr.class.must_be :==, Class

      obj = XsdComplexWithAttr.new
      [ :foo, :foo=, :bar, :bar= ].each { |m|
        obj.must_respond_to m
      }
    end
  end

  describe "complex roots" do
    let(:template) {
      schema % "<xs:complexType name='%s'>%s</xs:complexType>"
    }

    let(:complex_root) {
      template % [ "complex_root", "" ]
    }

    let(:root_with_attrs_template) {
      template % [ "xsd_root_with_attr", %{
        <xs:sequence>
          <xs:element name="foo" type="xs:string" />
          <xs:element name="bar" type="xs:string" />
        </xs:sequence>
      }]
    }

    it "defines new class" do
      RubyXsd.models_from complex_root
      defined?(ComplexRoot).must_be :==, "constant"
      ComplexRoot.class.must_be :==, Class
    end

    it "defines class attributes" do
      RubyXsd.models_from root_with_attrs_template

      defined?(XsdRootWithAttr).must_be :==, "constant"
      XsdRootWithAttr.class.must_be :==, Class

      obj = XsdRootWithAttr.new
      [ :foo, :foo=, :bar, :bar= ].each { |m|
        obj.must_respond_to m
      }
    end
  end

  describe "nested classes" do
    let(:template) {
      schema % %{
        <xs:complexType name='%s'>
          <xs:sequence>%s</xs:sequence>
        </xs:complexType>
      }
    }

    let(:elements_template) {
      template % [ "elem_parent", %{
        <xs:element name="nested1"></xs:element>
        <xs:element name="nested2"></xs:element>
      }]
    }

    let(:elements_template_with_attr) {
      template % [ "elem_parent_with_attr", %{
        <xs:element name="nested1">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="foo" type="xs:string" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="nested2">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="bar" type="xs:string" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      }]
    }

    it "nests with complex elements" do
      RubyXsd.models_from elements_template

      defined?(ElemParent).must_be :==, "constant"
      ElemParent.class.must_be :==, Class

      defined?(Nested1).must_be_nil
      defined?(ElemParent::Nested1).must_be :==, "constant"
      ElemParent::Nested1.class.must_be :==, Class

      defined?(Nested2).must_be_nil
      defined?(ElemParent::Nested2).must_be :==, "constant"
      ElemParent::Nested2.class.must_be :==, Class
    end

    it "nests with complex elements" do
      RubyXsd.models_from elements_template_with_attr

      ElemParentWithAttr::Nested1.new.must_respond_to :foo
      ElemParentWithAttr::Nested1.new.wont_respond_to :bar

      ElemParentWithAttr::Nested2.new.wont_respond_to :foo
      ElemParentWithAttr::Nested2.new.must_respond_to :bar
    end
  end

  describe "restrictions" do
    describe "compact form" do
      let(:template) {
        schema % %{
          <xs:simpleType name="foo">
            <xs:restriction base="xs:%s">%s</xs:restriction>
          </xs:simpleType>
        }
      }

      let(:make_bar) {
        class Bar
          include ActiveModel::Validations
          attr_accessor :baz
          validates :baz, foo: true
        end
      }

      after do
        [ :FooValidator, :Bar ].each { |const|
          Object.send(:remove_const, const) if Object.const_defined? const
        }
      end

      it "creates validator" do
        RubyXsd.models_from template % [ "string", "" ]

        defined?(FooValidator).must_be :==, "constant"
        FooValidator.superclass.must_be :==, ActiveModel::EachValidator
      end

      it "validates string type" do
        RubyXsd.models_from template % [ "string", "" ]
        make_bar

        bar = Bar.new
        bar.baz = 1
        bar.valid?.wont_equal true

        bar.baz = "1"
        bar.valid?.must_equal true
      end

      it "validates integer type" do
        RubyXsd.models_from template % [ "integer", "" ]
        make_bar

        bar = Bar.new
        bar.baz = 1
        bar.valid?.must_equal true

        bar.baz = "1"
        bar.valid?.wont_equal true
      end

      describe "Whitespace handling" do
        let(:whitespace_schema) {
          template % [ "string", %{<xs:whiteSpace value="%s" />} ]
        }

        let(:whitespace_string) {
          "  abc  de\tfg\n\rhi jk   "
        }

        let(:replaced_string) {
          "  abc  de fg  hi jk   "
        }

        let(:collapsed_string) {
          "abc de fg hi jk"
        }

        def apply action
          xsd = whitespace_schema % action
          RubyXsd.models_from xsd
          make_bar

          bar = Bar.new
          bar.baz = whitespace_string
          bar.valid?
          bar
        end

        it "preserves" do
          apply("preserve").baz.must_equal whitespace_string
        end

        it "replaces" do
          apply("replace").baz.must_equal replaced_string
        end

        it "collapses" do
          apply("collapse").baz.must_equal collapsed_string
        end
      end

      describe "Enumeration handling" do
        def enum_xsd values
          enum_str = ""
          values.each do |v|
            enum_str << %{<xs:enumeration value="#{v}" />}
          end
          template % [ "string", enum_str ]
        end

        let(:range) { (5..10).to_a + (20..25).to_a }
        let(:out_of_range) { (1..30).to_a - range }
        let(:bar) { Bar.new }

        before do
          RubyXsd.models_from enum_xsd range
          make_bar
        end

        it "accepts value in range" do
          range.each { |val|
            bar.baz = val.to_s
            bar.valid?.must_equal true, message: bar.errors.messages
          }
        end

        it "rejects value out of range" do
          out_of_range.each { |val|
            bar.baz = val.to_s
            bar.valid?.wont_equal true, message: bar.errors.messages

            range_str = range.collect{|v| v.to_s}.to_s
            bar.errors.messages[:baz].first
            .must_equal "#{val}: not in #{range_str}"
          }
        end
      end

      describe "Regexp handling" do
        let(:pattern) { '\w{3}[X-Z]{3}_\d{6}' }

        let(:pattern_schema) {
          template % [ "string", %{<xs:pattern value="#{pattern}" />} ]
        }

        let(:bar) {
          inst = Bar.new
          inst.baz = "AbcXYZ_123456"
          inst
        }

        before do
          RubyXsd.models_from pattern_schema
          make_bar
        end

        it "accepts value matching pattern" do
          bar.valid?.must_equal true, message: bar.errors.messages
        end

        it "rejects value not matching pattern" do
          bar.baz = "not matches"
          bar.valid?.wont_equal true, message: bar.errors.messages
          bar.errors.messages[:baz].first
            .must_equal "#{bar.baz}: not matching #{pattern}"
        end
      end
    end
  end
end


text:
package com.frodo.github.bean.dto.request;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Created by Bernat on 13/07/2014.
 */
public class RequestTokenDTO implements Parcelable {
    public static final Creator<RequestTokenDTO> CREATOR =
            new Creator<RequestTokenDTO>() {
                public RequestTokenDTO createFromParcel(Parcel source) {
                    return new RequestTokenDTO(source);
                }

                public RequestTokenDTO[] newArray(int size) {
                    return new RequestTokenDTO[size];
                }
            };
    public String client_id;
    public String client_secret;
    public String code;
    public String redirect_uri;

    public RequestTokenDTO() {
    }

    protected RequestTokenDTO(Parcel in) {
        this.client_id = in.readString();
        this.client_secret = in.readString();
        this.code = in.readString();
        this.redirect_uri = in.readString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.client_id);
        dest.writeString(this.client_secret);
        dest.writeString(this.code);
        dest.writeString(this.redirect_uri);
    }
}


text:
"""Hello World API implemented using Google Cloud Endpoints.

Defined here are the ProtoRPC messages needed to define Schemas for methods
as well as those methods defined in an API.
"""

import endpoints
from protorpc import messages
from protorpc import message_types
from protorpc import remote

# TODO: Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '416225420528-d233rmk6j166dil27ungv1j242bu3ikj.apps.googleusercontent.com'
ANDROID_CLIENT_ID = 'replace this with your Android client ID'
IOS_CLIENT_ID = 'replace this with your iOS client ID'
ANDROID_AUDIENCE = WEB_CLIENT_ID

package = 'Hello'

class Greeting(messages.Message):
    """Greeting that stores a message."""
    message = messages.StringField(1)

class GreetingCollection(messages.Message):
    """Collection of Greetings."""
    items = messages.MessageField(Greeting, 1, repeated=True)

STORED_GREETINGS = GreetingCollection(items=[
    Greeting(message='hello world!'),
    Greeting(message='goodbye world!'),
])

@endpoints.api(name='helloworld', version='v1',
               allowed_client_ids=[WEB_CLIENT_ID, ANDROID_CLIENT_ID,
                                   IOS_CLIENT_ID],
               audiences=[ANDROID_AUDIENCE])
class HelloWorldApi(remote.Service):
    """Helloworld API v1."""

    MULTIPLY_METHOD_RESOURCE = endpoints.ResourceContainer(
            Greeting,
            times=messages.IntegerField(2, variant=messages.Variant.INT32,
                                        required=True))

    @endpoints.method(MULTIPLY_METHOD_RESOURCE, Greeting,
                      path='hellogreeting/{times}', http_method='POST',
                      name='greetings.multiply')
    def greetings_multiply(self, request):
        return Greeting(message=request.message * request.times)

    @endpoints.method(message_types.VoidMessage, GreetingCollection,
                      path='hellogreeting', http_method='GET',
                      name='greetings.listGreeting')
    def greetings_list(self, unused_request):
        return STORED_GREETINGS

    ID_RESOURCE = endpoints.ResourceContainer(
            message_types.VoidMessage,
            id=messages.IntegerField(1, variant=messages.Variant.INT32))

    @endpoints.method(ID_RESOURCE, Greeting,
                      path='hellogreeting/{id}', http_method='GET',
                      name='greetings.getGreeting')
    def greeting_get(self, request):
        try:
            return STORED_GREETINGS.items[request.id]
        except (IndexError, TypeError):
            raise endpoints.NotFoundException('Greeting %s not found.' %
                                              (request.id,))

    @endpoints.method(message_types.VoidMessage, Greeting,
                      path='hellogreeting/authed', http_method='POST',
                      name='greetings.authed')
    def greeting_authed(self, request):
        current_user = endpoints.get_current_user()
        email = (current_user.email() if current_user is not None
                 else 'Anonymous')
        return Greeting(message='hello %s' % (email,))

APPLICATION = endpoints.api_server([HelloWorldApi])


text:
package io.lettuce.core.output;

import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.List;

import io.lettuce.core.codec.RedisCodec;
import io.lettuce.core.internal.LettuceAssert;

/**
 * {@link List} of keys output.
 *
 * @param <K> Key type.
 * @param <V> Value type.
 * @author Will Glozer
 * @author Mark Paluch
 */
public class KeyListOutput<K, V> extends CommandOutput<K, V, List<K>> implements StreamingOutput<K> {

    private boolean initialized;

    private Subscriber<K> subscriber;

    public KeyListOutput(RedisCodec<K, V> codec) {
        super(codec, Collections.emptyList());
        setSubscriber(ListSubscriber.instance());
    }

    @Override
    public void set(ByteBuffer bytes) {

        if (bytes == null) {
            return;
        }

        subscriber.onNext(output, bytes == null ? null : codec.decodeKey(bytes));
    }

    @Override
    public void multi(int count) {

        if (!initialized) {
            output = OutputFactory.newList(count);
            initialized = true;
        }
    }

    @Override
    public void setSubscriber(Subscriber<K> subscriber) {
        LettuceAssert.notNull(subscriber, "Subscriber must not be null");
        this.subscriber = subscriber;
    }

    @Override
    public Subscriber<K> getSubscriber() {
        return subscriber;
    }

}


text:
'use strict';

angular.module('webApp')
  .factory('api', function($http, $timeout) {
    var ordersUrl = '/api/orders',
      resetUrl = '/api/reset';
    return {
      /**
       * Get orders every interval ms. Call fn on success.
       * @param fn
       * @param interval
       */
      loopOrders: function(fn, interval) {
        function rec() {
          $http.get(ordersUrl)
            .success(function(data) {
              fn(data);
              $timeout(rec, interval);
            })
            .error(function() {
              $timeout(rec, interval);
            });
        }
        rec();
      },

      /**
       * Tell api to start over.
       */
      reset: function() {
        $http.post(resetUrl);
      }
    };
  });


text:
namespace metaforce {
class CSimplePool;

class CDecalDataFactory {
  static bool CreateDPSM(CDecalDescription* desc, CInputStream& in, CSimplePool* resPool);
  static std::unique_ptr<CDecalDescription> CreateGeneratorDescription(CInputStream& in, CSimplePool* resPool);
  static void GetQuadDecalInfo(CInputStream& in, CSimplePool* resPool, FourCC clsId, SQuadDescr& quad);

public:
  static std::unique_ptr<CDecalDescription> GetGeneratorDesc(CInputStream& in, CSimplePool* resPool);
};

CFactoryFnReturn FDecalDataFactory(const SObjectTag& tag, CInputStream& in, const CVParamTransfer& vparms,
                                   CObjectReference*);
} // namespace metaforce


text:
'use strict';

App.directive('clickOutside', function ($window, $parse) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var clickOutsideHandler = $parse(attrs.clickOutside);

            angular.element($window).on('click', function (event) {
                if (element[0].contains(event.target)) return;

                clickOutsideHandler(scope, {$event: event});
                scope.$apply();
            });
        }
    };
});


text:
SUBDIRS= certs config keys control domains metrics reserved system_status template version
#do_first_run

tests:
	echo -n "\033[0;34m System tests \033[0;30m\n"
	@$(foreach dir,$(SUBDIRS), cd $(dir); echo $(dir); make -s tests; cd ..;)


text:
var profile = require('../../../lib/util/profile');

exports.getMockedProfile = function () {
  var newProfile = new profile.Profile();

  newProfile.addSubscription(new profile.Subscription({
    id: 'c9cbd920-c00c-427c-852b-8aaf38badaeb',
    name: 'Azure SDK Powershell Test',
    user: {
      name: 'user@domain.example',
      type: 'user'
    },
    tenantId: '72f988bf-86f1-41af-91ab-2d7cd011db47',
    registeredProviders: ['website'],
    registeredResourceNamespaces: [],
    isDefault: true
  }, newProfile.environments['AzureCloud']));

  return newProfile;
};

exports.setEnvironment = function() {
  process.env['AZURE_STORAGE_CONNECTION_STRING'] = 'DefaultEndpointsProtocol=https;AccountName=teststorage101;AccountKey=null';
}

exports.scopes = [[function (nock) {
var result =
nock('https://teststorage101.blob.core.windows.net:443')
  .get('/storageclitest?restype=container&comp=acl')
  .reply(200, "<?xml version=\"1.0\" encoding=\"utf-8\"?><SignedIdentifiers />", { 'transfer-encoding': 'chunked',
  'content-type': 'application/xml',
  'last-modified': 'Fri, 13 Mar 2015 03:50:51 GMT',
  etag: '"0x8D22B5808A42244"',
  server: 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0',
  'x-ms-request-id': 'aff95390-0001-0051-7a22-f37769000000',
  'x-ms-version': '2014-02-14',
  'x-ms-blob-public-access': 'container',
  date: 'Fri, 13 Mar 2015 03:50:52 GMT' });
 return result; },
function (nock) {
var result =
nock('https://teststorage101.blob.core.windows.net:443')
  .filteringRequestBody(function (path) { return '*';})
.put('/storageclitest?restype=container&comp=acl', '*')
  .reply(200, "", { 'transfer-encoding': 'chunked',
  'last-modified': 'Fri, 13 Mar 2015 03:50:52 GMT',
  etag: '"0x8D22B5809242CBE"',
  server: 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0',
  'x-ms-request-id': 'd592bdc4-0001-003e-7eae-c433e3000000',
  'x-ms-version': '2014-02-14',
  date: 'Fri, 13 Mar 2015 03:50:52 GMT' });
 return result; }]];


text:
{extend name="base" /}
{block name="body"}

管理员

添加管理员

编辑管理员

                <form class="layui-form form-container" action="{:url('admin/admin_user/update')}" method="post">

                        用户名

                            <input type="text" name="username" value="{$admin_user.username}" required  lay-verify="required" placeholder="请输入用户名" class="layui-input">

                        密码

                            <input type="password" name="password" value="" placeholder="(选填)如不修改则留空" class="layui-input">

                        重复密码

                            <input type="password" name="confirm_password" value="" placeholder="(选填)如不修改则留空" class="layui-input">

                        状态

                            <input type="radio" name="status" value="1" title="启用" {if condition="$admin_user.status==1"} checked="checked"{/if}>
                            <input type="radio" name="status" value="0" title="禁用" {if condition="$admin_user.status==0"} checked="checked"{/if}>

                        所属权限组

                            <select name="group_id" lay-verify="required">
                                {foreach name="auth_group_list" item="vo"}
                                <option value="{$vo.id}" {if condition="$admin_user.group_id==$vo.id"} selected="selected"{/if}>{$vo.title}</option>
                                {/foreach}
                            </select>

                            <input type="hidden" name="id" value="{$admin_user.id}">
                            <button class="layui-btn" lay-submit lay-filter="*">更新</button>
                            <button type="reset" class="layui-btn layui-btn-primary">重置</button>

                </form>

{/block}


text:
<?php

declare(strict_types=1);

use Linna\Session\Session;
use Linna\Session\MysqlPdoSessionHandler;

//create session object
$session = new Session(
    name:           $config['session']['name'],
    expire:         $config['session']['expire'],
    cookieDomain:   $config['session']['cookieDomain'],
    cookiePath:     $config['session']['cookiePath'],
    cookieSecure:   $config['session']['cookieSecure'],
    cookieHttpOnly: $config['session']['cookieHttpOnly']
);

//switch to required session handler
//remind to uncomment proper section in Persistent storage section
$handler = $container->resolve(MysqlPdoSessionHandler::class);
$session->setSessionHandler($handler);

//start session
$session->start();

//store session instance
$container->set(Session::class, $session);


text:
A TensorFlow writer is used to write processed data to TFRecord files in the
data preparation. To create a new writer you should inherit from the general
TFWriter class defined in tfwriter.py and overwrite the abstract methods. You
should then add it to the factory method in tfwriter_factory.py and to the
package in \_\_init\_\_.py.


text:
layout: docs
title: Visually hidden
description: Use these helpers to visually hide elements but keep them accessible to assistive technologies.
group: helpers
aliases:
  - "/docs/helpers/screen-readers/"
  - "/docs/helpers/visually-hidden/"
  - "/docs/5.2/helpers/screen-readers/"
---

Visually hide an element while still allowing it to be exposed to assistive technologies (such as screen readers) with `.visually-hidden`. Use `.visually-hidden-focusable` to visually hide an element by default, but to display it when it's focused (e.g. by a keyboard-only user). `.visually-hidden-focusable` can also be applied to a container–thanks to `:focus-within`, the container will be displayed when any child element of the container receives focus.

{{< example >}}

Title for screen readers

Skip to main content

A container with a focusable element.

{{< /example >}}

Both `visually-hidden` and `visually-hidden-focusable` can also be used as mixins.

```scss
// Usage as a mixin

.visually-hidden-title {
  @include visually-hidden;
}

.skip-navigation {
  @include visually-hidden-focusable;
}
```


text:
#pragma once

#include <QtWidgets/QGraphicsView>
#include <QtGui/QKeyEvent>

#include "qrutils/utilsDeclSpec.h"

namespace graphicsUtils {

class QRUTILS_EXPORT AbstractView : public QGraphicsView
{
	Q_OBJECT
public:
	AbstractView(QWidget *parent = 0);

public slots:
	void zoomIn();
	void zoomOut();

signals:
	/// Emitted when user pressed delete button when this view was in focus.
	void deleteItem();

	/// Emitted when scene zoom changes.
	void zoomChanged();

	/// Emitted when current visible scene rectangle changes.
	void contentsRectChanged();

protected:
	void keyPressEvent(QKeyEvent *event) override;
	void wheelEvent(QWheelEvent *event) override;
	void scrollContentsBy(int dx, int dy) override;
};

}