text:
<?php
	require_once('include/config.php');
	require_once('include/BBCodeToHTML.php');
	require_once('include/database.php');
	require_once('include/user.php');
	require_once('include/strings.php');

	// Begin session if we don't have one currently, and assign a sane default username if it's a new session
	if (!isset ($_SESSION))
		session_start();
	if(!$_SESSION['username']) {
		$user['Name'] = "Unknown";
	}

	function get_distance_from_base($x, $y) {
		return round(hypot($x, $y));
	}

	function get_distance_from_point($x1, $y1, $x2, $y2) {
		return round(hypot($x1 - $x2, $y1 - $y2));
	}

	function get_level_number($level) {
		$num = 0;
		if($level > 0) $num = 1;
		if($level > 3) $num = 2;
		if($level > 7) $num = 3;
		if($level > 15) $num = 4;
		if($level > 31) $num = 5;
		if($level > 63) $num = 6;
		if($level > 127) $num = 7;
		if($level > 256) $num = 8;
		if($level > 500) $num = 9;
		if($level > 1000) $num = 10;
		return $num;
	}

	function display_location_info() {
		global $user, $UNREADHERE, $LOCBOARDSHERE, $PLAYERSHERE;
		$newlevel = get_level_number(get_distance_from_base($user['LocX'], $user['LocY']));
		if(get_high_message($newlevel) > get_last_read($user['userid'], $newlevel)) {
			echo $UNREADHERE;
		}
		if($user['LocX'] != 0 || $user['LocY'] != 0) {
			if(get_boards_at_loc($user['LocX'], $user['LocY'])) {
				echo $LOCBOARDSHERE;
			}
		}
		$users = get_users_at_loc($user['LocX'], $user['LocY']);
		if($users) {
			echo $PLAYERSHERE;
			echo '
';
			foreach($users as $u) {
				echo $u['Name']."
";
			}
			echo '
';
		}
	}

	function display_main() {
		global $user, $BN_MOTD, $MOTDHEADER, $ACTIVITYHEADER;
		$motds = get_messages($BN_MOTD, time() - (1440 * 60), 5);
		if($motds) {
			printf($MOTDHEADER, (sizeof($motds) > 1 ? "s" : ""));
			echo '
';
			//echo '';
			echo '
';
			foreach($motds as $m) {
				printf('
%s	%s
', mydate($m['timesent']), $m['msgid'], censor_text($m['subject']));
			}
			echo '
';
			echo '
';
		}
		$acts = get_events(0, 5);
		if($acts) {
			echo $ACTIVITYHEADER;
			echo '
';
			echo '
';
			foreach($acts as $a) {
				printf("
%s	%s
", mydate($a['Timesent']), censor_text(stripslashes($a['Event'])));
			}
			echo '
';
			echo '
';
		}
// TODO: Maybe this can be done somehow using background images..
// TODO: Test in IE7 and Firefox
		echo '';
	}

	function get_exhaust() {
		global $user;
		if($user['userid'] == 0) return;
		$sql = sprintf("SELECT * FROM `exhaust` WHERE userid=%d", $user['userid']);
		$exh = get_query($sql);
		//print_r($exh);
		//printf("get_exhaust(): exhaust=%s
", $exh['exhaust']);
		return $exh['exhaust'];
	}

	function save_exhaust() {
		global $user, $_SESSION;
		if($user['userid'] == 0) return;
		if(!$_SESSION['movethrottle']) return;
		//printf("save_exhaust(): exhaust=%s
", $_SESSION['movethrottle']);

		$sql = sprintf("UPDATE users SET lastcmdtime=%d WHERE userid=%d", time(), $user['userid']);
		mysql_query($sql);
		$x = get_exhaust();
		if(isset($x)) {
			$sql = sprintf("UPDATE exhaust SET exhaust=%d WHERE userid=%d", $_SESSION['movethrottle'], $user['userid']);
			$res = mysql_query($sql);
			//echo "res=$res
";
			//echo mysql_error()."
";
		} else {
			$sql = sprintf("INSERT INTO exhaust (userid,exhaust) VALUES (%d,%d)", $user['userid'], $_SESSION['movethrottle']);
			$res = mysql_query($sql);
			//echo "res=$res
";
			//echo mysql_error()."
";
		}
	}

	function same_sector($x1, $y1, $x2, $y2) {
		if(get_sector($x1, $y1) == get_sector($x2, $y2)) return 1;
		return 0;
	}

	function valid_target($u1, $u2) {
		if(!same_sector($u1['LocX'], $u1['LocY'], $u2['LocX'], $u2['LocY']))
			return "$u2[Name] does not seem to be in this sector.
";
		if($u1['Level'] <= $u2['Level'])
			return "$u2[Name] has too high of an access level for this to work.
";
		return 1;
	}

	function get_sector($x, $y) {
		//echo "get_sector($x, $y)
";
		if($x == 0 && $y == 0) return 0;
		if($x >= 0) {
			if($y >= 0) return 1;
			else return 4;
		} else {
			if($y >= 0) return 2;
			else return 3;
		}
	}

	function allocate_credits() {
		global $user;

		if(!$user['lastcmdtime'] && $user['userid'] > 0) // TODO: remove this after everyone who was a current user when it was added has logged in to update properly
			$user['lastcmdtime'] = time() - ( (60 * 60) * 24);

		if($user['lastcmdtime'] && $user['Level'] < 256 && $user['userid'] > 0) {
			if($user['Level'] < 25) $maxrest = 50 + $user['Level'];
			else $maxrest = 25 + ($user['Level'] * 2);
			//$maxrest = (25 + $user['Level']);
			//$user['lastcmdtime'] -= ((60 * 60) * 5);
			$hours = (((time() - $user['lastcmdtime']) / 60) / 60);
			//$hours = round(round((time() - $user['lastcmdtime']) + 6000 / 60) / 60);
			if($hours >= 1) {
				$_SESSION['movethrottle'] -= $hours * 5;
				//echo "Daily Allocation: $maxrest
";
				//echo "Hours since last command: $hours
";
				//printf("Allocation per hour: %f
", (float)($maxrest / 24));

				$add = round( ($maxrest / 24) * $hours);
				if($add > 0) {
					$pool = QueryStaminaPool();
					if($add > $pool) {
						$add = $pool;
					}
					if($add > 0) {
						printf($ALLOCATEDSTAMINA, $add);
						AdjustStaminaPool(-$add);
						$user['Stamina'] += $add;
					}
				}
			}
		}
	}

	ob_start();

	// If the session the web browser sent us claimed to be logged in and have a username,
	// then let's try and re-load that user in case anything good or bad happened to us since the last
	// time we loaded a page
	if($user['Name'] != "Unknown") {
		$user = get_user($_SESSION['username']);
		//echo "user=$user
";
	}

	// Get user's Group Name
	if($user['GroupID'] > 0) {
		$user['Group'] = load_group($user['GroupID']);
	}
	if(!$user['Group'] || $user['Group'] == "")
		$user['Group']['Name'] = "None";
	//else
//		$user['Group'] = $user['Group']['Name'];

	//print_r("group=$user[Group]
");
	// TODO: Since the save functions should now be able to deal with numeric vs. string values, we may want to remove this level conversion
	if(!$user['Level'])
		$user['Level'] = "0";
	// give guests a tiny bit of power
	if(!isset($user['Stamina']))
		$user['Stamina'] = "10";

	// Get the command name as entered in the "Command" db table, as well as it's cost and version
	$filename = basename($_SERVER['SCRIPT_NAME']);
	//echo "filename=$filename";
	if($_GET['cmd']) {
		$sql = sprintf("SELECT DISTINCT Command, max(Version) AS V, max(Cost) AS Cost, Program FROM commands WHERE (Level <= %d AND Program='%s' AND Command='%s') GROUP BY Command",
				$user['Level'], $filename, $_GET['cmd']);
	} else {
		$sql = sprintf("SELECT DISTINCT Command, max(Version) AS V, max(Cost) AS Cost, Program FROM commands WHERE (Level <= %d AND Program='%s') GROUP BY Command",
				$user['Level'], $filename);
	}
	$command = get_query($sql);
	//print_r($command);
	$warezname = $command['Command'];
	$version = $command['V'];
	//$command['Cost'] = $command['C'];
	//$version = $command['max(Version)'];
	//$command['Cost'] = $command['max(Cost)'];
	//print_r($command);
	if($command && $command['Cost'] > 0 && !$_GET['deletetell']) { // TODO: this last part could cause us some headaches?
		// TODO: perhaps play a CHEATER! message if deletetell fails?
		if($_SESSION['command'] != "$warezname $version") {
			//echo "prev command=".$_SESSION['command']."
";
			$_SESSION['command'] = "$warezname $version";
			$user['Stamina'] -= $command['Cost'];
			echo "Cost: $command[Cost]
";
		} // It will be the command's responsibility to clear the command when it is done executing, so pages that have confirmation and such won't double drain credits
	}

	require_once('maintenance.php');

	// If a player goes over their stamina limit, return it to the Stamina Pool
	$maxstam = 100 + ($user['Level'] * 50); // TODO: Make it (level + 1) * 50 .. make sure change goes to finger too
	if($user['Stamina'] > $maxstam) {
		$newstam = $user['Stamina'] - $maxstam;
		$user['Stamina'] = $maxstam;
		printf($OVERLOADEDSTAMINA, $newstam);

		AdjustStaminaPool($newstam);
	}

	// If time limits are configured on, then set the end time, otherwise it doesn't need to be set..
	// There's no reason -not- to set it here, just that the original unimplementation of time limits just commented this section out..
	// TODO: As said in the config.php, someone should bother testing time limits, if they'd like that feature.
	if($USETIMELIMITS && $_SESSION['LoginTime']) {
		$minutes = 15 + ($user['Level'] * 3);
		//$minutes = (12 * ($user['Level']+1));
		if($minutes > 120) $minutes = 120;
		$endtime = $_SESSION['LoginTime'] + ($minutes * 60);
	}

	if($user['userid']) {
		// If we have a valid user, let's check their messages and stuff

		// if we've been sent a delete tell command, let's do that before dealing with anything else.
		// TODO: In the future, this may have to short circuit any other instructions coming in, as it could allow free commands to get through, if the cost system is changed from the way it
		// was originally implemented.
		if($_GET['deletetell']) {
			delete_tell($user['userid'], $_GET['deletetell']);
		}
		$sql = sprintf("SELECT * FROM tells WHERE (toid=%d)", $user['userid']);

		$tells = get_query_array($sql); // use userid so it gets there even if names change
		if($tells) {
			echo $TELLHEADER;
			echo '
';
			foreach($tells as $tell) {
				echo '';
				//echo date("m-d-y h:m:t", $tell['timesent']);
				echo mydate(date("Y-m-d H:m:s", $tell['timesent']));
				echo ' ';
				if(!$tell['autodelete']) {
					printf(' Delete ', $_SERVER['PHP_SELF'], $tell['id']);
				}
				echo $tell['message'];
				echo '';
				if($tell['fromname'])
					echo '
'.get_user_menu($tell['fromname']).'
';
				echo '
';
			}
			echo '
';
			echo '
';
		}
		$sql = "DELETE FROM tells WHERE (toid=".$user['userid']." AND autodelete=1)";
		mysql_query($sql);
		$exhaust = get_exhaust();
		if($exhaust)
			$_SESSION['movethrottle'] = $exhaust;
		if($_SESSION['movethrottle'] > 0) {
			$_SESSION['movethrottle']--;
		} else if ($_SESSION['movethrottle'] < 0) {
			$_SESSION['movethrottle'] = 0;
		}
	} else {
		$user['Group'] = "None";
	}
	//echo "exhaust=$_SESSION[movethrottle]
";

	allocate_credits();

	$dist = get_distance_from_base($user['LocX'], $user['LocY']);
	if($dist > $user['Level']) {
		echo $NOACCESSTOLOC;
		$user['LocX'] = $user['HomeX'];
		$user['LocY'] = $user['HomeY'];
		$a = abs($user['LocX']);
		$b = abs($user['LocY']);
		$dist = round(sqrt(pow($a, 2) + pow($b, 2)));
		if($dist > $user['Level']) {
			echo $NOACCESSTOHOME;
			$user['LocX'] = 0;
			$user['LocY'] = 0;
		}
	}
	error_log(date("Y-m-d H:i:s").": $user[Name]: ".$_SERVER['PHP_SELF']."
\r\nPOST=".print_r($_POST, 1)."
\r\nuser=".print_r($user, 1), 3, "activity.log");

	if( (!loggedin() && rand(0,4) == 0) || rand(0,20) == 0) {
		// TODO: Move this into the templates thing
		echo get_random_quote()."
";
	}
	//print_r($_SESSION);
	//echo "
";
?>


text:
thread_num=4

# use current machine as master, if an ConnectException occurs in slave.log,
# try to set master_host=127.0.0.1
master_host=$(hostname)

# if you run more than one training tasks on the same host at the same time,
# different tasks must have different ports!
master_port=65534
echo "master host:${master_host}, master port:${master_port}"

# model name
model_name=gbdt
echo "model name:${model_name}"

# config
properties_path="demo/gbdt/binary_classification/local_gbdt.conf"
echo "config:${properties_path}"

# transform
transform="false"
transform_script_path="bin/transform.py"

echo "kill old task..."
kill $(cat master_${master_port}.pid)
kill $(cat slave_${master_port}.pid)

echo "start master..."
nohup java -server -Xmx2000m -classpath .:lib/*:config -Dlog4j.configuration=file:config/log4j_master.properties com.fenbi.mp4j.comm.CommMaster 1 "${master_port}" >> log/master.log 2>&1 & echo $! > master_${master_port}.pid

echo "start slave..."
nohup java -server -Xmx60000m -XX:-OmitStackTraceInFastThrow -classpath .:lib/*:config -Dlog4j.configuration=file:config/log4j_slave.properties com.fenbi.ytklearn.worker.LocalTrainWorker  \
    "${model_name}" "${properties_path}" "${transform_script_path}" "${transform}" user "${master_host}" "${master_port}" "${thread_num}" >> log/slave.log 2>&1 & echo $! > slave_${master_port}.pid
wait

redpajama_set_name: RedPajamaGithub


text:
APP_ROOT = File.expand_path('../../..', __FILE__)
APP_ENV = ENV['RACK_ENV'] ||= "development"

ENV['BUNDLE_GEMFILE'] = File.join(APP_ROOT, 'Gemfile')
require 'bundler/setup'
Bundler.require(:default, APP_ENV)

require 'yaml'
require 'uri'
require 'date'

Dir[File.join(APP_ROOT, "lib/**/*.rb")].each {|path| require path}
require File.join(APP_ROOT, 'app')

SocketChat.setup_database

Faye::Logging.log_level = :info
Server = Faye::RackAdapter.new(SocketChat::App,
  :mount => '/faye',
  :timeout => 30,
  :extensions => [ChatHistory.new, ActivityNotifier.new]
)


text:
package org.apache.streams.osgi.components.activitysubscriber;

import org.codehaus.jackson.annotate.JsonTypeInfo;

import java.util.ArrayList;
import java.util.List;

@JsonTypeInfo(use= JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class")
public interface ActivityStreamsSubscription {

    public void setFilters(List<String> filters);
    public List<String> getFilters();

    public List<ActivityStreamsSubscriptionOutput> getActivityStreamsSubscriptionOutputs();
    public void setActivityStreamsSubscriptionOutputs(List<ActivityStreamsSubscriptionOutput> outputs);

    public String getAuthToken();
    public void setAuthToken(String token);

}


text:
# Shopify Pipeline - A modern pipeline for Shopify theme development

---

**Important disclaimers:**

This project is still in beta.

We are also looking for maintainers and contributors as Dynamo as a group **will not be continuing active maintainance and features development** for [Shopify Pipeline](https://github.com/DynamoMTL/shopify-pipeline) (and it's scaffolder [create-shopify-pipeline](https://github.com/DynamoMTL/create-shopify-pipeline)). -- See [#108](https://github.com/DynamoMTL/shopify-pipeline/issues/108).

---

Shopify Pipeline aims at giving you access to a better, smoother and more modern workflow for building, testing and deploying Shopify themes and websites.

It is built on top of [Webpack 2](https://webpack.github.io/) and uses tools such as [ESlint](http://eslint.org/), [Babel](https://babeljs.io/), [Sass](http://sass-lang.com/), [SVGO](https://github.com/svg/svgo), [Theme Kit](https://shopify.github.io/themekit/), [Stylelint](https://stylelint.io/) and [Jest](https://facebook.github.io/jest/) to help you count on features like ES6+ support, module bundling, hot module reloading, automatic watch-and-deploy, JS unit testing, asset fingerprinting, and much more!

So excited you wanna get started right away? [Boom](#getting-started)

---

**Table of Contents**
- [Supported Features](#supported-features)
- [Project Structure](#project-structure)
- [Getting Started](#getting-started)
- [Using the tool](#using-the-tool)
- [Customizing your Workflow](#customizing-your-workflow)
- [Caveats](#caveats)
- [Roadmap](#roadmap)
- [Contribtions](#contributions)
- [Thanks](#thanks)
- [Made by Dynamo](#made-by-dynamo)
---

## Supported Features
**Module Bundling and Treeshaking**: We are using Webpack 2 to bundle and optimize all your Javascript modules, which also has the added benefit of allowing dead code removal (treeshaking).

**ES6+ Support**: Webpack and Babel are used to support the ES6+ standards in an effective way via [babel-preset-env](https://github.com/babel/babel-preset-env).

**Asset Optimization and Fingerprinting**: Webpack is used to skim through all your templates and find the assets and dependencies needed for the build, running those through its process and spitting out optimized and fingerprinted assets in the build folder. It will also map those assets by rendering the correct path in the templates. **Note** that paths should be relative to the file your asset's being referenced from.

**SVG Store**: We are supporting the use of SVG Store out of the box using [webpack-svgstore-plugin](https://github.com/mrsum/webpack-svgstore-plugin). You can jump to this [section](#6-svg-store) to learn how to use it in Shopify Pipeline.

**Hot Module Reloading**: Once you start developing your application, the webpack-dev-server will allow you to inject modified JS modules directly in your Shopify development theme without reloading the page. Please refer to [this section](#caveats) if you wanna know how to configure your code to be HMR-compliant.

**Sourcemaps**: We added support for JS and Sass sourcemaps when you are in development, as well as [hidden sourcemaps in production mode](https://webpack.js.org/configuration/devtool/#for-production).

**JS Code Linting**: ESlint is used by default to lint your JS files as part of the build process. You can add your own `.eslintrc` in your project and Shopify Pipeline will pick it up. Or you can rely on the one that is included by default [here](.eslintrc).

**Sass Support and Linting**: Shopify Pipeline supports CSS and Sass by default. We also added support for Sass `@imports` for better style modularity. Stylelint support is also [in the works](#roadmap).

**JS Unit Testing**: We added a default unit testing setup, using Jest, so that you don't have to. You can jump to [the testing section](#8-specs) to learn more about this.

**Pipeline Customization and Augmentation**: We are providing you with base Webpack configs for the development and production environments, but you can extend them to add your own specific solutions to the pipeline. More on this here [link].

**Multiple Environment Support**: Shopify Pipeline uses a YAML file similar to [Theme Kit's `config.yml`](https://shopify.github.io/themekit/configuration/) file to allow you to have different credentials for your development and production environments.

**Effective Development Flow**: On top of using HMR, we also use Webpack to render paths to your assets that point to your `localhost`, allowing you to instantly see the changes on the Shopify server without having to upload files to the server or reload the page. When that strategy is not available, Shopify Pipeline takes care of uploading the right files and reloading the page for you.

**Safe Watch and Deploy**: Shopify Pipeline has a set of flags and warnings baked in to prevent you from pushing code to the `main` live theme (unless you explicitely want to). This minimizes the risks of deploying changes to the live site while in local development.

## Getting Started
Shopify Pipeline is composed of two main pieces:

1. This current application, which is the CLI and what is used to build your theme,
2. A project scaffolder to help you get started quickly on development.

### Create a new project
To start a new project, you will need to install and run the `create-shopify-pipeline` scaffolder, as explained here: https://github.com/DynamoMTL/create-shopify-pipeline#getting-started.

In a gist, with `yarn`, creating a new project is as easy as follows:
```
yarn create shopify-pipeline name-of-your-project
```

### Setup your Shopify environments
Once you have bootstraped your development app, you will need to setup your `shopify.yml` file with the right information provided by Shopify.

We will defer to Shopify's documentation on how to give API access and where to find the `api_key`,`password`, `theme_id`, `store` necessary for the CLI to interact with the Shopify servers: https://github.com/Shopify/slate-cli/blob/master/store-configuration.md.

## Project Structure
Once Shopify Pipeline has created the scaffolding of your project, it will have the following structure:

```
├── package.json [0]
├── .eslintrc [1]
├── config
│   └── shopify.yml [2]
│   └── webpack.dev.conf.js [3]
│   └── webpack.prod.conf.js [3]
└── src
    ├── assets
    │   ├── fonts
    │   ├── images
    │   ├── js [4]
    │   └── sass [5]
    │   └── svg [6]
    │   └── vendors [9]
    ├── config [7]
    │   ├── settings_data.json
    │   └── settings_schema.json
    ├── layout
    │   └── theme.liquid [7]
    ├── locales [7]
    │   └── en.default.json
    ├── sections [7]
    ├── snippets [7]
    ├── specs [8]
    └── templates [7]
        ├── blog.liquid
        ├── cart.liquid
        ├── collection.liquid
        ├── gift_card.liquid
        ├── index.liquid
        ├── page.liquid
        └── product.liquid
```

#### [0] Packages

`package.json`

The package file will be generated for you by Shopify Pipeline upon project creation.

We are so nice that we will also generate npm/yarn scripts for you to be able to use Shopify Pipeline's CLI easily from the terminal (e.g. `yarn serve`).

#### [1] ESlint Config

`.eslintrc` (optional)

If you add a ESlint config file on the root of your app, Shopify Pipeline will use that file for the eslint-loader.

#### [2] Shopify Config

`config/shopify.yml`

Shopify Pipeline will use this config file to setup the development and production flow. It is mimicking what is already being used by [Theme Kit](https://shopify.github.io/themekit/configuration/) and will work accordingly.

#### [3] Webpack Config

`config/webpack.[dev|prod].conf.js`

If Shopify Pipeline finds one or both of those files in the `config` folder, it will merge them with the default Webpack config files everytime you start the webpack-dev-server or that you build your project. This allows you to add loaders and plugins to augment the base toolset provided to you by Shopify Pipeline.

We are using [webpack-merge](https://www.npmjs.com/package/webpack-merge) to elegantly achieve this goal.

Of course, with great power comes great responsibility: please use this feature wisely as to not override the core functionalities of Shopify Pipeline.

#### [4] JS Files

`src/assets/js`

This folder will contain all your JS modules. An `index.js` must be present, as it will act as the entry point for your JS application.

You can use ES6/ES2015's standard, which incidently allows you to require your modules with the `import` syntax:
```
import { contains } from 'lodash'
import Foo from './modules/foo'
// const Bar = require('./modules/bar') is also available if that's your jam!
```

#### [5] Sass and CSS Files

`src/assets/sass`

Shopify Pipeline fully supports `.css`, `.scss` and `.sass` files and their syntax, including `@import`.

You **must** include your style index file at the top of your `index.js` file for Webpack to be able to load your styles into its build process, as such:

```
import '../sass/index.scss';
```

Note that you should not use liquid templating in your styles as Shopify Pipeline will take care of generating the right URLs and paths depending on the environment.

If you intend to use [Stylelint support](#roadmap) (coming soon!), also note that you must rely on `.scss` files and style.

#### [6] SVG Store

`src/assets/svg`

If you want to use the [SVG Store technique](https://css-tricks.com/svg-sprites-use-better-icon-fonts/), we added its support out of the box with the help of [webpack-svgstore-plugin](https://github.com/mrsum/webpack-svgstore-plugin).

Here are the steps necessary to use it:
1. Place all the necessary Svg files inside the `svg` folder
2. Somewhere in your JS application, you need to create this variable and assignment:
    ```
    var __svg__ = { path: '../svg/**/*.svg', name: 'logos.svg' };
    ```
    This will tell the SVG Store plugin [that it needs to generate the sprite file](https://github.com/mrsum/webpack-svgstore-plugin#2-put-function-mark-at-your-chunk).

**Note** that the plugin will add a `icon-` prefix to your file name as the `id` of the symbol in the sprite. There is no way to change this at the moment. Given that this is less than an ideal integration, we will look for better ways to generate the store [in the future](#roadmap).

Also **note** that, if you want to reference the sprite file in your liquid templates, [you will need to make sure that the url is not parsed by Webpack](#how-to-prevent-webpack-from-parsing-some-liquid-methods-and-filters). You can do so by wrapping the liquid curly brackets in a single quote and the name of the sprite in double quotes, like so:
```
<div data-some-attribute='{{ "logos.svg" | asset_url }}'></div>
```

#### [7] Shopify Required

`src/config`, `src/layout/theme.liquid`, `src/locales`, `src/sections`, `src/snippets`, `src/templates/*.liquid`

The aforementioned [files and folders are required by Shopify](https://help.shopify.com/themes/development/templates) for any given theme.

Shopify Pipeline only adds the bare minimum files required to be able to deploy a theme to your Shopify server without any errors. You can start building your application from this baseline.

#### [8] Specs

`src/specs`

The way it is set up, Jest will look for files named `*.spec.js` or `*.test.js` in the `specs` folder of your application to run the test suite.

You can nest and organize your specs in subfolders as long as the filenames follow this convention.

The `test` command is just a proxy for launching `jest` and as such we recommend you read [their documentation](https://facebook.github.io/jest/docs/getting-started.html) to learn more about the framework and how to use it.

#### [9] Vendors

`src/assets/vendors`

Sometimes you need the ability to upload unmodified files to the Shopify server. This is where the `vendors` directory comes in. Any files placed inside this directory will be uploaded, as-is, to Shopify. To reference them in your `.liquid` files, you'll want to [ensure Webpack doesn't parse your liquid filters](how-to-prevent-webpack-from-parsing-some-liquid-methods-and-filters) when referencing those files.

This special directory can be useful for files added by plugins you've installed, or for when you need to construct an image URL in Liquid.

## Using the Tool

### Not Global
There are [various compelling reasons](https://www.smashingmagazine.com/2016/01/issue-with-global-node-npm-packages/) why we should not rely on global npm packages. And as such, we advise you to not do so when using Shopify Pipeline.

To have access to Shopify Pipeline's CLI commands, you then have two options:
- In the terminal, append the path to your local package to the command like so: `./node_modules/.bin/shopify-pipeline command`
- In the `package.json` file, you can create yarn/npm scripts to proxy the commands, like this:
    ```
    scripts: {
      xxx: 'shopify-pipeline command',
      ...
    }

    // In the terminal:
    // yarn xxx --someflag
    ```
    Note that Shopify Pipeline will create those for you on project creation.

### API Commands
Here are the available API commands for Shopify Pipeline:

`serve [-- --env=development]`
  - Starts the webpack-dev-server, deploys a first build to Shopify and launches the theme preview site
  - Will serve assets on `https://localhost:8080`
  - (Optional) You can pass it one of the `shopify.yml`'s environments as a flag; it will default to `development` environment

`build [-- [--deploy] [--env=development]]`
  - Builds a production-ready version of the theme and outputs it to the `dist` folder
  - (Optional) You can pass it a `deploy` flag, which will push the compiled theme to Shopify after the build
  - (Optional) You can pass it an environment as a flag; it will default to `development` environment

`test`
  - Will start Jest testing, targeting files living in `/specs` and following the `*.{test|spec}.js` globbing
  - Note that we are supporting ES6 with a `babel-jest` integration

## Customizing your Workflow
(More to come)

## Caveats
### How to generate a local SSH certificate
In order to be able to use local assets in Shopify's environment, you will need to allow your browser to use `https://localhost:8080` as a safe URL.

To do so, you must:
1. Launch the webpack-dev-server; it will launch the Shopify's theme preview, but will not accept assets coming from `localhost`
2. Navigate to `https://localhost:8080` in the same browser you intend to use for development
3. Discard the warning and proceed to the URL; you will see an error page, but it's cool
4. Go back to the Shopify's theme preview and you should now have local assets working on the distant server

### How to deal with Shopify Apps that inject code in templates and files in your theme
(More to come)

### You should not rely on liquid helpers in your JS and CSS files
(More to come)

### How to prevent Webpack from parsing some liquid methods and filters
Webpack will loop through your liquid files and parse the liquid helpers to compile the relevant assets. For example, if it detects a `<img src="{{ 'lamp.png' | assert_url }}>"` in a file, it will grab that `lamp.png` image and pass it through the build process.

If, for some reason, one file should not be picked up by Webpack, you can escape this process by using double quotes inside of the liquid expression, like so `<img src='{{ "lamp.png" | assert_url }}>'`. When using this escape hatch, you should not include a relative link to your asset but instead simply write it's name.

### How to make HMR-compliant code
To be able to use some sweet sweet HMR in your flow, you either need to use a framework that supports it (e.g. React, Vue, etc.) or modify your JS modules to be HMR-compatible. More info on how to do that [here](http://andrewhfarmer.com/webpack-hmr-tutorial/#part-2-code-changes).

## Roadmap
- Add support for Stylelint (with customizable rules)
- Find a better solution for SVG Store support
- Show a better landing page when proceeding to `https://localhost:8080`

## Contributions
(More to come)

## License
MIT, see [LICENSE](LICENSE) for details.

## Thanks
We would like to specifically thank the following projects, for the inspiration and help in regards to the creation of Shopify Pipeline:
- [create-react-app](https://github.com/facebookincubator/create-react-app)
- [Shopify](https://github.com/Shopify), [Themekit](https://github.com/Shopify/node-themekit) and [Slate](https://shopify.github.io/slate/)

## Made by Dynamo
This tool was created with love by [Dynamo](http://godynamo.com/), a Montreal-based full-service digital design studio.

The goal behind Shopify Pipeline is to alleviate some of the downsides of working within the Shopify ecosystem and bring forward some of the nice features you get when building custom e-commerce websites outside of it.

We hope that it will help you be more efficient in your work and achieve your goals!

Cheers,

[The Dynamo Team](http://godynamo.com/en/about)


text:
import sys

py2k = sys.version_info < (3, 0)
py3k = sys.version_info >= (3, 0)
py32 = sys.version_info >= (3, 2)
py27 = sys.version_info >= (2, 7)
jython = sys.platform.startswith('java')
win32 = sys.platform.startswith('win')

try:
    import threading
except ImportError:
    import dummy_threading as threading

if py3k: # pragma: no cover
    string_types = str,
    text_type = str
    string_type = str

    if py32:
        callable = callable
    else:
        def callable(fn):
            return hasattr(fn, '__call__')

    def u(s):
        return s

    def ue(s):
        return s

    import configparser
    import io
    import _thread as thread
else:
    string_types = basestring,
    text_type = unicode
    string_type = str

    def u(s):
        return unicode(s, "utf-8")

    def ue(s):
        return unicode(s, "unicode_escape")

    import ConfigParser as configparser
    import StringIO as io

    callable = callable
    import thread

if py3k or jython:
    import pickle
else:
    import cPickle as pickle

def timedelta_total_seconds(td):
    if py27:
        return td.total_seconds()
    else:
        return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 1e6) / 1e6


text:
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Polly;
using Polly.Retry;
using JobStreet.AdPostingApi.Client;
using JobStreet.AdPostingApi.Client.Models;
using JobStreet.AdPostingApi.Client.Models.JobStreet;
using JobStreet.AdPostingApi.Client.Resources;
using Environment = JobStreet.AdPostingApi.Client.Environment;

namespace JobStreet.AdPostingApi.SampleConsumer
{
    public class Program
    {
        private static string CreationId = "Sample Consumer " + Guid.NewGuid();
        private const string AdvertiserId = "10110000001";
        private const int BaseRetryIntervalSeconds = 2;
        private const string ClientId = "client1"; //"ClientId"; //"client1";
        private const string ClientSecret = "secret"; //"ClientSecret"; //"secret";

        private static readonly RetryPolicy TransientErrorRetryPolicy = Policy
            .Handle<RequestException>(ex => ex.StatusCode >= 500)
            .WaitAndRetryAsync(5, attempt => TimeSpan.FromSeconds(BaseRetryIntervalSeconds * Math.Pow(2, attempt)),
                    (exception, waitInterval) =>
                    {
                        Console.WriteLine($"Unexpected error, waiting {waitInterval.TotalSeconds} seconds before retrying.");
                    });

        public static void Main()
        {
            Task.Run(ExampleAsync).Wait();
        }

        public static async Task ExampleAsync()
        {
            using (IAdPostingApiClient client = new AdPostingApiClient(ClientId, ClientSecret, Environment.Integration))
            {
                // Create a new advertisement
                Advertisement advertisement = GetExampleAdvertisementToCreate();
                AdvertisementResource createdAdvertisement = await CreateAdvertisementExampleAsync(advertisement, client);

                if (createdAdvertisement != null)
                {
                    // Retrieve advertisement
                    AdvertisementResource advertisementResource = await GetAdvertisementExampleAsync(createdAdvertisement.Id, client);

                    // Modify details on the advertisement
                    advertisementResource.JobTitle = "Senior Dude";
                    advertisementResource.CreationId = CreationId;
                    AdvertisementResource updatedAdvertisementResource = await UpdateAdvertisementExampleAsync(advertisementResource);

                    // Expire the advertisement
                    await ExpireAdvertisementExampleAsync(updatedAdvertisementResource);
                }

                // Get paged summaries of created advertisements
                AdvertisementSummaryPageResource advertisementSummaryPage = await GetAllAdvertisementsExampleAsync(client);
                while (!advertisementSummaryPage.Eof)
                {
                    advertisementSummaryPage = await GetAllAdvertisementsNextPageExampleAsync(advertisementSummaryPage);
                }
            }

            Console.WriteLine("Finished Example. Press a key to exit.");
            Console.ReadKey(true);
        }

        public static async Task<AdvertisementResource> CreateAdvertisementExampleAsync(Advertisement advertisementToCreate, IAdPostingApiClient client)
        {
            AdvertisementResource advertisementResource = null;
            try
            {
                await TransientErrorRetryPolicy.ExecuteAsync(async () => advertisementResource = await client.CreateAdvertisementAsync(advertisementToCreate));
                Console.WriteLine($"Created Advertisement:\n{JsonConvert.SerializeObject(advertisementResource, Formatting.Indented)}");
            }
            catch (RequestException ex)
            {
                LogException(ex);
            }

            return advertisementResource;
        }

        public static async Task<AdvertisementResource> UpdateAdvertisementExampleAsync(AdvertisementResource advertisement)
        {
            AdvertisementResource advertisementResource = null;
            try
            {
                await TransientErrorRetryPolicy.ExecuteAsync(async () => advertisementResource = await advertisement.SaveAsync());
                Console.WriteLine($"Updated Advertisement:\n{JsonConvert.SerializeObject(advertisementResource, Formatting.Indented)}");
            }
            catch (RequestException ex)
            {
                LogException(ex);
            }

            return advertisementResource;
        }

        private static async Task<AdvertisementResource> ExpireAdvertisementExampleAsync(AdvertisementResource advertisement)
        {
            AdvertisementResource advertisementResource = null;
            try
            {
                await TransientErrorRetryPolicy.ExecuteAsync(async () => advertisementResource = await advertisement.ExpireAsync());
                Console.WriteLine($"Expired Advertisement:\n{JsonConvert.SerializeObject(advertisementResource, Formatting.Indented)}");
            }
            catch (RequestException ex)
            {
                LogException(ex);
            }

            return advertisementResource;
        }

        private static async Task<AdvertisementResource> GetAdvertisementExampleAsync(Guid advertisementId, IAdPostingApiClient client)
        {
            AdvertisementResource advertisementResource = null;
            try
            {
                await TransientErrorRetryPolicy.ExecuteAsync(async () => advertisementResource = await client.GetAdvertisementAsync(advertisementId));
                Console.WriteLine($"Retrieved Advertisement:\n{JsonConvert.SerializeObject(advertisementResource, Formatting.Indented)}");
            }
            catch (RequestException ex)
            {
                LogException(ex);
            }

            return advertisementResource;
        }

        private static async Task<AdvertisementSummaryPageResource> GetAllAdvertisementsExampleAsync(IAdPostingApiClient client)
        {
            AdvertisementSummaryPageResource advertisementSummaryPage = null;
            try
            {
                await TransientErrorRetryPolicy.ExecuteAsync(async () => advertisementSummaryPage = await client.GetAllAdvertisementsAsync());
                Console.WriteLine($"Retrieve all advertisements:{JsonConvert.SerializeObject(advertisementSummaryPage, Formatting.Indented)}");
            }
            catch (RequestException ex)
            {
                LogException(ex);
            }

            return advertisementSummaryPage;
        }

        private static async Task<AdvertisementSummaryPageResource> GetAllAdvertisementsNextPageExampleAsync(AdvertisementSummaryPageResource summaryPage)
        {
            try
            {
                await TransientErrorRetryPolicy.ExecuteAsync(async () => summaryPage = await summaryPage.NextPageAsync());
                Console.WriteLine($"Next page of advertisements:{JsonConvert.SerializeObject(summaryPage, Formatting.Indented)}");
            }
            catch (RequestException ex)
            {
                LogException(ex);
            }

            return summaryPage;
        }

        private static Advertisement GetExampleAdvertisementToCreate()
        {
            return new Advertisement
            {
                ThirdParties = new ThirdParties { AdvertiserId = AdvertiserId },
                JobTitle = "Senior Front-end Developer",
                EmploymentType = new int?[] { 1 },
                Salary = new SalaryModel
                {
                    Minimum = 1000,
                    Maximum = 3000,
                    CurrencyCode = 1,
                    Display = true
                },
                Location = new LocationModel
                {
                    Id = new int?[] { 50300, 70100 },
                    Area = ""
                },
                JobDescription = "Responsibility You know have knowledge of Laravel and AngularJS. Understand requirement and delivery quality products.",
                JobSpecialization = 191,
                JobRole = 1333,
                EducationLevel = new int?[] { 4, 5 },
                FieldOfStudy = new int?[] { 8 },
                PositionLevel = 16,
                YearOfExperience = 2,
                Site = new int?[] { 1, 2 },
                Language = new int?[] { 1, 2, 3 },
                PostingDate = new DateTime(2017, 9, 30),
                StandOutBullet = new string[] { "Good", "Best", "Awesome" },
                ApplicationFormUrl = "www.seekasia.com",
                ApplicationEmail = "klang@seekasia.com",
                CompanyOverview = "",
                JobReference = "",
                Skill = new string[] { "php", ".net", "java" },
                BlindAd = false,
                TemplateId = 12345,
                CreationId = CreationId
            };
        }

        private static void LogException(RequestException ex, [CallerMemberName] string callerName = "")
        {
            Console.WriteLine($"Error (Status Code: {ex.StatusCode}) while performing `{callerName}`.\r\nMessage: {ex.Message}");

            switch (ex.GetType().Name)
            {
                case nameof(CreationIdAlreadyExistsException):
                    Uri advertisementLink = ((CreationIdAlreadyExistsException)ex).AdvertisementLink;
                    Console.WriteLine($"Advertisement Link:{advertisementLink}");
                    break;

                case nameof(ValidationException):
                    PrintAdvertisementErrors(((ValidationException)ex).Errors);
                    break;

                case nameof(UnauthorizedException):
                    PrintAdvertisementErrors(((UnauthorizedException)ex).Errors);
                    break;

                case nameof(TooManyRequestsException):
                    TimeSpan? retryAfter = ((TooManyRequestsException)ex).RetryAfter;
                    if (retryAfter != null)
                    {
                        Console.WriteLine($"A Retry-After period of {retryAfter.Value.TotalSeconds} seconds is provided.");
                    }
                    break;

                case nameof(RequestException):
                    LogException(ex.ResponseContentType, ex.ResponseContent);
                    break;
            }
        }

        private static void LogException(string responseContentType, string responseContent)
        {
            if (responseContentType != null)
            {
                Console.WriteLine($"Response Content-Type: {responseContentType}");
            }
            if (responseContent != null)
            {
                Console.WriteLine($"Response Content: {responseContent}");
            }
        }

        private static void PrintAdvertisementErrors(AdvertisementError[] errors)
        {
            if (errors.Length < 1) return;

            Console.WriteLine("Advertisement Errors:");

            int counter = 1;
            foreach (AdvertisementError error in errors)
            {
                Console.WriteLine($"  [{counter:##}] Field: '{error.Field}' Code: '{error.Code}' Message: '{error.Message}'");
                counter++;
            }
        }
    }
}


text:
package scaffold.platform.fileexplorer;

import java.io.*;

/**
 * Utility class for directory and file manipulation.
 */
public class FileUtility
{
    private static String extension;
    private static String startChars;

    public static void createDirectory(String path) throws IOException {
        int index1 = path.indexOf("\\");
        int index2 = path.indexOf("/");

        int index = 0;
        File dir;

        while (index1 > -1 || index2 > -1) {
            if (index1 > -1) {
                if (index2 < 0 || index1 < index2) {
                    dir = new File(path.substring(0,index1));
                    if (!dir.exists()) {
                        dir.mkdir();
                    }
                    index = index1 + 2; // +2 for double backslash
                    if (index > path.length() - 1) {
                        break;
                    }

                    index1 = path.indexOf("\\", index);
                    continue;
                }
            }

            dir = new File(path.substring(0,index2));
            if (!dir.exists()) {
                dir.mkdir();
            }
            index = index2 + 1;
            if (index > path.length() - 1) {
                break;
            }

            index2 = path.indexOf("/", index);
            continue;
        }
    }

    public static String extractFileName(String path) {
        int index = path.lastIndexOf("\\");

        if (index > -1) {
            if (index < path.length() - 1) {
                return path.substring(index+1);
            } else {
                return "";
            }
        }

        index = path.lastIndexOf("/");

        if (index > -1) {
            if (index < path.length() - 1) {
                return path.substring(index+1);
            } else {
                return "";
            }
        }

        return path;
    }

    public static String extractDir(String path) {
        int index1 = path.lastIndexOf("\\");
        int index2 = path.lastIndexOf("/");
        int index = (index1 > index2) ? index1 : index2;

        if (index > 0) {
            return path.substring(0,index+1);
        } else {
            return "";
        }
    }

    public static void deleteFilesInDirectory(File dir, boolean recurse) {
        File[] files = dir.listFiles();

        for (File f: files) {
            if (f.isDirectory()) {
                if (recurse) {
                    deleteFilesInDirectory(f, recurse);
                    f.delete();
                }
            } else {
                f.delete();
            }
        }
    }

    //extension must start with '.'
    public static File[] getFilesByExt( String dirName, String ext){
    	File dir = new File(dirName);
        extension = ext;

    	return dir.listFiles(new FilenameFilter() {
            @Override
    	    public boolean accept(File dir, String fileName) {
    	        return fileName.endsWith(extension);
            }
    	});
    }

    public static File[] getFilesStartingWith( String dirName, String startsWith){
    	File dir = new File(dirName);
        startChars = startsWith;

    	return dir.listFiles(new FilenameFilter() {
            @Override
    	    public boolean accept(File dir, String fileName) {
    	        return fileName.startsWith(startChars);
            }
    	});
    }

    public static void writeFile(String fileName, String textToSave) throws IOException {
        if (fileName == null)
            throw new IOException( "filename is null");
        if (textToSave == null)
            throw new IOException("textToSave is null");

        FileWriter fw     = new FileWriter(fileName);
        BufferedWriter bw = new BufferedWriter(fw);

        fw.write( textToSave );

        bw.close();
        fw.close();
    }

    public static String readFile(String fileName) throws IOException {
        if (fileName == null)
            throw new IOException( "filename is null");

        FileReader fr = new FileReader(fileName);
        BufferedReader br = new BufferedReader(fr);
        StringBuilder buffer = new StringBuilder();

        String nextLine;
        while ((nextLine = br.readLine()) != null)
            buffer.append(nextLine).append("\n");

        //Remove final newline
        if (buffer.length() > 0 && buffer.charAt(buffer.length()-1) == '\n')
            buffer.deleteCharAt( buffer.length() - 1 );

        br.close();
        fr.close();

        return buffer.toString();
    }
}


text:
package com.yamin.reader.activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.geometerplus.android.fbreader.libraryService.BookCollectionShadow;
import org.geometerplus.fbreader.fbreader.FBReaderApp;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;

import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.yamin.reader.R;
import com.yamin.reader.adapter.FileListAdapter;
import com.yamin.reader.database.DbDataOperation;
import com.yamin.reader.database.DbTags;
import com.yamin.reader.model.Book;
import com.yamin.reader.model.FileItem;
import com.yamin.reader.utils.ToolUtils;

public class FileSearchResultActivity extends Activity {
	private ListView resultLV;
	private TextView resultTV;
	private ArrayList<String> searchitems;
	private ArrayList<FileItem> items;
	private FileListAdapter adapter;
	private FileItem item;
	private PopupWindow mPopuwindow;
	private LinearLayout openFileBtn;
	private LinearLayout shelfFileBtn;
	private LinearLayout favoriteFileBtn;
	private FBReaderApp myFBReaderApp;
	private ContentResolver resolver;
	SearchManager searchManager;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		ActionBar bar = this.getActionBar();
		bar.setDisplayShowTitleEnabled(true);
		bar.setDisplayHomeAsUpEnabled(true);
		bar.setDisplayShowHomeEnabled(true);
		bar.setTitle(R.string.book_file_manager);
		bar.setSubtitle("搜索结果");
		setContentView(R.layout.book_search_result);
		resolver=getContentResolver();
		myFBReaderApp = (FBReaderApp) FBReaderApp.Instance();
		if (myFBReaderApp == null) {
			myFBReaderApp = new FBReaderApp(FileSearchResultActivity.this,
					new BookCollectionShadow());
		}
		getCollection().bindToService(this, null);
		resultLV=(ListView)findViewById(R.id.bookSearchList);
		resultTV=(TextView)findViewById(R.id.bookResultNum);
		searchitems=new ArrayList<String>();
		items=new ArrayList<FileItem>();
		Intent i=this.getIntent();
		if(i!=null){
			searchitems=i.getStringArrayListExtra("SEARCH_LIST");

		if(searchitems!=null&&searchitems.size()>0){
			for(int j=0;j<searchitems.size();j++){
				String path=searchitems.get(j);
				File f=new File(path);
				item=new FileItem(f.getName(),ToolUtils.getIcon(FileSearchResultActivity.this, f.getName())
						,f.getPath()
						,ToolUtils.FormetFileSize(f.length()));
				items.add(item);
			}
		}
		adapter=new FileListAdapter(FileSearchResultActivity.this, items);
		resultLV.setAdapter(adapter);
		resultTV.setText("共为您搜索到"+items.size()+"个文件");
		resultTV.setTextColor(this.getResources().getColor(R.color.holo_blue_light));
		resultLV.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int position, long arg3) {

				 showPopupWindow(view,position);
			}
		});
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.bookfile_menu, menu);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
			SearchView searchView = (SearchView) menu.findItem(
					R.id.menu_file_search).getActionView();
			searchView.setSearchableInfo(searchManager
					.getSearchableInfo(getComponentName()));
			searchView.setIconifiedByDefault(true);
		}
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_file_search:
			onSearchRequested();
			return true;
		case android.R.id.home:
			Intent i = new Intent(this, FileBrowserActivity.class);
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
			return true;
		default:
			return false;
		}
	}
	/*
	 * @弹出POPU MENU
	 */
	public void showPopupWindow(View v,int position) {
		final int p=position;
		LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(
				R.layout.file_item_menu, null);
		mPopuwindow = new PopupWindow(layout,
				ViewGroup.LayoutParams.FILL_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		openFileBtn = (LinearLayout) layout.findViewById(R.id.openFileBtn);
		shelfFileBtn = (LinearLayout) layout.findViewById(R.id.shelfFileBtn);
		favoriteFileBtn = (LinearLayout) layout.findViewById(R.id.favoriteFileBtn);
		openFileBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ZLFile file = ZLFile.createFileByPath(items.get(p).getFilepath());
				org.geometerplus.fbreader.book.Book book = getCollection().getBookByFile(file);
				if (book != null) {
					CoreReadActivity.openBookActivity(FileSearchResultActivity.this, book, null);
					FileSearchResultActivity.this.overridePendingTransition(R.anim.activity_enter,
							R.anim.activity_exit);
					FileSearchResultActivity.this.finish();
				}
			}
		});
		shelfFileBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String filename = items.get(p).getFileName();
				String filepath = items.get(p).getFilepath();
				// Local Book---Easy Book
				Book book = new Book();
				book.setBookName(filename);
				book.setBookPath(filepath);
				book.setBookSize(items.get(p).getFilesize());
				Book b = DbDataOperation.queryBook(resolver,DbTags.FIELD_BOOK_NAME,filename);
				if (b == null) {
					DbDataOperation.insertToBookInfo(resolver, book);
					Toast.makeText(FileSearchResultActivity.this, "成功添加到书架", Toast.LENGTH_LONG).show();
				}
			}
		});
		favoriteFileBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String filename = items.get(p).getFileName();
				String filepath = items.get(p).getFilepath();
				// Local Book---Easy Book
				Book book = new Book();
				book.setBookName(filename);
				book.setBookPath(filepath);
				book.setBookSize(items.get(p).getFilesize());
				Date date=new Date();
				//
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				String bookAddTime=formatter.format(date);
				book.setBookAddTime(bookAddTime);

				Book b = DbDataOperation.queryBookFav(resolver,DbTags.FIELD_BOOK_NAME,filename);
				if (b == null) {
					DbDataOperation.insertToBookFav(resolver, book);
					Toast.makeText(FileSearchResultActivity.this, "成功收藏!", Toast.LENGTH_LONG).show();
				}
				else{
					Toast.makeText(FileSearchResultActivity.this, "已经存在收藏夹中!", Toast.LENGTH_LONG).show();
				}
			}
		});
		ColorDrawable cd = new ColorDrawable(-0000);
		mPopuwindow.setBackgroundDrawable(cd);
		mPopuwindow.setBackgroundDrawable(cd);
		mPopuwindow.setOutsideTouchable(true);
		mPopuwindow.setFocusable(true);
		// showAsDropDown
		// popupWindow.showAsDropDown(findViewById(R.id.tv_title), x, 10);
		mPopuwindow.showAsDropDown(v);

	}

	private BookCollectionShadow getCollection() {
		return (BookCollectionShadow) myFBReaderApp.Collection;
	}

	@Override
	protected void onDestroy() {
		getCollection().unbind();
		if(mPopuwindow!=null&&mPopuwindow.isShowing()){
			mPopuwindow.dismiss();
		}
		Log.i("MAIN", "onDestroy()");
		super.onDestroy();
	}
}


text:
require_relative 'aggregations/count'
require_relative 'aggregations/sum'

require_relative 'segmentation'
require_relative 'errors'


text:
(function($){
	//Save original function reference for internal usage
	var _val = $.fn.val;
	$.iHint = function(target, options) {
		var jElement = $(target);
		//Default values
		target.iHint = {
			"text": "iHint Text",
			"className": "iHint-default"
		};
		//Override with extra parameters
		$.extend(target.iHint, options);
		//Set event callbacks, attributes and call blur
		jElement
			.blur(function() {
				if (!_val.call(jElement)) {
					jElement.addClass(target.iHint.className);
					_val.call(jElement, target.iHint.text);
				}
			})
			.focus(function() {
				if (_val.call(jElement) == target.iHint.text) {
					jElement.removeClass(target.iHint.className);
					_val.call(jElement, "");
				}
			})
			.trigger("blur");
	};
	$.fn.iHint = function(options) {
		return this.each(function() {
			new $.iHint(this, options);
		});
	};
	//override default "val" function so it could be used on iHint elements
	$.fn.val = function(value) {
		if (this[0] && this[0].iHint) {
			if (typeof(value) == 'undefined') {
				if (_val.apply(this, arguments) == this[0].iHint.text) {
					return "";
				}
			} else {
				this.removeClass(this[0].iHint.className);
				return _val.apply(this, arguments);
			}
		}
		return _val.apply(this, arguments);
	};
})(jQuery);


text:
package org.dg.openAIL;

import java.util.List;

import org.dg.wifi.MyScanResult;
import org.opencv.core.Mat;

public class MapPosition {
	public int id;
	public double X, Y, Z, angle;
	public Mat image;
	public List<MyScanResult> scannedWiFiList;
}


text:
export function SaveDirective()
{
	'ngInject';

	return {
		scope: {
			isDisabled: '=' //use 2-way binding instead.
		},
		restrict: 'E',
		template: require( './save.directive.html' )
	};
}


text:
package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/ReneGa/tweetcount-microservices/ingestor/client"
	"github.com/ReneGa/tweetcount-microservices/ingestor/gateway"
	"github.com/ReneGa/tweetcount-microservices/ingestor/resource"
	"github.com/julienschmidt/httprouter"
)

func requireEnv(name string) string {
	value, ok := os.LookupEnv(name)
	if !ok {
		panic(fmt.Sprintf("Required environment variable '%s' not set.", name))
	}
	return value
}

var address = flag.String("address", "localhost:8080", "Address to listen on")

func main() {
	flag.Parse()

	key := requireEnv("TWITTER_CONSUMER_KEY")
	keySecret := requireEnv("TWITTER_CONSUMER_KEY_SECRET")
	token := requireEnv("TWITTER_ACCESS_TOKEN")
	tokenSecret := requireEnv("TWITTER_ACCESS_TOKEN_SECRET")

	anaconda := client.NewAnaconda()
	anaconda.SetConsumerKey(key)
	anaconda.SetConsumerSecret(keySecret)
	newTwitterAPI := func() client.TwitterAPI {
		return anaconda.NewTwitterAPI(token, tokenSecret)
	}

	twitterGateway := gateway.NewTwitter(newTwitterAPI)

	tweetsResource := resource.Tweets{Gateway: twitterGateway}

	router := httprouter.New()
	router.GET("/tweets", tweetsResource.GET)

	done := make(chan bool)
	go func() {
		err := http.ListenAndServe(*address, router)
		if err != nil {
			log.Fatal(err)
		}
		done <- true
	}()
	log.Printf("listening on %s", *address)
	<-done
}


text:
<?php

/**
 * @file
 * Contains \Drupal\Component\Utility\String.
 */

namespace Kula\Core\Component\Database\Utility;

/**
 * Provides helpers to operate on strings.
 *
 * @ingroup utility
 */
class DBString {

  /**
   * Encodes special characters in a plain-text string for display as HTML.
   *
   * Also validates strings as UTF-8. All processed strings are also
   * automatically flagged as safe markup strings for rendering.
   *
   * @param string $text
   *   The text to be checked or processed.
   *
   * @return string
   *   An HTML safe version of $text, or an empty string if $text is not
   *   valid UTF-8.
   *
   * @ingroup sanitization
   *
   * @see drupal_validate_utf8()
   * @see \Drupal\Component\Utility\SafeMarkup
   */
  public static function checkPlain($text) {
    return SafeMarkup::set(htmlspecialchars($text, ENT_QUOTES, 'UTF-8'));
  }

  /**
   * Decodes all HTML entities including numerical ones to regular UTF-8 bytes.
   *
   * Double-escaped entities will only be decoded once ("&lt;" becomes
   * "<", not "<"). Be careful when using this function, as it will revert
   * previous sanitization efforts (<script> will become


text:
package com.creeaaakk.tools.util.test;

import java.util.Arrays;

import junit.framework.TestCase;

import org.junit.Test;

import com.creeaaakk.tools.util.ArrayUtil;

public class ArrayUtilTest extends TestCase
{
  @Test
  public void test()
  {
    Integer[] forward;
    Integer[] reversed;

    forward = new Integer[0];
    reversed = ArrayUtil.reverse(forward, new Integer[0]);
    assertTrue(Arrays.equals(new Integer[0], reversed));

    forward = new Integer[] { 1 };
    reversed = ArrayUtil.reverse(forward, new Integer[1]);
    assertTrue(Arrays.equals(new Integer[] { 1 }, reversed));

    forward = new Integer[] { 1, 2 };
    reversed = ArrayUtil.reverse(forward, new Integer[2]);
    assertTrue(Arrays.equals(new Integer[] { 2, 1 }, reversed));

    forward = new Integer[] { 1, 2, 3 };
    reversed = ArrayUtil.reverse(forward, new Integer[3]);
    assertTrue(Arrays.equals(new Integer[] { 3, 2, 1 }, reversed));

    forward = new Integer[] { 1, 2, 3, 4 };
    reversed = ArrayUtil.reverse(forward, new Integer[4]);
    assertTrue(Arrays.equals(new Integer[] { 4, 3, 2, 1 }, reversed));

    reversed = new Integer[0];
    ArrayUtil.reverse(reversed);
    assertTrue(Arrays.equals(new Integer[0], reversed));

    reversed = new Integer[] { 1 };
    ArrayUtil.reverse(reversed);
    assertTrue(Arrays.equals(new Integer[] { 1 }, reversed));

    reversed = new Integer[] { 1, 2 };
    ArrayUtil.reverse(reversed);
    assertTrue(Arrays.equals(new Integer[] { 2, 1 }, reversed));

    reversed = new Integer[] { 1, 2, 3 };
    ArrayUtil.reverse(reversed);
    assertTrue(Arrays.equals(new Integer[] { 3, 2, 1 }, reversed));

    reversed = new Integer[] { 1, 2, 3, 4 };
    ArrayUtil.reverse(reversed);
    assertTrue(Arrays.equals(new Integer[] { 4, 3, 2, 1 }, reversed));
  }
}


text:
package ninja.egg82.patterns.tuples.pair;

import org.apache.commons.lang.builder.HashCodeBuilder;

import ninja.egg82.core.CollectionsReflectUtil;

public final class BooleanBooleanPair {
	//vars
	private volatile boolean left = false;
	private volatile boolean right = false;

	private volatile int hashCode = 0;

	//constructor
	public BooleanBooleanPair(boolean left, boolean right) {
		this.left = left;
		this.right = right;

		hashCode = new HashCodeBuilder(13048583, 9832513).append(left).append(right).toHashCode();
	}

	//public
	public boolean getLeft() {
		return left;
	}
	public void setLeft(boolean left) {
		this.left = left;
		hashCode = new HashCodeBuilder(13048583, 9832513).append(left).append(right).toHashCode();
	}
	public boolean getRight() {
		return right;
	}
	public void setRight(boolean right) {
		this.right = right;
		hashCode = new HashCodeBuilder(13048583, 9832513).append(left).append(right).toHashCode();
	}

	public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		}
		if (this == obj) {
			return true;
		}
		if (!CollectionsReflectUtil.doesExtend(getClass(), obj.getClass())) {
			return false;
		}

		BooleanBooleanPair p = (BooleanBooleanPair) obj;
		if (
			(p.left == left)
			&& (p.right == right)
		) {
			return true;
		}

		return false;
	}
	public int hashCode() {
		return hashCode;
	}

	//private

}


text:
FROM gcr.io/oss-fuzz-base/base-builder-rust
ENV GOPATH /root/go
ENV PATH $PATH:/root/.go/bin:$GOPATH/bin
RUN install_go.sh
RUN apt-get update && apt-get install -y make cmake bzip2 autoconf automake gettext libtool python curl
RUN rustup target add i686-unknown-linux-gnu
#use different package sources for recent npm
RUN curl -sL https://deb.nodesource.com/setup_10.x -o nodesource_setup.sh
RUN bash nodesource_setup.sh
RUN apt install -y nodejs
RUN npm install -g browserify
RUN npm install elliptic
RUN git clone --depth 1 https://github.com/bellard/quickjs quickjs
RUN git clone --depth 1 https://github.com/catenacyber/elliptic-curve-differential-fuzzer.git ecfuzzer
# needed to compile mbedtls
RUN pip3 install jinja2
RUN git clone --recursive --depth 1 -b development https://github.com/ARMmbed/mbedtls.git mbedtls
RUN git clone --depth 1 https://github.com/ANSSI-FR/libecc.git libecc
RUN git clone --depth 1 https://github.com/openssl/openssl.git openssl
RUN git clone --depth 1 git://git.gnupg.org/libgpg-error.git libgpg-error
RUN git clone --depth 1 git://git.gnupg.org/libgcrypt.git gcrypt
RUN git clone --depth 1 https://github.com/weidai11/cryptopp cryptopp
ADD https://gmplib.org/download/gmp/gmp-6.2.1.tar.bz2 gmp-6.2.1.tar.bz2
RUN git clone --depth 1 https://github.com/gnutls/nettle.git nettle
RUN git clone --depth 1 https://github.com/randombit/botan.git botan
WORKDIR $SRC/
COPY build.sh $SRC/


text:
class Solution:
    # @param s, a string
    # @return a list of strings
    def restoreIpAddresses(self, s):
        result = []
        self.restoreIpAddressesRecur(result, s, 0, "", 0)
        return result

    def restoreIpAddressesRecur(self, result, s, start, current, dots):
        # pruning to improve performance
        if (4 - dots) * 3 < len(s) - start or (4 - dots) > len(s) - start:
            return

        if start == len(s) and dots == 4:
            result.append(current[:-1])
        else:
            for i in xrange(start, start + 3):
                if len(s) > i and self.isValid(s[start:i + 1]):
                    current += s[start:i + 1] + '.'
                    self.restoreIpAddressesRecur(result, s, i + 1, current, dots + 1)
                    current = current[:-(i - start + 2)]

    def isValid(self, s):
        if len(s) == 0 or (s[0] == '0' and s != "0"):
            return False
        return int(s) < 256

if __name__ == "__main__":
    print Solution().restoreIpAddresses("0000")


text:
#import "NSData.h"

@interface NSData (IBToolOutputCoercion)
- (id)ibCoerceToDescriptivePListWithStrictness:(long long)arg1;
@end


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ WSO2 Inc. licenses this file to you 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.
  -->

<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">

    <parent>
        <groupId>org.wso2.carbon.devicemgt</groupId>
        <artifactId>certificate-mgt-feature</artifactId>
        <version>2.0.68-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>org.wso2.carbon.certificate.mgt.cert.admin.api.feature</artifactId>
    <packaging>pom</packaging>
    <name>WSO2 Carbon - Admin Certificate Management API Feature</name>
    <url>http://wso2.org</url>
    <description>This feature contains the APIs required for Admin Certificate Management.</description>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>org.wso2.carbon.devicemgt</groupId>
                                    <artifactId>org.wso2.carbon.certificate.mgt.cert.admin.api
                                    </artifactId>
                                    <version>${project.version}</version>
                                    <type>war</type>
                                    <overWrite>true</overWrite>
                                    <outputDirectory>
                                        ${project.build.directory}/maven-shared-archive-resources/webapps
                                    </outputDirectory>
                                    <destFileName>api#certificate-mgt#v1.0.war</destFileName>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>src/main/resources</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>resources</directory>
                                    <includes>
                                        <include>build.properties</include>
                                        <include>p2.inf</include>
                                    </includes>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.wso2.maven</groupId>
                <artifactId>carbon-p2-plugin</artifactId>
                <executions>
                    <execution>
                        <id>p2-feature-generation</id>
                        <phase>package</phase>
                        <goals>
                            <goal>p2-feature-gen</goal>
                        </goals>
                        <configuration>
                            <id>org.wso2.carbon.certificate.mgt.cert.admin.api</id>
                            <propertiesFile>../../../features/etc/feature.properties
                            </propertiesFile>
                            <adviceFile>
                                <properties>
                                    <propertyDef>org.wso2.carbon.p2.category.type:server
                                    </propertyDef>
                                    <propertyDef>org.eclipse.equinox.p2.type.group:false
                                    </propertyDef>
                                </properties>
                            </adviceFile>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
@interface RegistApi : TJSBaseRequest

@end


text:
@rem = '--*-Perl-*--
@echo off
if "%OS%" == "Windows_NT" goto WinNT
IF EXIST "%~dp0perl.exe" (
"%~dp0perl.exe" -x -S "%0" %1 %2 %3 %4 %5 %6 %7 %8 %9
) ELSE IF EXIST "%~dp0..\..\bin\perl.exe" (
"%~dp0..\..\bin\perl.exe" -x -S "%0" %1 %2 %3 %4 %5 %6 %7 %8 %9
) ELSE (
perl -x -S "%0" %1 %2 %3 %4 %5 %6 %7 %8 %9
)

goto endofperl
:WinNT
IF EXIST "%~dp0perl.exe" (
"%~dp0perl.exe" -x -S %0 %*
) ELSE IF EXIST "%~dp0..\..\bin\perl.exe" (
"%~dp0..\..\bin\perl.exe" -x -S %0 %*
) ELSE (
perl -x -S %0 %*
)

if NOT "%COMSPEC%" == "%SystemRoot%\system32\cmd.exe" goto endofperl
if %errorlevel% == 9009 echo You do not have Perl in your PATH.
if errorlevel 1 goto script_failed_so_exit_with_non_zero_val 2>nul
goto endofperl
@rem ';
#!/usr/bin/perl
#line 29
# $File: //depot/cpanplus/dist/bin/cpanp $
# $Revision: #8 $ $Change: 8345 $ $DateTime: 2003/10/05 19:25:48 $

use strict;
use vars '$VERSION';

use CPANPLUS;
$VERSION = CPANPLUS->VERSION;

use CPANPLUS::Shell qw[Default];
my $shell = CPANPLUS::Shell->new;

### if we're given a command, run it; otherwise, open a shell.
if (@ARGV) {
    ### take the command line arguments as a command
    my $input = "@ARGV";
    ### if they said "--help", fix it up to work.
    $input = 'h' if $input =~ /^\s*--?h(?:elp)?\s*$/i;
    ### strip the leading dash
    $input =~ s/^\s*-//;
    ### pass the command line to the shell
    ### exit with a useful return value on return
    exit not $shell->dispatch_on_input(input => $input, noninteractive => 1);
} else {
    ### open a shell for the user
    $shell->shell();
}

=head1 NAME

cpanp - The CPANPLUS launcher

=head1 SYNOPSIS

B<cpanp>

B<cpanp> S<[-]B<a>> S<[ --[B<no>-]I<option>... ]> S< I<author>... >

B<cpanp> S<[-]B<mfitulrcz>> S<[ --[B<no>-]I<option>... ]> S< I<module>... >

B<cpanp> S<[-]B<d>> S<[ --[B<no>-]I<option>... ]> S<[ --B<fetchdir>=... ]> S< I<module>... >

B<cpanp> S<[-]B<xb>> S<[ --[B<no>-]I<option>... ]>

B<cpanp> S<[-]B<o>> S<[ --[B<no>-]I<option>... ]> S<[ I<module>... ]>

=head1 DESCRIPTION

This script launches the B<CPANPLUS> utility to perform various operations
from the command line. If it's invoked without arguments, an interactive
shell is executed by default.

Optionally, it can take a single-letter switch and one or more argument,
to perform the associated action on each arguments.  A summary of the
available commands is listed below; C<cpanp -h> provides a detailed list.

    h                   # help information
    v                   # version information

    a AUTHOR ...        # search by author(s)
    m MODULE ...        # search by module(s)
    f MODULE ...        # list all releases of a module

    i MODULE ...        # install module(s)
    t MODULE ...        # test module(s)
    u MODULE ...        # uninstall module(s)
    d MODULE ...        # download module(s)
    l MODULE ...        # display detailed information about module(s)
    r MODULE ...        # display README files of module(s)
    c MODULE ...        # check for module report(s) from cpan-testers
    z MODULE ...        # extract module(s) and open command prompt in it

    x                   # reload CPAN indices

    o [ MODULE ... ]    # list installed module(s) that aren't up to date
    b                   # write a bundle file for your configuration

Each command may be followed by one or more I<options>.  If preceded by C<no>,
the corresponding option will be set to C<0>, otherwise it's set to C<1>.

Example: To skip a module's tests,

    cpanp -i --skiptest MODULE ...

Valid options for most commands are C<cpantest>, C<debug>, C<flush>, C<force>,
C<prereqs>, C<storable>, C<verbose>, C<md5>, C<signature>, and C<skiptest>; the
'd' command also accepts C<fetchdir>.  Please consult L<CPANPLUS::Configure>
for an explanation to their meanings.

Example: To download a module's tarball to the current directory,

    cpanp -d --fetchdir=. MODULE ...

=cut

1;

# Local variables:
# c-indentation-style: bsd
# c-basic-offset: 4
# indent-tabs-mode: nil
# End:
# vim: expandtab shiftwidth=4:

__END__
:endofperl


text:
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
   <!-- *** The normal plugin stuff *** -->
   <extension
         point="org.eclipse.ui.views">
      <category
            name="CSI Analysis"
            id="CSI">
      </category>
      <view
            name="CSI Analysis Data"
            icon="icons/blue_circle_small.png"
            category="CSI"
            class="csi.views.StackBrowserView"
            id="csi.views.StackBrowserView">
      </view>
   </extension>
   <extension
         id="org.eclipse."
         point="org.eclipse.ui.perspectiveExtensions">
      <perspectiveExtension
            targetID="org.eclipse.jdt.ui.JavaPerspective">
         <view
               id="csi.views.StackBrowserView"
               ratio="0.7"
               relative="org.eclipse.ui.editorss"
               relationship="right"
               visible="false">
         </view>
      </perspectiveExtension>
      <perspectiveExtension
            targetID="org.eclipse.cdt.ui.CPerspective">
         <view
               id="csi.views.StackBrowserView"
               ratio="0.7"
               relative="org.eclipse.ui.editorss"
               relationship="right"
               visible="false">
         </view>
      </perspectiveExtension>
   </extension>
   <extension
         point="org.eclipse.help.contexts">
      <contexts
            file="contexts.xml">
      </contexts>
      <contexts
            file="contexts.xml">
      </contexts>
   </extension>

   <!-- *** handlers for key bindings *** -->
   <extension point="org.eclipse.ui.commands">
      <command
            name="Next trace entry"
            description="Move forward to the next trace entry"
            categoryId="org.eclipse.ui.category.file"
            id="csi.trace.next" />
      <command
            name="Previous trace entry"
            description="Move backward to the previous trace entry"
            categoryId="org.eclipse.ui.category.file"
            id="csi.trace.prev" />
   </extension>
   <extension point="org.eclipse.ui.bindings">
      <key sequence="Ctrl+Alt+Shift+PAGE_DOWN"
           commandId="csi.trace.next"
           schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"/>
      <key sequence="Ctrl+Alt+Shift+PAGE_UP"
           commandId="csi.trace.prev"
           schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"/>
   </extension>

   <!-- *** Local coverage annotations *** -->
   <!-- Yes annotation -->
   <extension
         id="csi.yesMarker"
         name="ExeYes Marker"
         point="org.eclipse.core.resources.markers">
         <super type="org.eclipse.core.resources.textmarker"/>
         <persistent value="false"/>
   </extension>
   <extension
   		 id="csi.yesAnnotation"
   		 name="ExeYes Marker Annotation"
         point="org.eclipse.ui.editors.annotationTypes">
      <type
            markerType="csi.yesMarker"
            name="csi.yesAnnotation">
      </type>
   </extension>
	<extension
         point="org.eclipse.ui.editors.markerAnnotationSpecification"
         id="csi.yesAnnotationSpec">
      <specification
            annotationType="csi.yesAnnotation"
            includeOnPreferencePage="true"
            overviewRulerPreferenceKey="clruler"
            label="Local Yes"
			overviewRulerPreferenceValue="true"
			highlightPreferenceKey="highlight.background"
			highlightPreferenceValue="true"
			colorPreferenceKey="clcolor"
			colorPreferenceValue="205,255,205"
			textPreferenceKey="cltext"
			textPreferenceValue="true"
			presentationLayer="5"
			verticalRulerPreferenceKey="clvertical"
			verticalRulerPreferenceValue="true"
			textStylePreferenceKey="clstyle"
			textStylePreferenceValue="BOX">
      </specification>
   </extension>

   <!-- No annotation -->
   <extension
         id="csi.noMarker"
         name="ExeNo Marker"
         point="org.eclipse.core.resources.markers">
         <super type="org.eclipse.core.resources.textmarker"/>
         <persistent value="false"/>
   </extension>
   <extension
   		 id="csi.noAnnotation"
   		 name="ExeNo Marker Annotation"
         point="org.eclipse.ui.editors.annotationTypes">
      <type
            markerType="csi.noMarker"
            name="csi.noAnnotation">
      </type>
   </extension>
	<extension
         point="org.eclipse.ui.editors.markerAnnotationSpecification"
         id="csi.noAnnotationSpec">
      <specification
            annotationType="csi.noAnnotation"
            includeOnPreferencePage="true"
            overviewRulerPreferenceKey="clruler"
            label="Local No"
			overviewRulerPreferenceValue="true"
			highlightPreferenceKey="highlight.background"
			highlightPreferenceValue="true"
			colorPreferenceKey="no.clcolor"
			colorPreferenceValue="255,205,205"
			textPreferenceKey="no.cltext"
			textPreferenceValue="true"
			presentationLayer="4"
			verticalRulerPreferenceKey="no.clvertical"
			verticalRulerPreferenceValue="true"
			textStylePreferenceKey="no.clstyle"
			textStylePreferenceValue="BOX">
      </specification>
   </extension>

   <!-- Maybe annotation -->
   <extension
         id="csi.maybeMarker"
         name="ExeMaybe Marker"
         point="org.eclipse.core.resources.markers">
         <super type="org.eclipse.core.resources.textmarker"/>
         <persistent value="false"/>
   </extension>
   <extension
   		 id="csi.maybeAnnotation"
   		 name="ExeMaybe Marker Annotation"
         point="org.eclipse.ui.editors.annotationTypes">
      <type
            markerType="csi.maybeMarker"
            name="csi.maybeAnnotation">
      </type>
   </extension>
	<extension
         point="org.eclipse.ui.editors.markerAnnotationSpecification"
         id="csi.maybeAnnotationSpec">
      <specification
            annotationType="csi.maybeAnnotation"
            includeOnPreferencePage="true"
            overviewRulerPreferenceKey="clruler"
            label="Local Maybe"
			overviewRulerPreferenceValue="true"
			highlightPreferenceKey="highlight.background"
			highlightPreferenceValue="true"
			colorPreferenceKey="maybe.clcolor"
			colorPreferenceValue="255,255,141"
			textPreferenceKey="maybe.cltext"
			textPreferenceValue="true"
			presentationLayer="4"
			verticalRulerPreferenceKey="maybe.clvertical"
			verticalRulerPreferenceValue="true"
			textStylePreferenceKey="maybe.clstyle"
			textStylePreferenceValue="BOX">
      </specification>
   </extension>

   <!-- Other annotation -->
   <extension
         id="csi.otherMarker"
         name="Mixed Exe Marker"
         point="org.eclipse.core.resources.markers">
         <super type="org.eclipse.core.resources.textmarker"/>
         <persistent value="false"/>
   </extension>
   <extension
   		 id="csi.otherAnnotation"
   		 name="Complex Exe Marker Annotation"
         point="org.eclipse.ui.editors.annotationTypes">
      <type
            markerType="csi.otherMarker"
            name="csi.otherAnnotation">
      </type>
   </extension>
	<extension
         point="org.eclipse.ui.editors.markerAnnotationSpecification"
         id="csi.otherAnnotationSpec">
      <specification
            annotationType="csi.otherAnnotation"
            includeOnPreferencePage="true"
            overviewRulerPreferenceKey="clruler"
            label="Local Complex"
			overviewRulerPreferenceValue="true"
			highlightPreferenceKey="highlight.background"
			highlightPreferenceValue="true"
			colorPreferenceKey="other.clcolor"
			colorPreferenceValue="169,149,135"
			textPreferenceKey="other.cltext"
			textPreferenceValue="true"
			presentationLayer="4"
			verticalRulerPreferenceKey="other.clvertical"
			verticalRulerPreferenceValue="true"
			textStylePreferenceKey="other.clstyle"
			textStylePreferenceValue="BOX">
      </specification>
   </extension>

   <!-- *** Global coverage annotations *** -->
   <!-- Yes annotation -->
   <extension
         id="csi.global.yesMarker"
         name="Global ExeYes Marker"
         point="org.eclipse.core.resources.markers">
         <super type="org.eclipse.core.resources.textmarker"/>
         <persistent value="false"/>
   </extension>
   <extension
   		 id="csi.global.yesAnnotation"
   		 name="Global ExeYes Marker Annotation"
         point="org.eclipse.ui.editors.annotationTypes">
      <type
            markerType="csi.global.yesMarker"
            name="csi.global.yesAnnotation">
      </type>
   </extension>
	<extension
         point="org.eclipse.ui.editors.markerAnnotationSpecification"
         id="csi.global.yesAnnotationSpec">
      <specification
            annotationType="csi.global.yesAnnotation"
            includeOnPreferencePage="true"
            overviewRulerPreferenceKey="clruler"
            label="Global Yes"
            icon="icons/green_circle_extra_small.png"
            overviewRulerPreferenceValue="true"
			highlightPreferenceKey="globalyes.highlight.background"
			highlightPreferenceValue="false"
			colorPreferenceKey="globalyes.clcolor"
			colorPreferenceValue="100,255,100"
			textPreferenceKey="globalyes.cltext"
			textPreferenceValue="true"
			presentationLayer="3"
			verticalRulerPreferenceKey="globalyes.clvertical"
			verticalRulerPreferenceValue="true"
			textStylePreferenceKey="globalyes.clstyle"
			textStylePreferenceValue="NONE">
      </specification>
   </extension>

   <!-- No annotation -->
   <extension
         id="csi.global.noMarker"
         name="Global ExeNo Marker"
         point="org.eclipse.core.resources.markers">
         <super type="org.eclipse.core.resources.textmarker"/>
         <persistent value="false"/>
   </extension>
   <extension
   		 id="csi.global.noAnnotation"
   		 name="Global ExeNo Marker Annotation"
         point="org.eclipse.ui.editors.annotationTypes">
      <type
            markerType="csi.global.noMarker"
            name="csi.global.noAnnotation">
      </type>
   </extension>
	<extension
         point="org.eclipse.ui.editors.markerAnnotationSpecification"
         id="csi.global.noAnnotationSpec">
      <specification
            annotationType="csi.global.noAnnotation"
            includeOnPreferencePage="true"
            overviewRulerPreferenceKey="clruler"
            label="Global No"
            icon="icons/red_square_extra_small.png"
            overviewRulerPreferenceValue="true"
			highlightPreferenceKey="globalno.highlight.background"
			highlightPreferenceValue="false"
			colorPreferenceKey="globalno.clcolor"
			colorPreferenceValue="255,100,100"
			textPreferenceKey="globalno.cltext"
			textPreferenceValue="true"
			presentationLayer="1"
			verticalRulerPreferenceKey="globalno.clvertical"
			verticalRulerPreferenceValue="true"
			textStylePreferenceKey="globalno.clstyle"
			textStylePreferenceValue="NONE">
      </specification>
   </extension>

   <!-- Maybe annotation -->
   <extension
         id="csi.global.maybeMarker"
         name="Global ExeMaybe Marker"
         point="org.eclipse.core.resources.markers">
         <super type="org.eclipse.core.resources.textmarker"/>
         <persistent value="false"/>
   </extension>
   <extension
   		 id="csi.global.maybeAnnotation"
   		 name="Global ExeMaybe Marker Annotation"
         point="org.eclipse.ui.editors.annotationTypes">
      <type
            markerType="csi.global.maybeMarker"
            name="csi.global.maybeAnnotation">
      </type>
   </extension>
	<extension
         point="org.eclipse.ui.editors.markerAnnotationSpecification"
         id="csi.global.maybeAnnotationSpec">
      <specification
            annotationType="csi.global.maybeAnnotation"
            includeOnPreferencePage="true"
            overviewRulerPreferenceKey="clruler"
            label="Global Maybe"
            icon="icons/yellow_diamond_extra_small.png"
            overviewRulerPreferenceValue="true"
			highlightPreferenceKey="globalmaybe.highlight.background"
			highlightPreferenceValue="false"
			colorPreferenceKey="globalmaybe.clcolor"
			colorPreferenceValue="255,255,100"
			textPreferenceKey="globalmaybe.cltext"
			textPreferenceValue="true"
			presentationLayer="2"
			verticalRulerPreferenceKey="globalmaybe.clvertical"
			verticalRulerPreferenceValue="true"
			textStylePreferenceKey="globalmaybe.clstyle"
			textStylePreferenceValue="NONE">
      </specification>
   </extension>

   <!-- Other annotation -->
   <extension
         id="csi.global.otherMarker"
         name="Global Complex Exe Marker"
         point="org.eclipse.core.resources.markers">
         <super type="org.eclipse.core.resources.textmarker"/>
         <persistent value="false"/>
   </extension>
   <extension
   		 id="csi.global.otherAnnotation"
   		 name="Global Complex Exe Marker Annotation"
         point="org.eclipse.ui.editors.annotationTypes">
      <type
            markerType="csi.global.otherMarker"
            name="csi.global.otherAnnotation">
      </type>
   </extension>
	<extension
         point="org.eclipse.ui.editors.markerAnnotationSpecification"
         id="csi.global.otherAnnotationSpec">
      <specification
            annotationType="csi.global.otherAnnotation"
            includeOnPreferencePage="true"
            overviewRulerPreferenceKey="clruler"
            label="Global Complex Exe"
            icon="icons/orange_circle_extra_small.png"
            overviewRulerPreferenceValue="true"
			highlightPreferenceKey="globalother.highlight.background"
			highlightPreferenceValue="false"
			colorPreferenceKey="globalother.clcolor"
			colorPreferenceValue="169,149,135"
			textPreferenceKey="globalother.cltext"
			textPreferenceValue="true"
			presentationLayer="2"
			verticalRulerPreferenceKey="globalother.clvertical"
			verticalRulerPreferenceValue="true"
			textStylePreferenceKey="globalother.clstyle"
			textStylePreferenceValue="NONE">
      </specification>
   </extension>

   <!-- *** Path entry annotations *** -->
   <!-- Current annotation -->
   <extension
         id="csi.path.currentMarker"
         name="Local Path Current Marker"
         point="org.eclipse.core.resources.markers">
         <super type="org.eclipse.core.resources.textmarker"/>
         <persistent value="false"/>
   </extension>
   <extension
   		 id="csi.path.currentAnnotation"
   		 name="Local Path Current Annotation"
         point="org.eclipse.ui.editors.annotationTypes">
      <type
            markerType="csi.path.currentMarker"
            name="csi.path.currentAnnotation">
      </type>
   </extension>
	<extension
         point="org.eclipse.ui.editors.markerAnnotationSpecification"
         id="csi.path.currentAnnotationSpec">
      <specification
            annotationType="csi.path.currentAnnotation"
            includeOnPreferencePage="true"
            overviewRulerPreferenceKey="clruler"
            label="Current Path Entry"
            icon="icons/arrow_current.png"
            overviewRulerPreferenceValue="true"
			highlightPreferenceKey="pathcurrent.highlight.background"
			highlightPreferenceValue="true"
			colorPreferenceKey="pathcurrent.clcolor"
			colorPreferenceValue="63,255,63"
			textPreferenceKey="pathcurrent.cltext"
			textPreferenceValue="true"
			presentationLayer="100"
			verticalRulerPreferenceKey="pathcurrent.clvertical"
			verticalRulerPreferenceValue="true"
			textStylePreferenceKey="pathcurrent.clstyle"
			textStylePreferenceValue="NONE">
      </specification>
   </extension>

   <!-- Next annotation -->
   <extension
         id="csi.path.nextMarker"
         name="Local Path Adjacent Marker"
         point="org.eclipse.core.resources.markers">
         <super type="org.eclipse.core.resources.textmarker"/>
         <persistent value="false"/>
   </extension>
   <extension
   		 id="csi.path.nextAnnotation"
   		 name="Local Path Adjacent Annotation"
         point="org.eclipse.ui.editors.annotationTypes">
      <type
            markerType="csi.path.nextMarker"
            name="csi.path.nextAnnotation">
      </type>
   </extension>
	<extension
         point="org.eclipse.ui.editors.markerAnnotationSpecification"
         id="csi.path.nextAnnotationSpec">
      <specification
            annotationType="csi.path.nextAnnotation"
            includeOnPreferencePage="true"
            overviewRulerPreferenceKey="clruler"
            label="Adjacent Path Entry"
            icon="icons/arrow_next.png"
            overviewRulerPreferenceValue="true"
			highlightPreferenceKey="pathnext.highlight.background"
			highlightPreferenceValue="false"
			colorPreferenceKey="pathnext.clcolor"
			colorPreferenceValue="169,149,135"
			textPreferenceKey="pathnext.cltext"
			textPreferenceValue="true"
			presentationLayer="100"
			verticalRulerPreferenceKey="pathnext.clvertical"
			verticalRulerPreferenceValue="true"
			textStylePreferenceKey="pathnext.clstyle"
			textStylePreferenceValue="NONE">
      </specification>
   </extension>

</plugin>


text:
import logging

from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.shortcuts import get_current_site
from os.path import basename
from django.conf import settings
from django.db import models
from django.db.models import F, Func, IntegerField, Q
from django.utils.translation import ugettext_lazy as _
from django_mailbox.models import Message
from model_utils import Choices
from model_utils.fields import MonitorField, StatusField

from poradnia.cases.models import Case
from poradnia.cases.utils import get_users_with_perm
from poradnia.records.models import AbstractRecord, AbstractRecordQuerySet
from poradnia.users.models import User

from .utils import date_random_path
from .templatetags.format_text import format_text

from django.urls import reverse

logger = logging.getLogger(__name__)

class LetterQuerySet(AbstractRecordQuerySet):
    def for_user(self, user):
        qs = super().for_user(user)
        if not user.is_staff:
            qs = qs.filter(status=Letter.STATUS.done)
        return qs

    def last_staff_send(self):
        return (
            self.filter(status="done", created_by__is_staff=True)
            .order_by("-created_on", "-id")
            .all()[0]
        )

    def last_received(self):
        return (
            self.filter(created_by__is_staff=False)
            .order_by("-created_on", "-id")
            .all()[0]
        )

    def last(self):
        return self.order_by("-created_on", "-id").all()[0]

    def case(self, case):
        return self.filter(record__case=case)

    def with_month_year(self):
        return self.annotate(
            month=Func(F("created_on"), function="month", output_field=IntegerField())
        ).annotate(
            year=Func(F("created_on"), function="year", output_field=IntegerField())
        )

class Letter(AbstractRecord):
    STATUS = Choices(("staff", _("Staff")), ("done", _("Done")))
    GENRE = Choices("mail", "comment")
    genre = models.CharField(choices=GENRE, default=GENRE.comment, max_length=20)
    status = StatusField(db_index=True)
    status_changed = MonitorField(monitor="status")
    accept = MonitorField(
        monitor="status", when=["done"], verbose_name=_("Accepted on")
    )
    name = models.CharField(max_length=250, verbose_name=_("Subject"))
    text = models.TextField(verbose_name=_("Text"))
    html = models.TextField(verbose_name=_("HTML"), blank=True)
    signature = models.TextField(verbose_name=_("Signature"), blank=True, null=True)
    created_by = models.ForeignKey(
        to=settings.AUTH_USER_MODEL,
        related_name="letter_created_by",
        verbose_name=_("Created by"),
        on_delete=models.CASCADE,
    )
    created_on = models.DateTimeField(auto_now_add=True, verbose_name=_("Created on"))
    modified_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        verbose_name=_("Modified by"),
        null=True,
        on_delete=models.CASCADE,
        related_name="letter_modified_by",
    )
    modified_on = models.DateTimeField(
        auto_now=True, null=True, blank=True, verbose_name=_("Modified on")
    )
    message = models.ForeignKey(
        to=Message, null=True, blank=True, on_delete=models.CASCADE
    )
    eml = models.FileField(
        _("Raw message contents"),
        null=True,
        upload_to="messages",
        help_text=_("Original full content of message"),
    )

    objects = LetterQuerySet.as_manager()

    def __str__(self):
        return self.name

    def get_users(self, force_all=False):
        users_to_notify = self.get_users_with_perms()

        if self.status == self.STATUS.staff or force_all:
            users_to_notify = users_to_notify.filter(is_staff=True)

        return users_to_notify

    def get_absolute_url(self):
        case_url = self.record.case_get_absolute_url()
        return "{}#letter-{}".format(case_url, self.pk)

    def is_done(self):
        return True if self.status == self.STATUS.done else False

    def is_html(self):
        return bool(self.html)

    def render_as_html(self):
        if self.is_html():
            return self.html
        else:
            return "<pre>{text}</pre>".format(text=format_text(self.text))

    def get_edit_url(self):
        return reverse("letters:edit", kwargs={"pk": self.pk})

    def get_send_url(self):
        return reverse("letters:send", kwargs={"pk": self.pk})

    def set_new_case(self):
        self.case = Case.objects.create(
            subject=self.name, created_by=self.created_by, client=self.client
        )

    def send_notification(self, *args, **kwargs):
        staff_users = get_users_with_perm(self.case, "can_send_to_client")
        management = User.objects.filter(notify_unassigned_letter=True).all()
        if self.status is Letter.STATUS.done:
            if len(list(staff_users)) > 0:
                kwargs["user_qs"] = self.get_users_with_perms()
            else:
                kwargs["user_qs"] = User.objects.filter(
                    Q(pk__in=self.get_users_with_perms()) | Q(pk__in=management)
                )
        else:
            if len(list(staff_users)) > 0:
                kwargs["user_qs"] = self.get_users_with_perms().filter(is_staff=True)
            else:
                kwargs["user_qs"] = User.objects.filter(
                    Q(pk__in=self.get_users_with_perms().filter(is_staff=True))
                    | Q(pk__in=management)
                )
        return super().send_notification(*args, **kwargs)

    class Meta:
        verbose_name = _("Letter")
        verbose_name_plural = _("Letters")
        ordering = ["-created_on"]

lrc_cup = "letter__record__case__caseuserobjectpermission"

class AttachmentQuerySet(models.QuerySet):
    def for_user(self, user):
        qs = self
        if not user.has_perm("cases.can_view_all"):
            content_type = ContentType.objects.get_for_model(Case)
            qs = qs.filter(
                **{
                    "{}__permission__codename".format(lrc_cup): "can_view",
                    "{}__permission__content_type".format(lrc_cup): content_type,
                    "{}__user".format(lrc_cup): user,
                }
            )
        if not user.is_staff:
            qs = qs.filter(letter__status=Letter.STATUS.done)
        return qs

class Attachment(models.Model):
    letter = models.ForeignKey(to=Letter, on_delete=models.CASCADE)
    attachment = models.FileField(upload_to=date_random_path, verbose_name=_("File"))

    objects = AttachmentQuerySet.as_manager()

    @property
    def filename(self):
        return basename(self.attachment.name)

    def __str__(self):
        return "%s" % (self.filename)

    def get_absolute_url(self):
        return self.attachment.url

    def get_full_url(self):
        return "".join(
            ["https://", get_current_site(None).domain, self.get_absolute_url()]
        )

    class Meta:
        verbose_name = _("Attachment")
        verbose_name_plural = _("Attachments")