text:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import _ from 'lodash';
import Table from 'react-bootstrap-datagrid';
import faker from 'faker';

const columns = [
  {
    title: 'firstName',
    name: 'firstName',
  },
  {
    title: 'lastName',
    name: 'lastName',
  },
  {
    title: 'email',
    name: 'email',
  },
  {
    title: 'company',
    name: 'company',
  }
];
const items = _
  .range(1000)
  .map(i => ({
    id: i,
    firstName: faker.name.firstName(),
    lastName: faker.name.lastName(),
    phone: faker.phone.phoneNumber(),
    email: faker.internet.email(),
    company: faker.company.companyName()
  }));

class Simple extends Component {
  state = {
    items,
    multiSort: false
  };
  constructor(props) {
    super(props);
    function setSortMode(multiSort) {
      this.setState({
        multiSort,
        sortStatus: undefined
      });
    }
    this._handleSortChange = ::this._handleSortChange;
    this._setSortModeSingle = setSortMode.bind(this, false);
    this._setSortModeMultiple = setSortMode.bind(this, true);
  }
  _handleSortChange(sortStatus) {
    let items;
    if(this.state.multiSort) {
      items = _.orderBy(
        this.state.items,
        sortStatus.map(sort => (
          rowItem => rowItem[sort.name]
        )),
        sortStatus.map(sort => sort.dir)
      );
    }
    else {
      items = _.orderBy(
        this.state.items,
        [rowItem => rowItem[sortStatus.name]],
        [sortStatus.dir]
      );
    }
    this.setState({
      items,
      sortStatus
    });
  }
  render() {
    const {
      multiSort,
      items,
      sortStatus
    } = this.state;
    return (

              <input
                type="radio"
                style={{pointerEvent: 'none'}}
                checked={!multiSort}
                onChange={this._setSortModeSingle}
              />
              single field

              <input
                type="radio"
                style={{pointerEvent: 'none'}}
                checked={multiSort}
                onChange={this._setSortModeMultiple}
              />
              multiple field

    );
  }
}

ReactDOM.render(
  <Simple/>,
  document.getElementById('main')
);


text:
var Gemini = require('gemini-exchange-coffee-api/lib/gemini');
var util = require('../core/util.js');
var _ = require('lodash');
var moment = require('moment');
var log = require('../core/log');

var Trader = function(config) {
  _.bindAll(this);
  if(_.isObject(config)) {
    this.key = config.key;
    this.secret = config.secret;
  }
  this.name = 'Gemini';
  this.balance;
  this.price;
  this.asset = config.asset;
  this.currency = config.currency;
  this.pair = this.asset + this.currency;
  this.gemini = new Gemini(this.key, this.secret);
}

// if the exchange errors we try the same call again after
// waiting 10 seconds
Trader.prototype.retry = function(method, args) {
  var wait = +moment.duration(10, 'seconds');
  log.debug(this.name, 'returned an error, retrying..');

  var self = this;

  // make sure the callback (and any other fn)
  // is bound to Trader
  _.each(args, function(arg, i) {
    if(_.isFunction(arg))
      args[i] = _.bind(arg, self);
  });

  // run the failed method again with the same
  // arguments after wait
  setTimeout(
    function() { method.apply(self, args) },
    wait
  );
}

Trader.prototype.getPortfolio = function(callback) {
  var args = _.toArray(arguments);
  this.gemini.wallet_balances(function (err, data, body) {

    if(err && err.message === '401') {
      let e = 'Gemini replied with an unauthorized error. ';
      e += 'Double check whether your API key is correct.';
      util.die(e);
    }

    if(err || !data)
      return this.retry(this.getPortfolio, args);

    // We are only interested in funds in the "exchange" wallet
    data = data.filter(c => c.type === 'exchange');

    const asset = _.find(data, c => c.currency.toUpperCase() === this.asset);
    const currency = _.find(data, c => c.currency.toUpperCase() === this.currency);

    let assetAmount, currencyAmount;

    if(_.isObject(asset) && _.isNumber(+asset.available) && !_.isNaN(+asset.available))
      assetAmount = +asset.available;
    else {
      log.error(`Gemini did not provide ${this.asset} amount, assuming 0`);
      assetAmount = 0;
    }

    if(_.isObject(currency) && _.isNumber(+currency.available) && !_.isNaN(+currency.available))
      currencyAmount = +currency.available;
    else {
      log.error(`Gemini did not provide ${this.currency} amount, assuming 0`);
      currencyAmount = 0;
    }

    const portfolio = [
      { name: this.asset, amount: assetAmount },
      { name: this.currency, amount: currencyAmount },
    ];

    callback(err, portfolio);
  }.bind(this));
}

Trader.prototype.getTicker = function(callback) {
  var args = _.toArray(arguments);
  // the function that will handle the API callback
  var process = function(err, data, body) {
    if (err)
        return this.retry(this.getTicker(args));

    // whenever we reach this point we have valid
    // data, the callback is still the same since
    // we are inside the same javascript scope.
    callback(err, {bid: +data.bid, ask: +data.ask})
  }.bind(this);
  this.gemini.ticker(this.pair, process);
}

// This assumes that only limit orders are being placed, so fees are the
// "maker fee" of 0.1%.  It does not take into account volume discounts.
Trader.prototype.getFee = function(callback) {
    var makerFee = 0.25;
    callback(false, makerFee / 100);
}

Trader.prototype.submit_order = function(type, amount, price, callback) {
  var args = _.toArray(arguments);

  amount = Math.floor(amount*100000000)/100000000;
  this.gemini.new_order(
    this.pair,
    amount + '',
    price + '',
    this.name.toLowerCase(),
    type,
    'exchange limit',
    function (err, data, body) {
      if (err) {
        log.error('unable to ' + type, err, body);
        return this.retry(this.submit_order, args);
      }

      callback(err, data.order_id);
    }.bind(this));
}

Trader.prototype.buy = function(amount, price, callback) {
  this.submit_order('buy', amount, price, callback);
}

Trader.prototype.sell = function(amount, price, callback) {
  this.submit_order('sell', amount, price, callback);
}

Trader.prototype.checkOrder = function(order_id, callback) {
  var args = _.toArray(arguments);
  this.gemini.order_status(order_id, function (err, data, body) {

    if(err || !data)
      return this.retry(this.checkOrder, arguments);

    callback(err, !data.is_live);
  }.bind(this));
}

Trader.prototype.getOrder = function(order, callback) {
  var args = _.toArray(arguments);
  var get = function(err, data) {
    if(err || !data)
      return this.retry(this.getOrder, arguments);

    var price = parseFloat(data.avg_execution_price);
    var amount = parseFloat(data.executed_amount);
    var date = moment.unix(data.timestamp);

    callback(undefined, {price, amount, date});
  }.bind(this);

  this.gemini.order_status(order, get);
}

Trader.prototype.cancelOrder = function(order_id, callback) {
  var args = _.toArray(arguments);
  this.gemini.cancel_order(order_id, function (err, data, body) {
      if (err || !data) {
        // gemini way of telling it was already cancelled..
        if(err.message === 'Order could not be cancelled.')
          return callback();

        log.error('unable to cancel order', order_id, '(', err, data, '), retrying...');
        return this.retry(this.cancelOrder, args);
      }

      return callback();
  }.bind(this));
}

Trader.prototype.getTrades = function(since, callback, descending) {
  var args = _.toArray(arguments);

  var path = this.pair;
  if(since)
    path += '?limit_trades=2000';

  this.gemini.trades(path, function(err, data) {
    if (err)
      return this.retry(this.getTrades, args);

    var trades = _.map(data, function(trade) {
      return {
        tid: trade.tid,
        date:  trade.timestamp,
        price: +trade.price,
        amount: +trade.amount
      }
    });

    callback(null, descending ? trades : trades.reverse());
  }.bind(this));
}

Trader.getCapabilities = function () {
  return {
    name: 'Gemini',
    slug: 'gemini',
    currencies: ['USD', 'BTC'],
    assets: ['BTC', 'ETH'],
    markets: [

        { pair: ['USD', 'BTC'], minimalOrder: { amount: 0.01, unit: 'asset' } },
        { pair: ['USD', 'ETC'], minimalOrder: { amount: 0.01, unit: 'asset' } },
        { pair: ['BTC', 'ETH'], minimalOrder: { amount: 0.01, unit: 'asset' } },

    ],
    requires: ['key', 'secret'],
    tid: 'tid',
    tradable: true
  };
}

module.exports = Trader;

redpajama_set_name: RedPajamaGithub


text:
=head1 LICENSE

Copyright [2009-2014] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

=head1 MODIFICATIONS

Copyright [2014-2015] University of Edinburgh

All modifications licensed under the Apache License, Version 2.0, as above.

=cut

package EnsEMBL::Web::Document::Element::FooterLinks;

### Replacement footer links for www.ensembl.org

use strict;

sub content {

## BEGIN Tardibase MODIFICATIONS...
  return qq(

      tardibase.org |
      contact us |

)
  ;
## ...END Tardibase MODIFICATIONS
}

1;


text:
package DataProviders.csvDataProviders;

import org.testng.annotations.Test;

/**
 * Created by sunny_IT on 1/31/2017.
 */
@Test
public class TestSample {

    @Test(dataProvider = "csvDataProvider", dataProviderClass = CsvDataProvider.class)
    @CsvDataSource(value = "data.csv", sourcePath = "user.dir", separator = ';')
    public void testCsv(String par1, String par2, int par3) {
        System.out.println("Hello, " + par1 + "," + par2 + "," + par3);
    }

    @Test(dataProvider = "lazyCsvDataProvider", dataProviderClass = CsvLazyDataProvider.class)
    @CsvDataSource(value = "data.csv", separator = ';')
    public void testLazyCsv(String par1, String par2, String par3) {
        System.out.println("Hello, " + par1 + "," + par2 + "," + par3);
    }
}


text:
title: Add Login to your Go web application
description: This tutorial demonstrates how to add user login to a Go web application using Auth0.
budicon: 448
topics:
  - quickstarts
  - webapp
  - login
  - golang
github:
  path: 01-Login
contentType: tutorial
useCase: quickstart
interactive: true
files:
  - files/auth
  - files/callback
  - files/env
  - files/go-mod
  - files/isAuthenticated
  - files/login
  - files/logout
  - files/main
  - files/router
  - files/user
---

# Add login to your Go application

Auth0 allows you to add authentication and gain access to user profile information in your application. This guide demonstrates how to integrate Auth0 with any new or existing Go web application.

<%= include('../../_includes/_configure_auth0_interactive', {
  callback: 'http://localhost:3000/callback',
  returnTo: 'http://localhost:3000'
}) %>

## Install dependencies {{{ data-action=code data-code="go.mod" }}}

Create a `go.mod` file to list all the dependencies in your application.

To integrate Auth0 in a Go application, add the`coreos/go-oidc/v3` and `x/oauth2` packages.

In addition to the OIDC and OAuth2 packages, add`joho/godotenv`, `gin-gonic/gin` and `gin-contrib/sessions`.

