text:
/* List of contributors:
 *
 *  Initial  Name/description
 *  -------------------------------------------------------------------
 *  MF       Mario Fortier
 *  AC       Angelo Ciceri
 *
 *
 * Change history:
 *
 *  MMDDYY BY   Description
 *  -------------------------------------------------------------------
 *  112400 MF   First version.
 *  082004 AC   Add TA_SetCandleSettings, TA_RestoreCandleDefaultSettings
 *              and call to TA_RestoreCandleDefaultSettings in TA_Initialize
 *  041106 MF   Add prefix to theGlobals to avoid clash with other libs.
 *  040707 MF   Change global initialization to eliminate Mac OS X link error.
 */

/* Description:
 *   Provides initialization / shutdown functionality for all modules.
 */

/**** Headers ****/
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "ta_common.h"
#include "ta_magic_nb.h"
#include "ta_global.h"
#include "ta_func.h"

#ifdef TA_LIB_PRO
/* Section for code distributed with TA-Lib Pro only. */
#endif

/**** External functions declarations. ****/
/* None */

/**** External variables declarations. ****/
/* None */

/**** Global variables definitions.    ****/

/* The entry point for all globals */
TA_LibcPriv ta_theGlobals = {0,{{0,0,0}},0,0,0,0,(TA_Compatibility)0,{0},{{(TA_CandleSettingType)0,(TA_RangeType)0,0,0}}};

TA_LibcPriv *TA_Globals = &ta_theGlobals;

/**** Local declarations.              ****/
/* None */

/**** Local functions declarations.    ****/
/* None */

/**** Local variables definitions.     ****/
/* None */

/**** Global functions definitions.   ****/
TA_RetCode TA_Initialize( void )
{
   /* Initialize the "global variable" used to manage the global
    * variables of all other modules...
    */
   memset( TA_Globals, 0, sizeof( TA_LibcPriv ) );
   TA_Globals->magicNb = TA_LIBC_PRIV_MAGIC_NB;

#ifdef TA_LIB_PRO
      /* Section for code distributed with TA-Lib Pro only. */
#endif

   /*** At this point, TA_Shutdown can be called to clean-up. ***/

   /* Set the default value to global variables */
   TA_RestoreCandleDefaultSettings( TA_AllCandleSettings );

   return TA_SUCCESS;
}

TA_RetCode TA_Shutdown( void )
{
   if( TA_Globals->magicNb != TA_LIBC_PRIV_MAGIC_NB )
      return TA_LIB_NOT_INITIALIZE;

   /* Initialize to all zero to make sure we invalidate that object. */
   memset( TA_Globals, 0, sizeof( TA_LibcPriv ) );

   return TA_SUCCESS;
}

TA_RetCode TA_SetCandleSettings( TA_CandleSettingType settingType,
                                 TA_RangeType rangeType,
                                 int avgPeriod,
                                 double factor )
{
    /*printf("setcdlset:%d  ",settingType);*/
    if( settingType >= TA_AllCandleSettings )
        return TA_BAD_PARAM;
    TA_Globals->candleSettings[settingType].settingType = settingType;
    TA_Globals->candleSettings[settingType].rangeType = rangeType;
    TA_Globals->candleSettings[settingType].avgPeriod = avgPeriod;
    TA_Globals->candleSettings[settingType].factor = factor;
    /*printf("cdlset: %d %d %d %f\n",TA_Globals->candleSettings[settingType].settingType,TA_Globals->candleSettings[settingType].rangeType,
        TA_Globals->candleSettings[settingType].avgPeriod,TA_Globals->candleSettings[settingType].factor);*/
    return TA_SUCCESS;
}

TA_RetCode TA_RestoreCandleDefaultSettings( TA_CandleSettingType settingType )
{
    const TA_CandleSetting TA_CandleDefaultSettings[] = {
        /* real body is long when it's longer than the average of the 10 previous candles' real body */
        { TA_BodyLong, TA_RangeType_RealBody, 10, 1.0 },
        /* real body is very long when it's longer than 3 times the average of the 10 previous candles' real body */
        { TA_BodyVeryLong, TA_RangeType_RealBody, 10, 3.0 },
        /* real body is short when it's shorter than the average of the 10 previous candles' real bodies */
        { TA_BodyShort, TA_RangeType_RealBody, 10, 1.0 },
        /* real body is like doji's body when it's shorter than 10% the average of the 10 previous candles' high-low range */
        { TA_BodyDoji, TA_RangeType_HighLow, 10, 0.1 },
        /* shadow is long when it's longer than the real body */
        { TA_ShadowLong, TA_RangeType_RealBody, 0, 1.0 },
        /* shadow is very long when it's longer than 2 times the real body */
        { TA_ShadowVeryLong, TA_RangeType_RealBody, 0, 2.0 },
        /* shadow is short when it's shorter than half the average of the 10 previous candles' sum of shadows */
        { TA_ShadowShort, TA_RangeType_Shadows, 10, 1.0 },
        /* shadow is very short when it's shorter than 10% the average of the 10 previous candles' high-low range */
        { TA_ShadowVeryShort, TA_RangeType_HighLow, 10, 0.1 },
        /* when measuring distance between parts of candles or width of gaps */
        /* "near" means "<= 20% of the average of the 5 previous candles' high-low range" */
        { TA_Near, TA_RangeType_HighLow, 5, 0.2 },
        /* when measuring distance between parts of candles or width of gaps */
        /* "far" means ">= 60% of the average of the 5 previous candles' high-low range" */
        { TA_Far, TA_RangeType_HighLow, 5, 0.6 },
        /* when measuring distance between parts of candles or width of gaps */
        /* "equal" means "<= 5% of the average of the 5 previous candles' high-low range" */
        { TA_Equal, TA_RangeType_HighLow, 5, 0.05 }
    };

    int i;
    if( settingType > TA_AllCandleSettings )
        return TA_BAD_PARAM;
    if( settingType == TA_AllCandleSettings )
        for( i = 0; i < TA_AllCandleSettings; ++i )
            TA_Globals->candleSettings[i] = TA_CandleDefaultSettings[i];
    else
        TA_Globals->candleSettings[settingType] = TA_CandleDefaultSettings[settingType];
    return TA_SUCCESS;
}

/**** Local functions definitions.     ****/
/* None */


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>

      Dynamic first boot scripts with Imagr and Flask: Part 4 · graham gilbert

  </title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="/public/css/hyde.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml">
  <link href='/stylesheets/all-b18cc7d6d5710987503b687ec013f838.css' media='all' rel='stylesheet' type='text/css'>
  <link type="application/atom+xml" rel="alternate" href="https://grahamgilbert.com//atom.xml" title="graham gilbert" />

          graham gilbert

A Mac admin, automating the hell out of things.

      Home

            About

            Projects

            Talks

      The opinions on this site are my own, and are not necessarily shared by my employer.

Dynamic first boot scripts with Imagr and Flask: Part 4

  19 Jan 2016

If you are just starting with this series, it is highly recommended you start with Part 1.

The last part of this series is making it work in a Docker container. This is not a Docker tutorial - please head over to Docker's getting started pages to get yourself set up with the Docker Toolbox.

All done? Let's crack on with first creating our Dockerfile.

In the same ~/src/boostrapapp directory as your main script, create a new file called Dockerfile with the following contents:

~/src/boostrapapp/Dockerfile

FROM python:2.7-slim

ENV BOOTSTRAP_DEBUG=false BOOTSTRAP_USERNAME=admin BOOTSTRAP_PASSWORD=secret BOOTSTRAP_URL="http://localhost:5000"

COPY requirements.txt /requirements.txt

COPY gunicorn_config.py /gunicorn_config.py

COPY bootstrap.py /bootstrap.py

RUN pip install -r /requirements.txt && \

    rm /requirements.txt && \

    pip install gunicorn futures

CMD gunicorn -c gunicorn_config.py bootstrap:app

EXPOSE 5000

VOLUME ["/munki_repo"]

In the Dockerfile we copied a couple of files. The first is the requirements file - this will install the bits into python we need to run our app. Fortunately, this is incredibly easy to generate:

$ source ~/virtualenvs/bootstrapapp/bin/activate

$ cd ~/src/bootstrapapp

$ pip freeze > requirements.txt

And now for gunicorn_config.py. Up until now we have been using Flask's built in web server. This is fine for development, but in production it is better to use a more robust server. You would normally put an app running with Gunicorn behind a proxy server (you could use my Proxy image), but this time we won't for the sake of simplicity.

import multiprocessing

from os import getenv

bind = '0.0.0.0:5000'

workers = multiprocessing.cpu_count() * 2 + 1

timeout = 600

threads = multiprocessing.cpu_count() * 2

max_requests = 600

max_requests_jitter = 50

errorlog = '-'

accesslog = '-'

loglevel = 'warning'

# Read the DEBUG setting from env var

try:

    if getenv('BOOTSTRAP_DEBUG').lower() == 'true':

        loglevel = 'debug'

except:

    pass

Our last step before building the image is to replace a few parts that we've hardcoded into bootstrap.py with environment variables so they can be customised when the Docker image is run.

First off we have our username and password for HTTP authentication. Change:

~/src/boostrapapp/bootstrap.py

try:

    my_username = sys.argv[1]

except:

    my_username = 'admin'

try:

    my_password = sys.argv[2]

except:

    my_password = 'secret'

To look like:

~/src/boostrapapp/bootstrap.py

try:

    my_username = os.getenv('BOOTSTRAP_USERNAME', 'admin')

except:

    my_username = 'admin'

try:

    my_password = os.getenv('BOOTSTRAP_PASSWORD', 'secret')

except:

    my_password = 'secret'

Running our app in debug mode is useful during development, but can pose a security risk in production - let's be able to turn that on and off. Replace DEBUG = True at the top of boostrap.py with:

~/src/bootstrapapp/bootstrap.py

try:

    if getenv('BOOTSTRAP_DEBUG').lower() == 'true':

        DEBUG = True

    else:

        DEBUG = False

except:

    DEBUG = False

One last part is to be able to set our URL that the app is served on - we return this in the script that is sent to our clients, so we need to tell the container about it. Replace your def index section with:

~/src/bootstrapapp/bootstrap.py

@app.route('/')

@requires_auth

def index():

    build = request.headers.get('X-bootstrap-build')

    site = request.headers.get('X-bootstrap-site')

    url = os.getenv('BOOTSTRAP_URL', 'http://localhost:5000')

    script = '''#!/usr/bin/python

import subprocess

import re

import urllib

import os

site='{0}'

build='{1}'

username='{2}'

password='{3}'

url='{4}'

def get_hardware_info():

    cmd = ['/usr/sbin/system_profiler', 'SPHardwareDataType', '-xml']

    proc = subprocess.Popen(cmd, shell=False, bufsize=-1,

                            stdin=subprocess.PIPE,

                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    (output, unused_error) = proc.communicate()

    try:

        plist = FoundationPlist.readPlistFromString(output)

        # system_profiler xml is an array

        sp_dict = plist[0]

        items = sp_dict['_items']

        sp_hardware_dict = items[0]

        return sp_hardware_dict

    except Exception:

        return {{}}

hardware_info = get_hardware_info()

serial = hardware_info.get('serial_number', 'UNKNOWN')

serial = re.sub('[^A-Za-z0-9]+', '', serial)

serial_lower = serial.lower()

username_and_password = username+':'+password

data = {{

'serial': serial,

'site': site,

'build': build

}}

cmd = ['/usr/bin/curl', '-u', username_and_password, '--data', urllib.urlencode(data), url+'/gen_manifest']

task = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]

'''.format(site, build, my_username, my_password, url)

    return script

