text:
If you use [react-responsive](https://github.com/contra/react-responsive) and [server-side-rendering](https://facebook.github.io/react/docs/react-dom-server.html) you've probably come across this cryptic warning in your browser console before:

#### react 16
> Warning: Expected server HTML to contain a matching  in .

#### react 15
> Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server: (client) actid="1">Foo

Bar
<div

This happens when the server and client disagree about the state of the DOM. With [react-responsive](https://github.com/contra/react-responsive) specifically it can be caused by code like this:
```javascript
<MediaQuery maxWidth={991}>
  <div>You are a mobile device</div>
</MediaQuery>
<MediaQuery minWidth={992}>
  <div>You are a desktop</div>
</MediaQuery>
```
On the client side this works just fine, but on the server side it doesn't because there's no DOM to query, so both components render empty on the server. Once `react` takes over on the client side it will re-render these elements correctly based on the provided media queries.

 [react-responsive](https://github.com/contra/react-responsive) offers the [values prop](https://github.com/contra/react-responsive#server-rendering) as a workaround:
```javascript
<MediaQuery maxWidth={991} values={{ width: 1024 }}>
  <div>You are a mobile device</div>
</MediaQuery>
<MediaQuery minWidth={992} values={{ width: 1024 }}>
  <div>You are a desktop</div>
</MediaQuery>
```

This example will work fine as long as your browser window is `>= 1024px`. If it's not you're back to the warning above.

### A Solution

`react-responsive-redux` combines several pieces together to work around this issue.
1. The `User-Agent` string is sniffed to get a reasonable guess of the client's screen size
2. This value is stored in [redux](http://redux.js.org/) store so it's globally accessible
3. Wrapped versions of [MediaQuery](https://github.com/contra/react-responsive#using-css-media-queries) are provided which get their `width` from the global store.

The end result is that it's possible to do server-side rendering correctly for responsive pages which change for mobile, tablet, or desktop users (it also means that `react` warning probably disappears):
```javascript
<MobileScreen>
  <div>You are a mobile device</div>
</MobileScreen>
<DesktopScreen>
  <div>You are a desktop</div>
</DesktopScreen>
```

## Installation
Install with [npm](https://www.npmjs.com/):
```
npm install react-responsive-redux
```
`react-responsive-redux` has the following `peerDependencies`:
```
"prop-types": "^15.5.10",
"react": "^15.6.1 || ^16.0.0",
"react-redux": "^5.0.6",
"redux": "^3.7.2"
```

## Usage
### Example
Inside the `example` directory run:
```
$ yarn install
$ yarn build
$ yarn start
```
Try loading the page with chrome on a desktop display and pretending to be a mobile device.
In both cases you'll notice the initial redux state is correct and there's no error in the console.

### Overview
To use `react-responsive-redux` you need to do the following:
1. Add a redux reducer to your store
2. Add mobile detection and an action dispatch in your request handler
3. Use a wrapped component

### redux setup
Add the `responsive` reducer into your `redux` store:

#### ES5 Example
```javascript
var redux = require('redux')
var responsiveReducer = require('react-responsive-redux').reducer

var reducers = {
  // ... your other reducers here ...
  responsive: responsiveReducer
}
var reducer = redux.combineReducers(reducers)
var store = redux.createStore(reducer)
```

#### ES6 Example
```javascript
import { createStore, combineReducers } from 'redux'
import { reducer as responsiveReducer } from 'react-responsive-redux'

const reducers = {
  // ... your other reducers here ...
  responsive: responsiveReducer
}
const reducer = combineReducers(reducers)
const store = createStore(reducer)
```

### server setup
Add mobile detection and dispatch a redux action during your request handler. This must happen after you've created your `redux` store and before you do your server-side rendering.

(Note: these examples are based on the [redux SSR example](http://redux.js.org/docs/recipes/ServerRendering.html#the-server-side) and are incomplete as-is).
#### ES5 Example
```javascript
var setMobileDetect = require('react-responsive-redux').setMobileDetect
var mobileParser = require('react-responsive-redux').mobileParser
var reducers = require('./reducers')
var renderToString = require('react-dom/server').renderToString

function handleRender(req, res) {
  // Create a new Redux store instance
  var store = createStore(reducers)
  var dispatch = store.dispatch

  // do our mobile detection
  var mobileDetect = mobileParser(req)

  // set mobile detection for our responsive store
  dispatch(setMobileDetect(mobileDetect))

  // Render the component to a string
  var html = renderToString(
    <Provider store={store}>
      <App />
    </Provider>
  )

  // Grab the initial state from our Redux store
  var preloadedState = store.getState()

  // Send the rendered page back to the client
  res.send(renderFullPage(html, preloadedState))
}
```

#### ES6 Example
```javascript
import { setMobileDetect, mobileParser } from 'react-responsive-redux'
import reducers from './reducers'
import { renderToString } from 'react-dom/server'

function handleRender(req, res) {
  // Create a new Redux store instance
  const store = createStore(reducers)
  const { dispatch } = store

  // do our mobile detection
  const mobileDetect = mobileParser(req)

  // set mobile detection for our responsive store
  dispatch(setMobileDetect(mobileDetect))

  // Render the component to a string
  const html = renderToString(
    <Provider store={store}>
      <App />
    </Provider>
  )

  // Grab the initial state from our Redux store
  const preloadedState = store.getState()

  // Send the rendered page back to the client
  res.send(renderFullPage(html, preloadedState))
}
```
### React Components

#### responsiveWrapper(props={})
`responsiveWrapper` is a wrapper to generate [redux](http://redux.js.org/)-connected [MediaQuery](https://github.com/contra/react-responsive#using-css-media-queries) components. These components have `width` and `deviceWidth` set in the [values prop](https://github.com/contra/react-responsive#server-rendering) from the connected store. All props are passed through to the underlying `<MediaQuery` instance.

The following convenience components are exported and are all are built using `responsiveWrapper`:

##### Bootstrap sizes

#### <XsScreen>
```javascript
export const XsScreen = responsiveWrapper({ maxWidth: 767 })
```
#### <XsScreenHidden>
```javascript
export const XsScreenHidden = responsiveWrapper({ minWidth: 768 })
```
#### <SmScreen>
```javascript
export const SmScreen = responsiveWrapper({ query: `(min-width: 768px) and (max-width: 992px)` })
```
#### <SmScreenHidden>
```javascript
export const SmScreenHidden = responsiveWrapper({ query: `(max-width: 767px), (min-width: 993px)` })
```

#### <MdScreen>
```javascript
export const MdScreen = responsiveWrapper({ query: `(min-width: 993px) and (max-width: 1199px)` })
```
#### <MdScreenHidden>
```javascript
export const MdScreenHidden = responsiveWrapper({ query: `(max-width: 992px), (min-width: 1200px)` })
```

#### <LgScreen>
```javascript
export const LgScreen = responsiveWrapper({ minWidth: 1200 })
```

#### <LgScreenHidden>
```javascript
export const LgScreenHidden = responsiveWrapper({ maxWidth: 1199 })
```

##### Generic

#### <PhoneScreen>
alias for `<XsScreen>`

#### <PhoneScreenHidden>
alias for `<XsScreenHidden>`

#### <TabletScreen>
alias for `<SmScreen>`

#### <TabletScreenHidden>
alias for `<SmScreenHidden>`

#### <MobileScreen>
```javascript
export const MobileScreen = responsiveWrapper({ maxWidth: 991 })
```
#### <MobileScreenHidden>
alias for `<DesktopScreen>`

#### <DesktopScreen>
```javascript
export const DesktopScreeen = responsiveWrapper({ minWidth: 992 })
```
#### <DesktopScreenHidden>
alias for `<MobileScreen>`

#### ES5 Example
```javascript
var React = require('react')
var MobileScreen = require('react-responsive-redux').MobileScreen
var DesktopScreen = require('react-responsive-redux').DesktopScreen

function Component() {
  return(
    <div>
      <MobileScreen>
        <div>You are a mobile device</div>
      </MobileScreen>
      <DesktopScreen>
        <div>You are a desktop</div>
      </DesktopScreen>
    </div>
  )
}

```

#### ES6 Example
```javascript
import React from 'react'
import { MobileScreen, DesktopScreen } from 'react-responsive-redux'

const Component = () =>
  <div>
    <MobileScreen>
      <div>You are a mobile device</div>
    </MobileScreen>
    <DesktopScreen>
      <div>You are a desktop</div>
    </DesktopScreen>
  </div>
```

### Breakpoints
The current breakpoints are based on [bootstrap's](https://v4-alpha.getbootstrap.com/layout/overview/#responsive-breakpoints) sizings.

|Device Type| Breakpoint |
|-----------|-----|
| xs | max-width: 767px |
| sm | min-width: 768px, max-width: 991px |
| md | min-width: 992px, max-width: 1199px |
| lg | min-width: 1200px |
| Phone | max-width: 767px |
| Tablet | min-width: 768px, max-width: 991px |
| Mobile | max-width: 991px |
| Desktop | min-width: 992px |
-----------------

### Fake Widths
Device detection is done using [mobile-detect](https://github.com/hgoebl/mobile-detect.js) which allows us to get the following information:

 * `mobile` - is the device mobile (ie, `phone` or `tablet`)
 * `phone` - is the device a phone?
 * `tablet` - is the device a tablet?
 * `desktop` - the opposite of `mobile`

Based on this information and our breakpoints we set a fake screen size in our store:

|Device Type| Fake Width (in px)|
|-----------|-----|
| Phone | 767 |
| Tablet | 991 |
| Mobile | 767 |
| Desktop | 1200 |
-----------------

Note that the `desktop` fake width is set to `1200px` rather than `992px` - this is because [worldwide trends](http://gs.statcounter.com/screen-resolution-stats) indicate that most desktop views are >= `1200px` and defaulting the `desktop` size to this means that `<LgScreen>` / `<LgScreenHidden>` are more likely to render correctly on the server side.

### Examples for rendering to different components

```javascript
import React from 'react'
import { MobileScreen, DesktopScreen } from 'react-responsive-redux'

const Component = () =>
  <div>
    <MobileScreen component="p">
      You are a mobile device
    </MobileScreen>
    <DesktopScreen component={React.Fragment}>
      You are a desktop
    </DesktopScreen>
  </div>
```

### TODO
 * Add support for custom breakpoints
 * Add support for custom screen sizes


text:
import { User } from './User.js';

User.helpers({
  email() {
    return this.emails[0].address;
  },
  fullName() {
    const profile = this.profile;
    const {
      firstName,
      lastName,
    } = profile;

    return `${firstName} ${lastName}`;
  },
});

redpajama_set_name: RedPajamaGithub


text:
package conquest.bot.fight;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;

/**
 * Serves for the computation of victory probabilities of #ATTACKERS vs #DEFENDERS fights.
 * @author Jimmy
 */
public class FightSimulation {

	public static class FightResults implements Serializable {

		/**
		 * AUTO-GENERATED
		 */
		private static final long serialVersionUID = -2574692112490137019L;

		public final FightResult[][] results;

		/**
		 * Chance that an attacker will be killed during one fight round.
		 */
		public final double attackerDieChance;
		/**
		 * Chance that a defender will be killed during one fight round.
		 */
		public final double defenderDieChance;
		/**
		 * If fight-state probability dropped below this number, it was rounded to zero and was not used during computation.
		 */
		public final double computationAttackersWinChanceTrim;

		public FightResults(int attackersMax, int defendersMax, double attackerDieChance, double defenderDieChance, double computationAttackersWinChanceTrim) {
			results = new FightResult[attackersMax+1][defendersMax+1];
			for (int i = 0; i <= attackersMax; ++i) {
				for (int j = 0; j <= defendersMax; ++j) {
					results[i][j] = null;
				}
			}
			this.attackerDieChance = attackerDieChance;
			this.defenderDieChance = defenderDieChance;
			this.computationAttackersWinChanceTrim = computationAttackersWinChanceTrim;
		}

		public int getAttackersMax() {
			return results.length-1;
		}

		public int getDefendersMax() {
			return results[0].length-1;
		}

		public FightResult getResult(int attackers, int defenders) {
			return results[attackers][defenders];
		}

	}

	public static class FightAttackersResults extends FightResults implements Serializable {

		/**
		 * AUTO-GENERATED
		 */
		private static final long serialVersionUID = -2574698112490127019L;

		/**
		 * Whenever overall WIN CHANCE of the attackers drops below this number, we will not generate results for it, we will store NULL for that instead.
		 */
		public final double attackersWinChanceTrim;

		public FightAttackersResults(int attackersMax, int defendersMax, double attackerDieChance, double defenderDieChance, double computationAttackersWinChanceTrim, double attackersWinChanceTrim) {
			super(attackersMax, defendersMax, attackerDieChance, defenderDieChance, computationAttackersWinChanceTrim);
			this.attackersWinChanceTrim = attackersWinChanceTrim;
		}

        public double getAttackersWinChance(int attackers, int defenders) {
            try {
                if (results[attackers][defenders] == null) return 0.0;
                return results[attackers][defenders].attackersWinChance;
            } catch (Exception e) {
                return 0.0;
            }
        }

        public double getDefendersWinChance(int attackers, int defenders) {
            try {
                if (results[attackers][defenders] == null) return 1.0;
                return results[attackers][defenders].defendersWinChance;
            } catch (Exception e) {
                return 1.0;
            }
        }

        public double getExpectedAttackersDeaths(int attackers, int defenders) {
            try {
                if (results[attackers][defenders] == null) return attackers;
                return results[attackers][defenders].expectedAttackersDeaths;
            } catch (Exception e) {
                return attackers;
            }
        }

        public Double getExpectedDefendersDeaths(int attackers, int defenders) {
            try {
                if (results[attackers][defenders] == null) return null;
                return results[attackers][defenders].expectedDefendersDeaths;
            } catch (Exception e) {
                return null;
            }
        }

		public void saveToFile(File file) {
			ObjectOutputStream stream = null;
			try {
				stream = new ObjectOutputStream(new FileOutputStream(file));
				stream.writeObject(this);
				stream.close();
			} catch (Exception e) {
				if (stream != null) {
					try {
						stream.close();
					} catch (Exception e1) {
					}
				}
				throw new RuntimeException("Failed to save FightAttackersResults into: " + file.getAbsolutePath(), e);
			}
		}

		public static FightAttackersResults loadFromFile(File file) {
			ObjectInputStream stream = null;
			FightAttackersResults result = null;
			try {
				stream = new ObjectInputStream(new FileInputStream(file));
				result = (FightAttackersResults)stream.readObject();
				stream.close();
			} catch (Exception e) {
				if (stream != null) {
					try {
						stream.close();
					} catch (Exception e1) {
					}
				}
				throw new RuntimeException("Failed to load FightAttackersResults from: " + file.getAbsolutePath(), e);
			}
			return result;
		}

	}

	public static class FightDefendersResults extends FightResults implements Serializable {

		/**
		 * AUTO-GENERATED
		 */
		private static final long serialVersionUID = -2571698112490127018L;

		/**
		 * Whenever overall WIN CHANCE of the defenders drops below this number, we will not generate results for it, we will store NULL for that instead.
		 */
		public final double defendersWinChanceTrim;

		public FightDefendersResults(int attackersMax, int defendersMax, double attackerDieChance, double defenderDieChance, double computationAttackersWinChanceTrim, double defendersWinChanceTrim) {
			super(attackersMax, defendersMax, attackerDieChance, defenderDieChance, computationAttackersWinChanceTrim);
			this.defendersWinChanceTrim = defendersWinChanceTrim;
		}

		public double getAttackersWinChance(int attackers, int defenders) {
			if (results[attackers][defenders] == null) return 1;
			return results[attackers][defenders].attackersWinChance;
		}

		public double getDefendersWinChance(int attackers, int defenders) {
			if (results[attackers][defenders] == null) return 0;
			return results[attackers][defenders].defendersWinChance;
		}

		public Double getExpectedAttackersDeaths(int attackers, int defenders) {
			if (results[attackers][defenders] == null) return null;
			return results[attackers][defenders].expectedAttackersDeaths;
		}

		public double getExpectedDefendersDeaths(int attackers, int defenders) {
			if (results[attackers][defenders] == null) return defenders;
			return results[attackers][defenders].expectedDefendersDeaths;
		}

		public void saveToFile(File file) {
			ObjectOutputStream stream = null;
			try {
				stream = new ObjectOutputStream(new FileOutputStream(file));
				stream.writeObject(this);
				stream.close();
			} catch (Exception e) {
				if (stream != null) {
					try {
						stream.close();
					} catch (Exception e1) {
					}
				}
				throw new RuntimeException("Failed to save FightDefendersResults into: " + file.getAbsolutePath(), e);
			}
		}

		public static FightDefendersResults loadFromFile(File file) {
			ObjectInputStream stream = null;
			FightDefendersResults result = null;
			try {
				stream = new ObjectInputStream(new FileInputStream(file));
				result = (FightDefendersResults)stream.readObject();
				stream.close();
			} catch (Exception e) {
				if (stream != null) {
					try {
						stream.close();
					} catch (Exception e1) {
					}
				}
				throw new RuntimeException("Failed to load FightDefendersResults from: " + file.getAbsolutePath(), e);
			}
			return result;
		}

	}

	public double[][] states;

	public FightResult result;

	private int attackersMax;
	private int defendersMax;
	private double attackerDieChance;
	private double defenderDieChance;

	private double a1d1;
	private double a1d0;
	private double a0d1;

	public FightSimulation(int attackers, int defenders, double defenderDieChance, double attackerDieChance) {
		this.attackersMax = attackers;
		this.defendersMax = defenders;
		this.attackerDieChance = defenderDieChance;
		this.defenderDieChance = attackerDieChance;

		states = new double[attackers+1][defenders+1];
		for (int i = 0; i <= attackers; ++i) {
			for (int j = 0; j <= defenders; ++j) {
				states[i][j] = 0;
			}
		}

		states[attackers][defenders] = 1;

		// 0 attackers died, 0 defenders died
		double a0d0 = (1-defenderDieChance) * (1-attackerDieChance);
		// 1 attacker died, 1 defender died
		a1d1 = defenderDieChance * attackerDieChance;
		// 1 attacker died, 0 defenders died
		a1d0 = (1-defenderDieChance) * attackerDieChance;
		// 0 attackers died, 1 defender died
		a0d1 = defenderDieChance * (1-attackerDieChance);

		double sum = 1 - a0d0;

		// DIVIDIND a0d0 BETWEEN OTHER TRANSITIONS
		a1d1 = a1d1 + a0d0 * (a1d1 / sum);
		a1d0 = a1d0 + a0d0 * (a1d0 / sum);
		a0d1 = a0d1 + a0d0 * (a0d1 / sum);
	}

	public int getAttackers() {
		return attackersMax;
	}

	public int getDefenders() {
		return defendersMax;
	}

	public double getAttackerDieChance() {
		return attackerDieChance;
	}

	public double getDefenderDieChance() {
		return defenderDieChance;
	}

	/**
	 * @param chanceTrim once state probability drops below 'chanceTrim' it will  be rounded to 0 and won't be used to compute further results.
	 * @return
	 */
	public FightSimulation compute(double attackersVictoryChanceTrim) {
		int target = Math.max(attackersMax, defendersMax);

		System.out.println("COMPUTING FIGHT MATRIX A:" + attackersMax + " vs. D:" + defendersMax);
		System.out.println("Attacker die chance -> " + attackerDieChance);
		System.out.println("Defender die chance -> " + defenderDieChance);
		System.out.println("A1D1 -> " + FightUtils.formatterChance.format(a1d1));
		System.out.println("A1D0 -> " + FightUtils.formatterChance.format(a1d0));
		System.out.println("A0D1 -> " + FightUtils.formatterChance.format(a0d1));
		System.out.println("SUM  -> " + FightUtils.formatterChance.format(a1d1 + a1d0 + a0d1));
		long time = System.currentTimeMillis();

		System.out.println("FIRST HALF");
		for (int i = 0; i < target; ++i) {
			for (int j = 0; j < target; ++j) {
				int attackers = attackersMax - i + j;
				int defenders = defendersMax - j;

				if (attackers < 1 || attackers > attackersMax) break;
				if (defenders < 1 || defenders > defendersMax) break;

				if (states[attackers][defenders] > attackersVictoryChanceTrim) {
					updateState(attackers, defenders);
				}
			}
		}

		System.out.println("SECOND HALF");
		for (int i = 0; i < target; ++i) {
			for (int j = 0; j < target; ++j) {
				int attackers = 1 + j;
				int defenders = defendersMax - 1 - i - j;

				if (attackers < 1 || attackers > attackersMax) break;
				if (defenders < 1 || defenders > defendersMax) break;

				updateState(attackers, defenders);
			}
		}

		System.out.println("FINISHED in " + (System.currentTimeMillis()-time) + " ms");

		return this;
	}

	public FightResult getResult() {

		System.out.println("READING PROBABILITIES");

		FightResult result = new FightResult();

		double sum = 0;

		double winSum = 0;
		double loseSum = 0;

		double expectedAttackersDeaths = 0;
		double expectedDefendersDeaths = 0;

		for (int i = 1; i <= attackersMax; ++i) {
			System.out.println("WIN  ["+i+"][0] -> " + FightUtils.formatterChance.format(states[i][0]));
			sum = sum + states[i][0];
			winSum = winSum + states[i][0];

			double attackersDied = attackersMax - i;
			double defendersDied = defendersMax;

			expectedAttackersDeaths = expectedAttackersDeaths + states[i][0] * attackersDied;
			expectedDefendersDeaths = expectedDefendersDeaths + states[i][0] * defendersDied;
		}

		for (int i = 0; i <= defendersMax; ++i) {
			System.out.println("LOSE [0]["+i+"] -> " + FightUtils.formatterChance.format(states[0][i]));
			sum = sum + states[0][i];
			loseSum = loseSum + states[0][i];

			double attackersDied = attackersMax;
			double defendersDied = defendersMax - i;

			expectedAttackersDeaths = expectedAttackersDeaths + states[0][i] * attackersDied;
			expectedDefendersDeaths = expectedDefendersDeaths + states[0][i] * defendersDied;
		}

		result.attackersWinChance = winSum;
		result.defendersWinChance = loseSum;
		result.expectedAttackersDeaths = expectedAttackersDeaths;
		result.expectedDefendersDeaths = expectedDefendersDeaths;

		result.println();
		System.out.println("CONTROL SUM -> " + FightUtils.formatterChance.format(sum));

		this.result = result;

		return result;
	}

	private void updateState(int attackers, int defenders) {
		double state = states[attackers][defenders];

		int aMinus = attackers - 1;
		int dMinus = defenders - 1;

		//System.out.println("[" + attackers + "][" + defenders + "] -> " + FightUtils.formatterChance.format(state.probability) + " -> [" + aMinus + "][" + defenders + "] | [" + attackers + "][" + dMinus + "] | [" + aMinus + "][" + dMinus + "]");

		if (aMinus >= 0) {
			if (dMinus >= 0) {
				double sA1D1 = states[aMinus][dMinus];
				states[aMinus][dMinus] = sA1D1 + state * a1d1;
			}

			double sA1D0 = states[aMinus][defenders];
			states[aMinus][defenders] = sA1D0 + state * a1d0;
		}
		if (dMinus >= 0) {
			double sA0D1 = states[attackers][dMinus];
			states[attackers][dMinus] = sA0D1 + state * a0d1;
		}
	}

	public static void GenerateFightResults(int attackersMax, int defendersMax, double defenderDieChance, double attackerDieChance, double computationAttackersWinChanceTrim, double attackersWinChanceTrim, double defendersWinChanceTrim, File attackersFile, File defendersFile) {
		// ATTACKERS
		FightAttackersResults attackersResults = new FightAttackersResults(attackersMax, defendersMax, attackerDieChance, defenderDieChance, computationAttackersWinChanceTrim, attackersWinChanceTrim);
		for (int defenders = 1; defenders <= defendersMax; ++defenders) {
			for (int attackers = attackersMax; attackers > 0; --attackers) {
				FightSimulation simulator = new FightSimulation(attackers, defenders, defenderDieChance, attackerDieChance);
				simulator.compute(computationAttackersWinChanceTrim);
				FightResult result = simulator.getResult();
				if (result.attackersWinChance < attackersWinChanceTrim) {
					// TOO SMALL CHANCE FOR VICTORY!
					attackersResults.results[attackers][defenders] = null;
					// having fewer attackers won't help us
					// => continue with another number of defenders
					break;
				} else {
					attackersResults.results[attackers][defenders] = result;
				}
			}
		}
		System.out.println("SAVING FILE: " + attackersFile.getAbsolutePath());
		attackersResults.saveToFile(attackersFile);

		// DEFENDERS
		FightDefendersResults defendersResults = new FightDefendersResults(attackersMax, defendersMax, attackerDieChance, defenderDieChance, computationAttackersWinChanceTrim, defendersWinChanceTrim);
		for (int attackers = 1; attackers <= attackersMax; ++attackers) {
			for (int defenders = defendersMax; defenders > 0; --defenders) {
				FightSimulation simulator = new FightSimulation(attackers, defenders, defenderDieChance, attackerDieChance);
				simulator.compute(computationAttackersWinChanceTrim);
				FightResult result = simulator.getResult();
				if (result.defendersWinChance < defendersWinChanceTrim) {
					// TOO SMALL CHANCE FOR DEFENDERS VICTORY!
					defendersResults.results[attackers][defenders] = null;
					// having fewer defenders won't help us
					// => continue with another number of attackers
					break;
				} else {
					defendersResults.results[attackers][defenders] = result;
				}
			}
		}
		System.out.println("SAVING FILE: " + defendersFile.getAbsolutePath());
		defendersResults.saveToFile(defendersFile);

		System.out.println("---// DONE //---");
	}

	public static void GenerateFightDefendersResults(int attackersMax, int defendersMax, double defenderDieChance, double attackerDieChance, double computationAttackersWinChanceTrim, double winChanceTrim, File file) {

		System.out.println("---// DONE //---");
	}

	public static void main(String[] args) {
		// EXAMPLE HOW TO GENERATE RESULTS FOR A SINGLE FIGHT
		//new FightSimulation(80, 90, 0.6, 0.7).compute(0.00000001).getResult();

		// EXAMPLE HOW TO GENERATE AND SAVE THE WHOLE MATRIX...
		//GenerateFightResults(  50,   50, 0.6, 0.7, 0.00000001, 0.001, 0.001, new File("FightSimulation-Attackers-A50-D50.obj"),     new File("FightSimulation-Defenders-A50-D50.obj"));
		//GenerateFightResults( 100,  100, 0.6, 0.7, 0.00000001, 0.001, 0.001, new File("FightSimulation-Attackers-A100-D100.obj"),   new File("FightSimulation-Defenders-A100-D100.obj"));
		GenerateFightResults( 200,  200, 0.6, 0.7, 0.00000001, 0.001, 0.001, new File("FightSimulation-Attackers-A200-D200.obj"),   new File("FightSimulation-Defenders-A200-D200.obj"));
		//GenerateFightResults( 500,  500, 0.6, 0.7, 0.00000001, 0.001, 0.001, new File("FightSimulation-Attackers-A500-D500.obj"),   new File("FightSimulation-Defenders-A500-D500.obj"));
		//GenerateFightResults(1000, 1000, 0.6, 0.7, 0.00000001, 0.001, 0.001, new File("FightSimulation-Attackers-A1000-D1000.obj"), new File("FightSimulation-Defenders-A1000-D1000.obj"));
	}
}


text:
App::Application.routes.draw do

  resources :game_events

  resources :worlds

  devise_for :users #,
  #   path: "auth", path_names: {
  #   sign_in: 'login',
  #   sign_out: 'logout',
  #   password: 'secret',
  #   confirmation: 'verification',
  #   unlock: 'unblock',
  #   registration: 'register',
  #   sign_up: 'cmon_let_me_in'
  # }

  resources :u, :controller => 'users'

  root to: "worlds#index"

end


text:
package aaa.bbb;

/**
 * Created in IntelliJ IDEA.
 * And some more text.
 */
public class Margin {
}


text:
package gridwhack.fov;

import gridwhack.gameobject.grid.Grid;

/**
 * Ray tracing field of view class.
 * @author Christoffer Niska <ChristofferNiska@gmail.com>
 */
public class RayTracing extends GridFov
{
	/**
	 * Creates the field of view.
	 * @param viewer The owner of this field of view.
	 * @param grid The grid the viewer belongs to.
	 */
	public RayTracing(int radius, Grid grid, IViewer viewer)
	{
		super(radius, grid, viewer);
	}

	/**
	 * Updates the field of view.
	 * @param cx The current x-coordinate.
	 * @param cy The current y-coordinate.
	 */
	public void refresh(int cx, int cy)
	{
		init();

		for (int x = 0, width = getWidth(); x < width; x++)
		{
			for (int y = 0, height = getHeight(); y < height; y++)
			{
				if ((x == 0 || y == 0) || (x == width-1 || y == height-1))
				{
					castRay(cx, cy, x, y, getRadius());
				}
			}
		}
	}

	/**
	 * Raytracing method that uses an integer only version
	 * of "Bresenham line-drawing algorithm" to determine
	 * if the target can be seen from a specific position.
	 * @param sx the starting x-coordinate.
	 * @param sy the starting y-coordinate.
	 * @param tx the target x-coordinate.
	 * @param ty the target y-coordinate.
	 * @param range the view range in grid cells.
	 */
	public void castRay(int sx, int sy, int tx, int ty, int range)
	{
		// Calculate the deltas.
		int dx = Math.abs(tx - sx);
		int dy = Math.abs(ty - sy);

		int x = sx;
		int y = sy;

		// Calculate how many moves are required to reach the target.
		int n = 1 + dx + dy;

		// Calculate x- and y-increments.
		int xi = (tx > sx) ? 1 : -1;
		int yi = (ty > sy) ? 1 : -1;

		// Determine in which direction to set off.
		int error = dx - dy;

		dx *= 2;
		dy *= 2;

		Grid grid = getGrid();

		IViewer viewer = getViewer();

		// We need to remember where we started in order to check the range.
		int start = n;

		// We have not hit anything solid yet.
		boolean solid = false;

		// Loop while we have not hit anything solid.
		while (!solid && n > 0)
		{
			// Check whether the ray hit something solid.
			if (grid.isSolid(x, y, viewer))
			{
				solid = true;
			}

			// Mark grid cell within the range as visible.
			if (!visible[x][y] && n >= (start - range))
			{
				visible[x][y] = true;
			}

			// Add visible fields to the complete field of view if necessary.
			if (!complete[x][y])
			{
				complete[x][y] = true;
			}

			// Move horizontally.
			if (error > 0)
			{
				x += xi;
				error -= dy;
			}
			// Move vertically.
			else if (error < 0)
			{
				y += yi;
				error += dx;
			}
			// Line is passing through both a vertical and horizontal line.
			else
			{
				x += xi;
				error -= dy;
				y += yi;
				error += dx;
				n--;
			}

			n--;
		}
	}
}


text:
package com.sap.cloud.lm.sl.cf.web.message;

/**
 * A collection of string constants used for exception and logging messages.
 */
public final class Messages {

    public static final String CREATE_DEPLOY_TARGET = "Create deploy target";
    public static final String UPDATE_DEPLOY_TARGET = "Update deploy target";
    public static final String DELETE_DEPLOY_TARGET = "Delete deploy target";

    // Exception messages
    public static final String ORG_SPACE_NOT_SPECIFIED_1 = "Target does not contain 'org' and 'space' properties";
    public static final String ORG_SPACE_NOT_SPECIFIED_2 = "Target does not contain 'org' and 'space' parameters";
    public static final String ERROR_EXECUTING_REST_API_CALL = "Error occurred while executing REST API call";
    public static final String CONFIGURATION_ENTRY_ID_CANNOT_BE_UPDATED = "A configuration entry''s id cannot be updated";
    public static final String PROPERTY_DOES_NOT_CONTAIN_KEY_VALUE_PAIR = "Property \"{0}\" does not contain a key value pair";
    public static final String COULD_NOT_PARSE_CONTENT_PARAMETER = "Could not parse content query parameter as JSON or list";
    public static final String COULD_NOT_PARSE_NUMBER = "Could not parse \"{0}\" to number";
    public static final String MAX_UPLOAD_SIZE_EXCEEDED = "Cannot upload file, size is bigger than the configured maximum upload size \"{0}\" bytes";

    // Audit log messages

    // ERROR log messages
    public static final String MTA_NOT_FOUND = "MTA with id \"{0}\" does not exist";

    public static final String ERROR_STORING_OAUTH_TOKEN_IN_SECURE_STORE = "Error storing OAuth access token with id \"{0}\" in token store. Entry with this id already exists";
    public static final String ERROR_COMPRESSING_OAUTH_TOKEN = "Error compressing OAuth access token";
    public static final String ERROR_DECOMPRESSING_OAUTH_TOKEN = "Error decompressing OAuth access token";
    public static final String TOKEN_NOT_FOUND_IN_SECURE_STORE = "Token not found in secure store";
    public static final String TOKEN_KEY_FORMAT_NOT_VALID = "Token key format not valid";
    public static final String COULD_NOT_PARSE_CONTENT_PARAMETER_AS_JSON = "Could not parse content query parameter as JSON: {0}";
    public static final String COULD_NOT_PARSE_CONTENT_PARAMETER_AS_LIST = "Could not parse content query parameter as list: {0}";
    public static final String ORG_AND_SPACE_MUST_BE_SPECIFIED = "Org and space must be specified!";
    public static final String RETRIEVE_CONFIGURATION_SUBSCRIPTIONS_IN_ORG_AND_SPACE = "Retrieve configuration subscriptions in org {0} and space {1}";
    public static final String NOT_AUTHORIZED_TO_PERFORM_OPERATIONS_IN_SPACE = "You are not authorized to perform operations in the space with id {0}. You need a SpaceDeveloper role to operate in the space";
    public static final String COULD_NOT_GET_FILES = "Could not get MTA files";
    public static final String COULD_NOT_UPLOAD_FILE = "Could not upload MTA file";
    public static final String FILE_SERVICE_CLEANUP_FAILED = "FileService: Failed to delete files without content. Reason: \"{0}\"";

    // WARN log messages

    // INFO log messages
    public static final String OAUTH_TOKEN_STORE = "Using OAuth token store \"{0}\"";
    public static final String ALM_SERVICE_ENV_INITIALIZED = "Deploy service environment initialized";
    public static final String AUDIT_LOG_ABOUT_TO_PERFORM_SERVICE_ACTION = "About to perform action \"{0}\" on service \"{1}\"";
    public static final String AUDIT_LOG_SERVICE_ACTION_SUCCESS = "Succesfuly performed action \"{0}\" on service \"{1}\"";
    public static final String AUDIT_LOG_SERVICE_ACTION_FAILURE = "Failed to perform action \"{0}\" on service \"{1}\"";
    public static final String CANNOT_AUTHENTICATE_WITH_CLOUD_CONTROLLER = "Cannot authenticate with cloud controller";
    public static final String ASYNC_DATABASE_CHANGES_WILL_NOT_BE_EXECUTED_ON_THIS_INSTANCE = "Async database changes will not be executed on instance {0}.";
    public static final String TOKEN_LOADED_INTO_TOKEN_STORE = "Token with expiration time: {0} for user {1} has been loaded into token store";
    public static final String REGISTERED_0_AS_LIQUIBASE_LOCK_SERVICE = "Registered {0} as a Liquibase lock service.";
    public static final String FILE_SERVICE_DELETED_FILES = "FileService: Deleted {0} files without content.";

    // WARN log messages
    public static final String FILE_SYSTEM_SERVICE_NAME_IS_NOT_SPECIFIED = "Failed to detect file service storage path, because the service name is not specified in the configuration files!";
    public static final String FAILED_TO_DETECT_FILE_SERVICE_STORAGE_PATH = "Failed to detect file service storage path for service \"{0}\"!";

    // DEBUG log messages
    public static final String PARSED_CONTENT = "Parsed content: {0}";
    public static final String COMPUTED_TARGET = "Computed target: {0}";
    public static final String COMPUTING_STATE_OF_OPERATION = "Computing state of operation {0} with ID: {1}";

}


text:
package com.sun.java.util.jar.pack;

import java.io.*;
import java.util.*;
import com.sun.java.util.jar.pack.Package.Class;
import java.lang.reflect.Modifier;

/**
 * Represents a chunk of bytecodes.
 * @author John Rose
 */
class Code extends Attribute.Holder implements Constants {
    Class.Method m;

    public Code(Class.Method m) {
        this.m = m;
    }

    public Class.Method getMethod() {
        return m;
    }
    public Class thisClass() {
        return m.thisClass();
    }
    public Package getPackage() {
        return m.thisClass().getPackage();
    }

    public ConstantPool.Entry[] getCPMap() {
        return m.getCPMap();
    }

    static private final ConstantPool.Entry[] noRefs = ConstantPool.noRefs;

    // The following fields are used directly by the ClassReader, etc.
    int max_stack;
    int max_locals;

    ConstantPool.Entry handler_class[] = noRefs;
    int handler_start[] = noInts;
    int handler_end[] = noInts;
    int handler_catch[] = noInts;

    byte[] bytes;
    Fixups fixups;  // reference relocations, if any are required
    Object insnMap; // array of instruction boundaries

    int getLength() { return bytes.length; }

    int getMaxStack() {
        return max_stack;
    }
    void setMaxStack(int ms) {
        max_stack = ms;
    }

    int getMaxNALocals() {
        int argsize = m.getArgumentSize();
        return max_locals - argsize;
    }
    void setMaxNALocals(int ml) {
        int argsize = m.getArgumentSize();
        max_locals = argsize + ml;
    }

    int getHandlerCount() {
        assert(handler_class.length == handler_start.length);
        assert(handler_class.length == handler_end.length);
        assert(handler_class.length == handler_catch.length);
        return handler_class.length;
    }
    void setHandlerCount(int h) {
        if (h > 0) {
            handler_class = new ConstantPool.Entry[h];
            handler_start = new int[h];
            handler_end   = new int[h];
            handler_catch = new int[h];
            // caller must fill these in ASAP
        }
    }

    void setBytes(byte[] bytes) {
        this.bytes = bytes;
        if (fixups != null)
            fixups.setBytes(bytes);
    }

    void setInstructionMap(int[] insnMap, int mapLen) {
        //int[] oldMap = null;
        //assert((oldMap = getInstructionMap()) != null);
        this.insnMap = allocateInstructionMap(insnMap, mapLen);
        //assert(Arrays.equals(oldMap, getInstructionMap()));
    }
    void setInstructionMap(int[] insnMap) {
        setInstructionMap(insnMap, insnMap.length);
    }

    int[] getInstructionMap() {
        return expandInstructionMap(getInsnMap());
    }

    void addFixups(Collection moreFixups) {
        if (fixups == null) {
            fixups = new Fixups(bytes);
        }
        assert(fixups.getBytes() == bytes);
        fixups.addAll(moreFixups);
    }

    public void trimToSize() {
        if (fixups != null) {
            fixups.trimToSize();
            if (fixups.size() == 0)
                fixups = null;
        }
        super.trimToSize();
    }

    protected void visitRefs(int mode, Collection refs) {
        int verbose = getPackage().verbose;
        if (verbose > 2)
            System.out.println("Reference scan "+this);
        Class cls = thisClass();
        Package pkg = cls.getPackage();
        for (int i = 0; i < handler_class.length; i++) {
            refs.add(handler_class[i]);
        }
        if (fixups != null) {
            fixups.visitRefs(refs);
        } else {
            // References (to a local cpMap) are embedded in the bytes.
            ConstantPool.Entry[] cpMap = getCPMap();
            for (Instruction i = instructionAt(0); i != null; i = i.next()) {
                if (verbose > 4)
                    System.out.println(i);
                int cpref = i.getCPIndex();
                if (cpref >= 0) {
                    refs.add(cpMap[cpref]);
                }
            }
        }
        // Handle attribute list:
        super.visitRefs(mode, refs);
    }

    // Since bytecodes are the single largest contributor to
    // package size, it's worth a little bit of trouble
    // to reduce the per-bytecode memory footprint.
    // In the current scheme, half of the bulk of these arrays
    // due to bytes, and half to shorts.  (Ints are insignificant.)
    // Given an average of 1.8 bytes per instruction, this means
    // instruction boundary arrays are about a 75% overhead--tolerable.
    // (By using bytes, we get 33% savings over just shorts and ints.
    // Using both bytes and shorts gives 66% savings over just ints.)
    static final boolean shrinkMaps = true;

    private Object allocateInstructionMap(int[] insnMap, int mapLen) {
        int PClimit = getLength();
        if (shrinkMaps && PClimit <= Byte.MAX_VALUE - Byte.MIN_VALUE) {
            byte[] map = new byte[mapLen+1];
            for (int i = 0; i < mapLen; i++) {
                map[i] = (byte)(insnMap[i] + Byte.MIN_VALUE);
            }
            map[mapLen] = (byte)(PClimit + Byte.MIN_VALUE);
            return map;
        } else if (shrinkMaps && PClimit < Short.MAX_VALUE - Short.MIN_VALUE) {
            short[] map = new short[mapLen+1];
            for (int i = 0; i < mapLen; i++) {
                map[i] = (short)(insnMap[i] + Short.MIN_VALUE);
            }
            map[mapLen] = (short)(PClimit + Short.MIN_VALUE);
            return map;
        } else {
            int[] map = new int[mapLen+1];
            for (int i = 0; i < mapLen; i++) {
                map[i] = (int) insnMap[i];
            }
            map[mapLen] = (int) PClimit;
            return map;
        }
    }
    private int[] expandInstructionMap(Object map0) {
        int[] imap;
        if (map0 instanceof byte[]) {
            byte[] map = (byte[]) map0;
            imap = new int[map.length-1];
            for (int i = 0; i < imap.length; i++) {
                imap[i] = map[i] - Byte.MIN_VALUE;
            }
        } else if (map0 instanceof short[]) {
            short[] map = (short[]) map0;
            imap = new int[map.length-1];
            for (int i = 0; i < imap.length; i++) {
                imap[i] = map[i] - Byte.MIN_VALUE;
            }
        } else {
            int[] map = (int[]) map0;
            imap = new int[map.length-1];
            for (int i = 0; i < imap.length; i++) {
                imap[i] = map[i];
            }
        }
        return imap;
    }

    Object getInsnMap() {
        // Build a map of instruction boundaries.
        if (insnMap != null) {
            return insnMap;
        }
        int[] map = new int[getLength()];
        int fillp = 0;
        for (Instruction i = instructionAt(0); i != null; i = i.next()) {
            map[fillp++] = i.getPC();
        }
        // Make it byte[], short[], or int[] according to the max BCI.
        insnMap = allocateInstructionMap(map, fillp);
        //assert(assertBCICodingsOK());
        return insnMap;
    }

    /** Encode the given BCI as an instruction boundary number.
     *  For completeness, irregular (non-boundary) BCIs are
     *  encoded compactly immediately after the boundary numbers.
     *  This encoding is the identity mapping outside 0..length,
     *  and it is 1-1 everywhere.  All by itself this technique
     *  improved zipped rt.jar compression by 2.6%.
     */
    public int encodeBCI(int bci) {
        if (bci <= 0 || bci > getLength())  return bci;
        Object map0 = getInsnMap();
        int i, len;
        if (shrinkMaps && map0 instanceof byte[]) {
            byte[] map = (byte[]) map0;
            len = map.length;
            i = Arrays.binarySearch(map, (byte)(bci + Byte.MIN_VALUE));
        } else if (shrinkMaps && map0 instanceof short[]) {
            short[] map = (short[]) map0;
            len = map.length;
            i = Arrays.binarySearch(map, (short)(bci + Short.MIN_VALUE));
        } else {
            int[] map = (int[]) map0;
            len = map.length;
            i = Arrays.binarySearch(map, (int)bci);
        }
        assert(i != -1);
        assert(i != 0);
        assert(i != len);
        assert(i != -len-1);
        return (i >= 0) ? i : len + bci - (-i-1);
    }
    public int decodeBCI(int bciCode) {
        if (bciCode <= 0 || bciCode > getLength())  return bciCode;
        Object map0 = getInsnMap();
        int i, len;
        // len == map.length
        // If bciCode < len, result is map[bciCode], the common and fast case.
        // Otherwise, let map[i] be the smallest map[*] larger than bci.
        // Then, required by the return statement of encodeBCI:
        //   bciCode == len + bci - i
        // Thus:
        //   bci-i == bciCode-len
        //   map[i]-adj-i == bciCode-len ; adj in (0..map[i]-map[i-1])
        // We can solve this by searching for adjacent entries
        // map[i-1], map[i] such that:
        //   map[i-1]-(i-1) <= bciCode-len < map[i]-i
        // This can be approximated by searching map[i] for bciCode and then
        // linear searching backward.  Given the right i, we then have:
        //   bci == bciCode-len + i
        // This linear search is at its worst case for indexes in the beginning
        // of a large method, but it's not clear that this is a problem in
        // practice, since BCIs are usually on instruction boundaries.
        if (shrinkMaps && map0 instanceof byte[]) {
            byte[] map = (byte[]) map0;
            len = map.length;
            if (bciCode < len)
                return map[bciCode] - Byte.MIN_VALUE;
            i = Arrays.binarySearch(map, (byte)(bciCode + Byte.MIN_VALUE));
            if (i < 0)  i = -i-1;
            int key = bciCode-len + Byte.MIN_VALUE;
            for (;; i--) {
                if (map[i-1]-(i-1) <= key)  break;
            }
        } else if (shrinkMaps && map0 instanceof short[]) {
            short[] map = (short[]) map0;
            len = map.length;
            if (bciCode < len)
                return map[bciCode] - Short.MIN_VALUE;
            i = Arrays.binarySearch(map, (short)(bciCode + Short.MIN_VALUE));
            if (i < 0)  i = -i-1;
            int key = bciCode-len + Short.MIN_VALUE;
            for (;; i--) {
                if (map[i-1]-(i-1) <= key)  break;
            }
        } else {
            int[] map = (int[]) map0;
            len = map.length;
            if (bciCode < len)
                return map[bciCode];
            i = Arrays.binarySearch(map, (int)bciCode);
            if (i < 0)  i = -i-1;
            int key = bciCode-len;
            for (;; i--) {
                if (map[i-1]-(i-1) <= key)  break;
            }
        }
        return bciCode-len + i;
    }

    public void finishRefs(ConstantPool.Index ix) {
        if (fixups != null) {
            fixups.finishRefs(ix);
            fixups = null;
        }
        // Code attributes are finished in ClassWriter.writeAttributes.
    }

    Instruction instructionAt(int pc) {
        return Instruction.at(bytes, pc);
    }

    static boolean flagsRequireCode(int flags) {
        // A method's flags force it to have a Code attribute,
        // if the flags are neither native nor abstract.
        return (flags & (Modifier.NATIVE | Modifier.ABSTRACT)) == 0;
    }

    public String toString() {
        return m+".Code";
    }

    /// Fetching values from my own array.
    public int getInt(int pc)    { return Instruction.getInt(bytes, pc); }
    public int getShort(int pc)  { return Instruction.getShort(bytes, pc); }
    public int getByte(int pc)   { return Instruction.getByte(bytes, pc); }
    void setInt(int pc, int x)   { Instruction.setInt(bytes, pc, x); }
    void setShort(int pc, int x) { Instruction.setShort(bytes, pc, x); }
    void setByte(int pc, int x)  { Instruction.setByte(bytes, pc, x); }

/* TEST CODE ONLY
    private boolean assertBCICodingsOK() {
        boolean ok = true;
        int len = java.lang.reflect.Array.getLength(insnMap);
        int base = 0;
        if (insnMap.getClass().getComponentType() == Byte.TYPE)
            base = Byte.MIN_VALUE;
        if (insnMap.getClass().getComponentType() == Short.TYPE)
            base = Short.MIN_VALUE;
        for (int i = -1, imax = getLength()+1; i <= imax; i++) {
            int bci = i;
            int enc = Math.min(-999, bci-1);
            int dec = enc;
            try {
                enc = encodeBCI(bci);
                dec = decodeBCI(enc);
            } catch (RuntimeException ee) {
                ee.printStackTrace();
            }
            if (dec == bci) {
                //System.out.println("BCI="+bci+(enc<len?"":"   ")+" enc="+enc);
                continue;
            }
            if (ok) {
                for (int q = 0; q <= 1; q++) {
                    StringBuffer sb = new StringBuffer();
                    sb.append("bci "+(q==0?"map":"del")+"["+len+"] = {");
                    for (int j = 0; j < len; j++) {
                        int mapi = ((Number)java.lang.reflect.Array.get(insnMap, j)).intValue() - base;
                        mapi -= j*q;
                        sb.append(" "+mapi);
                    }
                    sb.append(" }");
                    System.out.println("*** "+sb);
                }
            }
            System.out.println("*** BCI="+bci+" enc="+enc+" dec="+dec);
            ok = false;
        }
        return ok;
    }
//*/
}


text:
namespace Alachisoft.NCache.Common.Protobuf
{
    [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"KeyValue")]
    public partial class KeyValue : global::ProtoBuf.IExtensible
    {
      public KeyValue() {}

    private string _key = "";
    [global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"key", DataFormat = global::ProtoBuf.DataFormat.Default)][global::System.ComponentModel.DefaultValue("")]
    public string key
    {
      get { return _key; }
      set { _key = value; }
    }
    private readonly global::System.Collections.Generic.List<Alachisoft.NCache.Common.Protobuf.ValueWithType> _value = new global::System.Collections.Generic.List<Alachisoft.NCache.Common.Protobuf.ValueWithType>();
    [global::ProtoBuf.ProtoMember(2, Name=@"value", DataFormat = global::ProtoBuf.DataFormat.Default)]
    public global::System.Collections.Generic.List<Alachisoft.NCache.Common.Protobuf.ValueWithType> value
    {
      get { return _value; }
    }

      private global::ProtoBuf.IExtension extensionObject;
      global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
        { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
    }

}


text:
package com.ctrip.zeus.service.app.impl;

import com.ctrip.zeus.model.Property;
import com.ctrip.zeus.service.app.AppService;
import com.ctrip.zeus.service.app.CriteriaNodeQuery;
import com.ctrip.zeus.service.app.QueryNode;
import com.ctrip.zeus.service.query.GroupCriteriaQuery;
import com.ctrip.zeus.service.query.SlbCriteriaQuery;
import com.ctrip.zeus.service.query.VirtualServerCriteriaQuery;
import com.ctrip.zeus.tag.PropertyService;
import com.ctrip.zeus.tag.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

;

/**
 * Created by fanqq on 2016/9/18.
 */
@Service("appCriteriaNodeQuery")
public class AppCriteriaNodeQuery implements CriteriaNodeQuery<String> {
    @Autowired
    AppService appService;
    @Resource
    GroupCriteriaQuery groupCriteriaQuery;
    @Resource
    VirtualServerCriteriaQuery virtualServerCriteriaQuery;
    @Resource
    SlbCriteriaQuery slbCriteriaQuery;
    @Resource
    TagService tagService;
    @Resource
    PropertyService propertyService;

    private final static String RESOURCE_TYPE = "app";

    @Override
    public boolean shouldSkip(QueryNode queryNode) {
        for (String key : queryNode.getQueryParams().keySet())
            switch (key) {
                case "groupId":
                case "groupName":
                case "appId":
                case "fuzzyName":
                case "vsId":
                case "vsName":
                case "domain":
                case "slbId":
                case "slbName":
                case "anyTag":
                case "unionTag":
                case "anyProp":
                case "unionProp":
                case "prop":
                case "joinProp":
                case "tags":
                case "joinTag":
                case "targetId":
                case "targetType":
                case "queryAll":
                    return false;
                default:
                    return true;
            }
        return true;
    }

    @Override
    public Set<String> query(Map<String, List<String>> query) throws Exception {
        Set<String> res = new HashSet<>();
        if (query.size() == 0) {
            return appService.getAllAppIds();
        }
        String firstKey = query.keySet().iterator().next();
        Long[] gids, vids, sids;
        List<String> tagNames;
        switch (firstKey) {
            case "groupId":
                gids = new Long[query.get(firstKey).size()];
                for (int i = 0; i < query.get(firstKey).size(); i++) {
                    gids[i] = Long.parseLong(query.get(firstKey).get(i));
                }
                return appService.getAppIdsByGroupIds(gids);
            case "groupName":
                gids = new Long[query.get(firstKey).size()];
                for (int i = 0; i < query.get(firstKey).size(); i++) {
                    gids[i] = groupCriteriaQuery.queryByName(query.get(firstKey).get(i));
                    i++;
                }
                return appService.getAppIdsByGroupIds(gids);
            case "appId":
                res.addAll(query.get(firstKey));
                return res;
            case "vsId":
                vids = new Long[query.get(firstKey).size()];
                for (int i = 0; i < query.get(firstKey).size(); i++) {
                    vids[i] = Long.parseLong(query.get(firstKey).get(i));
                }
                return appService.getAppIdsByVsIds(vids);
            case "vsName":
                vids = new Long[query.get(firstKey).size()];
                for (int i = 0; i < query.get(firstKey).size(); i++) {
                    vids[i] = virtualServerCriteriaQuery.queryByName(query.get(firstKey).get(i));
                }
                return appService.getAppIdsByVsIds(vids);
            case "domain":
                return appService.getAppIdsByDomains(query.get(firstKey).toArray(new String[]{}));
            case "slbId":
                sids = new Long[query.get(firstKey).size()];
                for (int i = 0; i < query.get(firstKey).size(); i++) {
                    sids[i] = Long.parseLong(query.get(firstKey).get(i));
                }
                return appService.getAppIdsBySlbIds(sids);
            case "slbName":
                sids = new Long[query.get(firstKey).size()];
                for (int i = 0; i < query.get(firstKey).size(); i++) {
                    sids[i] = slbCriteriaQuery.queryByName(query.get(firstKey).get(i));
                }
                return appService.getAppIdsBySlbIds(sids);
            case "anyTag":
            case "unionTag":
                tagNames = new ArrayList<>();
                for (String tag : query.get(firstKey)) {
                    tagNames.addAll(Arrays.asList(tag.split(",")));
                }
                Set<Long> tmp = tagService.unionQuery(tagNames, "app");
                Set<String> unionTagsApp = new HashSet<>();
                for (Long l : tmp) {
                    unionTagsApp.add(l.toString());
                }
                return unionTagsApp;
            case "anyProp":
            case "unionProp":
                List<Property> unionProps = getProperties(query.get(firstKey));
                Set<Long> t = propertyService.unionQuery(unionProps, RESOURCE_TYPE);
                Set<String> unionPropsApp = new HashSet<>();
                for (Long l : t) {
                    unionPropsApp.add(l.toString());
                }
                return unionPropsApp;
            case "prop":
            case "joinProp":
                List<Property> joinProps = getProperties(query.get(firstKey));
                Set<Long> jp = propertyService.joinQuery(joinProps, RESOURCE_TYPE);
                Set<String> joinPropsApp = new HashSet<>();
                for (Long l : jp) {
                    joinPropsApp.add(l.toString());
                }
                return joinPropsApp;
            case "tags":
            case "joinTag":
                tagNames = new ArrayList<>();
                for (String tag : query.get(firstKey)) {
                    tagNames.addAll(Arrays.asList(tag.split(",")));
                }
                Set<Long> tt = tagService.joinQuery(tagNames, "app");
                Set<String> joinTagsApp = new HashSet<>();
                for (Long l : tt) {
                    joinTagsApp.add(l.toString());
                }
                return joinTagsApp;
            case "queryAll":
                return appService.getAllAppIdsInSlb();
            case "fuzzyName":
            default:
                return res;
        }
    }

    public List<Property> getProperties(List<String> prop) {
        List<Property> properties = new ArrayList<>();
        for (String s : prop) {
            String[] tmp = s.split(",");
            for (String ss : tmp) {
                int ps = ss.trim().indexOf(':');
                if (ps == -1) continue;
                properties.add(new Property().setName(ss.substring(0, ps)).setValue(ss.substring(ps + 1)));
            }
        }
        return properties;
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: user
 * Date: 9/1/2015
 * Time: 11:55 AM
 */
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class System extends MY_Controller{
    public function index(){
        $this->load->library('table');
        $this->meta = 'home';

        $this->data['page_title'] = 'HOME Page';
        $this->data['site_url'] = site_url().'/';

        //$this->load->model('Common_model',"common");
        //$result = $this->common->retrieveAdministrator();
       //$this->data['admin_users']=$this->common->retrieveAdministrator();
        //json_encode($returnData);
       //$this->load->view('header_view',$this->data);
       //$this->display('_system/home_content',$this->data);
        $this->display('_system/home_content');
    }

}


text:
//
//  ZIKRouter+URLRouter.h
//  ZIKRouterDemo
//
//  Created by zuik on 2019/4/19.
//  Copyright © 2019 zuik. All rights reserved.
//

#import "ZIKServiceRouterType.h"
#import "ZIKServiceRoute.h"
#import "ZIKURLRouteResult.h"

NS_ASSUME_NONNULL_BEGIN

/// Key for data in router.configuration.userInfo
typedef NSString *ZIKURLRouteKey NS_EXTENSIBLE_STRING_ENUM;

/// Default is @"origin-url". You can change this key like: ZIKURLRouteKeyOriginURL = @"originURL"
FOUNDATION_EXTERN ZIKURLRouteKey ZIKURLRouteKeyOriginURL;
/// Default is @"action". You can change this key like: ZIKURLRouteKeyAction = @"action-name"
FOUNDATION_EXTERN ZIKURLRouteKey ZIKURLRouteKeyAction;

/**
 This provides basic URL router features. Call +enableDefaultURLRouteRule if you want to use this URL router.

 This uses the standard URL format: scheme://host/path/?query

 Features of this URL router:

 1. Save origin url to router.configuration.userInfo: userInfo = @{ZIKURLRouteKeyOriginURL: url}

 2. Use url as identifier to fetch destination router with `toIdentifier`. In url `scheme://host/path1/path2?k=v`, the identifier is `scheme://host/path1/path2`

 2. Get parameters from url to router.configuration.userInfo: app://loginView/?account=abc&pwd=123  => @{@"account": @"abc", @"pwd": @"123"}

 3. Process the userInfo before performing

 4. Perform action from the url after performing: app://loginView/?action=showAlert

 If you need more features, you can implement your custom URL rules by intercepting or hooking ZIKRouter's state control methods, or creating a parent URL router class overriding these methods for custom rules.
 */
@interface ZIKRouter (URLRouter)

/// Enable default URL router. You can implement your rules.
+ (void)enableDefaultURLRouteRule;

/// Get identifier and user info from url for fetching its router. Custom router parent class can override and process the url.
+ (ZIKURLRouteResult *)routeFromURL:(NSString *)url;

# pragma mark Subclass Override

/**
 Process the user info from url. This method is called before `performWithConfiguration:`. You can configure the configuration with the user info.

 If the router uses module config protocol (`makeDestinationWith` in configuration), you can get parameters from userInfo and call `configuration.makeDestinationWith`.
 */
- (void)processUserInfo:(NSDictionary *)userInfo fromURL:(NSURL *)url;

/// Perform `action` from the url (app://loginView/?action=showAlert) after performing ended. You can store a completion handler in userInfo and give some data back to the caller.
- (void)performAction:(NSString *)action userInfo:(NSDictionary *)userInfo fromURL:(NSURL *)url;

/// Do actions before `-performWithConfiguration:` for URL route rule.
- (void)beforePerformWithConfigurationFromURL:(ZIKPerformRouteConfiguration *)configuration NS_REQUIRES_SUPER;

/// Do actions after `-notifySuccessWithAction:` for URL route rule. The routeAction is ZIKRouteActionPerformRoute or ZIKRouteActionRemoveRoute.
- (void)afterSuccessActionFromURL:(ZIKRouteAction)routeAction NS_REQUIRES_SUPER;

@end

/**
 URL router to search and call service from url.

 It's easy to add other custom features with a custom URL router parent class.
 */
@interface ZIKServiceRouter<__covariant Destination, __covariant RouteConfig: ZIKPerformRouteConfiguration *> (URLRouter)

/**
 Register URL pattern, then you can get the router with `+[ZIKAnyServiceRouter routerForURL:]` or perform the url with `+[ZIKAnyServiceRouter performURL:]`.

 Supported patterns:

 app://service/path
 app://service/path?k=v&k2&v2
 app://service/path/:id
 app://service/path/:id/:number
 app://service/path/:id/:number?k=v&k2&v2
 app://service/path/:id/path/:number
 */
+ (void)registerURLPattern:(NSString *)pattern;

/// Perform route for the url. It will search router and get parameters with `+routeFromURL:`, then perform route.
+ (nullable ZIKServiceRouter<Destination, RouteConfig> *)performURL:(NSString *)url;

/// Perform route for the url with completion for current performing. It will search router and get parameters with `+routeFromURL:`, then perform route.
+ (nullable ZIKServiceRouter<Destination, RouteConfig> *)performURL:(NSString *)url completion:(void(^)(BOOL success, Destination _Nullable destination, ZIKRouteAction routeAction, NSError *_Nullable error))performerCompletion;

/// Get router for identifier from URL.
+ (nullable ZIKServiceRouterType<Destination, RouteConfig> *)routerForURL:(NSString *)url;

@end

@interface ZIKServiceRoute<__covariant Destination, __covariant RouteConfig: ZIKPerformRouteConfiguration *> (URLRouter)

/**
 Register URL pattern, then you can get the router with `+[ZIKAnyServiceRouter routerForURL:]` or perform the url with `+[ZIKAnyServiceRouter performURL:]`.

 Supported pattern samples:

 app://service/path
 app://service/path?k=v&k2&v2
 app://service/path/:id
 app://service/path/:id/:number
 app://service/path/:id/:number?k=v&k2&v2
 app://service/path/:id/path/:number

 @code
 [ZIKAnyServiceRoute
    makeRouteWithDestination:[LoginService class]
    makeDestination:^id<LoginServiceInput> _Nullable(ZIKPerformRouteConfig *config, __kindof ZIKRouter *router) {
        LoginService *destination = [[LoginService alloc] init];
        return destination;
 }]
 .prepareDestination(^(id<LoginServiceInput> destination, ZIKPerformRouteConfig *config, ZIKServiceRouter *router) {
    // Prepare the destination
 })
 .registerURLPattern(@"app://service/login/:uid")
 .processUserInfoFromURL(^(NSDictionary *userInfo, NSURL *url, ZIKPerformRouteConfig *config, ZIKServiceRouter *router) {

 })
 .performActionFromURL(^(NSString *action, NSDictionary *userInfo, NSURL *url, ZIKPerformRouteConfig *config, ZIKServiceRouter *router) {

 });
 @endcode
 */
@property (nonatomic, readonly) ZIKServiceRoute<Destination, RouteConfig> *(^registerURLPattern)(NSString *pattern);

/// Process the user info from url. This method is called before `performWithConfiguration:`. You can config the configuration with the user info.
@property (nonatomic, readonly) ZIKServiceRoute<Destination, RouteConfig> *(^processUserInfoFromURL)(void(^)(NSDictionary *userInfo, NSURL *url, RouteConfig config, ZIKServiceRouter *router));

/// Perform `action` from the url (app://loginView/?action=showAlert) after performing ended. You can store a completion handler in userInfo and give some data back to the caller.
@property (nonatomic, readonly) ZIKServiceRoute<Destination, RouteConfig> *(^performActionFromURL)(void(^)(NSString *action, NSDictionary *userInfo, NSURL *url, RouteConfig config, ZIKServiceRouter *router));

/// Do actions before `-performWithConfiguration:` for URL route rule.
@property (nonatomic, readonly) ZIKServiceRoute<Destination, RouteConfig> *(^beforePerformWithConfigurationFromURL)(void(^)(RouteConfig config, ZIKServiceRouter *router));

/// Do actions after `-notifySuccessWithAction:` for URL route rule. The routeAction is ZIKRouteActionPerformRoute or ZIKRouteActionRemoveRoute.
@property (nonatomic, readonly) ZIKServiceRoute<Destination, RouteConfig> *(^afterSuccessActionFromURL)(void(^)(ZIKRouteAction routeAction, RouteConfig config, ZIKServiceRouter *router));
@end

#pragma mark Interceptor

@interface ZIKRouter (Interceptor)
/**
 Inject interceptor for all routers before performing. You can process the configuration when implementing your custom URL router. See +enableDefaultURLRouteRule and +beforePerformWithConfigurationFromURL.

 @param handler A block invoked before `performWithConfiguration:`
 */
+ (void)interceptBeforePerformWithConfiguration:(void(^)(ZIKRouter *router, ZIKPerformRouteConfiguration *configuration))handler;

/// Inject interceptor for all routers after performing. Use this if you need to add action after the destination is instantiated.
+ (void)interceptAfterPerformWithConfiguration:(void(^)(ZIKRouter *router, ZIKPerformRouteConfiguration *configuration))handler;

/**
 Inject interceptor for all routers after success performing or removing. You can do some addtion custom actions when implementing your custom URL router. See +enableDefaultURLRouteRule and +afterSuccessActionFromURL.

 @note
 Success action may be called asynchronously (view router is notified performing success action after the view did finish displaying).
 Use `interceptAfterPerformWithConfiguration` instead if you need to add action immediately after the destination is instantiated.

 @param handler A block invoked after success performing or removing. The action is ZIKRouteActionPerformRoute or ZIKRouteActionRemoveRoute.
 */
+ (void)interceptAfterSuccessAction:(void(^)(ZIKRouter *router, ZIKRouteAction action))handler;

/// Inject interceptor for all routers after performing failed.
+ (void)interceptAfterEndPerformWithError:(void(^)(ZIKRouter *router, NSError *error))handler;

@end

NS_ASSUME_NONNULL_END


text:
package ru.obolensk.afff.beetle.protocol;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import lombok.Getter;

/**
 * Created by Afff on 04.09.2017.
 */
public enum ContentTransferEncoding {

    BASE64("base64"),
    QUOTED_PRINTABLE("quoted-printable"),
    _8BIT("8bit"),
    _7BIT("7bit"),
    BINARY("binary")
    ;

    @Nonnull @Getter
    private final String name;

    ContentTransferEncoding(@Nonnull final String name) {
        this.name = name;
    }

    @Nullable
    public static ContentTransferEncoding getByName(@Nullable final String name) {
        if (name == null) {
            return null;
        }
        for (ContentTransferEncoding enc : values()) {
            if (enc.getName().equalsIgnoreCase(name)) {
                return enc;
            }
        }
        return _7BIT; // default encoding
    }
}


text:
@interface LoadingLayer : CCLayer {

    CCLabelTTF* loadingLabel;
    CCSprite* black;
}

-(id)initWithText:(NSString*)text;
-(void) displayError:(NSString*)error;
-(void) setOpacity: (GLubyte) opacity;

@end


text:
DROP DATABASE IF EXISTS {schema} CASCADE;
CREATE DATABASE IF NOT EXISTS {schema};


text:
alter table lesson_builder_items add temp clob;
update lesson_builder_items set temp=description;
alter table lesson_builder_items drop column description;
alter table lesson_builder_items rename column temp to description;

--- alter table lesson_builder_items modify groups clob;
alter table lesson_builder_items add temp clob;
update lesson_builder_items set temp=groups;
alter table lesson_builder_items drop column groups;
alter table lesson_builder_items rename column temp to groups;

--- alter table lesson_builder_items modify ownerGroups clob;
alter table lesson_builder_items add temp clob;
update lesson_builder_items set temp=ownerGroups;
alter table lesson_builder_items drop column ownerGroups;
alter table lesson_builder_items rename column temp to ownerGroups;


text:
<?xml version="1.0"?>
<!--
 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.

 Copyright 1997-2010 Sun Microsystems, Inc. All rights reserved.

 The contents of this file are subject to the terms of either the GNU
 General Public License Version 2 only ("GPL") or the Common Development
 and Distribution License("CDDL") (collectively, the "License").  You
 may not use this file except in compliance with the License. You can obtain
 a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
 or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
 language governing permissions and limitations under the License.

 When distributing the software, include this License Header Notice in each
 file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
 Sun designates this particular file as subject to the "Classpath" exception
 as provided by Sun in the GPL Version 2 section of the License file that
 accompanied this code.  If applicable, add the following below the License
 Header, with the fields enclosed by brackets [] replaced by your own
 identifying information: "Portions Copyrighted [year]
 [name of copyright owner]"

 Contributor(s):

 If you wish your version of this file to be governed by only the CDDL or
 only the GPL Version 2, indicate your decision by adding "[Contributor]
 elects to include this software in this distribution under the [CDDL or GPL
 Version 2] license."  If you don't indicate a single choice of license, a
 recipient has the option to distribute your version of this file under
 either the CDDL, the GPL Version 2 or to extend the choice of license to
 its licensees as provided above.  However, if you add GPL Version 2 code
 and therefore, elected the GPL Version 2 license, then the option applies
 only if the new code is made subject to such option by the copyright
 holder.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.2.1</version>
  <packaging>jar</packaging>

  <name>JAXB API bundle for GlassFish V3</name>
  <url>https://jaxb.dev.java.net/</url>

  <licenses>
    <license>
      <name>CDDL 1.0</name>
      <url>https://glassfish.dev.java.net/public/CDDL+GPL.html</url>
      <distribution>repo</distribution>
    </license>
    <license>
      <name>GPL2 w/ CPE</name>
      <url>https://glassfish.dev.java.net/public/CDDL+GPL.html</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <scm>
    <url>https://jaxb2-sources.dev.java.net/source/browse/jaxb2-sources/jaxb-ri/</url>
  </scm>

  <description>
    JAXB (JSR 222) API
  </description>

  <dependencies>
    <dependency>
      <groupId>javax.xml.stream</groupId>
      <artifactId>stax-api</artifactId>
      <version>1.0-2</version>
    </dependency>
    <dependency>
      <groupId>javax.activation</groupId>
      <artifactId>activation</artifactId>
      <version>1.1</version>
    </dependency>
  </dependencies>

  <repositories>
    <repository>
      <id>m2.dev.java.net</id>
      <url>http://download.java.net/maven/2</url>
      <layout>default</layout>
    </repository>
  </repositories>

</project>


text:
package pl.pronux.sokker.data.sql.dto;

import java.sql.ResultSet;
import java.sql.SQLException;

import pl.pronux.sokker.model.Date;
import pl.pronux.sokker.model.SokkerDate;
import pl.pronux.sokker.model.Training;

public class TrainingDto extends Training {
	private ResultSet rs;
	public TrainingDto(ResultSet rs) {
		this.rs = rs;
	}

	public Training getTraining() throws SQLException {
		this.setId(rs.getInt("id_training"));
		this.setDate(new Date(rs.getLong("millis")));
		this.setType(rs.getInt("type"));
		this.setFormation(rs.getInt("formation"));
		this.setNote(rs.getString("note"));
		this.getDate().setSokkerDate(new SokkerDate(rs.getInt("day"), rs.getInt("week")));
		this.setReported(rs.getBoolean("reported"));
		return this;
	}
}


text:
using std::string;
using std::map;
using std::make_pair;

class MyCHttpResponseDecoder
{
public:
	MyCHttpResponseDecoder(){}
	int Decode(const char *pBuffer, int nLen);

	int GetHttpCode(){return m_nHttpCode;}
	string GetBody(){return m_strBody;}
	string GetHeadValue(const string &strHead);
	void Dump();
	map<string,string> GetHeadValue();

private:
	int m_nHttpCode;
	string m_strBody;
	map<string,string> m_mapHeadValue;

};

#endif


text:
var Router = Ember.Router.extend(); // ensure we don't share routes between all Router instances

Router.map(function () {
  this.route('component-test');
  this.route('helper-test');
  // this.resource('posts', function() {
  //   this.route('new');
  // });
  this.route('about');

  this.resource('questions', function() {
    this.resource("question", { path: "/:question_id"});
  });

  this.route('ask-question');
  this.route('sign-in');
});

export default
Router;


text:
package storage

import "cloud.google.com/go/bigquery/internal"

func init() {
	versionClient = internal.Version
}


text:
package org.apache.flink.runtime.io.network.partition;

import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.core.memory.MemorySegmentFactory;
import org.apache.flink.runtime.io.disk.FileChannelManager;
import org.apache.flink.runtime.io.disk.FileChannelManagerImpl;
import org.apache.flink.runtime.io.network.api.EndOfPartitionEvent;
import org.apache.flink.runtime.io.network.api.serialization.EventSerializer;
import org.apache.flink.runtime.io.network.buffer.Buffer;
import org.apache.flink.runtime.io.network.buffer.BufferPool;
import org.apache.flink.runtime.io.network.buffer.NetworkBuffer;
import org.apache.flink.runtime.io.network.buffer.NetworkBufferPool;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
import java.util.Random;

import static org.apache.flink.runtime.io.network.buffer.Buffer.DataType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

/**
 * Tests for {@link SortMergeResultPartition}.
 */
public class SortMergeResultPartitionTest {

	private static final BufferAvailabilityListener listener = new NoOpBufferAvailablityListener();

	private static final int bufferSize = 1024;

	private static final int totalBuffers = 1000;

	private FileChannelManager fileChannelManager;

	private NetworkBufferPool globalPool;

	@Rule
	public final TemporaryFolder tmpFolder = new TemporaryFolder();

	@Before
	public void setUp() {
		fileChannelManager = new FileChannelManagerImpl(
			new String[] {tmpFolder.getRoot().getPath()}, "testing");
		globalPool = new NetworkBufferPool(totalBuffers, bufferSize);
	}

	@After
	public void shutdown() throws Exception {
		fileChannelManager.close();
		globalPool.destroy();
	}

	@Test
	public void testWriteAndRead() throws Exception {
		int numSubpartitions = 10;
		int numBuffers = 100;
		int numRecords = 1000;
		Random random = new Random();

		BufferPool bufferPool = globalPool.createBufferPool(numBuffers, numBuffers);
		SortMergeResultPartition partition = createSortMergedPartition(numSubpartitions, bufferPool);

		Queue<PartitionSortedBufferTest.DataAndType>[] dataWritten = new Queue[numSubpartitions];
		Queue<Buffer>[] buffersRead = new Queue[numSubpartitions];
		for (int i = 0; i < numSubpartitions; ++i) {
			dataWritten[i] = new ArrayDeque<>();
			buffersRead[i] = new ArrayDeque<>();
		}

		int[] numBytesWritten = new int[numSubpartitions];
		int[] numBytesRead = new int[numSubpartitions];
		Arrays.fill(numBytesWritten, 0);
		Arrays.fill(numBytesRead, 0);

		for (int i = 0; i < numRecords; ++i) {
			byte[] data  = new byte[random.nextInt(2 * bufferSize) + 1];
			random.nextBytes(data);
			ByteBuffer record = ByteBuffer.wrap(data);
			boolean isBroadCast = random.nextBoolean();

			if (isBroadCast) {
				partition.broadcastRecord(record);
				for (int subpartition = 0; subpartition < numSubpartitions; ++subpartition) {
					recordDataWritten(
						record, dataWritten, subpartition, numBytesWritten, DataType.DATA_BUFFER);
				}
			} else {
				int subpartition = random.nextInt(numSubpartitions);
				partition.emitRecord(record, subpartition);
				recordDataWritten(
					record, dataWritten, subpartition, numBytesWritten, DataType.DATA_BUFFER);
			}
		}

		partition.finish();
		partition.close();
		for (int subpartition = 0; subpartition < numSubpartitions; ++subpartition) {
			ByteBuffer record = EventSerializer.toSerializedEvent(EndOfPartitionEvent.INSTANCE);
			recordDataWritten(
				record, dataWritten, subpartition, numBytesWritten, DataType.EVENT_BUFFER);
		}

		for (int subpartition = 0; subpartition < numSubpartitions; ++subpartition) {
			ResultSubpartitionView view = partition.createSubpartitionView(subpartition, listener);
			while (view.isAvailable(Integer.MAX_VALUE)) {
				Buffer buffer = view.getNextBuffer().buffer();
				int numBytes = buffer.readableBytes();
				numBytesRead[subpartition] += numBytes;

				MemorySegment segment = MemorySegmentFactory.allocateUnpooledSegment(numBytes);
				segment.put(0, buffer.getNioBufferReadable(), numBytes);
				buffersRead[subpartition].add(
					new NetworkBuffer(segment, (buf) -> {}, buffer.getDataType(), numBytes));
				buffer.recycleBuffer();
			}
			view.releaseAllResources();
		}

		PartitionSortedBufferTest.checkWriteReadResult(
			numSubpartitions, numBytesWritten, numBytesRead, dataWritten, buffersRead);
	}

	private void recordDataWritten(
			ByteBuffer record,
			Queue<PartitionSortedBufferTest.DataAndType>[] dataWritten,
			int subpartition,
			int[] numBytesWritten,
			Buffer.DataType dataType) {
		record.rewind();
		dataWritten[subpartition].add(
			new PartitionSortedBufferTest.DataAndType(record, dataType));
		numBytesWritten[subpartition] += record.remaining();
	}

	@Test
	public void testWriteLargeRecord() throws Exception {
		int numBuffers = 100;
		BufferPool bufferPool = globalPool.createBufferPool(numBuffers, numBuffers);
		SortMergeResultPartition partition = createSortMergedPartition(10, bufferPool);

		byte[] dataWritten  = new byte[bufferSize * numBuffers];
		Random random = new Random();
		random.nextBytes(dataWritten);
		ByteBuffer recordWritten = ByteBuffer.wrap(dataWritten);
		partition.emitRecord(recordWritten, 0);
		assertEquals(0, bufferPool.bestEffortGetNumOfUsedBuffers());

		partition.finish();
		partition.close();

		ResultSubpartitionView view = partition.createSubpartitionView(0, listener);
		ByteBuffer recordRead = ByteBuffer.allocate(bufferSize * numBuffers);
		while (view.isAvailable(Integer.MAX_VALUE)) {
			Buffer buffer = view.getNextBuffer().buffer();
			if (buffer.isBuffer()) {
				recordRead.put(buffer.getNioBufferReadable());
			}
			buffer.recycleBuffer();
		}
		view.releaseAllResources();

		recordWritten.rewind();
		recordRead.flip();
		assertEquals(recordWritten, recordRead);
	}

	@Test
	public void testFlush() throws Exception {
		int numBuffers = 10;
		BufferPool bufferPool = globalPool.createBufferPool(numBuffers, numBuffers);
		SortMergeResultPartition partition = createSortMergedPartition(10, bufferPool);

		partition.emitRecord(ByteBuffer.allocate(bufferSize), 0);
		partition.emitRecord(ByteBuffer.allocate(bufferSize), 1);
		assertEquals(3, bufferPool.bestEffortGetNumOfUsedBuffers());

		partition.flush(0);
		assertEquals(0, bufferPool.bestEffortGetNumOfUsedBuffers());

		partition.emitRecord(ByteBuffer.allocate(bufferSize), 2);
		partition.emitRecord(ByteBuffer.allocate(bufferSize), 3);
		assertEquals(3, bufferPool.bestEffortGetNumOfUsedBuffers());

		partition.flushAll();
		assertEquals(0, bufferPool.bestEffortGetNumOfUsedBuffers());

		assertNull(partition.getResultFile());
		partition.finish();
		assertEquals(3, partition.getResultFile().getNumRegions());

		partition.close();
	}

	@Test(expected = IllegalStateException.class)
	public void testReleaseWhileWriting() throws Exception {
		int numBuffers = 10;
		BufferPool bufferPool = globalPool.createBufferPool(numBuffers, numBuffers);
		SortMergeResultPartition partition = createSortMergedPartition(10, bufferPool);

		partition.emitRecord(ByteBuffer.allocate(bufferSize * (numBuffers - 1)), 0);
		partition.emitRecord(ByteBuffer.allocate(bufferSize * (numBuffers - 1)), 1);

		partition.emitRecord(ByteBuffer.allocate(bufferSize), 2);
		assertNull(partition.getResultFile());
		assertEquals(2, fileChannelManager.getPaths()[0].list().length);

		partition.release();
		try {
			partition.emitRecord(ByteBuffer.allocate(bufferSize * numBuffers), 2);
		} catch (IllegalStateException exception) {
			assertEquals(0, fileChannelManager.getPaths()[0].list().length);

			throw exception;
		}

		fail("Should throw ClosedChannelException.");
	}

	@Test
	public void testReleaseWhileReading() throws Exception {
		int numBuffers = 10;
		BufferPool bufferPool = globalPool.createBufferPool(numBuffers, numBuffers);
		SortMergeResultPartition partition = createSortMergedPartition(10, bufferPool);

		partition.emitRecord(ByteBuffer.allocate(bufferSize * (numBuffers - 1)), 0);
		partition.emitRecord(ByteBuffer.allocate(bufferSize * (numBuffers - 1)), 1);
		partition.finish();
		partition.close();

		assertEquals(2, partition.getResultFile().getNumRegions());
		assertEquals(2, fileChannelManager.getPaths()[0].list().length);

		ResultSubpartitionView view = partition.createSubpartitionView(0, listener);
		view.getNextBuffer().buffer().recycleBuffer();
		partition.release();

		assertEquals(2, partition.getResultFile().getNumRegions());
		assertEquals(2, fileChannelManager.getPaths()[0].list().length);

		while (view.isAvailable(Integer.MAX_VALUE)) {
			view.getNextBuffer().buffer().recycleBuffer();
		}
		view.releaseAllResources();

		assertNull(partition.getResultFile());
		assertEquals(0, fileChannelManager.getPaths()[0].list().length);
	}

	@Test
	public void testCloseReleasesAllBuffers() throws Exception {
		int numBuffers = 100;
		BufferPool bufferPool = globalPool.createBufferPool(numBuffers, numBuffers);
		SortMergeResultPartition partition = createSortMergedPartition(10, bufferPool);

		partition.emitRecord(ByteBuffer.allocate(bufferSize * (numBuffers - 1)), 5);
		assertEquals(numBuffers, bufferPool.bestEffortGetNumOfUsedBuffers());

		partition.close();
		assertTrue(bufferPool.isDestroyed());
		assertEquals(totalBuffers, globalPool.getNumberOfAvailableMemorySegments());
	}

	@Test(expected = IllegalStateException.class)
	public void testReadUnfinishedPartition() throws Exception {
		BufferPool bufferPool = globalPool.createBufferPool(10, 10);
		try {
			SortMergeResultPartition partition = createSortMergedPartition(10, bufferPool);
			partition.createSubpartitionView(0, listener);
		} finally {
			bufferPool.lazyDestroy();
		}
	}

	@Test(expected = IllegalStateException.class)
	public void testReadReleasedPartition() throws Exception {
		BufferPool bufferPool = globalPool.createBufferPool(10, 10);
		try {
			SortMergeResultPartition partition = createSortMergedPartition(10, bufferPool);
			partition.finish();
			partition.release();
			partition.createSubpartitionView(0, listener);
		} finally {
			bufferPool.lazyDestroy();
		}
	}

	private SortMergeResultPartition createSortMergedPartition(
			int numSubpartitions,
			BufferPool bufferPool) throws IOException {
		SortMergeResultPartition sortMergedResultPartition = new SortMergeResultPartition(
			"SortMergedResultPartitionTest",
			0,
			new ResultPartitionID(),
			ResultPartitionType.BLOCKING,
			numSubpartitions,
			numSubpartitions,
			bufferSize,
			new ResultPartitionManager(),
			fileChannelManager.createChannel().getPath(),
			null,
			() -> bufferPool);
		sortMergedResultPartition.setup();
		return sortMergedResultPartition;
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Template · Bootstrap</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet" media="screen">

    <link href="{{ url_for('static', filename='css/bootstrap-responsive.min.css') }}" rel="stylesheet" media="screen">

What does the Chinese Say

Search

What's this?

Github

what's this

What does Chinese say allows you to search among Chinese news and social media (weibo).

It uses Baidu translation API, so you can search in English and view results (machine-translated) in English.

A disclaimer

This service uses machine translating. You know, it's unrelialble. The translated content may not reflect the original ideal or intent of the content's author. I, or anybody who set up this server, will be not responsible for the translated content and any potential consequences following that. Use the data with discretion, and always read the source material with someone who understands Chinese before publishing any derived work.

Also, What appears in the results is not THE EXACT VIEWPOINT of 1.3 billion people in China, nor is its any collective representation. As you can see from the data source section, data come from Baidu search engine. They have their own *data gathering

Then why do you make this?

When I came to US, I started to read news about China through Associated Press, Foreign Policy, and websites such as Tea Leaf Nation. I found that people here are really curious about opinions of Chinese people (especially Chinese "Netizen") in some topics. However, it is funny to see that most of the information people here can get about China come from several "China experts", who delicately tailor the information - not too spicy, not too weak.

Therefore I made this tool, which allows you to "talk" directly to Chinese people (?, remember the disclaimer?). You can also continue the dailogue by following the links it provided in the search results.

Who is this made for?

Journalists. They can explore the topics they are interested in and use the result as a start point of follow-up research. Information from Chinese news media, blogs, forums, and Weibo (Chinese twitter) helps journalists to find new opportunities and achieve a balanced view.

Media Hackers. This tool provide a JSON interface, with which hackers can remix the data with something else. Want to see a comparision of views between Chinese and Americans? Want to see how attention of Chinese people on specific topic shifted? Code it out!

Just for fun. What do people say about Obama? What do Chinese say about a company? Find your question and get answers from 1.3b people who lives thousands of miles away.

Your data source?

Ok, it comes to tech details.
All the data came from Baidu news search engine. Including news, forum posts, blogs, and tweets.

I use Baidu Translation API to translate the keywords and results. This uses an API key, so when it's out of quota you can apply a new one at http://developer.baidu.com/

Here a description of each source (in my opinion):

News: mainstream, well-written, well-censored news from various Chinese news websites. Notice that most Chinese websites are not allowed to publish their own news. So the news you see here are probably come from paper-based media.

Blogs: Chinese blogs, mostly hosted on blog platforms such as Sina or Netease. Though they are not as popular as "micro-blogging (Twitter)" now.

Forum: Forum posts across websites. Note that Baidu Tieba (One of the most widely used forum in China) is not included in the results. Remember the disclaimer?

Weibo: "Chinese Twitter". The user base is declining but still considerable, and more heavily used than all other sources by native Chinese. Where do people go? A new private media called "Wechat".

Wang Yu @ Center for Civic Media 2014