::: note
This example uses `gin` for routing, but you can use whichever router you want.
:::

Save the `go.mod` file with the necessary dependencies and install them using the following command in your terminal:

```shell
go mod download
```

## Configure the environment variables {{{ data-action=code data-code=".env" }}}
You must set the following environment variables in `.env` within the root of your project directory:

- **AUTH0_DOMAIN**: The domain of your Auth0 tenant. Find your Auth0 Domain in the Auth0 Dashboard under your Application's Settings in the Domain field. For [custom domains](https://auth0.com/docs/custom-domains), set this to the value of your custom domain instead.
- **AUTH0_CLIENT_ID**: The ID of the Auth0 Application you set up earlier in this quickstart. Find this in the Auth0 Dashboard under your Application's Settings in the Client ID field.
- **AUTH0_CLIENT_SECRET**: The Secret of the Auth0 Application you set up earlier in this quickstart. Find this in the Auth0 Dashboard under your Application's Settings in the Client Secret field.
- **AUTH0_CALLBACK_URL**: The URL used by Auth0 to redirect the user after successful authentication.

## Configure OAuth2 and OpenID Connect packages {{{ data-action=code data-code="auth.go" }}}

Next, configure the OAuth2 and OpenID Connect packages.

Create a file called `auth.go` in the `platform/authenticator` folder. In this package, create a method to
configure and return [OAuth2](https://godoc.org/golang.org/x/oauth2) and
[OIDC](https://godoc.org/github.com/coreos/go-oidc) clients, and another one to verify an ID Token.

## Set up your application routes {{{ data-action=code data-code="router.go" }}}

Create a file called `router.go` in the `platform/router` folder. In this package, create a method to configure
and return our routes using [github.com/gin-gonic/gin](https://github.com/gin-gonic/gin). You will be passing an
instance of `Authenticator` to the method, for use with the `login` and `callback` handlers.

::: note
The router uses the [github.com/gin-contrib/sessions](https://github.com/gin-contrib/sessions) middleware to manage our cookie-based sessions.
:::

## Add login to your application {{{ data-action=code data-code="login.go" }}}

For the user to authenticate themselves, we need to create a handler function to handle the `/login` route.

Create a file called `login.go` in the `web/app/login` folder, and add a `Handler` function. Upon executing the handler, the user will be redirected to Auth0 where they can enter their credentials.

To call the `/login` route, add a link to `/login` in the `home.html` template located in the `web/template` directory.

```html
<!-- Save this within ./web/template/home.html -->

<div>
    <h3>Auth0 Example</h3>
    <p>Zero friction identity infrastructure, built for developers</p>
    <a href="/login">SignIn</a>
</div>
```

## Handle authentication callback {{{ data-action=code data-code="callback.go" }}}

Once users have authenticated using Auth0's Universal Login Page, they will return to the app at the `/callback` route.

Create a file called `callback.go` in the `web/app/callback` folder, and add a `Handler` function.

This handler will take the `code` query string, provided by Auth0, and exchange it for an ID token and an access token.

If the ID token is valid, it will store the profile information and access token in the session. The profile information is based on the claims contained in the ID token. Session storage allows the application to access that information as needed.

## Display user profile information {{{ data-action=code data-code="user.go" }}}

Now that your users can log in, you will likely want to be able to retrieve and use the [profile information](/users/concepts/overview-user-profile) associated with authenticated users.

You can access that [profile information](/users/concepts/overview-user-profile), such as their nickname or profile picture, through the `profile` that was stored in the session previously.

Create a handler for the `/user` endpoint in `web/app/user/user.go` and return the corresponding HTML file. As the `profile` is being passed to `ctx.HTML()`, you can access the profile information such as `picture` and `nickname` inside that same HTML file.

An example of such an HTML file could look like the example below, but you can retrieve any [profile information](/users/concepts/overview-user-profile), including custom claims.

```html
<!-- Save this within ./web/template/user.html -->

<div>
    <img class="avatar" src="{{ .picture }}"/>
    <h2>Welcome {{.nickname}}</h2>
</div>
```

## Add logout to your application {{{ data-action=code data-code="logout.go" }}}

To log the user out, clear the data from the session and redirect the user to the Auth0 logout endpoint. You can find more information about this in the [logout documentation](/logout).

Create a file called `logout.go` in the folder `web/app/logout`, and add the function `Handler` to redirect the user to Auth0's logout endpoint.

::: note
The `returnTo` URL needs to be in the list of Allowed Logout URLs in the settings section of the application, For more information, see [Redirect Users After Logout](/logout/guides/redirect-users-after-logout).
:::

Create a file called `user.js` in the folder `web/static/js`, and add the code to remove the cookie from a logged-in
user.

```js
// Save this within ./web/static/js/user.js

$(document).ready(function () {
    $('.btn-logout').click(function (e) {
        Cookies.remove('auth-session');
    });
});
```

::: note
This sample is using [js.cookie](https://github.com/js-cookie/js-cookie/tree/latest#readme) for cookie handling.
You need to add the `js.cookie.js` file to the `web/static/js` folder to use it.
:::

## Protect routes {{{ data-action=code data-code="isAuthenticated.go" }}}

Recommended practice dictates certain routes are accessible only to authenticated users. When unauthenticated users try accessing protected routes, your application should redirect them.

In this case, you will implement middleware to hook into the HTTP request. The middleware function determines if the request should route to the endpoint handler or block the request.

Create a file called `isAuthenticated.go` in `platform/middleware` and add a function that checks if the user is authenticated or not based on the `profile` session key. If the user is not authenticated, the middleware will redirect the user to the root of the application.

With the middleware created, we can set it up for any route that needs authentication by adding it to the router.

```go
// This goes within ./platform/router/router.go

router.GET("/user", middleware.IsAuthenticated, user.Handler)
```

## Serve your application {{{ data-action=code data-code="main.go" }}}

With both the authenticator and router configured, we can wire things up using our
application's entry point. Inside `main.go`, create an instance of the authenticator and the router, which gets passed the authenticator instance.

If you are using a `.env` file, you must call `godotenv.Load()` at the very beginning of the `main()` function.

Serve your application by using the following command in your terminal:

```shell
go run main.go
```


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <bitmap android:src="@drawable/ic_play_light" android:alpha="0.87" />
    </item>
</selector>


text:
layout: post
title: "Gelfand: Chunk 15 - Polynomial Division Addendum"
tags: [gelfand, division, polynomials, geometric-progression]
comments: true
---
{% include JB/setup %}

Seeing as this is merely an addendum to [the previous post](https://andrewharmellaw.github.io/2017/02/23/gelfands-algebra-chunk-14-polynomial-division-all-the-gory-details/), let's jump straight in.

## Problems 143(a)-(c) - A Handy Shortcut
{% newthought "We'll work through the first Problem (a)" %} using the long-winded method

{% math %}
\require{enclose}
\begin{array}{rll}
   x^2  + x \phantom{000000} + 1 && \hbox{(Explanations)} \\[-3pt]
   x - 1 \enclose{longdiv}{x^3 \phantom{000000} - 1 \phantom{0000}}\kern-.2ex \\[-3pt]
      \underline{x^3 - x^2 \phantom{000000000}} && \hbox{($(x - 1) \times x^2 = x^3 - x^2$)} \\[-3pt]
      x^2 \phantom{000000} -1 && \hbox{($-1 - (-x^2) = x^2 - 1$)} \\[-3pt]
      \underline{x^2 \phantom{00} - x\phantom{0000}} && \hbox{($(x - 1)\times x = x^2 - x$)} \\[-3pt]
      x \phantom{0} - 1  && \hbox{($-1 - (-x) = x - 1$)} \\[-3pt]
      \underline{x \phantom{0} - 1} && \hbox{($(x - 1) \times 1 = x - 1$)} \\[-3pt]
      0  && \hbox{($\leftarrow$ the remainder: $-1 - (-1) = 0$)} \\[-3pt]
  \end{array}
{% endmath %}

We could now do the same for (b) and (c), but I think it's evident, even from just the above, that we'd get a pattern emerging.  Gelfand would undoubtedly be pleased that we'd spotted this, as he goes on to point out just that they have all been generic forms of a standard formula

{% math %} \frac{x^n -1}{x - 1} = x^{n-1} + x^{n-2} + \hbox{...} + x^2 + x + 1{% endmath %}

It turns out that this has a special power - it can be used to compute the sums of consecutive powers of a number {% m %}x{% em %}.  You can imagine how it would be; just flip the above standard formula round and reverse the order of the additions

{% math %} 1 + x + x^2 + \hbox{...} + x^{n-2} + x^{n-1} = \frac{x^n -1}{x - 1}{% endmath %}

The left hand side shows the long-winded way you'd have to go about this. I.e. "what are the consecutive powers of {% m %}3{% em %} up to the power of three?" you might ask.

{% math %}3^0 + 3^1 + 3^2= {% endmath %}

{% math %} = 1 + 3 + 9= {% endmath %}

{% math %} = 13{% endmath %}

But as we know the left hand side and right hand sides of this forumula are equivalent, we can get the same answer by substituting the same values into our other formula.

{% math %}\frac{3^3 - 1}{3 - 1} = \frac{26 - 1}{2} = \frac{26}{2} = 13{% endmath %}

Much quicker.

## Problem 144 - A Sneak Peek at Geometric Progressions
{% newthought "Now while this is handy," %} we're actually getting a sneak preview of something which Gelfand will later spend quite a lot of time investigating - geometric progressions - but he stops here for now.{% sidenote 'sn-id-whatever' "I don't recommend you jump ahead, but if you must, take a look at [Chunk 21 - Geometric Progressions](https://andrewharmellaw.github.io/2017/03/21/gelfands-algebra-chunk-21-geometric-progressions/), but be sure and come right back." %}

There's little for us to do other than just try substituting the number {% m %}2{% em %} for {% m %}x{% em %} and realise that what we have just been working with is the reason this progression property.


text:
package com.syncleus.ferma.tx;

import com.syncleus.ferma.FramedGraph;
import com.syncleus.ferma.WrappedTransaction;

/**
 * Adapted flavor of the {@link FramedGraph}. This interface will return a {@link Tx} instead of a {@link WrappedTransaction}. The {@link Tx} interface contains
 * some useful methods which makes it easier is some cases to work with transactions. This includes automatic rollback within the autoclosable and transaction
 * reference handling.
 */
public interface FramedTxGraph extends FramedGraph {

    /**
     * Return an active transaction or create a new transaction if no active could be found.
     */
    @Override
    default Tx tx() {
        if (Tx.getActive() != null) {
            return Tx.getActive();
        } else {
            Tx tx = createTx();
            Tx.setActive(tx);
            return tx;
        }
    }

    /**
     * Create a new transaction.
     *
     * @return new transaction.
     */
    Tx createTx();

}


text:
package fake

import (
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	labels "k8s.io/apimachinery/pkg/labels"
	schema "k8s.io/apimachinery/pkg/runtime/schema"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	testing "k8s.io/client-go/testing"
	v1beta1 "k8s.io/kubernetes/pkg/apis/extensions/v1beta1"
)

// FakePodSecurityPolicies implements PodSecurityPolicyInterface
type FakePodSecurityPolicies struct {
	Fake *FakeExtensionsV1beta1
}

var podsecuritypoliciesResource = schema.GroupVersionResource{Group: "extensions", Version: "v1beta1", Resource: "podsecuritypolicies"}

func (c *FakePodSecurityPolicies) Create(podSecurityPolicy *v1beta1.PodSecurityPolicy) (result *v1beta1.PodSecurityPolicy, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(podsecuritypoliciesResource, podSecurityPolicy), &v1beta1.PodSecurityPolicy{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.PodSecurityPolicy), err
}

func (c *FakePodSecurityPolicies) Update(podSecurityPolicy *v1beta1.PodSecurityPolicy) (result *v1beta1.PodSecurityPolicy, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootUpdateAction(podsecuritypoliciesResource, podSecurityPolicy), &v1beta1.PodSecurityPolicy{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.PodSecurityPolicy), err
}

func (c *FakePodSecurityPolicies) Delete(name string, options *v1.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(testing.NewRootDeleteAction(podsecuritypoliciesResource, name), &v1beta1.PodSecurityPolicy{})
	return err
}

func (c *FakePodSecurityPolicies) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
	action := testing.NewRootDeleteCollectionAction(podsecuritypoliciesResource, listOptions)

	_, err := c.Fake.Invokes(action, &v1beta1.PodSecurityPolicyList{})
	return err
}

func (c *FakePodSecurityPolicies) Get(name string, options v1.GetOptions) (result *v1beta1.PodSecurityPolicy, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootGetAction(podsecuritypoliciesResource, name), &v1beta1.PodSecurityPolicy{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.PodSecurityPolicy), err
}

func (c *FakePodSecurityPolicies) List(opts v1.ListOptions) (result *v1beta1.PodSecurityPolicyList, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootListAction(podsecuritypoliciesResource, opts), &v1beta1.PodSecurityPolicyList{})
	if obj == nil {
		return nil, err
	}

	label, _, _ := testing.ExtractFromListOptions(opts)
	if label == nil {
		label = labels.Everything()
	}
	list := &v1beta1.PodSecurityPolicyList{}
	for _, item := range obj.(*v1beta1.PodSecurityPolicyList).Items {
		if label.Matches(labels.Set(item.Labels)) {
			list.Items = append(list.Items, item)
		}
	}
	return list, err
}

// Watch returns a watch.Interface that watches the requested podSecurityPolicies.
func (c *FakePodSecurityPolicies) Watch(opts v1.ListOptions) (watch.Interface, error) {
	return c.Fake.
		InvokesWatch(testing.NewRootWatchAction(podsecuritypoliciesResource, opts))
}

// Patch applies the patch and returns the patched podSecurityPolicy.
func (c *FakePodSecurityPolicies) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.PodSecurityPolicy, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootPatchSubresourceAction(podsecuritypoliciesResource, name, data, subresources...), &v1beta1.PodSecurityPolicy{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.PodSecurityPolicy), err
}


text:
package org.elasticsearch.search.aggregations.bucket.range.ipv4;

import org.elasticsearch.search.aggregations.bucket.range.AbstractRangeBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilderException;

import static org.elasticsearch.index.mapper.ip.IpFieldMapper.cidrMaskToMinMax;

/**
 * Builder for the {@code IPv4Range} aggregation.
 */
public class IPv4RangeBuilder extends AbstractRangeBuilder<IPv4RangeBuilder> {

    /**
     * Sole constructor.
     */
    public IPv4RangeBuilder(String name) {
        super(name, InternalIPv4Range.TYPE.name());
    }

    /**
     * Add a new range to this aggregation.
     *
     * @param key  the key to use for this range in the response
     * @param from the lower bound on the distances, inclusive
     * @param to   the upper bound on the distances, exclusive
     */
    public IPv4RangeBuilder addRange(String key, String from, String to) {
        ranges.add(new Range(key, from, to));
        return this;
    }

    /**
     * Same as {@link #addMaskRange(String, String)} but uses the mask itself as a key.
     */
    public IPv4RangeBuilder addMaskRange(String mask) {
        return addMaskRange(mask, mask);
    }

    /**
     * Add a range based on a CIDR mask.
     */
    public IPv4RangeBuilder addMaskRange(String key, String mask) {
        long[] fromTo = cidrMaskToMinMax(mask);
        if (fromTo == null) {
            throw new SearchSourceBuilderException("invalid CIDR mask [" + mask + "] in ip_range aggregation [" + getName() + "]");
        }
        ranges.add(new Range(key, fromTo[0] < 0 ? null : fromTo[0], fromTo[1] < 0 ? null : fromTo[1]));
        return this;
    }

    /**
     * Same as {@link #addRange(String, String, String)} but the key will be
     * automatically generated.
     */
    public IPv4RangeBuilder addRange(String from, String to) {
        return addRange(null, from, to);
    }

    /**
     * Same as {@link #addRange(String, String, String)} but there will be no lower bound.
     */
    public IPv4RangeBuilder addUnboundedTo(String key, String to) {
        ranges.add(new Range(key, null, to));
        return this;
    }

    /**
     * Same as {@link #addUnboundedTo(String, String)} but the key will be
     * generated automatically.
     */
    public IPv4RangeBuilder addUnboundedTo(String to) {
        return addUnboundedTo(null, to);
    }

    /**
     * Same as {@link #addRange(String, String, String)} but there will be no upper bound.
     */
    public IPv4RangeBuilder addUnboundedFrom(String key, String from) {
        ranges.add(new Range(key, from, null));
        return this;
    }

    /**
     * Same as {@link #addUnboundedFrom(String, String)} but the key will be
     * generated automatically.
     */
    public IPv4RangeBuilder addUnboundedFrom(String from) {
        return addUnboundedFrom(null, from);
    }

}


text:
namespace ui {

class DrmDisplayHostManager;

class DrmNativeDisplayDelegate : public display::NativeDisplayDelegate {
 public:
  explicit DrmNativeDisplayDelegate(DrmDisplayHostManager* display_manager);

  DrmNativeDisplayDelegate(const DrmNativeDisplayDelegate&) = delete;
  DrmNativeDisplayDelegate& operator=(const DrmNativeDisplayDelegate&) = delete;

  ~DrmNativeDisplayDelegate() override;

  void OnConfigurationChanged();
  void OnDisplaySnapshotsInvalidated();

  // display::NativeDisplayDelegate overrides:
  void Initialize() override;
  void TakeDisplayControl(display::DisplayControlCallback callback) override;
  void RelinquishDisplayControl(
      display::DisplayControlCallback callback) override;
  void GetDisplays(display::GetDisplaysCallback callback) override;
  void Configure(
      const std::vector<display::DisplayConfigurationParams>& config_requests,
      display::ConfigureCallback callback,
      uint32_t modeset_flag) override;
  void GetHDCPState(const display::DisplaySnapshot& output,
                    display::GetHDCPStateCallback callback) override;
  void SetHDCPState(const display::DisplaySnapshot& output,
                    display::HDCPState state,
                    display::ContentProtectionMethod protection_method,
                    display::SetHDCPStateCallback callback) override;
  bool SetColorMatrix(int64_t display_id,
                      const std::vector<float>& color_matrix) override;
  bool SetGammaCorrection(
      int64_t display_id,
      const std::vector<display::GammaRampRGBEntry>& degamma_lut,
      const std::vector<display::GammaRampRGBEntry>& gamma_lut) override;
  void SetPrivacyScreen(int64_t display_id,
                        bool enabled,
                        display::SetPrivacyScreenCallback callback) override;
  void AddObserver(display::NativeDisplayObserver* observer) override;
  void RemoveObserver(display::NativeDisplayObserver* observer) override;
  display::FakeDisplayController* GetFakeDisplayController() override;

 private:
  DrmDisplayHostManager* const display_manager_;  // Not owned.

  base::ObserverList<display::NativeDisplayObserver>::Unchecked observers_;
};

}  // namespace ui

#endif  // UI_OZONE_PLATFORM_DRM_HOST_DRM_NATIVE_DISPLAY_DELEGATE_H_


text:
<img src="beatsbear.png" alt="beatsbear" width="250" height="250">

A realtime tempo adjustment application with genre classification.

[![Build Status](https://travis-ci.org/musicretrieval/BeatsBear.svg?branch=master)](https://travis-ci.org/musicretrieval/BeatsBear)

# Process
The application first loads all the music that it can find on the user's device. From there TarsosDSP was used to estimate the BPM and MFCC's of each song. Using the MFCC's as a single vector feature, I was able to train an SVM classifier with Weka. After all the songs have been read and their features applied, the application will classify the songs and apply a tag.

The BPM and genre are used as a recommendation filter, which is still under work. Currently, if the songs BPM < 130 and the song was classified as Blues, Classical, or Country, then it is considered as relaxing music. Otherwise, it is considered activiating music.

From there, you can play music and play around with the song's tempo real time.

# Build Guide

Try building and running the application, if it doesn't work, the ffmpeg library might be missing.

To run, this Android project requires the following library:
https://github.com/WritingMinds/ffmpeg-android/releases
Download `prebuilt-binaries.zip`, you will get three files:
- armeabi-v7a/ffmpeg
- armeabi-v7a-neon/ffmpeg
- x86/ffmpeg

Rename each of the `ffmpeg` to `<FOLDER_NAME>_ffmpeg` and place it in `app/build/intermediates/assets`. Your `app/build/intermediates/assets` folder should have: `armeabi-v7a_ffmpeg`, `armeabi-v7a-neon_ffmpeg`, and `x86_ffmpeg`. If that does not work, try putting it in `app/build/intermediates/assets/debug`.

If you are using Android emulator, you will want to put music in the emulator:
- Download some songs
- Use Android Device Monitor
- /storage/sdcard/Music, or a similar path
- For API 23 it should be storage/emulated/0/Music
- May need to restart emulator

Enable storage permissions:
- Settings -> Apps -> TrackMix -> Permissions -> Storage

# Troubleshooting

- You may need to use API 23, it seems that API 23+ does not work well with this project.

# Technologies
[TarsosDSP](https://github.com/JorenSix/TarsosDSP) for audio processing

[Weka](http://www.cs.waikato.ac.nz/ml/weka/) for machine learning

# References
Genre icons made by [Freepik](http://www.freepik.com) from [flaticon](http://www.flaticon.com) is licensed by [Creative Commons BY 3.0](http://creativecommons.org/licenses/by/3.0/)


text:
package org.wildfly.camel.test.security;

import javax.security.auth.Subject;

import org.apache.camel.CamelAuthorizationException;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.camel.test.security.subA.AnnotatedSLSB;
import org.wildfly.extension.camel.CamelAware;
import org.wildfly.extension.camel.CamelContextRegistry;
import org.wildfly.extension.camel.security.DomainPrincipal;
import org.wildfly.extension.camel.security.EncodedUsernamePasswordPrincipal;

@CamelAware
@RunWith(Arquillian.class)
public class AuthorizationPolicyTestCase {

    @ArquillianResource
    CamelContextRegistry contextRegistry;

    @Deployment
    public static JavaArchive createDeployment() {
        JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "authorization-policy-route-test");
        archive.addAsResource("security/authorization-policy-camel-context.xml");
        return archive;
    }

    @Test
    public void testNoAuthenticationHeader() throws Exception {
        CamelContext camelctx = contextRegistry.getCamelContext("contextA");
        ProducerTemplate producer = camelctx.createProducerTemplate();
        try {
            producer.requestBody("direct:start", "Kermit", String.class);
            Assert.fail("CamelExecutionException expected");
        } catch (CamelExecutionException ex) {
            Throwable cause = ex.getCause();
            Assert.assertEquals(CamelAuthorizationException.class, cause.getClass());
            Assert.assertTrue(cause.getMessage(), cause.getMessage().startsWith("Cannot find the Authentication instance"));
        }
    }

    @Test
    public void testInvalidCredentials() throws Exception {
        CamelContext camelctx = contextRegistry.getCamelContext("contextA");
        ProducerTemplate producer = camelctx.createProducerTemplate();
        try {
            Subject subject = getAuthenticationToken("user-domain", AnnotatedSLSB.USERNAME, "bogus");
            producer.requestBodyAndHeader("direct:start", "Kermit", Exchange.AUTHENTICATION, subject, String.class);
            Assert.fail("CamelExecutionException expected");
        } catch (CamelExecutionException ex) {
            Throwable cause = ex.getCause();
            Assert.assertEquals(CamelAuthorizationException.class, cause.getClass());
            Assert.assertTrue(cause.getMessage(), cause.getMessage().contains("Password invalid/Password required"));
        }
    }

    @Test
    public void testAuthenticatedAccess() throws Exception {
        CamelContext camelctx = contextRegistry.getCamelContext("contextA");
        ProducerTemplate producer = camelctx.createProducerTemplate();
        Subject subject = getAuthenticationToken("user-domain", AnnotatedSLSB.USERNAME, AnnotatedSLSB.PASSWORD);
        String result = producer.requestBodyAndHeader("direct:start", "Kermit", Exchange.AUTHENTICATION, subject, String.class);
        Assert.assertEquals("Hello Kermit", result);
    }

    @Test
    public void testRoleBasedAccess() throws Exception {
        CamelContext camelctx = contextRegistry.getCamelContext("contextB");
        ProducerTemplate producer = camelctx.createProducerTemplate();
        Subject subject = getAuthenticationToken("user-domain", AnnotatedSLSB.USERNAME, AnnotatedSLSB.PASSWORD);
        String result = producer.requestBodyAndHeader("direct:start", "Kermit", Exchange.AUTHENTICATION, subject, String.class);
        Assert.assertEquals("Hello Kermit", result);
    }

    @Test
    public void testInsufficientRoles() throws Exception {
        CamelContext camelctx = contextRegistry.getCamelContext("contextC");
        ProducerTemplate producer = camelctx.createProducerTemplate();
        try {
            Subject subject = getAuthenticationToken("user-domain", AnnotatedSLSB.USERNAME, AnnotatedSLSB.PASSWORD);
            producer.requestBodyAndHeader("direct:start", "Kermit", Exchange.AUTHENTICATION, subject, String.class);
            Assert.fail("CamelExecutionException expected");
        } catch (CamelExecutionException ex) {
            Throwable cause = ex.getCause();
            Assert.assertEquals(CamelAuthorizationException.class, cause.getClass());
            Assert.assertTrue(cause.getMessage(), cause.getMessage().contains("User does not have required roles: [Role3]"));
        }
    }

    Subject getAuthenticationToken(String domain, String username, String password) {
        Subject subject = new Subject();
        subject.getPrincipals().add(new DomainPrincipal(domain));
        subject.getPrincipals().add(new EncodedUsernamePasswordPrincipal(username, password.toCharArray()));
        return subject;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using EasyNetQ;
using EasyNetQ.NonGeneric;
using RabbitScalingOut.Contract;

namespace RabbitScalingOut.Producer
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var bus = RabbitHutch.CreateBus();

            string messageVersion = ConfigurationManager.AppSettings["MessageVersion"];
            int sleep = int.Parse(ConfigurationManager.AppSettings["Sleep"]);

            var stopped = false;
            var thread = new Thread(() =>
            {
                while (!stopped)
                {
                    if (messageVersion == "1")
                    {
                        bus.Publish(new MyMessage1());
                    }

                    if (messageVersion == "2")
                    {
                        bus.Publish(new MyMessage2());
                    }

                    if (!stopped) Thread.Sleep(sleep);
                }
            });
            thread.Start();

            Console.WriteLine("Press enter to exit the application...");
            Console.ReadLine();

            stopped = true;
            thread.Join();

            bus.Dispose();
        }
    }
}


text:
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/third_party/quiche/src/quic/qbone/platform/rtnetlink_message.h"

#include <net/if_arp.h>

#include "net/third_party/quiche/src/quic/platform/api/quic_ip_address.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_test.h"

namespace quic {
namespace {

using ::testing::StrEq;

TEST(RtnetlinkMessageTest, LinkMessageCanBeCreatedForGetOperation) {
  uint16_t flags = NLM_F_REQUEST | NLM_F_ROOT | NLM_F_MATCH;
  uint32_t seq = 42;
  uint32_t pid = 7;
  auto message = LinkMessage::New(RtnetlinkMessage::Operation::GET, flags, seq,
                                  pid, nullptr);

  // No rtattr appended.
  EXPECT_EQ(1, message.IoVecSize());

  // nlmsghdr is built properly.
  auto iov = message.BuildIoVec();
  EXPECT_EQ(NLMSG_SPACE(sizeof(struct rtgenmsg)), iov[0].iov_len);
  auto* netlink_message = reinterpret_cast<struct nlmsghdr*>(iov[0].iov_base);
  EXPECT_EQ(NLMSG_LENGTH(sizeof(struct rtgenmsg)), netlink_message->nlmsg_len);
  EXPECT_EQ(RTM_GETLINK, netlink_message->nlmsg_type);
  EXPECT_EQ(flags, netlink_message->nlmsg_flags);
  EXPECT_EQ(seq, netlink_message->nlmsg_seq);
  EXPECT_EQ(pid, netlink_message->nlmsg_pid);

  // We actually included rtgenmsg instead of the passed in ifinfomsg since this
  // is a GET operation.
  EXPECT_EQ(NLMSG_LENGTH(sizeof(struct rtgenmsg)), netlink_message->nlmsg_len);
}

TEST(RtnetlinkMessageTest, LinkMessageCanBeCreatedForNewOperation) {
  struct ifinfomsg interface_info_header = {AF_INET, /* pad */ 0, ARPHRD_TUNNEL,
                                            3,       0,           0xffffffff};
  uint16_t flags = NLM_F_REQUEST | NLM_F_ROOT | NLM_F_MATCH;
  uint32_t seq = 42;
  uint32_t pid = 7;
  auto message = LinkMessage::New(RtnetlinkMessage::Operation::NEW, flags, seq,
                                  pid, &interface_info_header);

  std::string device_name = "device0";
  message.AppendAttribute(IFLA_IFNAME, device_name.c_str(), device_name.size());

  // One rtattr appended.
  EXPECT_EQ(2, message.IoVecSize());

  // nlmsghdr is built properly.
  auto iov = message.BuildIoVec();
  EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct ifinfomsg))),
            iov[0].iov_len);
  auto* netlink_message = reinterpret_cast<struct nlmsghdr*>(iov[0].iov_base);
  EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct ifinfomsg))) +
                RTA_LENGTH(device_name.size()),
            netlink_message->nlmsg_len);
  EXPECT_EQ(RTM_NEWLINK, netlink_message->nlmsg_type);
  EXPECT_EQ(flags, netlink_message->nlmsg_flags);
  EXPECT_EQ(seq, netlink_message->nlmsg_seq);
  EXPECT_EQ(pid, netlink_message->nlmsg_pid);

  // ifinfomsg is included properly.
  auto* parsed_header =
      reinterpret_cast<struct ifinfomsg*>(NLMSG_DATA(netlink_message));
  EXPECT_EQ(interface_info_header.ifi_family, parsed_header->ifi_family);
  EXPECT_EQ(interface_info_header.ifi_type, parsed_header->ifi_type);
  EXPECT_EQ(interface_info_header.ifi_index, parsed_header->ifi_index);
  EXPECT_EQ(interface_info_header.ifi_flags, parsed_header->ifi_flags);
  EXPECT_EQ(interface_info_header.ifi_change, parsed_header->ifi_change);

  // rtattr is handled properly.
  EXPECT_EQ(RTA_SPACE(device_name.size()), iov[1].iov_len);
  auto* rta = reinterpret_cast<struct rtattr*>(iov[1].iov_base);
  EXPECT_EQ(IFLA_IFNAME, rta->rta_type);
  EXPECT_EQ(RTA_LENGTH(device_name.size()), rta->rta_len);
  EXPECT_THAT(device_name,
              StrEq(std::string(reinterpret_cast<char*>(RTA_DATA(rta)),
                                RTA_PAYLOAD(rta))));
}

TEST(RtnetlinkMessageTest, AddressMessageCanBeCreatedForGetOperation) {
  uint16_t flags = NLM_F_REQUEST | NLM_F_ROOT | NLM_F_MATCH;
  uint32_t seq = 42;
  uint32_t pid = 7;
  auto message = AddressMessage::New(RtnetlinkMessage::Operation::GET, flags,
                                     seq, pid, nullptr);

  // No rtattr appended.
  EXPECT_EQ(1, message.IoVecSize());

  // nlmsghdr is built properly.
  auto iov = message.BuildIoVec();
  EXPECT_EQ(NLMSG_SPACE(sizeof(struct rtgenmsg)), iov[0].iov_len);
  auto* netlink_message = reinterpret_cast<struct nlmsghdr*>(iov[0].iov_base);
  EXPECT_EQ(NLMSG_LENGTH(sizeof(struct rtgenmsg)), netlink_message->nlmsg_len);
  EXPECT_EQ(RTM_GETADDR, netlink_message->nlmsg_type);
  EXPECT_EQ(flags, netlink_message->nlmsg_flags);
  EXPECT_EQ(seq, netlink_message->nlmsg_seq);
  EXPECT_EQ(pid, netlink_message->nlmsg_pid);

  // We actually included rtgenmsg instead of the passed in ifinfomsg since this
  // is a GET operation.
  EXPECT_EQ(NLMSG_LENGTH(sizeof(struct rtgenmsg)), netlink_message->nlmsg_len);
}

TEST(RtnetlinkMessageTest, AddressMessageCanBeCreatedForNewOperation) {
  struct ifaddrmsg interface_address_header = {AF_INET,
                                               /* prefixlen */ 24,
                                               /* flags */ 0,
                                               /* scope */ RT_SCOPE_LINK,
                                               /* index */ 4};
  uint16_t flags = NLM_F_REQUEST | NLM_F_ROOT | NLM_F_MATCH;
  uint32_t seq = 42;
  uint32_t pid = 7;
  auto message = AddressMessage::New(RtnetlinkMessage::Operation::NEW, flags,
                                     seq, pid, &interface_address_header);

  QuicIpAddress ip;
  CHECK(ip.FromString("10.0.100.3"));
  message.AppendAttribute(IFA_ADDRESS, ip.ToPackedString().c_str(),
                          ip.ToPackedString().size());

  // One rtattr is appended.
  EXPECT_EQ(2, message.IoVecSize());

  // nlmsghdr is built properly.
  auto iov = message.BuildIoVec();
  EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct ifaddrmsg))),
            iov[0].iov_len);
  auto* netlink_message = reinterpret_cast<struct nlmsghdr*>(iov[0].iov_base);
  EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct ifaddrmsg))) +
                RTA_LENGTH(ip.ToPackedString().size()),
            netlink_message->nlmsg_len);
  EXPECT_EQ(RTM_NEWADDR, netlink_message->nlmsg_type);
  EXPECT_EQ(flags, netlink_message->nlmsg_flags);
  EXPECT_EQ(seq, netlink_message->nlmsg_seq);
  EXPECT_EQ(pid, netlink_message->nlmsg_pid);

  // ifaddrmsg is included properly.
  auto* parsed_header =
      reinterpret_cast<struct ifaddrmsg*>(NLMSG_DATA(netlink_message));
  EXPECT_EQ(interface_address_header.ifa_family, parsed_header->ifa_family);
  EXPECT_EQ(interface_address_header.ifa_prefixlen,
            parsed_header->ifa_prefixlen);
  EXPECT_EQ(interface_address_header.ifa_flags, parsed_header->ifa_flags);
  EXPECT_EQ(interface_address_header.ifa_scope, parsed_header->ifa_scope);
  EXPECT_EQ(interface_address_header.ifa_index, parsed_header->ifa_index);

  // rtattr is handled properly.
  EXPECT_EQ(RTA_SPACE(ip.ToPackedString().size()), iov[1].iov_len);
  auto* rta = reinterpret_cast<struct rtattr*>(iov[1].iov_base);
  EXPECT_EQ(IFA_ADDRESS, rta->rta_type);
  EXPECT_EQ(RTA_LENGTH(ip.ToPackedString().size()), rta->rta_len);
  EXPECT_THAT(ip.ToPackedString(),
              StrEq(std::string(reinterpret_cast<char*>(RTA_DATA(rta)),
                                RTA_PAYLOAD(rta))));
}

