text:
const express = require('express'),
    router = express.Router(),
    path = require('path'),
    fs = require('fs'),
    cheerio = require('cheerio'),
    common = require('../common.js')

/**
  * /api/page/save
  * @param {Object} req - http://expressjs.com/api.html#req
  * @param {Object} res - http://expressjs.com/api.html#res
  * @param {Object} next - required for middleware
  */
router.post('/save', async (req, res) => {

    // auth
    if(!req.user) {
        res.status(400).send('Not authenticated')
        return
    }

    let body = req.body,
        content = body.html,
        url = body.url,
        template = 'default'

    console.log('[debug] save', req.body)

    try {

        // get existing page
        let html = fs.readFileSync(`${global.appRoot}/site/${url}`, 'utf8')

        // load html
        let $ = cheerio.load(html)

        // replace main
        $('[role="main"]').html(content)

        // save file
        fs.writeFileSync(`${global.appRoot}/site/${url}`, $.html(), 'utf8')

        // get page
        let page = common.retrievePage(url)

        console.log('[debug] page', page)

        // publish page
        if(page != null) {
            common.publishPage(page)

            // generate sitemap
            common.generateSiteMap()
        }

        // send 200
        res.status(200).send('Page saved successfully')

    }
    catch(e) {
        console.log(e)
        res.status(400).send('There was an error saving the page')
    }

})

/**
  * /api/page/list
  * @param {Object} req - http://expressjs.com/api.html#req
  * @param {Object} res - http://expressjs.com/api.html#res
  * @param {Object} next - required for middleware
  */
 router.get('/list', async (req, res) => {

    // auth
    if(!req.user) {
        res.status(400).send('Not authenticated')
        return
    }

    let body = req.body

    console.log('[debug] list', req.body)

    try {

        // get json
        let json = fs.readFileSync(`${global.appRoot}/site/data/pages.json`, 'utf8')

        // send 200
        res.setHeader('Content-Type', 'application/json')
        res.status(200).send(json)

    }
    catch(e) {
        res.status(400).send('There was an error saving the page')
    }

})

/**
  * /api/page/templates/list
  * @param {Object} req - http://expressjs.com/api.html#req
  * @param {Object} res - http://expressjs.com/api.html#res
  * @param {Object} next - required for middleware
  */
 router.post('/templates/list', async (req, res) => {

    // auth
    if(!req.user) {
        res.status(400).send('Not authenticated')
        return
    }

    let body = req.body

    console.log('[debug] list templates', req.body)

    try {

        let files = fs.readdirSync(`${global.appRoot}/site/templates/`), arr = []

        for(let x=0; x<files.length; x++) {

            // get stats for file
            let stats = fs.statSync(`${global.appRoot}/site/templates/${files[x]}`),
                ext = path.extname(`${global.appRoot}/site/templates/${files[x]}`),
                template = ''

            if(stats.isFile()) {

                // check for image
                if(ext == '.html') {
                    template = files[x].replace('.html', '')

                    arr.push(template)
                }
            }
        }

        // send 200
        res.setHeader('Content-Type', 'application/json')
        res.status(200).send(arr)

    }
    catch(e) {
        console.log(e)
        res.status(400).send('There was an error listing the templates')
    }

})

/**
  * /api/page/components/list
  * @param {Object} req - http://expressjs.com/api.html#req
  * @param {Object} res - http://expressjs.com/api.html#res
  * @param {Object} next - required for middleware
  */
 router.post('/components/list', async (req, res) => {

    // auth
    if(!req.user) {
        res.status(400).send('Not authenticated')
        return
    }

    let body = req.body

    console.log('[debug] list components', req.body)

    try {

        let files = fs.readdirSync(`${global.appRoot}/site/components/`), arr = []

        for(let x=0; x<files.length; x++) {

            // get stats for file
            let stats = fs.statSync(`${global.appRoot}/site/components/${files[x]}`),
                ext = path.extname(`${global.appRoot}/site/components/${files[x]}`),
                component = ''

            if(stats.isFile()) {

                // check for image
                if(ext == '.html') {
                    component = files[x].replace('.html', '')

                    arr.push(component)
                }
            }
        }

        // send 200
        res.setHeader('Content-Type', 'application/json')
        res.status(200).send(arr)

    }
    catch(e) {
        console.log(e)
        res.status(400).send('There was an error listing the components')
    }

})

/**
  * /api/page/retrieve
  * @param {Object} req - http://expressjs.com/api.html#req
  * @param {Object} res - http://expressjs.com/api.html#res
  * @param {Object} next - required for middleware
  */
 router.post('/retrieve', async (req, res) => {

    // auth
    if(!req.user) {
        res.status(400).send('Not authenticated')
        return
    }

    let body = req.body,
        url = body.url

    console.log('[debug] list', req.body)

    try {

        // get json
        let json = fs.readFileSync(`${global.appRoot}/site/data/pages.json`, 'utf8'),
            objs = JSON.parse(json)

        for(let x=0; x<objs.length; x++) {
            if(objs[x].url == url) {
                // send 200
                res.setHeader('Content-Type', 'application/json')
                res.status(200).send(JSON.stringify(objs[x]))
            }
        }

        res.status(400).send('No page found')

    }
    catch(e) {
        res.status(400).send('There was an error saving the page')
    }

})

/**
  * /api/page/elements.list
  * @param {Object} req - http://expressjs.com/api.html#req
  * @param {Object} res - http://expressjs.com/api.html#res
  * @param {Object} next - required for middleware
  */
 router.get('/elements/list', async (req, res) => {

    // auth
    if(!req.user) {
        res.status(400).send('Not authenticated')
        return
    }

    let body = req.body

    console.log('[debug] list elemenets', req.body)

    try {

        // get json
        let json = fs.readFileSync(`${global.appRoot}/site/data/elements.json`, 'utf8')

        // send 200
        res.setHeader('Content-Type', 'application/json')
        res.status(200).send(json)

    }
    catch(e) {
        res.status(400).send('There was an error saving the page')
    }

})

/**
  * /api/page/add
  * @param {Object} req - http://expressjs.com/api.html#req
  * @param {Object} res - http://expressjs.com/api.html#res
  * @param {Object} next - required for middleware
  */
 router.post('/add', async (req, res) => {

    // auth
    if(!req.user) {
        res.status(400).send('Not authenticated')
        return
    }

    let user = common.findUser(req.user.email),
        firstName = "Default",
        lastName = "User"

    // set first and last name
    if(user.firstName) firstName = user.firstName
    if(user.lastName) lastName = user.lastName

    console.log('[debug] user', req.user)

    let body = req.body,
        name = body.name,
        url = body.url,
        type = body.type,
        description = body.description,
        template = 'default'

    // clear leading slash
    if (url.charAt(0) == "/") url = url.substr(1)

    // remove file extension
    if(url.indexOf('.htm') != -1) url = url.split('.').slice(0, -1).join('.')

    // add html extension
    url = url += '.html'

    console.log('[debug] save', req.body)

    try {

        // settings
        let settings = {
            "name": name,
            "callout": '',
            "description": description,
            "url": url,
            "type": type,
            "template": template,
            "text": "",
            "keywords": "",
            "tags": "",
            "image": "",
            "location": "",
            "language": "en",
            "direction": "ltr",
            "firstName": firstName,
            "lastName": lastName,
            "lastModifiedBy": firstName + ' ' + lastName,
            "lastModifiedDate": (new Date()).toUTCString(),
            "customHeader": "",
            "customFooter": ""
        }

        // get json
        let json = fs.readFileSync(`${global.appRoot}/site/data/pages.json`, 'utf8')

        // read json
        let pages = JSON.parse(json)

        // check to see if page exists
        for(let x=0; x<pages.length; x++) {
            if(pages[x].url == url) {
                res.status(400).send('Page already exists')
                return
            }
        }

        // publish page
        common.publishPage(settings)

        // generate sitemap
        common.generateSiteMap()

        // send 200
        res.setHeader('Content-Type', 'application/json')
        res.status(200).send('Ok')

    }
    catch(e) {
        console.log(e)
        res.status(400).send('There was an error saving the page')
    }

})

/**
  * /api/page/settings
  * @param {Object} req - http://expressjs.com/api.html#req
  * @param {Object} res - http://expressjs.com/api.html#res
  * @param {Object} next - required for middleware
  */
 router.post('/settings', async (req, res) => {

    // auth
    if(!req.user) {
        res.status(400).send('Not authenticated')
        return
    }

    let user = common.findUser(req.user.email),
        firstName = "Default",
        lastName = "User"

    // set first and last name
    if(user.firstName) firstName = user.firstName
    if(user.lastName) lastName = user.lastName

    console.log('[debug] user', req.user)

    let body = req.body,
        url = body.url,
        name = body.name,
        callout = body.callout,
        description = body.description,
        keywords = body.keywords,
        tags = body.tags,
        location = body.location,
        image = body.image,
        language = body.language,
        direction = body.direction,
        template = body.template,
        customHeader = body.customHeader,
        customFooter = body.customFooter,
        settings = null

    try {

        // get json
        let json = fs.readFileSync(`${global.appRoot}/site/data/pages.json`, 'utf8'),
            objs = JSON.parse(json)

        for(let x=0; x<objs.length; x++) {
            if(objs[x].url == url) {

                // set settings
                settings = objs[x]

                // update settings
                settings.name = name
                settings.callout = callout
                settings.description = description
                settings.keywords = keywords
                settings.tags = tags
                settings.location = location
                settings.image = image
                settings.language = language
                settings.direction = direction
                settings.template = template
                settings.customHeader = customHeader
                settings.customFooter = customFooter

                // republish
                common.publishPage(settings)

                // generate sitemap
                common.generateSiteMap()

                // send 200
                res.setHeader('Content-Type', 'application/json')
                res.status(200).send(JSON.stringify(settings))
            }
        }

        res.status(400).send('No page found')

    }
    catch(e) {
        console.log(e)
        res.status(400).send('There was an error saving the page')
    }

})

