text:
from __future__ import absolute_import
from chaco.lineplot import LinePlot
from chaco.scatterplot import ScatterPlot
from traits.api import Float
# ============= standard library imports ========================
# ============= local library imports  ==========================
from pychron.pipeline.plot.overlays.base_inset import BaseInset

class InverseIsochronLineInset(BaseInset, LinePlot):
    def __init__(self, *args, **kw):
        self.border_visible = kw.get('border_visible', True)
        BaseInset.__init__(self, *args, **kw)
        LinePlot.__init__(self)

        if not self.visible_axes:
            self.x_axis.visible = False
            self.y_axis.visible = False

class InverseIsochronPointsInset(BaseInset, ScatterPlot):
    nominal_intercept = Float

    def __init__(self, *args, **kw):
        ScatterPlot.__init__(self)
        BaseInset.__init__(self, *args, **kw)

        self.border_visible = kw.get('border_visible', True)
        self.marker = 'circle'
        # self.color = 'red'
        # self.marker_size = 1.5
        if not self.visible_axes:
            self.x_axis.visible = False
            self.y_axis.visible = False

    def overlay(self, component, gc, *args, **kw):
        super(InverseIsochronPointsInset, self).overlay(component, gc, *args, **kw)
        self._draw_atm(gc)
        self._draw_zero(gc)

    def _draw_zero(self, gc):
        with gc:
            yl, yh = self.value_range.low, self.value_range.high
            pts = self.map_screen([(0, yl), (0, yh)])
            gc.set_line_dash((3, 5))
            gc.lines(pts)
            gc.draw_path()

    def _draw_atm(self, gc):
        with gc:
            xl = self.index_range.low
            pts = self.map_screen([(xl, self.nominal_intercept), (0, self.nominal_intercept)])

            # print x,y
            # gc.move_to(0,y)
            # gc.line_to(x,y)
            gc.set_line_width(1.25)
            gc.lines(pts)
            gc.draw_path()

            # reg = self.regressor
            # xintercept = reg.x_intercept * 1.1
            # yintercept = reg.predict(0)

            # m, _ = self.index.get_bounds()
            # self.index_range.low = lx = -0.1 * (xintercept - m)
            # self.index_range.high = hx = xintercept
            #
            # self.value_range.low = 0
            # self.value_range.high = max(1 / 300., yintercept * 1.1)

            # xs = linspace(lx, hx, 20)
            # ys = reg.predict(xs)
            # print 'xs', xs.shape
            # print 'ys', ys.shape
            #
            # index = ArrayDataSource(xs)
            # value = ArrayDataSource(ys)
            # index_range = DataRange1D()
            # index_range.add(index)
            # index_mapper = LinearMapper(range=index_range)
            # index_range.tight_bounds = False
            #
            # value_range = DataRange1D()
            # value_range.add(value)
            # value_mapper = LinearMapper(range=value_range)
            # value_range.tight_bounds = False
            #
            # lp = ScatterPlot()
            # lp.index = index
            # lp.value = value
            # lp.index_mapper = index_mapper
            # lp.value_mapper = value_mapper

            # self.underlays.append(lp)
            # self.plots.append(lp)

            # print self.get_screen_points()
            # print lp.get_screen_points()

            # ============= EOF =============================================


text:
// ========================================================================
// $Id: Break.java,v 1.3 2004/05/09 20:31:28 gregwilkins Exp $
// Copyright 1996-2004 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================

package net.lightbody.bmp.proxy.jetty.html;

/* -------------------------------------------------------------------- */
/** Break Tag.
 */
public class Break extends Tag
{
    /* ---------------------------------------------------------------- */
    /** Line Break tag type */
    public final static String Line="br";
    /** Rule Break tag type */
    public final static String Rule="hr";
    /** Paragraph Break tag type */
    public final static String Para="p";

    /* ---------------------------------------------------------------- */
    /** Default constructor (Line Break).
     */
    public Break()
    {
        this(Line);
    }

    /* ---------------------------------------------------------------- */
    /** Constructor.
     * @param type The Break type
     */
    public Break(String type)
    {
        super(type);
    }

    /* ---------------------------------------------------------------- */
    /** Static instance of line break */
    public final static Break line=new Break(Line);
    /** Static instance of rule break */
    public final static Break rule=new Break(Rule);
    /** Static instance of paragraph break */
    public final static Break para=new Break(Para);

}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * ©[2016] SugarCRM Inc.  Licensed by SugarCRM under the Apache 2.0 license.
 */

namespace SugarAPI\SDK\EntryPoint\POST;

use SugarAPI\SDK\EntryPoint\Abstracts\POST\AbstractPostFileEntryPoint;
use SugarAPI\SDK\Exception\EntryPoint\RequiredOptionsException;

class ModuleRecordFileField extends AbstractPostFileEntryPoint {

    /**
     * @inheritdoc
     */
    protected $_URL = '$module/$record/file/$field';

    /**
     * @inheritdoc
     */
    protected $_DATA_TYPE = 'array';

    /**
     * @inheritdoc
     */
    protected $_REQUIRED_DATA = array(
        'format' => 'sugar-html-json',
        'delete_if_fails' => FALSE
    );

    /**
     * Allow for shorthand calling of attachFile method.
     * Users can simply submit the File in via string, or pass the filename => path
     * @param $data
     * @throws RequiredOptionsException
     */
    protected function configureData($data){
        if (is_string($data)) {
            if (!empty($this->Options)) {
                $fileField = end($this->Options);
                $data = array(
                    $fileField => $data
                );
            } else {
                throw new RequiredOptionsException(get_called_class(), "Options are required, when passing String for data.");
            }
        }
        if (is_array($data)){
            foreach ($data as $key => $value){
                if (!array_key_exists($key,$this->_REQUIRED_DATA)){
                    $data[$key] = $this->setFileFieldValue($value);
                }
            }
        }
        parent::configureData($data);
    }

    /**
     * Configure the filepath to have an @ symbol in front if one is not found
     * @param string $value
     * @return string
     */
    protected function setFileFieldValue($value){
        if (strpos($value, '@')===FALSE){
            $value = '@'.$value;
        }
        return $value;
    }

}


text:
package org.rest.sec.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.xml.bind.annotation.XmlRootElement;

import org.rest.common.INameableEntity;

import com.thoughtworks.xstream.annotations.XStreamAlias;

@Entity
@XmlRootElement
@XStreamAlias( "privilege" )
public class Privilege implements INameableEntity{

	@Id @GeneratedValue( strategy = GenerationType.AUTO ) @Column( name = "PRIV_ID" ) private Long id;
	@Column( unique = true,nullable = false ) private String name;

	public Privilege(){
		super();
	}

	public Privilege( final String nameToSet ){
		super();
		name = nameToSet;
	}

	// API

	@Override
	public Long getId(){
		return id;
	}

	@Override
	public void setId( final Long idToSet ){
		id = idToSet;
	}

	@Override
	public String getName(){
		return name;
	}

	public void setName( final String nameToSet ){
		name = nameToSet;
	}

	//

	@Override
	public int hashCode(){
		final int prime = 31;
		int result = 1;
		result = prime * result + ( ( name == null ) ? 0 : name.hashCode() );
		return result;
	}

	@Override
	public boolean equals( final Object obj ){
		if( this == obj )
			return true;
		if( obj == null )
			return false;
		if( getClass() != obj.getClass() )
			return false;
		final Privilege other = (Privilege) obj;
		if( name == null ){
			if( other.name != null )
				return false;
		}
		else if( !name.equals( other.name ) )
			return false;
		return true;
	}

	@Override
	public String toString(){
		return getName();
	}

}


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

<title>Class Hierarchy</title>
    <meta name="date" content="2016-01-16">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For All Packages

Package Hierarchies:

Estimator

Class Hierarchy

java.lang.Object

Estimator.EstimatorMCRFactory

com.mathworks.toolbox.javabuilder.internal.MWComponentInstance<T> (implements com.mathworks.toolbox.javabuilder.Disposable)

Estimator.Estimator

Interface Hierarchy

java.rmi.Remote

com.mathworks.toolbox.javabuilder.pooling.Poolable

Estimator.EstimatorRemote

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
create table users (
  id serial primary key,
  email varchar(255) not null,
  crypted_password varchar(255) not null,
  phone varchar(255),
  first_name varchar(255),
  last_name varchar(255),
  languages varchar(255),
  profile_picture varchar(255),
  time_registered timestamptz default now(),
  token varchar(255),
  updated_at timestamptz default now()
);

create table homes (
  id serial primary key,
  customer_id integer references users (id),
  address varchar(255)
);

create table rooms (
  id serial primary key,
  home_id integer references homes (id),
  room_type varchar(40),
  room_count integer
);

create table jobs (
  id serial primary key,
  customer_id integer references users (id),
  home_id integer references homes (id),
  worker_id integer references users (id),
  time_created timestamptz default now(),
  time_started timestamptz,
  time_needed timestamptz,
  time_finished timestamptz,
  payment_type varchar(40)
);

create table avialable_times (
  id serial primary key,
  job_id integer references jobs (id),
  time_start timestamptz
);


text:
title: "Setting up GitLab Runner For Continuous Integration"
date: 2016-03-01
categories:
author: Ahmet Kizilay
author_twitter: ahmetkizilay

---

There are many cloud-based continuous integration (CI) providers out there and
most of them generously offer free plans for open-source projects.
While this is great for the open-source community, paid plans can get a little
bit too expensive for small start-ups that would prefer to keep their source code private.
In such an ecosystem, GitLab Inc. stands out as a viable option with unlimited private
repositories and its GitLab Runner, a free and open-source tool to automate the
testing and building of projects, thus giving software
developers the freedom to experiment with different approaches to build the
optimal pipeline for their needs.