TEST(RtnetlinkMessageTest, RouteMessageCanBeCreatedFromNewOperation) {
  struct rtmsg route_message_header = {AF_INET6,
                                       /* rtm_dst_len */ 48,
                                       /* rtm_src_len */ 0,
                                       /* rtm_tos */ 0,
                                       /* rtm_table */ RT_TABLE_MAIN,
                                       /* rtm_protocol */ RTPROT_STATIC,
                                       /* rtm_scope */ RT_SCOPE_LINK,
                                       /* rtm_type */ RTN_LOCAL,
                                       /* rtm_flags */ 0};
  uint16_t flags = NLM_F_REQUEST | NLM_F_ROOT | NLM_F_MATCH;
  uint32_t seq = 42;
  uint32_t pid = 7;
  auto message = RouteMessage::New(RtnetlinkMessage::Operation::NEW, flags, seq,
                                   pid, &route_message_header);

  QuicIpAddress preferred_source;
  CHECK(preferred_source.FromString("ff80::1"));
  message.AppendAttribute(RTA_PREFSRC,
                          preferred_source.ToPackedString().c_str(),
                          preferred_source.ToPackedString().size());

  // One rtattr is appended.
  EXPECT_EQ(2, message.IoVecSize());

  // nlmsghdr is built properly
  auto iov = message.BuildIoVec();
  EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct rtmsg))), iov[0].iov_len);
  auto* netlink_message = reinterpret_cast<struct nlmsghdr*>(iov[0].iov_base);
  EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct rtmsg))) +
                RTA_LENGTH(preferred_source.ToPackedString().size()),
            netlink_message->nlmsg_len);
  EXPECT_EQ(RTM_NEWROUTE, netlink_message->nlmsg_type);
  EXPECT_EQ(flags, netlink_message->nlmsg_flags);
  EXPECT_EQ(seq, netlink_message->nlmsg_seq);
  EXPECT_EQ(pid, netlink_message->nlmsg_pid);

  // rtmsg is included properly.
  auto* parsed_header =
      reinterpret_cast<struct rtmsg*>(NLMSG_DATA(netlink_message));
  EXPECT_EQ(route_message_header.rtm_family, parsed_header->rtm_family);
  EXPECT_EQ(route_message_header.rtm_dst_len, parsed_header->rtm_dst_len);
  EXPECT_EQ(route_message_header.rtm_src_len, parsed_header->rtm_src_len);
  EXPECT_EQ(route_message_header.rtm_tos, parsed_header->rtm_tos);
  EXPECT_EQ(route_message_header.rtm_table, parsed_header->rtm_table);
  EXPECT_EQ(route_message_header.rtm_protocol, parsed_header->rtm_protocol);
  EXPECT_EQ(route_message_header.rtm_scope, parsed_header->rtm_scope);
  EXPECT_EQ(route_message_header.rtm_type, parsed_header->rtm_type);
  EXPECT_EQ(route_message_header.rtm_flags, parsed_header->rtm_flags);

  // rtattr is handled properly.
  EXPECT_EQ(RTA_SPACE(preferred_source.ToPackedString().size()),
            iov[1].iov_len);
  auto* rta = reinterpret_cast<struct rtattr*>(iov[1].iov_base);
  EXPECT_EQ(RTA_PREFSRC, rta->rta_type);
  EXPECT_EQ(RTA_LENGTH(preferred_source.ToPackedString().size()), rta->rta_len);
  EXPECT_THAT(preferred_source.ToPackedString(),
              StrEq(std::string(reinterpret_cast<char*>(RTA_DATA(rta)),
                                RTA_PAYLOAD(rta))));
}

}  // namespace
}  // namespace quic


