text:
<?php namespace Tests;

use BookStack\Notifications\ConfirmEmail;
use BookStack\User;
use Illuminate\Support\Facades\Notification;

class AuthTest extends BrowserKitTest
{

    public function test_auth_working()
    {
        $this->visit('/')
            ->seePageIs('/login');
    }

    public function test_login()
    {
        $this->login('admin@admin.com', 'password')
            ->seePageIs('/');
    }

    public function test_public_viewing()
    {
        $settings = app('BookStack\Services\SettingService');
        $settings->put('app-public', 'true');
        $this->visit('/')
            ->seePageIs('/')
            ->see('Log In');
    }

    public function test_registration_showing()
    {
        // Ensure registration form is showing
        $this->setSettings(['registration-enabled' => 'true']);
        $this->visit('/login')
            ->see('Sign up')
            ->click('Sign up')
            ->seePageIs('/register');
    }

    public function test_normal_registration()
    {
        // Set settings and get user instance
        $this->setSettings(['registration-enabled' => 'true']);
        $user = factory(User::class)->make();

        // Test form and ensure user is created
        $this->visit('/register')
            ->see('Sign Up')
            ->type($user->name, '#name')
            ->type($user->email, '#email')
            ->type($user->password, '#password')
            ->press('Create Account')
            ->seePageIs('/')
            ->see($user->name)
            ->seeInDatabase('users', ['name' => $user->name, 'email' => $user->email]);
    }

    public function test_empty_registration_redirects_back_with_errors()
    {
        // Set settings and get user instance
        $this->setSettings(['registration-enabled' => 'true']);

        // Test form and ensure user is created
        $this->visit('/register')
            ->press('Create Account')
            ->see('The name field is required')
            ->seePageIs('/register');
    }

    public function test_confirmed_registration()
    {
        // Fake notifications
        Notification::fake();

        // Set settings and get user instance
        $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'true']);
        $user = factory(User::class)->make();

        // Go through registration process
        $this->visit('/register')
            ->see('Sign Up')
            ->type($user->name, '#name')
            ->type($user->email, '#email')
            ->type($user->password, '#password')
            ->press('Create Account')
            ->seePageIs('/register/confirm')
            ->seeInDatabase('users', ['name' => $user->name, 'email' => $user->email, 'email_confirmed' => false]);

        // Ensure notification sent
        $dbUser = User::where('email', '=', $user->email)->first();
        Notification::assertSentTo($dbUser, ConfirmEmail::class);

        // Test access and resend confirmation email
        $this->login($user->email, $user->password)
            ->seePageIs('/register/confirm/awaiting')
            ->see('Resend')
            ->visit('/books')
            ->seePageIs('/register/confirm/awaiting')
            ->press('Resend Confirmation Email');

        // Get confirmation and confirm notification matches
        $emailConfirmation = \DB::table('email_confirmations')->where('user_id', '=', $dbUser->id)->first();
        Notification::assertSentTo($dbUser, ConfirmEmail::class, function($notification, $channels) use ($emailConfirmation) {
            return $notification->token === $emailConfirmation->token;
        });

        // Check confirmation email confirmation activation.
        $this->visit('/register/confirm/' . $emailConfirmation->token)
            ->seePageIs('/')
            ->see($user->name)
            ->notSeeInDatabase('email_confirmations', ['token' => $emailConfirmation->token])
            ->seeInDatabase('users', ['name' => $dbUser->name, 'email' => $dbUser->email, 'email_confirmed' => true]);
    }

    public function test_restricted_registration()
    {
        $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'true', 'registration-restrict' => 'example.com']);
        $user = factory(User::class)->make();
        // Go through registration process
        $this->visit('/register')
            ->type($user->name, '#name')
            ->type($user->email, '#email')
            ->type($user->password, '#password')
            ->press('Create Account')
            ->seePageIs('/register')
            ->dontSeeInDatabase('users', ['email' => $user->email])
            ->see('That email domain does not have access to this application');

        $user->email = 'barry@example.com';

        $this->visit('/register')
            ->type($user->name, '#name')
            ->type($user->email, '#email')
            ->type($user->password, '#password')
            ->press('Create Account')
            ->seePageIs('/register/confirm')
            ->seeInDatabase('users', ['name' => $user->name, 'email' => $user->email, 'email_confirmed' => false]);

        $this->visit('/')->seePageIs('/login')
            ->type($user->email, '#email')
            ->type($user->password, '#password')
            ->press('Log In')
            ->seePageIs('/register/confirm/awaiting')
            ->seeText('Email Address Not Confirmed');
    }

    public function test_restricted_registration_with_confirmation_disabled()
    {
        $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'false', 'registration-restrict' => 'example.com']);
        $user = factory(User::class)->make();
        // Go through registration process
        $this->visit('/register')
            ->type($user->name, '#name')
            ->type($user->email, '#email')
            ->type($user->password, '#password')
            ->press('Create Account')
            ->seePageIs('/register')
            ->dontSeeInDatabase('users', ['email' => $user->email])
            ->see('That email domain does not have access to this application');

        $user->email = 'barry@example.com';

        $this->visit('/register')
            ->type($user->name, '#name')
            ->type($user->email, '#email')
            ->type($user->password, '#password')
            ->press('Create Account')
            ->seePageIs('/register/confirm')
            ->seeInDatabase('users', ['name' => $user->name, 'email' => $user->email, 'email_confirmed' => false]);

        $this->visit('/')->seePageIs('/login')
            ->type($user->email, '#email')
            ->type($user->password, '#password')
            ->press('Log In')
            ->seePageIs('/register/confirm/awaiting')
            ->seeText('Email Address Not Confirmed');
    }

    public function test_user_creation()
    {
        $user = factory(User::class)->make();

        $this->asAdmin()
            ->visit('/settings/users')
            ->click('Add New User')
            ->type($user->name, '#name')
            ->type($user->email, '#email')
            ->check('roles[admin]')
            ->type($user->password, '#password')
            ->type($user->password, '#password-confirm')
            ->press('Save')
            ->seePageIs('/settings/users')
            ->seeInDatabase('users', $user->toArray())
            ->see($user->name);
    }

    public function test_user_updating()
    {
        $user = $this->getNormalUser();
        $password = $user->password;
        $this->asAdmin()
            ->visit('/settings/users')
            ->click($user->name)
            ->seePageIs('/settings/users/' . $user->id)
            ->see($user->email)
            ->type('Barry Scott', '#name')
            ->press('Save')
            ->seePageIs('/settings/users')
            ->seeInDatabase('users', ['id' => $user->id, 'name' => 'Barry Scott', 'password' => $password])
            ->notSeeInDatabase('users', ['name' => $user->name]);
    }

    public function test_user_password_update()
    {
        $user = $this->getNormalUser();
        $userProfilePage = '/settings/users/' . $user->id;
        $this->asAdmin()
            ->visit($userProfilePage)
            ->type('newpassword', '#password')
            ->press('Save')
            ->seePageIs($userProfilePage)
            ->see('Password confirmation required')

            ->type('newpassword', '#password')
            ->type('newpassword', '#password-confirm')
            ->press('Save')
            ->seePageIs('/settings/users');

            $userPassword = User::find($user->id)->password;
            $this->assertTrue(\Hash::check('newpassword', $userPassword));
    }

    public function test_user_deletion()
    {
        $userDetails = factory(User::class)->make();
        $user = $this->getEditor($userDetails->toArray());

        $this->asAdmin()
            ->visit('/settings/users/' . $user->id)
            ->click('Delete User')
            ->see($user->name)
            ->press('Confirm')
            ->seePageIs('/settings/users')
            ->notSeeInDatabase('users', ['name' => $user->name]);
    }

    public function test_user_cannot_be_deleted_if_last_admin()
    {
        $adminRole = \BookStack\Role::getRole('admin');
        // Ensure we currently only have 1 admin user
        $this->assertEquals(1, $adminRole->users()->count());
        $user = $adminRole->users->first();

        $this->asAdmin()->visit('/settings/users/' . $user->id)
            ->click('Delete User')
            ->press('Confirm')
            ->seePageIs('/settings/users/' . $user->id)
            ->see('You cannot delete the only admin');
    }

    public function test_logout()
    {
        $this->asAdmin()
            ->visit('/')
            ->seePageIs('/')
            ->visit('/logout')
            ->visit('/')
            ->seePageIs('/login');
    }

    public function test_reset_password_flow()
    {

        Notification::fake();

        $this->visit('/login')->click('Forgot Password?')
            ->seePageIs('/password/email')
            ->type('admin@admin.com', 'email')
            ->press('Send Reset Link')
            ->see('A password reset link has been sent to admin@admin.com');

        $this->seeInDatabase('password_resets', [
            'email' => 'admin@admin.com'
        ]);

        $user = User::where('email', '=', 'admin@admin.com')->first();

        Notification::assertSentTo($user, \BookStack\Notifications\ResetPassword::class);
        $n = Notification::sent($user, \BookStack\Notifications\ResetPassword::class);

        $this->visit('/password/reset/' . $n->first()->token)
            ->see('Reset Password')
            ->submitForm('Reset Password', [
                'email' => 'admin@admin.com',
                'password' => 'randompass',
                'password_confirmation' => 'randompass'
            ])->seePageIs('/')
            ->see('Your password has been successfully reset');
    }

    public function test_reset_password_page_shows_sign_links()
    {
        $this->setSettings(['registration-enabled' => 'true']);
        $this->visit('/password/email')
            ->seeLink('Log in')
            ->seeLink('Sign up');
    }

    /**
     * Perform a login
     * @param string $email
     * @param string $password
     * @return $this
     */
    protected function login($email, $password)
    {
        return $this->visit('/login')
            ->type($email, '#email')
            ->type($password, '#password')
            ->press('Log In');
    }
}


text:
var xmlRequestObj;

function loadXMLDoc(url, callFunc, ignoreWhite) {
	functionToCall = callFunc;
	stripWS = ignoreWhite;
	xmlRequestObj = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
	xmlRequestObj.onreadystatechange = processXML;
	xmlRequestObj.open("GET", url, true);
	xmlRequestObj.send(null);
}

// private

function is_ws(nod) {
	return !(/[^\t\n\r ]/.test(nod.data));
}

function findWhiteSpace(node, nodeNo) {
	for (i=0; i<node.childNodes.length; i++) {
		if (node.childNodes[i].nodeType == 3 && is_ws(node.childNodes[i])) {
			nodesToDelete[nodesToDelete.length] = node.childNodes[i]
		}
		if (node.childNodes[i].hasChildNodes()) {
			findWhiteSpace(node.childNodes[i], i);
		}
	}
	node = node.parentNode;
	i = nodeNo;
}

function stripWhiteSpace(node) {
	nodesToDelete = Array();
	findWhiteSpace(node, 0);
	for(i=nodesToDelete.length-1;i>=0;i--) {
		nodeRef = nodesToDelete[i];
		nodeRef.parentNode.removeChild(nodeRef)
	}
}