/**
  * /api/page/remove
  * @param {Object} req - http://expressjs.com/api.html#req
  * @param {Object} res - http://expressjs.com/api.html#res
  * @param {Object} next - required for middleware
  */
 router.post('/remove', async (req, res) => {

    // auth
    if(!req.user) {
        res.status(400).send('Not authenticated')
        return
    }

    let user = common.findUser(req.user.email),
        firstName = "Default",
        lastName = "User"

    // set first and last name
    if(user.firstName) firstName = user.firstName
    if(user.lastName) lastName = user.lastName

    console.log('[debug] user', req.user)

    let body = req.body,
        url = body.url

    // clear leading slash
    if (url.charAt(0) == "/") url = url.substr(1)

    // remove file extension
    if(url.indexOf('.htm') != -1) url = url.split('.').slice(0, -1).join('.')

    // add html extension
    url = url += '.html'

    console.log('[debug] remove', req.body)

    try {

        // get json
        let json = fs.readFileSync(`${global.appRoot}/site/data/pages.json`, 'utf8')

        // read json
        let pages = JSON.parse(json)

        // remove page
        for(let x=0; x<pages.length; x++) {
            if(pages[x].url == url) {
                pages.splice(x, 1);
            }
        }

        console.log('[debug] removing', `${global.appRoot}/site/${url}`)

        // remove file
        fs.unlinkSync(`${global.appRoot}/site/${url}`)

         // save json file
        fs.writeFileSync(`${global.appRoot}/site/data/pages.json`, JSON.stringify(pages), 'utf8')

        // send 200
        res.setHeader('Content-Type', 'application/json')
        res.status(200).send('Ok')

    }
    catch(e) {
        console.log(e)
        res.status(400).send('There was an error saving the page')
    }

})

module.exports = router


text:
package com.yahoo.sketches;

/**
 * Common utility functions.
 *
 * @author Lee Rhodes
 */
public final class Util {

  private Util() {}

  /**
   * The default nominal entries is provided as a convenience for those cases where the
   * nominal sketch size in number of entries is not provided.
   * A sketch of 4096 entries has a Relative Standard Error (RSE) of +/- 1.56% at a confidence of
   * 68%; or equivalently, a Relative Error of +/- 3.1% at a confidence of 95.4%.
   * See Default Nominal Entries
   */
  public static final int DEFAULT_NOMINAL_ENTRIES = 4096;

  /**
   *
The seed 9001 used in the sketch update methods is a prime number that
   * was chosen very early on in experimental testing. Choosing a seed is somewhat arbitrary, and
   * the author cannot prove that this particular seed is somehow superior to other seeds.  There
   * was some early internet disussion that a seed of 0 did not produce as clean avalanche diagrams
   * as non-zero seeds, but this may have been more related to the MurmurHash2 release, which did
   * have some issues. As far as the author can determine, MurmurHash3 does not have these problems.
   *
   *
In order to perform set operations on two sketches it is critical that the same hash
   * function and seed are identical for both sketches, otherwise the assumed 1:1 relationship
   * between the original source key value and the hashed bit string would be violated. Once
   * you have developed a history of stored sketches you are stuck with it.
   * See Default Update Seed
   */
  public static final long DEFAULT_UPDATE_SEED = 9001L;

  /**
   * The java line separator character.
   */
  public static final String LS = System.getProperty("line.separator");

  /**
   * Checks if parameter v is a multiple of 8 and greater than zero.
   * @param v The parameter to check
   * @param argName This name will be part of the error message if the check fails.
   */
  public static void checkIfMultipleOf8AndGT0(long v, String argName) {
    if (((v & 0X7L) == 0L) && (v > 0L)) {
      return;
    }
    throw new IllegalArgumentException("The value of the parameter \"" + argName
      + "\" must be a positive multiple of 8 and greater than zero: " + v);
  }

  /**
   * Returns true if v is a multiple of 8 and greater than zero
   * @param v The parameter to check
   * @return true if v is a multiple of 8 and greater than zero
   */
  public static boolean isMultipleOf8AndGT0(long v) {
    return (((v & 0X7L) == 0L) && (v > 0L));
  }

  /**
   * Returns true if argument is exactly a positive power of 2 and greater than zero.
   *
   * @param v The input argument.
   * @return true if argument is exactly a positive power of 2 and greater than zero.
   */
  public static boolean isPowerOf2(int v) {
    return (v > 0) && ((v & (v - 1)) == 0); //or (v > 0) && ((v & -v) == v)
  }

  /**
   * Checks the given parameter to make sure it is positive, an integer-power of 2 and greater than
   * zero.
   *
   * @param v The input argument.
   * @param argName Used in the thrown exception.
   */
  public static void checkIfPowerOf2(int v, String argName) {
    if ((v > 0) && ((v & (v - 1)) == 0)) {
      return;
    }
    throw new IllegalArgumentException("The value of the parameter \"" + argName
        + "\" must be a positive integer-power of 2" + " and greater than 0: " + v);
  }

  /**
   * Checks the given parameter to make sure it is positive and between 0.0 inclusive and 1.0
   * inclusive.
   *
   * @param p See Sampling Probability, p
   * @param argName Used in the thrown exception.
   */
  public static void checkProbability(double p, String argName) {
    if ((p >= 0.0) && (p <= 1.0)) {
      return;
    }
    throw new IllegalArgumentException("The value of the parameter \"" + argName
        + "\" must be between 0.0 inclusive and 1.0 inclusive: " + p);
  }

  private static final int IntTopPwrOf2 = 1 << 30; //= #Bits -2
  private static final int MaxIntShifts = 16; //= #Bits / 2

  /**
   * Computes the ceiling power of 2 within the range [1, 2^30]. This is the smallest positive power
   * of 2 that equal to or greater than the given n. This algorithm finds the ceiling in a maximum
   * of lg(32)=5 iterations.

   * For:
   *

   *
n ≤ 1: returns 1

   *
2^30 ≤ n ≤ 2^31 -1 : returns 2^30

   *
n == a power of 2 : returns n

   *
otherwise returns the smallest power of 2 greater than n

   *

   *
   * @param n The input argument.
   * @return the ceiling power of 2.
   */
  public static int ceilingPowerOf2(int n) {
    if (n <= 1) {
      return 1;
    }
    if (n >= IntTopPwrOf2) {
      return IntTopPwrOf2;
    }
    n-- ;
    for (int i = 1; i <= MaxIntShifts; i <<= 1) {
      int m = (n | (n >> i));
      if (n == m) {
        break;
      }
      n = m;
    }
    return ++n;
  }

  /**
   * Computes the floor power of 2 within the range [1, 2^30]. This is the largest positive power of
   * 2 that equal to or less than the given n. This algorithm finds the floor in a maximum of
   * lg(32)=5 iterations.

   * For:
   *

   *
n ≤ 1: returns 1

   *
2^30 ≤ n ≤ 2^31 -1 : returns 2^30

   *
n == a power of 2 : returns n

   *
otherwise returns the largest power of 2 less than n

   *

   *
   * @param n The given argument.
   * @return the floor power of 2.
   */
  public static int floorPowerOf2(int n) {
    if (n <= 1) {
      return 1;
    }
    int f = ceilingPowerOf2(n);
    if (f <= n) {
      return f;
    }
    return f >> 1;
  }

  /**
   * Unsigned compare with longs.
   * @param n1 A long to be treated as if unsigned.
   * @param n2 A long to be treated as if unsigned.
   * @return true if n1 > n2.
   */
  public static boolean isLessThanUnsigned(long n1, long n2) {
    return (n1 < n2) ^ ((n1 < 0) != (n2 < 0));
  }

  /**
   * Prepend the given string with zeros.
   * @param s the given string
   * @param fieldLength desired total field length including the string
   * @return a string front padded with zeros.
   */
  public static final String zeroPad(String s, int fieldLength) {
    char[] chArr = s.toCharArray();
    int sLen = chArr.length;
    if (sLen < fieldLength) {
      char[] out = new char[fieldLength];
      int zeros = fieldLength - sLen;
      for (int i=0; i<zeros; i++) {
        out[i] = '0';
      }
      for (int i=zeros; i<fieldLength; i++) {
        out[i] = chArr[i-zeros];
      }
      return String.valueOf(out);
    }
    return s;
  }

}

redpajama_set_name: RedPajamaGithub


text:
@interface HexNode : SKNode

@property (strong, nonatomic) SKShapeNode* hexShapeNode;
@property (readonly, nonatomic) CGPoint center;
@property (assign, nonatomic) CGPoint gamePosition;

@end


text:
require 'rspec'
require 'benchmark'
require_relative '../core_ext'

describe 'Constraining' do

  describe 'integer numbers' do
    it 'should do nothing if number below constraint' do
      v = Vector[0, 0]
      v.constrain(1)
      expect(v.r).to eq 0
    end

    it 'should do nothing if number equals constraint' do
      [Vector[1, 0], Vector[0, 1], Vector[-1, 0], Vector[0, -1]].each { |v|
        v.constrain(1)
        expect(v.r).to eq 1
      }
    end

    it 'should apply constraint' do
      [Vector[1, 1], Vector[-1, -1]].each { |v|
        constrained = v.constrain(1)
        expect(constrained.r).to be_within(Float::EPSILON).of(1)
      }
    end

  end

end


text:
package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"io/ioutil"
	"log"
	"math/rand"
	"net"
	"net/http"
	"runtime"
	"sync"
	"time"

	"code.google.com/p/go.crypto/bcrypt"
	"github.com/codegangsta/martini"
)

type guiError struct {
	Time  time.Time
	Error string
}

var (
	configInSync = true
	guiErrors    = []guiError{}
	guiErrorsMut sync.Mutex
	static       = embeddedStatic()
	staticFunc   = static.(func(http.ResponseWriter, *http.Request, *log.Logger))
)

const (
	unchangedPassword = "--password-unchanged--"
)

func startGUI(cfg GUIConfiguration, m *Model) error {
	l, err := net.Listen("tcp", cfg.Address)
	if err != nil {
		return err
	}

	router := martini.NewRouter()
	router.Get("/", getRoot)
	router.Get("/rest/version", restGetVersion)
	router.Get("/rest/model", restGetModel)
	router.Get("/rest/connections", restGetConnections)
	router.Get("/rest/config", restGetConfig)
	router.Get("/rest/config/sync", restGetConfigInSync)
	router.Get("/rest/system", restGetSystem)
	router.Get("/rest/errors", restGetErrors)
	router.Get("/rest/discovery", restGetDiscovery)

	router.Post("/rest/config", restPostConfig)
	router.Post("/rest/restart", restPostRestart)
	router.Post("/rest/reset", restPostReset)
	router.Post("/rest/shutdown", restPostShutdown)
	router.Post("/rest/error", restPostError)
	router.Post("/rest/error/clear", restClearErrors)
	router.Post("/rest/discovery/hint", restPostDiscoveryHint)

	mr := martini.New()
	if len(cfg.User) > 0 && len(cfg.Password) > 0 {
		mr.Use(basic(cfg.User, cfg.Password))
	}
	mr.Use(static)
	mr.Use(martini.Recovery())
	mr.Use(restMiddleware)
	mr.Action(router.Handle)
	mr.Map(m)

	go http.Serve(l, mr)

	return nil
}