text:
/*
 PubSubClient.cpp - A simple client for MQTT.
  Nicholas O'Leary
  http://knolleary.net
*/

#include "PubSubClient.h"
#include <string.h>

PubSubClient::PubSubClient() {
   this->_client = NULL;
   this->stream = NULL;
}

PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, void (*callback)(char*,uint8_t*,unsigned int), Client& client) {
   this->_client = &client;
   this->callback = callback;
   this->ip = ip;
   this->port = port;
   this->domain = NULL;
   this->stream = NULL;
}

PubSubClient::PubSubClient(char* domain, uint16_t port, void (*callback)(char*,uint8_t*,unsigned int), Client& client) {
   this->_client = &client;
   this->callback = callback;
   this->domain = domain;
   this->port = port;
   this->stream = NULL;
}

PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, void (*callback)(char*,uint8_t*,unsigned int), Client& client, Stream& stream) {
   this->_client = &client;
   this->callback = callback;
   this->ip = ip;
   this->port = port;
   this->domain = NULL;
   this->stream = &stream;
}

PubSubClient::PubSubClient(char* domain, uint16_t port, void (*callback)(char*,uint8_t*,unsigned int), Client& client, Stream& stream) {
   this->_client = &client;
   this->callback = callback;
   this->domain = domain;
   this->port = port;
   this->stream = &stream;
}