function processXML() {
	if (xmlRequestObj.readyState == 4 && (xmlRequestObj.status == 200 || xmlRequestObj.status == 304)) {
		if(stripWS) {
			stripWhiteSpace(xmlRequestObj.responseXML);
		}
		resultXML = xmlRequestObj.responseXML;
		functionToCall()
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * PHP version 7.3
 *
 * @category Customer
 * @package  RetailCrm\Api\Model\Entity\Loyalty
 */

namespace RetailCrm\Api\Model\Entity\Loyalty;

use RetailCrm\Api\Component\Serializer\Annotation as JMS;

/**
 * Class Customer
 *
 * @category Customer
 * @package  RetailCrm\Api\Model\Entity\Loyalty
 */
class Customer
{
    /**
     * @var int
     *
     * @JMS\Type("int")
     * @JMS\SerializedName("id")
     */
    public $id;

    /**
     * @var string
     *
     * @JMS\Type("string")
     * @JMS\SerializedName("externalId")
     */
    public $externalId;

    /**
     * @var float
     *
     * @JMS\Type("float")
     * @JMS\SerializedName("personalDiscount")
     */
    public $personalDiscount;
}


text:
<?php

namespace Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpFoundation\Request;
use JoiPolloi\Bundle\JsonValidationBundle\JsonValidator\JsonValidator;

/**
 * JSON Validator tests
 *
 * @author John Noel <john.noel@joipolloi.com>
 * @package JsonValidationBundle
 */
class JsonValidatorTest extends TestCase
{
    public function testMissingSchema()
    {
        $validator = $this->getJsonValidator();

        $isNull = $validator->validateJson('{}', 'nonexistent-schema.json');
        $errors = $validator->getValidationErrors();

        $this->assertNull($isNull);
        $this->assertCount(1, $errors);
        $this->assertEquals($errors[0]['message'], 'Unable to locate schema nonexistent-schema.json');
    }

    public function testSyntacticallyInvalidJson()
    {
        $validator = $this->getJsonValidator();

        $isNull = $validator->validateJson('{invalid', 'schema-simple.json');
        $errors = $validator->getValidationErrors();

        $this->assertNull($isNull);
        $this->assertCount(1, $errors);
        $this->assertEquals($errors[0]['message'], '[4] Syntax error');
    }

    public function testSchemaInvalidJson()
    {
        $validator = $this->getJsonValidator();

        $isNull = $validator->validateJson('{"nottest": "hello"}', 'schema-simple.json');
        $errors = $validator->getValidationErrors();

        $this->assertNull($isNull);
        $this->assertCount(1, $errors);
        $this->assertEquals($errors[0]['message'], 'The property test is required');
    }

    public function testInvalidSchema()
    {
        $validator = $this->getJsonValidator();

        $isNull = $validator->validateJson('{"test": "hello"}', 'schema-invalid.json');
        $errors = $validator->getValidationErrors();

        $this->assertNull($isNull);
        $this->assertCount(1, $errors);
        $this->assertEquals($errors[0]['message'], 'JSON syntax is malformed');
    }

    public function testValidJson()
    {
        $validator = $this->getJsonValidator();

        $object = $validator->validateJson('{"test": "hello"}', 'schema-simple.json');
        $errors = $validator->getValidationErrors();

        $this->assertNotNull($object);
        $this->assertCount(0, $errors);
        $this->assertEquals('hello', $object->test);
    }

    public function testValidEmptyJsonRequest()
    {
        $validator = $this->getJsonValidator();
        $request = new Request([], [], [], [], [], [], '');

        $isTrue = $validator->validateJsonRequest($request, 'schema-simple.json', true);
        $errors = $validator->getValidationErrors();

        $this->assertNotNull($isTrue);
        $this->assertCount(0, $errors);
        $this->assertTrue($isTrue);
    }

    public function testInvalidEmptyResponse()
    {
        $validator = $this->getJsonValidator();
        $request = new Request([], [], [], [], [], [], '');

        $isNull = $validator->validateJsonRequest($request, 'schema-simple.json', false);
        $errors = $validator->getValidationErrors();

        $this->assertNull($isNull);
        $this->assertCount(1, $errors);
        $this->assertEquals($errors[0]['message'], '[4] Syntax error');
    }

    public function testValidJsonRequest()
    {
        $validator = $this->getJsonValidator();
        $request = new Request([], [], [], [], [], [], '{"test": "hello"}');

        $object = $validator->validateJsonRequest($request, 'schema-simple.json', false);
        $errors = $validator->getValidationErrors();

        $this->assertNotNull($object);
        $this->assertCount(0, $errors);
        $this->assertEquals($object->test, 'hello');
    }

    public function testValidJsonRequestAsArray()
    {
        $validator = $this->getJsonValidator();
        $request = new Request([], [], [], [], [], [], '{"test": "hello"}');

        $array = $validator->validateJsonRequest($request, 'schema-simple.json', false, true);
        $errors = $validator->getValidationErrors();

        $this->assertTrue(is_array($array));
        $this->assertCount(0, $errors);
        $this->assertEquals($array['test'], 'hello');
    }

    protected function getJsonValidator() : JsonValidator
    {
        $locator = new FileLocator([ __DIR__ ]);
        return new JsonValidator($locator);
    }
}


text:
import { PipeTransform } from '@angular/core';
import { NgLocalization } from '../localization';
/**
 *  Maps a value to a string that pluralizes the value properly.
 *
 *  ## Usage
 *
 *  expression | i18nPlural:mapping
 *
 *  where `expression` is a number and `mapping` is an object that mimics the ICU format,
 *  see http://userguide.icu-project.org/formatparse/messages
 *
 *  ## Example
 *
 *  ```
 *  class MyLocalization extends NgLocalization {
 *    getPluralCategory(value: any) {
 *      if(value > 1) {
 *        return 'other';
 *      }
 *    }
 *  }
 *
 *  @Component({
 *    selector: 'app',
 *    template: `
 *      <div>
 *        {{ messages.length | i18nPlural: messageMapping }}
 *      </div>
 *    `,
 *    providers: [{provide: NgLocalization, useClass: MyLocalization}]
 *  })
 *
 *  class MyApp {
 *    messages: any[];
 *    messageMapping: {[k:string]: string} = {
 *      '=0': 'No messages.',
 *      '=1': 'One message.',
 *      'other': '# messages.'
 *    }
 *    ...
 *  }
 *  ```
 *
 * @experimental
 */
export declare class I18nPluralPipe implements PipeTransform {
    private _localization;
    constructor(_localization: NgLocalization);
    transform(value: number, pluralMap: {
        [count: string]: string;
    }): string;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings
        xmlns="http://java.sun.com/xml/ns/persistence/orm"
        version="2.0">

    <description>Override Annotations...</description>

    <entity class="io.quarkus.it.jpa.mapping.xml.legacy.library_b.LibraryBEntity" metadata-complete="false">
        <attributes>
            <basic name="name">
                <!-- Override the column name -->
                <column name="name_b" />
            </basic>
        </attributes>
    </entity>
</entity-mappings>


text:
erialin translating

tmux – A Powerful Terminal Multiplexer For Heavy Command-Line Linux User
======
tmux stands for terminal multiplexer, it allows users to create/enable multiple terminals (vertical & horizontal) in single window, this can be accessed and controlled easily from single window when you are working with different issues.

It uses a client-server model, which allows you to share sessions between users, also you can attach terminals to a tmux session back. We can easily move or rearrange the virtual console as per the need. Terminal sessions can freely rebound from one virtual console to another.

tmux depends on libevent and ncurses libraries. tmux offers status-line at the bottom of the screen which display information about your current tmux session suc[]h as current window number, window name, username, hostname, current time, and current date.

When tmux is started it creates a new session with a single window and displays it on screen. It allows users to create Any number of windows in the same session.

Many of us says it's similar to screen but i'm not since this offers wide range of configuration options.

**Make a note:** `Ctrl+b` is the default prefix in tmux so, to perform any action in tumx, you have to type the prefix first then required options.

**Suggested Read :** [List Of Terminal Emulator For Linux][1]

### tmux Features

  * Create any number of windows
  * Create any number of panes in the single window
  * It allows vertical and horizontal splits
  * Detach and Re-attach window
  * Server-client architecture which allows users to share sessions between users
  * tmux offers wide range of configuration hacks

**Suggested Read :**
**(#)** [tmate - Instantly Share Your Terminal Session To Anyone In Seconds][2]
**(#)** [Teleconsole - A Tool To Share Your Terminal Session Instantly To Anyone In Seconds][3]

### How to Install tmux Command

tmux command is pre-installed by default in most of the Linux systems. If no, follow the below procedure to get installed.

For **`Debian/Ubuntu`** , use [APT-GET Command][4] or [APT Command][5] to install tmux.
```
$ sudo apt install tmux

```

For **`RHEL/CentOS`** , use [YUM Command][6] to install tmux.
```
$ sudo yum install tmux

```

For **`Fedora`** , use [DNF Command][7] to install tmux.
```
$ sudo dnf install tmux

```

For **`Arch Linux`** , use [Pacman Command][8] to install tmux.
```
$ sudo pacman -S tmux

```

For **`openSUSE`** , use [Zypper Command][9] to install tmux.
```
$ sudo zypper in tmux

```

### How to Use tmux

kick start the tmux session by running following command on terminal. When tmux is started it creates a new session with a single window and will automatically login to your default shell with your user account.
```
$ tmux

```

[![][10]![][10]][11]

You will get similar to above screenshot like us. tmux comes with status bar which display an information's about current sessions details, date, time, etc.,.

The status bar information's are below:

  * **`0 :`** It is indicating the session number which was created by the tmux server. By default it starts with 0.
  * **`0:username@host: :`** 0 is indicating the session number. Username and Hostname which is holding the current window.
  * **`~ :`** It is indicating the current directory (We are in the Home directory)
  * **`* :`** This indicate that the window is active now.
  * **`Hostname :`** This shows fully qualified hostname of the server
  * **`Date& Time:`** It shows current date and time

### How to Split Window

tmux allows users to split window vertically and horizontally. Let 's see how to do that.

Press `**(Ctrl+b), %**` to split the pane vertically.
[![][10]![][10]][13]

Press `**(Ctrl+b), "**` to split the pane horizontally.
[![][10]![][10]][14]

### How to Move Between Panes

Lets say, we have created few panes and want to move between them. How to do that? If you don 't know how to do, then there is no purpose to use tmux. Use the following control keys to perform the actions. There are many ways to move between panes.

Press `(Ctrl+b), Left arrow` - To Move Left

Press `(Ctrl+b), Right arrow` - To Move Right

Press `(Ctrl+b), Up arrow` - To Move Up

Press `(Ctrl+b), Down arrow` - To Move Down

Press `(Ctrl+b), {` - To Move Left

Press `(Ctrl+b), }` - To Move Right

Press `(Ctrl+b), o` - Switch to next pane (left-to-right, top-down)

Press `(Ctrl+b), ;` - Move to the previously active pane.

For testing purpose, we are going to move between panes. Now, we are in the `pane2` which shows `lsb_release -a` command output.
[![][10]![][10]][15]

And we are going to move to `pane0` which shows `uname -a` command output.
[![][10]![][10]][16]

### How to Open/Create New Window

You can open any number of windows within one terminal. Terminal window can be split vertically & horizontally which is called `panes`. Each pane will contain its own, independently running terminal instance.

Press `(Ctrl+b), c` to create a new window.

Press `(Ctrl+b), n` move to the next window.

Press `(Ctrl+b), p` to move to the previous window.

Press `(Ctrl+b), (0-9)` to immediately move to a specific window.

Press `(Ctrl+b), l` Move to the previously selected window.

I have two windows, first window has three panes which contains operating system distribution information, top command output & kernal information.
[![][10]![][10]][17]

And second window has two panes which contains Linux distributions logo information. Use the following commands perform the action.
[![][10]![][10]][18]

Press `(Ctrl+b), w` Choose the current window interactively.
[![][10]![][10]][19]

### How to Zoom Panes

You are working in some pane which is very small and you want to zoom it out for further work. To do use the following key binds.

Currently we have three panes and i'm working in `pane1` which shows system activity using **Top** command and am going to zoom that.
[![][10]![][10]][17]

When you zoom a pane, it will hide all other panes and display only the zoomed pane in the window.
[![][10]![][10]][20]

Press `(Ctrl+b), z` to zoom the pane and press it again, to bring the zoomed pane back.

### Display Pane Information

To know about pane number and it's size, run the following command.

Press `(Ctrl+b), q` to briefly display pane indexes.
[![][10]![][10]][21]

### Display Window Information

To know about window number, layout size, number of panes associated with the window and it's size, etc., run the following command.

Just run `tmux list-windows` to view window information.
[![][10]![][10]][22]

### How to Resize Panes

You may want to resize the panes to fit your requirement. You have to press `(Ctrl+b), :` then type the following details on the `yellow` color bar in the bottom of the page.
[![][10]![][10]][23]

In the previous section we have print pane index which shows panes size as well. To test this we are going to increase `10 cells UPward`. See the following output that has increased the pane1 & pane2 size from `55x21` to `55x31`.
[![][10]![][10]][24]

**Syntax:** `(Ctrl+b), :` then type `resize-pane [options] [cells size]`

`(Ctrl+b), :` then type `resize-pane -D 10` to resize the current pane Down for 10 cells.

`(Ctrl+b), :` then type `resize-pane -U 10` to resize the current pane UPward for 10 cells.

`(Ctrl+b), :` then type `resize-pane -L 10` to resize the current pane Left for 10 cells.

`(Ctrl+b), :` then type `resize-pane -R 10` to resize the current pane Right for 10 cells.

### Detaching and Re-attaching tmux Session

One of the most powerful features of tmux is the ability to detach and reattach session whenever you need.

Run a long running process and press `Ctrl+b` followed by `d` to detach your tmux session safely by leaving the running process.

**Suggested Read :** [How To Keep A Process/Command Running After Disconnecting SSH Session][25]

Now, run a long running process. For demonstration purpose, we are going to move this server backup to another remote server for disaster recovery (DR) purpose.

You will get similar output like below after detached tmux session.
```
[detached (from session 0)]

```

Run the following command to list the available tmux sessions.
```
$ tmux ls
0: 3 windows (created Tue Jan 30 06:17:47 2018) [109x45]

```

Now, re-attach the tmux session using an appropriate session ID as follow.
```
$ tmux attach -t 0

```

### How to Close Panes & Window

Just type `exit` or hit `Ctrl-d` in the corresponding pane to close it. It's similar to terminal close. To close window, press `(Ctrl+b), &`.

--------------------------------------------------------------------------------

via: https://www.2daygeek.com/tmux-a-powerful-terminal-multiplexer-emulator-for-linux/

作者:[Magesh Maruthamuthu][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]:https://www.2daygeek.com/author/magesh/
[1]:https://www.2daygeek.com/category/terminal-emulator/
[2]:https://www.2daygeek.com/tmate-instantly-share-your-terminal-session-to-anyone-in-seconds/
[3]:https://www.2daygeek.com/teleconsole-share-terminal-session-instantly-to-anyone-in-seconds/
[4]:https://www.2daygeek.com/apt-get-apt-cache-command-examples-manage-packages-debian-ubuntu-systems/
[5]:https://www.2daygeek.com/apt-command-examples-manage-packages-debian-ubuntu-systems/
[6]:https://www.2daygeek.com/yum-command-examples-manage-packages-rhel-centos-systems/
[7]:https://www.2daygeek.com/dnf-command-examples-manage-packages-fedora-system/
[8]:https://www.2daygeek.com/pacman-command-examples-manage-packages-arch-linux-system/
[9]:https://www.2daygeek.com/zypper-command-examples-manage-packages-opensuse-system/
[10]:data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
[11]:https://www.2daygeek.com/wp-content/uploads/2018/01/tmux-a-powerful-terminal-multiplexer-emulator-for-linux-1.png
[13]:https://www.2daygeek.com/wp-content/uploads/2018/01/tmux-a-powerful-terminal-multiplexer-emulator-for-linux-2.png
[14]:https://www.2daygeek.com/wp-content/uploads/2018/01/tmux-a-powerful-terminal-multiplexer-emulator-for-linux-3.png
[15]:https://www.2daygeek.com/wp-content/uploads/2018/01/tmux-a-powerful-terminal-multiplexer-emulator-for-linux-4.png
[16]:https://www.2daygeek.com/wp-content/uploads/2018/01/tmux-a-powerful-terminal-multiplexer-emulator-for-linux-5.png
[17]:https://www.2daygeek.com/wp-content/uploads/2018/01/tmux-a-powerful-terminal-multiplexer-emulator-for-linux-8.png
[18]:https://www.2daygeek.com/wp-content/uploads/2018/01/tmux-a-powerful-terminal-multiplexer-emulator-for-linux-6.png
[19]:https://www.2daygeek.com/wp-content/uploads/2018/01/tmux-a-powerful-terminal-multiplexer-emulator-for-linux-7.png
[20]:https://www.2daygeek.com/wp-content/uploads/2018/01/tmux-a-powerful-terminal-multiplexer-emulator-for-linux-9.png
[21]:https://www.2daygeek.com/wp-content/uploads/2018/01/tmux-a-powerful-terminal-multiplexer-emulator-for-linux-10.png
[22]:https://www.2daygeek.com/wp-content/uploads/2018/01/tmux-a-powerful-terminal-multiplexer-emulator-for-linux-14.png
[23]:https://www.2daygeek.com/wp-content/uploads/2018/01/tmux-a-powerful-terminal-multiplexer-emulator-for-linux-11.png
[24]:https://www.2daygeek.com/wp-content/uploads/2018/01/tmux-a-powerful-terminal-multiplexer-emulator-for-linux-13.png
[25]:https://www.2daygeek.com/how-to-keep-a-process-command-running-after-disconnecting-ssh-session/


text:
var express = require('express');
var app = express();

app.use(express.static(__dirname + '/public'));

var hello = ["Hi", "Hello", "Hallo", "Bonjour"];

app.get('/hello', function(req, res)	{
    var randomHello = Math.floor(Math.random()*hello.length);
	res.json({"hello":hello[randomHello]});
});

app.listen(3000);

console.log('Listening on port 3000');


text:
namespace OpenStack.Services.Identity.V2
{
    using System.Collections.Immutable;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using OpenStack.ObjectModel;

    /// <summary>
    /// This class models the JSON representation of the access information returned by an HTTP API authentication
    /// request to the OpenStack Identity Service V2.
    /// </summary>
    /// <seealso cref="IIdentityService.PrepareAuthenticateAsync"/>
    /// <threadsafety static="true" instance="false"/>
    /// <preliminary/>
    [JsonObject(MemberSerialization.OptIn)]
    public class Access : ExtensibleJsonObject
    {
#pragma warning disable 649 // Field 'fieldName' is never assigned to, and will always have its default value {value}
        /// <summary>
        /// This is the backing field for the <see cref="Token"/> property.
        /// </summary>
        [JsonProperty("token", DefaultValueHandling = DefaultValueHandling.Ignore)]
        private Token _token;

        /// <summary>
        /// This is the backing field for the <see cref="ServiceCatalog"/> property.
        /// </summary>
        [JsonProperty("serviceCatalog", DefaultValueHandling = DefaultValueHandling.Ignore)]
        private ImmutableArray<ServiceCatalogEntry> _serviceCatalog;

        /// <summary>
        /// This is the backing field for the <see cref="User"/> property.
        /// </summary>
        [JsonProperty("user", DefaultValueHandling = DefaultValueHandling.Ignore)]
        private User _user;

        /// <summary>
        /// This is the backing field for the <see cref="Metadata"/> property.
        /// </summary>
        [JsonProperty("metadata", DefaultValueHandling = DefaultValueHandling.Ignore)]
        private ImmutableDictionary<string, JToken> _metadata;
#pragma warning restore 649

        /// <summary>
        /// Initializes a new instance of the <see cref="Access"/> class
        /// during JSON deserialization.
        /// </summary>
        [JsonConstructor]
        protected Access()
        {
        }

        /// <summary>
        /// Gets the authentication token used for authenticating HTTP API calls to services described in the
        /// <see cref="ServiceCatalog"/>.
        /// </summary>
        /// <value>
        /// <para>The authentication token used for authenticating HTTP API calls to services described in the
        /// <see cref="ServiceCatalog"/>.</para>
        /// <token>NullIfNotIncluded</token>
        /// </value>
        public Token Token
        {
            get
            {
                return _token;
            }
        }

        /// <summary>
        /// Gets a collection of <see cref="ServiceCatalogEntry"/> objects describing the services, regions, and
        /// endpoints available to an authenticated user.
        /// </summary>
        /// <value>
        /// <para>A collection of <see cref="ServiceCatalogEntry"/> objects describing the services, regions, and
        /// endpoints available to an authenticated user.</para>
        /// <token>DefaultArrayIfNotIncluded</token>
        /// </value>
        public ImmutableArray<ServiceCatalogEntry> ServiceCatalog
        {
            get
            {
                return _serviceCatalog;
            }
        }

        /// <summary>
        /// Gets a <see cref="V2.User"/> object containing information about the authenticated user.
        /// </summary>
        /// <value>
        /// <para>A <see cref="V2.User"/> object containing information about the authenticated user.</para>
        /// <token>NullIfNotIncluded</token>
        /// </value>
        public User User
        {
            get
            {
                return _user;
            }
        }

        /// <summary>
        /// Gets a collection of additional vendor-specific metadata related to the authentication information.
        /// </summary>
        /// <value>
        /// <para>A collection of additional vendor-specific metadata related to the authentication information.</para>
        /// <token>NullIfNotIncluded</token>
        /// </value>
        public ImmutableDictionary<string, JToken> Metadata
        {
            get
            {
                return _metadata;
            }
        }
    }
}


text:
package com.sequenceiq.cloudbreak.service.image;

import static com.sequenceiq.cloudbreak.common.type.ComponentType.CDH_PRODUCT_DETAILS;
import static com.sequenceiq.cloudbreak.common.type.ComponentType.CM_REPO_DETAILS;

import java.util.Set;
import java.util.stream.Collectors;

import com.sequenceiq.cloudbreak.cloud.model.ClouderaManagerProduct;
import com.sequenceiq.cloudbreak.cloud.model.ClouderaManagerRepo;
import com.sequenceiq.cloudbreak.cloud.model.component.StackType;
import com.sequenceiq.cloudbreak.common.json.Json;
import com.sequenceiq.cloudbreak.domain.stack.Component;
import com.sequenceiq.cloudbreak.domain.stack.Stack;

/**
 * Converts between various types and Component, where Component can be persisted to Component table in cbdb
 */
@org.springframework.stereotype.Component
public class ComponentConverter {

    public Set<Component> fromClouderaManagerProductList(Set<ClouderaManagerProduct> clouderaManagerProductList, Stack stack) {
        return clouderaManagerProductList.stream()
                .map(cmp -> fromClouderaManagerProduct(cmp, stack))
                .collect(Collectors.toSet());
    }

    public Component fromClouderaManagerRepo(ClouderaManagerRepo clouderaManagerRepo, Stack stack) {
        return new Component(CM_REPO_DETAILS, CM_REPO_DETAILS.name(), new Json(clouderaManagerRepo), stack);
    }

    private Component fromClouderaManagerProduct(ClouderaManagerProduct clouderaManagerProduct, Stack stack) {
        if (StackType.CDH.name().equals(clouderaManagerProduct.getName())) {
            return new Component(CDH_PRODUCT_DETAILS, CDH_PRODUCT_DETAILS.name(), new Json(clouderaManagerProduct), stack);
        }
        return new Component(CDH_PRODUCT_DETAILS, clouderaManagerProduct.getName(), new Json(clouderaManagerProduct), stack);
    }

}


text:
import pytest
# from snovault.schema_utils import load_schema

pytestmark = [pytest.mark.setone, pytest.mark.working, pytest.mark.schema]

@pytest.fixture
def biosample_cc_w_diff(testapp, de_term, lab, award):
    item = {
        "culture_start_date": "2018-01-01",
        "differentiation_state": "Differentiated to definitive endoderm demonstrated by decreased Oct4 expression and increased Sox17 expression",
        "tissue": de_term['@id'],
        "in_vitro_differentiated": "Yes",
        'award': award['@id'],
        'lab': lab['@id']
    }
    return testapp.post_json('/biosample_cell_culture', item).json['@graph'][0]

@pytest.fixture
def biosample_1(testapp, human_biosource, lab, award):
    item = {
        'description': "GM12878 prepared for Hi-C",
        'biosource': [human_biosource['@id'], ],
        'award': award['@id'],
        'lab': lab['@id'],
    }
    return testapp.post_json('/biosample', item).json['@graph'][0]

@pytest.fixture
def biosample_w_mod(testapp, biosample_1, mod_w_target):
    return testapp.patch_json(biosample_1['@id'], {'modifications': [mod_w_target['@id']]}).json['@graph'][0]

@pytest.fixture
def biosample_w_treatment(testapp, biosample_1, rnai):
    return testapp.patch_json(biosample_1['@id'], {'treatments': [rnai['@id']]}).json['@graph'][0]

def biosample_relation(derived_from):
    return {"biosample_relation": [{"relationship_type": "derived from",
            "biosample": derived_from['@id']}]}

def test_biosample_has_display_title(testapp, biosample_1):
    # accession fallback used for display title here
    assert biosample_1['display_title'] == biosample_1['accession']

# data from test/datafixtures
def test_update_biosample_relation(testapp, human_biosample, biosample_1):
    patch_res = testapp.patch_json(human_biosample['@id'], biosample_relation(biosample_1))
    res = testapp.get(biosample_1['@id'])
    # expected relation: 'biosample': human_biosample['@id'],
    #                    'relationship_type': 'parent of'
    assert res.json['biosample_relation'][0]['biosample']['@id'] == human_biosample['@id']
    assert res.json['biosample_relation'][0]['relationship_type'] == 'parent of'

def test_biosample_calculated_properties(testapp, biosample_1, ):
    """
    Test to ensure the calculated properties are in result returned from testapp
    These have string 'None' returned if no value as they are used in Item page view
    """
    res = testapp.get(biosample_1['@id']).json
    assert 'modifications_summary' in res
    assert 'modifications_summary_short' in res
    assert 'treatments_summary' in res
    assert 'biosource_summary' in res

def test_biosample_biosource_summary_one_biosource(testapp, biosample_1, human_biosource):
    assert biosample_1['biosource_summary'] == human_biosource['biosource_name']

def test_biosample_biosource_summary_two_biosource(testapp, biosample_1, human_biosource, lung_biosource):
    res = testapp.patch_json(biosample_1['@id'], {'biosource': [human_biosource['@id'], lung_biosource['@id']]}).json['@graph'][0]
    assert human_biosource['biosource_name'] in res['biosource_summary']
    assert lung_biosource['biosource_name'] in res['biosource_summary']
    assert ' and ' in res['biosource_summary']

def test_biosample_biosource_summary_w_differentiation(testapp, biosample_1, human_biosource, biosample_cc_w_diff, de_term):
    res = testapp.patch_json(biosample_1['@id'], {'cell_culture_details': [biosample_cc_w_diff['@id']]}).json['@graph'][0]
    assert human_biosource['biosource_name'] in res['biosource_summary']
    assert ' differentiated to ' in res['biosource_summary']
    assert de_term['display_title'] in res['biosource_summary']

def test_biosample_sample_type_w_differentiation(testapp, biosample_1, biosample_cc_w_diff):
    res = testapp.patch_json(biosample_1['@id'], {'cell_culture_details': [biosample_cc_w_diff['@id']]}).json['@graph'][0]
    assert res['biosample_type'] == 'in vitro differentiated cells'

def test_biosample_sample_type_immortalized_wo_differentiation(testapp, biosample_1, biosample_cc_wo_diff):
    res = testapp.patch_json(biosample_1['@id'], {'cell_culture_details': [biosample_cc_wo_diff['@id']]}).json['@graph'][0]
    assert res['biosample_type'] == 'immortalized cells'

def test_biosample_sample_type_bs_stem_cell_line(testapp, biosample_1, human_biosource):
    bsres = testapp.patch_json(human_biosource['@id'], {'biosource_type': 'stem cell derived cell line'}).json['@graph'][0]
    res = testapp.patch_json(biosample_1['@id'], {'biosource': [bsres['@id']]}).json['@graph'][0]
    assert res['biosample_type'] == 'stem cells'

def test_biosample_sample_type_bs_multicellular(testapp, biosample_1, human_biosource):
    bsres = testapp.patch_json(human_biosource['@id'], {'biosource_type': 'multicellular organism'}).json['@graph'][0]
    res = testapp.patch_json(biosample_1['@id'], {'biosource': [bsres['@id']]}).json['@graph'][0]
    assert res['biosample_type'] == 'whole organisms'

def test_biosample_sample_type_bs_tissue(testapp, biosample_1, human_biosource):
    bty = 'tissue'
    bsres = testapp.patch_json(human_biosource['@id'], {'biosource_type': bty}).json['@graph'][0]
    res = testapp.patch_json(biosample_1['@id'], {'biosource': [bsres['@id']]}).json['@graph'][0]
    assert res['biosample_type'] == bty

def test_biosample_sample_type_bs_lines_and_to_pluralize(testapp, biosample_1, human_biosource):
    types = {
        "primary cell": "primary cells",
        "primary cell line": "primary cells",
        "immortalized cell line": "immortalized cells",
        "stem cell": "stem cells",
        "induced pluripotent stem cell": "induced pluripotent stem cells"
    }
    for bty, bsty in types.items():
        bsres = testapp.patch_json(human_biosource['@id'], {'biosource_type': bty}).json['@graph'][0]
        res = testapp.patch_json(biosample_1['@id'], {'biosource': [bsres['@id']]}).json['@graph'][0]
        assert res['biosample_type'] == bsty

def test_biosample_sample_type_bs_multiple_same_type(testapp, biosample_1, human_biosource, GM12878_biosource):
    res = testapp.patch_json(biosample_1['@id'], {'biosource': [human_biosource['@id'], GM12878_biosource['@id']]}).json['@graph'][0]
    assert res['biosample_type'] == 'immortalized cells'

def test_biosample_sample_type_bs_multiple_diff_types(testapp, biosample_1, human_biosource, lung_biosource):
    res = testapp.patch_json(biosample_1['@id'], {'biosource': [human_biosource['@id'], lung_biosource['@id']]}).json['@graph'][0]
    assert res['biosample_type'] == 'mixed sample'

def test_biosample_modifications_summaries(biosample_w_mod):
    assert biosample_w_mod['modifications_summary'] == 'Crispr for RAD21 gene'
    assert biosample_w_mod['modifications_summary_short'] == 'RAD21 Crispr'

def test_biosample_modifications_summaries_no_mods(biosample_1):
    assert biosample_1.get('modifications_summary') == 'None'
    assert biosample_1.get('modifications_summary_short') == 'None'

def test_biosample_treatments_summary(biosample_w_treatment):
    assert biosample_w_treatment.get('treatments_summary') == 'shRNA treatment'

def test_biosample_treatments_summary_no_treatment(biosample_1):
    assert biosample_1.get('treatments_summary') == 'None'

def test_biosample_category_undifferentiated_stem_cells(testapp, biosample_1, human_biosource):
    scl = testapp.patch_json(human_biosource['@id'], {'biosource_type': 'stem cell derived cell line'}).json['@graph'][0]
    bios = testapp.patch_json(biosample_1['@id'], {'biosource': [scl['@id']]}).json['@graph'][0]
    assert 'Human stem cell' in bios.get('biosample_category')

def test_biosample_category_differentiated_stem_cells(testapp, biosample_1, human_biosource, biosample_cc_w_diff):
    scl = testapp.patch_json(human_biosource['@id'], {'biosource_type': 'stem cell derived cell line'}).json['@graph'][0]
    bios = testapp.patch_json(biosample_1['@id'], {'biosource': [scl['@id']], 'cell_culture_details': [biosample_cc_w_diff['@id']]}).json['@graph'][0]
    cats = bios.get('biosample_category')
    assert 'Human stem cell' not in cats
    assert 'In vitro Differentiation' in cats

def test_biosample_biosource_category_two_biosource(testapp, biosample_1, human_biosource, lung_biosource):
    res = testapp.patch_json(biosample_1['@id'], {'biosource': [human_biosource['@id'], lung_biosource['@id']]}).json['@graph'][0]
    cat = res.get('biosample_category')
    assert len(cat) == 1
    assert cat[0] == 'Mixed samples'

# setting up fixtures for testing tissue and organ calcprop
@pytest.fixture
def brain_term(testapp, uberon_ont, cns_term, ectoderm_term):
    item = {
        "is_slim_for": "organ",
        "term_id": "brain_tid",
        "term_name": "brain",
        "source_ontologies": [uberon_ont['@id']],
        "slim_terms": [cns_term['@id'], ectoderm_term['@id']]
    }
    return testapp.post_json('/ontology_term', item).json['@graph'][0]

@pytest.fixture
def cns_term(testapp, uberon_ont, ectoderm_term):
    item = {
        "is_slim_for": "system",
        "term_id": "cns_tid",
        "term_name": "central nervous system",
        "source_ontologies": [uberon_ont['@id']],
        "slim_terms": [ectoderm_term['@id']]
    }
    return testapp.post_json('/ontology_term', item).json['@graph'][0]

@pytest.fixture
def ectoderm_term(testapp, uberon_ont):
    item = {
        "is_slim_for": "developmental",
        "term_id": "ectoderm_tid",
        "term_name": "ectoderm",
        "source_ontologies": [uberon_ont['@id']],
    }
    return testapp.post_json('/ontology_term', item).json['@graph'][0]

@pytest.fixture
def primary_cell_term(testapp, ontology):
    item = {
        "is_slim_for": "cell",
        "term_id": "pcell_id",
        "term_name": "primary cell",
        "source_ontologies": [ontology['@id']],
    }
    return testapp.post_json('/ontology_term', item).json['@graph'][0]

@pytest.fixture
def cortical_neuron_term(testapp, uberon_ont, brain_term, cns_term,
                         ectoderm_term, primary_cell_term):
    item = {
        "term_id": "cort_neuron_id",
        "term_name": "cortical neuron",
        "source_ontologies": [uberon_ont['@id']],
        "slim_terms": [brain_term['@id'], cns_term['@id'], ectoderm_term['@id'], primary_cell_term['@id']]
    }
    return testapp.post_json('/ontology_term', item).json['@graph'][0]

@pytest.fixture
def bcc_diff_to_cortical(testapp, lab, award, cortical_neuron_term):
    item = {
        "culture_start_date": "2018-01-01",
        "differentiation_state": "Stem cell differentiated to cortical neuron",
        "tissue": cortical_neuron_term['@id'],
        "in_vitro_differentiated": "Yes",
        'award': award['@id'],
        'lab': lab['@id']
    }
    return testapp.post_json('/biosample_cell_culture', item).json['@graph'][0]

@pytest.fixture
def diff_cortical_neuron_bs(testapp, F123_biosource, bcc_diff_to_cortical, lab, award):
    item = {
        "description": "Differentiated cortical neuron",
        "biosource": [F123_biosource['@id']],
        "cell_culture_details": [bcc_diff_to_cortical['@id']],
        "award": award['@id'],
        "lab": lab['@id']
    }
    return testapp.post_json('/biosample', item).json['@graph'][0]

@pytest.fixture
def brain_biosource(testapp, brain_term, lab, award):
    item = {
        "description": "Brain tissue",
        "biosource_type": "tissue",
        "tissue": brain_term['@id'],
        "lab": lab['@id'],
        "award": award['@id']
    }
    return testapp.post_json('/biosource', item).json['@graph'][0]

@pytest.fixture
def brain_biosample(testapp, brain_biosource, lab, award):
    item = {
        "description": "Brain Tissue Biosample",
        "biosource": [brain_biosource['@id']],
        "award": award['@id'],
        "lab": lab['@id']
    }
    return testapp.post_json('/biosample', item).json['@graph'][0]

@pytest.fixture
def mixed_biosample(testapp, brain_biosource, lung_biosource, lab, award):
    item = {
        "description": "Mixed Tissue Biosample",
        "biosource": [brain_biosource['@id'], lung_biosource['@id']],
        "award": award['@id'],
        "lab": lab['@id']
    }
    return testapp.post_json('/biosample', item).json['@graph'][0]

def test_get_tissue_organ_info_none_present(biosample_1):
    assert 'tissue_organ_info' not in biosample_1

def test_get_tissue_organ_info_tissue_in_cell_culture(diff_cortical_neuron_bs, cortical_neuron_term):
    org_sys = sorted(['brain', 'central nervous system', 'ectoderm'])
    assert 'tissue_organ_info' in diff_cortical_neuron_bs
    assert diff_cortical_neuron_bs['tissue_organ_info']['tissue_source'] == cortical_neuron_term.get('display_title')
    assert sorted(diff_cortical_neuron_bs['tissue_organ_info']['organ_system']) == org_sys

def test_get_tissue_organ_info_tissue_in_biosource(brain_biosample, brain_term):
    org_sys = sorted(['central nervous system', 'ectoderm'])
    assert 'tissue_organ_info' in brain_biosample
    assert brain_biosample['tissue_organ_info']['tissue_source'] == brain_term.get('display_title')
    assert sorted(brain_biosample['tissue_organ_info']['organ_system']) == org_sys

def test_get_tissue_organ_info_tissue_mixed_biosample(mixed_biosample):
    org_sys = sorted(['central nervous system', 'ectoderm'])
    assert 'tissue_organ_info' in mixed_biosample
    assert mixed_biosample['tissue_organ_info']['tissue_source'] == 'mixed tissue'
    assert sorted(mixed_biosample['tissue_organ_info']['organ_system']) == org_sys

def test_get_tissue_organ_info_none_if_only_cell_slim_terms(testapp, F123_biosource, lab, award):
    item = {
        "description": "F123 Biosample",
        "biosource": [F123_biosource['@id']],
        "award": award['@id'],
        "lab": lab['@id']
    }
    f123_biosample = testapp.post_json('/biosample', item).json['@graph'][0]
    assert 'tissue_organ_info' not in f123_biosample


text:
package yitian.study.java8.datetime;

import java.time.*;
import java.time.chrono.Chronology;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.TemporalQueries;
import java.time.temporal.TemporalQuery;
import java.util.Date;

public class DateTimeSample {
    static void oldDate() {
        Date date = new Date();
        System.out.println(date);
    }

    static void newDateTime() {
        //日期
        LocalDate date = LocalDate.now();
        System.out.println(date);
        //时间
        LocalTime time = LocalTime.now();
        System.out.println(time);
        //日期时间
        LocalDateTime dateTime = LocalDateTime.now();
        System.out.println(dateTime);
        LocalDate birthday = LocalDate.of(1994, Month.JANUARY, 18);

    }

    static void datetimeOperations() {
        //日期运算
        LocalDate date = LocalDate.of(1993, 12, 25);
        //十天以后
        LocalDate dateAfter10Days = date.plusDays(10);
        System.out.println("十天以后:" + dateAfter10Days);
        //一个月前
        LocalDate dateBefore1Month = date.minusMonths(1);
        System.out.println("一个月前:" + dateBefore1Month);
        //这个月的最后一天
        LocalDate lastDayOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println("这个月最后一天:" + lastDayOfMonth);
        //今年第一天
        System.out.println("今年第一天:" + date.with(TemporalAdjusters.firstDayOfYear()));

        //查询
        TemporalQuery<Integer> remainDaysOfYear = temporal -> {
            LocalDate d = LocalDate.from(temporal);
            LocalDate lastDayOfYear = d.with(TemporalAdjusters.lastDayOfYear());
            Period period = d.until(lastDayOfYear);
            return period.getDays();
        };
        int days = date.query(remainDaysOfYear);
        System.out.println("到年底还剩几天:" + days);

    }

    static void formatDateTime() {
        LocalDateTime datetime = LocalDateTime.now();
        //默认toString方法
        System.out.println(datetime);

        //手动格式化
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println(
                datetime.format(formatter));

        //字符串到对象
        datetime = LocalDateTime.from(formatter.parse("1993-11-25 12:00:15"));
        System.out.println(datetime);
    }

    static void transformBetweenNewAndOld() {
        //旧日期转换为新日期
        Date date = new Date();
        LocalDateTime dateTime = LocalDateTime.ofInstant(date.toInstant()
                , ZoneId.of("Asia/Shanghai"));
        System.out.println(dateTime);

        //新日期转换为旧日期
        Date now = Date.from(Instant.now());
        System.out.println(now);
    }

    public static void main(String[] args) {
        oldDate();
        System.out.println("----------------");
        newDateTime();
        System.out.println("----------------");
        datetimeOperations();
        System.out.println("----------------");
        formatDateTime();
        System.out.println("----------------");
        transformBetweenNewAndOld();
    }
}


text:
	<title>Michael Sheen's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Michael Sheen's panel show appearances

Michael Sheen (born 1969-02-05[ref]) has appeared in 2 episodes between 2013-2015.  Michael Sheen on IMDB. Michael Sheen on Wikipedia.

2013

2014

2015

2015-10-23 / Have I Got News For You

2013-10-28 / Loose Women


text:
import React from 'react';

import {
  TabLinks,
  TabContainer
} from '../primitives';

import {
  WithCache,
  WithCachedState,
  CachedComponent
} from '../cached';

import css from './MultiSheetTab.less';

export class MultiSheetTab extends CachedComponent {

  constructor(props) {
    super(props);

    this.editorRef = React.createRef();
  }

  /**
   * React to current sheet provider reporting
   * changed sheets.
   */
  sheetsChanged = (newSheets, newActiveSheet) => {
    let {
      activeSheet,
      sheets
    } = this.getCached();

    if (!sheets) {
      sheets = [];
    }

    const provider = activeSheet.provider;

    const wiredNewSheets = newSheets.map(newSheet => {
      return {
        ...newSheet,
        provider
      };
    });

    sheets = sheets
      .filter(sheet => sheet.provider !== provider)
      .concat(wiredNewSheets)
      .map(t => ({ ...t, order: t.order || 0 }))
      .sort((a, b) => a.order - b.order);

    if (newActiveSheet) {
      activeSheet = sheets.find(s => s.id === newActiveSheet.id);
    }

    this.setCached({
      sheets,
      activeSheet
    });
  }

  handleChanged = (newState = {}) => {
    const {
      onChanged
    } = this.props;

    const dirty = this.isDirty(newState);

    onChanged({
      ...newState,
      dirty
    });
  }

  handleError = (error) => {
    const {
      onError
    } = this.props;

    onError(error);
  }

  handleWarning = (warning) => {
    const {
      onWarning
    } = this.props;

    onWarning(warning);
  }

  /**
   * Check wether or not tab is dirty.
   *
   * @param {Object} state - Editor state.
   *
   * @returns {boolean}
   */
  isDirty(state = {}) {
    const { dirty } = state;

    if (dirty) {
      return true;
    }

    const { xml } = this.props;

    const { lastXML } = this.getCached();

    if (!lastXML) {
      return false;
    }

    return isXMLChange(lastXML, xml);
  }

  async showImportErrorDialog(error) {
    const {
      onAction,
      tab
    } = this.props;

    const {
      name,
      type
    } = tab;

    const { button } = await onAction('show-dialog', getErrorDialog({
      error,
      name,
      type
    }));

    if (button === 'ask-in-forum') {
      onAction('open-external-url', {
        url: 'https://forum.camunda.org/c/modeler'
      });
    }
  }

  handleImport = (error, warnings) => {

    if (warnings && warnings.length) {
      warnings.forEach(warning => {
        this.handleWarning(warning);
      });

      if (!error) {
        this.displayImportWarningsNotification(warnings);
      }
    }

    if (error) {
      this.openFallback();

      this.showImportErrorDialog(error);

      this.handleError(error);
    }
  }

  displayImportWarningsNotification(warnings) {
    this.props.onAction('display-notification', {
      type: 'warning',
      title: `Imported with ${warnings.length} warning${warnings.length !== 1 ? 's' : ''}`,
      content: 'See further details in the log.',
      duration: 0
    });
  }

  /**
   * Open fallback sheet if provided.
   */
  openFallback() {

    let {
      sheets
    } = this.getCached();

    if (!sheets) {
      sheets = this.getDefaultSheets();
    }

    const fallback = sheets.find(sheet => {
      const {
        provider
      } = sheet;

      return provider.isFallback;
    });

    if (fallback) {
      this.setCached({
        activeSheet: fallback
      });
    }
  }

  handleContentUpdated = xml => {
    this.setCached({
      lastXML: xml
    });
  }

  handleContextMenu = (event, context) => {

    const {
      activeSheet
    } = this.getCached();

    const {
      onContextMenu
    } = this.props;

    if (typeof onContextMenu === 'function') {
      onContextMenu(event, activeSheet.type, context);
    }

  }

  handleLayoutChanged = (newLayout) => {
    const {
      onLayoutChanged
    } = this.props;

    onLayoutChanged(newLayout);
  }

  triggerAction = async (action, options) => {

    const editor = this.editorRef.current;

    if (action === 'save') {
      const xml = await editor.getXML();

      this.setCached({
        lastXML: xml
      });

      return xml;
    } else if (action === 'export-as') {
      const { fileType } = options;

      return await editor.exportAs(fileType);
    }

    return editor.triggerAction(action, options);
  }

  switchSheet = async (sheet) => {
    const {
      activeSheet
    } = this.getCached();

    if (sheet === activeSheet) {
      return;
    }

    if (sheet.provider === activeSheet.provider) {
      return this.setCached({
        activeSheet: sheet
      });
    }

    const xml = await this.editorRef.current.getXML();

    this.setCached({
      activeSheet: sheet,
      lastXML: xml
    });

    this.props.onAction('emit-event', {
      type: 'tab.activeSheetChanged',
      payload: { activeSheet: sheet }
    });
  }

  getDefaultSheets = () => {
    const {
      providers
    } = this.props;

    return providers.map((provider) => {

      const {
        defaultName,
        type
      } = provider;

      return {
        id: type,
        name: defaultName,
        isDefault: true,
        provider,
        type
      };
    });
  }

  componentDidMount() {
    let { sheets } = this.getCached();

    if (!sheets) {
      sheets = this.getDefaultSheets();

      this.setCached({
        sheets,
        activeSheet: sheets[0]
      });
    }
  }

  componentDidUpdate(prevProps) {
    const { xml } = this.props;

    if (isXMLChange(prevProps.xml, xml)) {
      this.setCached({
        lastXML: xml
      });
    }
  }

  isUnsaved = (tab) => {
    const { file } = tab;

    return file && !file.path;
  }

  onAction = (action, options) => {
    const {
      onAction,
      tab
    } = this.props;

    if (action === 'close-tab') {
      return onAction('close-tab', { tabId: tab.id });
    }

    return onAction(action, options);
  }

  render() {
    let {
      activeSheet,
      sheets,
      lastXML
    } = this.getCached();

    let {
      id,
      xml,
      layout,
      tab
    } = this.props;

    if (!sheets) {
      sheets = this.getDefaultSheets();
    }

    if (!activeSheet) {
      activeSheet = sheets[0];
    }

    const Editor = activeSheet.provider.editor;

    const isNew = this.isUnsaved(tab);

    return (
      <div className={ css.MultiSheetTab }>
        <TabContainer className="content tab">
          <Editor
            ref={ this.editorRef }
            id={ `${id}-${activeSheet.provider.type}` }
            xml={ lastXML || xml }
            isNew={ isNew }
            layout={ layout }
            activeSheet={ activeSheet }
            onSheetsChanged={ this.sheetsChanged }
            onContextMenu={ this.handleContextMenu }
            onAction={ this.onAction }
            onChanged={ this.handleChanged }
            onContentUpdated={ this.handleContentUpdated }
            onError={ this.handleError }
            onImport={ this.handleImport }
            onLayoutChanged={ this.handleLayoutChanged }
            onModal={ this.props.onModal }
            getConfig={ this.props.getConfig }
            setConfig={ this.props.setConfig }
            getPlugins={ this.props.getPlugins }
          />
        </TabContainer>

        <TabLinks
          className="secondary links"
          tabs={ sheets }
          activeTab={ activeSheet }
          onSelect={ this.switchSheet } />

      </div>
    );
  }

}

export default WithCache(WithCachedState(MultiSheetTab));

// helper //////////

function getErrorDialog({
  error,
  name,
  type
}) {
  return {
    type: 'error',
    title: 'Import Error',
    message: 'Ooops!',
    buttons: [{
      id: 'close',
      label: 'Close'
    }, {
      id: 'ask-in-forum',
      label: 'Ask in Forum'
    }],
    detail: [
      error.message,
      '',
      'Do you believe "' + name + '" is valid ' + type.toUpperCase() + ' diagram?',
      '',
      'Post this error with your diagram in our forum for help.'
    ].join('\n')
  };
}

function isXMLChange(prevXML, xml) {
  return prevXML !== xml;
}


text:
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var WSDLElement = require('./wsdlElement');

var PortType = function (_WSDLElement) {
  _inherits(PortType, _WSDLElement);

  function PortType(nsName, attrs, options) {
    _classCallCheck(this, PortType);

    return _possibleConstructorReturn(this, (PortType.__proto__ || Object.getPrototypeOf(PortType)).call(this, nsName, attrs, options));
  }

  _createClass(PortType, [{
    key: 'postProcess',
    value: function postProcess(definitions) {
      if (this.operations) return;
      this.operations = {};
      var children = this.children;
      if (typeof children === 'undefined') return;
      for (var i = 0, child; child = children[i]; i++) {
        if (child.name !== 'operation') continue;
        child.postProcess(definitions);
        this.operations[child.$name] = child;
      }
    }
  }, {
    key: 'describe',
    value: function describe(definitions) {
      var operations = {};
      for (var name in this.operations) {
        var method = this.operations[name];
        operations[name] = method.describe(definitions);
      }
      return operations;
    }
  }]);

  return PortType;
}(WSDLElement);

PortType.elementName = 'portType';
PortType.allowedChildren = ['operation', 'documentation'];

module.exports = PortType;


text:
  Arnaldo Oliveira Founder & Managing Director
  Orion Executive Search December 2010 – Present (5 years 9 months)

  Established in December 2010 - Asia focus executive search firm. Orion Executive
  Search covers the following: Countries: Australia, China, Hong Kong, Japan, Singapore,
  US, UK.

  Interview with a Recruiter who specializes in Finance/Finance IT Sales roles
  and IT Positions

0:00 How did you get into Recruiting?

  Interview Question 1

  1:30 Do you specialize in any segment of the recruitment market?

  Interview Question 2

  2:15 Do you find that companies are looking for candidates that are local to
  the home market?
  Interview Question 3

  3:05 What kind of candidates do you look for or do companies generally look for?

  Interview Question 4

3:41 What kind of roles are companies asking you to fill?

  Interview Question 5

  4:45 Do you have any advice for people looking to get into sales or moving into
  a sales role from a sales support role?

  Interview Question 6

5:18 So you can screen people first?

  Interview Question 7

  5:36 Any industry has a software or tool aimed at it? Do you handle those types
  of searches?

  Interview Question 8

  6:44 Do you find in Japan that you need to give more advice on changing jobs?

  Interview Question 9

  8:20 Do you find that people are looking for a high-level of English-level fluency?

  Interview Question 10

9:11 Is there any advice for people who want to relocate?

  Interview Question 11


text:
const welcomeDiv = document.getElementById("WelcomeMessage");
const signInButton = document.getElementById("SignIn");
const popupButton = document.getElementById("popup");
const redirectButton = document.getElementById("redirect");
const cardDiv = document.getElementById("card-div");
const mailButton = document.getElementById("readMail");
const profileButton = document.getElementById("seeProfile");
const profileDiv = document.getElementById("profile-div");

function showWelcomeMessage(account) {
    // Reconfiguring DOM elements
    cardDiv.style.display = 'initial';
    welcomeDiv.innerHTML = `Welcome ${account.username}`;
    signInButton.setAttribute('class', "btn btn-success dropdown-toggle");
    signInButton.innerHTML = "Sign Out";
    popupButton.setAttribute('onClick', "signOut(this.id)");
    popupButton.innerHTML = "Sign Out with Popup";
    redirectButton.setAttribute('onClick', "signOut(this.id)");
    redirectButton.innerHTML = "Sign Out with Redirect";
}

function updateUI(data, endpoint) {
    console.log('Graph API responded at: ' + new Date().toString());

    if (endpoint === graphConfig.graphMeEndpoint) {
        const title = document.createElement('p');
        title.innerHTML = "Title: " + data.jobTitle;
        const email = document.createElement('p');
        email.innerHTML = "Mail: " + data.mail;
        const phone = document.createElement('p');
        phone.innerHTML = "Phone: " + data.businessPhones[0];
        const address = document.createElement('p');
        address.innerHTML = "Location: " + data.officeLocation;
        profileDiv.innerHTML = "";
        profileDiv.appendChild(title);
        profileDiv.appendChild(email);
        profileDiv.appendChild(phone);
        profileDiv.appendChild(address);
    }
}


text:
![1 stars](../../images/ic_star_black_18dp_1x.png)![1 stars](../../images/ic_star_border_black_18dp_1x.png)![1 stars](../../images/ic_star_border_black_18dp_1x.png)![1 stars](../../images/ic_star_border_black_18dp_1x.png)![1 stars](../../images/ic_star_border_black_18dp_1x.png) 5

To use the HighOrLow skill, try saying...

* *Alexa, open high or low*

* *Alexa, launch high or low*

Speaking a number will prompt Alexa to ask you if a number is higher than the chosen number or lower than the chosen number.

***

### Skill Details

* **Invocation Name:** high or low
* **Category:** null
* **ID:** amzn1.ask.skill.59a1dcd4-1431-4615-9846-30025a292f0c
* **ASIN:** B01MYMX7MX
* **Author:** Hop-A-Ride
* **Release Date:** November 25, 2016 @ 08:35:25
* **In-App Purchasing:** No


text:
import flask
import json
import mimetypes
import socket
import traceback

from novaclient import exceptions as nova_exceptions
from cinderclient import exceptions as cinder_exceptions
from tukey_middleware import utils

TENANT_CLIENTS = ["python-novaclient", "python-cinderclient"]

def set_api_manager(blueprint, registry, logger=utils.get_logger()):
    blueprint.registry = registry
    blueprint.api_manager = ApiManager(registry, logger)
    return blueprint

class ApiManager(object):
    '''  Collection of utility methods for converting
    from the code API to the HTTP API '''

    def __init__(self, registry, logger):
        self.registry = registry
        self.logger = logger

    def tag(self, item, cloud):
        try:
            item["cloud_id"] = cloud.cloud_id
            item["cloud"] = cloud.cloud
        except TypeError as e:
            item = [dict(i.items() + {"cloud_id": cloud.cloud_id,
                "cloud": cloud.cloud}.items())
                    for i in item]
        return item

    def _list_tagged(self, items, cloud):
        for i in items:
            i = self.tag(i, cloud)
        return items

    def list_for_all(self, name, callback):
        '''run method on each cloud then aggregate the results'''
        resources = []
        for cloud in self.registry.all_clouds(flask.g.auth_token):
            try:
                self.logger.debug("listing all for the cloud %s", cloud)
                resources += self._list_tagged(callback(cloud), cloud)
            except socket.error as sock_err:
                self.logger.warn("socket error %s connecting to %s" %
                        (sock_err, cloud))

        items = json.dumps({name: resources})
        return items

    def name_and_cloud_from_name(self, cloud_and_name):
        cloud = cloud_and_name.split('-')[0]
        name = cloud_and_name[len(cloud) + 1:]
        return name, cloud

    def do_action(self, name, item, callback):
        item["name"], cloud_name = self.name_and_cloud_from_name(item["name"])
        cloud = self.registry.get_cloud_by_id(cloud_name, flask.g.auth_token)
        resources = callback(cloud, item)
        return json.dumps({name: resources})

    def get_item(self, name, callback):
        item = None
        for cloud in self.registry.all_clouds(flask.g.auth_token):
            try:
                item = callback(cloud)
                if item:
                    return json.dumps({name: self.tag(item, cloud)})
            except (nova_exceptions.NotFound, cinder_exceptions.NotFound):
                pass
        raise nova_exceptions.NotFound(404)

    def all_clouds(self):
        return self.registry.all_clouds(flask.g.auth_token)

    def get_cloud_by_id(self, cloud_name):
        return self.registry.get_cloud_by_id(cloud_name, flask.g.auth_token)

    def get_cloud_from_item(self, callback):
        item = None
        for cloud in self.registry.all_clouds(flask.g.auth_token):
            try:
                item = callback(cloud)
                if item:
                    return cloud
            except (nova_exceptions.NotFound, cinder_exceptions.NotFound):
                pass
        raise nova_exceptions.NotFound(404)

class Rest(flask.Blueprint):

    def get(self, rule, status_code=200):
        return self._mroute('GET', rule, status_code)

    def post(self, rule, status_code=200):
        return self._mroute('POST', rule, status_code)

    def put(self, rule, status_code=200):
        return self._mroute('PUT', rule, status_code)

    def delete(self, rule, status_code=200):
        return self._mroute('DELETE', rule, status_code)

    def _mroute(self, methods, rule, status_code=None, **kw):
        if type(methods) is str:
            methods = [methods]
        return self.route(rule, methods=methods, status_code=status_code, **kw)

    def route(self, rule, **options):
        status = options.pop('status_code', None)
        file_upload = options.pop('file_upload', False)

        def decorator(func):
            endpoint = options.pop('endpoint', func.__name__)

            def handler(**kwargs):
                # extract response content type
                resp_type = flask.request.accept_mimetypes
                type_suffix = kwargs.pop('resp_type', None)
                if type_suffix:
                    suffix_mime = mimetypes.guess_type("res." + type_suffix)[0]
                    if suffix_mime:
                        resp_type = datastructures.MIMEAccept(
                            [(suffix_mime, 1)])
                flask.request.resp_type = resp_type
                flask.request.file_upload = file_upload

                # update status code
                if status:
                    flask.request.status_code = status

                try:
                    if flask.request.headers["user-agent"] in TENANT_CLIENTS:
                        kwargs.pop("tenant_id")
                except KeyError:
                    kwargs.pop("tenant_id")

                try:
                    flask.g.auth_token = flask.request.headers['X-Auth-Token']
                except Exception:
                    return flask.abort(401)

                if flask.request.method in ['POST', 'PUT']:
                    kwargs['data'] = flask.request.data

                try:
                    return func(**kwargs)
                except nova_exceptions.ClientException as exc:

                    return json.dumps({"error": {"message": exc.message,
                            "code": exc.http_status}}), exc.http_status
                except Exception as e:
                    # Something happened that we didn't expect at all this will
                    # likely need to be debugged and fixed. Let's make sure that
                    # people can see this error without having to look too hard.
                    error_message = traceback.format_exc()
                    print error_message
                    logger = utils.get_logger()
                    logger.error(error_message)

            self.add_url_rule(rule, endpoint, handler, **options)
            f_rule = "/<tenant_id>" + rule
            self.add_url_rule(f_rule, endpoint, handler, **options)
            ext_rule = f_rule + '.<resp_type>'
            self.add_url_rule(ext_rule, endpoint, handler, **options)

            return func

        return decorator


text:
#include "shrpx_http2_downstream_connection.h"

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif // HAVE_UNISTD_H

#include "http-parser/http_parser.h"

#include "shrpx_client_handler.h"
#include "shrpx_upstream.h"
#include "shrpx_downstream.h"
#include "shrpx_config.h"
#include "shrpx_error.h"
#include "shrpx_http.h"
#include "shrpx_http2_session.h"
#include "http2.h"
#include "util.h"

using namespace nghttp2;

namespace shrpx {

Http2DownstreamConnection::Http2DownstreamConnection(
    DownstreamConnectionPool *dconn_pool, Http2Session *http2session)
    : DownstreamConnection(dconn_pool), dlnext(nullptr), dlprev(nullptr),
      http2session_(http2session), sd_(nullptr) {}

Http2DownstreamConnection::~Http2DownstreamConnection() {
  if (LOG_ENABLED(INFO)) {
    DCLOG(INFO, this) << "Deleting";
  }
  if (downstream_) {
    downstream_->disable_downstream_rtimer();
    downstream_->disable_downstream_wtimer();

    uint32_t error_code;
    if (downstream_->get_request_state() == Downstream::STREAM_CLOSED &&
        downstream_->get_upgraded()) {
      // For upgraded connection, send NO_ERROR.  Should we consider
      // request states other than Downstream::STREAM_CLOSED ?
      error_code = NGHTTP2_NO_ERROR;
    } else {
      error_code = NGHTTP2_INTERNAL_ERROR;
    }

    if (http2session_->get_state() == Http2Session::CONNECTED &&
        downstream_->get_downstream_stream_id() != -1) {
      submit_rst_stream(downstream_, error_code);

      http2session_->consume(downstream_->get_downstream_stream_id(),
                             downstream_->get_response_datalen());

      downstream_->reset_response_datalen();

      http2session_->signal_write();
    }
  }
  http2session_->remove_downstream_connection(this);

  if (LOG_ENABLED(INFO)) {
    DCLOG(INFO, this) << "Deleted";
  }
}

int Http2DownstreamConnection::attach_downstream(Downstream *downstream) {
  if (LOG_ENABLED(INFO)) {
    DCLOG(INFO, this) << "Attaching to DOWNSTREAM:" << downstream;
  }
  http2session_->add_downstream_connection(this);
  if (http2session_->get_state() == Http2Session::DISCONNECTED) {
    http2session_->signal_write();
  }

  downstream_ = downstream;
  downstream_->reset_downstream_rtimer();

  return 0;
}

void Http2DownstreamConnection::detach_downstream(Downstream *downstream) {
  if (LOG_ENABLED(INFO)) {
    DCLOG(INFO, this) << "Detaching from DOWNSTREAM:" << downstream;
  }
  if (submit_rst_stream(downstream) == 0) {
    http2session_->signal_write();
  }

  if (downstream_->get_downstream_stream_id() != -1) {
    http2session_->consume(downstream_->get_downstream_stream_id(),
                           downstream_->get_response_datalen());

    downstream_->reset_response_datalen();

    http2session_->signal_write();
  }

  downstream->disable_downstream_rtimer();
  downstream->disable_downstream_wtimer();
  downstream_ = nullptr;
}

int Http2DownstreamConnection::submit_rst_stream(Downstream *downstream,
                                                 uint32_t error_code) {
  int rv = -1;
  if (http2session_->get_state() == Http2Session::CONNECTED &&
      downstream->get_downstream_stream_id() != -1) {
    switch (downstream->get_response_state()) {
    case Downstream::MSG_RESET:
    case Downstream::MSG_BAD_HEADER:
    case Downstream::MSG_COMPLETE:
      break;
    default:
      if (LOG_ENABLED(INFO)) {
        DCLOG(INFO, this) << "Submit RST_STREAM for DOWNSTREAM:" << downstream
                          << ", stream_id="
                          << downstream->get_downstream_stream_id()
                          << ", error_code=" << error_code;
      }
      rv = http2session_->submit_rst_stream(
          downstream->get_downstream_stream_id(), error_code);
    }
  }
  return rv;
}

namespace {
ssize_t http2_data_read_callback(nghttp2_session *session, int32_t stream_id,
                                 uint8_t *buf, size_t length,
                                 uint32_t *data_flags,
                                 nghttp2_data_source *source, void *user_data) {
  int rv;
  auto sd = static_cast<StreamData *>(
      nghttp2_session_get_stream_user_data(session, stream_id));
  if (!sd || !sd->dconn) {
    return NGHTTP2_ERR_DEFERRED;
  }
  auto dconn = static_cast<Http2DownstreamConnection *>(source->ptr);
  auto downstream = dconn->get_downstream();
  if (!downstream) {
    // In this case, RST_STREAM should have been issued. But depending
    // on the priority, DATA frame may come first.
    return NGHTTP2_ERR_DEFERRED;
  }
  auto input = downstream->get_request_buf();
  auto nread = input->remove(buf, length);
  auto input_empty = input->rleft() == 0;

  if (nread > 0) {
    // This is important because it will handle flow control
    // stuff.
    if (downstream->get_upstream()->resume_read(SHRPX_NO_BUFFER, downstream,
                                                nread) != 0) {
      // In this case, downstream may be deleted.
      return NGHTTP2_ERR_CALLBACK_FAILURE;
    }

    // Check dconn is still alive because Upstream::resume_read()
    // may delete downstream which will delete dconn.
    if (sd->dconn == nullptr) {
      return NGHTTP2_ERR_DEFERRED;
    }
  }

  if (input_empty &&
      downstream->get_request_state() == Downstream::MSG_COMPLETE &&
      // If connection is upgraded, don't set EOF flag, since HTTP/1
      // will set MSG_COMPLETE to request state after upgrade response
      // header is seen.
      (!downstream->get_upgrade_request() ||
       (downstream->get_response_state() == Downstream::HEADER_COMPLETE &&
        !downstream->get_upgraded()))) {

    *data_flags |= NGHTTP2_DATA_FLAG_EOF;

    auto &trailers = downstream->get_request_trailers();
    if (!trailers.empty()) {
      std::vector<nghttp2_nv> nva;
      nva.reserve(trailers.size());
      // We cannot use nocopy version, since nva may be touched after
      // Downstream object is deleted.
      http2::copy_headers_to_nva(nva, trailers);
      if (!nva.empty()) {
        rv = nghttp2_submit_trailer(session, stream_id, nva.data(), nva.size());
        if (rv != 0) {
          if (nghttp2_is_fatal(rv)) {
            return NGHTTP2_ERR_CALLBACK_FAILURE;
          }
        } else {
          *data_flags |= NGHTTP2_DATA_FLAG_NO_END_STREAM;
        }
      }
    }
  }

  if (!input_empty) {
    downstream->reset_downstream_wtimer();
  } else {
    downstream->disable_downstream_wtimer();
  }

  if (nread == 0 && (*data_flags & NGHTTP2_DATA_FLAG_EOF) == 0) {
    downstream->disable_downstream_wtimer();

    return NGHTTP2_ERR_DEFERRED;
  }

  return nread;
}
} // namespace

int Http2DownstreamConnection::push_request_headers() {
  int rv;
  if (!downstream_) {
    return 0;
  }
  if (!http2session_->can_push_request()) {
    // The HTTP2 session to the backend has not been established or
    // connection is now being checked.  This function will be called
    // again just after it is established.
    downstream_->set_request_pending(true);
    http2session_->start_checking_connection();
    return 0;
  }

  downstream_->set_request_pending(false);

  auto method = downstream_->get_request_method();
  auto no_host_rewrite = get_config()->no_host_rewrite ||
                         get_config()->http2_proxy ||
                         get_config()->client_proxy || method == HTTP_CONNECT;

  // http2session_ has already in CONNECTED state, so we can get
  // addr_idx here.
  auto addr_idx = http2session_->get_addr_idx();
  auto group = http2session_->get_group();
  auto downstream_hostport = get_config()
                                 ->downstream_addr_groups[group]
                                 .addrs[addr_idx]
                                 .hostport.get();

  // For HTTP/1.0 request, there is no authority in request.  In that
  // case, we use backend server's host nonetheless.
  const char *authority = downstream_hostport;
  auto &req_authority = downstream_->get_request_http2_authority();
  if (no_host_rewrite && !req_authority.empty()) {
    authority = req_authority.c_str();
  }

  downstream_->set_request_downstream_host(authority);

  auto nheader = downstream_->get_request_headers().size();

  size_t num_cookies = 0;
  if (!get_config()->http2_no_cookie_crumbling) {
    num_cookies = downstream_->count_crumble_request_cookie();
  }

  // 8 means:
  // 1. :method
  // 2. :scheme
  // 3. :path
  // 4. :authority
  // 5. via (optional)
  // 6. x-forwarded-for (optional)
  // 7. x-forwarded-proto (optional)
  // 8. te (optional)
  auto nva = std::vector<nghttp2_nv>();
  nva.reserve(nheader + 8 + num_cookies +
              get_config()->add_request_headers.size());

  nva.push_back(
      http2::make_nv_lc_nocopy(":method", http2::to_method_string(method)));

  auto &scheme = downstream_->get_request_http2_scheme();

  nva.push_back(http2::make_nv_lc_nocopy(":authority", authority));

  if (method != HTTP_CONNECT) {
    assert(!scheme.empty());

    nva.push_back(http2::make_nv_ls_nocopy(":scheme", scheme));

    auto &path = downstream_->get_request_path();
    if (method == HTTP_OPTIONS && path.empty()) {
      nva.push_back(http2::make_nv_ll(":path", "*"));
    } else {
      nva.push_back(http2::make_nv_ls_nocopy(":path", path));
    }
  }

  http2::copy_headers_to_nva_nocopy(nva, downstream_->get_request_headers());

  bool chunked_encoding = false;
  auto transfer_encoding =
      downstream_->get_request_header(http2::HD_TRANSFER_ENCODING);
  if (transfer_encoding &&
      util::strieq_l("chunked", (*transfer_encoding).value)) {
    chunked_encoding = true;
  }

  if (!get_config()->http2_no_cookie_crumbling) {
    downstream_->crumble_request_cookie(nva);
  }

  std::string xff_value;
  auto xff = downstream_->get_request_header(http2::HD_X_FORWARDED_FOR);
  if (get_config()->add_x_forwarded_for) {
    if (xff && !get_config()->strip_incoming_x_forwarded_for) {
      xff_value = (*xff).value;
      xff_value += ", ";
    }
    xff_value +=
        downstream_->get_upstream()->get_client_handler()->get_ipaddr();
    nva.push_back(http2::make_nv_ls("x-forwarded-for", xff_value));
  } else if (xff && !get_config()->strip_incoming_x_forwarded_for) {
    nva.push_back(http2::make_nv_ls_nocopy("x-forwarded-for", (*xff).value));
  }

  if (!get_config()->http2_proxy && !get_config()->client_proxy &&
      downstream_->get_request_method() != HTTP_CONNECT) {
    // We use same protocol with :scheme header field
    nva.push_back(http2::make_nv_ls_nocopy("x-forwarded-proto", scheme));
  }

  std::string via_value;
  auto via = downstream_->get_request_header(http2::HD_VIA);
  if (get_config()->no_via) {
    if (via) {
      nva.push_back(http2::make_nv_ls_nocopy("via", (*via).value));
    }
  } else {
    if (via) {
      via_value = (*via).value;
      via_value += ", ";
    }
    via_value += http::create_via_header_value(
        downstream_->get_request_major(), downstream_->get_request_minor());
    nva.push_back(http2::make_nv_ls("via", via_value));
  }

  auto te = downstream_->get_request_header(http2::HD_TE);
  // HTTP/1 upstream request can contain keyword other than
  // "trailers".  We just forward "trailers".
  // TODO more strict handling required here.
  if (te && util::strifind(te->value.c_str(), "trailers")) {
    nva.push_back(http2::make_nv_ll("te", "trailers"));
  }

  for (auto &p : get_config()->add_request_headers) {
    nva.push_back(http2::make_nv_nocopy(p.first, p.second));
  }

  if (LOG_ENABLED(INFO)) {
    std::stringstream ss;
    for (auto &nv : nva) {
      ss << TTY_HTTP_HD << nv.name << TTY_RST << ": " << nv.value << "\n";
    }
    DCLOG(INFO, this) << "HTTP request headers\n" << ss.str();
  }

  auto content_length =
      downstream_->get_request_header(http2::HD_CONTENT_LENGTH);
  // TODO check content-length: 0 case

  if (downstream_->get_request_method() == HTTP_CONNECT || chunked_encoding ||
      content_length || downstream_->get_request_http2_expect_body()) {
    // Request-body is expected.
    nghttp2_data_provider data_prd;
    data_prd.source.ptr = this;
    data_prd.read_callback = http2_data_read_callback;
    rv = http2session_->submit_request(this, downstream_->get_priority(),
                                       nva.data(), nva.size(), &data_prd);
  } else {
    rv = http2session_->submit_request(this, downstream_->get_priority(),
                                       nva.data(), nva.size(), nullptr);
  }
  if (rv != 0) {
    DCLOG(FATAL, this) << "nghttp2_submit_request() failed";
    return -1;
  }

  downstream_->reset_downstream_wtimer();

  http2session_->signal_write();
  return 0;
}

int Http2DownstreamConnection::push_upload_data_chunk(const uint8_t *data,
                                                      size_t datalen) {
  int rv;
  auto output = downstream_->get_request_buf();
  output->append(data, datalen);
  if (downstream_->get_downstream_stream_id() != -1) {
    rv = http2session_->resume_data(this);
    if (rv != 0) {
      return -1;
    }

    downstream_->ensure_downstream_wtimer();

    http2session_->signal_write();
  }
  return 0;
}

int Http2DownstreamConnection::end_upload_data() {
  int rv;
  if (downstream_->get_downstream_stream_id() != -1) {
    rv = http2session_->resume_data(this);
    if (rv != 0) {
      return -1;
    }

    downstream_->ensure_downstream_wtimer();

    http2session_->signal_write();
  }
  return 0;
}

int Http2DownstreamConnection::resume_read(IOCtrlReason reason,
                                           size_t consumed) {
  int rv;

  if (http2session_->get_state() != Http2Session::CONNECTED ||
      !http2session_->get_flow_control()) {
    return 0;
  }

  if (!downstream_ || downstream_->get_downstream_stream_id() == -1) {
    return 0;
  }

  if (consumed > 0) {
    assert(downstream_->get_response_datalen() >= consumed);

    rv = http2session_->consume(downstream_->get_downstream_stream_id(),
                                consumed);

    if (rv != 0) {
      return -1;
    }

    downstream_->dec_response_datalen(consumed);

    http2session_->signal_write();
  }

  return 0;
}

int Http2DownstreamConnection::on_read() { return 0; }

int Http2DownstreamConnection::on_write() { return 0; }

void Http2DownstreamConnection::attach_stream_data(StreamData *sd) {
  // It is possible sd->dconn is not NULL. sd is detached when
  // on_stream_close_callback. Before that, after MSG_COMPLETE is set
  // to Downstream::set_response_state(), upstream's readcb is called
  // and execution path eventually could reach here. Since the
  // response was already handled, we just detach sd.
  detach_stream_data();
  sd_ = sd;
  sd_->dconn = this;
}

StreamData *Http2DownstreamConnection::detach_stream_data() {
  if (sd_) {
    auto sd = sd_;
    sd_ = nullptr;
    sd->dconn = nullptr;
    return sd;
  }
  return nullptr;
}

int Http2DownstreamConnection::on_priority_change(int32_t pri) {
  int rv;
  if (downstream_->get_priority() == pri) {
    return 0;
  }
  downstream_->set_priority(pri);
  if (http2session_->get_state() != Http2Session::CONNECTED) {
    return 0;
  }
  rv = http2session_->submit_priority(this, pri);
  if (rv != 0) {
    DLOG(FATAL, this) << "nghttp2_submit_priority() failed";
    return -1;
  }
  http2session_->signal_write();
  return 0;
}

int Http2DownstreamConnection::on_timeout() {
  if (!downstream_) {
    return 0;
  }

  return submit_rst_stream(downstream_, NGHTTP2_NO_ERROR);
}

size_t Http2DownstreamConnection::get_group() const {
  // HTTP/2 backend connections are managed by Http2Session object,
  // and it stores group index.
  return http2session_->get_group();
}

} // namespace shrpx


text:
package static_md;

public class static_Foo_test3_Method extends quark.reflect.Method implements io.datawire.quark.runtime.QObject {
    public static_Foo_test3_Method() {
        super("quark.void", "test3", new java.util.ArrayList(java.util.Arrays.asList(new Object[]{})));
    }
    public Object invoke(Object object, java.util.ArrayList<Object> args) {
        static_.Foo obj = (static_.Foo) (object);
        (obj).test3();
        return null;
    }
    public String _getClass() {
        return (String) (null);
    }
    public Object _getField(String name) {
        return null;
    }
    public void _setField(String name, Object value) {}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
    <link rel="stylesheet" href="css/popup.css" type="text/css">

        <textarea class="form-control" id="tweet-text" rows="3"></textarea>
        <button class="btn btn-primary" id='tweet'> ツイート</button>

設定

          <input id="auto" type="checkbox"> 自動でつぶやく

      <button class="btn btn-default" id='make'> アカウントを登録</button>
      <form>

          <input class="form-control" id='pin' type="number">

            <button class="btn btn-default" id='send' type="button">送信</button>

      </form>


text:
using content::BrowserThread;

UsbDevice::UsbDevice(
    scoped_refptr<UsbContext> context,
    PlatformUsbDevice platform_device,
    uint16 vendor_id,
    uint16 product_id)
    : platform_device_(platform_device),
      vendor_id_(vendor_id),
      product_id_(product_id),
      context_(context) {
  CHECK(platform_device) << "platform_device cannot be NULL";
  libusb_ref_device(platform_device);
}

UsbDevice::UsbDevice()
    : platform_device_(NULL),
      vendor_id_(0),
      product_id_(0),
      context_(NULL) {
}

UsbDevice::~UsbDevice() {
  DCHECK(thread_checker_.CalledOnValidThread());
  for (HandlesVector::iterator it = handles_.begin();
      it != handles_.end();
      ++it) {
    (*it)->InternalClose();
  }
  STLClearObject(&handles_);
  libusb_unref_device(platform_device_);
}

scoped_refptr<UsbDeviceHandle> UsbDevice::Open() {
  DCHECK(thread_checker_.CalledOnValidThread());
  PlatformUsbDeviceHandle handle;
  int rv = libusb_open(platform_device_, &handle);
  if (LIBUSB_SUCCESS == rv) {
    scoped_refptr<UsbDeviceHandle> device_handle =
        new UsbDeviceHandle(context_, this, handle);
    handles_.push_back(device_handle);
    return device_handle;
  }
  return NULL;
}

bool UsbDevice::Close(scoped_refptr<UsbDeviceHandle> handle) {
  DCHECK(thread_checker_.CalledOnValidThread());

  for (HandlesVector::iterator it = handles_.begin();
      it != handles_.end();
      ++it) {
    if (*it == handle) {
      (*it)->InternalClose();
      handles_.erase(it);
      return true;
    }
  }
  return false;
}

bool UsbDevice::ListInterfaces(UsbConfigDescriptor* config) {
  DCHECK(thread_checker_.CalledOnValidThread());

  PlatformUsbConfigDescriptor platform_config;
  const int list_result =
      libusb_get_active_config_descriptor(platform_device_, &platform_config);
  if (list_result == 0)
    config->Reset(platform_config);

  return list_result == 0;
}

void UsbDevice::OnDisconnect() {
  DCHECK(thread_checker_.CalledOnValidThread());
  HandlesVector handles;
  swap(handles, handles_);
  for (std::vector<scoped_refptr<UsbDeviceHandle> >::iterator it =
      handles.begin();
      it != handles.end();
      ++it) {
    (*it)->InternalClose();
  }
}