Prepare the build

Now we're ready to build our Docker image. Make sure your  Docker Machine VM is running and that you've run all the commands the Docker guide told you to and:

docker build -t bootstrapapp .

You'll see the base image being downloaded (if you don't already have it) and then each step of your Dockerfile being run. Now we've got an image built, let's run it. Assuming your VM's IP address is 172.16.155.136 (you can get yours by running docker-machine ip YOURVMNAME):

$ docker run -d --name=bootstrap \

    -e BOOTSTRAP_URL='http://172.16.155.136:5000' \

    -e BOOTSTRAP_USERNAME=myadmin \

    -e BOOTSTRAP_PASSWORD=mypassword \

    -v /Users/grahamgilbert/src/bootstrapapp/munki_repo:/munki_repo \

    -p 5000:5000 \

    bootstrapapp

Obviously replace /Users/grahamgilbert with your own home directory.

Will it blend?

Let's try pulling the script down:

curl --user "myadmin:mypassword" --header "X-bootstrap-build: build" --header "X-bootstrap-site: site" http://172.16.155.136:5000

Let's test manifest creation:

$ curl --user "myadmin:mypassword" --data 'serial=xyz789&site=london&build=somebuild' http://172.16.155.136:5000/gen_manifest

You should see your manifest being created on your Mac's filesystem.

And you can also see what your container is doing:

docker logs bootstrap

Using it with Imagr

Now to last part - using the thing. Let's generate the hash of your chosen username and password:

$ python -c 'import base64; print "Authorization: Basic %s" % base64.b64encode("USERNAME:PASSWORD")'

Authorization: Basic VVNFUk5BTUU6UEFTU1dPUkQ=

And add the following component to your Imagr workflow, substituting the output of the previous command:

<dict>

    <key>additional_headers</key>

    <array>

        <string>Authorization: Basic VVNFUk5BTUU6UEFTU1dPUkQ=</string>

        <string>X-enrolment-build: some_build</string>

        <string>X-enrolment-site: test_site</string>

    </array>

    <key>type</key>

    <string>script</string>

    <key>url</key>

    <string>http://172.16.155.136:5000</string>

</dict>

What's next?

You could now push this image to the Docker Hub, or you could build it on your server. If you want to see the completed project, I've posted it on GitHub, and I've set up an automated build on the Docker Hub if you want to use it and be lazy ;)

Fin

Congratulations - you've build a web app using the Flask framework, dynamically served scripts to Imagr, made your manifests for Munki on the fly and wrapped it all up into a Docker image.

Please enable JavaScript to view the comments powered by Disqus.

Related Posts

            Something something commercial, something something opensource
            08 Feb 2017

            Pocket Mac admin's guide to London
            19 Jan 2017

            Imagr with target disk mode
            11 Jan 2017

redpajama_set_name: RedPajamaGithub


text:
'use strict';

angular.module('directivasApp')
  .controller('RuedaCtrl', function ($scope) {
    $scope.rotating = false;
    $scope.toggle = function () {
      $scope.rotating = !$scope.rotating;
    };
  })
  .directive('rueda', function () {
    return {
      templateUrl: 'templates/rueda.html',
      controller: 'RuedaCtrl',
      restrict: 'E',
      link: function postLink() {}
    };
  });


text:
          Gadgets & Gear

Need Help?

Chat

Call

cart999

Fashionista

Fitness Buff

Medialorem

Traveler

Modern Family

Fun Seeker

              photo & video

              cases & protection

              chargers & power

              health & fitness

              home & family

              memory & storage

              Configuration

              see all

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

                see all lorem ipsum >

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

                see all lorem ipsum >

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

                see all lorem ipsum >

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

                see all lorem ipsum >

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

                see all lorem ipsum >

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

                see all lorem ipsum >

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

                see all lorem ipsum >

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

                see all lorem ipsum >

            See all brands >

Your cart is empty.

Continue shopping or sign-in to view your saved cart.

    						Sign In

Track the success of your workouts.

        			Learn More

Free Shipping on All Orders!

        			Learn More

Shop Skullcandy for 10% off.

        			Learn More

Track the success of your workouts.

        			Learn More

        	<form id="minicart-form" method="POST" action="mini-cart-remove.jsp">

        				Last 3 Items
        				Next 3 Items

        					$309.98

        				Subtotal:

        						View Cart (
2
)

        					<input class="button add-cart-cta" type="submit" title="Checkout" value="Checkout">

        	</form>

        menu

          Gadgets & Gear

cart999

lifestyles

Fashionista

Fitness Buff

Medialorem

Traveler

Modern Family

Fun Seeker

products

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

brands

special offers

  			Free 2-Day Shipping

  			Free 2-Day Shipping: Free 2-Day Shipping when you order online Monday - Friday by 4.30pm!
  			Some customers may need to select the Free 2-Day Shipping option in the Shipping drop=down menu at checkout.
  			Signature will be required upon delivery.

  			Accessory-Only Orders: Free 2-Day Shipping for orders totaling $49 or more when you order online Monday - Friday by 4.30pm*.  Free Ground Shipping on all other orders**.
  			Some customers may need to select the Free Shipping option in the drop down at checkout.  Signature will be required upon delivery.

  			*Free 2-Day Shipping when you order online Monday - Friday by 4.30pm.
  			Available for purchases placed on VerizonWireless.com for delivery within the U.S. only, excluding Alaska and Hawaii.
  			Orders placed by 4.30pm local time Monday - Friday (excluding holidays) will deliver in two (2) business days.
  			Orders placed after 4.30pm local time on Friday and before 4.30pm local time on Monday will be delivered on the following Wednesday. Subject to credit authorization, verification and inventory availability.

  			**Free Ground Shipping available for accessory-only purchases placed on VerizonWireless.com for delivery.


text:
<!DOCTYPE html>

        <title>Controls</title>

Controls

        <video width="320" height="240" controls>
          <source src="movie.mp4" type="video/mp4">
          <source src="movie.ogg" type="video/ogg">
          Your browser does not support the video tag.
        </video>


text:
var fs = require('fs');
var path = require('path');
var assert = require("assert");
var router = require("../lib/router");

var Σ = require('../lib/state');

var req0 = {
  'url': '/',
  'headers': {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'user-agent': 'Mozilla/5.0 (Windows NT 6.0; rv:12.0) Gecko/20100101 Firefox/12.0'
  },
  'method': 'GET',
  'httpVersion': '1.1'
};

var req1 = {
  'url': '/info',
  'headers': {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'user-agent': 'Mozilla/5.0 (Windows NT 6.0; rv:12.0) Gecko/20100101 Firefox/12.0'
  },
  'method': 'GET',
  'httpVersion': '1.1'
};

var req2 = {
  'url': '/search?q=X',
  'headers': {
    'accept': 'application/json',
    'user-agent': 'Mozilla/5.0 (Linux; U; Android 2.3.6; it-it; GT-I9100 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'
  },
  'method': 'GET',
  'httpVersion': '1.1'
};

var req3 = {
  'url': '/search.html/www',
  'headers': {
    'accept': 'text/html',
    'user-agent': 'Mozilla/5.0 (Linux; U; Android 2.3.6; it-it; GT-I9100 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'
  },
  'method': 'GET',
  'httpVersion': '1.1'
};

var req4 = {
  'url': '/search/tag/2',
  'headers': {
    'accept': 'text/html',
    'user-agent': 'Mozilla/5.0 (Linux; U; Android 2.3.6; it-it; GT-I9100 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'
  },
  'method': 'GET',
  'httpVersion': '1.1'
};

var req5 = {
  'url': '/42',
  'headers': {
    'accept': 'text/html',
    'user-agent': 'Mozilla/5.0 (Linux; U; Android 2.3.6; it-it; GT-I9100 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'
  },
  'method': 'GET',
  'httpVersion': '1.1'
};

var req6 = {
  'url': '/title-0/dummypath',
  'headers': {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'user-agent': 'Mozilla/5.0 (Windows NT 6.0; rv:12.0) Gecko/20100101 Firefox/12.0'
  },
  'method': 'GET',
  'httpVersion': '1.1'
};

var req7 = {
  'url': '/secret-0',
  'headers': {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'user-agent': 'Mozilla/5.0 (Windows NT 6.0; rv:12.0) Gecko/20100101 Firefox/12.0'
  },
  'method': 'GET',
  'httpVersion': '1.1'
};

var req8 = {
  'url': '/index/42',
  'headers': {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'user-agent': 'Mozilla/5.0 (Windows NT 6.0; rv:12.0) Gecko/20100101 Firefox/12.0'
  },
  'method': 'GET',
  'httpVersion': '1.1'
};

var doc1 = {
  n: 1,
  tag: [ 'www' ],
  rel: [],
  blip: false,
  secret: false,
  doc: false,
  timestamp: new Date('Sun, 02 Oct 2011 13:42:03 GMT'),
  title: 'Title 0',
  content: '
HTML5 valid ♥',
  id: 'title-0'
};

var doc2 = {
  n: 2,
  tag: [],
  rel: [],
  blip: false,
  secret: true,
  doc: false,
  timestamp: new Date('Sun, 02 Oct 2011 13:42:03 GMT'),
  title: 'Secret',
  content: '
HTML5 valid ♥',
  id: 'secret-0'
};

