text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="IE=Edge" http-equiv="X-UA-Compatible"/>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>twilio.rest.preview.understand.assistant.field_type package — twilio-python 7.15.3 documentation</title>
<link href="../../../_static/alabaster.css" rel="stylesheet" type="text/css"/>
<link href="../../../_static/pygments.css" rel="stylesheet" type="text/css"/>

<link href="../../../genindex.html" rel="index" title="Index"/>
<link href="../../../search.html" rel="search" title="Search"/>
<link href="twilio.rest.preview.understand.assistant.task.html" rel="next" title="twilio.rest.preview.understand.assistant.task package"/>
<link href="twilio.rest.preview.understand.assistant.html" rel="prev" title="twilio.rest.preview.understand.assistant package"/>
<link href="../../../_static/custom.css" rel="stylesheet" type="text/css"/>
<meta content="width=device-width, initial-scale=0.9, maximum-scale=0.9" name="viewport"/>

twilio.rest.preview.understand.assistant.field_type package¶

Submodules¶

twilio.rest.preview.understand.assistant.field_type.field_value module¶

This code was generated by
/ _    _  _|   _  _

(_)/(_)(_|/| |(/_  v1.0.0
/       /

class twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueContext(version, assistant_sid, field_type_sid, sid)[source]¶

Bases: twilio.base.instance_context.InstanceContext

PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com.

delete()[source]¶

Deletes the FieldValueInstance

<col class="field-name"/>
<col class="field-body"/>

Returns:	True if delete succeeds, False otherwise

Return type:	bool

fetch()[source]¶

Fetch the FieldValueInstance

<col class="field-name"/>
<col class="field-body"/>

Returns:	The fetched FieldValueInstance

Return type:	twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance

class twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance(version, payload, assistant_sid, field_type_sid, sid=None)[source]¶

Bases: twilio.base.instance_resource.InstanceResource

PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com.

account_sid¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	The unique ID of the Account that created this Field Value.

Return type:	unicode

assistant_sid¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	The unique ID of the Assistant.

Return type:	unicode

date_created¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	The date that this resource was created

Return type:	datetime

date_updated¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	The date that this resource was last updated

Return type:	datetime

delete()[source]¶

Deletes the FieldValueInstance

<col class="field-name"/>
<col class="field-body"/>

Returns:	True if delete succeeds, False otherwise

Return type:	bool

fetch()[source]¶

Fetch the FieldValueInstance

<col class="field-name"/>
<col class="field-body"/>

Returns:	The fetched FieldValueInstance

Return type:	twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance

field_type_sid¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	The unique ID of the Field Type associated with this Field Value.

Return type:	unicode

language¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	An ISO language-country string of the value.

Return type:	unicode

sid¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	A 34 character string that uniquely identifies this resource.

Return type:	unicode

synonym_of¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	A value that indicates this field value is a synonym of. Empty if the value is not a synonym.

Return type:	unicode

url¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	The url

Return type:	unicode

value¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	The Field Value itself.

Return type:	unicode

class twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueList(version, assistant_sid, field_type_sid)[source]¶

Bases: twilio.base.list_resource.ListResource

PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com.

create(language, value, synonym_of=<object object>)[source]¶

Create the FieldValueInstance

<col class="field-name"/>
<col class="field-body"/>

Parameters:

language (unicode) – An ISO language-country string of the value.

value (unicode) – A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long.

synonym_of (unicode) – A value that indicates this field value is a synonym of. Empty if the value is not a synonym.

Returns:
The created FieldValueInstance

Return type:
twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance

get(sid)[source]¶

Constructs a FieldValueContext

<col class="field-name"/>
<col class="field-body"/>

Parameters:	sid – The sid

Returns:	twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueContext

Return type:	twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueContext

get_page(target_url)[source]¶

Retrieve a specific page of FieldValueInstance records from the API.
Request is executed immediately

<col class="field-name"/>
<col class="field-body"/>

Parameters:	target_url (str) – API-generated URL for the requested results page

Returns:	Page of FieldValueInstance

Return type:	twilio.rest.preview.understand.assistant.field_type.field_value.FieldValuePage

list(language=<object object>, limit=None, page_size=None)[source]¶

Lists FieldValueInstance records from the API as a list.
Unlike stream(), this operation is eager and will load limit records into
memory before returning.

<col class="field-name"/>
<col class="field-body"/>

Parameters:

language (unicode) – An ISO language-country string of the value. For example: en-US

limit (int) – Upper limit for the number of records to return. list() guarantees
never to return more than limit.  Default is no limit

page_size (int) – Number of records to fetch per request, when not set will use
the default value of 50 records.  If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)

Returns:
Generator that will yield up to limit results

Return type:
list[twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance]

page(language=<object object>, page_token=<object object>, page_number=<object object>, page_size=<object object>)[source]¶

Retrieve a single page of FieldValueInstance records from the API.
Request is executed immediately

<col class="field-name"/>
<col class="field-body"/>

Parameters:

language (unicode) – An ISO language-country string of the value. For example: en-US

page_token (str) – PageToken provided by the API

page_number (int) – Page Number, this value is simply for client state

page_size (int) – Number of records to return, defaults to 50

Returns:
Page of FieldValueInstance

Return type:
twilio.rest.preview.understand.assistant.field_type.field_value.FieldValuePage

stream(language=<object object>, limit=None, page_size=None)[source]¶

Streams FieldValueInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.

<col class="field-name"/>
<col class="field-body"/>

Parameters:

language (unicode) – An ISO language-country string of the value. For example: en-US

limit (int) – Upper limit for the number of records to return. stream()
guarantees to never return more than limit.  Default is no limit

page_size (int) – Number of records to fetch per request, when not set will use
the default value of 50 records.  If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)

Returns:
Generator that will yield up to limit results

Return type:
list[twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance]

class twilio.rest.preview.understand.assistant.field_type.field_value.FieldValuePage(version, response, solution)[source]¶

Bases: twilio.base.page.Page

PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com.

get_instance(payload)[source]¶

Build an instance of FieldValueInstance

<col class="field-name"/>
<col class="field-body"/>

Parameters:	payload (dict) – Payload response from the API

Returns:	twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance

Return type:	twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueInstance

Module contents¶

This code was generated by
/ _    _  _|   _  _

(_)/(_)(_|/| |(/_  v1.0.0
/       /

class twilio.rest.preview.understand.assistant.field_type.FieldTypeContext(version, assistant_sid, sid)[source]¶

Bases: twilio.base.instance_context.InstanceContext

PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com.

delete()[source]¶

Deletes the FieldTypeInstance

<col class="field-name"/>
<col class="field-body"/>

Returns:	True if delete succeeds, False otherwise

Return type:	bool

fetch()[source]¶

Fetch the FieldTypeInstance

<col class="field-name"/>
<col class="field-body"/>

Returns:	The fetched FieldTypeInstance

Return type:	twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance

field_values¶

Access the field_values

<col class="field-name"/>
<col class="field-body"/>

Returns:	twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueList

Return type:	twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueList

update(friendly_name=<object object>, unique_name=<object object>)[source]¶

Update the FieldTypeInstance

<col class="field-name"/>
<col class="field-body"/>

Parameters:

friendly_name (unicode) – A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long.

unique_name (unicode) – A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long.

Returns:
The updated FieldTypeInstance

Return type:
twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance

class twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance(version, payload, assistant_sid, sid=None)[source]¶

Bases: twilio.base.instance_resource.InstanceResource

PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com.

account_sid¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	The unique ID of the Account that created this Field Type.

Return type:	unicode

assistant_sid¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	The unique ID of the Assistant.

Return type:	unicode

date_created¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	The date that this resource was created

Return type:	datetime

date_updated¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	The date that this resource was last updated

Return type:	datetime

delete()[source]¶

Deletes the FieldTypeInstance

<col class="field-name"/>
<col class="field-body"/>

Returns:	True if delete succeeds, False otherwise

Return type:	bool

fetch()[source]¶

Fetch the FieldTypeInstance

<col class="field-name"/>
<col class="field-body"/>

Returns:	The fetched FieldTypeInstance

Return type:	twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance

field_values¶

Access the field_values

<col class="field-name"/>
<col class="field-body"/>

Returns:	twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueList

Return type:	twilio.rest.preview.understand.assistant.field_type.field_value.FieldValueList

friendly_name¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long.

Return type:	unicode

links¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	The links

Return type:	unicode

sid¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	A 34 character string that uniquely identifies this resource.

Return type:	unicode

unique_name¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long.

Return type:	unicode

update(friendly_name=<object object>, unique_name=<object object>)[source]¶

Update the FieldTypeInstance

<col class="field-name"/>
<col class="field-body"/>

Parameters:

friendly_name (unicode) – A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long.

unique_name (unicode) – A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long.

Returns:
The updated FieldTypeInstance

Return type:
twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance

url¶

<col class="field-name"/>
<col class="field-body"/>

Returns:	The url

Return type:	unicode

class twilio.rest.preview.understand.assistant.field_type.FieldTypeList(version, assistant_sid)[source]¶

Bases: twilio.base.list_resource.ListResource

PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com.

create(unique_name, friendly_name=<object object>)[source]¶

Create the FieldTypeInstance

<col class="field-name"/>
<col class="field-body"/>

Parameters:

unique_name (unicode) – A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long.

friendly_name (unicode) – A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long.

Returns:
The created FieldTypeInstance

Return type:
twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance

get(sid)[source]¶

Constructs a FieldTypeContext

<col class="field-name"/>
<col class="field-body"/>

Parameters:	sid – The sid

Returns:	twilio.rest.preview.understand.assistant.field_type.FieldTypeContext

Return type:	twilio.rest.preview.understand.assistant.field_type.FieldTypeContext

get_page(target_url)[source]¶

Retrieve a specific page of FieldTypeInstance records from the API.
Request is executed immediately

<col class="field-name"/>
<col class="field-body"/>

Parameters:	target_url (str) – API-generated URL for the requested results page

Returns:	Page of FieldTypeInstance

Return type:	twilio.rest.preview.understand.assistant.field_type.FieldTypePage

list(limit=None, page_size=None)[source]¶

Lists FieldTypeInstance records from the API as a list.
Unlike stream(), this operation is eager and will load limit records into
memory before returning.

<col class="field-name"/>
<col class="field-body"/>

Parameters:

limit (int) – Upper limit for the number of records to return. list() guarantees
never to return more than limit.  Default is no limit

page_size (int) – Number of records to fetch per request, when not set will use
the default value of 50 records.  If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)

Returns:
Generator that will yield up to limit results

Return type:
list[twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance]

page(page_token=<object object>, page_number=<object object>, page_size=<object object>)[source]¶

Retrieve a single page of FieldTypeInstance records from the API.
Request is executed immediately

<col class="field-name"/>
<col class="field-body"/>

Parameters:

page_token (str) – PageToken provided by the API

page_number (int) – Page Number, this value is simply for client state

page_size (int) – Number of records to return, defaults to 50

Returns:
Page of FieldTypeInstance

Return type:
twilio.rest.preview.understand.assistant.field_type.FieldTypePage

stream(limit=None, page_size=None)[source]¶

Streams FieldTypeInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.

<col class="field-name"/>
<col class="field-body"/>

Parameters:

limit (int) – Upper limit for the number of records to return. stream()
guarantees to never return more than limit.  Default is no limit

page_size (int) – Number of records to fetch per request, when not set will use
the default value of 50 records.  If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)