boolean PubSubClient::connect(char *id) {
   return connect(id,NULL,NULL,0,0,0,0);
}

boolean PubSubClient::connect(char *id, char *user, char *pass) {
   return connect(id,user,pass,0,0,0,0);
}

boolean PubSubClient::connect(char *id, char* willTopic, uint8_t willQos, uint8_t willRetain, char* willMessage)
{
   return connect(id,NULL,NULL,willTopic,willQos,willRetain,willMessage);
}

boolean PubSubClient::connect(char *id, char *user, char *pass, char* willTopic, uint8_t willQos, uint8_t willRetain, char* willMessage) {
   if (!connected()) {
      int result = 0;

      if (domain != NULL) {
        result = _client->connect(this->domain, this->port);
      } else {
        result = _client->connect(this->ip, this->port);
      }

      if (result) {
         nextMsgId = 1;
         uint8_t d[9] = {0x00,0x06,'M','Q','I','s','d','p',MQTTPROTOCOLVERSION};
         // Leave room in the buffer for header and variable length field
         uint16_t length = 5;
         unsigned int j;
         for (j = 0;j<9;j++) {
            buffer[length++] = d[j];
         }

         uint8_t v;
         if (willTopic) {
            v = 0x06|(willQos<<3)|(willRetain<<5);
         } else {
            v = 0x02;
         }

         if(user != NULL) {
            v = v|0x80;

            if(pass != NULL) {
               v = v|(0x80>>1);
            }
         }

         buffer[length++] = v;

         buffer[length++] = ((MQTT_KEEPALIVE) >> 8);
         buffer[length++] = ((MQTT_KEEPALIVE) & 0xFF);
         length = writeString(id,buffer,length);
         if (willTopic) {
            length = writeString(willTopic,buffer,length);
            length = writeString(willMessage,buffer,length);
         }

         if(user != NULL) {
            length = writeString(user,buffer,length);
            if(pass != NULL) {
               length = writeString(pass,buffer,length);
            }
         }

         write(MQTTCONNECT,buffer,length-5);

         lastInActivity = lastOutActivity = millis();

         while (!_client->available()) {
            unsigned long t = millis();
            if (t-lastInActivity > MQTT_KEEPALIVE*1000UL) {
               _client->stop();
               return false;
            }
         }
         uint8_t llen;
         uint16_t len = readPacket(&llen);

         if (len == 4 && buffer[3] == 0) {
            lastInActivity = millis();
            pingOutstanding = false;
            return true;
         }
      }
      _client->stop();
   }
   return false;
}

uint8_t PubSubClient::readByte() {
   while(!_client->available()) {}
   return _client->read();
}

