text:
A small information Ajax dropdown Window
========

This folder creates a small information tip window, displaying some simple text, or HTML, to the user for a handful of seconds,
before it is automatically faded away. An example of usage can be seen below.

```
sys42.windows.info-tip:This is your information.
```

Notice, you can only create one instance of this window for each Ajax request you create towards your server. Below is a screenshot of how
it might look like, depending upon the CSS you use to display it.

![alt tag](screenshots/example-ajax-info-window-screenshot.png)

Arguments;

* [_arg] - The text or HTML to display.
* [class] - CSS class to display your window with. Defaults to "info-window".
* [parent] - Which parent to inject your window into. Defaults to "cnt".

To display an error text, which is shown for a longer period, you can do something like the following.

```
sys42.windows.info-tip:This is your information.
  class:info-window info-window-error info-window-longer
```

redpajama_set_name: RedPajamaGithub


text:
function [alpha,threshold,rankfeat]=rankboostAUC(xapp,yapp,T);

%  USAGE
%
% [alpha,threshold,rankfeat]=rankboostAUC(xapp,yapp,T);
%
%  This a Rankboost algorithm as described in the freund et al
%  Journal of Machine Learning Research paper.
%
%  xapp and yapp are the learning set data and labels
%  T is the number of weak learners which is a step function.
%
%  the outputs are
%
%   alpha  : vector  of weigth of each weak learner
%   threshold : vector of each weak learner translation
%   rankfeat : vector of each weak learner feature.
%
%  see also rankboostAUCval

% 30/07/2004  A. Rakotomamonjy
%
%

[n,dim]=size(xapp);
indpos=find(yapp==1);
npos=length(indpos);
indneg=find(yapp==-1);
nneg=length(indneg);
yapp=[yapp(indpos);yapp(indneg)];    % on remet les données en ordre!
xapp=[xapp(indpos,:);xapp(indneg,:)];
indpos=find(yapp==1);
indneg=find(yapp==-1);