func getRoot(w http.ResponseWriter, r *http.Request) {
	r.URL.Path = "/index.html"
	staticFunc(w, r, nil)
}

func restMiddleware(w http.ResponseWriter, r *http.Request) {
	if len(r.URL.Path) >= 6 && r.URL.Path[:6] == "/rest/" {
		w.Header().Set("Cache-Control", "no-cache")
	}
}

func restGetVersion() string {
	return Version
}

func restGetModel(m *Model, w http.ResponseWriter, r *http.Request) {
	var qs = r.URL.Query()
	var repo = qs.Get("repo")
	var res = make(map[string]interface{})

	for _, cr := range cfg.Repositories {
		if cr.ID == repo {
			res["invalid"] = cr.Invalid
			break
		}
	}

	globalFiles, globalDeleted, globalBytes := m.GlobalSize(repo)
	res["globalFiles"], res["globalDeleted"], res["globalBytes"] = globalFiles, globalDeleted, globalBytes

	localFiles, localDeleted, localBytes := m.LocalSize(repo)
	res["localFiles"], res["localDeleted"], res["localBytes"] = localFiles, localDeleted, localBytes

	needFiles, needBytes := m.NeedSize(repo)
	res["needFiles"], res["needBytes"] = needFiles, needBytes

	res["inSyncFiles"], res["inSyncBytes"] = globalFiles-needFiles, globalBytes-needBytes

	res["state"] = m.State(repo)

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(res)
}

func restGetConnections(m *Model, w http.ResponseWriter) {
	var res = m.ConnectionStats()
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(res)
}

func restGetConfig(w http.ResponseWriter) {
	encCfg := cfg
	if encCfg.GUI.Password != "" {
		encCfg.GUI.Password = unchangedPassword
	}
	json.NewEncoder(w).Encode(encCfg)
}

func restPostConfig(req *http.Request) {
	var prevPassHash = cfg.GUI.Password
	err := json.NewDecoder(req.Body).Decode(&cfg)
	if err != nil {
		warnln(err)
	} else {
		if cfg.GUI.Password == "" {
			// Leave it empty
		} else if cfg.GUI.Password != unchangedPassword {
			hash, err := bcrypt.GenerateFromPassword([]byte(cfg.GUI.Password), 0)
			if err != nil {
				warnln(err)
			} else {
				cfg.GUI.Password = string(hash)
			}
		} else {
			cfg.GUI.Password = prevPassHash
		}
		saveConfig()
		configInSync = false
	}
}

func restGetConfigInSync(w http.ResponseWriter) {
	json.NewEncoder(w).Encode(map[string]bool{"configInSync": configInSync})
}

func restPostRestart(w http.ResponseWriter) {
	flushResponse(`{"ok": "restarting"}`, w)
	go restart()
}

func restPostReset(w http.ResponseWriter) {
	flushResponse(`{"ok": "resetting repos"}`, w)
	resetRepositories()
	go restart()
}

func restPostShutdown(w http.ResponseWriter) {
	flushResponse(`{"ok": "shutting down"}`, w)
	go shutdown()
}

func flushResponse(s string, w http.ResponseWriter) {
	w.Write([]byte(s + "\n"))
	f := w.(http.Flusher)
	f.Flush()
}

var cpuUsagePercent [10]float64 // The last ten seconds
var cpuUsageLock sync.RWMutex

func restGetSystem(w http.ResponseWriter) {
	var m runtime.MemStats
	runtime.ReadMemStats(&m)

	res := make(map[string]interface{})
	res["myID"] = myID
	res["goroutines"] = runtime.NumGoroutine()
	res["alloc"] = m.Alloc
	res["sys"] = m.Sys
	if cfg.Options.GlobalAnnEnabled && discoverer != nil {
		res["extAnnounceOK"] = discoverer.ExtAnnounceOK()
	}
	cpuUsageLock.RLock()
	var cpusum float64
	for _, p := range cpuUsagePercent {
		cpusum += p
	}
	cpuUsageLock.RUnlock()
	res["cpuPercent"] = cpusum / 10

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(res)
}

func restGetErrors(w http.ResponseWriter) {
	guiErrorsMut.Lock()
	json.NewEncoder(w).Encode(guiErrors)
	guiErrorsMut.Unlock()
}

func restPostError(req *http.Request) {
	bs, _ := ioutil.ReadAll(req.Body)
	req.Body.Close()
	showGuiError(string(bs))
}

func restClearErrors() {
	guiErrorsMut.Lock()
	guiErrors = nil
	guiErrorsMut.Unlock()
}

func showGuiError(err string) {
	guiErrorsMut.Lock()
	guiErrors = append(guiErrors, guiError{time.Now(), err})
	if len(guiErrors) > 5 {
		guiErrors = guiErrors[len(guiErrors)-5:]
	}
	guiErrorsMut.Unlock()
}

func restPostDiscoveryHint(r *http.Request) {
	var qs = r.URL.Query()
	var node = qs.Get("node")
	var addr = qs.Get("addr")
	if len(node) != 0 && len(addr) != 0 && discoverer != nil {
		discoverer.Hint(node, []string{addr})
	}
}

func restGetDiscovery(w http.ResponseWriter) {
	json.NewEncoder(w).Encode(discoverer.All())
}

func basic(username string, passhash string) http.HandlerFunc {
	return func(res http.ResponseWriter, req *http.Request) {
		error := func() {
			time.Sleep(time.Duration(rand.Intn(100)+100) * time.Millisecond)
			res.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
			http.Error(res, "Not Authorized", http.StatusUnauthorized)
		}

		hdr := req.Header.Get("Authorization")
		if len(hdr) < len("Basic ") || hdr[:6] != "Basic " {
			error()
			return
		}

		hdr = hdr[6:]
		bs, err := base64.StdEncoding.DecodeString(hdr)
		if err != nil {
			error()
			return
		}

		fields := bytes.SplitN(bs, []byte(":"), 2)
		if len(fields) != 2 {
			error()
			return
		}

		if string(fields[0]) != username {
			error()
			return
		}

		if err := bcrypt.CompareHashAndPassword([]byte(passhash), fields[1]); err != nil {
			error()
			return
		}
	}
}


text:
namespace extensions {

class CefExtensionsRendererClient : public ExtensionsRendererClient {
 public:
  CefExtensionsRendererClient();
  ~CefExtensionsRendererClient() override;

  // ExtensionsRendererClient implementation.
  bool IsIncognitoProcess() const override;
  int GetLowestIsolatedWorldId() const override;

 private:
  DISALLOW_COPY_AND_ASSIGN(CefExtensionsRendererClient);
};

}  // namespace extensions

#endif  // CEF_LIBCEF_RENDERER_EXTENSIONS_EXTENSIONS_RENDERER_CLIENT_H_


text:
package org.opensaml.saml1.core.impl;

import org.opensaml.common.impl.AbstractSAMLObjectMarshaller;
import org.opensaml.saml1.core.NameIdentifier;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.io.MarshallingException;
import org.opensaml.xml.util.XMLHelper;
import org.w3c.dom.Element;

/**
 * A thread safe Marshaller for {@link org.opensaml.saml1.core.NameIdentifier} objects.
 */
public class NameIdentifierMarshaller extends AbstractSAMLObjectMarshaller {

    /** {@inheritDoc} */
    protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException {
        NameIdentifier nameIdentifier = (NameIdentifier) samlElement;

        if (nameIdentifier.getNameQualifier() != null) {
            domElement
                    .setAttributeNS(null, NameIdentifier.NAMEQUALIFIER_ATTRIB_NAME, nameIdentifier.getNameQualifier());
        }

        if (nameIdentifier.getFormat() != null) {
            domElement.setAttributeNS(null, NameIdentifier.FORMAT_ATTRIB_NAME, nameIdentifier.getFormat());
        }
    }