Returns:
Generator that will yield up to limit results

Return type:
list[twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance]

class twilio.rest.preview.understand.assistant.field_type.FieldTypePage(version, response, solution)[source]¶

Bases: twilio.base.page.Page

PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com.

get_instance(payload)[source]¶

Build an instance of FieldTypeInstance

<col class="field-name"/>
<col class="field-body"/>

Parameters:	payload (dict) – Payload response from the API

Returns:	twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance

Return type:	twilio.rest.preview.understand.assistant.field_type.FieldTypeInstance

About twilio-python

    A Python module for communicating with the Twilio API and generating TwiML.

Useful Links

Twilio's Python Helper Library Docs

twilio @ PyPI

twilio-python @ GitHub

Table of Contents

twilio.rest.preview.understand.assistant.field_type package

Submodules

twilio.rest.preview.understand.assistant.field_type.field_value module

Module contents

Related Topics

Documentation overview

twilio

twilio package

twilio.rest package

twilio.rest.preview package

twilio.rest.preview.understand package

twilio.rest.preview.understand.assistant package

Previous: twilio.rest.preview.understand.assistant package

Next: twilio.rest.preview.understand.assistant.task package

This Page

Show Source

Quick search

<form action="../../../search.html" class="search" method="get">
<input name="q" type="text"/>
<input type="submit" value="Go"/>
<input name="check_keywords" type="hidden" value="yes"/>
<input name="area" type="hidden" value="default"/>
</form>

      ©2019, Twilio.

      |
      Powered by Sphinx 1.8.0
      & Alabaster 0.7.12

      |
      Page source


text:
package lecho.lib.hellocharts.animation;

import lecho.lib.hellocharts.model.Viewport;

public interface ChartViewportAnimator {

    int FAST_ANIMATION_DURATION = 300;

    void startAnimation(Viewport startViewport, Viewport targetViewport);

    void startAnimation(Viewport startViewport, Viewport targetViewport, long duration);

    void cancelAnimation();

    boolean isAnimationStarted();

    void setChartAnimationListener(ChartAnimationListener animationListener);

}

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.web.reactive.socket.adapter;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.util.Assert;
import org.springframework.web.reactive.socket.HandshakeInfo;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.WebSocketSession;

/**
 * Convenient base class for {@link WebSocketSession} implementations that
 * holds common fields and exposes accessors. Also implements the
 * {@code WebSocketMessage} factory methods.
 *
 * @author Rossen Stoyanchev
 * @since 5.0
 * @param <T> the native delegate type
 */
public abstract class AbstractWebSocketSession<T> implements WebSocketSession {

	protected final Log logger = LogFactory.getLog(getClass());

	private final T delegate;

	private final String id;

	private final HandshakeInfo handshakeInfo;

	private final DataBufferFactory bufferFactory;

	private final Map<String, Object> attributes = new ConcurrentHashMap<>();

	private final String logPrefix;

	/**
	 * Create a new WebSocket session.
	 */
	protected AbstractWebSocketSession(T delegate, String id, HandshakeInfo info, DataBufferFactory bufferFactory) {
		Assert.notNull(delegate, "Native session is required");
		Assert.notNull(id, "Session id is required");
		Assert.notNull(info, "HandshakeInfo is required");
		Assert.notNull(bufferFactory, "DataBuffer factory is required");

		this.delegate = delegate;
		this.id = id;
		this.handshakeInfo = info;
		this.bufferFactory = bufferFactory;
		this.logPrefix = initLogPrefix(info, id);

		info.getAttributes().entrySet().stream()
				.filter(entry -> (entry.getKey() != null && entry.getValue() != null))
				.forEach(entry -> this.attributes.put(entry.getKey(), entry.getValue()));

		if (logger.isDebugEnabled()) {
			logger.debug(getLogPrefix() + "Session id \"" + getId() + "\" for " + getHandshakeInfo().getUri());
		}
	}

	private static String initLogPrefix(HandshakeInfo info, String id) {
		return info.getLogPrefix() != null ? info.getLogPrefix() : "[" + id + "] ";
	}

	protected T getDelegate() {
		return this.delegate;
	}

	@Override
	public String getId() {
		return this.id;
	}

	@Override
	public HandshakeInfo getHandshakeInfo() {
		return this.handshakeInfo;
	}

	@Override
	public DataBufferFactory bufferFactory() {
		return this.bufferFactory;
	}

	@Override
	public Map<String, Object> getAttributes() {
		return this.attributes;
	}

	protected String getLogPrefix() {
		return this.logPrefix;
	}

	@Override
	public abstract Flux<WebSocketMessage> receive();

	@Override
	public abstract Mono<Void> send(Publisher<WebSocketMessage> messages);

	// WebSocketMessage factory methods

	@Override
	public WebSocketMessage textMessage(String payload) {
		byte[] bytes = payload.getBytes(StandardCharsets.UTF_8);
		DataBuffer buffer = bufferFactory().wrap(bytes);
		return new WebSocketMessage(WebSocketMessage.Type.TEXT, buffer);
	}

	@Override
	public WebSocketMessage binaryMessage(Function<DataBufferFactory, DataBuffer> payloadFactory) {
		DataBuffer payload = payloadFactory.apply(bufferFactory());
		return new WebSocketMessage(WebSocketMessage.Type.BINARY, payload);
	}

	@Override
	public WebSocketMessage pingMessage(Function<DataBufferFactory, DataBuffer> payloadFactory) {
		DataBuffer payload = payloadFactory.apply(bufferFactory());
		return new WebSocketMessage(WebSocketMessage.Type.PING, payload);
	}

	@Override
	public WebSocketMessage pongMessage(Function<DataBufferFactory, DataBuffer> payloadFactory) {
		DataBuffer payload = payloadFactory.apply(bufferFactory());
		return new WebSocketMessage(WebSocketMessage.Type.PONG, payload);
	}

	@Override
	public String toString() {
		return getClass().getSimpleName() + "[id=" + getId() + ", uri=" + getHandshakeInfo().getUri() + "]";
	}

}


text:
# CallbackEvent.MessageUri Property

Url to message

**Namespace:** Bandwidth.Net
**Assembly:** Bandwidth.Net (in Bandwidth.Net.dll) Version: 3.0.3

## Syntax

**C#**

``` C#
public string MessageUri { get; set; }
```

#### Property Value
Type: String

## See Also

#### Reference
CallbackEvent Class
Bandwidth.Net Namespace


text:
@interface ViewController ()

@property (nonatomic, weak) IBOutlet UILabel *label;

@end

@implementation ViewController

- (void)viewDidLoad
{
	[super viewDidLoad];
//	[self showSpinAnimation1];
	[self showSpinAnimation2];
}

- (void)showSpinAnimation1
{
	CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
	rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2];
	rotationAnimation.duration = 1;
	rotationAnimation.repeatCount = CGFLOAT_MAX;
	[self.label.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

- (void)showSpinAnimation2
{
	[UIView animateWithDuration:1 delay:1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
		[self.label setTransform:CGAffineTransformRotate(self.label.transform, M_PI)];
	} completion:^(BOOL finished) {
		if (finished) {
			[self showSpinAnimation2];
		}
	}];
}

@end


text:
PhProject
=========

PHP Project template with vagrant and composer


text:
using std::unique_ptr;
using std::string;
using std::vector;
using strings::Substitute;