uint16_t PubSubClient::readPacket(uint8_t* lengthLength) {
   uint16_t len = 0;
   buffer[len++] = readByte();
   bool isPublish = (buffer[0]&0xF0) == MQTTPUBLISH;
   uint32_t multiplier = 1;
   uint16_t length = 0;
   uint8_t digit = 0;
   uint16_t skip = 0;
   uint8_t start = 0;

   do {
      digit = readByte();
      buffer[len++] = digit;
      length += (digit & 127) * multiplier;
      multiplier *= 128;
   } while ((digit & 128) != 0);
   *lengthLength = len-1;

   if (isPublish) {
      // Read in topic length to calculate bytes to skip over for Stream writing
      buffer[len++] = readByte();
      buffer[len++] = readByte();
      skip = (buffer[*lengthLength+1]<<8)+buffer[*lengthLength+2];
      start = 2;
      if (buffer[0]&MQTTQOS1) {
         // skip message id
         skip += 2;
      }
   }

   for (uint16_t i = start;i<length;i++) {
      digit = readByte();
      if (this->stream) {
         if (isPublish && len-*lengthLength-2>skip) {
             this->stream->write(digit);
         }
      }
      if (len < MQTT_MAX_PACKET_SIZE) {
         buffer[len] = digit;
      }
      len++;
   }

   if (!this->stream && len > MQTT_MAX_PACKET_SIZE) {
       len = 0; // This will cause the packet to be ignored.
   }

   return len;
}

boolean PubSubClient::loop() {
   if (connected()) {
      unsigned long t = millis();
      if ((t - lastInActivity > MQTT_KEEPALIVE*1000UL) || (t - lastOutActivity > MQTT_KEEPALIVE*1000UL)) {
         if (pingOutstanding) {
            _client->stop();
            return false;
         } else {
            buffer[0] = MQTTPINGREQ;
            buffer[1] = 0;
            _client->write(buffer,2);
            lastOutActivity = t;
            lastInActivity = t;
            pingOutstanding = true;
         }
      }
      if (_client->available()) {
         uint8_t llen;
         uint16_t len = readPacket(&llen);
         uint16_t msgId = 0;
         uint8_t *payload;
         if (len > 0) {
            lastInActivity = t;
            uint8_t type = buffer[0]&0xF0;
            if (type == MQTTPUBLISH) {
               if (callback) {
                  uint16_t tl = (buffer[llen+1]<<8)+buffer[llen+2];
                  char topic[tl+1];
                  for (uint16_t i=0;i<tl;i++) {
                     topic[i] = buffer[llen+3+i];
                  }
                  topic[tl] = 0;
                  // msgId only present for QOS>0
                  if ((buffer[0]&0x06) == MQTTQOS1) {
                    msgId = (buffer[llen+3+tl]<<8)+buffer[llen+3+tl+1];
                    payload = buffer+llen+3+tl+2;
                    callback(topic,payload,len-llen-3-tl-2);

                    buffer[0] = MQTTPUBACK;
                    buffer[1] = 2;
                    buffer[2] = (msgId >> 8);
                    buffer[3] = (msgId & 0xFF);
                    _client->write(buffer,4);
                    lastOutActivity = t;

                  } else {
                    payload = buffer+llen+3+tl;
                    callback(topic,payload,len-llen-3-tl);
                  }
               }
            } else if (type == MQTTPINGREQ) {
               buffer[0] = MQTTPINGRESP;
               buffer[1] = 0;
               _client->write(buffer,2);
            } else if (type == MQTTPINGRESP) {
               pingOutstanding = false;
            }
         }
      }
      return true;
   }
   return false;
}

boolean PubSubClient::publish(char* topic, char* payload) {
   return publish(topic,(uint8_t*)payload,strlen(payload),false);
}

boolean PubSubClient::publish(char* topic, uint8_t* payload, unsigned int plength) {
   return publish(topic, payload, plength, false);
}

boolean PubSubClient::publish(char* topic, uint8_t* payload, unsigned int plength, boolean retained) {
   if (connected()) {
      // Leave room in the buffer for header and variable length field
      uint16_t length = 5;
      length = writeString(topic,buffer,length);
      uint16_t i;
      for (i=0;i<plength;i++) {
         buffer[length++] = payload[i];
      }
      uint8_t header = MQTTPUBLISH;
      if (retained) {
         header |= 1;
      }
      return write(header,buffer,length-5);
   }
   return false;
}

boolean PubSubClient::publish_P(char* topic, uint8_t* PROGMEM payload, unsigned int plength, boolean retained) {
   uint8_t llen = 0;
   uint8_t digit;
   unsigned int rc = 0;
   uint16_t tlen;
   unsigned int pos = 0;
   unsigned int i;
   uint8_t header;
   unsigned int len;

   if (!connected()) {
      return false;
   }

   tlen = strlen(topic);

   header = MQTTPUBLISH;
   if (retained) {
      header |= 1;
   }
   buffer[pos++] = header;
   len = plength + 2 + tlen;
   do {
      digit = len % 128;
      len = len / 128;
      if (len > 0) {
         digit |= 0x80;
      }
      buffer[pos++] = digit;
      llen++;
   } while(len>0);

   pos = writeString(topic,buffer,pos);

   rc += _client->write(buffer,pos);

   for (i=0;i<plength;i++) {
      rc += _client->write((char)pgm_read_byte_near(payload + i));
   }

   lastOutActivity = millis();

   return rc == tlen + 4 + plength;
}

boolean PubSubClient::write(uint8_t header, uint8_t* buf, uint16_t length) {
   uint8_t lenBuf[4];
   uint8_t llen = 0;
   uint8_t digit;
   uint8_t pos = 0;
   uint8_t rc;
   uint8_t len = length;
   do {
      digit = len % 128;
      len = len / 128;
      if (len > 0) {
         digit |= 0x80;
      }
      lenBuf[pos++] = digit;
      llen++;
   } while(len>0);

   buf[4-llen] = header;
   for (int i=0;i<llen;i++) {
      buf[5-llen+i] = lenBuf[i];
   }
   rc = _client->write(buf+(4-llen),length+1+llen);

   lastOutActivity = millis();
   return (rc == 1+llen+length);
}

boolean PubSubClient::subscribe(char* topic) {
  return subscribe(topic, 0);
}

boolean PubSubClient::subscribe(char* topic, uint8_t qos) {
   if (qos < 0 || qos > 1)
     return false;

   if (connected()) {
      // Leave room in the buffer for header and variable length field
      uint16_t length = 5;
      nextMsgId++;
      if (nextMsgId == 0) {
         nextMsgId = 1;
      }
      buffer[length++] = (nextMsgId >> 8);
      buffer[length++] = (nextMsgId & 0xFF);
      length = writeString(topic, buffer,length);
      buffer[length++] = qos;
      return write(MQTTSUBSCRIBE|MQTTQOS1,buffer,length-5);
   }
   return false;
}

boolean PubSubClient::unsubscribe(char* topic) {
   if (connected()) {
      uint16_t length = 5;
      nextMsgId++;
      if (nextMsgId == 0) {
         nextMsgId = 1;
      }
      buffer[length++] = (nextMsgId >> 8);
      buffer[length++] = (nextMsgId & 0xFF);
      length = writeString(topic, buffer,length);
      return write(MQTTUNSUBSCRIBE|MQTTQOS1,buffer,length-5);
   }
   return false;
}

void PubSubClient::disconnect() {
   buffer[0] = MQTTDISCONNECT;
   buffer[1] = 0;
   _client->write(buffer,2);
   _client->stop();
   lastInActivity = lastOutActivity = millis();
}

uint16_t PubSubClient::writeString(char* string, uint8_t* buf, uint16_t pos) {
   char* idp = string;
   uint16_t i = 0;
   pos += 2;
   while (*idp) {
      buf[pos++] = *idp++;
      i++;
   }
   buf[pos-i-2] = (i >> 8);
   buf[pos-i-1] = (i & 0xFF);
   return pos;
}

boolean PubSubClient::connected() {
   boolean rc;
   if (_client == NULL ) {
      rc = false;
   } else {
      rc = (int)_client->connected();
      println("Eugene :: ");
      printlln(rc);
      if (!rc) _client->stop();
   }
   return rc;
}


text:
import fs from 'fs'
import path from 'path'
import Layout from '../../../components/layout'

const Post = ({ blogpost }) => {
  if (!blogpost) return
not found

  const { html, attributes } = blogpost

  return (
    <Layout>

{attributes.title}

    </Layout>
  )
}

export async function getStaticPaths() {
  const paths = fs
    .readdirSync(path.join(process.cwd(), 'content/blogPosts'))
    .map((blogName) => {
      const trimmedName = blogName.substring(0, blogName.length - 3)
      return {
        params: { slug: trimmedName },
      }
    })

  return {
    paths,
    fallback: false, // constrols whether not predefined paths should be processed on demand, check for more info: https://nextjs.org/docs/basic-features/data-fetching#the-fallback-key-required
  }
}

export async function getStaticProps({ params }) {
  const { slug } = params

  const blogpost = await import(`../../../content/blogPosts/${slug}.md`).catch(
    () => null
  )

  return {
    props: {
      blogpost: blogpost.default,
    },
  }
}

export default Post


text:
var FetchById = require('./fetchById.js');

class PostsById extends FetchById {

  getIdQuery(id) {
    return this.wp.posts().id(id);
  }

  getReturnPath(id, key) {
    return (typeof key !== 'undefined') ? ['postsById', id, key] : ['postsById', id];
  }

  getCachedPath(id) {
    return `postsById[${id}]`;
  }

  getReferenceKeys() {
    return {
      author: (id, value) => `authorsById[${value}]`,
      featured_media: (id, value) => `mediaById[${value}]`,
      terms: (id, value) => `termsByPost[${id}]`
    };
  }
}

export default PostsById;


text:
'use strict';

export default link => (
  process.env.NODE_ENV === 'production' ?
    /* istanbul ignore next */ link :
    `/hsuting.github.io${link}`
);


text:
package datareq

import (
	"strconv"

	"github.com/apache/incubator-trafficcontrol/traffic_monitor_golang/traffic_monitor/enum"
	"github.com/apache/incubator-trafficcontrol/traffic_monitor_golang/traffic_monitor/peer"
	"github.com/apache/incubator-trafficcontrol/traffic_monitor_golang/traffic_monitor/threadsafe"
	to "github.com/apache/incubator-trafficcontrol/traffic_ops/client"
)

func srvAPICacheDownCount(localStates peer.CRStatesThreadsafe, monitorConfig threadsafe.TrafficMonitorConfigMap) []byte {
	return []byte(strconv.Itoa(cacheDownCount(localStates.Get().Caches, monitorConfig.Get().TrafficServer)))
}

// cacheOfflineCount returns the total reported caches marked down, excluding status offline and admin_down.
func cacheDownCount(caches map[enum.CacheName]peer.IsAvailable, toServers map[string]to.TrafficServer) int {
	count := 0
	for cache, available := range caches {
		if !available.IsAvailable && enum.CacheStatusFromString(toServers[string(cache)].Status) == enum.CacheStatusReported {
			count++
		}
	}
	return count
}


text:
#ifndef __VOSD_ALSA_ALSA_CARD_H__
#define __VOSD_ALSA_ALSA_CARD_H__

#include <map>

#include "alsa_mixer.h"

namespace VOsd {

	typedef std::map<std::string, AlsaMixer*> MixerList;

	class AlsaCard {
	public:
		AlsaCard(int pCardNum);
		~AlsaCard(void);