This tutorial will demonstrate how to get started with a CI workflow using
[GitLab Runner](https://gitlab.com/gitlab-org/gitlab-ci-multi-runner).
We will first setup a sample NodeJS project hosted on Gitlab.com to run tests
on build machines provided by GitLab Inc.
Then, we will setup and configure our own specific runner on a private server.
Finally we will go over some good practices to speed up the build time as the project grows.
By the end of this tutorial you will feel comfortable building your own
CI solution, custom-tailored for your existing projects.
This post will be useful for project managers looking for affordable
CI solutions and developers wanting to build test-driven
and sustainable software projects.

<!-- more -->

### Introducing the sample project

Before we start with the GitLab Runner, let's briefly review this simple
[NodeJS project](https://gitlab.com/gitlab-examples/nodejs/) we will
work with throughout this tutorial.
Our project contains two independent modules we would like to test.
One module consists of some utility methods for asynchronous operations.
The other module implements a simple wrapper around a PostgreSQL database to
insert and retrieve records. Thanks to the latter module, we will need a
database instance in our testing environment to run the tests.

After starting a test database, we can run the tests locally and see all tests pass.

```
DB_USER=[db-username] \
BD_PASS=[db-password] \
DB_HOST=[db-host:db-port] \
node ./specs/start.js
```

Feel free to explore the project [source code](https://gitlab.com/gitlab-examples/nodejs/tree/master)
if you are interested.

### Getting started with GitLab Runner

GitLab Runner is triggered with every push to the central repository if a
`.gitlab-ci.yml` file is present (unless explicitly configured not to).
This file specifies how the build environment should be set up and what
commands to be executed to build, test, and deploy our project in a series of
jobs that can be parallelized. In this tutorial, we will be using GitLab Runner's
built-in **docker executor** to set up the build environment.
This executor provides a powerful abstraction that uses Docker in the
background to load our app and run the tests in a container.
In addition, this executor conveniently starts any dependent services (such as
databases) before running jobs and links containers to communicate with each other.

### Creating `.gitlab-ci.yml` file

We will add our `.gitlab-ci.yml` file to the root directory of our project.

```
image: node:4.2.2

services:
  - postgres:9.5.0

all_tests:
  script:
   - npm install
   - node ./specs/start.js
```

Now let's go over the parts of this file.

The first line specifies the base image against which our tests will run.
Since we are testing a NodeJS app, our base image will be a recent NodeJS version.

The `services` section is where external dependencies are listed.
In our tests, we need a PostgreSQL database, so we add the image name for this database.
Any Docker image name can be specified here, such as `mysql` for MySQL databases.
The database will start with default credentials before tests run and it will be
accessible under the the host name `postgres` on the default PostgreSQL port, 5432.

If we needed to use any credentials other than the defaults, we could add them
inside the `variables` tag. Values under this tag are passed to all services
on initialization. As per the PostgreSQL service [documentation](http://doc.gitlab.com/ce/ci/services/postgres.html),
the following settings will overwrite the user and password for our database:

```
image: node:4.2.2

variables:
  POSTGRES_USER: testuser
  POSTGRES_PASSWORD: testpass

services:
  - postgres:9.5.0

all_tests:
  script:
   - npm install
   - node ./specs/start.js
```

Note that since these test credentials are internal to our project, it is OK to simply
add them to the `.gitlab-ci.yml` file. However, you should register any external
configuration variables, such as API keys, in the **Secure Variables**
page (**Settings -> Variables**) and reference them here by name.

In the final section, we define a job named `all_tests`, which contains the command
that will run our tests.
In the `script` subsection here, we simply add our commands to install the dependencies
and start the tests.

To be extra cautious, we could lint-check our yml file on the
[GitLab CI Lint page](https://gitlab.com/ci/lint) to see the breakdown of
the build steps to make sure we don't have a typo.

### Using Shared Runners

GitLab Inc. provides a number of servers with GitLab Runner installed.
On the **Runners** page (**Settings -> Runners**), we can see the list of currently available runners.
We should see that Shared Runners are already available for us, so we can immediately queue our first build by simply pushing our `.gitlab-ci.yml` file to our repository.
We can track the progress of our build on the [Builds page](https://gitlab.com/gitlab-examples/nodejs/builds).
Once our build starts, we should see that it completes with success in a couple of minutes.

### Installing a specific runner

While these Shared Runners are great to get a sense of how to get started with
CI, we will now install GitLab Runner on a private server to run exclusively
for our project.
We will use exactly the same [open-source software](https://gitlab.com/gitlab-org/gitlab-ci-multi-runner)
GitLab.com uses on their Shared Runners, so we will have the extra benefit of
optimizing and securing our builds for our specific project.

We will need a server instance where we will install the GitLab Runner.
GitLab Runner can be installed on [Linux](https://gitlab.com/gitlab-org/gitlab-ci-multi-runner/blob/master/docs/install/linux-repository.md), [OSX](https://gitlab.com/gitlab-org/gitlab-ci-multi-runner/blob/master/docs/install/osx.md) and [Windows](https://gitlab.com/gitlab-org/gitlab-ci-multi-runner/blob/master/docs/install/windows.md).
For our sample project, a small server instance with 1 GB RAM should be enough.
In addition, since we will be running with the Docker executor, we also need to have [Docker Engine](https://docs.docker.com/engine/installation/) installed.

Upon installation, we will register a new runner for our project.
Start the registration with the following command:

```
gitlab-ci-multi-runner register
```

The registration will walk us through a few steps to configure our runner.

```
Running in system-mode.

Please enter the gitlab-ci coordinator URL (e.g. https://gitlab.com/ci):
https://gitlab.com/ci
```

Since our project is hosted on Gitlab.com, we will use the default
gitlab-ci coordinator URL.

```
Please enter the gitlab-ci token for this runner:
[your private gitlab-ci token]
```

On **Runners** page (**Settings -> Runners**), we will copy the private gitlab-ci token for our project and paste it here.

```
Please enter the gitlab-ci description for this runner:
[ubuntu-2gb-nyc3-01]: new-docker-executor
Please enter the gitlab-ci tags for this runner (comma separated):
docker
Registering runner... succeeded                     runner=8tB1zBiU
```

It is a good practice to give a descriptive name and tags for runners to
be able to remember and target them later on. We will add the `docker` tag to this
runner since we can run any Docker image and services with it.

```
Please enter the executor: virtualbox, ssh, shell, parallels, docker, docker-ssh:
docker
Please enter the default Docker image (eg. ruby:2.1):
node:4.2.2
Runner registered successfully. Feel free to start it, but if it's running already the config should be automatically reloaded!
```

Notice that there are several executor options available.
In this post, we are using the `docker` executor.
Remember from the `.gitlab-ci.yml` file, our base image is already set as node:4.2.2.
Note that the default Docker image specified here will be used only when `.gitlab-ci.yml`
file does not contain an image declaration.

Specific runners take precedence over the Shared Runners.
Our project won't be using Shared Runners as long as our specific runner is available.
If preferred, we can disable the Shared Runners on the **Runners** page
(**Settings -> Runners**) by toggling off the Shared Runners button.

Finally, we are ready to trigger a new build.
We should see the next build running with our specific runner on our private server.

### Enabling cache

Now that we have a functional CI workflow, let's talk about
how to make it faster and more efficient.

To start, we can eliminate redundant downloading of dependency libraries by
caching and restoring dependencies between builds.
For NodeJS projects, dependent libraries are installed in a folder called `node_modules`.
We should specify this folder to cache in our `.gitlab-ci.yml` file:

```
image: node:4.2.2

cache:
  paths:
  - node_modules/

services:
  - postgres:9.5.0

all_tests:
  script:
   - npm install
   - node ./specs/start.js
```

After a successful build, you should see the `node_modules` folder is archived at
the end of builds to be restored at the beginning of following builds.
As long as our dependencies file remains unchanged, no new libraries will be
downloaded and our total build time will significantly decrease.

### Adding concurrency

Another modification we can add to speed up the build process is to
parallelize the tests.
In our project, we can split the tests into two jobs.
One for the database tests and another for the async module tests.
Furthermore, we can restrict the PostgreSQL service to run only for our database
job since we won't need a database for the async module.

```
image: node:4.2.2

cache:
  paths:
  - node_modules/

test_async:
  script:
   - npm install
   - node ./specs/start.js ./specs/async.spec.js

test_db:
  services:
    - postgres:9.5.0
  script:
   - npm install
   - node ./specs/start.js ./specs/db-postgres.spec.js
```

Note that we still need to introduce concurrency to the build.
To do that we could either create a new server and register a runner for
our project, or increase the concurrency level for our existing runner.
We will go with the latter and edit the `concurrent` setting on the first
line of our `config.toml` file in the server.
If you installed GitLab Runner as the root user with the deb or rpm packages,
the config file will be in `/etc/gitlab-runner/config.toml` by default:

```
concurrent = 2
```

After triggering a new build, we can see two jobs running
at the same time.

### Conclusion

In this tutorial, we set up automated testing with GitLab Runner for a NodeJS
project to get started with continuous integration on Gitlab.com.
For more information on the GitLab Runner and GitLab CI platform, check out the [documentation](http://doc.gitlab.com/ce/ci/).
Happy coding!

### About Guest Author: Ahmet Kizilay

[Ahmet Kizilay](https://about.me/ahmetkizilay) is a software developer living in Istanbul.
He is currently working as a full-stack developer at [Graph Commons](https://graphcommons.com/).


text:
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <in.srain.cube.views.ptr.PtrFrameLayout
        android:id="@+id/comment_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/color_gray_f2f2f2"
        android:paddingBottom="0dp"
        android:paddingTop="0dp">
        <android.support.v7.widget.RecyclerView
            android:id="@+id/rc_comment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbarSize="1dp"
            android:scrollbarStyle="outsideOverlay"
            android:scrollbars="vertical"/>
    </in.srain.cube.views.ptr.PtrFrameLayout>
</FrameLayout>


text:
import { NgModule, ModuleWithProviders } from '@angular/core'
import { CommonModule } from '@angular/common'

import {
  WidgetLibraryModule,
  Framework
} from 'angular2-json-schema-form'
import { ChixFrameworkComponent } from './chix.component'
import { ChixFramework } from './chix'

@NgModule({
  imports: [CommonModule, WidgetLibraryModule],
  declarations: [ChixFrameworkComponent],
  exports: [ChixFrameworkComponent],
  entryComponents: [ChixFrameworkComponent]
})
export class ChixFrameworkModule {
  static forRoot (): ModuleWithProviders {
    return {
      ngModule: ChixFrameworkModule,
      providers: [
        {
          provide: Framework,
          useClass: ChixFramework,
          multi: true
        }
      ]
    }
  }
}


text:
@interface HLQuartzTextView ()
@property(nonatomic,weak)UITextField *textField;
@property(nonatomic,assign)CGFloat deltaX;
@property(nonatomic,assign)CGFloat deltaY;

@end
@implementation HLQuartzTextView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];

        UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(10, 100, 100, 44)];
        tf.backgroundColor = [UIColor greenColor];
        [self addSubview:tf];
//        [tf setEnabled:false];
        tf.placeholder = @"双击添加文字";
        tf.layer.borderColor = [UIColor blueColor].CGColor;
        tf.layer.borderWidth = 8;
        self.textField = tf;

        self.textField.gestureRecognizers = nil;

        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureAction:)];
        [self.textField addGestureRecognizer:pan];

        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureAction:)];
        tap.numberOfTapsRequired = 2;
        [self.textField addGestureRecognizer:tap];
    }
    return self;
}

//- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
//    UITouch *touch = event.allTouches.anyObject;
//    if (touch.tapCount == 2) {
//        CGPoint p = [self convertPoint:point toView:self.textField];
//        if ([self.textField pointInside:p withEvent:event]) {
//            [self.textField setEnabled:true];
//             [self.textField becomeFirstResponder];
//        }
//    }
//    return [super hitTest:point withEvent:event];
//}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.textField endEditing:true];
}
- (void)tapGestureAction:(UIGestureRecognizer *)gesture {
//    [self.textField setEnabled:true];
    [self.textField becomeFirstResponder];
}
- (void)panGestureAction:(UIGestureRecognizer *)gesture {

    CGPoint currentPoint, beginPoint;

    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
            beginPoint = [gesture locationInView:self];
            self.deltaX = beginPoint.x - self.textField.frame.origin.x;
            self.deltaY = beginPoint.y - self.textField.frame.origin.y;
            NSLog(@"begin");
            break;
        case UIGestureRecognizerStateChanged:
            currentPoint = [gesture locationInView:self];
            NSLog(@"changed");
            NSLog(@"pan");
            self.textField.frame = CGRectMake(currentPoint.x - self.deltaX, currentPoint.y - self.deltaY, self.textField.frame.size.width, self.textField.frame.size.height);
            [self.textField setNeedsLayout];
            [self setNeedsDisplay];
            break;
        case UIGestureRecognizerStateCancelled:
            NSLog(@"cancel");
            break;
        case UIGestureRecognizerStateEnded:
            currentPoint = [gesture locationInView:self];
            NSLog(@"end");
            break;
        default:
            break;
    }

}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGFloat length[2] = {3,3};
    CGContextSetLineDash(context, 1, length, 2);
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    CGContextMoveToPoint(context, self.textField.frame.origin.x, 0);
    CGContextAddLineToPoint(context, self.textField.x, self.bounds.size.height);
    CGContextStrokePath(context);

    CGContextSaveGState(context);
    CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor);
    CGContextMoveToPoint(context, 0, self.textField.frame.origin.y);
    CGContextAddLineToPoint(context, self.bounds.size.width, self.textField.frame.origin.y);
    CGContextStrokePath(context);

    CGContextRestoreGState(context);
    CGContextMoveToPoint(context, CGRectGetMaxX(self.textField.frame), 0);
    CGContextAddLineToPoint(context, CGRectGetMaxX(self.textField.frame), self.bounds.size.height);
    CGContextStrokePath(context);

    NSString *testStr = @"极乐空间";
    [testStr drawInRect:CGRectMake(0, 100, 100, 44) withAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, CGRectGetMaxY(self.textField.frame));
    CGPathAddLineToPoint(path, NULL, self.bounds.size.width, CGRectGetMaxY(self.textField.frame));
    CGContextAddPath(context, path);
    CGContextStrokePath(context);
    CGPathRelease(path);

    UIImage *img = [UIImage imageNamed:@"gesture_node_error"];
    [img drawInRect:CGRectMake(0, 130, 20, 20)];

}