namespace kudu {
namespace cluster {

using client::KuduClient;
using client::KuduClientBuilder;
using master::CatalogManager;
using master::MasterServiceProxy;
using master::MiniMaster;
using master::TSDescriptor;
using std::shared_ptr;
using tserver::MiniTabletServer;
using tserver::TabletServer;

InternalMiniClusterOptions::InternalMiniClusterOptions()
  : num_masters(1),
    num_tablet_servers(1),
    num_data_dirs(1),
    bind_mode(MiniCluster::kDefaultBindMode) {
}

InternalMiniCluster::InternalMiniCluster(Env* env, InternalMiniClusterOptions options)
  : env_(env),
    opts_(std::move(options)),
    running_(false) {
  if (opts_.cluster_root.empty()) {
    opts_.cluster_root = JoinPathSegments(GetTestDataDirectory(), "minicluster-data");
  }
}

InternalMiniCluster::~InternalMiniCluster() {
  Shutdown();
}

Status InternalMiniCluster::Start() {
  CHECK(!opts_.cluster_root.empty()) << "No cluster root was provided";
  CHECK(!running_);

  if (!env_->FileExists(opts_.cluster_root)) {
    RETURN_NOT_OK(env_->CreateDir(opts_.cluster_root));
  }

  RETURN_NOT_OK_PREPEND(StartMasters(), "Couldn't start masters");

  for (int i = 0; i < opts_.num_tablet_servers; i++) {
    RETURN_NOT_OK_PREPEND(AddTabletServer(),
                          Substitute("Error adding TS $0", i));
  }

  RETURN_NOT_OK_PREPEND(WaitForTabletServerCount(opts_.num_tablet_servers),
                        "Waiting for tablet servers to start");

  RETURN_NOT_OK_PREPEND(rpc::MessengerBuilder("minicluster-messenger")
                        .set_num_reactors(1)
                        .set_max_negotiation_threads(1)
                        .Build(&messenger_),
                        "Failed to start Messenger for minicluster");

  running_ = true;
  return Status::OK();
}

Status InternalMiniCluster::StartMasters() {
  int num_masters = opts_.num_masters;

  // Collect and keep alive the set of master sockets bound with SO_REUSEPORT
  // until all master proccesses are started. This allows the mini-cluster to
  // reserve a set of ports up front, then later start the set of masters, each
  // configured with the full set of ports.
  //
  // TODO(dan): re-bind the ports between node restarts in order to prevent other
  // processess from binding to them in the interim.
  vector<unique_ptr<Socket>> reserved_sockets;

  if (mini_masters_.empty()) {
    vector<HostPort> master_rpc_addrs;
    for (int i = 0; i < num_masters; i++) {
      unique_ptr<Socket> reserved_socket;
      RETURN_NOT_OK_PREPEND(ReserveDaemonSocket(MiniCluster::MASTER, i, opts_.bind_mode,
                                                &reserved_socket),
                            "failed to reserve master socket address");

      Sockaddr addr;
      RETURN_NOT_OK(reserved_socket->GetSocketAddress(&addr));

      master_rpc_addrs.emplace_back(addr.host(), addr.port());
      reserved_sockets.emplace_back(std::move(reserved_socket));
    }

    LOG(INFO) << "Creating distributed mini masters. Addrs: "
              << HostPort::ToCommaSeparatedString(master_rpc_addrs);

    for (int i = 0; i < num_masters; i++) {
      shared_ptr<MiniMaster> mini_master(new MiniMaster(GetMasterFsRoot(i), master_rpc_addrs[i]));
      if (num_masters > 1) {
        mini_master->SetMasterAddresses(master_rpc_addrs);
      }
      mini_masters_.emplace_back(std::move(mini_master));
    }
  }

  CHECK_EQ(num_masters, mini_masters_.size());
  for (int i = 0; i < num_masters; i++) {
    RETURN_NOT_OK_PREPEND(mini_masters_[i]->Start(), Substitute("failed to start master $0", i));
    VLOG(1) << "Started MiniMaster with UUID " << mini_masters_[i]->permanent_uuid()
            << " at index " << i;
  }

  for (int i = 0; i < num_masters; i++) {
    LOG(INFO) << "Waiting to initialize catalog manager on master " << i;
    RETURN_NOT_OK_PREPEND(mini_masters_[i]->WaitForCatalogManagerInit(),
                          Substitute("Could not initialize catalog manager on master $0", i));
  }

  if (num_masters == 1) {
    RETURN_NOT_OK(mini_masters_[0]->master()->WaitUntilCatalogManagerIsLeaderAndReadyForTests(
          MonoDelta::FromSeconds(kMasterStartupWaitTimeSeconds)));
  }

  return Status::OK();
}

Status InternalMiniCluster::StartSync() {
  RETURN_NOT_OK(Start());
  int count = 0;
  for (const shared_ptr<MiniTabletServer>& tablet_server : mini_tablet_servers_) {
    RETURN_NOT_OK_PREPEND(tablet_server->WaitStarted(),
                          Substitute("TabletServer $0 failed to start.", count));
    count++;
  }
  return Status::OK();
}

Status InternalMiniCluster::AddTabletServer() {
  if (mini_masters_.empty()) {
    return Status::IllegalState("Master not yet initialized");
  }
  int new_idx = mini_tablet_servers_.size();

  uint16_t ts_rpc_port = 0;
  if (opts_.tserver_rpc_ports.size() > new_idx) {
    ts_rpc_port = opts_.tserver_rpc_ports[new_idx];
  }

  string bind_ip = GetBindIpForDaemon(MiniCluster::TSERVER, new_idx, opts_.bind_mode);
  gscoped_ptr<MiniTabletServer> tablet_server(new MiniTabletServer(GetTabletServerFsRoot(new_idx),
                                                                   HostPort(bind_ip, ts_rpc_port),
                                                                   opts_.num_data_dirs));

  // set the master addresses
  tablet_server->options()->master_addresses = master_rpc_addrs();
  RETURN_NOT_OK(tablet_server->Start())
  mini_tablet_servers_.push_back(shared_ptr<MiniTabletServer>(tablet_server.release()));
  return Status::OK();
}

void InternalMiniCluster::ShutdownNodes(ClusterNodes nodes) {
  if (nodes == ClusterNodes::ALL || nodes == ClusterNodes::TS_ONLY) {
    for (const shared_ptr<MiniTabletServer>& tablet_server : mini_tablet_servers_) {
      tablet_server->Shutdown();
    }
    mini_tablet_servers_.clear();
  }
  if (nodes == ClusterNodes::ALL || nodes == ClusterNodes::MASTERS_ONLY) {
    for (const shared_ptr<MiniMaster>& master_server : mini_masters_) {
      master_server->Shutdown();
    }
  }
  running_ = false;
}

MiniMaster* InternalMiniCluster::mini_master(int idx) const {
  CHECK_GE(idx, 0) << "Master idx must be >= 0";
  CHECK_LT(idx, mini_masters_.size()) << "Master idx must be < num masters started";
  return mini_masters_[idx].get();
}

MiniTabletServer* InternalMiniCluster::mini_tablet_server(int idx) const {
  CHECK_GE(idx, 0) << "TabletServer idx must be >= 0";
  CHECK_LT(idx, mini_tablet_servers_.size()) << "TabletServer idx must be < 'num_ts_started_'";
  return mini_tablet_servers_[idx].get();
}

MiniTabletServer* InternalMiniCluster::mini_tablet_server_by_uuid(const string& uuid) const {
  for (const auto& ts : mini_tablet_servers_) {
    if (ts->uuid() == uuid) {
      return ts.get();
    }
  }
  return nullptr;
}

int InternalMiniCluster::tablet_server_index_by_uuid(const std::string& uuid) const {
  for (int i = 0; i < mini_tablet_servers_.size(); i++) {
    if (mini_tablet_servers_[i]->uuid() == uuid) {
      return i;
    }
  }
  return -1;
}

vector<HostPort> InternalMiniCluster::master_rpc_addrs() const {
  vector<HostPort> master_hostports;
  for (const auto& master : mini_masters_) {
      Sockaddr add = master->bound_rpc_addr();
      master_hostports.emplace_back(add.host(), add.port());
  }
  return master_hostports;
}

string InternalMiniCluster::GetMasterFsRoot(int idx) const {
  return JoinPathSegments(opts_.cluster_root, Substitute("master-$0-root", idx));
}

string InternalMiniCluster::GetTabletServerFsRoot(int idx) const {
  return JoinPathSegments(opts_.cluster_root, Substitute("ts-$0-root", idx));
}

Status InternalMiniCluster::WaitForTabletServerCount(int count) const {
  vector<shared_ptr<master::TSDescriptor>> descs;
  return WaitForTabletServerCount(count, MatchMode::MATCH_TSERVERS, &descs);
}

Status InternalMiniCluster::WaitForTabletServerCount(int count,
                                             MatchMode mode,
                                             vector<shared_ptr<TSDescriptor>>* descs) const {
  std::unordered_set<int> masters_to_search;
  for (int i = 0; i < num_masters(); i++) {
    if (!mini_master(i)->master()->IsShutdown()) {
      masters_to_search.insert(i);
    }
  }

  Stopwatch sw;
  sw.start();
  while (sw.elapsed().wall_seconds() < kRegistrationWaitTimeSeconds) {
    for (auto iter = masters_to_search.begin(); iter != masters_to_search.end();) {
      mini_master(*iter)->master()->ts_manager()->GetAllDescriptors(descs);
      int match_count = 0;
      switch (mode) {
        case MatchMode::MATCH_TSERVERS:
          // GetAllDescriptors() may return servers that are no longer online.
          // Do a second step of verification to verify that the descs that we got
          // are aligned (same uuid/seqno) with the TSs that we have in the cluster.
          for (const shared_ptr<TSDescriptor>& desc : *descs) {
            for (const auto& mini_tablet_server : mini_tablet_servers_) {
              const TabletServer* ts = mini_tablet_server->server();
              if (ts->instance_pb().permanent_uuid() == desc->permanent_uuid() &&
                  ts->instance_pb().instance_seqno() == desc->latest_seqno()) {
                match_count++;
                break;
              }
            }
          }
          break;
        case MatchMode::DO_NOT_MATCH_TSERVERS:
          match_count = descs->size();
          break;
        default:
          LOG(FATAL) << "Invalid match mode";
      }

      if (match_count == count) {
        // This master has returned the correct set of tservers.
        iter = masters_to_search.erase(iter);
      } else {
        iter++;
      }
    }
    if (masters_to_search.empty()) {
      // All masters have returned the correct set of tservers.
      LOG(INFO) << Substitute("$0 TS(s) registered with all masters after $1s",
                              count, sw.elapsed().wall_seconds());
      return Status::OK();
    }
    SleepFor(MonoDelta::FromMilliseconds(1));
  }
  return Status::TimedOut(Substitute(
      "Timed out waiting for $0 TS(s) to register with all masters", count));
}

Status InternalMiniCluster::CreateClient(KuduClientBuilder* builder,
                                         client::sp::shared_ptr<KuduClient>* client) const {
  client::KuduClientBuilder defaults;
  if (builder == nullptr) {
    builder = &defaults;
  }

  builder->clear_master_server_addrs();
  for (const shared_ptr<MiniMaster>& master : mini_masters_) {
    CHECK(master);
    builder->add_master_server_addr(master->bound_rpc_addr_str());
  }
  return builder->Build(client);
}

Status InternalMiniCluster::GetLeaderMasterIndex(int* idx) const {
  const MonoTime deadline = MonoTime::Now() +
      MonoDelta::FromSeconds(kMasterStartupWaitTimeSeconds);

  int leader_idx = -1;
  while (MonoTime::Now() < deadline) {
    for (int i = 0; i < num_masters(); i++) {
      master::MiniMaster* mm = mini_master(i);
      if (!mm->is_started() || mm->master()->IsShutdown()) {
        continue;
      }
      master::CatalogManager* catalog = mm->master()->catalog_manager();
      master::CatalogManager::ScopedLeaderSharedLock l(catalog);
      if (l.first_failed_status().ok()) {
        leader_idx = i;
        break;
      }
    }
    if (leader_idx != -1) {
      break;
    }
    SleepFor(MonoDelta::FromMilliseconds(100));
  }
  if (leader_idx == -1) {
    return Status::NotFound("Leader master was not found within deadline");
  }

  if (idx) {
    *idx = leader_idx;
  }
  return Status::OK();
}

std::shared_ptr<rpc::Messenger> InternalMiniCluster::messenger() const {
  return messenger_;
}

std::shared_ptr<MasterServiceProxy> InternalMiniCluster::master_proxy() const {
  CHECK_EQ(1, mini_masters_.size());
  return master_proxy(0);
}

std::shared_ptr<MasterServiceProxy> InternalMiniCluster::master_proxy(int idx) const {
  const auto& addr = CHECK_NOTNULL(mini_master(idx))->bound_rpc_addr();
  return std::make_shared<MasterServiceProxy>(messenger_, addr, addr.host());
}

string InternalMiniCluster::WalRootForTS(int ts_idx) const {
  return mini_tablet_server(ts_idx)->options()->fs_opts.wal_root;
}

string InternalMiniCluster::UuidForTS(int ts_idx) const {
  return mini_tablet_server(ts_idx)->uuid();
}

} // namespace cluster
} // namespace kudu