		bool                    Init(void);
		int                     CardId(void) const;
		const std::string&      Name(void) const;
		const std::string&      Error(void) const;;
		void                    Dump(void) const;
		AlsaMixer*				Mixer(const std::string& pMixerName);
	private:
		std::string             mError;
		std::string             mName;
		int                     mCardNum;
		snd_mixer_t*            mMixerHandle;
		MixerList				mMixers;
	};

} // End Namespace

#endif // __VOSD_ALSA_ALSA_CARD_H__


text:
<?php

/** Zend_Pdf_Filter_Compression */
require_once 'Zend/Pdf/Filter/Compression.php';

/**
 * Flate stream filter
 *
 * @package    Zend_Pdf
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Filter_Compression_Flate extends Zend_Pdf_Filter_Compression
{
    /**
     * Encode data
     *
     * @param string $data
     * @param array $params
     * @return string
     * @throws Zend_Pdf_Exception
     */
    public static function encode($data, $params = null)
    {
        if ($params != null) {
            $data = self::_applyEncodeParams($data, $params);
        }

        if (extension_loaded('zlib')) {
            $trackErrors = ini_get( "track_errors");
            ini_set('track_errors', '1');

            if (($output = @gzcompress($data)) === false) {
                ini_set('track_errors', $trackErrors);
                require_once 'Zend/Pdf/Exception.php';
                throw new Zend_Pdf_Exception($php_errormsg);
            }

            ini_set('track_errors', $trackErrors);
        } else {
            require_once 'Zend/Pdf/Exception.php';
            throw new Zend_Pdf_Exception('Not implemented yet. You have to use zlib extension.');
        }

        return $output;
    }

    /**
     * Decode data
     *
     * @param string $data
     * @param array $params
     * @return string
     * @throws Zend_Pdf_Exception
     */
    public static function decode($data, $params = null)
    {
        global $php_errormsg;

        if (extension_loaded('zlib')) {
            $trackErrors = ini_get( "track_errors");
            ini_set('track_errors', '1');

            if (($output = @gzuncompress($data)) === false) {
                ini_set('track_errors', $trackErrors);
                require_once 'Zend/Pdf/Exception.php';
                throw new Zend_Pdf_Exception($php_errormsg);
            }

            ini_set('track_errors', $trackErrors);
        } else {
            require_once 'Zend/Pdf/Exception.php';
            throw new Zend_Pdf_Exception('Not implemented yet');
        }

        if ($params !== null) {
            return self::_applyDecodeParams($output, $params);
        } else {
            return $output;
        }
    }
}


text:
.. _integrator_mobile:

Mobile Applications
===================

Any c2cgeoportal projet created with the ``c2cgeoportal_create`` and
``c2cgeoportal_update`` scaffolds comes with a `Sencha Touch
<http://www.sencha.com/products/touch/>`_ based mobile application.

The mobile application is available at the URLs ``/mobile_dev/`` and
``/mobile/``. Do not forget the trailing slash! The first URL should be used
during development, as non-minified resources are used. The second URL is for
production.

This application includes the following features:

* Map with zoom buttons.
* Geolocation.
* Base layer selector.
* Overlay selector.
* Text search.
* Map queries (long-press on the map).

Current limitations:

* The overlays only are queryable.
* Non-WMS overlays are not supported.
* For map queries it is assumed that there a 1:1 relationship between WMS
  layers and WFS feature types, which is not the case if a WMS layer is
  actually a group in the mapfile.

For map queries (long-press) to work a `specific OpenLayers commit
<https://github.com/openlayers/openlayers/commit/f5aae88a3141dc94863791e500253b8a89ccd7ce>`_
is required. Commit `444ba16
<https://github.com/camptocamp/cgxp/commit/444ba161fa67cdb503479da12dda71a82a70f310>`_
of CGXP includes this OpenLayers commit. So make sure your c2cgeoportal
application uses this commit (or better) of CGXP.

Infrastructure
--------------

Creating and building a mobile application requires the `Sencha Cmd
<http://www.sencha.com/products/sencha-cmd/download/>`_ tools and `Compass
<http://compass-style.org/>`_ to be installed on the target machine.

On Camptocamp server we just need the Debian packages ``sencha-cmd``
and ``ruby-compass`` (The ``sencha-cmd`` package was created by
the Camptocamp sysadmins).

On Camptocamp servers, in case you have both ``sencha-sdk-tools`` and
``sencha-cmd`` installed, commands are named respectively ``sencha-sdk``
and ``sencha-cmd``. By default the ``sencha-cmd`` command is used, if
it's not the case on your host put the following configuration variables
in your `<package>.mk` file:

.. code:: make

    SENCHA_CMD = <sencha-command>

Replace ``<sencha-command>`` by ``sencha-sdk`` if you want to build the
mobile app using a version of GeoMapFish older than 1.4.

Adding mobile routes and views
------------------------------

The last step involves adding *routes* and *views* specific to the mobile
application. Edit the project's ``__init__.py`` file and add the following
lines before the ``main`` function's return statement:

.. code:: javascript

    # mobile views and routes
    config.add_route('mobile_index_dev', '/mobile_dev/')
    config.add_view('c2cgeoportal.views.entry.Entry',
                    attr='mobile',
                    renderer='<package>:static/mobile/index.html',
                    route_name='mobile_index_dev')
    config.add_route('mobile_config_dev', '/mobile_dev/config.js')
    config.add_view('c2cgeoportal.views.entry.Entry',
                    attr='mobileconfig',
                    renderer='<package>:static/mobile/config.js',
                    route_name='mobile_config_dev')
    config.add_static_view('mobile_dev', '<package>:static/mobile')

    config.add_route('mobile_index_prod', '/mobile/')
    config.add_view('c2cgeoportal.views.entry.Entry',
                    attr='mobile',
                    renderer='<package>:static/mobile/build/production/App/index.html',
                    route_name='mobile_index_prod')
    config.add_route('mobile_config_prod', '/mobile/config.js')
    config.add_view('c2cgeoportal.views.entry.Entry',
                    attr='mobileconfig',
                    renderer='<package>:static/mobile/build/production/App/config.js',
                    route_name='mobile_config_prod')
    config.add_static_view('mobile', '<package>:static/mobile/build/production/App')

Replace ``<package>`` with the project's actual package name.

Now switch to the next section.

Building the mobile application
-------------------------------

The ``CONST_Makefile`` file includes the part ``sencha-touch`` and
``mobile`` that are dedicated to building the mobile application.

For the ``mobile`` part to work Sencha SDK Tools and Compass should be
installed on the build machine. (See above.)

.. note::

    On Windows you will need to override the values of the ``mobile`` part
    ``SENCHA_CMD`` variables as such:

    .. code:: make

        SENCHA_CMD = sencha.bat

    You would add this in ``<package>.mk``, or any make configuration file
    that extends ``<package>.mk``.

Once built the mobile application should be available on ``/mobile_dev/`` and
``/mobile/`` in the browser, where ``/`` is the root of the WSGI application.

Configuring the map and the layers
----------------------------------

To change the map configuration and the layers for the mobile application edit
the project's ``static/mobile/config.js`` and modify the config object passed
to the ``OpenLayers.Map`` constructor. The execution of the ``config.js``
script should result in ``App.map`` being set to an ``OpenLayers.Map``
instance.

Theme
~~~~~

The list of themes and layers shown in the mobile application is dynamically
generated. See :ref:`administrator_guide`.

UI strings translations
-----------------------

The overlay selector uses the layer names (as defined in the ``allLayers``
array of overlays) as translation keys. To add your translations edit
``static/mobile/config.js`` and populate the ``OpenLayers.Lang.`` objects
as necessary.

Raster service
--------------

When querying the map (longpress), the c2cgeoportal ``raster`` service can be
used to retrieve data from raster file (elevation, slope, etc...) and display
it in the ``Query view`` above query results.

If the raster service is already configured on the server, you can activate it
in the mobile application by adding the following to the config.js file::

    App.raster = true;

You'll also need to add a template string to each translation object. It needs
to be adapted to the data retrieved from the server:

.. code:: javascript

    OpenLayers.Lang.fr = {
        [...]
        'rasterTpl': [
            '
',
                '
X : {x} - Y : {y}
',
                '
Altitude terrain : {mnt} m
',
                '
Altitude surface : {mns} m
',
            '
'
        ].join(''),
        [...]
    };

In the example above ``mns`` and ``mnt`` are the keys used in the server
config for the ``raster web services``.

Settings view
-------------

The ``Settings`` view, located in ``app/view/Settings.js``, can be customized
to suit the project needs. The ``Settings.js`` file is part of c2cgeoportal's
``c2cgeoportal_create`` scaffold, it will therefore not be overwritten when
applying the ``c2cgeoportal_update`` scaffold during an update of c2cgeoportal.

If style customization is also required for components in this view, use the
``custom.scss`` file.

Permalink
~~~~~~~~~

If a permalink field is needed, just add the following component in the
Settings view:

.. code:: javascript

    { xtype: 'map_permalink' }

Login/logout
~~~~~~~~~~~~

The mobile application includes a ``Login`` view component that the
``Settings`` view can include as one of its items. This component enables login
and logout. If the user is not authenticated the ``Login`` component adds
a "log in" button, that, when clicked, redirects the user to a login form view.
If the user is authenticated the ``Login`` component adds a welcome message,
and a "log out" button.

Here's an example of a ``Settings`` view that includes a ``Login`` view
component:

.. code:: javascript

    Ext.define("App.view.Settings", {
        extend: 'Ext.Container',
        xtype: 'settingsview',
        requires: [
            // Do not forget this requirement, or Sencha Touch
            // will complain that "widget.login" is an
            // unrecognized alias.
            'App.view.Login'
        ],
        config: {
            items: [{
                xtype: 'toolbar',
                docked: 'top',
                items: [{
                    xtype: 'spacer'
                }, {
                    xtype: 'button',
                    iconCls: 'home',
                    iconMask: true,
                    action: 'home'
                }]
            }, {
                xtype: 'container',
                cls: 'settings',
                items: [{
                    xtype: 'component',
                    html: '
Some text
'
                }, {
                    // This is the login view component.
                    xtype: 'login'
                }]
            }]
        }
    });

The i18n keys relative to the login/logout functionality are: ``welcomeText``,
``loginLabel``, ``passwordLabel``, ``loginSubmitButtonText``, and
``loginCancelButtonText``. The last four pertain to the login form, they should
be self-explanatory. ``welcomeText`` is the text displayed above the "log out"
button when the user is authenticated, it typically includes the variable
``{username}``, which is changed to the actual username at render time. By
default, ``config.js`` includes the following english translations:

.. code:: javascript

    OpenLayers.Lang.en = {
        ...
        // login/logout
        'loginButtonText': 'Log in',
        'welcomeText': '
You are {username}.
',
        'logoutButtonText': 'Log out',
        'loginLabel': 'Login',
        'passwordLabel': 'Password',
        'loginSubmitButtonText': 'Submit',
        'loginCancelButtonText': 'Cancel'
    };