@end


text:
<?php
namespace Omise\Payment\Gateway\Command;

use Magento\Payment\Gateway\Command\CommandException;
use Magento\Payment\Gateway\Command\CommandPoolInterface;
use Magento\Payment\Gateway\CommandInterface;
use Magento\Payment\Gateway\Helper\ContextHelper;
use Magento\Payment\Gateway\Helper\SubjectReader;
use Magento\Sales\Model\Order;
use Omise\Payment\Helper\OmiseHelper;
use Omise\Payment\Helper\OmiseEmailHelper;
use Omise\Payment\Model\Api\Charge;
use Magento\Sales\Model\Order\Payment\Transaction;

class CreditCardStrategyCommand implements CommandInterface
{
    /**
     * @var string
     */
    const ACTION_AUTHORIZE                     = \Magento\Payment\Model\Method\AbstractMethod::ACTION_AUTHORIZE;

    /**
     * @var string
     */
    const ACTION_AUTHORIZE_CAPTURE             = \Magento\Payment\Model\Method\AbstractMethod::ACTION_AUTHORIZE_CAPTURE;

    /**
     * @var string
     */
    const COMMAND_AUTHORIZE       = 'charge_authorize';

    /**
     * @var string
     */
    const COMMAND_AUTHORIZE_CAPTURE = 'charge_capture';

    /**
     * @var CommandPoolInterface
     */
    private $commandPool;

    /**
     * @var OmiseHelper
     */
    private $helper;

    /**
     * @var OmiseEmailHelper
     */
    private $emailHelper;

    /**
     * @var Charge
     */
    private $charge;

    /**
     * @param CommandPoolInterface $commandPool
     * @param OmiseHelper $helper
     * @param OmiseEmailHelper $emailHelper
     * @param Charge $charge
     */
    public function __construct(
        CommandPoolInterface $commandPool,
        OmiseHelper          $helper,
        OmiseEmailHelper     $emailHelper,
        Charge               $charge
    ) {
        $this->commandPool = $commandPool;
        $this->helper      = $helper;
        $this->emailHelper = $emailHelper;
        $this->charge      = $charge;
    }

    /**
     * @inheritdoc
     */
    public function execute(array $commandSubject)
    {
        /** @var \Magento\Payment\Model\InfoInterface **/
        $payment = SubjectReader::readPayment($commandSubject)->getPayment();
        ContextHelper::assertOrderPayment($payment);

        $order             = $payment->getOrder();
        $paymentAction     = $this->getPaymentAction($commandSubject);
        switch ($paymentAction) {
            case self::ACTION_AUTHORIZE:
                $this->commandPool->get(self::COMMAND_AUTHORIZE)->execute($commandSubject);
                break;

            case self::ACTION_AUTHORIZE_CAPTURE:
                $this->commandPool->get(self::COMMAND_AUTHORIZE_CAPTURE)->execute($commandSubject);
                break;

            default:
                throw new CommandException(__('Unable to resolve payment_action type.'));
        }

        $charge = $this->charge->find($payment->getAdditionalInformation('charge_id'));
        $isCapture = $paymentAction == self::ACTION_AUTHORIZE_CAPTURE;
        $is3dsecured = $this->helper->is3DSecureEnabled($charge);
        if (! $is3dsecured) {
                $order->save();
                $invoice = $this->helper->createInvoiceAndMarkAsPaid($order, $charge->id, $isCapture);
                $this->emailHelper->sendInvoiceAndConfirmationEmails($order);

                $payment->setAdditionalInformation('charge_authorize_uri', "");
            if ($isCapture) {
                $payment->addTransactionCommentsToOrder(
                    $payment->addTransaction(Transaction::TYPE_CAPTURE, $invoice),
                    __(
                        'Captured amount of %1 online via Omise Payment Gateway.',
                        $order->getBaseCurrency()->formatTxt($invoice->getBaseGrandTotal())
                    )
                );
            } else {
                $payment->addTransactionCommentsToOrder(
                    $payment->addTransaction(Transaction::TYPE_AUTH),
                    $payment->prependMessage(
                        __(
                            'Authorized amount of %1 via Omise Payment Gateway.',
                            $order->getBaseCurrency()->formatTxt($order->getTotalDue())
                        )
                    )
                );
            }
            $this->updateOrderState(
                $commandSubject,
                ($order->getState() ? $order->getState() : Order::STATE_PROCESSING),
                ($order->getStatus()
                ? $order->getStatus()
                : $order->getConfig()->getStateDefaultStatus(Order::STATE_PROCESSING))
            );
        }
    }

    /**
     * @param  array  $commandSubject
     *
     * @return string
     */
    protected function getPaymentAction(array $commandSubject)
    {
        return $commandSubject['paymentAction'];
    }

    /**
     * @param array  $commandSubject
     * @param string $state
     * @param string $status
     */
    protected function updateOrderState(array $commandSubject, $state, $status)
    {
        $stateObject = SubjectReader::readStateObject($commandSubject);
        $stateObject->setState($state);
        $stateObject->setStatus($status);
    }
}


text:
'use strict';

var GuestbookCtrl = ['$scope', '$http', '$location', '$routeParams', '$route',
  function ($scope, $http, $location, $routeParams) {

    $scope.guestbookName = $routeParams['guestbookName'];
    retrieveGuestbook($routeParams['guestbookName']);

    function retrieveGuestbook(guestbookName) {
      $http.get('/rest/guestbook/' + encodeURIComponent(guestbookName))
          .success(function(data) {
            $scope.greetings = data.greetings;
            $scope.userServiceInfo = data.userServiceInfo;
            $scope.guestbookName = data.guestbookName;
            $scope.currentGuestbookName = data.guestbookName;
            $location.path(data.guestbookName);
          })
          .error(function(data, status) {
            console.log('Retrieving a guestbook failed with the status code: ' + status);
            console.log(data);
          });
    }

    $scope.submit_form = function () {
      $http.post(
          '/rest/guestbook/' + encodeURIComponent($scope.guestbookName),
          {'content': $scope.content, 'genre': $scope.genre})
          .success(function (data) {
            $scope.content = '';
            $scope.gebre = '';
            $scope.greetings = data.greetings;
            $scope.guestbookName = data.guestbookName;
            $scope.currentGuestbookName = data.guestbookName;
            $location.path(data.guestbookName);
          })
          .error(function(data, status) {
            console.log('Posting a message failed with the status code: ' + status);
            console.log(data);
          });
    };
  }
];


text:
'use strict';