text:
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.google.apigee</groupId>
  <artifactId>edge-java-callout-baseclass</artifactId>
  <version>1.0</version>
  <packaging>jar</packaging>

  <properties>
    <apigee.expressions.version>1.0.0</apigee.expressions.version>
    <apigee.message.flow.version>1.0.0</apigee.message.flow.version>
    <jdk.target.version>1.8</jdk.target.version>
    <mockito-core.version>3.3.3</mockito-core.version>
    <junit.version>4.13</junit.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.apigee.edge</groupId>
      <artifactId>message-flow</artifactId>
      <version>${apigee.message.flow.version}</version>
    </dependency>
    <dependency>
      <groupId>com.apigee.edge</groupId>
      <artifactId>expressions</artifactId>
      <version>${apigee.expressions.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>${mockito-core.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>${project.artifactId}-${project.version}</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <source>8</source>
          <target>8</target>
          <compilerArgs>
            <!-- <arg>-verbose</arg> -->
            <arg>-Xlint:unchecked,deprecation</arg>
          </compilerArgs>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>3.2.0</version>
        <configuration>
          <archive>
            <!-- do not include the pom.xml file in the generated jar -->
            <addMavenDescriptor>false</addMavenDescriptor>
          </archive>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>


text:
// ============================================================================
//
// Copyright (C) 2006-2018 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// https://github.com/Talend/data-prep/blob/master/LICENSE
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================

package org.talend.dataprep.api.service.settings.views.api.appheaderbar;

import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL;

import java.util.Objects;

import org.talend.dataprep.api.service.settings.views.api.ViewSettings;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;

/**
 * An app header bar is a static bar placed on the top of the window
 * see
 * https://talend.github.io/react-talend-components/?selectedKind=App%20Header%20Bar&selectedStory=default&full=0&down=1
 * &left=1&panelRight=0&downPanel=kadirahq%2Fstorybook-addon-actions%2Factions-panel
 */
@JsonInclude(NON_NULL)
public class AppHeaderBarSettings implements ViewSettings {

    public static final String VIEW_TYPE = TYPE_APP_HEADER_BAR;

    /**
     * The id that is the key to the view dictionary
     */
    @JsonIgnore
    private String id;

    /**
     * The app name
     */
    private LinkSettings logo;

    /**
     * The brand link configuration
     */
    private LinkSettings brand;

    /**
     * The search bar configuration
     */
    private SearchSettings search;

    /**
     * The help configuration
     */
    private String help;

    /**
     * The user dropdown action
     */
    private String userMenu;

    /**
     * The information dropdown action
     */
    private String information;

    /**
     * The products dropdown action
     */
    private String products;

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

    @Override
    public ViewSettings translate() {
        return AppHeaderBarSettings //
                .from(this) //
                .translate() //
                .build();
    }

    public void setId(String id) {
        this.id = id;
    }

    public LinkSettings getLogo() {
        return logo;
    }

    public void setLogo(LinkSettings logo) {
        this.logo = logo;
    }

    public LinkSettings getBrand() {
        return brand;
    }

    public void setBrand(LinkSettings brand) {
        this.brand = brand;
    }

    public SearchSettings getSearch() {
        return search;
    }

    public void setSearch(SearchSettings search) {
        this.search = search;
    }

    public String getHelp() {
        return help;
    }

    public void setHelp(String help) {
        this.help = help;
    }

    public String getUserMenu() {
        return userMenu;
    }

    public void setUserMenu(String userMenu) {
        this.userMenu = userMenu;
    }

    public String getInformation() {
        return information;
    }

    public void setInformation(String information) {
        this.information = information;
    }

    public String getProducts() {
        return products;
    }

    public void setProducts(String products) {
        this.products = products;
    }

    public static Builder builder() {
        return new Builder();
    }

    public static Builder from(final AppHeaderBarSettings viewSettings) {
        return builder() //
                .id(viewSettings.getId()) //
                .logo(viewSettings.getLogo()) //
                .brand(viewSettings.getBrand()) //
                .search(viewSettings.getSearch()) //
                .help(viewSettings.getHelp()) //
                .userMenu(viewSettings.getUserMenu()) //
                .information(viewSettings.getInformation()) //
                .products(viewSettings.getProducts());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;
        AppHeaderBarSettings that = (AppHeaderBarSettings) o;
        return Objects.equals(id, that.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    public static class Builder {

        private String id;

        private LinkSettings logo;

        private LinkSettings brand;

        private SearchSettings search;

        private String help;

        private String userMenu;

        private String information;

        private String products;

        public Builder id(final String id) {
            this.id = id;
            return this;
        }

        public Builder logo(final LinkSettings logo) {
            this.logo = logo;
            return this;
        }

        public Builder brand(final LinkSettings brand) {
            this.brand = brand;
            return this;
        }

        public Builder search(final SearchSettings search) {
            this.search = search;
            return this;
        }

        public Builder help(final String help) {
            this.help = help;
            return this;
        }

        public Builder removeHelp() {
            this.help = null;
            return this;
        }

        public Builder userMenu(final String userMenu) {
            this.userMenu = userMenu;
            return this;
        }

        public Builder information(final String information) {
            this.information = information;
            return this;
        }

        public Builder products(final String products) {
            this.products = products;
            return this;
        }

        public Builder translate() {
            if (this.logo != null) {
                this.logo = LinkSettings.from(this.logo).translate().build();
            }
            if (this.brand != null) {
                this.brand = LinkSettings.from(this.brand).translate().build();
            }
            if (this.search != null) {
                this.search = SearchSettings.from(this.search).translate().build();
            }
            return this;
        }

        public AppHeaderBarSettings build() {
            final AppHeaderBarSettings settings = new AppHeaderBarSettings();
            settings.setId(this.id);
            settings.setLogo(this.logo);
            settings.setBrand(this.brand);
            settings.setSearch(this.search);
            settings.setHelp(this.help);
            settings.setUserMenu(this.userMenu);
            settings.setInformation(this.information);
            settings.setProducts(this.products);
            return settings;
        }
    }
}


text:
using namespace Framework;

CWavOutputStream::CWavOutputStream(CStream& stream)
: m_stream(stream)
, m_chunkSizePos(0)
, m_dataSizePos(0)
, m_writeSize(0)
, m_begun(false)
{

}

CWavOutputStream::~CWavOutputStream()
{
	if(m_begun)
	{
		End();
	}
}

void CWavOutputStream::Begin(const WAVINFO& wavInfo)
{
	if(m_begun)
	{
		throw std::runtime_error("Already begun output.");
	}
	m_begun = true;
	m_writeSize = 0;

	//Write the header
	const char riffSignature[4] = { 'R', 'I', 'F', 'F' };
	const char headerFormatSignature[4] = { 'W', 'A', 'V', 'E' };
	const char fmtSignature[4] = { 'f', 'm', 't', ' ' };
	const char dataSignature[4] = { 'd', 'a', 't', 'a' };

	//RIFF header
	m_stream.Write(riffSignature, 4);
	m_chunkSizePos = m_stream.Tell();
	m_stream.Write32(0);
	m_stream.Write(headerFormatSignature, 4);

	//fmt header
	m_stream.Write(fmtSignature, 4);
	//Subchunk1Size
	m_stream.Write32(16);
	//AudioFormat
	m_stream.Write16(1);
	//NumChannels
	m_stream.Write16(wavInfo.channelCount);
	//SampleRate
	m_stream.Write32(wavInfo.sampleRate);
	//ByteRate = SampleRate * NumChannels * BitsPerSample/8
	m_stream.Write32(wavInfo.sampleRate * wavInfo.channelCount * wavInfo.bitDepth / 8);
	//BlockAlign = NumChannels * BitsPerSample / 8
	m_stream.Write16(wavInfo.channelCount * wavInfo.bitDepth / 8);
	//BitsPerSample
	m_stream.Write16(wavInfo.bitDepth);

	//data header
	m_stream.Write(dataSignature, 4);
	m_dataSizePos = m_stream.Tell();
	m_stream.Write32(0);
}

void CWavOutputStream::Flush()
{
	assert(m_begun);
	assert((m_writeSize & 1) == 0);

	m_stream.Seek(m_chunkSizePos, STREAM_SEEK_SET);
	uint32 totalChunkSize = 4 + 24 + (8 + static_cast<uint32>(m_writeSize));
	m_stream.Write32(totalChunkSize);

	m_stream.Seek(m_dataSizePos, STREAM_SEEK_SET);
	m_stream.Write32(static_cast<uint32>(m_writeSize));

	m_stream.Seek(0, STREAM_SEEK_END);
	m_stream.Flush();
}

void CWavOutputStream::Seek(int64, STREAM_SEEK_DIRECTION)
{
	throw std::exception();
}

uint64 CWavOutputStream::Tell()
{
	throw std::exception();
}

bool CWavOutputStream::IsEOF()
{
	throw std::exception();
}

uint64 CWavOutputStream::Read(void* data, uint64 size)
{
	throw std::exception();
}

uint64 CWavOutputStream::Write(const void* data, uint64 size)
{
	assert(m_begun);
	uint64 result = m_stream.Write(data, size);
	m_writeSize += result;
	return result;
}

void CWavOutputStream::End()
{
	if(!m_begun)
	{
		throw std::runtime_error("Didn't start output yet.");
	}

	Flush();

	m_begun = false;
}


text:
package com.prd.modules.prd.entity;

import org.hibernate.validator.constraints.Length;

import com.prd.common.persistence.DataEntity;

/**
 * 单表生成Entity
 * @author samson
 * @version 2016-02-04
 */
public class Sms extends DataEntity<Sms> {

	private static final long serialVersionUID = 1L;
	private String mobile;		// 手机号码
	private String code; 	//随机码
	private String content;		// 内容
	private String result;		// 返回值
	private String type;
	private String status;

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public Sms() {
		super();
	}

	public Sms(String id){
		super(id);
	}
	public Sms(String mobile,String code){
		this.mobile=mobile;
		this.code=code;
	}
	@Length(min=0, max=20, message="手机号码长度必须介于 0 和 20 之间")
	public String getMobile() {
		return mobile;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	@Length(min=0, max=500, message="内容长度必须介于 0 和 500 之间")
	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	@Length(min=0, max=10, message="返回值长度必须介于 0 和 10 之间")
	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

}


text:
package mobi.cangol.web.action.app;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import mobi.cangol.web.action.BaseAction;
import mobi.cangol.web.common.search.Page;
import mobi.cangol.web.common.search.PageSearchEntity;
import mobi.cangol.web.modules.app.entity.AppInfo;
import mobi.cangol.web.modules.app.entity.AppPower;
import mobi.cangol.web.modules.app.service.AppInfoService;
import mobi.cangol.web.modules.app.service.AppPowerService;
import mobi.cangol.web.modules.sys.entity.SysUser;
import mobi.cangol.web.modules.sys.service.SysUserService;
import mobi.cangol.web.utils.Constants;
import mobi.cangol.web.utils.ExtCheckTreeMenu;
import mobi.cangol.web.utils.MD5Helper;
import mobi.cangol.web.utils.TimeUtils;
import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
@ParentPackage("base")
@Namespace("/modules/app")
@Results( { @Result(name = "success", location = "app_power.jsp",type = "dispatcher")
			,@Result(name="failure", type="dispatcher", location="error.jsp")
        	,@Result(name = "input", location = "app_power.jsp")
        } )
public class AppPowerAction extends BaseAction {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private static final String ROLE_ID_APP_MANAGER = "4";
	private String ids = "";
	private AppPowerService appPowerService;
	private AppInfoService appInfoService;
	private SysUserService sysUserService=null;
	private String appIds = "";
	private String user = "";
	private AppPower appPower=new AppPower();
	private SysUser currentUser=null;
	private String newpassword;
	private String repassword;
	public void prepare() throws Exception {
		currentUser=(SysUser) request.getSession().getAttribute(Constants.SESSION_ADMIN_KEY);
	}
	@Action(value="/modules/app/appPower")
	public String execute() throws Exception {
		return "success";
	}
	public void list() throws Exception{
		response.setContentType("text/html;charset=UTF-8");
		try {
			PageSearchEntity pEntity = new PageSearchEntity();
			pEntity.addSearch("sysUser", appPower.getSysUser(), "=");
			pEntity.addSearch("appId", appPower.getAppId(), "=");
			pEntity.setOrderSql(" createTime desc");
			Page page = appPowerService.findPage(pEntity,  this.page, this.rows);
			JSONArray jsonArray = JSONArray.fromObject(page.getData());
			printJSONArray((int)page.getTotalCount(),jsonArray);
		} catch (Exception e) {
			log.error(e);
	    	printResultJson(false,e.getMessage());

		}
	}
	public void save() throws Exception{
		this.response.setContentType("text/json; charset=UTF-8");
		String operate = "";
		try{
			if(StringUtils.isBlank(appPower.getId())){
				operate = "添加";
				appPower.setCreateMan(currentUser.getUserAccount());
				appPower.setCreateTime(TimeUtils.getCurrentTime());
			}else{
				operate = "修改";
			}
			appPowerService.save(appPower);
			// 记录操作日志
			saveOperateLog("授权管理",operate + "授权", "操作主键" + appPower.getId());
			printResultJson(true,operate + "授权成功!");
		}catch(Exception e){
			log.error(e);
	    	printResultJson(false,e.getMessage());
	    	saveOperateLog("授权管理", "删除授权" ,operate +"授权失败!" + e.getMessage());
		}
	}
	public void del() throws IOException{
		this.response.setContentType("text/json; charset=UTF-8");
	    String[] idarry = this.ids.split(",");
	    try {
	      for (int i = 0; i < idarry.length; ++i) {
	    	if(!idarry[i].equals(currentUser.getId())){
	    		this.appPowerService.delete(idarry[i]);
	    		saveOperateLog("授权管理", "删除授权", "删除授权成功!操作主键为:" + idarry[i]);
	    	}else{
	    		saveOperateLog("授权管理", "删除授权", "删除授权为当前授权,跳过:" + idarry[i]);
	    	}
	      }
	      ids=null;
	      printResultJson(true,"删除操作成功!");
	    } catch (Exception e) {
	    	log.error(e);
	    	printResultJson(false,e.getMessage());
	    	saveOperateLog("授权管理", "删除授权", "删除授权失败!" + e.getMessage());
	    }
	}

	public boolean isAccreditByAppId(String appId,List<AppPower> allPowers){
		if(allPowers==null||allPowers.size()==0)return false;
		for(int i=0;i<allPowers.size();i++){
			if(StringUtils.equals(appId, allPowers.get(i).getAppId())){
				return true;
			}
		}
		return false;
	}
	public void getAppTree() throws Exception{
		this.response.setContentType("text/json; charset=UTF-8");
		List<AppInfo> appInfoList =appInfoService.getList(new PageSearchEntity());
	    List<AppPower> appPowerList =appPowerService.getListBySysUser(user);

	    List<ExtCheckTreeMenu> menus = new ArrayList<ExtCheckTreeMenu>();
	    for (int i = 0; i < appInfoList.size(); i++) {
	      ExtCheckTreeMenu parentMenu = new ExtCheckTreeMenu();
	      parentMenu.setId(appInfoList.get(i).getAppId());
	      parentMenu.setText(appInfoList.get(i).getName());
	      parentMenu.setLeaf(true);
	      parentMenu.setIcon("");
	      parentMenu.setUrl("");
	      if (isAccreditByAppId(appInfoList.get(i).getAppId(), appPowerList))
	        parentMenu.setChecked(true);
	      else {
	        parentMenu.setChecked(false);
	      }
	      menus.add(parentMenu);
	    }
	    JSONArray jsonArray = JSONArray.fromObject(menus);
	    this.response.getWriter().print(jsonArray.toString());
	}
	public void savePower() throws Exception {
	    this.response.setContentType("text/json; charset=UTF-8");
	    try {
	      String[] appIdArray = this.appIds.split(",");
	      appPowerService.delAllBy(user);
	      for (int i = 0; i < appIdArray.length; ++i) {
	    	  	AppPower temp = new AppPower();
	    	  	temp.setAppId(appIdArray[i]);
	    	  	temp.setSysUser(user);
	    	  	temp.setCreateMan(currentUser.getUserAccount());
	    	  	temp.setCreateTime(TimeUtils.getCurrentTime());
				appPowerService.save(temp);
	    	}
	      appIds=null;
	      printResultJson(true, "授权成功!");
	    } catch (Exception e) {
	    	log.error(e);
	    	printResultJson(false,e.getMessage());
	    }
	}
	public String getIds() {
		return ids;
	}
	public void setIds(String ids) {
		this.ids = ids;
	}
	public AppPowerService getAppPowerService() {
		return appPowerService;
	}
	public void setAppPowerService(AppPowerService appPowerService) {
		this.appPowerService = appPowerService;
	}
	public SysUserService getSysUserService() {
		return sysUserService;
	}
	public void setSysUserService(SysUserService sysUserService) {
		this.sysUserService = sysUserService;
	}
	public AppInfoService getAppInfoService() {
		return appInfoService;
	}
	public void setAppInfoService(AppInfoService appInfoService) {
		this.appInfoService = appInfoService;
	}
	public String getAppIds() {
		return appIds;
	}
	public void setAppIds(String appIds) {
		this.appIds = appIds;
	}
	public String getUser() {
		return user;
	}
	public void setUser(String user) {
		this.user = user;
	}
	public String getNewpassword() {
		return newpassword;
	}
	public void setNewpassword(String newpassword) {
		this.newpassword = newpassword;
	}
	public String getRepassword() {
		return repassword;
	}
	public void setRepassword(String repassword) {
		this.repassword = repassword;
	}
	public AppPower getAppPower() {
		return appPower;
	}
	public void setAppPower(AppPower appPower) {
		this.appPower = appPower;
	}

}


text:
class Pagination(object):
    def __init__(self, page, row_limit, skip_limit, posts=None):
        self.page = int(page)
        self.row_limit = int(row_limit)
        self.skip_limit = (int(self.page) - 1) * skip_limit
        self.posts = posts
        try:
            self.count = self.posts.count()
        except AttributeError:
            self.count = 0

    @property
    def pages(self):
        return self.count / self.page

    @property
    def has_prev(self):
        return self.page > 1

    @property
    def has_next(self):
        return self.page < self.pages


text:
package com.github.buchandersenn.android_permission_manager.callbacks;

public interface OnPermissionDeniedCallback {
    void onPermissionDenied();
}


text:
layout: event
title:  Jérôme Li-Thiao-Té (RE) // Miss God (PL)
date:   2015-10-01 20:23:00 +0200
is_updated: false
update:   ""

cover-image-path: cover.jpg
imageurl: /assets/image/fixme1x1.jpg
start-date: 2015-10-15 20:30:00 +0200
end-date: ""
event-name: Jérôme Li-Thiao-Té (RE) // Miss God (PL)
event-fee: ""
fb-event-url: http://www.facebook.com/events/548879445262803
ticket-url: ""

genre: concert

comments: true

venues:
  - name: Szimpla Kert
    address: Budapest, Kazinczy u. 14, 1075
    city: Budapest
    code: 1075
    country: Hungary
    embedd-gmap: "<iframe src=\"https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d43130.21132538267!2d19.063272!3d47.496961!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x267742d3fb311da4!2sSzimpla+Kert!5e0!3m2!1sen!2shu!4v1478943258994\" width=\"100%\" height=\"450\" frameborder=\"0\" style=\"border:0\" allowfullscreen></iframe>"
    gmap-url: https://www.google.com/maps/place/Szimpla+Kert/@47.496961,19.063272,13z/data=!4m5!3m4!1s0x0:0x267742d3fb311da4!8m2!3d47.4969609!4d19.0632723?hl=en-US

links:
  - name: ""
    url: ""
  - name: ""
    url: ""

categories:
  - event
# excerpt: HELLO WORLD Event. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different ways, but the most common way is to run `jekyll serve`, which launches a web server and auto-regenerates your site when a file is updated.

---
Miss God is an exquisite singer, composer and producer from Poland. Her music is a subtle electronic sound combined with deep base line, ethnically inspired experimental vocals make an eclectic mixture bringing to mind artist such as Burial, Mister Lies and Soap&Skin. She will perform at Timishorts Film Festival in Romania  16th October with her music to the "Blancanieves" movie.

Miss God & VSHOOD supported Dizzie Rascal & Modeselektor at Electronic Beats Festival in Poznan, Poland, 2013 and featured at a number of prestigious music festivals in Europe including Ambition Festival in London, Heineken Opener Festival and Soundrive Festival, and since winning Skoda & TMobile competition for emerging musicians in 2014 her music can be heard in the National Polish Radio. Miss God composes for film ("Balancavies" by Pablo Berger) and she was also performing in Paris with the dance theatre "Le flux".

Miss God released "Widzę cię" ("I see you", EP, 2013) and "Woda" ("Water", EP,2014).

- Soundcloud: [https://soundcloud.com/miss-god/sets/woda-water](https://soundcloud.com/miss-god/sets/woda-water)
- Cosmic Mother – video: [https://www.youtube.com/watch?v=bH0Vi9Ktyvw](https://www.youtube.com/watch?v=bH0Vi9Ktyvw)
- Far Away – video: [https://www.youtube.com/watch?v=RLvUI3PuXME]( https://www.youtube.com/watch?v=RLvUI3PuXME)
- Facebook: [https://www.facebook.com/MissGodMusic](https://www.facebook.com/MissGodMusic)
- Bandcamp: [http://missgod.bandcamp.com/](http://missgod.bandcamp.com/)
- Twitter: [https://twitter.com/missgodmusic](https://twitter.com/missgodmusic)

---

Jérôme Li-Thiao-Té

Jérôme Li-Thiao-Té drags his violin everywhere he can find people enjoying Music. He is the founding member of "J3ZZ", a producer, a composer and he coaches interdisciplinary improvisation using a violin and electronics. He enjoys working in an international and multicultural environment, always looking for exchanges and collaborations between different artists and societies.

From classical to contemporary music (taking part in Grecsó Zoltán's Willany Leó Improvizációs Táncszínház), spoken word, barn rock, bluegrass and pop music, he likes to jump from one world to another.

Jérôme Li-Thiao-Té is an active member of the European experimental scene and recently performed at Trafo Electrify Vol. 7 in collaboration with electronic artist Modeo, opening for Ben Frost and Vessel.

Events: [{{ site.url }}/categories/event/]({{ site.url }}/categories/event/) [http://www.facebook.com/jeromelithiaote/events](http://www.facebook.com/jeromelithiaote/events)

- J3ZZ: [http://www.j3zz.com/](http://www.j3zz.com/)
- Webpage: [{{ site.url }}/]({{ site.url }}/)
- Facebook: [https://www.facebook.com/jeromelithiaote](https://www.facebook.com/jeromelithiaote)
- Instagram: [http://www.instagram.com/jeromelithiaote](http://www.instagram.com/jeromelithiaote)
- Twitter: [http://www.twitter.com/jeromelithiaote](http://www.twitter.com/jeromelithiaote)
- Bandcamp: [http://goo.gl/4mCx3y](http://goo.gl/4mCx3y)


text:
"""A module to produce a distogram heatmap plot"""

import numpy as np

from conkit.core.struct import Gap
from conkit.plot.contactmapmatrix import ContactMapMatrixFigure
from conkit.plot.tools import _isinstance

class DistogramHeatmapFigure(ContactMapMatrixFigure):
    """A Figure object specifically for a :obj:`~conkit.core.distogram.Distogram`

    This figure will illustrate the predicted residues distances in a
    distogram. If two instances of :obj:`~conkit.core.distogram.Distogram`
    are used, then each half square of the heatmap corresponds with the distances
    at each instance

    Attributes
    ----------
    hierarchy : :obj:`~conkit.core.distogram.Distogram`
       The default distogram hierarchy
    other : :obj:`~conkit.core.distogram.Distogram`
       The second distogram hierarchy
    altloc : bool
       Use the :attr:`~conkit.core.distance.Distance.res_altloc` positions [default: False]

    Examples
    --------
    >>> import conkit
    >>> distogram = conkit.io.read('toxd/toxd.npz', 'rosettanpz').top_map
    >>> sequence  = conkit.io.read('toxd/toxd.fasta', 'fasta').top
    >>> distogram.sequence = sequence
    >>> distogram.set_sequence_register()
    >>> conkit.plot.DistogramHeatmapFigure(distogram)

    """

    def __init__(self, *args, **kwargs):
        """A new distogram heatmap plot

        Parameters
        ----------
        hierarchy : :obj:`~conkit.core.distogram.Distogram`
           The default distogram hierarchy
        other : :obj:`~conkit.core.distogram.Distogram`, optional
           The second distogram hierarchy
        altloc : bool, optional
           Use the :attr:`~conkit.core.distance.Distance.res_altloc` positions [default: False]
        lim : tuple, list, optional
           The [min, max] residue numbers to show
        **kwargs
           General :obj:`~conkit.plot.figure.Figure` keyword arguments

        """
        super(DistogramHeatmapFigure, self).__init__(*args, **kwargs)

    @property
    def hierarchy(self):
        return self._hierarchy

    @hierarchy.setter
    def hierarchy(self, hierarchy):
        if hierarchy and _isinstance(hierarchy, "Distogram"):
            self._hierarchy = hierarchy
        else:
            raise TypeError("Invalid hierarchy type: %s" % hierarchy.__class__.__name__)

    @property
    def other(self):
        return self._other

    @other.setter
    def other(self, hierarchy):
        if hierarchy and _isinstance(hierarchy, "Distogram"):
            self._other = hierarchy
        else:
            raise TypeError("Invalid hierarchy type: %s" % hierarchy.__class__.__name__)

    def draw(self):
        if self._other:
            array = self._hierarchy.merge_arrays(self._hierarchy, self._other)
            self_data = np.array([c for c in self._hierarchy.as_list() if all(ci != Gap.IDENTIFIER for ci in c)])
            other_data = np.array([c for c in self._other.as_list() if all(ci != Gap.IDENTIFIER for ci in c)])
        else:
            array = self._hierarchy.as_array()
            self_data = np.array([c for c in self._hierarchy.as_list() if all(ci != Gap.IDENTIFIER for ci in c)])
            other_data = self_data

        im = self.ax.imshow(array, cmap='hot')
        self.fig.colorbar(im, orientation='vertical')
        self.define_axis_settings(self_data, other_data)

        # TODO: deprecate this in 0.14
        if self._file_name:
            self.savefig(self._file_name, dpi=self._dpi)


text:
/**
 * @fileOverview Sisältää {@link Bullet}-luokan toteutuksen.
 */

"use strict";

/**#nocode+*/
var log = require('./Utils').log
  , rand = require('./Utils').rand
  , distance = require('./Utils').distance
  , NET = require('./Constants').NET
  , WPN = require('./Constants').WPN
  , Obj = require('./Object')
  , Weapons = require('./Weapon');
/**#nocode-*/

/**
 * Luo uuden ammuksen.
 *
 * @class Ammus
 *
 * @param {Server} server  Palvelimen sisältävä muuttuja, instanssi luokasta {@link Server}.
 * @param {Player} player  Pelaaja joka ampui ammuksen
 * @param {Integer} newId  Uuden ammuksen ID
 * @param {Boolean} [mirrored=false]  Peilataanko ammuksen lähtösuunta (kranaatinlaukaisimen 2. ammus)
 *
 * @extends Obj
 *
 * @property {Short}   id           Ammuksen tunnus
 * @property {Player}  player       Kuka ampui
 * @property {Byte}    weapon       Millä aseella tämä on ammuttu
 * @property {Integer} x            Paikkatietoa
 * @property {Integer} y            Paikkatietoa
 * @property {Integer} angle        Ammuksen kulma
 * @property {Float}   prevPosX     Ammuksen edellinen paikka
 * @property {Float}   prevPosY     Ammuksen edellinen paikka
 * @property {Byte}    moved        Onko ammusta vielä liikutettu yhtään
 * @property {Integer} timeShooted  Milloin ammus on ammuttu
 */
function Bullet(server, player, newId, mirrored) {
  Obj.call(this, 0, 0, 0);

  this.server = server;

  // Jos pelaaja on nakkina niin ei anneta sen luoda uutta ammusta
  if (player.spawnTime + server.config.spawnProtection > Date.now()) {
    this.failed = true;
    return;
  }

  // Luodaan ammus
  this.id = newId;
  this.player = player;
  this.weapon = player.weapon;
  this.timeShooted = Date.now();
  this.moved = 0;
  this.x = player.x;
  this.y = player.y;
  this.angle = player.angle;
  this.mirrored = !!mirrored;
}
Bullet.prototype = new Obj();
Bullet.prototype.constructor = Bullet;

/**
 * Alustaa ammuksen.
 *
 * @returns {Boolean}  Onnistuiko ammuksen alustus. Jos palautusarvo on false, ei ammusta tulisi
 *                     lisätä palvelimelle muistiin.
 */
Bullet.prototype.initialize = function () {
  var weaponConfig
    , bPos
    , spread
    , randomSpread;

  // UNIMPLEMENTED
  // Ei tehdä ammusta jos erä on päättynyt

  if ('undefined' === typeof this.player) {
    log.error("Tried to shoot a bullet from an undefined player!");
    return false;
  }

  weaponConfig = Weapons[this.weapon];

  // Debugataan
  if (this.server.debug > 1) {
    log.debug('Created bullet %0 (%1), shot by %2',
      String(this.id).magenta, weaponConfig.name.yellow, this.player.name.green);
  }
  // Mistä ammus lähtee pelaajaan nähden
  bPos = weaponConfig.bulletYaw;
  if (this.weapon === WPN.PISTOL) {
    if (!this.player.handShooted) {
      bPos = -bPos;
      this.player.handShooted = 1;
    } else {
      this.player.handShooted = 0;
    }
  }
  this.x += Math.cos((this.angle) / 180 * Math.PI) * weaponConfig.bulletForth;
  this.y += Math.sin((this.angle) / 180 * Math.PI) * weaponConfig.bulletForth;
  this.x += Math.cos((this.angle - 90) / 180 * Math.PI) * bPos;
  this.y += Math.sin((this.angle - 90) / 180 * Math.PI) * bPos;
  this.prevPosX = this.x;
  this.prevPosY = this.y;

  // Hajonta
  spread = weaponConfig.spread;
  if (this.weapon === WPN.LAUNCHER) {
    if (this.mirrored) {
      spread = -spread;
    }
  } else {
    spread = rand(-spread, spread);
  }

  this.angle += spread;
  if (this.weapon === WPN.SHOTGUN) {
    randomSpread = rand(0, 20);
    this.x += Math.cos((this.angle / 180) * Math.PI) * randomSpread;
    this.y += Math.sin((this.angle / 180) * Math.PI) * randomSpread;
  }

  // Tarkista että onko ammus kartan sisällä ja liikuttele taaksepäin kunnes ei ole
  for (var i = 50; i--; true) {
    if (!this.server.gameState.map.isColliding(this.x, this.y)) {
      break;
    }
    this.x -= Math.cos((this.angle / 180) * Math.PI);
    this.y -= Math.sin((this.angle / 180) * Math.PI);
  }
  // Jos mentiin edellinen for-looppi loppuun asti, niin failataan ammuksen luonti.
  if (i < 0) {
    if (!this.player.zombie || this.server.debug) {
      // Jos kyseessä oli ihmispelaaja niin heitetään varoitusta (tai jos debug)
      log.warn("Player %0 tried to shoot a bullet while inside of a wall!", this.player.name.green);
    }
    return false;
  }

  // Jos tänne asti päästiin, on ammus alustettu onnistuneesti
  return true;
};

/**
 * Päivittää yksittäisen ammuksen.
 */
Bullet.prototype.update = function () {
  var weaponConfig = Weapons[this.weapon]
    , speed = weaponConfig.bulletSpeed // Nopeus riippuu siitä, millä aseella ammus on ammuttu
    , hit = false
    , playerIds;

  if (!this.moved) {
    this.moved = 1;
    speed = 0;
  }
  this.move(this.server.game.movePerSec(speed));

  // Jos on ammuttu kranaatinlaukaisimella niin tutkitaan aikaviive (1 sekunti)
  if (this.weapon === WPN.LAUNCHER && this.timeShooted + 1000 < Date.now()) {
    hit = true;

    // Lisätään viestijonoon ilmoitus osumasta.
    this.server.messages.addToAll({
      msgType: NET.BULLETHIT,  // Mikä viesti
      bullet: this,            // Ammuksen tunnus
      x: this.x,               // Missä osui
      y: this.y,               // Missä osui
      weapon: this.weapon      // Millä aseella ammus ammuttiin
    });

    // Tarkistetaan räjähdysalue ja vahingoitetaan pelaajia
    this.checkExplosion();
  }

  // Osuiko seinään, menikö kartalta ulos tai onko moottorisaha
  if (!hit && (this.server.gameState.map.isColliding(this.x, this.y) || this.weapon === WPN.CHAINSAW)) {
    hit = true;
    // Tarkistetaan räjähdysalue ja vahingoitetaan pelaajia
    this.checkExplosion();
  } else if (!hit) {
    // Ei osunut seinään mutta osuiko pelaajaan
    // UNIMPLEMENTED
    // Ei tarkisteta jos kierros on päättynyt

    playerIds = Object.keys(this.server.players);
    for (var i = playerIds.length; i--; true) {
      hit = this.checkPlayerHit(this.server.players[playerIds[i]]);
      if (hit) {
        break;
      }
    }

    // Jos erä on päättynyt niin ammus on törmännyt
    if (this.server.gameState.sessionComplete) {
      hit = true;
    }
  }

  if (hit) {
    // Jos ollaan törmätty johonkin, poistetaan ammus.
    if (this.server.debug > 1) {
      log.debug('Deleted bullet %0 (%1).', String(this.id).magenta, weaponConfig.name.yellow);
    }
    delete this.server.bullets[this.id];
  } else {
    this.prevPosX = this.x;
    this.prevPosY = this.y;
  }
};

/**
 * Tutkii onko pelaajia räjähdyksen vaikutusalueella. Tai moottorisahan (lol?).
 *
 * @param {Number} [x=this.x]  Tarkistuspisteen x-koordinaatti
 * @param {Number} [y=this.y]  Tarkistuspisteen y-koordinaatti
 *
 * @returns {Boolean} Räjähtikö ammus
 */
Bullet.prototype.checkExplosion = function (x, y) {
  var damageRange = Weapons[this.weapon].damageRange
  , playerIds
  , player
  , isProtected
  , dist
  , checkRange;

  // Jos erä on loppunut niin palataan
  if (this.server.gameState.sessionComplete) {
    return false;
  }

  // Poistutaan jos ammus ei ole räjähtävää mallia
  if (!damageRange) {
    return false;
  }

  // Tarkistetaan, onko annettu x- ja y-koordinaatit parametreina
  if ('number' !== typeof x || 'number' !== typeof y) {
    x = this.x;
    y = this.y;
  }

  if (this.server.debug > 1) {
    log.debug('Checking explosion from %0 (%1) at (%2, %3).',
      String(this.id).magenta, Weapons[this.weapon].name.yellow,
      this.x.toFixed(1).blue, this.y.toFixed(1).blue);
  }

  playerIds = Object.keys(this.server.players);
  for (var i = playerIds.length; i--; true) {
    player = this.server.players[playerIds[i]];
    isProtected = (player.spawnTime + this.server.config.spawnProtection > Date.now());
    // Onko pelaaja aktiivinen, hengissä eikä suojattu
    if (player.active && player.health > 0 && !isProtected) {
      dist = distance(x, y, player.x, player.y);
      checkRange = true;

      if (this.weapon === WPN.CHAINSAW && this.player === player) {
        // Moottorisahalla ei voi osua itseensä
        checkRange = false;
      }

      // Onko etäisyys pienempi kuin räjähdyksen vaikutusalue
      if (dist <= damageRange && checkRange) {
        player.applyExplosion(this, dist);
      }
    }
  }

  // Ammus on räjähtänyt.
  return true;
};

/**
 * Tutkii osuiko ammus pelaajaan.
 * @param {Player} player  Pelaaja, kehen tarkistus kohdistuu.
 * @returns {Boolean} Osuiko vai eikö
 */
Bullet.prototype.checkPlayerHit = function (player) {
  var isProtected = (player.spawnTime + this.server.config.spawnProtection > Date.now())
    , move
    , xMove
    , yMove
    , steps
    , stp
    , bPos
    , bx
    , by;
  // Osuma tutkitaan vain jos pelaaja on aktiivinen ja hengissä
  if (!isProtected && player.active && player.health > 0) {
    move = distance(this.prevPosX, this.prevPosY, this.x, this.y);
    xMove = (this.x - this.prevPosX) / move;
    yMove = (this.y - this.prevPosY) / move;

    // Ammus on voinut kulkea yhden framen aikana paljonkin joten tutkitaan siirtymää vähitellen.
    steps = Math.ceil(move / 5);
    if (steps > 0) {
      // Tutkitaan välipisteet
      stp = move / steps;
      for (var i = 1; i <= steps; i++) {
        bPos = i * stp;
        bx = this.prevPosX + (xMove * bPos);
        by = this.prevPosY + (yMove * bPos);

        // Nyt tarkistetaan osuma. Osumaa itseensä ei tarkisteta
        if (player !== this.player && distance(player.x, player.y, bx, by) < 20) {
          // Osui
          player.bulletHit(this, bx, by);
          return true;
        }
      }
    }
  }

  // Jos tänne asti päästiin, ei ammus osunut.
  return false;
};

module.exports = Bullet;


text:
class AddRefundedAtToDonation < ActiveRecord::Migration
  def change
    change_table :donations do |t|
      t.datetime :refunded_at, after: :disputed_at
    end
  end
end


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

<title>HistoryManager</title>
<meta name="date" content="2012-10-22">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.google.zxing.client.android.history

Class HistoryManager

java.lang.Object

com.google.zxing.client.android.history.HistoryManager

public final class HistoryManager
extends java.lang.Object

Manages functionality related to scan history.

Author:

Sean Owen

Constructor Summary

Constructors

Constructor and Description

HistoryManager(android.app.Activity activity)

Method Summary

Methods

Modifier and Type
Method and Description

void
addHistoryItem(Result result,
              ResultHandler handler)

void
addHistoryItemDetails(java.lang.String itemID,
                     java.lang.String itemDetails)

HistoryItem
buildHistoryItem(int number)

java.util.List<HistoryItem>
buildHistoryItems()

void
deleteHistoryItem(int number)

boolean
hasHistoryItems()

void
trimHistory()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HistoryManager

public HistoryManager(android.app.Activity activity)

Method Detail

hasHistoryItems

public boolean hasHistoryItems()

buildHistoryItems

public java.util.List<HistoryItem> buildHistoryItems()

buildHistoryItem

public HistoryItem buildHistoryItem(int number)

deleteHistoryItem

public void deleteHistoryItem(int number)

addHistoryItem

public void addHistoryItem(Result result,
                  ResultHandler handler)

addHistoryItemDetails

public void addHistoryItemDetails(java.lang.String itemID,
                         java.lang.String itemDetails)

trimHistory

public void trimHistory()

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php
echo "
";
echo "You are logged in as : ";
echo $this->session->userdata('user_name');
echo "
";

echo "
";
echo "

Username	Email	Role	Status

";
echo "
";
$odd_even = "odd";
foreach ($users as $row)
{
	$ini_file = $this->config->item('config_path') . "users/" . $row . ".ini";

	/* Check if database ini file exists */
	if (get_file_info($ini_file))
	{
		/* Parsing database ini file */
		$active_users = parse_ini_file($ini_file);
		if ($active_users)
		{
			$username = isset($active_users['username']) ? $active_users['username'] : "-";
			$email = isset($active_users['email']) ? $active_users['email'] : "-";
			$role = isset($active_users['role']) ? $active_users['role'] : "-";
			$status = isset($active_users['status']) ? $active_users['status'] : "-";
		}
	}

	echo "
session->userdata('user_name') == $row)
		echo " tr-active";
	echo "\">";
	echo "" . $username . "	";
	echo "" . $email . "	";

	echo "";
	switch ($role)
	{
		case "administrator": echo "administrator"; break;
		case "manager": echo "manager"; break;
		case "accountant": echo "accountant"; break;
		case "dataentry": echo "dataentry"; break;
		case "guest": echo "guest"; break;
		default: echo "(unknown)"; break;
	}
	echo "	";

	echo "";
	switch ($status)
	{
		case 0: echo "Disabled"; break;
		case 1: echo "Active"; break;
		default: echo "(unknown)"; break;
	}
	echo "	";

	if ($this->session->userdata('user_name') == $row)
	{
		echo "";
		echo anchor("admin/user/edit/" . $row, "Edit", array('title' => 'Edit User', 'class' => 'red-link'));
		echo "	";
	} else {
		echo "";
		echo anchor("admin/user/edit/" . $row, "Edit", array('title' => 'Edit User', 'class' => 'red-link'));
		echo "  " . anchor('admin/user/delete/' .  $row, img(array('src' => asset_url() . "images/icons/delete.png", 'border' => '0', 'alt' => 'Delete User', 'class' => "confirmClick", 'title' => "Delete User")), array('title' => 'Delete User')) . " ";
		echo "	";
	}

	echo "
";
	$odd_even = ($odd_even == "odd") ? "even" : "odd";
}
echo "
";
echo "
";
echo "
";
echo anchor('admin', 'Back', array('title' => 'Back to admin'));


text: Name of an environment variable to be set to the temporary path of the SSH key file during the build. The contents of this file are not masked.


text:
"""
This is a minimum working example of a Matchmaker Exchange server.
It is intended strictly as a useful reference, and should not be
used in a production setting.
"""

from __future__ import with_statement, division, unicode_literals

import logging
import json

from flask import Flask, request, after_this_request, jsonify
from flask_negotiate import consumes, produces
from collections import defaultdict
from werkzeug.exceptions import BadRequest

from .compat import urlopen, Request
from .auth import auth_token_required
from .models import MatchRequest
from .schemas import validate_request, validate_response, ValidationError

API_MIME_TYPE = 'application/vnd.ga4gh.matchmaker.v1.0+json'

# Global flask application
app = Flask(__name__.split('.')[0])
# app.config['DEBUG'] = True

# Logger
logger = logging.getLogger(__name__)

@app.route('/v1/match', methods=['POST'])
@consumes(API_MIME_TYPE, 'application/json')
@produces(API_MIME_TYPE)
@auth_token_required()
def match():
    """Return patients similar to the query patient"""

    @after_this_request
    def add_header(response):
        response.headers['Content-Type'] = API_MIME_TYPE
        return response

    try:
        logger.info("Getting flask request data")
        request_json = request.get_json(force=True)
    except BadRequest:
        error = jsonify(message='Invalid request JSON')
        error.status_code = 400
        return error

    try:
        logger.info("Validate request syntax")
        validate_request(request_json)
    except ValidationError as e:
        error = jsonify(message='Request does not conform to API specification',
                        request=request_json)
        error.status_code = 422
        return error

    logger.info("Parsing query")
    request_obj = MatchRequest.from_api(request_json)

    logger.info("Finding similar patients")
    response_obj = request_obj.match(n=5)

    logger.info("Serializing response")
    response_json = response_obj.to_api()

    try:
        logger.info("Validating response syntax")
        validate_response(response_json)
    except ValidationError as e:
        # log to console and return response anyway
        logger.error('Response does not conform to API specification:\n{}\n\nResponse:\n{}'.format(e, response_json))

    return jsonify(response_json)


text:
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="@dimen/icon_small"
    android:layout_height="@dimen/icon_small" />


text:
SRC=$HOME/.dotfiles/nixos
sudo rsync --filter="protect /hardware-configuration.nix" \
           --filter="protect /hostname" \
           --filter="protect /nixpkgs" \
           --filter="exclude,s *.gitignore" \
           --filter="exclude,s *.gitmodules" \
           --filter="exclude,s *.git" \
           --filter="exclude .*.swp" \
           --filter="exclude Session.vim" \
           --delete --recursive --perms \
           $SRC/ /etc/nixos/

if [ $# -eq 0 ]; then
  operation='switch'
else
  operation=$1
fi
cd $wd
sudo NIX_CURL_FLAGS='--retry 1000' nixos-rebuild --fast --keep-failed $operation


text:
class AliEvePreferencesWindow : public TGMainFrame
{
public:
    static AliEvePreferencesWindow* Instance();

    void onExit(bool save=true);

private:
    AliEvePreferencesWindow();
    ~AliEvePreferencesWindow();

    static AliEvePreferencesWindow *fInstance;

    void InitWindow();
    void ReadFromConfigFile();
    void SaveToConfigFile();
    void ApplyChanges();

    virtual Bool_t ProcessMessage(Long_t msg, Long_t parm1, Long_t);

    TGNumberEntry *fTrackWidth;
    TGCheckButton *fDashNoRefit;
    TGCheckButton *fDrawNoRefit;
    TGCheckButton *fTracksByPID;
    TGCheckButton *fTracksByCategory;

    TGCheckButton *fShowV0s;
    TGCheckButton *fShowCascades;
    TGCheckButton *fShowRawData;
    TGCheckButton *fShowPrimaryVertex;
    TGCheckButton *fShowHits;
    TGCheckButton *fShowDigits;
    TGCheckButton *fShowClusters;
    TGCheckButton *fShowKinks;

    TGTextEntry *fLogbookHost;
    TGNumberEntry *fLogbookPort;
    TGTextEntry *fLogbookDatabase;
    TGTextEntry *fLogbookUser;
    TGTextEntry *fLogbookPassword;

    TGCheckButton *fShowMuon;
    TGCheckButton *fShowHLTESDTree;
    TGTextEntry *fOCDBpath;
    TGCheckButton *fAutoload;
    TGCheckButton *fAliceLive;

    TGTextButton *fSaveAndExitButton;
    TGTextButton *fCancel;

    TGColorSelect *fColorSelect2658;//tpc
    TGColorSelect *fColorSelect2668;//tof
    TGColorSelect *fColorSelect2669;//trd
    TGColorSelect *fColorSelect2670;//muon
    TGColorSelect *fColorSelect2671;//spd
    TGColorSelect *fColorSelect2672;//sdd
    TGColorSelect *fColorSelect2673;//ssd
    TGColorSelect *fColorSelect2674;//phos
    TGColorSelect *fColorSelect2675;//emcal
    TGColorSelect *fColorSelect2676;//hmpid

    TGColorSelect *fColorSelect2693;// electron
    TGColorSelect *fColorSelect2694;// muon
    TGColorSelect *fColorSelect2695;// pion
    TGColorSelect *fColorSelect2696;// kaon
    TGColorSelect *fColorSelect2697;// proton
    TGColorSelect *fColorSelect2698;// deuteron
    TGColorSelect *fColorSelect2699;// triton
    TGColorSelect *fColorSelect2700;// he3
    TGColorSelect *fColorSelect2701;// alpha
    TGColorSelect *fColorSelect2702;// photon
    TGColorSelect *fColorSelect2703;// pi0
    TGColorSelect *fColorSelect2704;// neutron
    TGColorSelect *fColorSelect2705;// kaon0
    TGColorSelect *fColorSelect2706;// elecon
    TGColorSelect *fColorSelect2707;// unknown

    AliEvePreferencesWindow(const AliEvePreferencesWindow&);            // Not implemented
    AliEvePreferencesWindow& operator=(const AliEvePreferencesWindow&); // Not implemented

    ClassDef(AliEvePreferencesWindow, 0); // Short description.
};

#endif


text:
import PropTypes from 'prop-types';
import Router from 'next/router';

import NanoButton from '../components/elements/NanoButton';

const FullScreenBanner = props => (

{props.headline}

{props.tagline}

      <NanoButton type="button" className="btn btn-lg" onClick={() => Router.push('/page2')}>Test Page</NanoButton>

);

FullScreenBanner.propTypes = {
  headline: PropTypes.string,
  tagline: PropTypes.string,
};
FullScreenBanner.defaultProps = {
  headline: '',
  tagline: '',
};

export default FullScreenBanner;


text:
package com.jayway.restassured.itest.java;

import com.jayway.restassured.itest.java.support.WithJetty;
import org.junit.Test;

import static com.jayway.restassured.RestAssured.expect;
import static com.jayway.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;

public class ParamITest extends WithJetty {

    @Test
    public void noValueParamWhenUsingParamWithGetRequest() throws Exception {
        given().param("some").expect().body(is("Params: some=")).when().get("/noValueParam");
    }

    @Test
    public void noValueParamWhenUsingQueryParamWithGetRequest() throws Exception {
        given().queryParam("some").expect().body(is("Params: some=")).when().get("/noValueParam");
    }

    @Test
    public void multipleNoValueQueryParamWhenUsingQueryParamInUrlForGetRequest() throws Exception {
        // For some reason Scalatra returns the order different when running in Intellij and Maven
        expect().body(anyOf(is("Params: some=some1="), is("Params: some1=some="))).when().get("/noValueParam?some&some1");
    }

    @Test
    public void singleNoValueQueryParamWhenUsingQueryParamInUrlForGetRequest() throws Exception {
        expect().body(is("Params: some=")).when().get("/noValueParam?some");
    }

    @Test
    public void mixingStartingNoValueQueryParamWhenUsingQueryParamInUrlForGetRequest() throws Exception {
        expect().body(is("Params: some1=some2=one")).when().get("/noValueParam?some1&some2=one");
    }

    @Test
    public void mixingEndingNoValueQueryParamWhenUsingQueryParamInUrlForGetRequest() throws Exception {
        expect().body(is("Params: some1=onesome2=")).when().get("/noValueParam?some1=one&some2");
    }

    @Test
    public void noValueParamWhenUsingFormParamWithPutRequest() throws Exception {
        given().formParam("some").expect().body(is("OK")).when().put("/noValueParam");
    }

    @Test
    public void noValueParamWhenUsingFormParamWithPostRequest() throws Exception {
        given().formParam("some").expect().body(is("Params: some=")).when().post("/noValueParam");
    }

    @Test
    public void multipleNoValueParamWhenUsingFormParamWithPostRequest() throws Exception {
        // For some reason Scalatra returns the order different when running in Intellij and Maven
        given().formParam("some").and().formParam("some1").expect().body(anyOf(is("Params: some=some1="), is("Params: some1=some="))).when().post("/noValueParam");
    }

    @Test
    public void formParamsAreUrlEncoded() throws Exception {
        given().
                formParam("firstName", "Some & firstname").
                formParam("lastName", "<lastname>").
        expect().
                body("greeting", equalTo("Greetings Some & firstname <lastname>")).
        when().
                post("/greet");
    }

    @Test
    public void formParamsAreUrlEncodedWithDefinedCharset() throws Exception {
        given().
                contentType("application/x-www-form-urlencoded; charset=ISO-8859-1").
                formParam("ikk", "&&&").
        expect().
                body(is("iso-8859-1")). // Jetty 9 always send charset as lowercase
        when().
                post("/charEncoding");
    }

    @Test
    public void charsetIsReallyDefined() throws Exception {
        given().
                contentType("application/x-www-form-urlencoded; charset=ISO-8859-1").
                formParam("firstName", "Some & firstname").
                formParam("lastName", "<lastname>").
        expect().
                body("greeting", equalTo("Greetings Some & firstname <lastname>")).
        when().
                post("/greet");
    }

    @Test
    public void formParamsAreUrlEncodedWithUtf8WhenCharsetDefinedWithNoEqualSign() throws Exception {
        given().
                contentType("application/x-www-form-urlencoded; charset").
                formParam("firstName", "Some & firstname").
                formParam("lastName", "<lastname>").
        expect().
                body("greeting", equalTo("Greetings Some & firstname <lastname>")).
        when().
                post("/greet");
    }

    @Test
    public void mixingNoValueAndValueParamWhenUsingFormParamWithPostRequest() throws Exception {
        // For some reason Scalatra returns the order different when running in Intellij and Maven
        given().formParam("some").and().formParam("some1", "one").expect().body(anyOf(is("Params: some=some1=one"), is("Params: some1=onesome="))).when().post("/noValueParam");
    }

    @Test
    public void noValueParamWhenUsingParamWithPostRequest() throws Exception {
        given().param("some").expect().body(is("Params: some=")).when().post("/noValueParam");
    }

    @Test
    public void whenLastParamInGetRequestEndsWithEqualItsTreatedAsANoValueParam() throws Exception {
        expect().body("greeting", equalTo("Greetings John ")).when().get("/greet?firstName=John&lastName=");
    }

    @Test
    public void whenFirstParamInGetRequestEndsWithEqualItsTreatedAsANoValueParam() throws Exception {
        expect().body("greeting", equalTo("Greetings  Doe")).when().get("/greet?firstName=&lastName=Doe");
    }

    @Test
    public void multiPartUploadingWorksForFormParamsAndByteArray() throws Exception {
        given().
                formParam("formParam1").
                formParam("formParam2", "formParamValue").
                multiPart("file", "juX").
                multiPart("string", "body").
        expect().
                statusCode(200).
                body(containsString("formParam1 -> WrappedArray()")).
        when().
                post("/multipart/multiple");
    }
}


text:
<!-- travis no permissions - CacheTest -->
<!-- issue with config.php in travis? - MailTest -->
<!-- env issue in travis - CookieTest.php && FileSystemTest.php -->
<phpunit bootstrap="vendor/autoload.php">
	<testsuites>
		<testsuite name="core">
            <!-- <file>test/CookieTest.php</file> -->
            <!-- <file>test/MailTest.php</file> -->
            <file>test/CacheTest.php</file>
            <file>test/ControllerTest.php</file>
            <file>test/DatabaseTest.php</file>
            <file>test/FactoryIteratorTest.php</file>
            <file>test/FactoryTest.php</file>
            <file>test/FileSystemTest.php</file>
            <file>test/FileSystemTest.php</file>
            <file>test/HelperTest.php</file>
            <file>test/IteratorCollectionTest.php</file>
            <file>test/IteratorModelTest.php</file>
            <file>test/IteratorTest.php</file>
            <file>test/KernelTest.php</file>
            <file>test/MapperTest.php</file>
            <file>test/ModelTest.php</file>
            <file>test/MonologTest.php</file>
            <file>test/PaginationTest.php</file>
            <file>test/RequestTest.php</file>
            <file>test/ResponseTest.php</file>
            <file>test/RouterTest.php</file>
            <file>test/ServiceTest.php</file>
            <file>test/SessionTest.php</file>
            <file>test/UrlTest.php</file>
            <file>test/ViewTest.php</file>
        </testsuite>
	</testsuites>
</phpunit>