For the ``Login`` component to work the ``App.info`` JavaScript variable should
be set. The setting of this variable should be done anywhere in the
``config.js`` file, with this:

.. code:: javascript

    App.info = '${info | n}';

By default ``config.js`` includes it.

Multiple mobile applications
----------------------------

This section discusses the possibility of having multiple mobile applications
within a c2cgeoportal application.

As you will find out by reading the rest of this section creating multiple
mobile applications is a clear violation of the "don't repeat yourself"
principle. It is therefore discouraged; creating multiple *profiles* of the
mobile application should be done through multiple themes. However you may need
multiple mobile applications if you want, for example, different base layers,
and/or a high degree of customization, for each application.

Any c2cgeoportal application includes a mobile application in the
``<package>/static/mobile/`` directory.  The mobile application is created
by the ``c2cgeoportal_create`` and ``c2cgeoportal_update`` scaffolds. To create
another mobile application, the easiest is to copy the existing ``mobile``
directory into a new directory. For example:

.. prompt:: bash

    cd <package>/static
    cp -r mobile mobile2

.. warning::

    It is important to note that the ``c2cgeoportal_update`` scaffold, which is
    used when updating a c2cgeoportal application to a new c2cgeoportal
    version, will update the ``mobile`` directory only. This further means that
    any other mobile application will need to be manually updated (by copying
    files).

Other things need to be duplicated:

* The ``jsbuild`` mobile config file should be duplicated.

  For this copy
  ``jsbuild/mobile.cfg`` into ``jsbuild/mobile2.cfg``, for example. You may
  want to adapt the new config file, based on your needs.

* The ``sencha-touch`` make part should be duplicated.

  For this copy the ``[jsbuild-mobile]`` and ``[mobile]`` sections of
  ``CONST_buildout.cfg``, them into the application's ``buildout.cfg`` file,
  rename them (to ``[jsbuild-mobile2]`` and ``[mobile2]``), and adapt their
  contents so they reference the new mobile directory (``static/mobile2``), and
  the new ``jsbuild`` mobile config file (``jsbuild/mobile2.cfg``).

  You also need to add ``jsbuild-mobile2`` and ``mobile2`` to the list
  of parts that are run by Buildout by default::

      [buildout]
      extends = CONST_buildout.cfg
      parts += jsbuild-mobile mobile jsbuild-mobile2 mobile2

  At this point you should be able to successfully run Buildout again.

* The mobile routes and views should be duplicated.

  For that edit the application's main ``__init__.py`` file and copy the entire
  ``# mobile views and routes`` block, and paste it right below the original.
  Now change the route names, for example from ``mobile_index_dev`` to
  ``mobile_index_dev2``. Change the route URLs, for example from
  ``/mobile_dev/`` to ``/mobile_dev2/``. Change the paths to the templates
  files, for example from
  ``renderer='<package>:static/mobile/index.html'`` to
  ``renderer='<package>:static/mobile2/index.html'``.  Do this for every
  route and view.

  You should be done.


text:
require 'spec_helper'

describe CASino::StaticAuthenticator do
  subject {
    described_class.new({
      users: {
        user: {
          password: 'testing123',
          fullname: 'Example User'
        }
      }
    })
  }

  context '#validate' do
    context 'with invalid credentials' do
      it 'returns false for an unknown username' do
        subject.validate('foobar', 'test').should == false
      end

      it 'returns false for a known username with wrong password' do
        subject.validate('user', 'test').should == false
      end
    end

    context 'with valid credentials' do
      let(:result) { subject.validate('user', 'testing123') }

      it 'does not return false' do
        result.should_not == false
      end

      it 'returns the username' do
        result[:username].should == 'user'
      end

      it 'returns extra attributes' do
        result[:extra_attributes][:fullname].should == 'Example User'
      end
    end
  end
end


text:
module OneProvision

    # Driver
    module Driver

        class << self

            # Mutex to synchronize console output
            # rubocop:disable Style/ClassVars
            @@mutex = Mutex.new
            # rubocop:enable Style/ClassVars

            # Retry the operation in case of failure
            #
            # @param text    [String]    Operation
            # @param cleanup [Boolean]   True if the operation can be cleaned up
            # @param block   [Ruby Code] Block of code to execute
            def retry_loop(text, cleanup = Mode.cleanup)
                retries = 0

                begin
                    yield
                rescue OneProvisionLoopException => e
                    STDERR.puts "ERROR: #{text}\n#{e.text}"

                    retries += 1

                    if retries > Mode.max_retries && Mode.mode == :batch
                        exit(-1)
                    end

                    choice = Mode.fail_choice

                    if Mode.mode == :interactive
                        begin
                            @@mutex.synchronize do
                                cli = HighLine.new($stdin, $stderr)

                                choice = cli.choose do |menu|
                                    menu.prompt = 'Choose failover method:'
                                    menu.choices(:quit, :retry, :skip)
                                    menu.choices(:cleanup) if cleanup
                                    menu.default = choice
                                end
                            end
                        rescue EOFError
                            STDERR.puts choice
                        rescue Interrupt => e
                            exit(-1)
                        end
                    end

                    if choice == :retry
                        retry
                    elsif choice == :quit
                        exit(-1)
                    elsif choice == :skip
                        return
                    elsif choice == :cleanup
                        raise OneProvisionCleanupException if cleanup

                        Utils.fail('Cleanup unsupported for this operation')
                    end

                    exit(-1)
                end
            end

            # Runs commands
            #
            # @param cmd   [Array]       Command and arguments to execute
            # @param block [Ruby Code]
            #
            # @return      [Array]       Output, Error and Value returned
            def run(*cmd, &_block)
                OneProvisionLogger.debug("Command run: #{cmd.join(' ')}")

                rtn = nil

                begin
                    if Hash == cmd.last
                        opts = cmd.pop.dup
                    else
                        opts = {}
                    end

                    stdin_data = opts.delete(:stdin_data) || ''
                    binmode = opts.delete(:binmode)

                    Open3.popen3(*cmd, opts) do |i, o, e, t|
                        if binmode
                            i.binmode
                            o.binmode
                            e.binmode
                        end

                        out_reader = Thread.new { o.read }
                        err_reader = Thread.new { e.read }

                        begin
                            i.write stdin_data
                        rescue Errno::EPIPE => e
                            raise OneProvisionLoopException, e.text
                        end

                        begin
                            i.close
                        rescue IOError => e
                            raise OneProvisionLoopException, e.text
                        end

                        rtn = [out_reader.value, err_reader.value, t.value]
                    end

                    @@mutex.synchronize do
                        if rtn
                            if !rtn[0].empty?
                                OneProvisionLogger.debug('Command STDOUT: ' \
                                                "#{rtn[0].strip}")
                            end

                            if !rtn[1].empty?
                                OneProvisionLogger.debug('Command STDERR: ' \
                                                "#{rtn[1].strip}")
                            end

                            if rtn[2].success?
                                OneProvisionLogger.debug('Command succeeded')
                            else
                                OneProvisionLogger.warn('Command FAILED ' \
                                               "(code=#{rtn[2].exitstatus}): " \
                                               "#{cmd.join(' ')}")
                            end
                        else
                            OneProvisionLogger
                                .error('Command failed on unknown error')
                        end
                    end
                rescue Interrupt
                    Utils.fail('Command interrupted')
                rescue StandardError => e
                    OneProvisionLogger.error("Command exception: #{e.message}")
                end

                rtn
            end

            # Executes an action in the host
            #
            # @param pm_mad [String]           Provision Manager Driver
            # @param action [String]           Action to executue
            # @param args   [Array]            Arguments for the driver
            # @param host   [OpenNebula::Host] Host where execute the action
            #
            # @return       [String]           Output of the commmand
            def pm_driver_action(pm_mad, action, args, host = nil)
                cmd = ["#{REMOTES_LOCATION}/pm/#{pm_mad}/#{action}"]

                args.each do |arg|
                    cmd << arg
                end

                # action always gets host ID/name
                # if host defined, same as for VMs:
                # https://github.com/OpenNebula/one/blob/d95b883e38a2cee8ca9230b0dbef58ce3b8d6d6c/src/mad/ruby/OpenNebulaDriver.rb#L95
                @@mutex.synchronize do
                    unless host.nil?
                        cmd << host.id
                        cmd << host.name
                    end
                end

                unless File.executable? cmd[0]
                    OneProvisionLogger.error('Command not found or ' \
                                    "not executable #{cmd[0]}")
                    Utils.fail('Driver action script not executable')
                end

                o = nil

                retry_loop "Driver action '#{cmd[0]}' failed" do
                    o, e, s = run(cmd.join(' '))

                    unless s && s.success?
                        err = Utils.get_error_message(e)

                        text = err.lines[0].strip if err
                        text = 'Unknown error' if text == '-'

                        raise OneProvisionLoopException, text
                    end
                end

                o
            end

            # TODO: handle exceptions?
            #
            # Writes content to file
            #
            # @param name    [String] Name of the file
            # @param content [String] Content of the file
            def write_file_log(name, content)
                @@mutex.synchronize do
                    OneProvisionLogger.debug("Creating #{name}:\n" + content)
                end

                f = File.new(name, 'w')
                f.write(content)
                f.close
            end

        end

    end

end


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace PowerCommandParser
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = true)]
    public class DescriptionAttribute : Attribute
    {
        public string Text { get; set; }
        public string Summary { get; set; }
        public DescriptionAttribute() { }
        public DescriptionAttribute(string summary)
        {
            Summary = summary;
        }
        public DescriptionAttribute(string summary, string text)
        {
            Summary = summary;
            Text = text;
        }
    }
    public class HelpText<T>
    {
        public string Name { get; set; }
        private DescriptionAttribute Description => typeof(T).GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute;
        public string ProgramName => typeof(T).Assembly.GetName().Name;
        public string Synopsis => Description?.Summary ?? ProgramName;
        public string LongDescription => Description?.Text;
        private IEnumerable<PropertyInfo> OrderedProperties => typeof(T).GetProperties().OrderBy(p => p.GetCustomAttributes().Min(a => (a as PositionAttribute)?.Position) ?? int.MaxValue);
        public string GetSyntax()
        {
            var result = Name;
            foreach (var parameter in OrderedProperties)
            {
                var positioned = parameter.GetCustomAttribute(typeof(PositionAttribute)) != null;
                var required = parameter.GetCustomAttribute(typeof(RequiredAttribute)) != null;
                var parameterType = parameter.PropertyType.ToString();
                var parameterText = parameter.Name;
                if (positioned)
                    parameterText = $"[{parameterText}]";

                parameterText += $" {parameterType}";
                if (!required)
                    parameterText = $"[{parameterText}]";

                result += " " + parameterText;
            }

            return result;
        }

        public string GetParameterHelp()
        {
            return string.Join("\n\n", OrderedProperties
                            .Select(p => new { p, d = p.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute })
                            .Where(x => x.d != null)
                            .Select(x => $"{x.p.Name}:\n {x.d.Summary}"));
        }
    }
}