import * as nls from 'vs/nls';
import { Action, IAction } from 'vs/base/common/actions';
import { illegalArgument } from 'vs/base/common/errors';
import * as arrays from 'vs/base/common/arrays';
import { IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { IBadge } from 'vs/workbench/services/activity/common/activity';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ActionBar, ActionsOrientation, Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { CompositeActionItem, CompositeOverflowActivityAction, ICompositeActivity, CompositeOverflowActivityActionItem, ActivityAction, ICompositeBar, ICompositeBarColors } from 'vs/workbench/browser/parts/compositebar/compositeBarActions';
import { TPromise } from 'vs/base/common/winjs.base';
import { Dimension, $, addDisposableListener, EventType, EventHelper } from 'vs/base/browser/dom';
import { StandardMouseEvent } from 'vs/base/browser/mouseEvent';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { Widget } from 'vs/base/browser/ui/widget';

export interface ICompositeBarOptions {
	icon: boolean;
	storageId: string;
	orientation: ActionsOrientation;
	colors: ICompositeBarColors;
	compositeSize: number;
	overflowActionSize: number;
	getActivityAction: (compositeId: string) => ActivityAction;
	getCompositePinnedAction: (compositeId: string) => Action;
	getOnCompositeClickAction: (compositeId: string) => Action;
	getContextMenuActions: () => Action[];
	openComposite: (compositeId: string) => TPromise<any>;
	getDefaultCompositeId: () => string;
	hidePart: () => TPromise<any>;
}

export class CompositeBar extends Widget implements ICompositeBar {

	private dimension: Dimension;

	private compositeSwitcherBar: ActionBar;
	private compositeOverflowAction: CompositeOverflowActivityAction;
	private compositeOverflowActionItem: CompositeOverflowActivityActionItem;

	private model: CompositeBarModel;
	private storedState: ISerializedCompositeBarItem[];
	private visibleComposites: string[];
	private compositeSizeInBar: Map<string, number>;

	constructor(
		private options: ICompositeBarOptions,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IStorageService private storageService: IStorageService,
		@IContextMenuService private contextMenuService: IContextMenuService
	) {
		super();

		this.model = new CompositeBarModel(options);
		this.storedState = this.loadCompositeItemsFromStorage();
		this.visibleComposites = [];
		this.compositeSizeInBar = new Map<string, number>();
	}

	getCompositesFromStorage(): string[] {
		return this.storedState.map(s => s.id);
	}

	create(parent: HTMLElement): HTMLElement {
		const actionBarDiv = parent.appendChild($('.composite-bar'));
		this.compositeSwitcherBar = this._register(new ActionBar(actionBarDiv, {
			actionItemProvider: (action: Action) => {
				if (action instanceof CompositeOverflowActivityAction) {
					return this.compositeOverflowActionItem;
				}
				const item = this.model.findItem(action.id);
				return item && this.instantiationService.createInstance(CompositeActionItem, action, item.pinnedAction, this.options.colors, this.options.icon, this);
			},
			orientation: this.options.orientation,
			ariaLabel: nls.localize('activityBarAriaLabel', "Active View Switcher"),
			animated: false,
		}));

		// Contextmenu for composites
		this._register(addDisposableListener(parent, EventType.CONTEXT_MENU, e => this.showContextMenu(e)));

		// Allow to drop at the end to move composites to the end
		this._register(addDisposableListener(parent, EventType.DROP, (e: DragEvent) => {
			const draggedCompositeId = CompositeActionItem.getDraggedCompositeId();
			if (draggedCompositeId) {
				EventHelper.stop(e, true);
				CompositeActionItem.clearDraggedComposite();

				const targetItem = this.model.items[this.model.items.length - 1];
				if (targetItem && targetItem.id !== draggedCompositeId) {
					this.move(draggedCompositeId, targetItem.id);
				}
			}
		}));

		return actionBarDiv;
	}

	layout(dimension: Dimension): void {
		this.dimension = dimension;
		if (dimension.height === 0 || dimension.width === 0) {
			// Do not layout if not visible. Otherwise the size measurment would be computed wrongly
			return;
		}

		if (this.compositeSizeInBar.size === 0) {
			// Compute size of each composite by getting the size from the css renderer
			// Size is later used for overflow computation
			this.computeSizes(this.model.items);
		}

		this.updateCompositeSwitcher();
	}

	addComposite({ id, name, order }: { id: string; name: string, order: number }): void {
		const state = this.storedState.filter(s => s.id === id)[0];
		const pinned = state ? state.pinned : true;
		let index = order >= 0 ? order : this.model.items.length;

		if (state) {
			// Find the index by looking its previous item
			index = 0;
			for (let i = this.storedState.indexOf(state) - 1; i >= 0; i--) {
				const previousItemId = this.storedState[i].id;
				const previousItemIndex = this.model.findIndex(previousItemId);
				if (previousItemIndex !== -1) {
					index = previousItemIndex + 1;
					break;
				}
			}
		}

		// Add to the model
		if (this.model.add(id, name, order, index)) {
			this.computeSizes([this.model.findItem(id)]);
			if (pinned) {
				this.pin(id);
			} else {
				this.updateCompositeSwitcher();
			}
		}
	}

	removeComposite(id: string): void {

		// If it pinned, unpin it first
		if (this.isPinned(id)) {
			this.unpin(id);
		}

		// Remove from the model
		if (this.model.remove(id)) {
			this.updateCompositeSwitcher();
		}
	}

	activateComposite(id: string): void {
		const previousActiveItem = this.model.activeItem;
		if (this.model.activate(id)) {
			// Update if current composite is neither visible nor pinned
			// or previous active composite is not pinned
			if (this.visibleComposites.indexOf(id) === - 1 || !this.model.activeItem.pinned || (previousActiveItem && !previousActiveItem.pinned)) {
				this.updateCompositeSwitcher();
			}
		}
	}

	deactivateComposite(id: string): void {
		const previousActiveItem = this.model.activeItem;
		if (this.model.deactivate()) {
			if (previousActiveItem && !previousActiveItem.pinned) {
				this.updateCompositeSwitcher();
			}
		}
	}

	showActivity(compositeId: string, badge: IBadge, clazz?: string, priority?: number): IDisposable {
		if (!badge) {
			throw illegalArgument('badge');
		}

		if (typeof priority !== 'number') {
			priority = 0;
		}

		const activity: ICompositeActivity = { badge, clazz, priority };
		this.model.addActivity(compositeId, activity);
		return toDisposable(() => this.model.removeActivity(compositeId, activity));
	}

	pin(compositeId: string, open?: boolean): void {
		if (this.model.setPinned(compositeId, true)) {
			this.updateCompositeSwitcher();

			if (open) {
				this.options.openComposite(compositeId)
					.done(() => this.activateComposite(compositeId)); // Activate after opening
			}
		}
	}

	unpin(compositeId: string): void {
		if (this.model.setPinned(compositeId, false)) {

			this.updateCompositeSwitcher();

			const defaultCompositeId = this.options.getDefaultCompositeId();

			// Case: composite is not the active one or the active one is a different one
			// Solv: we do nothing
			if (!this.model.activeItem || this.model.activeItem.id !== compositeId) {
				return;
			}

			// Deactivate itself
			this.deactivateComposite(compositeId);

			// Case: composite is not the default composite and default composite is still showing
			// Solv: we open the default composite
			if (defaultCompositeId !== compositeId && this.isPinned(defaultCompositeId)) {
				this.options.openComposite(defaultCompositeId);
			}

			// Case: we closed the last visible composite
			// Solv: we hide the part
			else if (this.visibleComposites.length === 1) {
				this.options.hidePart();
			}

			// Case: we closed the default composite
			// Solv: we open the next visible composite from top
			else {
				this.options.openComposite(this.visibleComposites.filter(cid => cid !== compositeId)[0]);
			}
		}
	}

	isPinned(compositeId: string): boolean {
		const item = this.model.findItem(compositeId);
		return item && item.pinned;
	}

	move(compositeId: string, toCompositeId: string): void {
		if (this.model.move(compositeId, toCompositeId)) {
			// timeout helps to prevent artifacts from showing up
			setTimeout(() => this.updateCompositeSwitcher(), 0);
		}
	}

	getAction(compositeId): ActivityAction {
		const item = this.model.findItem(compositeId);
		return item && item.activityAction;
	}

	private computeSizes(items: ICompositeBarItem[]): void {
		const size = this.options.compositeSize;
		if (size) {
			items.forEach(composite => this.compositeSizeInBar.set(composite.id, size));
		} else {
			if (this.dimension && this.dimension.height !== 0 && this.dimension.width !== 0) {
				// Compute sizes only if visible. Otherwise the size measurment would be computed wrongly.
				const currentItemsLength = this.compositeSwitcherBar.items.length;
				this.compositeSwitcherBar.push(items.map(composite => composite.activityAction));
				items.map((composite, index) => this.compositeSizeInBar.set(composite.id, this.options.orientation === ActionsOrientation.VERTICAL
					? this.compositeSwitcherBar.getHeight(currentItemsLength + index)
					: this.compositeSwitcherBar.getWidth(currentItemsLength + index)
				));
				items.forEach(() => this.compositeSwitcherBar.pull(this.compositeSwitcherBar.items.length - 1));
			}
		}
	}

	private updateCompositeSwitcher(): void {
		if (!this.compositeSwitcherBar || !this.dimension) {
			return; // We have not been rendered yet so there is nothing to update.
		}

		let compositesToShow = this.model.items.filter(item =>
			item.pinned
			|| (this.model.activeItem && this.model.activeItem.id === item.id) /* Show the active composite even if it is not pinned */
		).map(item => item.id);

		// Ensure we are not showing more composites than we have height for
		let overflows = false;
		let maxVisible = compositesToShow.length;
		let size = 0;
		const limit = this.options.orientation === ActionsOrientation.VERTICAL ? this.dimension.height : this.dimension.width;
		for (let i = 0; i < compositesToShow.length && size <= limit; i++) {
			size += this.compositeSizeInBar.get(compositesToShow[i]);
			if (size > limit) {
				maxVisible = i;
			}
		}
		overflows = compositesToShow.length > maxVisible;

		if (overflows) {
			size -= this.compositeSizeInBar.get(compositesToShow[maxVisible]);
			compositesToShow = compositesToShow.slice(0, maxVisible);
			size += this.options.overflowActionSize;
		}
		// Check if we need to make extra room for the overflow action
		if (size > limit) {
			size -= this.compositeSizeInBar.get(compositesToShow.pop());
		}

		// We always try show the active composite
		if (this.model.activeItem && compositesToShow.every(compositeId => compositeId !== this.model.activeItem.id)) {
			const removedComposite = compositesToShow.pop();
			size = size - this.compositeSizeInBar.get(removedComposite) + this.compositeSizeInBar.get(this.model.activeItem.id);
			compositesToShow.push(this.model.activeItem.id);
		}

		// The active composite might have bigger size than the removed composite, check for overflow again
		if (size > limit) {
			compositesToShow.length ? compositesToShow.splice(compositesToShow.length - 2, 1) : compositesToShow.pop();
		}

		const visibleCompositesChange = !arrays.equals(compositesToShow, this.visibleComposites);

		// Pull out overflow action if there is a composite change so that we can add it to the end later
		if (this.compositeOverflowAction && visibleCompositesChange) {
			this.compositeSwitcherBar.pull(this.compositeSwitcherBar.length() - 1);

			this.compositeOverflowAction.dispose();
			this.compositeOverflowAction = null;

			this.compositeOverflowActionItem.dispose();
			this.compositeOverflowActionItem = null;
		}

		// Pull out composites that overflow or got hidden
		const compositesToRemove: number[] = [];
		this.visibleComposites.forEach((compositeId, index) => {
			if (compositesToShow.indexOf(compositeId) === -1) {
				compositesToRemove.push(index);
			}
		});
		compositesToRemove.reverse().forEach(index => {
			const actionItem = this.compositeSwitcherBar.items[index];
			this.compositeSwitcherBar.pull(index);
			actionItem.dispose();
			this.visibleComposites.splice(index, 1);
		});

		// Update the positions of the composites
		compositesToShow.forEach((compositeId, newIndex) => {
			const currentIndex = this.visibleComposites.indexOf(compositeId);
			if (newIndex !== currentIndex) {
				if (currentIndex !== -1) {
					const actionItem = this.compositeSwitcherBar.items[currentIndex];
					this.compositeSwitcherBar.pull(currentIndex);
					actionItem.dispose();
					this.visibleComposites.splice(currentIndex, 1);
				}

				this.compositeSwitcherBar.push(this.model.findItem(compositeId).activityAction, { label: true, icon: this.options.icon, index: newIndex });
				this.visibleComposites.splice(newIndex, 0, compositeId);
			}
		});

		// Add overflow action as needed
		if ((visibleCompositesChange && overflows) || this.compositeSwitcherBar.length() === 0) {
			this.compositeOverflowAction = this.instantiationService.createInstance(CompositeOverflowActivityAction, () => this.compositeOverflowActionItem.showMenu());
			this.compositeOverflowActionItem = this.instantiationService.createInstance(
				CompositeOverflowActivityActionItem,
				this.compositeOverflowAction,
				() => this.getOverflowingComposites(),
				() => this.model.activeItem ? this.model.activeItem.id : void 0,
				(compositeId: string) => {
					const item = this.model.findItem(compositeId);
					return item && item.activity[0] && item.activity[0].badge;
				},
				this.options.getOnCompositeClickAction,
				this.options.colors
			);

			this.compositeSwitcherBar.push(this.compositeOverflowAction, { label: false, icon: true });
		}

		// Persist
		this.saveCompositeItems();
	}

	private getOverflowingComposites(): { id: string, name: string }[] {
		let overflowingIds = this.model.items.filter(item => item.pinned).map(item => item.id);

		// Show the active composite even if it is not pinned
		if (this.model.activeItem && !this.model.activeItem.pinned) {
			overflowingIds.push(this.model.activeItem.id);
		}

		overflowingIds = overflowingIds.filter(compositeId => this.visibleComposites.indexOf(compositeId) === -1);
		return this.model.items.filter(c => overflowingIds.indexOf(c.id) !== -1);
	}

	private showContextMenu(e: MouseEvent): void {
		EventHelper.stop(e, true);
		const event = new StandardMouseEvent(e);
		const actions: IAction[] = this.model.items
			.map(({ id, name, activityAction }) => (<IAction>{
				id,
				label: name,
				checked: this.isPinned(id),
				enabled: activityAction.enabled,
				run: () => {
					if (this.isPinned(id)) {
						this.unpin(id);
					} else {
						this.pin(id, true);
					}
				}
			}));
		const otherActions = this.options.getContextMenuActions();
		if (otherActions.length) {
			actions.push(new Separator());
			actions.push(...otherActions);
		}
		this.contextMenuService.showContextMenu({
			getAnchor: () => { return { x: event.posx, y: event.posy }; },
			getActions: () => TPromise.as(actions),
		});
	}

	private loadCompositeItemsFromStorage(): ISerializedCompositeBarItem[] {
		const storedStates = <Array<string | ISerializedCompositeBarItem>>JSON.parse(this.storageService.get(this.options.storageId, StorageScope.GLOBAL, '[]'));
		const compositeStates = <ISerializedCompositeBarItem[]>storedStates.map(c =>
			typeof c === 'string' /* migration from pinned states to composites states */ ? { id: c, pinned: true } : c);
		return compositeStates;
	}

	private saveCompositeItems(): void {
		this.storedState = this.model.toJSON();
		this.storageService.store(this.options.storageId, JSON.stringify(this.storedState), StorageScope.GLOBAL);
	}
}

interface ISerializedCompositeBarItem {
	id: string;
	pinned: boolean;
	order: number;
}

interface ICompositeBarItem extends ISerializedCompositeBarItem {
	name: string;
	activityAction: ActivityAction;
	pinnedAction: Action;
	activity: ICompositeActivity[];
}

class CompositeBarModel {

	readonly items: ICompositeBarItem[] = [];
	activeItem: ICompositeBarItem;

	constructor(private options: ICompositeBarOptions) { }

	private createCompositeBarItem(id: string, name: string, order: number, pinned: boolean): ICompositeBarItem {
		const options = this.options;
		return {
			id, name, pinned, order, activity: [],
			get activityAction() {
				return options.getActivityAction(id);
			},
			get pinnedAction() {
				return options.getCompositePinnedAction(id);
			}
		};
	}

	add(id: string, name: string, order: number, index: number): boolean {
		const item = this.findItem(id);
		if (item) {
			item.order = order;
			item.name = name;
			return false;
		} else {
			if (index === void 0) {
				index = 0;
				while (index < this.items.length && this.items[index].order < order) {
					index++;
				}
			}
			this.items.splice(index, 0, this.createCompositeBarItem(id, name, order, false));
			return true;
		}
	}

	remove(id: string): boolean {
		for (let index = 0; index < this.items.length; index++) {
			if (this.items[index].id === id) {
				this.items.splice(index, 1);
				return true;
			}
		}
		return false;
	}

	move(compositeId: string, toCompositeId: string): boolean {

		const fromIndex = this.findIndex(compositeId);
		const toIndex = this.findIndex(toCompositeId);

		// Make sure both items are known to the model
		if (fromIndex === -1 || toIndex === -1) {
			return false;
		}

		const sourceItem = this.items.splice(fromIndex, 1)[0];
		this.items.splice(toIndex, 0, sourceItem);

		// Make sure a moved composite gets pinned
		sourceItem.pinned = true;

		return true;
	}

	setPinned(id: string, pinned: boolean): boolean {
		for (let index = 0; index < this.items.length; index++) {
			const item = this.items[index];
			if (item.id === id) {
				if (item.pinned !== pinned) {
					item.pinned = pinned;
					return true;
				}
				return false;
			}
		}
		return false;
	}

	addActivity(id: string, activity: ICompositeActivity): boolean {
		const item = this.findItem(id);
		if (item) {
			const stack = item.activity;
			for (let i = 0; i <= stack.length; i++) {
				if (i === stack.length) {
					stack.push(activity);
					break;
				} else if (stack[i].priority <= activity.priority) {
					stack.splice(i, 0, activity);
					break;
				}
			}
			this.updateActivity(id);
			return true;
		}
		return false;
	}

	removeActivity(id: string, activity: ICompositeActivity): boolean {
		const item = this.findItem(id);
		if (item) {
			const index = item.activity.indexOf(activity);
			if (index !== -1) {
				item.activity.splice(index, 1);
				this.updateActivity(id);
				return true;
			}
		}
		return false;
	}

	updateActivity(id: string): void {
		const item = this.findItem(id);
		if (item) {
			if (item.activity.length) {
				const [{ badge, clazz }] = item.activity;
				item.activityAction.setBadge(badge, clazz);
			}
			else {
				item.activityAction.setBadge(undefined);
			}
		}
	}

	activate(id: string): boolean {
		if (!this.activeItem || this.activeItem.id !== id) {
			if (this.activeItem) {
				this.deactivate();
			}
			for (let index = 0; index < this.items.length; index++) {
				const item = this.items[index];
				if (item.id === id) {
					this.activeItem = item;
					this.activeItem.activityAction.activate();
					return true;
				}
			}
		}
		return false;
	}

	deactivate(): boolean {
		if (this.activeItem) {
			this.activeItem.activityAction.deactivate();
			this.activeItem = void 0;
			return true;
		}
		return false;
	}

	findItem(id: string): ICompositeBarItem {
		return this.items.filter(item => item.id === id)[0];
	}

	findIndex(id: string): number {
		for (let index = 0; index < this.items.length; index++) {
			if (this.items[index].id === id) {
				return index;
			}
		}
		return -1;
	}

	toJSON(): ISerializedCompositeBarItem[] {
		return this.items.map(({ id, pinned, order }) => ({ id, pinned, order }));
	}
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>sandbox</title>
        <link rel="stylesheet" href="sandboxed.css">


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Bootstrap Template</title>

    <link href="../css/bootstrap.min.css" rel="stylesheet">

    默认的复选框和单选按钮的实例

        <input type="checkbox" value="">选项 1

        <input type="checkbox" value="">选项 2

            <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked> 选项 1

            <input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">
            选项 2 - 选择它将会取消选择选项 1

    内联的复选框和单选按钮的实例

            <input type="checkbox" id="inlineCheckbox1" value="option1"> 选项 1

            <input type="checkbox" id="inlineCheckbox2" value="option2"> 选项 2

            <input type="checkbox" id="inlineCheckbox3" value="option3"> 选项 3

            <input type="radio" name="optionsRadiosinline" id="optionsRadios3" value="option1" checked> 选项 1

            <input type="radio" name="optionsRadiosinline" id="optionsRadios4" value="option2"> 选项 2


text:
#include "errcode.h"
#include "file.h"
#include "util.h"
#include "yasm.h"

#include <ctype.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#if defined(_MSC_VER) && (_MSC_VER < 1900)
#  define snprintf _snprintf_c
#endif

static int create_section_label_name(char *label, size_t size,
				     const char *name, const char *attribute)
{
	int written;

	written = snprintf(label, size, "section_%s_%s", name, attribute);
	if ((written < 0) || (size <= (size_t) written))
		return -err_no_mem;

	return 0;
}

static int add_section_label(struct label *l, const char *name,
			     const char *attribute, uint64_t value,
			     struct label **length)
{
	char label[255];
	int errcode;

	errcode = create_section_label_name(label, sizeof(label), name,
					    attribute);
	if (errcode < 0)
		return errcode;

	errcode = l_append(l, label, value);
	if (errcode < 0)
		return errcode;

	if (length)
		*length = l_find(l, label);

	return 0;
}

static int parse_section_label(struct label *l, const char *name,
			       const char *attribute)
{
	uint64_t addr;
	char *value;

	value = strtok(NULL, " ]");
	if (!value)
		return -err_section_attribute_no_value;

	if (sscanf(value, "%" PRIx64, &addr) != 1)
		return -err_parse_int;

	return add_section_label(l, name, attribute, addr, NULL);
}

static int parse_section(char *line, struct label *l, struct label **length)
{
	char *name, *attribute;
	int errcode;

	name = strtok(line, " ");
	if (!name)
		return -err_section_no_name;

	/* we initialize the section's length to zero - it will be updated
	 * when we process the section's content.
	 */
	errcode = add_section_label(l, name, "length", 0ull, length);
	if (errcode < 0)
		return errcode;

	for (;;) {
		attribute = strtok(NULL, " =]");
		if (!attribute)
			return 0;

		if (strcmp(attribute, "start") == 0) {
			errcode = parse_section_label(l, name, "start");
			if (errcode < 0)
				return errcode;
		} else if (strcmp(attribute, "vstart") == 0) {
			errcode = parse_section_label(l, name, "vstart");
			if (errcode < 0)
				return errcode;
		} else
			return -err_section_unknown_attribute;
	}
}

static int lookup_section_label(struct label *l, const char *name,
				const char *attribute, uint64_t *value)
{
	char label[255];
	int errcode;

	errcode = create_section_label_name(label, sizeof(label), name,
					    attribute);
	if (errcode < 0)
		return errcode;

	return l_lookup(l, value, label);
}

static int lookup_section_vstart(struct label *l, char *line,
				 uint64_t *vstart)
{
	char *name;

	name = strtok(line, " ");
	if (!name)
		return -err_section_no_name;

	return lookup_section_label(l, name, "vstart", vstart);
}

static const char key_section[] = "[section";
static const char key_org[] = "[org";

int parse_yasm_labels(struct label *l, const struct text *t)
{
	int errcode, no_org_directive;
	size_t i;
	uint64_t base_addr;
	char line[1024], *end;
	struct label *length;

	if (bug_on(!t))
		return -err_internal;

	base_addr = 0;
	no_org_directive = 1;
	length = NULL;
	end = line + sizeof(line);

	/* determine base address from org directive and insert special
	 * section labels.
	 */
	for (i = 0; i < t->n; i++) {
		char *tmp;

		errcode = text_line(t, line, sizeof(line), i);
		if (errcode < 0)
			return errcode;

		tmp = strstr(line, key_section);
		if (tmp) {
			tmp += sizeof(key_section) - 1;
			errcode = parse_section(tmp, l, &length);
			if (errcode < 0)
				return errcode;
			continue;
		}

		tmp = strstr(line, key_org);
		if (tmp) {
			char *org;

			org = tmp + sizeof(key_org) - 1;
			tmp = strstr(org, "]");
			if (!tmp)
				return -err_no_org_directive;

			*tmp = 0;

			errcode = str_to_uint64(org, &base_addr, 0);
			if (errcode < 0)
				return errcode;

			errcode = l_append(l, "org", base_addr);
			if (errcode < 0)
				return errcode;

			no_org_directive = 0;
			continue;
		}

		/* update the section_<name>_length label, if we have one.
		 *
		 * this must be last; it destroys @line.
		 */
		if (length) {
			uint64_t value, size;

			tmp = strtok(line, " ");
			if (!tmp)
				continue;

			/* we expect a line number. */
			errcode = str_to_uint64(tmp, &value, 10);
			if (errcode < 0)
				continue;

			tmp = strtok(NULL, " ");
			if (!tmp)
				continue;

			/* we expect an address. */
			errcode = str_to_uint64(tmp, &value, 16);
			if (errcode < 0)
				continue;

			tmp = strtok(NULL, " ");
			if (!tmp)
				continue;

			/* we expect an opcode. */
			errcode = str_to_uint64(tmp, &value, 16);
			if (errcode < 0)
				continue;

			/* we got an opcode - let's compute it's size. */
			for (size = 0; value != 0; value >>= 8)
				size += 1;

			/* update the section_<name>_length label. */
			length->addr += size;
		}
	}

	if (no_org_directive)
		return -err_no_org_directive;

	for (i = 0; i < t->n; i++) {
		char *tmp;
		uint64_t addr;

		errcode = text_line(t, line, sizeof(line), i);
		if (errcode < 0)
			goto error;

		/* Change the base on section switches. */
		tmp = strstr(line, key_section);
		if (tmp) {
			tmp += sizeof(key_section) - 1;
			errcode = lookup_section_vstart(l, tmp, &base_addr);
			if (errcode < 0)
				return errcode;
			continue;
		}

		/* skip line number count.  */
		tmp = strtok(line, " ");
		if (!tmp)
			continue;

		/* the label can now be on the same line as the memory
		 * address or on a line by its own.
		 * we look at the next token and (1) if it looks like a
		 * label, we search in the following lines for the
		 * corresponding address; or (2) if it looks like an
		 * address, we store it and see if the token after the
		 * opcode looks like a token; or (3) none of the above,
		 * we continue with the next line.
		 */

		/* second token after the line number count.  it's
		 * either an address; or a label.
		 */
		tmp = strtok(NULL, " ");
		if (!tmp)
			continue;

		if (!make_label(tmp, end)) {
			uint64_t laddr;

			/* get address in case we find a label later.  */
			if (sscanf(tmp, "%" PRIx64, &addr) != 1)
				continue;

			/* skip the opcode token.  */
			tmp = strtok(NULL, " ");
			if (!tmp)
				continue;

			/* this might be a label now.  */
			tmp = strtok(NULL, " ");
			if (!make_label(tmp, end))
				continue;

			laddr = addr + base_addr;
			if (laddr < base_addr) {
				errcode = -err_label_addr;
				goto error;
			}

			errcode = l_append(l, tmp, laddr);
			if (errcode < 0)
				goto error;
			continue;
		}

		/* there was a label so now an address needs to
		 * be found.
		 */
		errcode = -err_label_addr;
		for (i += 1; i < t->n; i++) {
			int errcode_text;

			errcode_text = text_line(t, line, sizeof(line), i);
			if (errcode_text < 0) {
				errcode = errcode_text;
				break;
			}
			if (sscanf(line, "%*d %" PRIx64 " %*x %*s", &addr)
			    == 1) {
				uint64_t laddr;

				laddr = addr + base_addr;
				if (laddr < base_addr) {
					errcode = -err_label_addr;
					break;
				}

				errcode = l_append(l, tmp, laddr);
				break;
			}
		}
		if (errcode == -err_label_addr)
			fprintf(stderr, "label '%s' has no address\n", tmp);

		if (errcode < 0)
			goto error;
	}

	return 0;

error:
	l_free(l->next);
	free(l->name);
	l->next = NULL;
	l->name = NULL;
	return errcode;
}

int make_label(char *s, const char *end)
{
	size_t n, size;

	if (bug_on(!s))
		return 0;

	if (bug_on(end <= s))
		return 0;

	size = (size_t) ((uintptr_t) end - (uintptr_t) s);
	n = strnlen(s, size);
	if (size <= n)
		return 0;

	if (n == 0 || s[n-1] != ':')
		return 0;

	s[n-1] = '\0';
	return 1;
}

struct state *st_alloc(void)
{
	return calloc(1, sizeof(struct state));
}

void st_free(struct state *st)
{
	if (!st)
		return;

	free(st->filename);
	free(st->line);
	free(st);
}

int st_print_err(const struct state *st, const char *s, int errcode)
{
	if (bug_on(!st))
		return -err_internal;

	if (bug_on(!(-err_max < errcode && errcode < 0)))
		return -err_internal;

	if (!s)
		s = "";

	fprintf(stderr, "%s:%d: error: %s (%s)\n", st->filename, st->n-1, s,
		errstr[-errcode]);

	return errcode;
}

/* Sets current @filename, increment (@inc) and line number (@n) in @st.
 *
 * Note that @filename, @inc and @n correspond to the yasm .lst file
 * source file information.
 *
 * Returns 0 on success; a negative enum errcode otherwise.
 */
static int st_set_file(struct state *st, const char *filename, int inc, int n)
{
	int errcode;

	if (bug_on(!st))
		return -err_internal;

	if (bug_on(!filename))
		return -err_internal;

	free(st->filename);
	errcode = duplicate_name(&st->filename, filename, FILENAME_MAX);
	if (errcode < 0)
		return errcode;

	st->inc = inc;
	st->n = n;
	return 0;
}

/* Sets current line in @st to @s and increases the line number.
 *
 * Returns 0 on success; a negative enum errcode otherwise.
 */
static int st_update(struct state *st, const char *s)
{
	int errcode;

	free(st->line);
	st->line = NULL;

	errcode = duplicate_name(&st->line, s, FILENAME_MAX);
	if (errcode < 0)
		return errcode;

	st->n += st->inc;
	return 0;
}

struct pt_directive *pd_alloc(size_t n)
{
	struct pt_directive *pd;

	pd = calloc(1, sizeof(*pd));
	if (!pd)
		return NULL;

	pd->name = malloc(n);
	if (!pd->name)
		goto error;

	pd->payload = malloc(n);
	if (!pd->payload)
		goto error;

	pd->nlen = n;
	pd->plen = n;

	return pd;

error:
	pd_free(pd);
	return NULL;
}

void pd_free(struct pt_directive *pd)
{
	if (!pd)
		return;

	free(pd->name);
	free(pd->payload);
	free(pd);
}

int pd_set(struct pt_directive *pd, enum pt_directive_kind kind,
	   const char *name, const char *payload)
{
	if (bug_on(!pd))
		return -err_internal;

	if (bug_on(!name))
		return -err_internal;

	if (bug_on(!payload))
		return -err_internal;

	pd->kind = kind;
	strncpy(pd->name, name, pd->nlen);
	if (pd->nlen > 0)
		pd->name[pd->nlen - 1] = '\0';
	strncpy(pd->payload, payload, pd->plen);
	if (pd->plen > 0)
		pd->payload[pd->plen - 1] = '\0';

	return 0;
}

/* Magic annotation markers.  */
static const char pt_marker[] = "@pt ";

#if defined(FEATURE_SIDEBAND)
static const char sb_marker[] = "@sb ";
#endif

int pd_parse(struct pt_directive *pd, struct state *st)
{
	enum pt_directive_kind kind;
	char *line, *comment, *openpar, *closepar, *directive, *payload;
	int errcode;
	char *c;

	if (bug_on(!pd))
		return -err_internal;

	if (bug_on(!st))
		return -err_internal;

	errcode = duplicate_name(&line, st->line, FILENAME_MAX);
	if (errcode < 0)
		return errcode;

	/* make line lower case.  */
	for (c = line; *c; ++c)
		*c = (char) tolower(*c);

	/* if the current line is not a comment or contains no magic marker
	 * -err_no_directive is returned.
	 */
	errcode = -err_no_directive;

	/* search where the comment begins.  */
	comment = strchr(line, ';');

	/* if there is no comment in the line, we don't have anything to
	 * do.
	 */
	if (!comment)
		goto cleanup;

	/* search for @pt marker.  */
	directive = strstr(comment+1, pt_marker);
	if (directive) {
		directive += sizeof(pt_marker) - 1;
		kind = pdk_pt;
	} else {
#if defined(FEATURE_SIDEBAND)
		/* search for @sb marker. */
		directive = strstr(comment+1, sb_marker);
		if (directive) {
			directive += sizeof(sb_marker) - 1;
			kind = pdk_sb;
		} else
#endif
			goto cleanup;
	}

	/* skip leading whitespace. */
	while (isspace(*directive))
		directive += 1;

	/* directive found, now parse the payload.  */
	errcode = 0;

	/* find position of next '(', separating the directive and the
	 * payload.
	 */
	openpar = strchr(directive, '(');
	if (!openpar) {
		errcode = -err_missing_openpar;
		st_print_err(st, "invalid syntax", errcode);
		goto cleanup;
	}

	/* find position of next ')', marking the end of the payload */
	closepar = strchr(openpar, ')');
	if (!closepar) {
		errcode = -err_missing_closepar;
		st_print_err(st, "invalid syntax", errcode);
		goto cleanup;
	}

	/* make "multiple" strings by artifically terminating them with
	 * '\0' then get directive and payload substrings, which will
	 * have leading and trailing whitespace "removed".
	 */
	*openpar = '\0';
	*closepar = '\0';

	payload = openpar+1;

	errcode = pd_set(pd, kind, directive, payload);

cleanup:
	free(line);
	return errcode;
}

static const char bin_suffix[] = ".bin";
static const char lst_suffix[] = ".lst";
static const char path_separator = '/';

struct yasm *yasm_alloc(const char *pttfile)
{
	char *tmp;
	size_t flen, binsize, lstsize;
	struct yasm *y;
	int errcode, len;

	if (bug_on(!pttfile))
		return NULL;

	y = calloc(1, sizeof(*y));
	if (!y)
		return NULL;

	y->fl = fl_alloc();
	if (!y->fl)
		goto error;

	y->st_asm = st_alloc();
	if (!y->st_asm)
		goto error;

	errcode = duplicate_name(&y->fileroot, pttfile, FILENAME_MAX);
	if (errcode < 0)
		goto error;

	errcode = duplicate_name(&y->pttfile, pttfile, FILENAME_MAX);
	if (errcode < 0)
		goto error;

	tmp = strrchr(y->fileroot, '.');
	if (tmp)
		*tmp = '\0';

	tmp = strrchr(y->fileroot, path_separator);
	if (tmp) {
		tmp += 1;

		flen = strnlen(tmp, FILENAME_MAX);
		if (FILENAME_MAX <= flen)
			goto error;

		memmove(y->fileroot, tmp, flen);
		y->fileroot[flen] = '\0';
	}

	flen = strnlen(y->fileroot, FILENAME_MAX);
	if (FILENAME_MAX <= flen)
		goto error;

	binsize = flen + sizeof(bin_suffix);
	lstsize = flen + sizeof(lst_suffix);

	y->binfile = malloc(binsize);
	if (!y->binfile)
		goto error;

	len = snprintf(y->binfile, binsize, "%s%s", y->fileroot, bin_suffix);
	if ((len < 0) || ((size_t) len != (binsize - 1)))
		goto error;

	y->lstfile = malloc(lstsize);
	if (!y->lstfile)
		goto error;

	len = snprintf(y->lstfile, lstsize, "%s%s", y->fileroot, lst_suffix);
	if ((len < 0) || ((size_t) len != (lstsize - 1)))
		goto error;

	y->l = l_alloc();
	if (!y->l)
		goto error;

	return y;

error:
	yasm_free(y);
	return 0;
}

static int yasm_run(struct yasm *y)
{
	char *argv[] = {
		"yasm",
		"<pttfile>",
		"-f", "bin",
		"-o", "<binfile>",
		"-L", "nasm",
		"-l", "<lstfile>",
		NULL,
	};

	argv[1] = y->pttfile;
	argv[5] = y->binfile;
	argv[9] = y->lstfile;

	return run(argv[0], argv);
}

int yasm_parse(struct yasm *y)
{
	int errcode;
	const struct text *t;

	if (bug_on(!y))
		return -err_internal;

	errcode = yasm_run(y);
	if (errcode < 0)
		goto error;

	errcode = fl_gettext(y->fl, &t, y->lstfile);
	if (errcode < 0)
		goto error;

	errcode = parse_yasm_labels(y->l, t);
	if (errcode < 0)
		goto error;

error:
	return errcode;
}

void yasm_free(struct yasm *y)
{
	if (!y)
		return;

	free(y->fileroot);
	free(y->pttfile);
	free(y->lstfile);
	free(y->binfile);
	fl_free(y->fl);
	st_free(y->st_asm);
	l_free(y->l);
	free(y);
}

int yasm_lookup_label(const struct yasm *y, uint64_t *addr,
		      const char *labelname)
{
	if (bug_on(!y))
		return -err_internal;

	return l_lookup(y->l, addr, labelname);
}

static int yasm_advance_next_line(struct yasm *y)
{
	char s[1024];
	char filename[FILENAME_MAX];
	int errcode;
	int asm_line, asm_inc;

	if (bug_on(!y))
		return -err_internal;

	for (;;) {
		errcode = fl_getline(y->fl, s, sizeof(s), y->lstfile,
				     (size_t) y->lst_curr_line);
		/* always advance in lst file.  */
		y->lst_curr_line += 1;

		if (errcode < 0)
			break;

		/* if the current lst file line is a line directive, set
		 * state information to this file, line and increment
		 * and continue.
		 */
		if (sscanf(s, "%*d %%line %d+%d %1023[^\r\n]", &asm_line,
			   &asm_inc, filename) == 3) {
			st_set_file(y->st_asm, filename, asm_line, asm_inc);
			continue;
		}

		/* if line number or increment in the previous line
		 * directive is <= 0, the current lst line has no
		 * corresponding line in the source file.
		 */
		if (y->st_asm->n <= 0 || y->st_asm->inc <= 0)
			continue;

		/* finally the current line in the lst file can be
		 * correlated to the source file, so we retrieve the
		 * line from it and update the state.
		 */
		errcode = fl_getline(y->fl, s, (size_t) sizeof(s),
				     y->st_asm->filename,
				     (size_t) y->st_asm->n - 1u);
		if (errcode < 0)
			break;

		errcode = st_update(y->st_asm, s);
		break;
	}

	return errcode;
}

int yasm_pd_parse(struct yasm *y, struct pt_directive *pd)
{
	return pd_parse(pd, y->st_asm);
}

int yasm_next_pt_directive(struct yasm *y, struct pt_directive *pd)
{
	int errcode;

	for (;;) {
		errcode = yasm_advance_next_line(y);
		if (errcode < 0)
			break;

		errcode = pd_parse(pd, y->st_asm);
		if (errcode != -err_no_directive)
			return errcode;

	}
	if (errcode == -err_out_of_range)
		errcode = -err_no_directive;

	return errcode;
}

int yasm_next_line(struct yasm *y, char *dest, size_t destlen)
{
	int errcode;

	if (!destlen)
		return 0;

	if (bug_on(!dest))
		return -err_internal;

	errcode = yasm_advance_next_line(y);
	if (errcode < 0)
		return errcode;

	strncpy(dest, y->st_asm->line, destlen);
	dest[destlen-1] = '\0';

	return 0;
}

int yasm_print_err(const struct yasm *y, const char *s, int errcode)
{
	if (bug_on(!y))
		return -err_internal;

	return st_print_err(y->st_asm, s, errcode);
}

int yasm_lookup_section_label(const struct yasm *y, const char *name,
			      const char *attribute, uint64_t *value)
{
	if (bug_on(!y))
		return -err_internal;

	return lookup_section_label(y->l, name, attribute, value);
}


text:
package com.sokeri.hypercycle;

import android.os.Bundle;

import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.sokeri.hypercycle.HyperCycle;

public class AndroidLauncher extends AndroidApplication {
	@Override
	protected void onCreate (Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
		config.useImmersiveMode = true;
		initialize(new HyperCycle(), config);
	}
}


text:
var companies = [
	{
		name: "gaz",
		productPrice: 562
	},
	{
		name: "kamaz",
		productPrice: 512
	},
	{
		name: "nefaz",
		productPrice: 122
	},
	{
		name: "mak",
		productPrice: 221
	},
];

console.log(companies);

var orderCount = document.getElementById('orderCount');
var result = document.getElementById('result');

var plus = document.getElementById('plus');
var minus = document.getElementById('minus');

var buttonAdd = document.getElementById('add');

var price = 0;

var arr = companies.map(function(item, number) {
	console.log(item);
	console.log(number);
})

console.log(arr);

plus.onclick = function() {
	orderCount.value++;
	price = Math.min.apply(Math, companies.map(function(o) {
		return o.productPrice;
	})) * orderCount.value;
	result.innerHTML = 'result: ' + price;
	console.log(price);
}

minus.onclick = function() {
	orderCount.value--;
	price = Math.min.apply(Math, companies.map(function(o) {
		return o.productPrice;
	})) * orderCount.value;
	result.innerHTML = 'result: ' + price;
	console.log(price);
}

buttonAdd.onclick =function(){
	var obj ={};
	obj.name =document.getElementById('name').value;
	obj.productPrice =parseInt(document.getElementById('price').value);
	console.log(obj);
	companies.push(obj)

	addToTable(obj);

        document.getElementById('name').value = "";
	document.getElementById('price').value = "";
}

function addToTable(company){

    var table = document.createElement('table');
    // Insert New Row for table at index '0'.
    var row1 = table.insertRow(0);
    // Insert New Column for Row1 at index '0'.
    var row1col1 = row1.insertCell(0);
    row1col1.innerHTML = company.name;
    // Insert New Column for Row1 at index '1'.
    var row1col2 = row1.insertCell(1);
    row1col2.innerHTML = company.productPrice;
    // Append Table into div.
    var div = document.getElementById('divTable');
    div.appendChild(table);
}

(function createTable(){
	for (i = 0; i < companies.length; i++ ){

		addToTable(companies[i]);
	}
})();


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('validated-input', 'Integration | Component | validated input', {
  integration: true
});

test('it renders', function(assert) {
  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });

  this.render(hbs`{{validated-input}}`);

  assert.equal(this.$().text().trim(), '');
});