describe('router', function() {
  describe('#mobileCheck()', function() {
    it('should detect mobile User Agents', function() {
      assert.equal(true, router.mobileCheck({ 'headers': {'user-agent': 'Android Mobile'} }));
    })
  })

  describe('#parse()', function() {
    it('should parse an HTTP request', function() {

      var route0 = router.parse(req0);
      assert.equal("index", route0.url);
      assert.equal(true, route0.hiSpec);
      assert.equal("html", route0.output);
      assert.equal("text/html", route0.contentType);

      var route1 = router.parse(req1);
      assert.equal("info", route1.url);
      assert.equal(true, route1.hiSpec);
      assert.equal("html", route1.output);
      assert.equal("text/html", route1.contentType);

      var route2 = router.parse(req2);
      assert.equal("search", route2.url);
      assert.equal(false, route2.hiSpec);
      assert.equal("json", route2.output);

      var route3 = router.parse(req3);
      assert.equal("search", route3.url);
      assert.equal(false, route3.hiSpec);
      assert.equal("html", route3.output);

      var route4 = router.parse(req4);
      assert.equal("search", route4.url);
      assert.equal(false, route4.hiSpec);
      assert.equal("html", route4.output);

      var route5 = router.parse(req5);
      assert.equal("42", route5.url);
      assert.equal(false, route5.hiSpec);
      assert.equal("html", route5.output);
    });
  })

  describe('#resource()', function() {
    it('should do whatever it takes to get the requested resource', function(done) {
      // First build an index
      var indexer = require('../lib/indexer').createIndexer();
      indexer.add(doc1);

      // We will get the standard template for this request, and it must already exist.
      /*var tmpfile = path.normalize(__dirname + '/../../tmpl/hi-spec.mu.html');
      try {
        fs.statSync(tmpfile);
      } catch (e) {
        fs.writeFileSync(tmpfile, 'TEST url: {{url}}', 'utf8');
      }*/

      router.getResource(req6, router.parse(req6), function(err, resource) {
        assert.ifError(err);
        assert.notEqual('', resource);
        done(err);
      });
    });

    it('should return 404', function(done) {
      Σ.index['id'] = {};
      Σ.renders = {};
      Σ.compiled_templates = {};
      router.getResource(req6, router.parse(req6), function(err, resource) {
        assert.equal(404, err.status);
        done();
      });
    });

    /*it('should return 403 for secret documents', function(done) {
      Σ.cfg.verbose = false; // prevent log messages
      Σ.index['id'] = {};
      Σ.renders = {};
      Σ.compiled_templates = {};
      // First build an index
      var indexer = require('../lib/indexer').createIndexer();
      indexer.add(doc2);

      router.getResource(req7, router.parse(req7), function(err, resource) {
        assert.equal(403, err.status);
        done();
      });
    });*/
    it('should return secret documents if requested by direct url', function(done) {
      Σ.cfg.verbose = false; // prevent log messages
      Σ.index['id'] = {};
      Σ.renders = {};
      Σ.compiled_templates = {};
      // First build an index
      var indexer = require('../lib/indexer').createIndexer();
      indexer.add(doc2);

      router.getResource(req7, router.parse(req7), function(err, resource) {
        assert.ifError(err);
        assert.notEqual('', resource);
        done(err);
      });
    });

    it('should set a unique key for the resource cache', function() {
      var route0 = router.parse(req0);
      assert.equal("index", route0.key);

      var route1 = router.parse(req1);
      assert.equal("info", route1.key);

      var route2 = router.parse(req2);
      assert.equal("search", route2.key);

      var route3 = router.parse(req3);
      assert.equal("search/www", route3.key);

      var route4 = router.parse(req4);
      assert.equal("search/tag/2", route4.key);

      var route6 = router.parse(req6);
      assert.equal("title-0", route6.key);

      var route8 = router.parse(req8);
      assert.equal("index/42", route8.key);
    });

  })

})


text:
package v1

import (
	"context"

	"google.golang.org/grpc"

	"go-common/library/net/rpc/warden"
)

// AppID unique app id for service discovery
const AppID = "account.service.ugcpay"