    /** {@inheritDoc} */
    protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException {
        NameIdentifier nameIdentifier = (NameIdentifier) samlObject;

        if (nameIdentifier.getNameIdentifier() != null) {
            XMLHelper.appendTextContent(domElement, nameIdentifier.getNameIdentifier());
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:background="?android:attr/selectableItemBackground"
    android:orientation="horizontal"
    android:padding="10dp">

    <LinearLayout
        android:layout_width="90dp"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/device_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:padding="14dp"
            android:scaleType="centerCrop"
            tools:src="@drawable/ic_devices_other_black_24dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="300dp"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/device_name"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center_vertical"
            android:textSize="@dimen/article_subheading"
            tools:text="@string/item_title" />

        <TextView
            android:id="@+id/device_MACAddress"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center_vertical"
            android:textColor="@color/medium_grey"
            android:textSize="@dimen/list_body"
            tools:text="@string/item_desc" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/device_status"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center_vertical"
            android:text="Status" />

        <Button
            android:id="@+id/device_unpair"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:text="Remove" />
    </LinearLayout>

</LinearLayout>


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>colour.algebra.matrix Module — Colour 0.3.3 documentation</title>

    <link rel="stylesheet" href="_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="_static/bootswatch-3.1.0/colour/bootstrap.min.css" type="text/css" />
    <link rel="stylesheet" href="_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="_static/styles.css" type="text/css" />

    <link rel="top" title="Colour 0.3.3 documentation" href="index.html" />
    <link rel="up" title="colour.algebra Package" href="colour.algebra.html" />
    <link rel="next" title="colour.algebra.regression Module" href="colour.algebra.regression.html" />
    <link rel="prev" title="colour.algebra.interpolation Module" href="colour.algebra.interpolation.html" />
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

          Colour 0.3

colour-science.org

                   Documentation

                           API Reference

                           IPython Notebooks

                           Features

                           Contributing

    « colour.algebra.i...

    colour.algebra.r... »

<form class="navbar-form navbar-right" action="search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

colour.algebra.matrix Module¶

Matrix Helpers¶

Defines matrices computation helpers objects.

<tt class="descclassname">colour.algebra.matrix.</tt><tt class="descname">is_identity</tt><big>(</big>x, n=3<big>)</big>[source]¶

Returns if given array_like variable \(x\) is an identity matrix.

<col class="field-name" />
<col class="field-body" />

Parameters:

x (array_like, (N)) – Variable \(x\) to test.

n (int, optional) – Matrix dimension.

Returns:
Is identity matrix.

Return type:
bool

Examples

>>> is_identity(np.array([1, 0, 0, 0, 1, 0, 0, 0, 1]).reshape(3, 3))
True
>>> is_identity(np.array([1, 2, 0, 0, 1, 0, 0, 0, 1]).reshape(3, 3))
False

      Back to top

        © Copyright 2013 - 2014, Colour Developers.

      Created using Sphinx 1.2.2.


text:
#include "src/core/lib/gprpp/ref_counted_ptr.h"

#include <gtest/gtest.h>

#include <grpc/support/log.h>

#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/gprpp/ref_counted.h"
#include "test/core/util/test_config.h"

namespace grpc_core {
namespace testing {
namespace {

class Foo : public RefCounted<Foo> {
 public:
  Foo() : value_(0) {}

  explicit Foo(int value) : value_(value) {}

  int value() const { return value_; }

 private:
  int value_;
};

TEST(RefCountedPtr, DefaultConstructor) { RefCountedPtr<Foo> foo; }

TEST(RefCountedPtr, ExplicitConstructorEmpty) {
  RefCountedPtr<Foo> foo(nullptr);
}

TEST(RefCountedPtr, ExplicitConstructor) { RefCountedPtr<Foo> foo(New<Foo>()); }

TEST(RefCountedPtr, MoveConstructor) {
  RefCountedPtr<Foo> foo(New<Foo>());
  RefCountedPtr<Foo> foo2(std::move(foo));
  EXPECT_EQ(nullptr, foo.get());
  EXPECT_NE(nullptr, foo2.get());
}

TEST(RefCountedPtr, MoveAssignment) {
  RefCountedPtr<Foo> foo(New<Foo>());
  RefCountedPtr<Foo> foo2 = std::move(foo);
  EXPECT_EQ(nullptr, foo.get());
  EXPECT_NE(nullptr, foo2.get());
}

TEST(RefCountedPtr, CopyConstructor) {
  RefCountedPtr<Foo> foo(New<Foo>());
  RefCountedPtr<Foo> foo2(foo);
  EXPECT_NE(nullptr, foo.get());
  EXPECT_EQ(foo.get(), foo2.get());
}

TEST(RefCountedPtr, CopyAssignment) {
  RefCountedPtr<Foo> foo(New<Foo>());
  RefCountedPtr<Foo> foo2 = foo;
  EXPECT_NE(nullptr, foo.get());
  EXPECT_EQ(foo.get(), foo2.get());
}

TEST(RefCountedPtr, CopyAssignmentWhenEmpty) {
  RefCountedPtr<Foo> foo;
  RefCountedPtr<Foo> foo2;
  foo2 = foo;
  EXPECT_EQ(nullptr, foo.get());
  EXPECT_EQ(nullptr, foo2.get());
}

TEST(RefCountedPtr, CopyAssignmentToSelf) {
  RefCountedPtr<Foo> foo(New<Foo>());
  foo = *&foo;  // The "*&" avoids warnings from LLVM -Wself-assign.
}

TEST(RefCountedPtr, EnclosedScope) {
  RefCountedPtr<Foo> foo(New<Foo>());
  {
    RefCountedPtr<Foo> foo2(std::move(foo));
    EXPECT_EQ(nullptr, foo.get());
    EXPECT_NE(nullptr, foo2.get());
  }
  EXPECT_EQ(nullptr, foo.get());
}

TEST(RefCountedPtr, ResetFromNullToNonNull) {
  RefCountedPtr<Foo> foo;
  EXPECT_EQ(nullptr, foo.get());
  foo.reset(New<Foo>());
  EXPECT_NE(nullptr, foo.get());
}

TEST(RefCountedPtr, ResetFromNonNullToNonNull) {
  RefCountedPtr<Foo> foo(New<Foo>());
  EXPECT_NE(nullptr, foo.get());
  Foo* original = foo.get();
  foo.reset(New<Foo>());
  EXPECT_NE(nullptr, foo.get());
  EXPECT_NE(original, foo.get());
}

TEST(RefCountedPtr, ResetFromNonNullToNull) {
  RefCountedPtr<Foo> foo(New<Foo>());
  EXPECT_NE(nullptr, foo.get());
  foo.reset();
  EXPECT_EQ(nullptr, foo.get());
}

TEST(RefCountedPtr, ResetFromNullToNull) {
  RefCountedPtr<Foo> foo;
  EXPECT_EQ(nullptr, foo.get());
  foo.reset(nullptr);
  EXPECT_EQ(nullptr, foo.get());
}

TEST(RefCountedPtr, DerefernceOperators) {
  RefCountedPtr<Foo> foo(New<Foo>());
  foo->value();
  Foo& foo_ref = *foo;
  foo_ref.value();
}

TEST(RefCountedPtr, EqualityOperators) {
  RefCountedPtr<Foo> foo(New<Foo>());
  RefCountedPtr<Foo> bar = foo;
  RefCountedPtr<Foo> empty;
  // Test equality between RefCountedPtrs.
  EXPECT_EQ(foo, bar);
  EXPECT_NE(foo, empty);
  // Test equality with bare pointers.
  EXPECT_EQ(foo, foo.get());
  EXPECT_EQ(empty, nullptr);
  EXPECT_NE(foo, nullptr);
}

TEST(MakeRefCounted, NoArgs) {
  RefCountedPtr<Foo> foo = MakeRefCounted<Foo>();
  EXPECT_EQ(0, foo->value());
}

TEST(MakeRefCounted, Args) {
  RefCountedPtr<Foo> foo = MakeRefCounted<Foo>(3);
  EXPECT_EQ(3, foo->value());
}

TraceFlag foo_tracer(true, "foo");

class FooWithTracing : public RefCountedWithTracing<FooWithTracing> {
 public:
  FooWithTracing() : RefCountedWithTracing(&foo_tracer) {}
};

TEST(RefCountedPtr, RefCountedWithTracing) {
  RefCountedPtr<FooWithTracing> foo(New<FooWithTracing>());
  RefCountedPtr<FooWithTracing> foo2 = foo->Ref(DEBUG_LOCATION, "foo");
  foo2.release();
  foo->Unref(DEBUG_LOCATION, "foo");
}

}  // namespace
}  // namespace testing
}  // namespace grpc_core

int main(int argc, char** argv) {
  grpc_test_init(argc, argv);
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}


text:
using System;
using System.Linq;
using System.Net;
#if !NETFX_CORE
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif

namespace CoAP.Channel
{
    [TestClass]
    public class IPAddressTest
    {
        [TestMethod]
        public void TestMapBetweenIPv4AndIPv6()
        {
            for (Byte i = 0; i < Byte.MaxValue; i++)
            {
                IPAddress ipv4 = new IPAddress(new Byte[] { 10, 0, 0, i });
                IPAddress ipv6 = IPAddressExtensions.MapToIPv6(ipv4);
                Assert.IsTrue(IPAddressExtensions.IsIPv4MappedToIPv6(ipv6));

                IPAddress ipv4Mapped = IPAddressExtensions.MapToIPv4(ipv6);
                Assert.AreEqual(ipv4, ipv4Mapped);
            }
        }
    }
}


text:
/*  This file is part of Jellyfish.

    Jellyfish is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jellyfish is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Jellyfish.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef __JELLYFISH_MAPPED_FILE_HPP__
#define __JELLYFISH_MAPPED_FILE_HPP__

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <vector>
#include <errno.h>
#include <iostream>

#include <jellyfish/err.hpp>
#include <jellyfish/misc.hpp>
#include <jellyfish/atomic_gcc.hpp>
#include <jellyfish/dbg.hpp>

class mapped_file {
protected:
  std::string  _path;
  bool         _unmap;
  char        *_base, *_end;
  size_t       _length;

  void map(const char *filename) {
    int fd = open(filename, O_RDONLY);
    struct stat stat;

    if(fd < 0)
      eraise(ErrorMMap) << "Can't open file '" << filename << "'" << err::no;

    if(fstat(fd, &stat) < 0)
      eraise(ErrorMMap) << "Can't stat file '" << filename << "'" << err::no;

    _length = stat.st_size;
    _base = (char *)mmap(NULL, _length, PROT_READ, MAP_PRIVATE, fd, 0);
    if(_base == MAP_FAILED)
      eraise(ErrorMMap) << "Can't mmap file '" << filename << "'" << err::no;
    close(fd);
    _end = _base + _length;
  }

public:
  define_error_class(ErrorMMap);
  mapped_file(char *__base, size_t __length) :
    _unmap(false), _base(__base), _end(__base + __length), _length(__length) {}

  mapped_file(const char *filename) : _path(filename), _unmap(false) {
    map(filename);
  }
  mapped_file(const mapped_file &mf) :
    _path(mf.path()), _unmap(false), _base(mf._base), _end(mf._end),
    _length(mf._length) {}

  ~mapped_file() {
    if(_unmap)
      unmap();
  }

  void unmap() {
    if(!_base)
      return;
    munmap(_base, _length);
    _base = 0;
    _length = 0;
  }

  char *base() const { return _base; }
  char *end() const { return _end; }
  size_t length() const { return _length; }
  std::string path() const { return _path; }

  bool will_unmap(bool value = true) {
    bool ovalue = _unmap;
    _unmap = value;
    return ovalue;
  }
  // No error checking here. Should I throw something?
  const mapped_file & will_need() const {
    madvise(_base, _length, MADV_WILLNEED);
    return *this;
  }
  const mapped_file & sequential() const {
    madvise(_base, _length, MADV_SEQUENTIAL);
    return *this;
  }
  const mapped_file & random() const {
    madvise(_base, _length, MADV_RANDOM);
    return *this;
  }
  const mapped_file & lock() const {
    if(mlock(_base, _length) < 0)
      eraise(ErrorMMap) << "Can't lock map in memory" << err::no;
    return *this;
  }

  // Do not optimize. Side effect is that every page is accessed and should now be in cache.
  // The flagg __attribute__((optimize(0))) does not compile, so return a useless char argument
  char load() const;
};

class mapped_files_t : public std::vector<mapped_file> {
public:
  mapped_files_t(int nb_files, char *argv[]) {
    for(int j = 0; j < nb_files; j++)
      push_back(mapped_file(argv[j]));
  }

  mapped_files_t(int nb_files, char *argv[], bool sequential) {
    for(int j = 0; j < nb_files; j++) {
      push_back(mapped_file(argv[j]));
      if(sequential)
        end()->sequential();
    }
  }
};

// File mapped on demand.
class lazy_mapped_file_t : public mapped_file {
  std::string       _path;
  volatile bool     done;
  volatile long     used_counter;

public:
  lazy_mapped_file_t(const char *path) :
    mapped_file((char *)0, (size_t)0),
    _path(path), done(false), used_counter(0) {}

  void map() {
    used_counter = 1;
    done = false;
    mapped_file::map(_path.c_str());
  }
  void unmap() {
    done = true;
    dec();
  }

  void inc() {
    atomic::gcc::fetch_add(&used_counter, (long)1);
  }
  void dec() {
    long val = atomic::gcc::add_fetch(&used_counter, (long)-1);
    if(done && val == 0)
      mapped_file::unmap();
  }
};

class lazy_mapped_files_t : public std::vector<lazy_mapped_file_t> {
public:
  lazy_mapped_files_t(int nb_files, char *argv[]) {
    for(int j = 0; j < nb_files; j++)
      push_back(lazy_mapped_file_t(argv[j]));
  }

  lazy_mapped_files_t(int nb_files, char *argv[], bool sequential) {
    for(int j = 0; j < nb_files; j++) {
      push_back(lazy_mapped_file_t(argv[j]));
      if(sequential)
        end()->sequential();
    }
  }
};

#endif


text:
def extract_sections(text)
  in_section = false
  sections = []
  text.each_line do |line|
    line = line.chomp
    case line
      # request/response header
    when /^\** (Request|Response)+/
      in_section = true
      section_name = line
      sections << [section_name, []]
      # some other header
    when /^\*+/
      in_section = false
      section_name = nil
    else
      if in_section
        sections[-1][-1] << line
      end
    end
  end
  sections
end

def construct_filename(type, number, api_call)
  api_call = api_call.gsub(/\W+/, '-')
  [number, type, api_call].map{ |x| x.downcase}.join('-')
end

def output_sections(filename, sections)
  if filename
    prefix =  File.join(File.dirname(filename), File.basename(filename, File.extname(filename)))
  else
    prefix = nil
  end
  sections.each do |section, lines|
    section = section.gsub(/\*+/, '').strip
    if match = section.match(/(Request|Response)\s+(\d+)\s+-\s+(.*)\s*/)
      if match.captures.size == 3
        fn = construct_filename(*match.captures)
        if prefix
          fn = [prefix, fn].join("-")
        end
        File.open(fn + ".org", "wb") do |file|
          file.puts "# #{section}"
          file.puts lines
        end
      end
    end
  end
end

if ARGV.size == 0
  text = STDIN.read
  prefix = nil
  filename = nil
elsif ARGV.size == 1
  filename = ARGV[0]
  text = File.read(filename)
else
  abort "usage: #{$0} [orgfile containing trace]"
end
sections = extract_sections(text)
output_sections(filename, sections)


text:
package cwl
import cats.syntax.traverse._
import cats.instances.list._
import common.assertion.CromwellTimeoutSpec
import eu.timepit.refined.numeric.Positive
import eu.timepit.refined.refineMV
import org.scalatest.ParallelTestExecution
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import shapeless.Coproduct
import wom.callable.Callable.RequiredInputDefinition
import wom.callable.RuntimeEnvironment
import wom.expression.NoIoFunctionSet
import wom.types._
import wom.values.{WomArray, WomBoolean, WomEvaluatedCallInputs, WomInteger, WomObject, WomSingleFile, WomString, WomValue}

class CommandLineToolSpec extends AnyFlatSpec with CromwellTimeoutSpec with Matchers with ParallelTestExecution {

  behavior of "CommandLineTool"

  val inputs: WomEvaluatedCallInputs = Map(
    RequiredInputDefinition("a", WomStringType) -> WomString("helloA"),
    RequiredInputDefinition("b", WomStringType) -> WomString("helloB"),
    RequiredInputDefinition("c", WomStringType) -> WomString("helloC"),
    RequiredInputDefinition("d", WomArrayType(WomStringType)) -> WomArray(WomArrayType(WomStringType), List(WomString("helloD0"), WomString("helloD1"))),
    RequiredInputDefinition("e", WomCompositeType(Map("fa" -> WomSingleFileType, "fb" -> WomIntegerType)))
      -> WomObject.withTypeUnsafe(Map("fa" -> WomSingleFile("helloEfa"), "fb" -> WomInteger(0)), WomCompositeType(Map("fa" -> WomSingleFileType, "fb" -> WomIntegerType))),
    RequiredInputDefinition("f", WomBooleanType) -> WomBoolean.True,
    RequiredInputDefinition("g", WomBooleanType) -> WomBoolean.False,
    RequiredInputDefinition("h", WomIntegerType) -> WomInteger(0),
    RequiredInputDefinition("i", WomSingleFileType) -> WomSingleFile("ifile")
  )

  val localNameValues = inputs.map({ case (k, v) => k.localName -> v })

  val noIoFunctionSet = NoIoFunctionSet

  val runtimeEnv = RuntimeEnvironment("", "", refineMV[Positive](1), 0D, 0L, 0L)

  def validate(tool: String, expectation: List[String]) = {
    val cltFile = better.files.File.newTemporaryFile()().write(tool)

    val clt = CwlDecoder.decodeCwlFile(cltFile, None).value.unsafeRunSync() match {
      case Left(errors) => fail("Cannot parse command line tool " + errors.toList.mkString(", "))
      case Right(cwlFile) => cwlFile.select[CommandLineTool].get
    }

    val template = clt
      .buildCommandTemplate.run((RequirementsAndHints(List.empty), Vector.empty,inputs))
      .valueOr(errors => fail(errors.toList.mkString(", ")))
    template
      .flatTraverse(_.instantiate(localNameValues, noIoFunctionSet, identity[WomValue], runtimeEnv).map(_.map(_.commandString)))
      .valueOr(errors => fail(errors.toList.mkString(", "))) shouldBe expectation

    cltFile.delete(true)
  }

  it should "filter input arguments when not bound to command line" in {
    val tool = """
      |class: CommandLineTool
      |cwlVersion: v1.0
      |inputs:
      |  - id: a
      |    type: string
      |    inputBinding: { position: 2 }
      |
      |  - id: b
      |    type: string
      |
      |baseCommand: echo
      |outputs: []
    """.stripMargin

    validate(tool, List("'echo'", "'helloA'"))
  }

  it should "order input arguments that are bound to command line" in {
    val tool = """
                 |class: CommandLineTool
                 |cwlVersion: v1.0
                 |inputs:
                 |  - id: b
                 |    type: string
                 |    inputBinding: { position: 2 }
                 |
                 |  - id: c
                 |    type: string
                 |    inputBinding: { position: 3 }
                 |
                 |  - id: a
                 |    type: string
                 |    inputBinding: { position: 1 }
                 |
                 |baseCommand: echo
                 |outputs: []
               """.stripMargin

    validate(tool, List("'echo'", "'helloA'", "'helloB'", "'helloC'"))
  }

  it should "include arguments and sort them" in {
    val tool = """
                 |class: CommandLineTool
                 |cwlVersion: v1.0
                 |inputs:
                 |  - id: b
                 |    type: string
                 |    inputBinding: { position: 4 }
                 |
                 |  - id: c
                 |    type: string
                 |    inputBinding: { position: 5 }
                 |
                 |  - id: a
                 |    type: string
                 |    inputBinding: { position: 1 }
                 |
                 |baseCommand: echo
                 |arguments:
                 |  - arg0
                 |  - valueFrom: "arg2"
                 |    position: 3
                 |  - valueFrom: "arg1"
                 |    position: 2
                 |outputs: []
               """.stripMargin

    validate(tool, List("'echo'", "'arg0'", "'helloA'", "'arg1'", "'arg2'", "'helloB'", "'helloC'"))
  }

  it should "handle array types" in {
    val tool = """
                 |class: CommandLineTool
                 |cwlVersion: v1.0
                 |inputs:
                 |  - id: d
                 |    type:
                 |      type: array
                 |      items: string
                 |      inputBinding: { prefix: "-YYY" }
                 |    inputBinding: { position: 3, prefix: "-XXX" }
                 |
                 |  - id: a
                 |    type: string
                 |    inputBinding: { position: 1 }
                 |
                 |baseCommand: echo
                 |arguments:
                 |  - valueFrom: "arg2"
                 |    position: 2
                 |outputs: []
               """.stripMargin

    validate(tool, List("'echo'", "'helloA'", "'arg2'", "'-XXX'", "'-YYY'", "'helloD0'", "'-YYY'", "'helloD1'"))
  }

  it should "handle record schema" in {
    val tool = """
                 |class: CommandLineTool
                 |cwlVersion: v1.0
                 |inputs:
                 |  e:
                 |    type:
                 |      name: e
                 |      type: record
                 |      fields:
                 |      - name: fa
                 |        type: File
                 |        inputBinding:
                 |          position: 2
                 |          prefix: "--prefixFa"
                 |      - name: fb
                 |        type: int
                 |        inputBinding:
                 |          position: 4
                 |          prefix: "--prefixFb"
                 |    inputBinding:
                 |      prefix: "--prefixRecord"
                 |  a:
                 |    type: string
                 |    inputBinding: { position: 1 }
                 |
                 |baseCommand: echo
                 |arguments:
                 |  - valueFrom: "arg2"
                 |    position: 3
                 |outputs: []
               """.stripMargin

    validate(tool, List("'echo'", "'--prefixRecord'", "'--prefixFa'", "'helloEfa'", "'--prefixFb'", "'0'", "'helloA'", "'arg2'"))
  }

  it should "handle prefixes properly for primitive types" in {
    val tool = """
                 |class: CommandLineTool
                 |cwlVersion: v1.0
                 |inputs:
                 |  a:
                 |    type: string
                 |    inputBinding: { position: 1, prefix: --aprefix }
                 |  f:
                 |    type: boolean
                 |    inputBinding: { position: 2, prefix: --show }
                 |  g:
                 |    type: boolean
                 |    inputBinding: { position: 3, prefix: --noshow }
                 |  h:
                 |    type: string
                 |    inputBinding: { position: 4, prefix: --hprefix }
                 |  i:
                 |    type: File
                 |    inputBinding: { position: 5, prefix: --iprefix }
                 |
                 |baseCommand: echo
                 |outputs: []
               """.stripMargin

    validate(tool, List("'echo'", "'--aprefix'", "'helloA'", "'--show'", "'--hprefix'", "'0'", "'--iprefix'", "'ifile'"))
  }

  it should "handle arrays with item separator" in {
    val tool = """
                 |class: CommandLineTool
                 |cwlVersion: v1.0
                 |inputs:
                 |  d:
                 |    type:
                 |      type: array
                 |      items: string
                 |      inputBinding: { position: 2, prefix: --item }
                 |    inputBinding: { position: 2, prefix: --array, itemSeparator: ", " }
                 |
                 |baseCommand: echo
                 |outputs: []
               """.stripMargin

    validate(tool, List("'echo'", "'--array'", "'helloD0, helloD1'"))
  }

  it should "handle arrays with valueFrom" in {
    val tool = """
                 |class: CommandLineTool
                 |cwlVersion: v1.0
                 |inputs:
                 |  d:
                 |    type:
                 |      type: array
                 |      items: string
                 |      inputBinding: { position: 2, prefix: --item }
                 |    inputBinding: { position: 2, prefix: --array, valueFrom: "hello" }
                 |
                 |baseCommand: echo
                 |outputs: []
               """.stripMargin

    validate(tool, List("'echo'", "'--array'", "'hello'"))
  }

  it should "handle the separate field" in {
    val tool = """
                 |class: CommandLineTool
                 |cwlVersion: v1.0
                 |inputs:
                 |  a:
                 |    type: string
                 |    inputBinding: { position: 0, prefix: --prefix, separate: false }
                 |
                 |baseCommand: echo
                 |outputs: []
               """.stripMargin

    validate(tool, List("'echo'", "'--prefixhelloA'"))
  }

  it should "pull expression libs from all requirements" in {
    val list = List(Coproduct[Requirement](InlineJavascriptRequirement(`class` = "InlineJavascriptRequirement", expressionLib = Some(Array("a")))))
    Tool.inlineJavascriptRequirements(list).head shouldBe "a"
  }
}


text:
**The article is outdated, [read updated article about certificate in official documentation of Power BI.](https://docs.microsoft.com/power-bi/developer/visuals/create-ssl-certificate)**

To be access your visual through PowerBI you need to add a trusted certificate for localhost. This will allow PowerBI to load the visual assets in your browser without a security warning.

----------

## Step 1

Run the following command to open the certificate and start the process.

```
pbiviz --install-cert
```

*If this command fails for some reason, find pbiviz in your global node modules folder and open the certificate manually.*

----------

## Step 2

![](images/windows0.png)

* Click `Install Certificate...`

----------

## Step 3

![](images/windows2.png)

* Select `Current User` and click `Next`

----------

## Step 4

![](images/windows3.png)

* Select `Place all certificates in the following store`
* Click `Browse...`

----------

## Step 5

You should see this dialog

![](images/windows4.png)

* Select `Trusted Root Certification Authorities`
* Click `OK`
* Click `Next` *(previous screen)*

----------

## Step 6

![](images/windows5.png)

* Click `Finish`

----------

## Step 7

You will then see this security warning

![](images/windows6.png)

* Click `Yes`

----------

## Step 8

**Close all open browsers**

Once this is done your browser will trust this certificate for connections to `localhost` which will allow you to serve visuals. You will need to close all open web browsers before changes will take effect. If this doesn't work try restarting your computer.


text:
{% extends "base.html" %}
{% block title %}Load data from DBLP{% endblock %}

{%block head%}
{{super()}}
{%endblock%}

{%block content%}

An ampty database were detected. We need to load fresh data from DBLP url.

<form method="post">

Enter DBLP XML file url:<input type="text" id="dblpurl" />

<input type="submit" value="Enviar"

</form>
{% endblock %}


text:
package util

import (
	"io"
	"net/http"
	"os"
	"strings"
)

// Input stores the user-provided data and its origin.
type Input struct {
	Origin string        // either file path or URL or empty if data was read from stdin
	Data   io.ReadCloser // the HTML data (hopefully)
}

func GetInput(args []string) []Input {
	result := make([]Input, 0)
	if len(args) > 0 {
		for _, arg := range args {
			if strings.HasPrefix(arg, "http://") || strings.HasPrefix(arg, "https://") {
				if resp, err := http.Get(arg); err == nil {
					result = append(result, Input{arg, resp.Body})
				}
			} else {
				if file, err := os.Open(arg); err == nil {
					result = append(result, Input{arg, file})
				}
			}
		}
	} else {
		result = append(result, Input{"", os.Stdin})
	}
	return result
}


text:
package org.linkedin.schema;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="code">
 *           <simpleType>
 *             <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *               <enumeration value="business-partner"/>
 *               <enumeration value="colleague"/>
 *               <enumeration value="education"/>
 *               <enumeration value="service-provider"/>
 *             </restriction>
 *           </simpleType>
 *         </element>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
public interface RecommendationType
    extends SchemaEntity
{

    /**
     * Gets the value of the code property.
     *
     * @return
     *     possible object is
     *     {@link RecommendationCode }
     *
     */
    RecommendationCode getCode();

    /**
     * Sets the value of the code property.
     *
     * @param value
     *     allowed object is
     *     {@link RecommendationCode }
     *
     */
    void setCode(RecommendationCode value);

}


text:
package com.linecorp.armeria.server.annotation;

import static com.linecorp.armeria.internal.AnnotatedHttpServiceParamUtil.convertParameter;
import static com.linecorp.armeria.internal.AnnotatedHttpServiceParamUtil.findHeaderName;
import static com.linecorp.armeria.internal.AnnotatedHttpServiceParamUtil.findParamName;
import static com.linecorp.armeria.internal.AnnotatedHttpServiceParamUtil.hasParamOrHeader;
import static com.linecorp.armeria.internal.AnnotatedHttpServiceParamUtil.httpParametersOf;
import static com.linecorp.armeria.internal.AnnotatedHttpServiceParamUtil.validateAndNormalizeSupportedType;
import static java.util.Collections.singletonList;
import static org.reflections.ReflectionUtils.getAllFields;
import static org.reflections.ReflectionUtils.getAllMethods;

import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

import javax.annotation.Nullable;

import org.reflections.ReflectionUtils;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.MapMaker;

import com.linecorp.armeria.common.AggregatedHttpMessage;
import com.linecorp.armeria.common.HttpParameters;
import com.linecorp.armeria.internal.AnnotatedHttpServiceParamUtil;
import com.linecorp.armeria.internal.AnnotatedHttpServiceParamUtil.EnumConverter;
import com.linecorp.armeria.server.ServiceRequestContext;

import io.netty.util.AsciiString;

/**
 * A default {@link RequestConverterFunction} which converts a request into a Java bean.
 *
 *
The following parameters are eligible for automatic injection into bean fields or properties:
 *

 *
Path parameters to fields annotated by {@link Param}

 *
HTTP parameters to fields annotated by {@link Param}

 *
Headers to fields annotated by {@link Header}

 *

 */
public final class BeanRequestConverterFunction implements RequestConverterFunction {
    // In BeanParamInfo, there are strong references to Field/Method/Constructor, which end up with strong
    // references to their parent Class. So it don't make sense if we use map with weak reference key here
    private static final ConcurrentMap<Class<?>, BeanParamInfo> beanParamInfoCache = new ConcurrentHashMap<>();

    private static final ConcurrentMap<Class<?>, Boolean> ignoredResultTypeCache = new MapMaker().weakKeys()
                                                                                .makeMap();

    /**
     * Builds and registers the parameter information for {@code expectedResultType}.
     *
     * @param expectedResultType a candidate data type, which will be converted
     *                           by {@link BeanRequestConverterFunction}
     */
    public static synchronized void register(final Class<?> expectedResultType) {
        if (ignoredResultTypeCache.containsKey(expectedResultType) ||
            beanParamInfoCache.containsKey(expectedResultType)) {
            // already processed this result type
            return;
        }

        final BeanParamInfo beanParamInfo = BeanParamInfo.from(expectedResultType);
        if (beanParamInfo == null) {
            ignoredResultTypeCache.put(expectedResultType, true);
        } else {
            beanParamInfoCache.put(expectedResultType, beanParamInfo);
        }
    }

    private static <T> void addIfNotNull(final List<T> list, final T item) {
        if (item != null) {
            list.add(item);
        }
    }

    private static String getMemberFullName(final Member member) {
        return member.getDeclaringClass().getSimpleName() + '.' + member.getName();
    }

    private static String toString(Object[] objects) {
        final StringJoiner joiner = new StringJoiner(",", "(", ")");
        Arrays.stream(objects).forEach(o -> joiner.add(o.toString()));
        return joiner.toString();
    }

    @Override
    public Object convertRequest(final ServiceRequestContext ctx,
                                 final AggregatedHttpMessage request,
                                 final Class<?> expectedResultType) throws Exception {
        final BeanParamInfo beanParamInfo = beanParamInfoCache.get(expectedResultType);
        if (beanParamInfo == null) {
            // no BeanParamInfo for this result type, we should not handle it
            return RequestConverterFunction.fallthrough();
        }

        final MutableValueHolder<HttpParameters> httpParams = MutableValueHolder.ofEmpty();
        final RequestConvertContext context = new RequestConvertContext(ctx, request, httpParams);
        return beanParamInfo.buildBean(context);
    }

    private static final class RequestConvertContext {
        private final ServiceRequestContext ctx;

        private final AggregatedHttpMessage request;

        private final MutableValueHolder<HttpParameters> httpParams;

        @SuppressWarnings("NullableProblems")
        private Object targetBean;

        private RequestConvertContext(final ServiceRequestContext ctx,
                                      final AggregatedHttpMessage request,
                                      final MutableValueHolder<HttpParameters> httpParams) {
            this.ctx = ctx;
            this.request = request;
            this.httpParams = httpParams;
        }
    }

    private static final class BeanParamInfo {
        private final ConstructorInfo constructorInfo;

        private final List<AbstractParamSetter> paramSetterList;

        private BeanParamInfo(final ConstructorInfo constructorInfo,
                              final List<AbstractParamSetter> paramSetterList) {
            this.constructorInfo = constructorInfo;
            this.paramSetterList = paramSetterList;
        }

        @Nullable
        private static BeanParamInfo from(final Class<?> beanType) {

            final ConstructorInfo constructorInfo = ConstructorInfo.from(beanType);
            if (constructorInfo == null) {
                // No annotated constructor or default constructor. Skip this.
                return null;
            }

            final List<AbstractParamSetter> paramSetterList = new ArrayList<>();
            getAllFields(beanType).forEach(
                    field -> addIfNotNull(paramSetterList, FieldParamSetter.from(field)));
            getAllMethods(beanType).forEach(
                    method -> addIfNotNull(paramSetterList, MethodParamSetter.from(method)));

            if (constructorInfo.getParameterCount() == 0 && paramSetterList.isEmpty()) {
                // No arg constructor exists but there is no annotated field or method. Skip this.
                return null;
            }

            return new BeanParamInfo(constructorInfo, paramSetterList);
        }

        private Object buildBean(final RequestConvertContext context) {
            context.targetBean = constructorInfo.createInstance(context);
            paramSetterList.forEach(paramSetter -> paramSetter.setParamValue(context));
            return context.targetBean;
        }
    }

    private static final class ConstructorInfo {
        private final Constructor<?> constructor;

        private final ParamArrayValueRetriever paramArrayValueRetriever;

        private ConstructorInfo(final Constructor<?> constructor,
                                final ParamArrayValueRetriever paramArrayValueRetriever) {
            this.constructor = constructor;
            this.paramArrayValueRetriever = paramArrayValueRetriever;

            this.constructor.setAccessible(true);
        }

        private static ConstructorInfo from(final Class<?> beanType) {
            final List<ConstructorInfo> constructorList = new ArrayList<>();

            final MutableValueHolder<ConstructorInfo> defaultConstructor = MutableValueHolder.ofEmpty();

            ReflectionUtils.getConstructors(beanType).forEach(
                    constructor -> {
                        final ConstructorInfo constructorInfo = from(constructor);
                        if (constructorInfo != null) {
                            if (constructorInfo.getParameterCount() == 0) {
                                // default constructor, with no args
                                defaultConstructor.setValue(constructorInfo);
                            } else {
                                // constructor with args
                                constructorList.add(constructorInfo);
                            }
                        }
                    }
            );

            if (constructorList.isEmpty()) {
                // No annotated constructor. Use default constructor.
                return defaultConstructor.getValue();
            }
            if (constructorList.size() == 1) {
                // Only 1 annotated constructor.
                return constructorList.get(0);
            }
            // More than 1 annotated constructors. We don't know which one to use.
            throw new IllegalArgumentException(
                    "too many annotated constructors in " + beanType.getSimpleName() +
                    ": " + constructorList.size() + " (expected: 0 or 1)");
        }

        @Nullable
        private static ConstructorInfo from(final Constructor<?> constructor) {
            final ParamArrayValueRetriever retriever = ParamArrayValueRetriever.from(constructor);
            if (retriever != null) {
                return new ConstructorInfo(constructor, retriever);
            }
            if (constructor.getParameterCount() == 0) {
                return new ConstructorInfo(constructor, ParamArrayValueRetriever.NO_PARAMETERS);
            }
            return null;
        }

        private int getParameterCount() {
            return paramArrayValueRetriever.retrieverList.size();
        }

        private Object createInstance(final RequestConvertContext context) {
            final Object[] initArgs = paramArrayValueRetriever.getParamValues(context);
            try {
                return constructor.newInstance(initArgs);
            } catch (final Exception e) {
                throw new IllegalArgumentException(
                        "cannot invoke constructor: " + getMemberFullName(constructor) +
                        BeanRequestConverterFunction.toString(initArgs), e);
            }
        }
    }

    private abstract static class AbstractParamSetter {
        protected abstract void setParamValue(RequestConvertContext context);
    }

    private static final class FieldParamSetter extends AbstractParamSetter {
        private final Field field;
        private final ParamValueRetriever paramValueRetriever;

        private FieldParamSetter(final Field field,
                                 final ParamValueRetriever paramValueRetriever) {
            this.field = field;
            this.paramValueRetriever = paramValueRetriever;
            this.field.setAccessible(true);
        }

        @Nullable
        private static FieldParamSetter from(final Field field) {
            final ParamValueRetriever retriever = ParamValueRetriever.of(field.getType(), field);
            return retriever != null ? new FieldParamSetter(field, retriever)
                                     : null;
        }

        @Override
        protected void setParamValue(final RequestConvertContext context) {
            final Object paramValue = paramValueRetriever.getParamValue(context);
            try {
                field.set(context.targetBean, paramValue);
            } catch (final Exception e) {
                throw new IllegalArgumentException(
                        "cannot set '" + paramValue + "' to: " + getMemberFullName(field), e);
            }
        }
    }

    private static final class MethodParamSetter extends AbstractParamSetter {
        private final Method method;
        private final ParamArrayValueRetriever paramArrayValueRetriever;

        private MethodParamSetter(final Method method,
                                  final ParamArrayValueRetriever paramArrayValueRetriever) {
            this.method = method;
            this.paramArrayValueRetriever = paramArrayValueRetriever;

            this.method.setAccessible(true);
        }

        @Nullable
        private static MethodParamSetter from(final Method method) {
            final ParamArrayValueRetriever retriever = ParamArrayValueRetriever.from(method);
            return retriever != null ? new MethodParamSetter(method, retriever)
                                     : null;
        }

        @Override
        protected void setParamValue(final RequestConvertContext context) {
            final Object[] paramValues = paramArrayValueRetriever.getParamValues(context);
            try {
                method.invoke(context.targetBean, paramValues);
            } catch (final Exception e) {
                throw new IllegalArgumentException(
                        "cannot invoke method: " + getMemberFullName(method) +
                        BeanRequestConverterFunction.toString(paramValues), e);
            }
        }
    }

    private abstract static class ParamValueRetriever {
        private final Class<?> type;

        private final EnumConverter<?> enumConverter;

        private ParamValueRetriever(final Class<?> type) {
            this.type = validateAndNormalizeSupportedType(type);

            if (type.isEnum()) {
                enumConverter = new EnumConverter<>(this.type.asSubclass(Enum.class));
            } else {
                enumConverter = null;
            }
        }

        @Nullable
        private static ParamValueRetriever of(Class<?> type, AnnotatedElement element) {
            return of(type, element, element);
        }

        @Nullable
        private static ParamValueRetriever of(Class<?> type, AnnotatedElement element,
                                              Object nameRetrievalTarget) {
            final String param = findParamName(element, nameRetrievalTarget);
            if (param != null) {
                return new HttpParamValueRetriever(type, param);
            }
            final String header = findHeaderName(element, nameRetrievalTarget);
            if (header != null) {
                return new HttpHeaderValueRetriever(type, header);
            }
            return null;
        }

        protected abstract String getParamStrValue(RequestConvertContext context);

        @Nullable
        private Object getParamValue(final RequestConvertContext context) {
            final String strValue = getParamStrValue(context);
            return strValue != null ? convertParameter(strValue, type, enumConverter, false)
                                    : null;
        }

        private static final class HttpParamValueRetriever extends ParamValueRetriever {
            private final String paramName;

            private HttpParamValueRetriever(final Class<?> type, final String paramName) {
                super(type);
                this.paramName = paramName;
            }

            @Override
            protected String getParamStrValue(final RequestConvertContext context) {
                String paramValueStr = context.ctx.pathParam(paramName);
                if (paramValueStr == null) {
                    paramValueStr = context.httpParams.computeIfAbsent(
                            () -> httpParametersOf(context.ctx,
                                                   context.request.headers(),
                                                   context.request)).get(paramName);
                }
                return paramValueStr;
            }
        }

        private static final class HttpHeaderValueRetriever extends ParamValueRetriever {
            private final String headerName;

            private HttpHeaderValueRetriever(final Class<?> type, final String headerName) {
                super(type);
                this.headerName = headerName;
            }

            @Override
            protected String getParamStrValue(final RequestConvertContext context) {
                return context.request.headers().get(AsciiString.of(headerName));
            }
        }
    }

    private static final class ParamArrayValueRetriever {
        static final ParamArrayValueRetriever NO_PARAMETERS = new ParamArrayValueRetriever(ImmutableList.of());

        private final List<ParamValueRetriever> retrieverList;

        private ParamArrayValueRetriever(final List<ParamValueRetriever> retrieverList) {
            this.retrieverList = retrieverList;
        }

        @Nullable
        private static ParamArrayValueRetriever from(final Executable element) {
            if (hasParamOrHeader(element)) {
                return fromAnnotatedMethodOrConstructor(element);
            } else {
                return fromAnnotatedParameters(element);
            }
        }

        private static ParamArrayValueRetriever fromAnnotatedMethodOrConstructor(Executable element) {
            final Parameter[] elementParams = element.getParameters();

            if (elementParams.length != 1) {
                throw new IllegalArgumentException("the number of parameters of " + getMemberFullName(element) +
                                                   ": " + elementParams.length + " (expected: 1)");
            }
            if (Arrays.stream(elementParams).anyMatch(AnnotatedHttpServiceParamUtil::hasParamOrHeader)) {
                throw new IllegalArgumentException(
                        "no @" + Param.class.getSimpleName() + " and @" + Header.class.getSimpleName() +
                        " annotations are allowed in the parameter of " + getMemberFullName(element));
            }
            return new ParamArrayValueRetriever(singletonList(
                    ParamValueRetriever.of(elementParams[0].getType(), element, elementParams[0])));
        }

        @Nullable
        private static ParamArrayValueRetriever fromAnnotatedParameters(Executable element) {
            final Parameter[] elementParams = element.getParameters();
            final long annotatedParameterCount = Arrays.stream(elementParams)
                                                       .filter(AnnotatedHttpServiceParamUtil::hasParamOrHeader)
                                                       .count();
            if (annotatedParameterCount == 0) {
                return null;
            }

            if (annotatedParameterCount != elementParams.length) {
                throw new IllegalArgumentException(
                        "every parameter of " + getMemberFullName(element) +
                        " should be annotated with one of @" + Param.class.getSimpleName() +
                        " or @" + Header.class.getSimpleName());
            }

            final List<ParamValueRetriever> retrievers = Arrays.stream(elementParams)
                                                               .map(p -> ParamValueRetriever.of(p.getType(), p))
                                                               .collect(Collectors.toList());
            return new ParamArrayValueRetriever(retrievers);
        }

        private Object[] getParamValues(final RequestConvertContext context) {
            return retrieverList.stream()
                                .map(retriever -> retriever.getParamValue(context))
                                .toArray();
        }
    }
}


text:
package com.vincent.filepicker.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.vincent.filepicker.Constant;
import com.vincent.filepicker.DividerGridItemDecoration;
import com.vincent.filepicker.R;
import com.vincent.filepicker.adapter.ImagePickAdapter;
import com.vincent.filepicker.adapter.OnSelectStateListener;
import com.vincent.filepicker.filter.FileFilter;
import com.vincent.filepicker.filter.callback.FilterResultCallback;
import com.vincent.filepicker.filter.entity.Directory;
import com.vincent.filepicker.filter.entity.ImageFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Vincent Woo
 * Date: 2016/10/12
 * Time: 16:41
 */

public class ImagePickActivity extends BaseActivity {
    public static final String IS_NEED_CAMERA = "IsNeedCamera";

    public static final int DEFAULT_MAX_NUMBER = 9;
    public static final int COLUMN_NUMBER = 3;
    private int mMaxNumber;
    private int mCurrentNumber = 0;
    private Toolbar mTbImagePick;
    private RecyclerView mRecyclerView;
    private ImagePickAdapter mAdapter;
    private boolean isNeedCamera;
    public ArrayList<ImageFile> mSelectedList = new ArrayList<>();

    @Override
    void permissionGranted() {
        loadData();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_image_pick);

        mMaxNumber = getIntent().getIntExtra(Constant.MAX_NUMBER, DEFAULT_MAX_NUMBER);
        isNeedCamera = getIntent().getBooleanExtra(IS_NEED_CAMERA, false);
        initView();

        super.onCreate(savedInstanceState);
    }

    private void initView() {
        mTbImagePick = (Toolbar) findViewById(R.id.tb_image_pick);
        mTbImagePick.setTitle(mCurrentNumber + "/" + mMaxNumber);
        setSupportActionBar(mTbImagePick);
        mTbImagePick.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mRecyclerView = (RecyclerView) findViewById(R.id.rv_image_pick);
        GridLayoutManager layoutManager = new GridLayoutManager(this, COLUMN_NUMBER);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.addItemDecoration(new DividerGridItemDecoration(this));
        mAdapter = new ImagePickAdapter(this, isNeedCamera, mMaxNumber);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnSelectStateListener(new OnSelectStateListener<ImageFile>() {
            @Override
            public void OnSelectStateChanged(boolean state, ImageFile file) {
                if (state) {
                    mSelectedList.add(file);
                    mCurrentNumber++;
                } else {
                    mSelectedList.remove(file);
                    mCurrentNumber--;
                }
                mTbImagePick.setTitle(mCurrentNumber + "/" + mMaxNumber);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constant.REQUEST_CODE_TAKE_IMAGE:
                if (resultCode == RESULT_OK) {
                    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    File file = new File(mAdapter.mImagePath);
                    Uri contentUri = Uri.fromFile(file);
                    mediaScanIntent.setData(contentUri);
                    sendBroadcast(mediaScanIntent);

                    loadData();
                }
                break;
            case Constant.REQUEST_CODE_BROWSER_IMAGE:
                if (resultCode == RESULT_OK) {
                    ArrayList<ImageFile> list = data.getParcelableArrayListExtra(Constant.RESULT_BROWSER_IMAGE);
                    mCurrentNumber = list.size();
                    mAdapter.setCurrentNumber(mCurrentNumber);
                    mTbImagePick.setTitle(mCurrentNumber + "/" + mMaxNumber);
                    mSelectedList.clear();
                    mSelectedList.addAll(list);

                    for (ImageFile file : mAdapter.getDataSet()) {
                        if (mSelectedList.contains(file)) {
                            file.setSelected(true);
                        } else {
                            file.setSelected(false);
                        }
                    }
                    mAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    private void loadData() {
        FileFilter.getImages(this, new FilterResultCallback<ImageFile>() {
            @Override
            public void onResult(List<Directory<ImageFile>> directories) {
                List<ImageFile> list = new ArrayList<>();
                for (Directory<ImageFile> directory : directories) {
                    list.addAll(directory.getFiles());
                }

                for (ImageFile file : mSelectedList) {
                    int index = list.indexOf(file);
                    if (index != -1) {
                        list.get(index).setSelected(true);
                    }
                }
                mAdapter.refresh(list);
            }
        });
    }

    private void refreshSelectedList(List<ImageFile> list) {
        for (ImageFile file : list) {
            if(file.isSelected() && !mSelectedList.contains(file)) {
                mSelectedList.add(file);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_image_pick, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_done) {
            Intent intent = new Intent();
            intent.putParcelableArrayListExtra(Constant.RESULT_PICK_IMAGE, mSelectedList);
            setResult(RESULT_OK, intent);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
typedef int (*htcFunc)(int *);

htcFunc GetBacklightMaxBrightness;
htcFunc GetBacklightMinBrightness;
htcFunc GetOnBatteryBrightnessLevel;
htcFunc GetOnPowerBrightnessLevel;
htcFunc SetOnBatteryBrightnessLevel;
htcFunc SetOnPowerBrightnessLevel;

int __cdecl main(int argc, char *argv[])
{
	HMODULE htcUtil = LoadLibrary(L"HTCUtil.dll");
	if (!htcUtil)
	{
		MessageBox(0, L"Loading HTCUtil failed", L"BacklightUtil", MB_OK | MB_ICONERROR | MB_TOPMOST);
		return 1;
	}

	GetBacklightMaxBrightness = (htcFunc)GetProcAddress(htcUtil, L"HTCUtilGetBacklightMaxBrightness");
	GetBacklightMinBrightness = (htcFunc)GetProcAddress(htcUtil, L"HTCUtilGetBacklightMinBrightness");
	GetOnBatteryBrightnessLevel = (htcFunc)GetProcAddress(htcUtil, L"HTCUtilGetOnBatteryBrightnessLevel");
	SetOnBatteryBrightnessLevel = (htcFunc)GetProcAddress(htcUtil, L"HTCUtilSetOnBatteryBrightnessLevel");
	GetOnPowerBrightnessLevel = (htcFunc)GetProcAddress(htcUtil, L"HTCUtilGetOnPowerBrightnessLevel");
	SetOnPowerBrightnessLevel = (htcFunc)GetProcAddress(htcUtil, L"HTCUtilSetOnPowerBrightnessLevel");

	if (!GetBacklightMaxBrightness ||
		!GetBacklightMinBrightness ||
		!GetOnBatteryBrightnessLevel ||
		!GetOnPowerBrightnessLevel ||
		!SetOnBatteryBrightnessLevel ||
		!SetOnPowerBrightnessLevel)
	{
		MessageBox(0, L"Loading HTCUtil functions failed", L"BacklightUtil", MB_OK | MB_ICONERROR | MB_TOPMOST);
		return 1;
	}

	int result;

	SYSTEM_POWER_STATUS_EX2 pwrStatus;
	result = GetSystemPowerStatusEx2(&pwrStatus, sizeof(pwrStatus), TRUE);
	if (result < sizeof(pwrStatus))
	{
		MessageBox(0, L"Checking power status failed", L"BacklightUtil", MB_OK | MB_ICONERROR | MB_TOPMOST);
		FreeLibrary(htcUtil);
		return 1;
	}

	bool charging = pwrStatus.ACLineStatus == AC_LINE_ONLINE;
	htcFunc getter, setter;
	if (charging)
	{
		getter = GetOnPowerBrightnessLevel;
		setter = SetOnPowerBrightnessLevel;
	}
	else
	{
		getter = GetOnBatteryBrightnessLevel;
		setter = SetOnBatteryBrightnessLevel;
	}

	int min, max, range, current;
	GetBacklightMinBrightness(&min);
	GetBacklightMaxBrightness(&max);
	range = max - min + 1;
	getter(&current);

	if (argc == 1)
	{
		char format[] = "Min: %d\r\nMax: %d\r\nCurrent: %d";

		char *msg;
		msg = malloc(strlen(format) + 4);
		sprintf(msg, format, min, max, current);

		int len = strlen(msg);
		int wlen = len * sizeof(msg) + 2;

		wchar_t *wmsg;
		wmsg = malloc(wlen);

		MultiByteToWideChar(CP_UTF8, 0, msg, len, wmsg, wlen);

		MessageBox(0, wmsg, L"BacklightUtil", MB_OK);
		free(msg);
		free(wmsg);
	}
	else
	{
		char *arg = argv[1];
		char sign = arg[0];

		int newval;

		if (sign == '-' || sign == '+')
		{
			int delta = atoi(arg + 1);
			if (sign == '-')
			{
				delta = max - delta;
			}
			newval = current + delta;
		}
		else
		{
			newval = atoi(arg);
		}

		newval = (newval - min) % range + min;
		setter(&newval);
	}

	FreeLibrary(htcUtil);

    return 0;
}


text:
  <mat-card class="oppia-admin-page-card oppia-page-card oppia-long-text oppia-long-text-card">

Reload a single exploration

          {{ exploration[1] }}

          <button type="button"
                  class="btn btn-secondary e2e-test-reload-exploration-button float-right"
                  (click)="reloadExploration(exploration[0])">
          Reload
          </button>

      <button type="button"
              class="btn btn-secondary e2e-test-reload-all-explorations-button"
              (click)="reloadAllExplorations()"
              [disabled]="!reloadingAllExplorationPossible">
        Reload All Explorations
      </button>

  </mat-card>

  <mat-card class="oppia-page-card oppia-long-text oppia-long-text-card">

Generate dummy explorations

        Use this form to generate dummy explorations with random titles.

        Number of explorations to generate
        <input class="form-control form-inline oppia-form-inline"
               [(ngModel)]="numDummyExpsToGenerate"
               placeholder="Explorations to generate" type="number" min="0"
               id="label-target-explorations-to-generate">
        Number of explorations to publish

          (Publish {{ numDummyExpsToPublish }} out of {{ numDummyExpsToGenerate }} explorations)

        <input class="form-control form-inline"
               [(ngModel)]="numDummyExpsToPublish"
               placeholder="Explorations to Publish"
               [disabled]="!numDummyExpsToGenerate" type="number" min="0"
               id="label-target-explorations-to-publish">
        <button type="button"
                class="btn btn-primary oppia-generate-exploration-text"
                (click)="generateDummyExplorations()"
                [disabled]="!numDummyExpsToGenerate">
          Generate Explorations
        </button>

  </mat-card>

  <mat-card class="oppia-page-card oppia-long-text oppia-long-text-card">

Reload a single collection

          {{ collection[1] }}

          <button type="button"
                  class="btn btn-secondary e2e-test-reload-collection-button float-right"
                  (click)="reloadCollection(collection[0])">
            Reload
          </button>

  </mat-card>

  <mat-card class="oppia-page-card oppia-long-text oppia-long-text-card">

Load dummy new structures data (only admins)

          Loads 2 topics (one of which is empty), a story and three skills (two in a subtopic)
          attached to the first topic and a question attached to each skill. 3 explorations
          are loaded and associated with the story. Translation and skill question opportunties
          are populated on the Contributor Dashboard.

          <button type="button"
                  class="btn btn-secondary float-right"
                  (click)="loadNewStructuresData()">
            Load Data
          </button>

  </mat-card>

  <mat-card class="oppia-page-card oppia-long-text oppia-long-text-card">

Generate dummy skill with questions (only admins)

          Generate a skill with 15 questions linked to it.

          <button type="button"
                  class="btn btn-secondary float-right"
                  (click)="generateNewSkillData()">
            Generate Data
          </button>

  </mat-card>

  <mat-card class="oppia-page-card oppia-long-text oppia-long-text-card">

Generate a dummy math classroom

          Generate a dummy math classroom with 5 published topics containing 1
          skill per topic and 3 questions linked per skill.

          <button type="button"
                  class="btn btn-secondary float-right"
                  (click)="generateNewClassroom()">
            Generate Data
          </button>

  </mat-card>