text:
oc-client
=========

Node.js client for [OpenComponents](https://github.com/opentable/oc)

[![NPM](https://nodei.co/npm/oc-client.png?downloads=true)](https://npmjs.org/package/oc-client)

Node.js version: **0.10.0** required

Build status: Linux: [![Build Status](https://secure.travis-ci.org/opentable/oc.png?branch=master)](http://travis-ci.org/opentable/oc) | Windows: [![Build status](https://ci.appveyor.com/api/projects/status/8cklgw4hymutqrsg?svg=true)](https://ci.appveyor.com/project/matteofigus/oc)

Disclaimer: This project is still under heavy development and the API is likely to change at any time. In case you would find any issues, check the [troubleshooting page](../CONTRIBUTING.md#troubleshooting).

# API

### new Client(options)

It will create an instance of the client. Options:

|Parameter|type|mandatory|description|
|---------|----|---------|-----------|
|`cache`|`object`|no|Cache options. If null or empty will use default settings (never flush the cache)|
|`cache.flushInterval`|`number` (seconds)|no|The interval for flushing the cache|
|`components`|`object`|yes|The components to consume with versions|
|`components[name]`|`string`|yes|The component version|
|`forwardAcceptLanguageToClient`|`boolean`|no|Default false. When true, when doing client-side requests (normal or failover) appends a custom parameter to the browser's component hrefs so that the framework will ignore the browser's Accept-Language in favour of the query-string value|
|`registries`|`object`|yes|The registries' endpoints|
|`registries.serverRendering`|`string`|no|The baseUrl for server-side rendering requests|
|`registries.clientRendering`|`string`|no|The baseUrl for client-side rendering requests|

Example:

```js
var Client = require('oc-client');

var client = new Client({
  registries: { serverRendering: 'https://myregistry.com/'},
  components: {
    hello: '1.2.3',
    world: '~2.2.5',
    bla: ''
  }
});
```

### Client#init(options, callback)

It will warmup the components that have been declared during the instantiation. Options:

|Parameter|type|mandatory|description|
|---------|----|---------|-----------|
|`headers`|`object`|no|An object containing all the headers that must be forwarded to the components' requests|
|`timeout`|`number` (seconds)|no|Default 5. Maximum amount of time to wait during requests|

Example:

```js
var Client = require('oc-client');

var client = new Client({
  registries: { serverRendering: 'https://myregistry.com/'},
  components: {
    hello: '1.2.3'
  }
});

client.init({
  headers { 'accept-language': 'en-US'}
}, function(error, responses){
  console.log(error);
  // => something like null or Error making request to registry

  console.log(responses);
  // => something like { hello: '<b>hello</b>'}
});
```

### Client#renderComponent(componentName [, options], callback)

It will resolve a component href, will make a request to the registry, and will render the component. The callback will contain an error (if present) and rendered html.

Options:

|Parameter|type|mandatory|description|
|---------|----|---------|-----------|
|`container`|`boolean`|no|Default true, when false, renders a component without its <oc-component> container|
|`disableFailoverRendering`|`boolean`|no|Disables the automatic failover rendering in case the registry times-out (in case configuration.registries.clientRendering contains a valid value.) Default false|
|`forwardAcceptLanguageToClient`|`boolean`|no|When not specified in config, defaults to false. When true, when doing client-side requests (normal or failover) appends a custom parameter to the browser's component hrefs so that the framework will ignore the browser's Accept-Language in favour of the query-string value|
|`headers`|`object`|no|An object containing all the headers that must be forwarded to the component|
|`ie8`|`boolean`|no|Default false, if true puts in place the necessary polyfills to make all the stuff work with ie8|
|`parameters`|`object`|no|An object containing the parameters for component's request|
|`render`|`string`|no|Default `server`. When `server`, it will return html. When `client` will produce the html to put in the page for post-poning the rendering to the browser|
|`timeout`|`number` (seconds)|no|Default 5. When request times-out, the callback will be fired with a timeout error and a client-side rendering response (unless `disableFailoverRendering` is set to `true`)|

Example:
```js
...
client.renderComponent('header', {
  container: false,
  headers: {
    'accept-language': 'en-GB'
  },
  parameters: {
    loggedIn: true
  },
  timeout: 2
}, function(err, html){
  console.log(html);
  // => "<div>This is the header. <a>Log-out</a></div>"
});
```

### Client#renderComponents(components [, options], callback)

It will make a request to the registry, and will render the components. The callback will contain an array of errors (array of `null` in case there aren't any) and an array of rendered html snippets. It will follow the same order of the request. This method will make **1** request to the registry + **n** requests for each component to get the views of components that aren't cached yet. After caching the views, this will make just **1** request to the registry.

Components parameter:

|Parameter|type|mandatory|description|
|---------|----|---------|-----------|
|`components`|`array of objects`|yes|The array of components to retrieve and render|
|`components[index].name`|`string`|yes|The component's name|
|`components[index].version`|`string`|no|The component's version. When not speficied, it will use globally specified one (doing client initialisation); when not specified and not globally specified, it will default to "" (latest)|
|`components[index].parameters`|`object`|no|The component's parameters|
|`components[index].render`|`string`|no|The component's render mode. When not specified, it will be the one specified in the options (for all components); if none is specified in options, it will default to `server`. When `server`, the rendering will be performed on the server-side and the result will be component's html. If `client`, the html will contain a promise to do the rendering on the browser.|

Options:

|Parameter|type|mandatory|description|
|---------|----|---------|-----------|
|`container`|`boolean`|no|Default true, when false, renders a component without its <oc-component> container|
|`disableFailoverRendering`|`boolean`|no|Disables the automatic failover rendering in case the registry times-out (in case configuration.registries.clientRendering contains a valid value.) Default false|
|`headers`|`object`|no|An object containing all the headers that must be forwarded to the component|
|`ie8`|`boolean`|no|Default false, if true puts in place the necessary polyfills to make all the stuff work with ie8|
|`render`|`string`|no|Default `server`. When `server`, it will return html. When `client` will produce the html to put in the page for post-poning the rendering to the browser|
|`timeout`|`number` (seconds)|no|Default 5. When request times-out, the callback will be fired with a timeout error and a client-side rendering response (unless `disableFailoverRendering` is set to `true`)|

Example:
```js
...
client.renderComponents([{
  name: 'header',
  parameters: { loggedIn: true }
}, {
  name: 'footer',
  version: '4.5.X'
}, {
  name: 'advert',
  parameters: { position: 'left' },
  render: 'client'
}], {
  container: false,
  headers: {
    'accept-language': 'en-US'
  },
  timeout: 3.0
}, function(errors, htmls){
  console.log(html);
  // => ["<div>Header</div>",
  //     "<p>Footer</p>",
  //     "<oc-component href=\"\/\/registry.com\/advert\/?position=left\"><\/oc-component>"]
});
```


text:
elevate.exe
=======

This tool allows you to start a program with elevated privileges from the command line.

Fixed and extended version of the original tool https://github.com/jpassing/elevate


text:
'use strict';

var util = require('util'),
  Lock = require('../base'),
  _ = require('lodash'),
  async = require('async'),
  redis = require('redis');

function Redis(options) {
  Lock.call(this, options);

  var defaults = {
    host: 'localhost',
    port: 6379,
    prefix: 'aggregatelock',
    max_attempts: 1
  };

  _.defaults(options, defaults);

  if (options.url) {
    var url = require('url').parse(options.url);
    if (url.protocol === 'redis:') {
      if (url.auth) {
        var userparts = url.auth.split(":");
        options.user = userparts[0];
        if (userparts.length === 2) {
          options.password = userparts[1];
        }
      }
      options.host = url.hostname;
      options.port = url.port;
      if (url.pathname) {
        options.db   = url.pathname.replace("/", "", 1);
      }
    }
  }

  this.options = options;
}

util.inherits(Redis, Lock);

_.extend(Redis.prototype, {

  connect: function (callback) {
    var self = this;

    var options = this.options;

    this.client = new redis.createClient(options.port || options.socket, options.host, options);

    this.prefix = options.prefix;

    var calledBack = false;

    if (options.password) {
      this.client.auth(options.password, function(err) {
        if (err && !calledBack && callback) {
          calledBack = true;
          if (callback) callback(err, self);
          return;
        }
        if (err) throw err;
      });
    }

    if (options.db) {
      this.client.select(options.db);
    }

    this.client.on('end', function () {
      self.disconnect();
    });

    this.client.on('error', function (err) {
      console.log(err);

      if (calledBack) return;
      calledBack = true;
      if (callback) callback(null, self);
    });

    this.client.on('connect', function () {
      if (options.db) {
        self.client.send_anyways = true;
        self.client.select(options.db);
        self.client.send_anyways = false;
      }

      self.emit('connect');

      if (calledBack) return;
      calledBack = true;
      if (callback) callback(null, self);
    });
  },

  disconnect: function (callback) {
    if (this.client) {
      this.client.end();
    }
    this.emit('disconnect');
    if (callback) callback(null, this);
  },

  getNewId: function(callback) {
    this.client.incr('nextItemId:' + this.prefix, function(err, id) {
      if (err) {
        return callback(err);
      }
      callback(null, id.toString());
    });
  },

  reserve: function(workerId, aggregateId, callback) {
    var prefixedId = this.prefix + ':' + aggregateId;

    this.client.rpush(prefixedId, workerId, function (err) {
      if (callback) callback(err);
    });
  },

  getAll: function(aggregateId, callback) {
    var prefixedId = this.prefix + ':' + aggregateId;

    this.client.lrange(prefixedId, 0, -1, callback);
  },

  resolve: function(aggregateId, callback) {
    var prefixedId = this.prefix + ':' + aggregateId;

    this.client.del(prefixedId, function (err) {
      if (callback) callback(err);
    });
  },

  clear: function (callback) {
    var self = this;
    async.parallel([
      function (callback) {
        self.client.del('nextItemId:' + self.options.prefix, callback);
      },
      function (callback) {
        self.client.keys(self.options.prefix + ':*', function(err, keys) {
          if (err) {
            return callback(err);
          }
          async.each(keys, function (key, callback) {
            self.client.del(key, callback);
          }, callback);
        });
      }
    ], function (err) {
      if (callback) callback(err);
    });
  }

});

module.exports = Redis;


text:
.softwarerepositories {
	padding: 5px;
}


text:
<?php

namespace Panda\Foundation\Bootstrap;

use Panda\Contracts\Bootstrap\Bootstrapper;
use Panda\Debug\Debugger;
use Panda\Foundation\Application;
use Panda\Http\Request;
use Panda\Localization\DateTimer;
use Panda\Session\Session;

/**
 * Class Environment
 * @package Panda\Foundation\Bootstrap
 */
class Environment implements Bootstrapper
{
    /**
     * @var Application
     */
    private $app;

    /**
     * Environment constructor.
     *
     * @param Application $app
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * Run the initializer.
     *
     * @param Request $request
     *
     * @throws \DI\DependencyException
     * @throws \DI\NotFoundException
     * @throws \InvalidArgumentException
     */
    public function boot($request)
    {
        // Initialize environment
        $this->app->make(Debugger::class)->boot($request);
        $this->app->make(DateTimer::class)->boot($request);
        $this->app->make(Session::class)->boot($request);
    }
}


text:
<?php

namespace Cake\Test\TestCase\ORM\Behavior\Translate;

use Cake\ORM\Behavior\Translate\TranslateTrait;
use Cake\ORM\Entity;
use Cake\TestSuite\TestCase;

class TestEntity extends Entity
{
    use TranslateTrait;
}

/**
 * Translate behavior test case
 */
class TranslateTraitTest extends TestCase
{

    /**
     * Tests that missing translation entries are created automatically
     *
     * @return void
     */
    public function testTranslationCreate()
    {
        $entity = new TestEntity;
        $entity->translation('eng')->set('title', 'My Title');
        $this->assertEquals('My Title', $entity->translation('eng')->get('title'));

        $this->assertTrue($entity->dirty('_translations'));

        $entity->translation('spa')->set('body', 'Contenido');
        $this->assertEquals('My Title', $entity->translation('eng')->get('title'));
        $this->assertEquals('Contenido', $entity->translation('spa')->get('body'));
    }

    /**
     * Tests that modifying existing translation entries work
     *
     * @return void
     */
    public function testTranslationModify()
    {
        $entity = new TestEntity;
        $entity->set('_translations', [
            'eng' => new Entity(['title' => 'My Title']),
            'spa' => new Entity(['title' => 'Titulo'])
        ]);
        $this->assertEquals('My Title', $entity->translation('eng')->get('title'));
        $this->assertEquals('Titulo', $entity->translation('spa')->get('title'));
    }

    /**
     * Tests empty translations.
     *
     * @return void
     */
    public function testTranslationEmpty()
    {
        $entity = new TestEntity;
        $entity->set('_translations', [
            'eng' => new Entity(['title' => 'My Title']),
            'spa' => new Entity(['title' => 'Titulo'])
        ]);
        $this->assertTrue($entity->translation('pol')->isNew());
        $this->assertInstanceOf('Cake\Test\TestCase\ORM\Behavior\Translate\TestEntity', $entity->translation('pol'));
    }

    /**
     * Tests that just accessing the translation will mark the property as dirty, this
     * is to facilitate the saving process by not having to remember to mark the property
     * manually
     *
     * @return void
     */
    public function testTranslationDirty()
    {
        $entity = new TestEntity;
        $entity->set('_translations', [
            'eng' => new Entity(['title' => 'My Title']),
            'spa' => new Entity(['title' => 'Titulo'])
        ]);
        $entity->clean();
        $this->assertEquals('My Title', $entity->translation('eng')->get('title'));
        $this->assertTrue($entity->dirty('_translations'));
    }
}