// NewClient new identify grpc client
func NewClient(cfg *warden.ClientConfig, opts ...grpc.DialOption) (UGCPayClient, error) {
	client := warden.NewClient(cfg, opts...)
	conn, err := client.Dial(context.Background(), "discovery://default/"+AppID)
	if err != nil {
		return nil, err
	}
	return NewUGCPayClient(conn), nil
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cladosporium phlei-pratense Sawada

### Remarks
null


text:
YUI.add('datatable-datasource', function(Y) {

/**
 * Plugs DataTable with DataSource integration.
 *
 * @module datatable
 * @submodule datatable-datasource
 */

/**
 * Adds DataSource integration to DataTable.
 * @class DataTableDataSource
 * @extends Plugin.Base
 */
function DataTableDataSource() {
    DataTableDataSource.superclass.constructor.apply(this, arguments);
}

/////////////////////////////////////////////////////////////////////////////
//
// STATIC PROPERTIES
//
/////////////////////////////////////////////////////////////////////////////
Y.mix(DataTableDataSource, {
    /**
     * The namespace for the plugin. This will be the property on the host which
     * references the plugin instance.
     *
     * @property NS
     * @type String
     * @static
     * @final
     * @value "datasource"
     */
    NS: "datasource",

    /**
     * Class name.
     *
     * @property NAME
     * @type String
     * @static
     * @final
     * @value "dataTableDataSource"
     */
    NAME: "dataTableDataSource",

/////////////////////////////////////////////////////////////////////////////
//
// ATTRIBUTES
//
/////////////////////////////////////////////////////////////////////////////
    ATTRS: {
        /**
        * @attribute datasource
        * @description Pointer to DataSource instance.
        * @type Y.DataSource
        */
        datasource: {
            setter: "_setDataSource"
        },

        /**
        * @attribute initialRequest
        * @description Request sent to DataSource immediately upon initialization.
        * @type Object
        */
        initialRequest: {
            setter: "_setInitialRequest"
        }
    }
});

/////////////////////////////////////////////////////////////////////////////
//
// PROTOTYPE
//
/////////////////////////////////////////////////////////////////////////////
Y.extend(DataTableDataSource, Y.Plugin.Base, {
    /////////////////////////////////////////////////////////////////////////////
    //
    // ATTRIBUTE HELPERS
    //
    /////////////////////////////////////////////////////////////////////////////
    /**
    * @method _setDataSource
    * @description Creates new DataSource instance if one is not provided.
    * @param ds {Object | Y.DataSource}
    * @returns Y.DataSource
    * @private
    */
    _setDataSource: function(ds) {
        return ds || new Y.DataSource.Local(ds);
    },

    /**
    * @method _setInitialRequest
    * @description Sends request to DataSource.
    * @param request {Object} DataSource request.
    * @private
    */
    _setInitialRequest: function(request) {
    },

    /////////////////////////////////////////////////////////////////////////////
    //
    // METHODS
    //
    /////////////////////////////////////////////////////////////////////////////
    /**
    * Initializer.
    *
    * @method initializer
    * @param config {Object} Config object.
    * @private
    */
    initializer: function(config) {
        if(!Y.Lang.isUndefined(config.initialRequest)) {
            this.load({request:config.initialRequest});
        }
    },

    ////////////////////////////////////////////////////////////////////////////
    //
    // DATA
    //
    ////////////////////////////////////////////////////////////////////////////

    /**
     * Load data by calling DataSource's sendRequest() method under the hood.
     *
     * @method load
     * @param config {object} Optional configuration parameters:
     *
     *

     *
request

Pass in a new request, or initialRequest is used.

     *
callback

Pass in DataSource callback object, or the following default is used:
     *

     *
success

datatable.onDataReturnInitializeTable

     *
failure

datatable.onDataReturnInitializeTable

     *
scope

datatable

     *
argument

datatable.getState()

     *

     *

     *
datasource

Pass in a new DataSource instance to override the current DataSource for this transaction.

     *

     */
    load: function(config) {
        config = config || {};
        config.request = config.request || this.get("initialRequest");
        config.callback = config.callback || {
            success: Y.bind(this.onDataReturnInitializeTable, this),
            failure: Y.bind(this.onDataReturnInitializeTable, this),
            argument: this.get("host").get("state") //TODO
        };

        var ds = (config.datasource || this.get("datasource"));
        if(ds) {
            ds.sendRequest(config);
        }
    },

    /**
     * Callback function passed to DataSource's sendRequest() method populates
     * an entire DataTable with new data, clearing previous data, if any.
     *
     * @method onDataReturnInitializeTable
     * @param e {Event.Facade} DataSource Event Facade object.
     */
    onDataReturnInitializeTable : function(e) {
        var records = (e.response && e.response.results) || [];

        this.get("host").get("recordset").set("records", records);
    }
});

Y.namespace("Plugin").DataTableDataSource = DataTableDataSource;

}, '@VERSION@' ,{requires:['datatable-base','plugin','datasource-local']});


text:
package com.sonoport.freesound.query.sound;

/**
 * Geolocation details associated with a sound.
 */
public class Geotag {

	/** Latitude of location. */
	private final double latitude;

	/** Longitude of location. */
	private final double longitude;

	/** Zoom level of location. */
	private final int zoom;

	/**
	 * @param latitude Latitude of location
	 * @param longitude Longitude of location
	 * @param zoom Zoom level of location
	 */
	public Geotag(final double latitude, final double longitude, final int zoom) {
		this.latitude = latitude;
		this.longitude = longitude;
		this.zoom = zoom;
	}

	/**
	 * @return the latitude
	 */
	public double getLatitude() {
		return latitude;
	}

	/**
	 * @return the longitude
	 */
	public double getLongitude() {
		return longitude;
	}

	/**
	 * @return the zoom
	 */
	public int getZoom() {
		return zoom;
	}
}


text:
@class CCNewsDescriptionContentServerModel;
@class CCNewDescriptionContentCoreDataModel;

@interface CCNewsImageContentViewModel : CCNewsContentViewModel

@property (nonatomic, strong) NSURL *coverImageURL;
@property (nonatomic, assign) CGFloat contentHeight;

@end

@interface CCNewsImageContentViewModelBuilder : NSObject

+ (CCNewsImageContentViewModel *)buildWithServerModel:(CCNewsDescriptionContentServerModel *)serverModel;

+ (CCNewsImageContentViewModel *)buildWithCoreDataModel:(CCNewDescriptionContentCoreDataModel *)coreDataModel;

@end


text:
from sqlalchemy import and_
from sqlalchemy import Column
from sqlalchemy import exc
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import Integer
from sqlalchemy import join
from sqlalchemy import select
from sqlalchemy import testing
from sqlalchemy.orm import aliased
from sqlalchemy.orm import joinedload
from sqlalchemy.orm import noload
from sqlalchemy.orm import relationship
from sqlalchemy.orm import selectinload
from sqlalchemy.orm import Session
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
from sqlalchemy.testing.assertions import expect_raises_message
from sqlalchemy.testing.assertsql import CompiledSQL
from sqlalchemy.testing.fixtures import ComparableEntity
from sqlalchemy.testing.fixtures import fixture_session

class PartitionByFixture(fixtures.DeclarativeMappedTest):
    @classmethod
    def setup_classes(cls):
        Base = cls.DeclarativeBasic

        class A(Base):
            __tablename__ = "a"

            id = Column(Integer, primary_key=True)

        class B(Base):
            __tablename__ = "b"
            id = Column(Integer, primary_key=True)
            a_id = Column(ForeignKey("a.id"))
            cs = relationship("C")

        class C(Base):
            __tablename__ = "c"
            id = Column(Integer, primary_key=True)
            b_id = Column(ForeignKey("b.id"))

        partition = select(
            B,
            func.row_number()
            .over(order_by=B.id, partition_by=B.a_id)
            .label("index"),
        ).alias()

        cls.partitioned_b = partitioned_b = aliased(B, alias=partition)

        A.partitioned_bs = relationship(
            partitioned_b,
            primaryjoin=and_(
                partitioned_b.a_id == A.id, partition.c.index < 10
            ),
        )

    @classmethod
    def insert_data(cls, connection):
        A, B, C = cls.classes("A", "B", "C")

        s = Session(connection)
        s.add_all([A(id=i) for i in range(1, 4)])
        s.flush()
        s.add_all(
            [
                B(a_id=i, cs=[C(), C()])
                for i in range(1, 4)
                for j in range(1, 21)
            ]
        )
        s.commit()

class AliasedClassRelationshipTest(
    PartitionByFixture, testing.AssertsCompiledSQL
):
    # TODO: maybe make this more  backend agnostic
    __requires__ = ("window_functions",)
    __dialect__ = "default"

    def test_lazyload(self):
        A, B, C = self.classes("A", "B", "C")

        s = Session(testing.db)

        def go():
            for a1 in s.query(A):  # 1 query
                eq_(len(a1.partitioned_bs), 9)  # 3 queries
                for b in a1.partitioned_bs:
                    eq_(len(b.cs), 2)  # 9 * 3 = 27 queries

        self.assert_sql_count(testing.db, go, 31)

    def test_join_one(self):
        A, B, C = self.classes("A", "B", "C")

        s = Session(testing.db)

        q = s.query(A).join(A.partitioned_bs)
        self.assert_compile(
            q,
            "SELECT a.id AS a_id FROM a JOIN "
            "(SELECT b.id AS id, b.a_id AS a_id, row_number() "
            "OVER (PARTITION BY b.a_id ORDER BY b.id) "
            "AS index FROM b) AS anon_1 "
            "ON anon_1.a_id = a.id AND anon_1.index < :index_1",
        )

    def test_join_two(self):
        A, B, C = self.classes("A", "B", "C")

        s = Session(testing.db)

        q = s.query(A, A.partitioned_bs.entity).join(A.partitioned_bs)
        self.assert_compile(
            q,
            "SELECT a.id AS a_id, anon_1.id AS anon_1_id, "
            "anon_1.a_id AS anon_1_a_id "
            "FROM a JOIN "
            "(SELECT b.id AS id, b.a_id AS a_id, row_number() "
            "OVER (PARTITION BY b.a_id ORDER BY b.id) "
            "AS index FROM b) AS anon_1 "
            "ON anon_1.a_id = a.id AND anon_1.index < :index_1",
        )

    def test_selectinload_w_noload_after(self):
        A, B, C = self.classes("A", "B", "C")

        s = Session(testing.db)

        def go():
            for a1 in s.query(A).options(
                noload("*"), selectinload(A.partitioned_bs)
            ):
                for b in a1.partitioned_bs:
                    eq_(b.cs, [])

        self.assert_sql_count(testing.db, go, 2)

    @testing.combinations("ac_attribute", "ac_attr_w_of_type")
    def test_selectinload_w_joinedload_after(self, calling_style):
        """test has been enhanced to also test #7224"""

        A, B, C = self.classes("A", "B", "C")

        s = Session(testing.db)

        partitioned_b = self.partitioned_b

        if calling_style == "ac_attribute":
            opt = selectinload(A.partitioned_bs).joinedload(partitioned_b.cs)
        elif calling_style == "ac_attr_w_of_type":
            # this would have been a workaround for people who encountered
            # #7224. The exception that was raised for "ac_attribute" actually
            # suggested to use of_type() so we can assume this pattern is
            # probably being used
            opt = selectinload(
                A.partitioned_bs.of_type(partitioned_b)
            ).joinedload(partitioned_b.cs)
        else:
            assert False

        def go():
            for a1 in s.query(A).options(opt):
                for b in a1.partitioned_bs:
                    eq_(len(b.cs), 2)

        self.assert_sql_count(testing.db, go, 2)

    @testing.combinations(True, False)
    def test_selectinload_w_joinedload_after_base_target_fails(
        self, use_of_type
    ):
        A, B, C = self.classes("A", "B", "C")

        s = Session(testing.db)
        partitioned_b = self.partitioned_b

        with expect_raises_message(
            exc.ArgumentError,
            r'ORM mapped attribute "B.cs" does not link from '
            r'relationship "A.partitioned_bs.of_type\(aliased\(B\)\)"',
        ):
            if use_of_type:
                opt = selectinload(
                    A.partitioned_bs.of_type(partitioned_b)
                ).joinedload(B.cs)
            else:
                opt = selectinload(A.partitioned_bs).joinedload(B.cs)

            q = s.query(A).options(opt)

            q._compile_context()

class AltSelectableTest(
    fixtures.DeclarativeMappedTest, testing.AssertsCompiledSQL
):
    __dialect__ = "default"

    @classmethod
    def setup_classes(cls):
        Base = cls.DeclarativeBasic

        class A(ComparableEntity, Base):
            __tablename__ = "a"

            id = Column(Integer, primary_key=True)
            b_id = Column(ForeignKey("b.id"))

        class B(ComparableEntity, Base):
            __tablename__ = "b"

            id = Column(Integer, primary_key=True)

        class C(ComparableEntity, Base):
            __tablename__ = "c"

            id = Column(Integer, primary_key=True)
            a_id = Column(ForeignKey("a.id"))

        class D(ComparableEntity, Base):
            __tablename__ = "d"

            id = Column(Integer, primary_key=True)
            c_id = Column(ForeignKey("c.id"))
            b_id = Column(ForeignKey("b.id"))

        # 1. set up the join() as a variable, so we can refer
        # to it in the mapping multiple times.
        j = join(B, D, D.b_id == B.id).join(C, C.id == D.c_id)

        # 2. Create an AliasedClass to B
        B_viacd = aliased(B, j, flat=True)

        A.b = relationship(B_viacd, primaryjoin=A.b_id == j.c.b_id)

    @classmethod
    def insert_data(cls, connection):
        A, B, C, D = cls.classes("A", "B", "C", "D")
        sess = Session(connection)

        for obj in [
            B(id=1),
            A(id=1, b_id=1),
            C(id=1, a_id=1),
            D(id=1, c_id=1, b_id=1),
        ]:
            sess.add(obj)
            sess.flush()
        sess.commit()

    def test_lazyload(self):
        A, B = self.classes("A", "B")

        sess = fixture_session()
        a1 = sess.query(A).first()

        with self.sql_execution_asserter() as asserter:
            # note this is many-to-one.  use_get is unconditionally turned
            # off for relationship to aliased class for now.
            eq_(a1.b, B(id=1))

        asserter.assert_(
            CompiledSQL(
                "SELECT b.id AS b_id FROM b JOIN d ON d.b_id = b.id "
                "JOIN c ON c.id = d.c_id WHERE :param_1 = b.id",
                [{"param_1": 1}],
            )
        )

    def test_joinedload(self):
        A, B = self.classes("A", "B")

        sess = fixture_session()

        with self.sql_execution_asserter() as asserter:
            # note this is many-to-one.  use_get is unconditionally turned
            # off for relationship to aliased class for now.
            a1 = sess.query(A).options(joinedload(A.b)).first()
            eq_(a1.b, B(id=1))

        asserter.assert_(
            CompiledSQL(
                "SELECT a.id AS a_id, a.b_id AS a_b_id, b_1.id AS b_1_id "
                "FROM a LEFT OUTER JOIN (b AS b_1 "
                "JOIN d AS d_1 ON d_1.b_id = b_1.id "
                "JOIN c AS c_1 ON c_1.id = d_1.c_id) ON a.b_id = b_1.id "
                "LIMIT :param_1",
                [{"param_1": 1}],
            )
        )

    def test_selectinload(self):
        A, B = self.classes("A", "B")

        sess = fixture_session()

        with self.sql_execution_asserter() as asserter:
            # note this is many-to-one.  use_get is unconditionally turned
            # off for relationship to aliased class for now.
            a1 = sess.query(A).options(selectinload(A.b)).first()
            eq_(a1.b, B(id=1))

        asserter.assert_(
            CompiledSQL(
                "SELECT a.id AS a_id, a.b_id AS a_b_id "
                "FROM a LIMIT :param_1",
                [{"param_1": 1}],
            ),
            CompiledSQL(
                "SELECT a_1.id AS a_1_id, b.id AS b_id FROM a AS a_1 "
                "JOIN (b JOIN d ON d.b_id = b.id JOIN c ON c.id = d.c_id) "
                "ON a_1.b_id = b.id WHERE a_1.id "
                "IN (__[POSTCOMPILE_primary_keys])",
                [{"primary_keys": [1]}],
            ),
        )

    def test_join(self):
        A, B = self.classes("A", "B")

        sess = fixture_session()

        self.assert_compile(
            sess.query(A).join(A.b),
            "SELECT a.id AS a_id, a.b_id AS a_b_id "
            "FROM a JOIN (b JOIN d ON d.b_id = b.id "
            "JOIN c ON c.id = d.c_id) ON a.b_id = b.id",
        )


text:
from __future__ import absolute_import

from os import environ
from .base import *
from .s3 import *

ALLOWED_HOSTS = ("oshot.hasadna.org.il", ".localshot.org.il", )
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
DEBUG = os.environ.get('DEBUG', False)
TEMPLATE_DEBUG = DEBUG

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'oshot',                      # Or path to database file if using sqlite3.
        'USER': 'oshot',                      # Not used with sqlite3.
        'PASSWORD': 'oshot',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

EMAIL_HOST = 'localhost'
EMAIL_PORT = 25
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False

ANALYTICS_ID = os.environ.get('ANALYTICS_ID')

ADMINS += [('tbrisker', 'tbrisker@gmail.com') ]
BROKER_URL = 'amqp://guest:guest@localhost:5672/'
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook MathML Module V1.1b1//EN"
              "http://www.oasis-open.org/docbook/xml/mathml/1.1CR1/dbmathml.dtd">
<refentry id="gluOrtho2D">
    <refmeta>
        <refmetainfo>
            <copyright>
                <year>1991-2006</year>
                <holder>Silicon Graphics, Inc.</holder>
            </copyright>
        </refmetainfo>
        <refentrytitle>gluOrtho2D</refentrytitle>
        <manvolnum>3G</manvolnum>
    </refmeta>
    <refnamediv>
        <refname>gluOrtho2D</refname>
        <refpurpose>define a 2D orthographic projection matrix</refpurpose>
    </refnamediv>
    <refsynopsisdiv><title>C Specification</title>
        <funcsynopsis>
            <funcprototype>
                <funcdef>void <function>gluOrtho2D</function></funcdef>
                <paramdef>GLdouble <parameter>left</parameter></paramdef>
                <paramdef>GLdouble <parameter>right</parameter></paramdef>
                <paramdef>GLdouble <parameter>bottom</parameter></paramdef>
                <paramdef>GLdouble <parameter>top</parameter></paramdef>
            </funcprototype>
        </funcsynopsis>
    </refsynopsisdiv>
    <!-- eqn: ignoring delim $$ -->
    <refsect1 id="parameters"><title>Parameters</title>
        <variablelist>
        <varlistentry>
            <term><parameter>left</parameter></term>
            <term><parameter>right</parameter></term>
            <listitem>
                <para>
                    Specify the coordinates for the left and right vertical clipping planes.
                </para>
            </listitem>
        </varlistentry>
        <varlistentry>
            <term><parameter>bottom</parameter></term>
            <term><parameter>top</parameter></term>
            <listitem>
                <para>
                    Specify the coordinates for the bottom and top horizontal clipping planes.
                </para>
            </listitem>
        </varlistentry>
        </variablelist>
    </refsect1>
    <refsect1 id="description"><title>Description</title>
        <para>
            <function>gluOrtho2D</function> sets up a two-dimensional orthographic viewing region.
            This is equivalent to calling <citerefentry><refentrytitle>glOrtho</refentrytitle></citerefentry> with
            <inlineequation><mml:math>
                <!-- eqn: near  =  -1:-->
                <mml:mrow>
                    <mml:mi mathvariant="italic">near</mml:mi>
                    <mml:mo>=</mml:mo>
                    <mml:mn>-1</mml:mn>
                </mml:mrow>
            </mml:math></inlineequation>
            and
            <inlineequation><mml:math>
                <!-- eqn: far  =  1:-->
                <mml:mrow>
                    <mml:mi mathvariant="italic">far</mml:mi>
                    <mml:mo>=</mml:mo>
                    <mml:mn>1</mml:mn>
                </mml:mrow>
            </mml:math></inlineequation>.
        </para>
    </refsect1>
    <refsect1 id="seealso"><title>See Also</title>
        <para>
            <citerefentry><refentrytitle>glOrtho</refentrytitle></citerefentry>,
            <citerefentry><refentrytitle>gluPerspective</refentrytitle></citerefentry>
        </para>
    </refsect1>
    <refsect1 id="Copyright"><title>Copyright</title>
        <para>
            Copyright <trademark class="copyright"></trademark> 1991-2006
            Silicon Graphics, Inc. This document is licensed under the SGI
            Free Software B License. For details, see
            <ulink url="http://oss.sgi.com/projects/FreeB/">http://oss.sgi.com/projects/FreeB/</ulink>.
        </para>
    </refsect1>
</refentry>


text:
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.util import dumpNodeConnections
from mininet.log import setLogLevel

class Khalili(Topo):
    "TCP vs MPTCP khalili et al., 2012"

    def __init__(self,n1,n2,**opts):
        #Initialize Topology
        super(Khalili,self).__init__(**opts)

        #--------------n1---------------
        #Create private switches (MPTCP)
        SWITCHES_MPTCP = [self.addSwitch('sw_mptcp%s' %s) for s in range(1,n1+1)]

        #Create type1 hosts (MPTCP)
        HOSTS_MPTCP = [self.addHost('h%s' % h) for h in range(1,n1+1)]

        #--------------n2---------------_
        #Create streaming Servers (TCP)
        SERVERS_TCP = [self.addHost('serv_tcp%s' %s) for s in range(1,n2+1)]

        #Create streaming switches (TCP)
        HOSTS_TCP = [self.addHost('h_tcp%s' % h) for h in range(1,n2+1)]

        #------------only one----------
        #Create ONE MPTCP Server (MPTCP)
        SERVER_MPTCP = [self.addHost('serv_mptcp1')]

        #Create ONE AP switch (SHARED)
        SWITCH_SHARED = [self.addHost('h_shared1')]

       #-------------Links-------------
       #--left
        #wire up MPTCP hosts and private switches
        for A, B in zip(HOSTS_MPTCP,SWITCHES_MPTCP):
            self.addLink(A,B)

        #wire up MPTCP hosts and shared switch
        for A in HOSTS_MPTCP:
            self.addLink(A,SWITCH_SHARED[0])

        #wire up NON MPTCP HOSTS and shared switch
        for A in HOSTS_TCP:
            self.addLink(A,SWITCH_SHARED[0])

        #--right
        #wire up NON MPTCP HOSTS and NON TCP servers
        for A in CP:
            self.addLink(A,SWITCH_SHARED[0])

def PingTest():
    topo = Khalili(n1=2,n2=2)
    net = Mininet(topo)
    net.start()
    print "Dump"
    #dumpNodeConnections(net.node)
    print "Testing network connectivity"
  #  net.pingAll()
    net.stop()

if __name__ == '__main__':
    # Tell mininet to print useful information
    setLogLevel('info')
    PingTest()


text:
package io.digdag.core.notification;

import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.name.Names;
import io.digdag.client.config.Config;
import io.digdag.commons.ThrowablesUtil;
import io.digdag.spi.Notification;
import io.digdag.spi.NotificationException;
import io.digdag.spi.NotificationSender;
import io.digdag.spi.Notifier;
import io.digdag.util.RetryExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static io.digdag.util.RetryExecutor.retryExecutor;

public class DefaultNotifier
        implements Notifier
{
    private static final String NOTIFICATION_TYPE = "notification.type";

    private static final String NOTIFICATION_RETRIES = "notification.retries";
    private static final String NOTIFICATION_MIN_RETRY_WAIT = "notification.min_retry_wait";
    private static final String NOTIFICATION_MAX_RETRY_WAIT = "notification.max_retry_wait";
    private static final int NOTIFICATION_RETRIES_DEFAULT = 10;
    private static final int NOTIFICATION_MIN_RETRY_WAIT_DEFAULT = 1000;
    private static final int NOTIFICATION_MAX_RETRY_WAIT_DEFAULT = 30000;

    private static Logger logger = LoggerFactory.getLogger(DefaultNotifier.class);

    private Injector injector;
    private final NotificationSender sender;
    private final int retries;
    private final int minRetryWait;
    private final int maxRetryWait;

    @Inject
    public DefaultNotifier(Config systemConfig, Injector injector)
    {
        this.injector = injector;
        Optional<String> type = systemConfig.getOptional(NOTIFICATION_TYPE, String.class);
        this.sender = type.isPresent() ? sender(type.get()) : null;
        this.retries = systemConfig.get(NOTIFICATION_RETRIES, int.class, NOTIFICATION_RETRIES_DEFAULT);
        this.minRetryWait = systemConfig.get(NOTIFICATION_MIN_RETRY_WAIT, int.class, NOTIFICATION_MIN_RETRY_WAIT_DEFAULT);
        this.maxRetryWait = systemConfig.get(NOTIFICATION_MAX_RETRY_WAIT, int.class, NOTIFICATION_MAX_RETRY_WAIT_DEFAULT);
    }

    private NotificationSender sender(String type)
    {
        return injector.getInstance(Key.get(NotificationSender.class, Names.named(type)));
    }

    @Override
    public void sendNotification(Notification notification)
            throws NotificationException
    {
        logger.debug("Notification: {}", notification);

        if (sender == null) {
            return;
        }

        RetryExecutor retryExecutor = retryExecutor()
                .retryIf(exception -> true)
                .withInitialRetryWait(minRetryWait)
                .withMaxRetryWait(maxRetryWait)
                .onRetry((exception, retryCount, retryLimit, retryWait) -> logger.warn("Sending notification failed: retry {} of {}", retryCount, retryLimit, exception))
                .withRetryLimit(retries);

        try {
            retryExecutor.run(() -> {
                try {
                    sender.sendNotification(notification);
                }
                catch (NotificationException e) {
                    throw ThrowablesUtil.propagate(e);
                }
            });
        }
        catch (RetryExecutor.RetryGiveupException e) {
            throw new NotificationException("Sending notification failed", e);
        }
    }
}


text:
package com.simbest.cores.exceptions;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 关于异常的工具类.
 *
 * @author lishuyi
 */
public class Exceptions {

	protected final static Log log = LogFactory.getLog(Exceptions.class);

	/**
	 * 将CheckedException转换为UncheckedException.
	 */
	public static RuntimeException unchecked(Exception e) {
		if (e instanceof RuntimeException) {
			return (RuntimeException) e;
		} else {
			return new RuntimeException(e);
		}
	}

	/**
	 * 将ErrorStack转化为String.
	 */
	public static String getStackTraceAsString(Exception e) {
		StringWriter stringWriter = new StringWriter();
		e.printStackTrace(new PrintWriter(stringWriter));
		return stringWriter.toString();
	}

	/**
	 * 判断异常是否由某些底层的异常引起.
	 */
	public static boolean isCausedBy(Exception ex, @SuppressWarnings("unchecked") Class<? extends Exception>... causeExceptionClasses) {
		Throwable cause = ex;
		while (cause != null) {
			for (Class<? extends Exception> causeClass : causeExceptionClasses) {
				if (causeClass.isInstance(cause)) {
					return true;
				}
			}
			cause = cause.getCause();
		}
		return false;
	}

	public static void printException(Exception e){
		ByteArrayOutputStream buf = new ByteArrayOutputStream();
		e.printStackTrace(new PrintWriter(buf, true));
		String expMsg = buf.toString();
		log.error(expMsg);
	}
}


text:
using System;
using Azure.Core;

namespace Azure.Security.KeyVault.Administration
{
    /// <summary>
    /// Options to configure the requests sent to Key Vault.
    /// </summary>
    public class KeyVaultAdministrationClientOptions : ClientOptions
    {
        /// <summary>
        /// The latest service version supported by this client library.
        /// For more information, see
        /// <see href="https://docs.microsoft.com/rest/api/keyvault/key-vault-versions">Key Vault versions</see>.
        /// </summary>
        internal const ServiceVersion LatestVersion = ServiceVersion.V7_3_Preview;

        /// <summary>
        /// The versions of Azure Key Vault supported by this client
        /// library.
        /// </summary>
        public enum ServiceVersion
        {
#pragma warning disable CA1707 // Identifiers should not contain underscores
            /// <summary>
            /// The Key Vault API version 7.2.
            /// </summary>
            V7_2 = 1,

            /// <summary>
            /// The Key Vault API version 7.3-preview.
            /// </summary>
            V7_3_Preview = 2,
#pragma warning restore CA1707 // Identifiers should not contain underscores
        }

        /// <summary>
        /// Gets the <see cref="ServiceVersion"/> of the service API used when
        /// making requests. For more information, see
        /// <see href="https://docs.microsoft.com/rest/api/keyvault/key-vault-versions">Key Vault versions</see>.
        /// </summary>
        public ServiceVersion Version { get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="KeyVaultAdministrationClientOptions"/> class.
        /// class.
        /// </summary>
        /// <param name="version">
        /// The <see cref="ServiceVersion"/> of the service API used when
        /// making requests.
        /// </param>
        public KeyVaultAdministrationClientOptions(ServiceVersion version = LatestVersion)
        {
            Version = version;

            this.ConfigureLogging();
        }

        internal string GetVersionString()
        {
            return Version switch
            {
                ServiceVersion.V7_2 => "7.2",
                ServiceVersion.V7_3_Preview => "7.3-preview",
                _ => throw new ArgumentException(Version.ToString()),
            };
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Christian Ringler -</title>
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="https://cringler.github.io/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//cringler.github.io/themes/casper/assets/css/screen.css?v=1501620331270" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="https://cringler.github.io/https://cringler.github.io/author/cringler/" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="" />
    <meta property="og:type" content="profile" />
    <meta property="og:title" content="Christian Ringler -" />
    <meta property="og:url" content="https://cringler.github.io/https://cringler.github.io/author/cringler/" />
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Christian Ringler -" />
    <meta name="twitter:url" content="https://cringler.github.io/https://cringler.github.io/author/cringler/" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="" href="https://cringler.github.io/rss/" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/styles/atom-one-dark.min.css">

Christian Ringler

             1 post

        Page 1 of 1

Test-Page

Das würde ich doch gerne mal sehen. »

            Christian Ringler

            <time class="post-date" datetime="2017-08-01">01 August 2017</time>

        Page 1 of 1

 © 2017

Proudly published with HubPress


text:
package com.rincon.testharness;

/**
 * @author David Moss (dmm@rincon.com)
 */

public class TestHarnessCommands {
	public static final byte CMD_START = 50;
	public static final byte CMD_PING = 51;
	public static final byte CMD_DONE = 52;
	public static final byte CMD_BLOCKED = 53;
}


text:
@* dynamics loop form *@

@()

<form method="POST" action="ac-loop">
  @dynQueries()

      Percentage probability of extending presentation<input name="pres-cntn" type="number" value="70">
      Percentage probability of extending word<input name="word-cntn" type="number" value="70">

</form>


text:
/**
 * @author Sean sean.snow@live.com
 * @date 2015/12/27
 */

import StringBuilder from '../../lang/StringBuilder';

(() => {

    let sb = new StringBuilder();

    sb.append(123);
    console.log(sb.toString());
    console.log(sb.length())

})();


text:
import { isDefined, isString, cleanPath } from "../util";
import { HistoryMode } from "./historyMode";
import { routes } from "./router";
import { routeLink } from "./routeLink";

function formatUrl(value: string): string {
    // format base path url "http://localhost:3000/" -> "http://localhost:3000" in order to add short url
    return value.replace(/\/$/, "");
}

export class Html5 extends HistoryMode {
    constructor() {
        super();
    }

    onLoad(fn: Function): void {
        let url = window.location.href;
        let path = this.getPath(this.baseHref, url);
        fn({ url, path });
    }

    onChange(fn: Function): void {
        window.onpopstate = (e) => {
            fn(e.state);
        };
    }

    checkChanged(infos: any): void {
        this.check(infos.url, infos.path, true, (to) => {
            this.current = to;
            this.onSuccess(to);
        }, (event) => {
            // Error
            window.history.pushState(this.getState(), null, this.current.url);
            if (this.onError) { this.onError(event); }
        });
    }

    onDemand(url: string, replace?: boolean): void {
        let path = this.getPath(this.baseHref, url);
        this.check(url, path, replace, (to) => {
            this.current = to;
            if (replace) { window.history.replaceState(this.getState(), null, url); }
            else { window.history.pushState(this.getState(), null, url); }
            this.onSuccess(to);
        }, (event) => {
            // Error
            if (this.onError) { this.onError(event); }
        });
    }

    subscribe(onSuccess: Function, onError?: Function): void {
        this.onSuccess = onSuccess;
        this.onError = onError;

        this.onLoad((infos) => {
            this.check(infos.url, infos.path, true, (to) => {
                this.current = to;
                window.history.replaceState(this.getState(), null, this.current.url);
                this.onSuccess(to);
            }, (event) => {
                // Error
                if (this.onError) { this.onError(event); }
            });
        });

        this.onChange((infos) => {
            this.checkChanged(infos);
        });

        routeLink.subscribe((url) => {
            this.onDemand(url);
        });
    }

    getState(): any {
        return { url: this.current.url, path: this.current.path, name: this.current.name };
    }

    getPath(baseHref: string, url: string): string {
        /*
            base path:
            - http://mysite.com/
            home:
            - http://mysite.com/ --> remove base path ""
            other:
            - http://mysite.com/posts/10 --> remove base path "posts/10"
        */
        if (url.indexOf(baseHref) !== -1) {
            let replacement = /\/$/.test(baseHref) ? "/" : "";
            let result = url.replace(baseHref, replacement);
            if (result === "") { return "/"; }
            else {
                return cleanPath(result);
            }
        }
        else {
            return cleanPath(url);
        }
    }

    getUrl(baseHref: string, source: string): string {
        // source is path or url ?
        return source.indexOf(baseHref) !== -1 ? source : formatUrl(baseHref) + source;
    }
}


text:
using namespace PaintsNow;
using namespace PaintsNow::NsMythForest;

RenderFlowComponent::RenderFlowComponent() {}

TObject<IReflect>& RenderFlowComponent::operator () (IReflect& reflect) {
	ReflectClass(RenderFlowComponent);

	return *this;
}

void RenderFlowComponent::AddNode(RenderStage* stage) {
	Graph<RenderStage>::AddNode(stage);
}

void RenderFlowComponent::RemoveNode(RenderStage* stage) {
	// removes all symbols related with stage ...
	for (std::map<String, RenderStage::Port*>::const_iterator it = stage->GetPortMap().begin(); it != stage->GetPortMap().end(); ++it) {
		RenderStage::Port* port = it->second;
		for (std::set<String>::const_iterator it = port->publicSymbols.begin(); it != port->publicSymbols.end(); ++it) {
			symbolMap.erase(*it);
		}

		port->publicSymbols.clear();
	}

	Graph<RenderStage>::RemoveNode(stage);
}

RenderStage::Port* RenderFlowComponent::ImportSymbol(const String& symbol) {
	std::map<String, std::pair<RenderStage*, String> >::const_iterator s = symbolMap.find(symbol);
	if (s != symbolMap.end()) {
		return (*s->second.first)[s->second.second];
	} else {
		return nullptr;
	}
}

bool RenderFlowComponent::ExportSymbol(const String& symbol, RenderStage* renderStage, const String& port) {
	RenderStage::Port* p = (*renderStage)[port];
	if (p != nullptr) {
		std::map<String, std::pair<RenderStage*, String> >::const_iterator s = symbolMap.find(symbol);

		if (s != symbolMap.end()) {
			// remove old entry
			RenderStage::Port* port = (*s->second.first)[s->second.second];

			if (port != nullptr) {
				port->publicSymbols.erase(symbol);
			}
		}

		p->publicSymbols.insert(port);
		symbolMap[symbol] = std::make_pair(renderStage, port);
		return true;
	} else {
		return false;
	}
}

struct CallBatch {
public:
	typedef IRenderStage Node;
	CallBatch(std::vector<std::vector<Node*> >& r) : result(r) {}
	// once item
	bool operator () (Node* stage) {
		batch.push_back(stage);
		return true;
	}

	// once batch
	bool operator () () {
		result.push_back(batch);
		batch.clear();
		return true;
	}

	std::vector<Node*> batch;
	std::vector<ZRenderFlow::Milestone>& result;
};

void RenderFlowComponent::UpdateCacheStages() {
	std::vector<ZRenderFlow::Milestone> result;
	CallBatch batch(result);
	IterateTopological(batch, batch);

	std::swap(result, cachedRenderStages);
}


text:
package wsserver;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebService
@SOAPBinding(style=SOAPBinding.Style.RPC)
public class Invoice {
	public String get_invoice_date_by_id(String id) {
		// Simulate the service
		SimpleDateFormat format_date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    	Date now = new Date();
    	return format_date.format(now);
	}
}


text:
import hammerhead from '../deps/hammerhead';
import testCafeCore from '../deps/testcafe-core';
import { ClickOptions } from '../../../test-run/commands/options';
import VisibleElementAutomation from './visible-element-automation';
import ClickAutomation from './click';
import AutomationSettings from '../settings';

const featureDetection = hammerhead.utils.featureDetection;
const browserUtils     = hammerhead.utils.browser;
const eventSimulator   = hammerhead.eventSandbox.eventSimulator;

const eventUtils = testCafeCore.eventUtils;
const delay      = testCafeCore.delay;

const FIRST_CLICK_DELAY = featureDetection.isTouchDevice ? 0 : 160;

export default class DblClickAutomation extends VisibleElementAutomation {
    constructor (element, clickOptions) {
        super(element, clickOptions);

        this.modifiers = clickOptions.modifiers;
        this.caretPos  = clickOptions.caretPos;
        this.speed     = clickOptions.speed;

        this.automationSettings = new AutomationSettings(this.speed);

        this.offsetX = clickOptions.offsetX;
        this.offsetY = clickOptions.offsetY;

        this.eventArgs = null;

        this.eventState = {
            dblClickElement: null
        };
    }

    _firstClick (useStrictElementCheck) {
        // NOTE: we should always perform click with the highest speed
        const clickOptions = new ClickOptions(this.options);

        clickOptions.speed = 1;

        const clickAutomation = new ClickAutomation(this.element, clickOptions);

        clickAutomation.on(clickAutomation.TARGET_ELEMENT_FOUND_EVENT, e => this.emit(this.TARGET_ELEMENT_FOUND_EVENT, e));

        return clickAutomation.run(useStrictElementCheck)
            .then(clickEventArgs => {
                return delay(FIRST_CLICK_DELAY).then(() => clickEventArgs);
            });
    }

    _secondClick (eventArgs) {
        //NOTE: we should not call focus after the second mousedown (except in IE) because of the native browser behavior
        if (browserUtils.isIE)
            eventUtils.bind(document, 'focus', eventUtils.preventDefault, true);

        const clickOptions = new ClickOptions({
            offsetX:   eventArgs.screenPoint.x,
            offsetY:   eventArgs.screenPoint.y,
            caretPos:  this.caretPos,
            modifiers: this.modifiers,
            speed:     1
        });

        const clickAutomation = new ClickAutomation(document.documentElement, clickOptions);

        return clickAutomation.run()
            .then(clickEventArgs => {
                // NOTE: We should raise the `dblclick` event on an element that
                // has been actually clicked during the second click automation.
                this.eventState.dblClickElement = clickAutomation.eventState.clickElement;

                if (browserUtils.isIE)
                    eventUtils.unbind(document, 'focus', eventUtils.preventDefault, true);

                return clickEventArgs;
            });
    }

    _dblClick (eventArgs) {
        if (this.eventState.dblClickElement)
            eventSimulator.dblclick(this.eventState.dblClickElement, eventArgs.options);
    }

    run (useStrictElementCheck) {
        // NOTE: If the target element is out of viewport the firstClick sub-automation raises an error
        return this
            ._firstClick(useStrictElementCheck)
            .then(eventArgs => this._secondClick(eventArgs))
            .then(eventArgs => this._dblClick(eventArgs));
    }
}


text:
import logging

from rss_scrapper.tasks.task import Task

logger = logging.getLogger(__name__)

class ExecuteTask(Task):
    name = "execute"

    tasks = []

    def init(self, tasks=None):
        if tasks is not None:
            self.tasks = tasks

    def init_conf(self, conf):
        tasks = self.create_subtasks(conf)

        self.init(tasks)

    def do_execute(self, data):
        return self.execute_tasks(self.tasks, data)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Kendrick Lo's Portfolio</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/stylish-portfolio.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

                Home

                About

                Skills

                Portfolio

                Contact

Kendrick Lo

Software Engineer

            Learn More

About Me

                    I am an avid sports fan, musician, dog dad, knowledge seeker, critical thinker, and a problem solver.

                    After graduating from Purdue University with degrees in Actuarial Science and Applied Statistics, I worked as an auditor in the healthcare industry. While working as an auditor, I found that my interests started to shift. I've always enjoyed building things and understanding how they work inside and out which is what led me to start learning how to code. After taking some computer science courses during my undergraduate studies and then taking more classes later at IUPUI (Indiana University Purdue University Indianapolis) while I worked, I stumbled upon The Iron Yard which offered a 12-week immersive code camp.

                    Going through The Iron Yard has been one of the most valuable experiences. Through their back end engineering course, I've met and worked with diverse and wonderful individuals and crafted a foundation to pursue a career I am passionate about. I'm excited to be able to continue to learn and can't wait to use my skills to contribute in the workplace.

Skills

                                    Ruby on Rails

                                    JavaScript

                                    HTML & CSS

                                    PostgreSQL

My Work

Artist Assemble

Artist Assemble is a platform to bring together musicians to turn their ideas into reality

                               Website
                               Github

Corgi Shark

Corgi Shark is a full-stack Rails blog site dedicated to the majestic Corgi

                                 Website
                                 Github

Galleria

Galleria is a photo gallery app built with using full-stack Rails

                                 Website
                                 Github

Chirpy

Chirpy is a twitter clone built with a Rails API, HTML, and JavaScript

                                 Website
                                 Github

                    View More on Github

Resume

                    View

Contact

 (219) 617-2600

 kendrick.t.lo@gmail.com


text:
module Azure::AnalysisServices::Mgmt::V2017_08_01_beta
  module Models
    #
    # The gateway details.
    #
    class GatewayDetails

      include MsRestAzure

      # @return [String] Gateway resource to be associated with the server.
      attr_accessor :gateway_resource_id

      # @return [String] Gateway object id from in the DMTS cluster for the
      # gateway resource.
      attr_accessor :gateway_object_id

      # @return [String] Uri of the DMTS cluster.
      attr_accessor :dmts_cluster_uri

      #
      # Mapper for GatewayDetails class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'GatewayDetails',
          type: {
            name: 'Composite',
            class_name: 'GatewayDetails',
            model_properties: {
              gateway_resource_id: {
                client_side_validation: true,
                required: false,
                serialized_name: 'gatewayResourceId',
                type: {
                  name: 'String'
                }
              },
              gateway_object_id: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'gatewayObjectId',
                type: {
                  name: 'String'
                }
              },
              dmts_cluster_uri: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'dmtsClusterUri',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
    // Set Option Module
    // =================

    // Set Option
    // ----------
    //      Accepts an string key, a value, and a callback function to replace a single
    //      property of the plugin options object

    selectBoxIt.setOption = function(key, value, callback) {

        var self = this;

        //Makes sure a string is passed in
        if($.type(key) === "string") {

            // Sets the plugin option to the new value provided by the user
            self.options[key] = value;

        }

        // Rebuilds the dropdown
        self.refresh(function() {

            // Provide callback function support
            self._callbackSupport(callback);

        }, true);

        // Maintains chainability
        return self;

    };


text:
require 'spec_helper'

describe Mongo::Error::OperationFailure do

  describe '#write_concern_error' do
    # Fail point will work on 4.0 mongod but requires 4.2 for mongos
    min_server_fcv '4.2'
    # Fail point must be set on the same server to which the query is sent
    require_no_multi_mongos

    # https://github.com/mongodb/specifications/commit/7745234f93039a83ae42589a6c0cdbefcffa32fa
    let(:fail_point_command) do
     {
       "configureFailPoint": "failCommand",
       "data": {
         "failCommands": ["insert"],
         "writeConcernError": {
           "code": 100,
           "codeName": "UnsatisfiableWriteConcern",
           "errmsg": "Not enough data-bearing nodes",
           "errInfo": {
             "writeConcern": {
               "w": 2,
               "wtimeout": 0,
               "provenance": "clientSupplied"
             }
           }
         }
       },
       "mode": { "times": 1 }
     }
    end

    it 'exposes all server-provided fields' do
      authorized_client.use('admin').command(fail_point_command)

      begin
        authorized_client['foo'].insert_one(test: 1)
      rescue Mongo::Error::OperationFailure => exc
        expect(exc.details).to eq(exc.document['writeConcernError']['errInfo'])
        expect(exc.server_message).to eq(exc.document['writeConcernError']['errmsg'])
        expect(exc.code).to eq(exc.document['writeConcernError']['code'])
      else
        fail 'Expected an OperationFailure'
      end

      exc.write_concern_error_document.should == {
        'code' => 100,
        'codeName' => 'UnsatisfiableWriteConcern',
        'errmsg' => 'Not enough data-bearing nodes',
        'errInfo' => {
          'writeConcern' => {
            'w' => 2,
            'wtimeout' => 0,
            'provenance' => 'clientSupplied',
          },
        },
      }
    end
  end

  describe 'WriteError details' do
    min_server_fcv '5.0'

    let(:subscriber) { Mrss::EventSubscriber.new }

    let(:subscribed_client) do
      authorized_client.tap do |client|
        client.subscribe(Mongo::Monitoring::COMMAND, subscriber)
      end
    end

    let(:collection_name) { 'write_error_prose_spec' }

    let(:collection) do
      subscribed_client[:collection_name].drop
      subscribed_client[:collection_name,
      {
        'validator' => {
          'x' => { '$type' => 'string' },
        }
      }].create
      subscribed_client[:collection_name]
    end

    context 'when there is a write error' do
      it 'succeeds and prints the error' do
        begin
          collection.insert_one({x: 1})
        rescue Mongo::Error::OperationFailure => e
          insert_events = subscriber.succeeded_events.select { |e| e.command_name == "insert" }
          expect(insert_events.length).to eq 1
          expect(e.message).to match(/\[#{e.code}(:.*)?\].+ -- .+/)

          expect(e.details).to eq(e.document['writeErrors'][0]['errInfo'])
          expect(e.server_message).to eq(e.document['writeErrors'][0]['errmsg'])
          expect(e.code).to eq(e.document['writeErrors'][0]['code'])

          expect(e.code).to eq 121
          expect(e.details).to eq(insert_events[0].reply['writeErrors'][0]['errInfo'])
        else
          fail 'Expected an OperationFailure'
        end
      end
    end
  end
end


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="joust">

        <roleset framnet="" id="joust.01" name="horses and lances" vncls="36.4-1">
            <roles>
                <role descr="knight in shining armor" f="" n="0">
                    <vnrole vncls="36.4-1" vntheta="actor1"/>
                </role>
                <role descr="target" f="" n="1">
                    <vnrole vncls="36.4-1" vntheta="topic"/>
                </role>
                <note/>
            </roles>

            <example name="agentive" src="" type="">
                <inflection aspect="progressive" form="participle" person="ns" tense="ns" voice="active"/>
                <text>Amid a riot of jousting knights, circus clowns, gold-leaf
                    centurions and creatures of the wild, lesser competitors will
                    fall.
                </text>
                <rel f="">jousting</rel>
                <arg f="" n="0">knights</arg>
                <note/>
            </example>

            <example name="Don Quixote" src="" type="">
                <inflection aspect="progressive" form="participle" person="ns" tense="ns" voice="active"/>
                <text>John-1 spent a lovely Saturday afternoon *trace*-1 jousting at windmills.</text>
                <arg f="" n="0">*trace*</arg>
                <rel f="">jousting</rel>
                <arg f="" n="1">at windmills</arg>
                <note/>
            </example>

            <note/>
        </roleset>
        <note>Frames file for 'joust' based on sentences in wsj.  Verbnet entry 36.1.</note>
    </predicate>
    <note/>
</frameset>


text:
package org.apache.camel.component.bean.issues;

import org.apache.camel.BeanScope;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.builder.AdviceWith;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Test;

public class BeanThisAdviceWithIssueTest extends ContextTestSupport {

    private static final String ROUTE_ID = "mytest";

    @Override
    public boolean isUseRouteBuilder() {
        return false;
    }

    @Test
    public void shouldFire() throws Exception {
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:mytest").id(ROUTE_ID).bean(this, "hello", BeanScope.Prototype).to("log:out");
            }

            public void hello(final Exchange exchange) {
            }
        });

        AdviceWith.adviceWith(context.getRouteDefinitions().get(0), context, new AdviceWithRouteBuilder() {
            @Override
            public void configure() throws Exception {
                weaveAddLast().to("mock:extract");
            }
        });

        context.start();

        // given
        final MockEndpoint myMock = getMockEndpoint("mock:extract");

        myMock.expectedMessageCount(1);

        // when
        template.sendBody("direct:mytest", "test");

        // then
        myMock.assertIsSatisfied();
    }
}


text:
/**
 * Created by wok on 08.02.16.
 *
 */

class TaskRepeater {
    constructor(templateTask) {
        this._cloneTask = new Task();
        this._cloneTask.cloneFromTask (templateTask);
        this._calcRepeatedDates();
        this._cloneTask.save();
    }

    get clone() {
        return this._cloneTask;
    }

    // ###### PRIVATE ##############

    _calcRepeatedDates() {
        if (this._cloneTask.repeat && this._cloneTask.repeat.repeat) {
            if (this._cloneTask.repeat.everyInterval == "day") {
                this._calcRepeatedDays(this._cloneTask.repeat.everyNumber);
            }
            if (this._cloneTask.repeat.everyInterval == "week") {
                this._calcRepeatedDays(7 * this._cloneTask.repeat.everyNumber);
            }
            if (this._cloneTask.repeat.everyInterval == "month") {
                this._calcRepeatedMonth(this._cloneTask.repeat.everyNumber);
            }
            if (this._cloneTask.repeat.everyInterval == "year") {
                this._calcRepeatedYear(this._cloneTask.repeat.everyNumber);
            }
        }
    };

    _calcRepeatedDays (dayDelta) {
        dayDelta = dayDelta * 1;    // force as number!
        var groundDate = new Date();    // if (this._cloneTask.repeat.repeatOnCompleteDate) ...
        if (this._cloneTask.repeat.repeatOnCompleteDate && !this._cloneTask.startDate && !this._cloneTask.dueDate) {
            this._cloneTask.startDate = groundDate;
        }
        if (this._cloneTask.startDate && !this._cloneTask.dueDate) {
            if (this._cloneTask.repeat.repeatOnTaskDate) {
                groundDate = this._cloneTask.startDate;
            }
            this._cloneTask.startDate = groundDate;   // setDate can't work across month. We must pull it up to grounddate, first.
            this._cloneTask.startDate.setDate(groundDate.getDate() + dayDelta);
        }
        if (!this._cloneTask.startDate && this._cloneTask.dueDate) {
            if (this._cloneTask.repeat.repeatOnTaskDate) {
                groundDate = this._cloneTask.dueDate;
            }
            this._cloneTask.dueDate = groundDate;   // setDate can't work across month. We must pull it up to grounddate, first.
            this._cloneTask.dueDate.setDate(groundDate.getDate() + dayDelta);
        }
        if (this._cloneTask.startDate && this._cloneTask.dueDate) {
            if (this._cloneTask.repeat.repeatOnTaskDate) {
                groundDate = this._cloneTask.dueDate;
            }
            var startToDueTimeDiff = this._cloneTask.dueDate.getTime() - this._cloneTask.startDate.getTime()
            this._cloneTask.dueDate = groundDate;   // setDate can't work across month. We must pull it up to grounddate, first.
            this._cloneTask.dueDate.setDate(groundDate.getDate() + dayDelta);
            this._cloneTask.startDate.setTime(this._cloneTask.dueDate.getTime() - startToDueTimeDiff);
        }
    };

    _calcRepeatedMonth(monthDelta) {
        monthDelta = monthDelta * 1;    // force as number!
        var groundDate = new Date();    // if (this._cloneTask.repeat.repeatOnCompleteDate) ...

        if (this._cloneTask.repeat.repeatOnCompleteDate && !this._cloneTask.startDate && !this._cloneTask.dueDate) {
            this._cloneTask.startDate = groundDate;
        }
        if (this._cloneTask.startDate && !this._cloneTask.dueDate) {
            if (this._cloneTask.repeat.repeatOnTaskDate) {
                groundDate = this._cloneTask.startDate;
            }
            this._cloneTask.startDate = groundDate;   // setDate can't work across month. We must pull it up to grounddate, first.
            this._cloneTask.startDate.setMonth(groundDate.getMonth() + monthDelta);
        }
        if (!this._cloneTask.startDate && this._cloneTask.dueDate) {
            if (this._cloneTask.repeat.repeatOnTaskDate) {
                groundDate = this._cloneTask.dueDate;
            }
            this._cloneTask.dueDate = groundDate;   // setDate can't work across month. We must pull it up to grounddate, first.
            this._cloneTask.dueDate.setMonth(groundDate.getMonth() + monthDelta);
        }
        if (this._cloneTask.startDate && this._cloneTask.dueDate) {
            if (this._cloneTask.repeat.repeatOnTaskDate) {
                groundDate = this._cloneTask.dueDate;
            }
            var startToDueTimeDiff = this._cloneTask.dueDate.getTime() - this._cloneTask.startDate.getTime()
            this._cloneTask.dueDate = groundDate;   // setDate can't work across month. We must pull it up to grounddate, first.
            this._cloneTask.dueDate.setMonth(groundDate.getMonth() + monthDelta);
            this._cloneTask.startDate.setTime(this._cloneTask.dueDate.getTime() - startToDueTimeDiff);
        }
    };

    _calcRepeatedYear(yearDelta) {
        yearDelta = yearDelta * 1;    // force as number!
        var groundDate = new Date();    // if (this._cloneTask.repeat.repeatOnCompleteDate) ...

        if (this._cloneTask.repeat.repeatOnCompleteDate && !this._cloneTask.startDate && !this._cloneTask.dueDate) {
            this._cloneTask.startDate = groundDate;
        }
        if (this._cloneTask.startDate && !this._cloneTask.dueDate) {
            if (this._cloneTask.repeat.repeatOnTaskDate) {
                groundDate = this._cloneTask.startDate;
            }
            this._cloneTask.startDate = groundDate;   // setDate can't work across month. We must pull it up to grounddate, first.
            this._cloneTask.startDate.setFullYear(groundDate.getFullYear() + yearDelta);
        }
        if (!this._cloneTask.startDate && this._cloneTask.dueDate) {
            if (this._cloneTask.repeat.repeatOnTaskDate) {
                groundDate = this._cloneTask.dueDate;
            }
            this._cloneTask.dueDate = groundDate;   // setDate can't work across month. We must pull it up to grounddate, first.
            this._cloneTask.dueDate.setFullYear(groundDate.getFullYear() + yearDelta);
        }
        if (this._cloneTask.startDate && this._cloneTask.dueDate) {
            if (this._cloneTask.repeat.repeatOnTaskDate) {
                groundDate = this._cloneTask.dueDate;
            }
            var startToDueTimeDiff = this._cloneTask.dueDate.getTime() - this._cloneTask.startDate.getTime()
            this._cloneTask.dueDate = groundDate;   // setDate can't work across month. We must pull it up to grounddate, first.
            this._cloneTask.dueDate.setFullYear(groundDate.getFullYear() + yearDelta);
            this._cloneTask.startDate.setTime(this._cloneTask.dueDate.getTime() - startToDueTimeDiff);
        }
    };
}

this.TaskRepeater = TaskRepeater;


text:
layout: page_v2
title: Show Multi-Format Ads with Prebid.js
description: Show Multi-Format Ads with Prebid.js
pid: 0
is_top_nav: yeah
top_nav_section: dev_docs
nav_section: prebid-multi-format
sidebarType: 1
---

# Show Multi-Format Ads with Prebid.js
{: .no_toc }

This page has instructions for showing multi-format ads using Prebid.js.

An ad unit is said to be multi-format if it supports at least two of the following media types:

+ Banner
+ Native
+ Video

Once declared, any bidder that supports at least one of the media types can participate in the auction for that ad unit.

{: .alert.alert-info :}
For ad ops setup instructions, see [Setting up Prebid Multi-Format in Google Ad Manager]({{site.baseurl}}/adops/setting-up-prebid-multi-format-in-dfp.html).

* TOC
{:toc}

## How Multi-Format Ads Work

Prebid multi-format ad units allow direct competition between banner, native, and/or video bids.

At a high level, Prebid.js supports multi-format ads as follows:

1. An ad unit may define a [`mediaTypes`](/dev-docs/publisher-api-reference/addAdUnits.html#addAdUnits-MediaTypes) object to specify one or more supported formats and their respective properties.
2. Each bidder specified on a given ad unit will be eligible to bid if the bidder supports at least one of the media types specified via `adUnit.mediaTypes`.
3. Prebid.js sends bid requests to each eligible bidder.

The following key is added to your ad server targeting, and set to the value of the bid response's `mediaType` property.

+ `hb_format`

The ad ops team will reference this key in the ad server to set targeting.  For ad ops setup instructions, see [Setting up Prebid Multi-Format in Google Ad Manager]({{site.baseurl}}/adops/setting-up-prebid-multi-format-in-dfp.html).

## Prerequisites

Keep the following prerequisites in mind during the implementation:

+ Make sure to work with bidders that support demand for the media types you want, particularly native and video.  To see which bidders have native and/or video demand, see [Bidders with Video and Native Demand]({{site.baseurl}}/dev-docs/bidders.html#bidders-with-video-and-native-demand).

## Implementation

This section describes the implementation using code samples, but ignores some of the details that are common to all Prebid.js setups.

### 1. Add multi-format ad units

The ad unit below supports the banner, native, and video media types.

```javascript

    pbjs.addAdUnits({
        code: 'div-banner-outstream-native',
        mediaTypes: {
            banner: {
                sizes: [
                    [300, 250],
                    [300, 50]
                ]
            },
            native: {
                image: {
                    sizes: [300, 250]
                }
            },
            video: {
                context: 'outstream',
                playerSize: [640, 480],
                mimes: ['video/mp4'],
                protocols: [1, 2, 3, 4, 5, 6, 7, 8],
                playbackmethod: [2],
                skip: 1
            },
        },
        bids: [

            {
                bidder: 'bannerBidder',
                params: {
                    placementId: '481'
                }
            },

            {
                bidder: 'nativeBidder',
                params: {
                    titleAsset: '516'
                }
            },

            {
                bidder: 'videoBidder',
                params: {
                    vidId: '234'
                }
            },

        ]
    });
```

### 2. Add your tag to the page body

Add a tag like the following to your page.  Depending on who wins the auction, a banner, outstream, or native ad should serve.

```html
    <div id='div-banner-outstream-native'>
        <p>No response</p>
        <script type='text/javascript'>
            googletag.cmd.push(function () {
                googletag.display('div-banner-outstream-native');
            });
        </script>
    </div>
```

## Working Examples

+ [Multi-Format Example](/dev-docs/examples/multi-format-example.html)

## Related Topics

+ [Setting up Prebid Multi-Format in Google Ad Manager]({{site.baseurl}}/adops/setting-up-prebid-multi-format-in-dfp.html)


text:
Customizing Flask-User
======================
.. include:: includes/submenu_defs.rst
.. include:: includes/customizing_submenu.rst

--------

From the very beginning, Flask-User was specifically designed to be fully customizable
in addition to being secure and reliable.

- Flask-User can be configured through :doc:`configuring_settings`.
    - Enabling and disabling of features
    - General settings
    - Token expiration settings
    - Complete control of Passlib's password hash settings
    - Form URLs
    - Form template file paths
    - Email template file paths

- :doc:`customizing_forms`
    - :ref:`CustomizingFormTemplates`
    - :ref:`CustomizingFormClasses`
    - :ref:`CustomizingFormValidators`
    - :ref:`CustomizingFormViews`

- :doc:`customizing_emails`
    - :ref:`CustomizingEmailTemplates`

- And then there are :doc:`customizing_advanced`
    - :ref:`CustomizingManagers`
    - :ref:`CustomDbAdapters`
    - :ref:`CustomEmailAdapters`

--------

.. include:: includes/submenu_defs.rst
.. include:: includes/customizing_submenu.rst


text:
require 'digest/sha1'

class <%= class_name %> < ActiveRecord::Base
  include Authentication
  include Authentication::ByPassword

  validates_presence_of     :login
  validates_length_of       :login,    :within => 3..40
  validates_uniqueness_of   :login

  validates_presence_of     :nome
  validates_length_of       :nome,      :maximum => 40
  validates_length_of       :sobrenome, :maximum => 60

  # HACK HACK HACK -- how to do attr_accessible from here?
  # prevents a user from submitting a crafted form that bypasses activation
  # anything else you want your user to change should be added here.
  attr_accessible :login, :nome, :sobrenome, :password, :password_confirmation, :role, :role_id

  # Authenticates a user by their login name and unencrypted password.  Returns the user or nil.
  #
  # uff.  this is really an authorization, not authentication routine.
  # We really need a Dispatch Chain here or something.
  # This will also let us return a human error message.
  #
  def self.authenticate(login, password)
    return nil if login.blank? || password.blank?
    u = find_by_login(login.downcase) # need to get the salt
    u && u.authenticated?(password) ? u : nil
  end

  def login=(value)
    write_attribute :login, (value ? value.downcase : nil)
  end
end