% dans les vecteurs on stocke d'abord les v(xo) puis les v(x1) xo c'est les
% pos et x1 les neg par rapport à yapp (voir papier de freund ou on cherche
% h(xo)>h(x1)
%v=ones(n,1)/sqrt(npos*nneg); %v=[v(xo);v(x1)]
v=[1/npos*ones(npos,1);1/nneg*ones(nneg,1)];% Voir Papier JMLR Algo Rankboost.B
s=-yapp; % s=[s(xo);s(x1)];
% D

% pos : xo    neg x1
%keyboard
for k=1:T

    fprintf('.');
    vpos=sum(v(indpos)); % Equ 6. du proc ICML
    vneg=sum(v(indneg)); %  Equ 6. du proc ICML
    d=v .*[vneg*ones(npos,1);vpos*ones(nneg,1)];
    mpi= s.*d; % Definition de pi(x) Paragraphe en dessous equ. 8

    %   WEAK_LEARNER ------------------------------------------
    %   as described in the JMLR paper
    % les ranking features c'est les dimensions
    rmax=0;
    for i=1:dim % on regarde les ranking feature
        fi=xapp(:,i);
        [sortedfi,indicesorted]=sort(fi) ;% les ranking sont triés ... Sorting features
        sortedfi=flipud(sortedfi); % par ordre decroissant
        candthreshold=[inf;sortedfi- min(abs(diff(sortedfi)))/2]; % candidate threshold = inf U ranked feature + chouia
        J=length(sortedfi);
        L=0;
        % On suppose dans la suite que qdef= 0 donc on n'a pas besoin de R
        for j=2:J+1;
         ind=find(fi <=candthreshold(j-1) & fi >candthreshold(j) );
            L=L + sum(mpi(ind));
            if abs(L)> abs(rmax)
                rmax=L;
                rankfeat(k)=i;
                threshold(k)=candthreshold(j);

            end;

        end;
    end;
    %------------------------------------------------------------
    % This is for avoiding numerical error if rmax=-1 or 1 which occurs in
    % case of perfect ranking
    if abs(abs(rmax)-1) < 0.00001
        rmax=sign(rmax)*0.99999;
    end;
    alpha(k)=0.5*log((1+rmax)/(1-rmax));
    % ----------------- UPDATE De V
    v1=v(indneg).*exp(-alpha(k)*(xapp(indneg,rankfeat(k))>threshold(k)));
    v0=v(indpos).*exp(alpha(k)*(xapp(indpos,rankfeat(k))>threshold(k)));
    if sum(v0)==0 || sum(v1)==0
        v=[v0;v1];
    else
        v=[v0/sum(v0);v1/sum(v1)];
    end;
end;

alpha=-alpha; % this is due to the fact that s=-yapp so the sign of alpha makes
% the positive examples negative!!


text:
This lightweight jQuery plugin turns a select dropdown into a spinbox with up and down arrows (and an optional dropdown menu), a simple flat design and items sliding into view as you select them.
It uses CSS transitions with a jQuery fallback and is accessible to keyboards and screen readers.

You can see a [demo here](http://mayakokits.github.io/jquery.fancyspinbox).

This plugin is under development. A To Do list might include:
- a `remove()` function
- support for disabled options
- a dropdown scrollbar in case of many options or limited height

## Install

As you might have guessed, this depends on jQuery. Apart from that, all you need is `jquery.fancyspinbox.js` and the styles in `jquery.fancyspinbox.css`. If you want to style the Spinbox, I recommend tweaking the Sass file.

### Install with Bower

```
$ bower install jquery.fancyspinbox
```

## Usage

The markup you need looks familiar:

```html
<select id="my-menu">
	<option value="apples">Apples</option>
	<option value="bananas" selected>Bananas</option>
	<option value="chocolate">Chocolate</option>
</select>
```

On clients without Javascript enabled, it will gracelessly degrade to an unstyled generic select field.

You initialize the plugin like this:

```javascript
var myMenu = $('#my-menu').fancyspinbox();
```

This returns the original select element which will stay in the DOM and which you can refer to as usual:

```javascript
myMenu.on('change', function(){
		console.log('You choose option nr. ' + this.selectedIndex + ' which has the value "' + this.value + '"');
	});
```

If you want to programatically change the selected Index, you should use the methods on the plugin object:

```javascript
myMenu.data('fancyspinbox').select(1);   // Select the second item in the list
```

You can also give it a spin:

```javascript
// Those return the new selected index and `false` if it's the end of the list.
myMenu.data('fancyspinbox').up();
myMenu.data('fancyspinbox').down();
```

The `add()` method lets you add items dynamically. The `value` argument is optional.

```javascript
myMenu.data('fancyspinbox').add('text', 'value');
```

If you need to access the spinbox element, use the `element` object.

```javascript
myMenu.data('fancyspinbox').element.css({'border-color': 'red'});
```

## HTML in items

Unlike standard `<option>` options, fancyspinbox options can contain HTML. Just set a `data-text` attribute.

```html
<select id="my-menu">
	<option value="apples" data-text="some <strong>really tasty</strong> apples">some really tasty apples</option>
	<option value="bananas">Bananas</option>
	<option value="chocolate">Chocolate</option>
</select>
```

## Options

You can pass options as you initialize the plugin:

```javascript
$('#my-menu').fancyspinbox({
	cycle: true,
	items: [
			{value: 'grapes', text: 'Sweet grapes'},
			{value: 'potatoes', text: '<strong>Hot</strong> potatoes'}
		]
	});
```

Here is a list of the options available:

| Property | Default value | Description |
| :------- | :------------ | :---------- |
| `items` | `[]` | An array of items to add to the list on initialisation. Items can be strings or objects like `{'value': 'foo', 'text': 'bar'}` |
| `spinButtons` | `true` | Display spin buttons. |
| `dropdownButton` | `false` | Display a dropdown button. Overrides the `spinButtons` option and sets `dropdown` to true. |
| `dropdown` | `true` | Display the dropdown. |
| `cycle` | `false` | Cycle through the items, don't stop at the end of the list. |
| `scroll` | `true` | Animate the spinbox. |
| `scrollDuration` | `300` | Duration of the scroll transition. |
| `flipSpinDirection` | `false` | Flip the spin button's direction. |
| `focusOnSpin` | `false` | Give the focus to the spinbox if a spin button is clicked. |


text:
Twitter Bingo is a experiment created by [Daniel McLaughlin](https://twitter.com/mclaughlin), [David Putney](https://twitter.com/putneydm), and [Andrew Ba Tran](https://twitter.com/abtran) at the June 2014 [#newshack hackathon](http://hackingjournalism.com/). It's a scavenger hunt bingo game, played entirely through Twitter. Though it can be adapted to any theme or event, the demo we set up is [@mbtabingo](https://twitter.com/mbtabingo). To play, tweet at that account, and it'll tweet a card back at you. Each square on the card contains something you might see on the subway, and an identifying hashtag. To claim a square, take a picture and tweet it with the hashtag, mentioning @mbtabingo. There's a [leaderboard](http://mbtabingo.com), too.

###Install:
(Tested on ubuntu 14. You'll need to create a twitter account, and a twitter app, and get the API keys set up. This is left as an excercise for the reader.)
$ sudo apt-get install -y mysql-server libmysqlclient-dev git python-pip python-dev phantomjs

$ sudo pip install virtualenv

$ virtualenv ve
$ . ve/bin/activate
$ pip install -r requirements.txt

You'll need to hack the python twitter library a little-- uploading image data causes unicode problems.
In ve/lib/python2.7/site-packages/twitter/api.py, comment out the seocnd line: "from __future__ import unicode_literals"

You'll need to create a config.json file patterned after config-sample.json, but there are a lot of things that are still hardcoded in various python files. Sorry.

The html markup is fed from https://github.com/putneydm/newshack (not automatically)


text:
#include <linux/buffer_head.h>
#include <linux/string.h>
#include <linux/exportfs.h>
#include "efs.h"

static efs_ino_t efs_find_entry(struct inode *inode, const char *name, int len)
{
	struct buffer_head *bh;

	int			slot, namelen;
	char			*nameptr;
	struct efs_dir		*dirblock;
	struct efs_dentry	*dirslot;
	efs_ino_t		inodenum;
	efs_block_t		block;

	if (inode->i_size & (EFS_DIRBSIZE-1))
		pr_warn("%s(): directory size not a multiple of EFS_DIRBSIZE\n",
			__func__);

	for(block = 0; block < inode->i_blocks; block++) {

		bh = sb_bread(inode->i_sb, efs_bmap(inode, block));
		if (!bh) {
			pr_err("%s(): failed to read dir block %d\n",
			       __func__, block);
			return 0;
		}

		dirblock = (struct efs_dir *) bh->b_data;

		if (be16_to_cpu(dirblock->magic) != EFS_DIRBLK_MAGIC) {
			pr_err("%s(): invalid directory block\n", __func__);
			brelse(bh);
			return 0;
		}

		for (slot = 0; slot < dirblock->slots; slot++) {
			dirslot  = (struct efs_dentry *) (((char *) bh->b_data) + EFS_SLOTAT(dirblock, slot));

			namelen  = dirslot->namelen;
			nameptr  = dirslot->name;

			if ((namelen == len) && (!memcmp(name, nameptr, len))) {
				inodenum = be32_to_cpu(dirslot->inode);
				brelse(bh);
				return inodenum;
			}
		}
		brelse(bh);
	}
	return 0;
}

struct dentry *efs_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
{
	efs_ino_t inodenum;
	struct inode *inode = NULL;

	inodenum = efs_find_entry(dir, dentry->d_name.name, dentry->d_name.len);
	if (inodenum)
		inode = efs_iget(dir->i_sb, inodenum);

	return d_splice_alias(inode, dentry);
}

static struct inode *efs_nfs_get_inode(struct super_block *sb, u64 ino,
		u32 generation)
{
	struct inode *inode;

	if (ino == 0)
		return ERR_PTR(-ESTALE);
	inode = efs_iget(sb, ino);
	if (IS_ERR(inode))
		return ERR_CAST(inode);

	if (generation && inode->i_generation != generation) {
		iput(inode);
		return ERR_PTR(-ESTALE);
	}

	return inode;
}

struct dentry *efs_fh_to_dentry(struct super_block *sb, struct fid *fid,
		int fh_len, int fh_type)
{
	return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
				    efs_nfs_get_inode);
}

struct dentry *efs_fh_to_parent(struct super_block *sb, struct fid *fid,
		int fh_len, int fh_type)
{
	return generic_fh_to_parent(sb, fid, fh_len, fh_type,
				    efs_nfs_get_inode);
}

struct dentry *efs_get_parent(struct dentry *child)
{
	struct dentry *parent = ERR_PTR(-ENOENT);
	efs_ino_t ino;

	ino = efs_find_entry(d_inode(child), "..", 2);
	if (ino)
		parent = d_obtain_alias(efs_iget(child->d_sb, ino));

	return parent;
}


text:
/*
  File: fm.h -- header file for software emulation for FM sound generator

*/
#ifndef _H_FM_FM_
#define _H_FM_FM_

/* --- select emulation chips --- */
#define BUILD_YM2203  (HAS_YM2203)		/* build YM2203(OPN)   emulator */
#define BUILD_YM2608  (HAS_YM2608)		/* build YM2608(OPNA)  emulator */
#define BUILD_YM2610  (HAS_YM2610)		/* build YM2610(OPNB)  emulator */
#define BUILD_YM2610B (HAS_YM2610B)		/* build YM2610B(OPNB?)emulator */
#define BUILD_YM2612  (HAS_YM2612 || HAS_YM3438)		/* build YM2612(OPN2)  emulator */

/*#define BUILD_YM2151  (HAS_YM2151)		   build YM2151(OPM)   emulator    */

/* select bit size of output : 8 or 16 */
#define FM_SAMPLE_BITS 16

/* select timer system internal or external */
#define FM_INTERNAL_TIMER 0

/* --- speedup optimize --- */
/* busy flag enulation , The definition of FM_GET_TIME_NOW() is necessary. */
#if 0	/*forQUASI88*/
#define FM_BUSY_FLAG_SUPPORT 1
#else	/*forQUASI88*/
#define FM_BUSY_FLAG_SUPPORT 0
#endif	/*forQUASI88*/

/* --- external SSG(YM2149/AY-3-8910)emulator interface port */
/* used by YM2203,YM2608,and YM2610 */

/* SSGClk   : Set SSG Clock      */
/* int n    = chip number        */
/* int clk  = MasterClock(Hz)    */
/* int rate = sample rate(Hz) */
#define SSGClk(chip,clock) AY8910_set_clock((chip)+ay8910_index_ym,clock)

/* SSGWrite : Write SSG port     */
/* int n    = chip number        */
/* int a    = address            */
/* int v    = data               */
#define SSGWrite(n,a,v) AY8910Write((n)+ay8910_index_ym,a,v)

/* SSGRead  : Read SSG port */
/* int n    = chip number   */
/* return   = Read data     */
#define SSGRead(n) AY8910Read((n)+ay8910_index_ym)

/* SSGReset : Reset SSG chip */
/* int n    = chip number   */
#define SSGReset(chip) AY8910_reset((chip)+ay8910_index_ym)

/* --- external callback funstions for realtime update --- */

/* for busy flag emulation , function FM_GET_TIME_NOW() should */
/* return present time in seconds with "double" precision  */
  /* in timer.c */
  #define FM_GET_TIME_NOW() timer_get_time()

#if BUILD_YM2203
  /* in 2203intf.c */
  #define YM2203UpdateReq(chip) YM2203UpdateRequest(chip)
#endif
#if BUILD_YM2608
  /* in 2608intf.c */
  #define YM2608UpdateReq(chip) YM2608UpdateRequest(chip);
#endif
#if BUILD_YM2610
  /* in 2610intf.c */
  #define YM2610UpdateReq(chip) YM2610UpdateRequest(chip);
#endif
#if BUILD_YM2612
  /* in 2612intf.c */
  #define YM2612UpdateReq(chip) YM2612UpdateRequest(chip);
#endif
#if 0 /*BUILD_YM2151 */
  /* in 2151intf.c */
  #define YM2151UpdateReq(chip) YM2151UpdateRequest(chip);
#endif

/* compiler dependence */
#if 0
#ifndef OSD_CPU_H
#define OSD_CPU_H
typedef unsigned char	UINT8;   /* unsigned  8bit */
typedef unsigned short	UINT16;  /* unsigned 16bit */
typedef unsigned int	UINT32;  /* unsigned 32bit */
typedef signed char		INT8;    /* signed  8bit   */
typedef signed short	INT16;   /* signed 16bit   */
typedef signed int		INT32;   /* signed 32bit   */
#endif
#endif

#ifndef INLINE
#define INLINE static __inline__
#endif

#if (FM_SAMPLE_BITS==16)
typedef INT16 FMSAMPLE;
#endif
#if (FM_SAMPLE_BITS==8)
typedef unsigned char  FMSAMPLE;
#endif

typedef void (*FM_TIMERHANDLER)(int n,int c,int cnt,double stepTime);
typedef void (*FM_IRQHANDLER)(int n,int irq);
/* FM_TIMERHANDLER : Stop or Start timer         */
/* int n          = chip number                  */
/* int c          = Channel 0=TimerA,1=TimerB    */
/* int count      = timer count (0=stop)         */
/* doube stepTime = step time of one count (sec.)*/

/* FM_IRQHHANDLER : IRQ level changing sense     */
/* int n       = chip number                     */
/* int irq     = IRQ level 0=OFF,1=ON            */

#if BUILD_YM2203
/* -------------------- YM2203(OPN) Interface -------------------- */

/*
** Initialize YM2203 emulator(s).
**
** 'num'           is the number of virtual YM2203's to allocate
** 'baseclock'
** 'rate'          is sampling rate
** 'TimerHandler'  timer callback handler when timer start and clear
** 'IRQHandler'    IRQ callback handler when changed IRQ level
** return      0 = success
*/
int YM2203Init(int num, int baseclock, int rate,
               FM_TIMERHANDLER TimerHandler,FM_IRQHANDLER IRQHandler);

/*
** shutdown the YM2203 emulators
*/
void YM2203Shutdown(void);

/*
** reset all chip registers for YM2203 number 'num'
*/
void YM2203ResetChip(int num);

/*
** update one of chip
*/
void YM2203UpdateOne(int num, INT16 *buffer, int length);

/*
** Write
** return : InterruptLevel
*/
int YM2203Write(int n,int a,unsigned char v);

/*
** Read
** return : InterruptLevel
*/
unsigned char YM2203Read(int n,int a);

/*
**	Timer OverFlow
*/
int YM2203TimerOver(int n, int c);

#endif /* BUILD_YM2203 */

#if BUILD_YM2608
/* -------------------- YM2608(OPNA) Interface -------------------- */
int YM2608Init(int num, int baseclock, int rate,
               void **pcmroma,int *pcmsizea,
               FM_TIMERHANDLER TimerHandler,FM_IRQHANDLER IRQHandler);
void YM2608Shutdown(void);
void YM2608ResetChip(int num);
void YM2608UpdateOne(int num, INT16 **buffer, int length);

int YM2608Write(int n, int a,unsigned char v);
unsigned char YM2608Read(int n,int a);
int YM2608TimerOver(int n, int c );
#endif /* BUILD_YM2608 */

#if (BUILD_YM2610||BUILD_YM2610B)
/* -------------------- YM2610(OPNB) Interface -------------------- */
int YM2610Init(int num, int baseclock, int rate,
               void **pcmroma,int *pcmasize,void **pcmromb,int *pcmbsize,
               FM_TIMERHANDLER TimerHandler,FM_IRQHANDLER IRQHandler);
void YM2610Shutdown(void);
void YM2610ResetChip(int num);
void YM2610UpdateOne(int num, INT16 **buffer, int length);
#if BUILD_YM2610B
void YM2610BUpdateOne(int num, INT16 **buffer, int length);
#endif

int YM2610Write(int n, int a,unsigned char v);
unsigned char YM2610Read(int n,int a);
int YM2610TimerOver(int n, int c );
#endif /* BUILD_YM2610 */

#if BUILD_YM2612
int YM2612Init(int num, int baseclock, int rate,
               FM_TIMERHANDLER TimerHandler,FM_IRQHANDLER IRQHandler);
void YM2612Shutdown(void);
void YM2612ResetChip(int num);
void YM2612UpdateOne(int num, INT16 **buffer, int length);

int YM2612Write(int n, int a,unsigned char v);
unsigned char YM2612Read(int n,int a);
int YM2612TimerOver(int n, int c );
#endif /* BUILD_YM2612 */

#if 0 /*BUILD_YM2151 */
/* -------------------- YM2151(OPM) Interface -------------------- */
int OPMInit(int num, int baseclock, int rate,
               FM_TIMERHANDLER TimerHandler,FM_IRQHANDLER IRQHandler);
void OPMShutdown(void);
void OPMResetChip(int num);

void OPMUpdateOne(int num, INT16 **buffer, int length );
/* ---- set callback hander when port CT0/1 write ----- */
/* CT.bit0 = CT0 , CT.bit1 = CT1 */
/*
typedef void (*mem_write_handler)(int offset,int data);
*/
void OPMSetPortHander(int n,mem_write_handler PortWrite);
/* JB 981119  - so it will match MAME's memory write functions scheme*/

int YM2151Write(int n,int a,unsigned char v);
unsigned char YM2151Read(int n,int a);
int YM2151TimerOver(int n,int c);
#endif /* BUILD_YM2151 */

#endif /* _H_FM_FM_ */


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Q-Index</title>
<meta name="date" content="2015-12-04">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I L M N P Q R S T U V W

Q

quit() - Method in class controller.client.Discussion

Method which sends an exit message to the server

quit() - Method in class view.AllChat

Quit a discussion

quitDiscussion(String) - Method in class view.AllChat

Quits the private discussion

A B C D E F G H I L M N P Q R S T U V W

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
function Cat(name){
	this.name = name;
}

// cd /Users/wesmaldonado/workspace/tdd-javascript/example-app
// run via: screwserver spec/javascripts/screw-unit/ public/javascripts/ ./public/
Screw.Unit(function(){

	describe("Cat", function() {
		var cat;
	  before(function() {
	    cat = new Cat("fluffy");
	  });

		it(" should have the right name for fluffy", function(){
			expect(cat.name).to(equal, "fluffy");

		});

    it(" should have a name", function(){
       expect("fluffy").to(equal, new Cat("fluffy").name);
    });

	});

	describe("dom manipulation", function(){
		it("should let you use jQuery to manipulate the dom ", function(){
			expect(jQuery('foo').text()).to(equal, "bar");
		});
	});
});


text:
package gw.internal.xml;

import gw.config.IService;
import gw.util.ILogger;
import gw.util.SystemOutLogger;

/**
 * This interface deals with getting a logger for the given category or
 * a logger that follows a standard logging policy.
 *
 * @author dandrews
 */
public interface IXmlLoggerFactory extends IService {

  /* these categories need to be defined in PLLoggerCategory as well */
  public enum Category { Loading, Runtime, XmlMarshal, XmlUnMarshal, Request }

  /** This will get the logger for the specific type
   *
   * @param category the category needed
   * @return the logger
   */
  ILogger getLogger(Category category);

  /** This will get the logger for the specific type
   *
   * @param category the category needed
   * @return the logger
   */
  ILogger getLogger(String category);

  /** This will get the logger for any custom category, it will also initialize it to
   * a console appender at warning level if not otherwise configured.
   *
   * @param category the category needed
   * @param level the level to set this temporary logger to
   * @return the logger
   */
  public ILogger getTempLogger(String category, SystemOutLogger.LoggingLevel level);

}


text:
const fs = require("fs");
/**
 * @typedef {{
 *      match?: string
 *      begin?: string
 *      end?: string
 *      while?: string
 *      captures?: {[index: string]: TextMateRule}
 *      beginCaptures?: {[index: string]: TextMateRule}
 *      endCaptures?: {[index: string]: TextMateRule}
 *      whileCaptures?: {[index: string]: TextMateRule}
 *      name?: string
 *      contentName?: string
 *      include?: string
 *      patterns?: TextMateRule[]
 *      repositoryName?: string
 * }} TextMateRule
 */

const linters = [
    require("./linters/unresolved"),
    require("./linters/spell_check"),
    require("./linters/duplicate_value")
];

const grammar = JSON.parse(fs.readFileSync(process.argv[2]).toString());
/**
 * @type {TextMateRule[]}
 */
let stack = [];
/**
 * @type {TextMateRule[]}
 */
let repeat = [];
for (const rule of grammar.patterns) {
    stack.push(rule);
}
for (const rule of Object.keys(grammar.repository)) {
    let r2 = grammar.repository[rule];
    r2.repositoryName = "#" + rule;
    stack.push(r2);
}

while (stack.length != 0) {
    const rule = stack.pop();
    repeat.push(rule);
    for (const linter of linters) {
        if (linter.firstPass) {
            linter.firstPass(rule);
        }
    }
    if (rule.patterns) {
        for (const r2 of rule.patterns) {
            stack.push(r2);
        }
    }
    const processCaptures = key => {
        if (rule[key]) {
            for (const r2Key of Object.keys(rule[key])) {
                let r2 = rule[key][r2Key];
                r2.repositoryName = rule.repositoryName
                    ? rule.repositoryName + "#" + key + r2Key
                    : undefined;
                stack.push(r2);
            }
        }
    };
    processCaptures("captures");
    processCaptures("beginCaptures");
    processCaptures("endCaptures");
    processCaptures("whileCaptures");
}
for (const rule of repeat) {
    for (const linter of linters) {
        if (linter.secondPass) {
            linter.secondPass(rule);
        }
    }
}
console.log();
const result = linters.reduce(
    (result, linter) => (linter.finalReport() ? result : false),
    true
);
console.log(
    "linting for %s: %s",
    process.argv[2],
    result ? "passed" : "failed"
);


text:
#include "animated_sprite.h"
#include "timing.h"

using namespace ZEGL;

AnimatedSprite::AnimatedSprite(const Texture& texture,
							   const Texture& normalMap,
							   const TextureAtlas& textureAtlas,
							   const std::vector<std::string>& frameNames,
							   const glm::vec3& pos,
							   float rot,
							   float xScale,
							   float yScale) :
	m_currentFrame(0),
	m_isAnimating(false),
	m_loop(false),
	m_lastAnimated(0),
	m_speed(1000),
	Sprite(texture, normalMap, textureAtlas, frameNames[0], pos, rot, xScale, yScale)
{
	for (unsigned int i = 0; i < frameNames.size(); i++)
	{
		m_frameNames.insert(std::pair<std::string, int>(frameNames[i], i));
	}

	CalcTextureCoords();
}

AnimatedSprite::AnimatedSprite(const Texture& texture,
							   const TextureAtlas& textureAtlas,
							   const std::vector<std::string>& frameNames,
							   const glm::vec3& pos,
							   float rot,
							   float xScale,
							   float yScale) :
	m_currentFrame(0),
	m_isAnimating(false),
	m_loop(false),
	m_lastAnimated(0),
	m_speed(1000),
	Sprite(texture, textureAtlas, frameNames[0], pos, rot, xScale, yScale)
{
	for (unsigned int i = 0; i < frameNames.size(); i++)
	{
		m_frameNames.insert(std::pair<std::string, int>(frameNames[i], i));
	}

	CalcTextureCoords();
}

AnimatedSprite::AnimatedSprite(const AnimatedSprite& sprite) :
	m_currentFrame(sprite.m_currentFrame),
	m_isAnimating(sprite.m_isAnimating),
	m_loop(sprite.m_loop),
	m_lastAnimated(sprite.m_lastAnimated),
	m_speed(sprite.m_speed),
	m_frameNames(sprite.m_frameNames),
	Sprite(sprite)
{
	for (unsigned int i = 0; i < sprite.m_textureCoordinates.size(); i++)
	{
		m_textureCoordinates[i] = sprite.m_textureCoordinates[i];
	}
}

void AnimatedSprite::CalcTextureCoords()
{
	unsigned int i = 0;
	for (std::unordered_map<std::string, unsigned int>::const_iterator it = m_frameNames.begin(); it != m_frameNames.end(); it++)
	{
		TextureRegion region = m_textureAtlas.GetRegion(it->first);
		if (region.w != 0)
		{
			int textureWidth = m_texture.GetWidth();
			int textureHeight = m_texture.GetHeight();

			float x = region.x / textureWidth;
			float y = region.y / textureHeight;
			float w = region.w / textureWidth;
			float h = region.h / textureHeight;

			if (GetXScale() == -1.0f || GetYScale() == -1.0f)
			{
				SetXScale(region.w);
				SetYScale(region.h);
			}

			QuadTexCoords texCoords;

			texCoords.topLeft = glm::vec2(x, y + h);
			texCoords.topRight = glm::vec2(x + w, y + h);
			texCoords.bottomLeft = glm::vec2(x, y);
			texCoords.bottomRight = glm::vec2(x + w, y);

			m_textureCoordinates.push_back(texCoords);

			i++;
		}
	}

	SetFrame(0);
}

void AnimatedSprite::SetFrame(unsigned int frame)
{
	if (frame >= m_frameNames.size())
	{
		return;
	}

	m_currentFrame = frame;

	m_data.m_texCoords[0] = m_textureCoordinates[m_currentFrame].topLeft;
	m_data.m_texCoords[1] = m_textureCoordinates[m_currentFrame].topRight;
	m_data.m_texCoords[2] = m_textureCoordinates[m_currentFrame].bottomLeft;
	m_data.m_texCoords[3] = m_textureCoordinates[m_currentFrame].bottomRight;
}

void AnimatedSprite::Reset(bool restart)
{
	m_isAnimating = restart;
	if (restart)
	{
		Start(0);
	}
	else
	{
		m_isAnimating = false;
		SetFrame(0);
	}
}

void AnimatedSprite::Start(unsigned int frame)
{
	SetFrame(frame);
	m_isAnimating = true;
	m_lastAnimated = 0;
}

void AnimatedSprite::Update(float delta)
{
	if (m_isAnimating)
	{
		Uint32 time = SDL_GetTicks();
		if ((time - m_lastAnimated) > m_speed)
		{
			m_lastAnimated = time;
			if ((m_currentFrame + 1) >= m_frameNames.size())
			{
				if (m_loop)
				{
					SetFrame(0);
				}
				else
				{
					m_isAnimating = false;
				}
			}
			else
			{
				SetFrame(m_currentFrame + 1);
			}
		}
	}
}


text:
@interface SpectacleWindowPositionCalculator : NSObject

+ (SpectacleCalculationResult *)calculateWindowRect:(CGRect)windowRect
                               visibleFrameOfScreen:(CGRect)visibleFrameOfScreen
                                             action:(SpectacleWindowAction)action;

+ (SpectacleCalculationResult *)calculateResizedWindowRect:(CGRect)windowRect
                                      visibleFrameOfScreen:(CGRect)visibleFrameOfScreen
                                                sizeOffset:(CGFloat)sizeOffset
                                                    action:(SpectacleWindowAction)action;

@end


text:
import os
import argparse
import datetime
import time
import json
import re
import logging
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
from collections import defaultdict
from speech2text import log_kv, make_dir

"""
What it does:
Merges and formats the output generated by two other stats scripts,
and writes the results to a TSV file.
"""

IBM_LOG_STATS_FILEPATH = "processed.json"
GOOGLE_LOG_STATS_FILEPATH = "gprocessed.json"
IBM_WORD_COUNT_FILEPATH = "file_stats.json"
GOOGLE_WORD_COUNT_FILEPATH = "gfile_stats.json"

IBM_BASE = "ibm_stt"
GOOGLE_BASE = "google_stt"
TRANSCRIBED_STATS_TSV = "transcribed_stats.tsv"

API_META = {"ibm" : {"base" : "ibm_stt", "transcripts" : ["hypotheses.txt", "hypotheses.txt.dictated"]},
            "google": {"base": "google_stt", "transcripts": ["transcript.txt", "transcript.txt.dictated"]}}

def etl_transcripts(log_stats_path, word_counts_path, api, ext=".out"):
    """
    Merges the two datasets using a canonicalized key.
    If the two share a filed then the value in <word_counts_path> will overwrite the value from <log_stats_path>
    :param log_stats_path: gives processing time
    :param word_counts_path: gives word counts
    :param api: "ibm" or "google"
    :param ext: extension stripped from basename
    :return: dict
    """
    result = {}
    loaded = {}
    if os.path.isfile(log_stats_path):
        with open(log_stats_path) as fp:
            log_kv("Loading(%s log stats)" % api, log_stats_path)
            loaded = json.load(fp)
    if loaded and type(loaded) is dict:
        log_kv("Count  (%s log stats)" % api, len(loaded))
    else:
        logging.error("Expected log stats data.")

    for key, row in loaded.items():
        id = key
        if key.startswith(API_META[api]["base"]+"/"):
            id = key.replace(API_META[api]["base"]+"/", "")
        result[id] = row

    counts = {}
    if os.path.isfile(word_counts_path):
        with open(word_counts_path) as fp:
            log_kv("Loading(%s word counts)" % api, word_counts_path)
            counts = json.load(fp)
    if counts and type(counts) is dict:
        log_kv("Count  (%s word counts)" % api, len(counts))
    else:
        logging.error("Expected word counts data.")

    for key, row in counts.items():
        id = key
        if key.startswith(API_META[api]["base"]+"/"):
            id = key.replace(API_META[api]["base"]+"/", "")
        for suffix in API_META[api]["transcripts"]:
            if id.endswith("/"+suffix):
                id = re.sub(re.escape("/"+suffix) + r"$", "", id)
        if id.endswith(ext):
            id = re.sub(re.escape(ext) + r"$", "", id)
        if id in result:
            for x, y in row.items():
                result[id][x] = y
        else:
            result[id] = row

    return result

if __name__ == '__main__':

    start_time = time.time()

    parser = argparse.ArgumentParser(description='Analyze transcribe rate')
    parser.add_argument('--infolder','-i', action='store', default='.', help='folder containing previous ETL files')
    parser.add_argument('--outfolder','-o', action='store', default='./output', help='output directory')

    args = parser.parse_args()

    log_kv("Running", __file__)
    log_kv("From", os.path.dirname(os.path.realpath(__file__)))
    print

    inpath = os.path.realpath(args.infolder if args.infolder else os.getcwd())
    log_kv("inpath", inpath)
    outpath = os.path.realpath(args.outfolder if args.outfolder else u'./output')
    log_kv("outpath", outpath)
    make_dir(outpath)

    log_kv("")
    log_kv("IBM log stats", IBM_LOG_STATS_FILEPATH)
    log_kv("IBM transcript stats", IBM_WORD_COUNT_FILEPATH)
    log_kv("Google log stats", GOOGLE_LOG_STATS_FILEPATH)
    log_kv("Google transcript stats", GOOGLE_WORD_COUNT_FILEPATH)
    log_kv("")
    log_kv("IBM base", API_META["ibm"]["base"])
    log_kv("Google base", API_META["google"]["base"])
    log_kv("")
    log_kv("tsv filename", TRANSCRIBED_STATS_TSV)

    print
    log_kv("Loading IBM")
    ibm_data = etl_transcripts(os.path.join(inpath, IBM_LOG_STATS_FILEPATH),
                               os.path.join(inpath,IBM_WORD_COUNT_FILEPATH),
                              "ibm")
    log_kv("Count(IBM)", len(ibm_data))
    print
    log_kv("Loading Google")
    google_data = etl_transcripts(os.path.join(inpath, GOOGLE_LOG_STATS_FILEPATH),
                                  os.path.join(inpath, GOOGLE_WORD_COUNT_FILEPATH),
                              "google")
    log_kv("Count(Google)", len(google_data))

    print
    keys = set(ibm_data.keys()).union(set(google_data.keys()))
    log_kv("Number of keys in both", len(keys))

    tsv_fields = set(["etl_time"])
    tsv_data = defaultdict(dict)
    for key in keys:
        if key in ibm_data:
            for x,y in ibm_data[key].items():
                tsv_data[key]["ibm_" + x] = y
                tsv_fields.add("ibm_" + x)
        if key in google_data:
            for x, y in google_data[key].items():
                tsv_data[key]["google_" + x] = y
                tsv_fields.add("google_" + x)
        tsv_data[key]["etl_time"] = datetime.datetime.now().isoformat()

    tsv_keys = sorted(tsv_data.keys())
    tsv_fields = sorted(tsv_fields)
    print "Fields:\npath,", ",".join(tsv_fields)

    #   Writes line data
    tsv_path = os.path.join(args.outfolder,TRANSCRIBED_STATS_TSV)
    log_kv("Writing", tsv_path)
    with open(tsv_path, 'w') as fp:
        fp.write("path\t")
        for field in tsv_fields:
            fp.write("\t"+field if tsv_fields.index(field) else field)
        fp.write("\n")
        for key in tsv_keys:
            fp.write('"%s"\t' % key)
            for field in tsv_fields:

                value = tsv_data[key][field] if field in tsv_data[key] else None
                value = "" if not value else '"%s"' % value if type(value) is str else "%s" % value
                fp.write("\t"+value if tsv_fields.index(field) else value)
            fp.write("\n")

    log_kv("Done:              ", __file__)
    print("(%.1f min)" % ((time.time() - start_time) / 60.0))


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System.ServiceModel;
using System.ServiceModel.Channels;

namespace Microsoft.WindowsAzure.Commands.Utilities.Common
{
    public static class ConfigurationConstants
    {
        public const int MaxReceivedMessageSize = 100000000;

        public const int MaxStringContentLength = 67108864;

        public static Binding WebHttpBinding(int maxStringContentLength = 0)
        {
            var binding = new WebHttpBinding(WebHttpSecurityMode.Transport);
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
            binding.ReaderQuotas.MaxStringContentLength =
                maxStringContentLength > 0 ?
                maxStringContentLength :
                MaxStringContentLength;

            // Increasing MaxReceivedMessageSize to allow big deployments
            binding.MaxReceivedMessageSize = MaxReceivedMessageSize;

            return binding;
        }
    }
}


text:
package org.netling.ssh.connection.channel.forwarded;

import org.netling.ssh.common.SSHPacket;
import org.netling.ssh.connection.Connection;
import org.netling.ssh.connection.ConnectionException;
import org.netling.ssh.transport.TransportException;

/**
 * Handles forwarded {@code x11} channels. The actual request to forward X11 should be made from the specific {@link
 * org.netling.ssh.connection.channel.direct.Session Session}.
 */
public class X11Forwarder
        extends AbstractForwardedChannelOpener {

    /** An {@code x11} forwarded channel. */
    public static class X11Channel
            extends AbstractForwardedChannel {

        public static final String TYPE = "x11";

        public X11Channel(Connection conn, int recipient, int remoteWinSize, int remoteMaxPacketSize, String origIP,
                          int origPort) {
            super(conn, TYPE, recipient, remoteWinSize, remoteMaxPacketSize, origIP, origPort);
        }

    }

    private final ConnectListener listener;

    /**
     * @param conn     connection layer
     * @param listener listener which will be delegated {@link X11Channel}'s to next
     */
    public X11Forwarder(Connection conn, ConnectListener listener) {
        super(X11Channel.TYPE, conn);
        this.listener = listener;
    }

    /** Internal API */
    @Override
    public void handleOpen(SSHPacket buf)
            throws ConnectionException, TransportException {
        callListener(listener, new X11Channel(conn,
                                              buf.readInt(),
                                              buf.readInt(), buf.readInt(),
                                              buf.readString(), buf.readInt()));
    }

    /** Stop handling {@code x11} channel open requests. De-registers itself with connection layer. */
    public void stop() {
        conn.forget(this);
    }

}


text:
void set_file_part_name(char *str, size_t curentPart, const char *directory)
{
    size_t lenDestPath = strlen(directory);

    if (directory[lenDestPath - 1] != '/')
    {
        sprintf(str, "%s/Part-%d.jpg", directory, curentPart + 1);
    }
    else
    {
        sprintf(str, "%sPart-%d.jpg", directory, curentPart + 1);
    }
}

void set_names(char *str[], size_t size, const char *directory)
{
    size_t fileNameLenght = 15;
    size_t i;
    for (i = 0; i < size; i++)
    {
        size_t lenDestPath = strlen(directory);
        str[i] = calloc(lenDestPath + fileNameLenght, sizeof (char));
        if (!str[i])
        {
            error("Not enough memory!");
        }
        set_file_part_name(str[i], i, directory);
    }
}

void free_array(char *str[], size_t size)
{
    int i;
    for (i = 0; i < size; i++)
    {
        free(str[i]);
    }
}

void error(const char *msg)
{
    if (errno)
    {
        perror(msg);
    }
    else
    {
        fprintf(stderr, "ERROR: %s", msg);
    }

    exit(1);
}

void slice(const char *sourceFile, const char *destinationDirectory, size_t parts)
{
    FILE *source = fopen(sourceFile, "r");
    if (!sourceFile)
    {
        error("Can't open file");
    }

    fseek(source, 0, SEEK_END);
    long long sourceFileSize = ftell(source);
    fseek(source, 0, SEEK_SET);

    long long partSize = sourceFileSize / parts;

    char buffer[READ_BUFFER];
    size_t i;
    for (i = 0; i < parts; i++)
    {
        char partName[NAME_BUFFER];
        set_file_part_name(partName, i, destinationDirectory);

        FILE *currentDestFile = fopen(partName, "w");
        if (!currentDestFile)
        {
            error("Could not create a part");
        }

        size_t writtenBytes = 0;
        while (writtenBytes <= partSize && !feof(source))
        {
            size_t readBytes = fread(buffer, 1, READ_BUFFER, source);
            fwrite(buffer, 1, readBytes, currentDestFile);
            writtenBytes += readBytes;
        }

        fclose(currentDestFile);
    }
    fclose(source);
}

void assemble(char **partsName, const char *destinationDirectory)
{
    char buffer[READ_BUFFER];

    char resultFileName[NAME_BUFFER];
    size_t len = strlen(destinationDirectory);
    if (destinationDirectory[len - 1] != '/')
    {
        sprintf(resultFileName, "%s/Asebled.jpg", destinationDirectory);
    }
    else
    {
        sprintf(resultFileName, "%sAsebled.jpg", destinationDirectory);
    }

    FILE *result = fopen(resultFileName, "w");
    if (!result)
    {
        error("Can't create file");
    }

    int i;
    for (i = 0; i < parts_global; i++)
    {
        FILE *curentFile = fopen(partsName[i], "r");
        if (!curentFile)
        {
            error(partsName[i]);
        }

        while (!feof(curentFile))
        {
            size_t readBytes = fread(buffer, 1, READ_BUFFER, curentFile);
            fwrite(buffer, 1, readBytes, result);
        }
        fclose(curentFile);
    }
    fclose(result);
}


text:
package co.cask.cdap.examples.wikipedia;

import co.cask.cdap.api.Resources;
import co.cask.cdap.api.spark.AbstractSpark;
import co.cask.cdap.api.spark.ScalaSparkProgram;

/**
 * Spark program that executes in a workflow and analyzes wikipedia data
 */
public class SparkWikipediaClustering extends AbstractSpark {
  public static final String NAME = SparkWikipediaClustering.class.getSimpleName();

  private final WikipediaPipelineApp.WikipediaAppConfig appConfig;

  public SparkWikipediaClustering(WikipediaPipelineApp.WikipediaAppConfig appConfig) {
    this.appConfig = appConfig;
  }

  @Override
  protected void configure() {
    String description;
    Class<? extends ScalaSparkProgram> mainClass;
    if ("lda".equals(appConfig.clusteringAlgorithm)) {
      description = "A Spark program that analyzes wikipedia data using Latent Dirichlet Allocation (LDA).";
      mainClass = ScalaSparkLDA.class;
    } else if ("kmeans".equals(appConfig.clusteringAlgorithm)) {
      description = "A Spark program that analyzes wikipedia data using K-Means.";
      mainClass = ScalaSparkKMeans.class;
    } else {
      throw new IllegalArgumentException("Only 'lda' and 'kmeans' are supported as clustering algorithms. " +
                                           "Found " + appConfig.clusteringAlgorithm);
    }
    setName(NAME + "-" + appConfig.clusteringAlgorithm.toUpperCase());
    setDescription(description);
    setMainClass(mainClass);
    setDriverResources(new Resources(1024));
    setExecutorResources(new Resources(1024));
  }
}


text:
=========================
LLVM 10.0.0 Release Notes
=========================

.. contents::
    :local:

.. warning::
   These are in-progress notes for the upcoming LLVM 10 release.
   Release notes for previous releases can be found on
   `the Download Page <https://releases.llvm.org/download.html>`_.

Introduction
============

This document contains the release notes for the LLVM Compiler Infrastructure,
release 10.0.0.  Here we describe the status of LLVM, including major improvements
from the previous release, improvements in various subprojects of LLVM, and
some of the current users of the code.  All LLVM releases may be downloaded
from the `LLVM releases web site <https://llvm.org/releases/>`_.

For more information about LLVM, including information about the latest
release, please check out the `main LLVM web site <https://llvm.org/>`_.  If you
have questions or comments, the `LLVM Developer's Mailing List
<https://lists.llvm.org/mailman/listinfo/llvm-dev>`_ is a good place to send
them.

Note that if you are reading this file from a Subversion checkout or the main
LLVM web page, this document applies to the *next* release, not the current
one.  To see the release notes for a specific release, please see the `releases
page <https://llvm.org/releases/>`_.

Non-comprehensive list of changes in this release
=================================================
.. NOTE
   For small 1-3 sentence descriptions, just add an entry at the end of
   this list. If your description won't fit comfortably in one bullet
   point (e.g. maybe you would like to give an example of the
   functionality, or simply have a lot to talk about), see the `NOTE` below
   for adding a new subsection.

* The ISD::FP_ROUND_INREG opcode and related code was removed from SelectionDAG.
* Enabled MemorySSA as a loop dependency.

.. NOTE
   If you would like to document a larger change, then you can add a
   subsection about it right here. You can copy the following boilerplate
   and un-indent it (the indentation causes it to be inside this comment).

   Special New Feature
   -------------------

   Makes programs 10x faster by doing Special New Thing.

Changes to the LLVM IR
----------------------

* Unnamed function arguments now get printed with their automatically
  generated name (e.g. "i32 %0") in definitions. This may require front-ends
  to update their tests; if so there is a script utils/add_argument_names.py
  that correctly converted 80-90% of Clang tests. Some manual work will almost
  certainly still be needed.

Changes to building LLVM
------------------------

Changes to the ARM Backend
--------------------------

 During this release ...

Changes to the MIPS Target
--------------------------

 During this release ...

Changes to the PowerPC Target
-----------------------------

 During this release ...

Changes to the X86 Target
-------------------------

 During this release ...

* Less than 128 bit vector types, v2i32, v4i16, v2i16, v8i8, v4i8, and v2i8, are
  now stored in the lower bits of an xmm register and the upper bits are
  undefined. Previously the elements were spread apart with undefined bits in
  between them.
* v32i8 and v64i8 vectors with AVX512F enabled, but AVX512BW disabled will now
  be passed in ZMM registers for calls and returns. Previously they were passed
  in two YMM registers. Old behavior can be enabled by passing
  -x86-enable-old-knl-abi
* -mprefer-vector-width=256 is now the default behavior skylake-avx512 and later
  Intel CPUs. This tries to limit the use of 512-bit registers which can cause a
  decrease in CPU frequency on these CPUs. This can be re-enabled by passing
  -mprefer-vector-width=512 to clang or passing -mattr=-prefer-256-bit to llc.

Changes to the AMDGPU Target
-----------------------------

Changes to the AVR Target
-----------------------------

 During this release ...

* Deprecated the mpx feature flag for the Intel MPX instructions. There were no
  intrinsics for this feature. This change only this effects the results
  returned by getHostCPUFeatures on CPUs that implement the MPX instructions.

Changes to the WebAssembly Target
---------------------------------

 During this release ...

Changes to the OCaml bindings
-----------------------------

Changes to the C API
--------------------

Changes to the DAG infrastructure
---------------------------------

Changes to LLDB
===============

External Open Source Projects Using LLVM 10
===========================================

* A project...

Additional Information
======================

A wide variety of additional information is available on the `LLVM web page
<https://llvm.org/>`_, in particular in the `documentation
<https://llvm.org/docs/>`_ section.  The web page also contains versions of the
API documentation which is up-to-date with the Subversion version of the source
code.  You can access versions of these documents specific to this release by
going into the ``llvm/docs/`` directory in the LLVM tree.

If you have any questions or comments about LLVM, please feel free to contact
us via the `mailing lists <https://llvm.org/docs/#mailing-lists>`_.


text:
=encoding utf-8

=head1 Name

windows - nginx for Windows

=head1

Version of nginx for Windows uses the native Win32 API (not the Cygwin emulation
layer).
Only the C<select> connection processing method is currently used,
so high performance and scalability should not be expected.
Due to this and some other known issues version of nginx for Windows
is considered to be a I<beta> version.
At this time, it provides almost the same functionality as a UNIX version
of nginx except for
XSLT filter, image filter, GeoIP module, and embedded Perl language.

To install nginxE<sol>Windows, L<download|download>
the latest mainline version distribution (1.9.7),
since the mainline branch of nginx contains all known fixes.
Then unpack the distribution, go to the
nginx-1.9.7
directory, and run C<nginx>.
Here is an example for the drive C: root directory:

    cd c:\
    unzip nginx-<mainline_version/>.zip
    cd nginx-<mainline_version/>
    start nginx

Run the C<tasklist> command-line utility
to see nginx processes:

    C:\nginx-<mainline_version/>>tasklist /fi "imagename eq nginx.exe"

    Image Name           PID Session Name     Session#    Mem Usage
    =============== ======== ============== ========== ============
    nginx.exe            652 Console                 0      2 780 K
    nginx.exe           1332 Console                 0      3 112 K

One of the processes is the master process and another is the worker process.
If nginx does not start, look for the reason in
the error log file F<logs\error.log>.
If the log file has not been created, the reason for this should be reported
in the Windows Event Log.
If an error page is displayed instead of the expected page, also look
for the reason in the F<logs\error.log> file.

nginxE<sol>Windows uses the directory where it has been run as the prefix
for relative paths in the configuration.
In the example above, the prefix is
F<C:\nginx-1.9.7\>.
Paths in a configuration file must be specified in UNIX-style using
forward slashes:

    access_log   logs/site.log;
    root         C:/web/html;

nginxE<sol>Windows runs as a standard console application (not a service),
and it can be managed using the following commands:

=head1 Known issues

=over

=item *

Although several workers can be started, only one of them
actually does any work.

=item *

A worker can handle no more than 1024 simultaneous connections.

=item *

The UDP proxy functionality is not supported.

=back

=head1 Possible future enhancements

=over

=item *

Running as a service.

=item *

Using the IE<sol>O completion ports as a connection processing method.

=item *

Using multiple worker threads inside a single worker process.

=back


text:
trap "rm .f 2> /dev/null; exit" 0 1 3

source /opt/anaconda3/bin/activate base

export CUDA_ROOT=/usr/local/cuda
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CUDA_ROOT/lib64
export NUMBAPRO_NVVM=$CUDA_ROOT/nvvm/lib64/libnvvm.so
export NUMBAPRO_LIBDEVICE=$CUDA_ROOT/nvvm/libdevice

function err() {
    # Handle error
    echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')]: $@" >&2
    exit 1
}

function start_dask() {
	local SCHEDULER_IPADDR=$1
	local SCHEDULER_PORT=$2
	/opt/anaconda3/bin/dask-worker ${SCHEDULER_IPADDR}:${SCHEDULER_PORT}
}

function main() {
    start_dask $1 $2 || err "Unable to start CUDA worker"
}

if [ -z "$1" ] || [ -z "$2" ]; then
    echo "Improper arguments supplied..."
    echo "Exiting..."
    exit
fi

main $1 $2


text:
module OneviewCookbook
  module API2800
    module C7000
      # StoragePool API2800 C7000 provider
      class StoragePoolProvider < OneviewCookbook::API2600::C7000::StoragePoolProvider
      end
    end
  end
end


text:
not-a-web-framework
===================
A [go vendor](https://golang.org/s/go15vendor)version of the [not-a-web-framework](https://github.com/oleksandr/not-a-web-framework) with minor modifications

* `gorilla/mux` as a router instead of the `github.com/julienschmidt/httprouter`

Original description:

A baseline for creating web-services in Go (a bit on steroids, but still pretty small). It's not a framework, not even a library. Steal this code instead of making yet another framework out of it! Don't even `go get` this package. Instead - git clone and merge it with your code base or build your next service on top of it.

The inspiration comes from the blog post [Build Your Own Framework in Go](http://nicolasmerouze.com/build-web-framework-golang/).


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
BasicFormatParams (Apache OpenNLP Tools 1.5.3 API)
</TITLE>

<META NAME="keywords" CONTENT="opennlp.tools.cmdline.params.BasicFormatParams interface">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

opennlp.tools.cmdline.params

Interface BasicFormatParams

All Superinterfaces:
EncodingParameter

All Known Subinterfaces:
NameSampleDataStreamFactory.Parameters, ParseSampleStreamFactory.Parameters, WordTagSampleStreamFactory.Parameters

public interface BasicFormatParams
extends EncodingParameter

Common format parameters.

Method Summary

 File
getData()

Methods inherited from interface opennlp.tools.cmdline.params.EncodingParameter

getEncoding

Method Detail

getData

File getData()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2013 The Apache Software Foundation. All Rights Reserved.


text:
[![Build Status](https://travis-ci.org/voxpupuli/puppet-splunk.png?branch=master)](https://travis-ci.org/voxpupuli/puppet-splunk)
[![Code Coverage](https://coveralls.io/repos/github/voxpupuli/puppet-splunk/badge.svg?branch=master)](https://coveralls.io/github/voxpupuli/puppet-splunk)
[![Puppet Forge](https://img.shields.io/puppetforge/v/puppet/splunk.svg)](https://forge.puppetlabs.com/puppet/splunk)
[![Puppet Forge - downloads](https://img.shields.io/puppetforge/dt/puppet/splunk.svg)](https://forge.puppetlabs.com/puppet/splunk)
[![Puppet Forge - endorsement](https://img.shields.io/puppetforge/e/puppet/splunk.svg)](https://forge.puppetlabs.com/puppet/splunk)
[![Puppet Forge - scores](https://img.shields.io/puppetforge/f/puppet/splunk.svg)](https://forge.puppetlabs.com/puppet/splunk)

#### Table of Contents

1. [Overview](#overview)
1. [Module Description - What the module does and why it is useful](#module-description)
1. [Setup - The basics of getting started with splunk](#setup)
    * [What splunk affects](#what-splunk-affects)
    * [Setup requirements](#setup-requirements)
    * [Beginning with splunk](#beginning-with-splunk)
1. [Usage - Configuration options and additional functionality](#usage)
1. [Reference - An under-the-hood peek at what the module is doing and how](#reference)
1. [Limitations - OS compatibility, etc.](#limitations)
1. [Development - Guide for contributing to the module](#development)

## Overview

This module provides a method to deploy Splunk Server or Splunk Universal Forwarder
with common configurations and ensure the services maintain a running
state. It provides types/providers to interact with the various Splunk/Forwarder
configuration files.

## Module Description

This module does not configure firewall rules. Firewall rules will need to be
configured separately in order to allow for correct operation of Splunk and the
Splunk Universal Forwarder. Additionally, this module does not supply Splunk or
Splunk Universal Forwarder installation media. Installation media will need to
be aquired seperately, and the module configured to use it. Users can use yum
or apt to install these components if they're self-hosted.

## Setup

### What splunk affects

* Installs the Splunk/Forwarder package and manages their config files. It does
  not purge them by default.
* The module will set up both Splunk and Splunkforwarder to run as the 'root'
  user on POSIX platforms.

### Setup Requirements

To begin using this module, use the Puppet Module Tool (PMT) from the command
line to install this module:

`puppet module install puppet-splunk`

This will place the module into your primary module path if you do not utilize
the --target-dir directive.

You can also use r10k or code-manager to deploy the module so ensure that you
have the correct entry in your Puppetfile.

Once the module is in place, there is just a little setup needed.

First, you will need to place your downloaded splunk installers into the files
directory, `<module_path>/splunk/files/`. If you're using r10k or code-manager
you'll need to override the `splunk::params::src_root` parameter to point at a
modulepath outside of the Splunk module because each deploy will overwrite the
files.

The files must be placed according to directory structure example given below.

The expected directory structure is:

     $root_url/
     └── products/
         ├── universalforwarder/
         │   └── releases/
         |       └── $version/
         |           └── $platform/
         |               └── splunkforwarder-${version}-${build}-${additl}
         └── splunk/
             └── releases/
                 └── $version/
                     └── $platform/
                         └── splunk-${version}-${build}-${additl}

A semi-populated example files directory might then contain:

    $root_url/
    └── products/
        ├── universalforwarder/
        │   └── releases/
        |       └── 7.0.0/
        |           ├── linux/
        |           |   ├── splunkforwarder-7.0.0-c8a78efdd40f-linux-2.6-amd64.deb
        |           |   ├── splunkforwarder-7.0.0-c8a78efdd40f-linux-2.6-intel.deb
        |           |   └── splunkforwarder-7.0.0-c8a78efdd40f-linux-2.6-x86_64.rpm
        |           ├── solaris/
        |           └── windows/
        |               └── splunkforwarder-7.0.0-c8a78efdd40f-x64-release.msi
        └── splunk/
            └── releases/
                └── 7.0.0/
                    └── linux/
                        ├── splunk-7.0.0-c8a78efdd40f-linux-2.6-amd64.deb
                        ├── splunk-7.0.0-c8a78efdd40f-linux-2.6-intel.deb
                        └── splunk-7.0.0-c8a78efdd40f-linux-2.6-x86_64.rpm

Second, you will need to supply the `splunk::params` class with three critical
pieces of information.

* The version of Splunk you are using
* The build of Splunk you are using
* The root URL to use to retrieve the packages

In the example given above, the version is 7.0.0, the build is c8a78efdd40f,
and the root URL is puppet:///modules/splunk. See the splunk::params class
documentation for more information.

### Beginning with splunk

Once the Splunk packages are hosted in the users repository or hosted by the
Puppet Server in the modulepath the module is ready to deploy.

## Usage

If a user is installing Splunk with packages provided from their modulepath,
this is the most basic way of installing Splunk Server with default settings:

```puppet
include ::splunk
```

This is the most basic way of installing the Splunk Universal Forwarder with
default settings:

```puppet
class { '::splunk::params':
    server => $my_splunk_server,
}

include ::splunk::forwarder
```

Once both Splunk and Splunk Universal Forwarder have been deployed on their
respective nodes, the Forwarder is ready to start sending logs.

In order to start sending some log data, users can take advantage of the
`Splunkforwarder_input` type. Here is a basic example of adding an input to
start sending Puppet Server logs:

```puppet
@splunkforwarder_input { 'puppetserver-sourcetype':
  section => 'monitor:///var/log/puppetlabs/puppetserver/puppetserver.log',
  setting => 'sourcetype',
  value   => 'puppetserver',
  tag     => 'splunk_forwarder'
}
```

This virtual resource will get collected by the `::splunk::forwarder` class if
it is tagged with `splunk_forwarder` and will add the appropriate setting to
the inputs.conf file and refresh the service.

## Reference

### Types

* `splunk_config`: This is a meta resource used to configur defaults for all the
  splunkforwarder and splunk types. This type should not be declared directly as
  it is declared in `splunk::params` and used internally by the types and providers.

* `splunk_authentication`: Used to manage ini settings in [authentication.conf][authentication.conf-docs]
* `splunk_authorize`: Used to manage ini settings in [authorize.conf][authorize.conf-docs]
* `splunk_distsearch`: Used to manage ini settings in [distsearch.conf][distsearch.conf-docs]
* `splunk_indexes`: Used to manage ini settings in [indexes.conf][indexes.conf-docs]
* `splunk_input`: Used to manage ini settings in [inputs.conf][inputs.conf-docs]
* `splunk_limits`: Used to mange ini settings in [limits.conf][limits.conf-docs]
* `splunk_metadata`: Used to manage ini settings in [default.meta][default.meta-docs]
* `splunk_output`: Used to manage ini settings in [outputs.conf][outputs.conf-docs]
* `splunk_props`: Used to manage ini settings in [props.conf][props.conf-docs]
* `splunk_server`: Used to mangage ini settings in [server.conf][server.conf-docs]
* `splunk_transforms`: Used to manage ini settings in [transforms.conf][transforms.conf-docs]
* `splunk_web`: Used to manage ini settings in [web.conf][web.conf-docs]

* `splunkforwarder_input`: Used to manage ini settings in [inputs.conf][inputs.conf-docs]
* `splunkforwarder_output`:Used to manage ini settings in [outputs.conf][outputs.conf-docs]
* `splunkforwarder_props`: Used to manage ini settings in [props.conf][props.conf-docs]
* `splunkforwarder_transforms`: Used to manage ini settings in [transforms.conf][transforms.conf-docs]
* `splunkforwarder_web`: Used to manage ini settings in [web.conf][web.conf-docs]
* `splunkforwarder_limits`: Used to manage ini settings in [limits.conf][limits.conf-docs]
* `splunkforwarder_server`: Used to manage ini settings in [server.conf][server.conf-docs]

All of the above types use `puppetlabs/ini_file` as a parent and are declared in
an identical way, and accept the following parameters:

* `section`:  The name of the section in the configuration file
* `setting`:  The setting to be managed
* `value`: The value of the setting

Both section and setting are namevars for the types.  Specifying a single string
as the title without a forward slash implies that the title is the section to be
managed (if the section attribute is not defined).  You can also specify the
resource title as `section/setting` and ommit both `section` and `setting` params
for a more shortform way of declaring the resource.   Eg:

```puppet
splunkforwarder_output { 'useless title':
  section => 'default',
  setting => 'defaultGroup',
  value   => 'splunk_9777',
}

splunkforwarder_output { 'default':
  setting => 'defaultGroup',
  value   => 'splunk_9777',
}

splunkforwarder_output { 'default/defaultGroup':
  value   => 'splunk_9777',
}
```

The above resource declarations will all configure the following entry in `outputs.conf`

```
[default]
defaultGroup=splunk_9997
```

Note: if the section contains forward slashes you should not use it as the resource
title and should explicitly declare it with the `section` attribute.

## Parameters

### Class: ::splunk::params

#### `version`

*Optional* Specifies the version of Splunk Enterprise that the module should install.

#### `build`

*Optional* Specifies the build of Splunk Enterprise that the module should use.

#### `src_root`

*Optional* The root path that the staging module will use to find packages for
splunk and splunk::forwarder.

#### `splunkd_port`

*Optional* The splunkd port. Used as a default for both splunk and splunk::forwarder.

#### `logging_port`

*Optional* The port on which to send and listen for logs. Used as a default for
both splunk and splunk::forwarder.

#### `server`

*Optional* The fqdn or IP address of the Splunk server. Used for setting up the
default TCP output and input.

### Class: ::splunk Parameters

#### `package_source`

The source URL for the splunk installation media (typically an RPM, MSI,
etc). If a $src_root parameter is set in splunk::params, this will be
automatically supplied. Otherwise it is required. The URL can be of any
protocol supported by the nanliu/staging module. On Windows, this can be
a UNC path to the MSI.

#### `package_name`

The name of the package(s) Puppet will use to install Splunk.

#### `package_ensure`

Ensure parameter which will get passed to the Splunk package resource.
Default to the value in splunk::params

#### `logging_port`

The port to receive TCP logs on. Default to the port specified in
splunk::params.

#### `splunk_user`

The user to run Splunk as. Default to the value set in splunk::params.

#### `splunkd_port`

The management port for Splunk. Default to the value set in splunk::params.

#### `web_port`

The port on which to service the Splunk Web interface. Default to 8000.

#### `purge_inputs`

*Optional* If set to true, inputs.conf will be purged of configuration that is
no longer managed by the splunk_input type. Default to false.

#### `purge_outputs`

*Optional* If set to true, outputs.conf will be purged of configuration that is
no longer managed by the splunk_output type. Default to false.

#### `purge_authentication`

*Optional* If set to true, authentication.conf will be purged of configuration
that is no longer managed by the splunk_authentication type. Default to false.

#### `purge_authorize`

*Optional* If set to true, authorize.conf will be purged of configuration that
is no longer managed by the splunk_authorize type. Default to false.

#### `purge_distsearch`

*Optional* If set to true, distsearch.conf will be purged of configuration that
is no longer managed by the splunk_distsearch type. Default to false.

#### `purge_indexes`

*Optional* If set to true, indexes.conf will be purged of configuration that is
no longer managed by the splunk_indexes type. Default to false.

#### `purge_limits`

*Optional* If set to true, limits.conf will be purged of configuration that is
no longer managed by the splunk_limits type. Default to false.

#### `purge_props`

*Optional* If set to true, props.conf will be purged of configuration that is
no longer managed by the splunk_props type. Default to false.

#### `purge_server`

*Optional* If set to true, server.conf will be purged of configuration that is
no longer managed by the splunk_server type. Default to false.

#### `purge_transforms`

*Optional* If set to true, transforms.conf will be purged of configuration that
is no longer managed by the splunk_transforms type. Default to false.

#### `purge_web`

*Optional* If set to true, web.conf will be purged of configuration that is no
longer managed by the splunk_web type. Default to false.

### Class ::splunk::forwarder Parameters

#### `server`

*Optional* The fqdn or IP address of the Splunk server. Default to the value in ::splunk::params.

#### `package_source`

The source URL for the splunk installation media (typically an RPM, MSI,
etc). If a $src_root parameter is set in splunk::params, this will be
automatically supplied. Otherwise it is required. The URL can be of any
protocol supported by the nanliu/staging module. On Windows, this can be
a UNC path to the MSI.

#### `package_name`

The name of the package(s) Puppet will use to install Splunk Universal Forwarder.

#### `package_ensure`

Ensure parameter which will get passed to the Splunk package resource.
Default to the value in ::splunk::params

#### `logging_port`

*Optional* The port on which to send and listen for logs. Default to the value
in ::splunk::params.

#### `splunkd_port`

The management port for Splunk. Default to the value set in splunk::params.

#### `install_options`

This variable is passed to the package resources' *install_options* parameter.
Default to the value in ::splunk::params.

#### `splunk_user`

The user to run Splunk as. Default to the value set in splunk::params.

#### `splunkd_listen`

The address on which splunkd should listen. Defaults to 127.0.0.1.

#### `purge_inputs`

*Optional* If set to true, inputs.conf will be purged of configuration that is
no longer managed by the splunkforwarder_input type. Default to false.

#### `purge_outputs`

*Optional* If set to true, outputs.conf will be purged of configuration that is
no longer managed by the splunk_output type. Default to false.

#### `purge_props`

*Optional* If set to true, props.conf will be purged of configuration that is
no longer managed by the splunk_props type. Default to false.

#### `purge_transforms`

*Optional* If set to true, transforms.conf will be purged of configuration that is
no longer managed by the splunk_transforms type. Default to false.

#### `purge_web`

*Optional* If set to true, web.conf will be purged of configuration that is
no longer managed by the splunk_web type. Default to false.

#### `pkg_provider`

*Optional* This will override the default package provider for the package
resource. Default to undef.

#### `forwarder_confdir`

The root directory where Splunk Universal Forwarder is installed. Default to
the value in ::splunk::params.

#### `forwarder_input`

Used to override the default forwarder_input type defined in ::splunk::params.

#### `forwarder_output`

Used to override the default forwarder_output type defined in ::splunk::params.

#### `create_password`

Not yet implemented.

## Limitations

- Currently tested manually on Centos 7, but we will eventually add automated
  testing and are targeting compatibility with other platforms.
- Tested with Puppet 4.x

## Development

TBD

## Release Notes/Contributors/Etc

TBD

[authentication.conf-docs]: http://docs.splunk.com/Documentation/Splunk/latest/Admin/Authenticationconf
[authorize.conf-docs]: http://docs.splunk.com/Documentation/Splunk/latest/Admin/Authenticationconf
[default.meta-docs]: http://docs.splunk.com/Documentation/Splunk/latest/Admin/Defaultmetaconf
[distsearch.conf-docs]: http://docs.splunk.com/Documentation/Splunk/latest/Admin/Distsearchconf
[indexes.conf-docs]: http://docs.splunk.com/Documentation/Splunk/latest/Admin/Indexesconf
[inputs.conf-docs]: http://docs.splunk.com/Documentation/Splunk/latest/Admin/Inputsconf
[limits.conf-docs]: http://docs.splunk.com/Documentation/Splunk/latest/Admin/Limitsconf
[outputs.conf-docs]: http://docs.splunk.com/Documentation/Splunk/latest/Admin/Outputsconf
[props.conf-docs]: http://docs.splunk.com/Documentation/Splunk/latest/Admin/Propsconf
[server.conf-docs]: http://docs.splunk.com/Documentation/Splunk/latest/Admin/Serverconf
[transforms.conf-docs]: http://docs.splunk.com/Documentation/Splunk/latest/Admin/Transformsconf
[web.conf-docs]: http://docs.splunk.com/Documentation/Splunk/latest/Admin/Webconf


text:
<?php

namespace karlsson;

class request {

	private static
		$resolved = false,
		$page = null,
		$path = '',
		$parameters = array(),
		$types = array(
			'int',
			'string',
			'float',
			'bool'
			),
		$client = null,
		$browsCap = null;

	/**
	 * Get the browsCap object
	 * @return \BrowsCap
	 */
	static function browsCap() {
		if (self::$browsCap == null) {
			try {
				self::$browsCap = new \Browscap(KARLSSON_ROOT . '/content/cache/');
				self::$browsCap->doAutoUpdate = true;

				self::$browsCap->updateMethod = \Browscap::UPDATE_CURL;

				if (!KARLSSON_URL_CURL and KARLSSON_URL_FSOCKOPEN) {
					self::$browsCap->updateMethod = \Browscap::UPDATE_FSOCKOPEN;
				} elseif (!KARLSSON_URL_CURL and !KARLSSON_URL_FSOCKOPEN and KARLSSON_URL_FOPEN) {
					self::$browsCap->updateMethod = \Browscap::UPDATE_FOPEN;
				} elseif (!KARLSSON_URL_CURL and !KARLSSON_URL_FSOCKOPEN and !KARLSSON_URL_FOPEN) {
					self::$browsCap->doAutoUpdate = false;
					self::$browsCap->localFile = KARLSSON_ROOT . '/lib/others/browscap.ini';
					self::$browsCap->updateMethod = \Browscap::UPDATE_LOCAL;
				}
			} catch (\Browscap_Exception $e) {

			}
		}

		return self::$browsCap;
	}

	/**
	 * Get the client of the current request.
	 */
	static function client() {
		if (self::$client === null) {
			self::$client = self::browsCap()->getBrowser();
			self::$client->is_bot = false;
			if (self::$client->Platform == 'unknown' || self::$client->Browser == '')
				self::$client->is_bot = true;
		}

		return self::$client;
	}

	/**
	 * Initialize and set wanted request parameters to wanted types.
	 * @param array $params
	 */
	static function make_useable(array $params) {
		if (isset($params['POST'])) {
			foreach ($params['POST'] as $param => $type) {
				if (in_array($type, self::$types))
					settype($_POST[$param], $type);
				else
					settype($_POST[$param], 'string');
			}
		}

		if (isset($params['GET'])) {
			foreach ($params['GET'] as $param => $type) {
				if (in_array($type, self::$types))
					settype($_GET[$param], $type);
				else
					settype($_GET[$param], 'string');
			}
		}

		if (isset($params['SESSION'])) {
			foreach ($params['SESSION'] as $param => $type) {
				if (in_array($type, self::$types))
					settype($_SESSION[$param], $type);
				else
					settype($_SESSION[$param], 'string');
			}
		}

		if (isset($params['SERVER'])) {
			foreach ($params['SERVER'] as $param => $type) {
				if (in_array($type, self::$types))
					settype($_SERVER[$param], $type);
				else
					settype($_SERVER[$param], 'string');
			}
		}
	}

	/**
	 * Resolves a request.
	 */
	private static function resolve() {
		if (isset($_GET['x'])) {
			$x = explode('/', trim($_GET['x'], '/'));
		} else {
			$x = $_SERVER['REQUEST_URI'];

			/**
			 * Remove ~ from requests... Some stupid servers put it there.
			 */
			if (mb_strpos($x, '~') !== false and mb_strpos(KARLSSON_PATH, '~') === false)
				$x = str_replace('~', '', $x);

			/**
			 * Same as above for doubled slashes.
			 */
			if (mb_strpos($x, '//') !== false and mb_strpos(KARLSSON_PATH, '//') === false)
				$x = str_replace('//', '/', $x);

			/**
			 * Remove considered web path to karlsson from request.
			 */
			$x = preg_replace('~^' . KARLSSON_PATH . '~', '', $x, 1);

			/**
			 * Remove #... and ?... from request.
			 */
			$x = explode('#', $x);
			$x = explode('?', $x[0]);
			$x = explode('/', $x[0]);
		}

		if (!isset($x[0]) or empty($x[0]) or $x[0] == 'index.php')
			$x[0] = \karlsson\pages\get_name(KARLSSON_STANDARD_PAGE);

		$parsed_request = self::parse_request($x);

		if (is_object($parsed_request['page'])) {
			//header('HTTP/1.1 403 Forbidden');
			header('HTTP/1.1 200 Ok');
			self::$page = $parsed_request['page'];
			self::$path = $parsed_request['path'];
			self::$parameters = $parsed_request['parameters'];
		} else {
			header('HTTP/1.1 404 Not Found');
			self::$page = \karlsson\pages\get_data_by_name('404');
			self::$path = KARLSSON_PATH . '404';
			self::$parameters = array();
		}

		self::$resolved = true;
	}

	/**
	 * Parse a request that is given as array generated from a string split at /.
	 * @param array $x
	 * @return array
	 */
	static function parse_request($x) {
		$last_page = null;
		$page = null;

		if ($x[0] == 'user') {
			$page = new \karlsson\pages\page;
			$page->name = 'user';

			return array(
				'page' => $page,
				'path' => 'user',
				'parameters' => array_slice($x, 1),
				'index' => 0
			);
		} elseif ($x[0] == 'admin') {
			$page = new \karlsson\pages\page;
			$page->name = 'admin';

			return array(
				'page' => $page,
				'path' => 'admin',
				'parameters' => array_slice($x, 1),
				'index' => 0
			);
		}

		foreach ($x as $i => $name) {
			$page = \karlsson\pages\get_data_by_name($name);

			if ($page === false) {
				$page = $last_page;
				$i--;
				break;
			} elseif ($last_page === null and $page->superiorPage != 0) {
				$page = null;
				$i = 0;
				break;
			} elseif ($last_page !== null and $last_page->id !== $page->superiorPage) {
				$page = null;
				$i = 0;
				break;
			}
			$last_page = $page;
		}

		$x = array_map('urldecode', $x);

		$return = array(
			'page' => $page,
			'path' => implode('/', array_slice($x, 0, $i + 1)),
			'parameters' => array(),
			'index' => $i
		);
		if (count($x) > 1)
			$return['parameters'] = array_slice($x, $i + 1);

		return $return;
	}

	/**
	 * Get the requested page.
	 * @return type
	 */
	public static function page() {
		if (!self::$resolved)
			self::resolve();

		return self::$page;
	}

	/**
	 * Get the path to the requested page.
	 * @return type
	 */
	public static function path() {
		if (!self::$resolved)
			self::resolve();

		return self::$path;
	}

	/**
	 * Get the parameters for the requested page.
	 * @param int $i
	 * @return boolean
	 */
	public static function parameter($i) {
		if (!is_numeric($i))
			throw new \Exception('$i has to be an integer!');

		if (!self::$resolved)
			self::resolve();

		if (isset(self::$parameters[$i]))
			return self::$parameters[$i];

		return false;
	}

	/**
	 * Return the parameters of the current request.
	 * @return array
	 */
	public static function parameters() {
		return self::$parameters;
	}

}


text:
package com.blogspot.colibriapps.inthemusic.vkLoaders;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.blogspot.colibriapps.inthemusic.user.CacheData;

import com.vk.sdk.api.VKApi;
import com.vk.sdk.api.VKApiConst;
import com.vk.sdk.api.VKParameters;
import com.vk.sdk.api.VKRequest;
import com.vk.sdk.api.VKResponse;
import com.vk.sdk.api.model.VKApiAudio;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Dmitriy Gaiduk on 22.06.15.
 */
public class SearchLoader extends BaseVkAudioLoader {
    private static final String LOG_TAG = "SearchLoader";

    public static final String ARGS_SEARCH_STRING = "args_search_string";

    private String searchString;

    public SearchLoader(Context context, Bundle args) {
        super(context, args);
        Log.i(LOG_TAG, " create");

        searchString = args.getString(ARGS_SEARCH_STRING);

        if (TextUtils.isEmpty(searchString)){
            searchString = "";
        }

        if(!searchString.equals(CacheData.getInstance().getSearchQuery())){
            mForceLoad = true;
        }
    }

    @Override
    protected VKRequest makeRequest() {
        // из документации: максимальное значение 300.
        // С параметром offset: доступны только первые 1000 результатов
        final int count = 300;
        VKParameters vkParameters = new VKParameters();
        vkParameters.put(VKApiConst.Q, searchString);
        vkParameters.put(VKApiConst.COUNT, count);

        return VKApi.audio().search(vkParameters);
    }

    @Override
    protected void onRequestComplete(ArrayList<VKApiAudio> itemsList){
        super.onRequestComplete(itemsList);
        // дополнительно запоминаем строку поиска для текущего плейлиста в поиске
        CacheData.getInstance().setSearchQuery(searchString);
    }

    @Override
    protected ArrayList<VKApiAudio> processResponse(VKResponse response) {

        JSONObject responseObj = null;

        try {
            responseObj = response.json.getJSONObject("response");
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (responseObj == null) {

            return null;
        }

        JSONArray items = null;

        try {
            items = responseObj.getJSONArray("items");
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (items == null) {
            return null;
        }

        JSONObject json;
        VKApiAudio vkApiAudio;
        int arrayCount = items.length();

        ArrayList<VKApiAudio> vkApiAudioArrayList = new ArrayList<>();

        for (int i = 0; i < arrayCount; i++) {
            json = null;
            try {
                json = items.getJSONObject(i);
            } catch (Exception e) {
                e.printStackTrace();
            }

            vkApiAudio = new VKApiAudio();
            vkApiAudio.parse(json);

            vkApiAudioArrayList.add(vkApiAudio);
        }

        return  vkApiAudioArrayList;
    }
}


text:
<?php
namespace ExampleCommonTest\Entity;

include_once('../src/ExampleCommon/Entity/Person.php');

use ExampleCommon\Entity\Person;
use PHPUnit_Framework_TestCase;

class PersonTest extends PHPUnit_Framework_TestCase
{
    public function testInitialState()
    {
        $person = new Person();
        $person->firstName = "alec";
        $person->lastName = "test";

        $this->assertEquals($person->firstName, "alec");
        $this->assertEquals($person->lastName, "test");
    }
}


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot. '/course/format/lib.php');

/**
 * Main class for the singleactivity course format
 *
 * @package    format_singleactivity
 * @copyright  2012 Marina Glancy
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class format_singleactivity extends format_base {
    /** @var cm_info the current activity. Use get_activity() to retrieve it. */
    private $activity = false;

    /**
     * The URL to use for the specified course
     *
     * @param int|stdClass $section Section object from database or just field course_sections.section
     *     if null the course view page is returned
     * @param array $options options for view URL. At the moment core uses:
     *     'navigation' (bool) if true and section has no separate page, the function returns null
     *     'sr' (int) used by multipage formats to specify to which section to return
     * @return null|moodle_url
     */
    public function get_view_url($section, $options = array()) {
        $sectionnum = $section;
        if (is_object($sectionnum)) {
            $sectionnum = $section->section;
        }
        if ($sectionnum == 1) {
            return new moodle_url('/course/view.php', array('id' => $this->courseid, 'section' => 1));
        }
        if (!empty($options['navigation']) && $section !== null) {
            return null;
        }
        return new moodle_url('/course/view.php', array('id' => $this->courseid));
    }

    /**
     * Loads all of the course sections into the navigation
     *
     * @param global_navigation $navigation
     * @param navigation_node $node The course node within the navigation
     */
    public function extend_course_navigation($navigation, navigation_node $node) {
        // Display orphaned activities for the users who can see them.
        $context = context_course::instance($this->courseid);
        if (has_capability('moodle/course:viewhiddensections', $context)) {
            $modinfo = get_fast_modinfo($this->courseid);
            if (!empty($modinfo->sections[1])) {
                $section1 = $modinfo->get_section_info(1);
                // Show orphaned activities.
                $orphanednode = $node->add(get_string('orphaned', 'format_singleactivity'),
                        $this->get_view_url(1), navigation_node::TYPE_SECTION, null, $section1->id);
                $orphanednode->nodetype = navigation_node::NODETYPE_BRANCH;
                $orphanednode->add_class('orphaned');
                foreach ($modinfo->sections[1] as $cmid) {
                    if (has_capability('moodle/course:viewhiddenactivities', context_module::instance($cmid))) {
                        $this->navigation_add_activity($orphanednode, $modinfo->cms[$cmid]);
                    }
                }
            }
        }
    }

    /**
     * Adds a course module to the navigation node
     *
     * This is basically copied from function global_navigation::load_section_activities()
     * because it is not accessible from outside.
     *
     * @param navigation_node $node
     * @param cm_info $cm
     * @return null|navigation_node
     */
    protected function navigation_add_activity(navigation_node $node, $cm) {
        if (!$cm->uservisible) {
            return null;
        }
        $action = $cm->get_url();
        if (!$action) {
            // Do not add to navigation activity without url (i.e. labels).
            return null;
        }
        $activityname = format_string($cm->name, true, array('context' => context_module::instance($cm->id)));
        if ($cm->icon) {
            $icon = new pix_icon($cm->icon, $cm->modfullname, $cm->iconcomponent);
        } else {
            $icon = new pix_icon('icon', $cm->modfullname, $cm->modname);
        }
        $activitynode = $node->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
        if (global_navigation::module_extends_navigation($cm->modname)) {
            $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
        } else {
            $activitynode->nodetype = navigation_node::NODETYPE_LEAF;
        }
        return $activitynode;
    }

    /**
     * Returns the list of blocks to be automatically added for the newly created course
     *
     * @return array of default blocks, must contain two keys BLOCK_POS_LEFT and BLOCK_POS_RIGHT
     *     each of values is an array of block names (for left and right side columns)
     */
    public function get_default_blocks() {
        // No blocks for this format because course view page is not displayed anyway.
        return array(
            BLOCK_POS_LEFT => array(),
            BLOCK_POS_RIGHT => array()
        );
    }

    /**
     * Definitions of the additional options that this course format uses for course
     *
     * Singleactivity course format uses one option 'activitytype'
     *
     * @param bool $foreditform
     * @return array of options
     */
    public function course_format_options($foreditform = false) {
        static $courseformatoptions = false;
        if ($courseformatoptions === false) {
            $config = get_config('format_singleactivity');
            $courseformatoptions = array(
                'activitytype' => array(
                    'default' => $config->activitytype,
                    'type' => PARAM_TEXT,
                ),
            );
        }
        if ($foreditform && !isset($courseformatoptions['activitytype']['label'])) {
            $availabletypes = $this->get_supported_activities();
            $courseformatoptionsedit = array(
                'activitytype' => array(
                    'label' => new lang_string('activitytype', 'format_singleactivity'),
                    'help' => 'activitytype',
                    'help_component' => 'format_singleactivity',
                    'element_type' => 'select',
                    'element_attributes' => array($availabletypes),
                ),
            );
            $courseformatoptions = array_merge_recursive($courseformatoptions, $courseformatoptionsedit);
        }
        return $courseformatoptions;
    }

    /**
     * Adds format options elements to the course/section edit form
     *
     * This function is called from {@link course_edit_form::definition_after_data()}
     *
     * Format singleactivity adds a warning when format of the course is about to be changed.
     *
     * @param MoodleQuickForm $mform form the elements are added to
     * @param bool $forsection 'true' if this is a section edit form, 'false' if this is course edit form
     * @return array array of references to the added form elements
     */
    public function create_edit_form_elements(&$mform, $forsection = false) {
        global $PAGE;
        $elements = parent::create_edit_form_elements($mform, $forsection);
        if (!$forsection && ($course = $PAGE->course) && !empty($course->format) &&
                $course->format !== 'site' && $course->format !== 'singleactivity') {
            // This is the existing course in other format, display a warning.
            $element = $mform->addElement('static', '', '',
                    html_writer::tag('span', get_string('warningchangeformat', 'format_singleactivity'),
                            array('class' => 'error')));
            array_unshift($elements, $element);
        }
        return $elements;
    }

    /**
     * Make sure that current active activity is in section 0
     *
     * All other activities are moved to section 1 that will be displayed as 'Orphaned'.
     * It may be needed after the course format was changed or activitytype in
     * course settings has been changed.
     *
     * @return null|cm_info current activity
     */
    public function reorder_activities() {
        course_create_sections_if_missing($this->courseid, array(0, 1));
        foreach ($this->get_sections() as $sectionnum => $section) {
            if (($sectionnum && $section->visible) ||
                    (!$sectionnum && !$section->visible)) {
                // Make sure that 0 section is visible and all others are hidden.
                set_section_visible($this->courseid, $sectionnum, $sectionnum == 0);
            }
        }
        $modinfo = get_fast_modinfo($this->courseid);

        // Find the current activity (first activity with the specified type in all course activities).
        $activitytype = $this->get_activitytype();
        $activity = null;
        if (!empty($activitytype)) {
            foreach ($modinfo->sections as $sectionnum => $cmlist) {
                foreach ($cmlist as $cmid) {
                    if ($modinfo->cms[$cmid]->modname === $activitytype) {
                        $activity = $modinfo->cms[$cmid];
                        break 2;
                    }
                }
            }
        }

        // Make sure the current activity is in the 0-section.
        if ($activity && $activity->sectionnum != 0) {
            moveto_module($activity, $modinfo->get_section_info(0));
            // Cache was reset so get modinfo again.
            $modinfo = get_fast_modinfo($this->courseid);
        }

        // Move all other activities into section 1 (the order must be kept).
        $hasvisibleactivities = false;
        $firstorphanedcm = null;
        foreach ($modinfo->sections as $sectionnum => $cmlist) {
            if ($sectionnum && !empty($cmlist) && $firstorphanedcm === null) {
                $firstorphanedcm = reset($cmlist);
            }
            foreach ($cmlist as $cmid) {
                if ($sectionnum > 1) {
                    moveto_module($modinfo->get_cm($cmid), $modinfo->get_section_info(1));
                } else if (!$hasvisibleactivities && $sectionnum == 1 && $modinfo->get_cm($cmid)->visible) {
                    $hasvisibleactivities = true;
                }
            }
        }
        if (!empty($modinfo->sections[0])) {
            foreach ($modinfo->sections[0] as $cmid) {
                if (!$activity || $cmid != $activity->id) {
                    moveto_module($modinfo->get_cm($cmid), $modinfo->get_section_info(1), $firstorphanedcm);
                }
            }
        }
        if ($hasvisibleactivities) {
            set_section_visible($this->courseid, 1, false);
        }
        return $activity;
    }

    /**
     * Returns the name of activity type used for this course
     *
     * @return string|null
     */
    protected function get_activitytype() {
        $options = $this->get_format_options();
        $availabletypes = $this->get_supported_activities();
        if (!empty($options['activitytype']) &&
                array_key_exists($options['activitytype'], $availabletypes)) {
            return $options['activitytype'];
        } else {
            return null;
        }
    }

    /**
     * Returns the current activity if exists
     *
     * @return null|cm_info
     */
    protected function get_activity() {
        if ($this->activity === false) {
            $this->activity = $this->reorder_activities();
        }
        return $this->activity;
    }

    /**
     * Get the activities supported by the format.
     *
     * Here we ignore the modules that do not have a page of their own, like the label.
     *
     * @return array array($module => $name of the module).
     */
    public static function get_supported_activities() {
        $availabletypes = get_module_types_names();
        foreach ($availabletypes as $module => $name) {
            if (plugin_supports('mod', $module, FEATURE_NO_VIEW_LINK, false)) {
                unset($availabletypes[$module]);
            }
        }
        return $availabletypes;
    }

    /**
     * Checks if the current user can add the activity of the specified type to this course.
     *
     * @return bool
     */
    protected function can_add_activity() {
        global $CFG;
        if (!($modname = $this->get_activitytype())) {
            return false;
        }
        if (!has_capability('moodle/course:manageactivities', context_course::instance($this->courseid))) {
            return false;
        }
        if (!course_allowed_module($this->get_course(), $modname)) {
            return false;
        }
        $libfile = "$CFG->dirroot/mod/$modname/lib.php";
        if (!file_exists($libfile)) {
            return null;
        }
        return true;
    }

    /**
     * Checks if the activity type requires subtypes.
     *
     * @return bool|null (null if the check is not possible)
     */
    public function activity_has_subtypes() {
        global $CFG;
        if (!($modname = $this->get_activitytype())) {
            return null;
        }
        $libfile = "$CFG->dirroot/mod/$modname/lib.php";
        if (!file_exists($libfile)) {
            return null;
        }
        include_once($libfile);
        return function_exists($modname. '_get_types');
    }

    /**
     * Allows course format to execute code on moodle_page::set_course()
     *
     * This function is executed before the output starts.
     *
     * If everything is configured correctly, user is redirected from the
     * default course view page to the activity view page.
     *
     * "Section 1" is the administrative page to manage orphaned activities
     *
     * If user is on course view page and there is no module added to the course
     * and the user has 'moodle/course:manageactivities' capability, redirect to create module
     * form.
     *
     * @param moodle_page $page instance of page calling set_course
     */
    public function page_set_course(moodle_page $page) {
        global $PAGE;
        $page->add_body_class('format-'. $this->get_format());
        if ($PAGE == $page && $page->has_set_url() &&
                $page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
            $edit = optional_param('edit', -1, PARAM_BOOL);
            if (($edit == 0 || $edit == 1) && confirm_sesskey()) {
                // This is a request to turn editing mode on or off, do not redirect here, /course/view.php will do redirection.
                return;
            }
            $cm = $this->get_activity();
            $cursection = optional_param('section', null, PARAM_INT);
            if (!empty($cursection) && has_capability('moodle/course:viewhiddensections',
                    context_course::instance($this->courseid))) {
                // Display orphaned activities (course view page, section 1).
                return;
            }
            if (!$this->get_activitytype()) {
                if (has_capability('moodle/course:update', context_course::instance($this->courseid))) {
                    // Teacher is redirected to edit course page.
                    $url = new moodle_url('/course/edit.php', array('id' => $this->courseid));
                    redirect($url, get_string('erroractivitytype', 'format_singleactivity'));
                } else {
                    // Student sees an empty course page.
                    return;
                }
            }
            if ($cm === null) {
                if ($this->can_add_activity()) {
                    // This is a user who has capability to create an activity.
                    if ($this->activity_has_subtypes()) {
                        // Activity that requires subtype can not be added automatically.
                        if (optional_param('addactivity', 0, PARAM_INT)) {
                            return;
                        } else {
                            $url = new moodle_url('/course/view.php', array('id' => $this->courseid, 'addactivity' => 1));
                            redirect($url);
                        }
                    }
                    // Redirect to the add activity form.
                    $url = new moodle_url('/course/mod.php', array('id' => $this->courseid,
                        'section' => 0, 'sesskey' => sesskey(), 'add' => $this->get_activitytype()));
                    redirect($url);
                } else {
                    // Student views an empty course page.
                    return;
                }
            } else if (!$cm->uservisible || !$cm->get_url()) {
                // Activity is set but not visible to current user or does not have url.
                // Display course page (either empty or with availability restriction info).
                return;
            } else {
                // Everything is set up and accessible, redirect to the activity page!
                redirect($cm->get_url());
            }
        }
    }

    /**
     * Allows course format to execute code on moodle_page::set_cm()
     *
     * If we are inside the main module for this course, remove extra node level
     * from navigation: substitute course node with activity node, move all children
     *
     * @param moodle_page $page instance of page calling set_cm
     */
    public function page_set_cm(moodle_page $page) {
        global $PAGE;
        parent::page_set_cm($page);
        if ($PAGE == $page && ($cm = $this->get_activity()) &&
                $cm->uservisible &&
                ($cm->id === $page->cm->id) &&
                ($activitynode = $page->navigation->find($cm->id, navigation_node::TYPE_ACTIVITY)) &&
                ($node = $page->navigation->find($page->course->id, navigation_node::TYPE_COURSE))) {
            // Substitute course node with activity node, move all children.
            $node->action = $activitynode->action;
            $node->type = $activitynode->type;
            $node->id = $activitynode->id;
            $node->key = $activitynode->key;
            $node->isactive = $node->isactive || $activitynode->isactive;
            $node->icon = null;
            if ($activitynode->children->count()) {
                foreach ($activitynode->children as &$child) {
                    $child->remove();
                    $node->add_node($child);
                }
            } else {
                $node->search_for_active_node();
            }
            $activitynode->remove();
        }
    }

    /**
     * Returns true if the course has a front page.
     *
     * @return boolean false
     */
    public function has_view_page() {
        return false;
    }

}