text:
package edu.pitt.cabig.cae.domain.general;

/**
 * <!-- LICENSE_TEXT_START -->
 * <!-- LICENSE_TEXT_END -->
 */

  /**
   * The edge of the specimen removed during a surgical procedure.
   */

public  class SurgicalMargin
    extends AnnotationSet
	implements java.io.Serializable
{
	private static final long serialVersionUID = 1234567890L;

	   private java.lang.String spatialRelationshipToPatient;
	   public  java.lang.String getSpatialRelationshipToPatient(){
	      return spatialRelationshipToPatient;
	   }
	   public void setSpatialRelationshipToPatient( java.lang.String spatialRelationshipToPatient){
	      this.spatialRelationshipToPatient = spatialRelationshipToPatient;
	   }

	   private java.lang.String otherSpatialRelationshipToPatient;
	   public  java.lang.String getOtherSpatialRelationshipToPatient(){
	      return otherSpatialRelationshipToPatient;
	   }
	   public void setOtherSpatialRelationshipToPatient( java.lang.String otherSpatialRelationshipToPatient){
	      this.otherSpatialRelationshipToPatient = otherSpatialRelationshipToPatient;
	   }

	   private java.lang.String MVR;
	   public  java.lang.String getMVR(){
	      return MVR;
	   }
	   public void setMVR( java.lang.String MVR){
	      this.MVR = MVR;
	   }

		public boolean equals(Object obj){
			boolean eq = false;
			if(obj instanceof SurgicalMargin) {
				SurgicalMargin c =(SurgicalMargin)obj;
				Long thisId = getId();

					if(thisId != null && thisId.equals(c.getId())) {
					   eq = true;
				    }

			}
			return eq;
		}

		public int hashCode(){
			int h = 0;

			if(getId() != null) {
				h += getId().hashCode();
			}

			return h;
	}

}


text:
@interface ABKWarbleResource : AFHTTPClient

@property (strong, nonatomic) NSDictionary *currentSong;
@property (strong, nonatomic) NSArray *songQueue;

-(id)initWithBaseURL:(NSURL *)url;

+(void)setVolume:(int)level;
+(void)getCurrentPlayWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id JSON))success
                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
+(void)skipSong;
+(void)likeSong;

+(NSArray *)songQueue;
+(NSUInteger)getQueueLength;
+(void)getQueueWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id JSON))success
                   failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
@end

redpajama_set_name: RedPajamaGithub


text:
import { ApplicationException } from './ApplicationException';
/**
 * Access errors caused by missing user identity or security permissions
 */
export declare class UnauthorizedException extends ApplicationException {
    constructor(correlation_id?: string, code?: string, message?: string);
}


text:
=pod

=head1 NAME

FileCheck - Flexible pattern matching file verifier

=head1 SYNOPSIS

B<FileCheck> I<match-filename> [I<--check-prefix=XXX>] [I<--strict-whitespace>]

=head1 DESCRIPTION

B<FileCheck> reads two files (one from standard input, and one specified on the
command line) and uses one to verify the other.  This behavior is particularly
useful for the testsuite, which wants to verify that the output of some tool
(e.g. llc) contains the expected information (for example, a movsd from esp or
whatever is interesting).  This is similar to using grep, but it is optimized
for matching multiple different inputs in one file in a specific order.

The I<match-filename> file specifies the file that contains the patterns to
match.  The file to verify is always read from standard input.

=head1 OPTIONS

=over

=item B<-help>

Print a summary of command line options.

=item B<--check-prefix> I<prefix>

FileCheck searches the contents of I<match-filename> for patterns to match.  By
default, these patterns are prefixed with "CHECK:".  If you'd like to use a
different prefix (e.g. because the same input file is checking multiple
different tool or options), the B<--check-prefix> argument allows you to specify
a specific prefix to match.

=item B<--strict-whitespace>

By default, FileCheck canonicalizes input horizontal whitespace (spaces and
tabs) which causes it to ignore these differences (a space will match a tab).
The --strict-whitespace argument disables this behavior.

=item B<-version>

Show the version number of this program.

=back

=head1 EXIT STATUS

If B<FileCheck> verifies that the file matches the expected contents, it exits
with 0.  Otherwise, if not, or if an error occurs, it will exit with a non-zero
value.

=head1 TUTORIAL

FileCheck is typically used from LLVM regression tests, being invoked on the RUN
line of the test.  A simple example of using FileCheck from a RUN line looks
like this:

  ; RUN: llvm-as < %s | llc -march=x86-64 | FileCheck %s

This syntax says to pipe the current file ("%s") into llvm-as, pipe that into
llc, then pipe the output of llc into FileCheck.  This means that FileCheck will
be verifying its standard input (the llc output) against the filename argument
specified (the original .ll file specified by "%s").  To see how this works,
lets look at the rest of the .ll file (after the RUN line):

  define void @sub1(i32* %p, i32 %v) {
  entry:
  ; CHECK: sub1:
  ; CHECK: subl
          %0 = tail call i32 @llvm.atomic.load.sub.i32.p0i32(i32* %p, i32 %v)
          ret void
  }

  define void @inc4(i64* %p) {
  entry:
  ; CHECK: inc4:
  ; CHECK: incq
          %0 = tail call i64 @llvm.atomic.load.add.i64.p0i64(i64* %p, i64 1)
          ret void
  }

Here you can see some "CHECK:" lines specified in comments.  Now you can see
how the file is piped into llvm-as, then llc, and the machine code output is
what we are verifying.  FileCheck checks the machine code output to verify that
it matches what the "CHECK:" lines specify.

The syntax of the CHECK: lines is very simple: they are fixed strings that
must occur in order.  FileCheck defaults to ignoring horizontal whitespace
differences (e.g. a space is allowed to match a tab) but otherwise, the contents
of the CHECK: line is required to match some thing in the test file exactly.

One nice thing about FileCheck (compared to grep) is that it allows merging
test cases together into logical groups.  For example, because the test above
is checking for the "sub1:" and "inc4:" labels, it will not match unless there
is a "subl" in between those labels.  If it existed somewhere else in the file,
that would not count: "grep subl" matches if subl exists anywhere in the
file.

=head2 The FileCheck -check-prefix option

The FileCheck -check-prefix option allows multiple test configurations to be
driven from one .ll file.  This is useful in many circumstances, for example,
testing different architectural variants with llc.  Here's a simple example:

  ; RUN: llvm-as < %s | llc -mtriple=i686-apple-darwin9 -mattr=sse41 \
  ; RUN:              | FileCheck %s -check-prefix=X32
  ; RUN: llvm-as < %s | llc -mtriple=x86_64-apple-darwin9 -mattr=sse41 \
  ; RUN:              | FileCheck %s -check-prefix=X64

  define <4 x i32> @pinsrd_1(i32 %s, <4 x i32> %tmp) nounwind {
          %tmp1 = insertelement <4 x i32>; %tmp, i32 %s, i32 1
          ret <4 x i32> %tmp1
  ; X32: pinsrd_1:
  ; X32:    pinsrd $1, 4(%esp), %xmm0

  ; X64: pinsrd_1:
  ; X64:    pinsrd $1, %edi, %xmm0
  }

In this case, we're testing that we get the expected code generation with
both 32-bit and 64-bit code generation.

=head2 The "CHECK-NEXT:" directive

Sometimes you want to match lines and would like to verify that matches
happen on exactly consequtive lines with no other lines in between them.  In
this case, you can use CHECK: and CHECK-NEXT: directives to specify this.  If
you specified a custom check prefix, just use "<PREFIX>-NEXT:".  For
example, something like this works as you'd expect:

  define void @t2(<2 x double>* %r, <2 x double>* %A, double %B) {
	%tmp3 = load <2 x double>* %A, align 16
	%tmp7 = insertelement <2 x double> undef, double %B, i32 0
	%tmp9 = shufflevector <2 x double> %tmp3,
                              <2 x double> %tmp7,
                              <2 x i32> < i32 0, i32 2 >
	store <2 x double> %tmp9, <2 x double>* %r, align 16
	ret void

  ; CHECK: t2:
  ; CHECK: 	movl	8(%esp), %eax
  ; CHECK-NEXT: 	movapd	(%eax), %xmm0
  ; CHECK-NEXT: 	movhpd	12(%esp), %xmm0
  ; CHECK-NEXT: 	movl	4(%esp), %eax
  ; CHECK-NEXT: 	movapd	%xmm0, (%eax)
  ; CHECK-NEXT: 	ret
  }

CHECK-NEXT: directives reject the input unless there is exactly one newline
between it an the previous directive.  A CHECK-NEXT cannot be the first
directive in a file.

=head2 The "CHECK-NOT:" directive

The CHECK-NOT: directive is used to verify that a string doesn't occur
between two matches (or the first match and the beginning of the file).  For
example, to verify that a load is removed by a transformation, a test like this
can be used:

  define i8 @coerce_offset0(i32 %V, i32* %P) {
    store i32 %V, i32* %P

    %P2 = bitcast i32* %P to i8*
    %P3 = getelementptr i8* %P2, i32 2

    %A = load i8* %P3
    ret i8 %A
  ; CHECK: @coerce_offset0
  ; CHECK-NOT: load
  ; CHECK: ret i8
  }

=head2 FileCheck Pattern Matching Syntax

The CHECK: and CHECK-NOT: directives both take a pattern to match.  For most
uses of FileCheck, fixed string matching is perfectly sufficient.  For some
things, a more flexible form of matching is desired.  To support this, FileCheck
allows you to specify regular expressions in matching strings, surrounded by
double braces: B<{{yourregex}}>.  Because we want to use fixed string
matching for a majority of what we do, FileCheck has been designed to support
mixing and matching fixed string matching with regular expressions.  This allows
you to write things like this:

  ; CHECK: movhpd	{{[0-9]+}}(%esp), {{%xmm[0-7]}}

In this case, any offset from the ESP register will be allowed, and any xmm
register will be allowed.

Because regular expressions are enclosed with double braces, they are
visually distinct, and you don't need to use escape characters within the double
braces like you would in C.  In the rare case that you want to match double
braces explicitly from the input, you can use something ugly like
B<{{[{][{]}}> as your pattern.

=head2 FileCheck Variables

It is often useful to match a pattern and then verify that it occurs again
later in the file.  For codegen tests, this can be useful to allow any register,
but verify that that register is used consistently later.  To do this, FileCheck
allows named variables to be defined and substituted into patterns.  Here is a
simple example:

  ; CHECK: test5:
  ; CHECK:    notw	[[REGISTER:%[a-z]+]]
  ; CHECK:    andw	{{.*}}[[REGISTER]]

The first check line matches a regex (<tt>%[a-z]+</tt>) and captures it into
the variables "REGISTER".  The second line verifies that whatever is in REGISTER
occurs later in the file after an "andw".  FileCheck variable references are
always contained in <tt>[[ ]]</tt> pairs, are named, and their names can be
formed with the regex "<tt>[a-zA-Z_][a-zA-Z0-9_]*</tt>".  If a colon follows the
name, then it is a definition of the variable, if not, it is a use.

FileCheck variables can be defined multiple times, and uses always get the
latest value.  Note that variables are all read at the start of a "CHECK" line
and are all defined at the end.  This means that if you have something like
"<tt>CHECK: [[XYZ:.*]]x[[XYZ]]<tt>" that the check line will read the previous
value of the XYZ variable and define a new one after the match is performed.  If
you need to do something like this you can probably take advantage of the fact
that FileCheck is not actually line-oriented when it matches, this allows you to
define two separate CHECK lines that match on the same line.

=head1 AUTHORS

Maintained by The LLVM Team (L<http://llvm.org>).

=cut


text:
FROM ubuntu:trusty

ENV DEBIAN_FRONTEND noninteractive
ENV OPT_MROOTPWD CorrectHorseBatteryStaple42

# install all packages
RUN echo "mysql-server mysql-server/root_password password $OPT_MROOTPWD" | debconf-set-selections && \
    echo "mysql-server mysql-server/root_password_again password $OPT_MROOTPWD" | debconf-set-selections && \
    apt-get update && apt-get install -y --no-install-recommends \
        apache2 \
        apache2-utils \
        ca-certificates \
        curl \
        ipmitool \
        libapache2-mod-php5 \
        libapache2-mod-proxy-html \
        librrd4 \
        libtime-modules-perl \
        logrotate \
        mysql-server \
        nmap \
        openssh-client \
        php5 \
        php5-cli \
        php5-ldap \
        php5-mcrypt \
        php5-mysql \
        php5-snmp \
        rrdtool \
        screen \
        smbclient \
        sshpass \
        wget \
        zip \
        && \
    apt-get clean && rm -rf /var/lib/apt/lists/*

# versions and variables
EXPOSE 80
ENV OAEVERSION %VERSION%
ENV OAEDOWNLOAD http://dl-openaudit.opmantek.com/OAE-Linux-x86_64-release_$OAEVERSION.run

# fetch OAE installer from Opmantek server
WORKDIR /tmp
RUN curl "$OAEDOWNLOAD" -o /tmp/openaudit.run && \
    (test -f /tmp/openaudit.run || echo "[[[ FILE DOESN'T EXIST ]]]") && \
    chmod 755 /tmp/openaudit.run && \
    /tmp/openaudit.run --check && \
    /tmp/openaudit.run --noexec --keep && \
    rm /tmp/openaudit.run

# setup mysql volume and ownership
VOLUME /data/mysql
CMD chown -Rf mysql: /data/mysql

# install OAE
RUN service mysql start && \
    cd /tmp/Open-AudIT* && \
    timeout -s9 5m ./installer && \
    service mysql stop

# move distribution data out of the way (run.sh will move them back if necessary)
RUN mv /var/lib/mysql /var/lib/mysql-dist && \
    mv /usr/local/omk/conf /usr/local/omk/conf-dist

# give nmap setgid as requested by OAE
RUN chmod g+s $(which nmap)

# enable php5 modules
RUN php5enmod mcrypt

# setup run.sh, which is our container init
WORKDIR /usr/local/omk
COPY run.sh run.sh
RUN chmod 755 run.sh
CMD ["./run.sh"]


text:
'use strict'

var locator = require('node-service-locator');
var request = require('supertest');
var q = require('q');
var moment = require('moment-timezone');
var app = require('../../app.js');
var Job = require('../../jobs/notify');
var JobModel = require('../../models/job');
var NotificationModel = require('../../models/notification');

describe('Notify job', function () {
    var config;
    var model;

    beforeEach(function () {
        config = locator.get('config');
        config['error']['job_failure']['enabled'] = false;
        locator.register('config', config);

        locator.register('logger', {
            log: function () {},
            trace: function () {},
            debug: function () {},
            info: function () {},
            warn: function () {},
            error: function () {},
        });

        model = new JobModel();
        model.setName('notify');
        model.setQueue('queue');
        model.setStatus('created');
        model.setCreatedAt(moment());
        model.setScheduledFor(moment());
        model.setValidUntil(moment().add(5, 'days'));
        model.setInputData({});
        model.setOutputData({});
    });

    afterEach(function () {
    });

    it('works', function (done) {
        var notification = new NotificationModel();
        notification.setId('id');
        notification.setText('text');
        notification.setTitle('title');
        notification.setIcon('icon');
        notification.setVariables({ foo: 'bar' });
        notification.setUserId(42);
        notification.setRoleId(9000);
        model.setInputData(notification.data());

        var savedNotification;
        locator.register('notification-repository', {
            save: function (model) {
                savedNotification = model;
                var defer = q.defer();
                defer.resolve('resolved_id');
                return defer.promise;
            },
        });

        locator.register('job-repository', {
            save: function (model) {
                expect(model.getStatus()).toBe('success');
                expect(savedNotification.data()).toEqual(notification.data());
                done();
            },
        });

        Job(model);
    });
});


text:
#include "color.h"

static int find_candidate(_ljit_color_stack *cs,
                          ljit_interference_graph *ig)
{
    for (int i = 0; i < ig->size; ++i)
    {
        if (!_ljit_color_stack_is_present(cs, i) &&
            _ljit_liveness_info_size(ig->graph[i]) < LJIT_USABLE_REGS)
            return i;
    }

    return -1;
}

static void remove_all_vertex(ljit_interference_graph *ig, int candidate)
{
    _ljit_liveness_info *li = ig->graph[candidate];

    while (li)
    {
        ig->graph[li->elt] = _ljit_liveness_info_remove(ig->graph[li->elt],
                                                        candidate);

        li = li->next;
    }
}

static void _ljit_fill_stack(_ljit_color_stack *cs,
                             ljit_interference_graph *ig)
{
    int ig_virtual_size = ig->size;
    int candidate = 0;

    while (ig_virtual_size)
    {
        /*
        ** Find a node with less than K node.
        ** Where K is the number of registers)
        */
        if ((candidate = find_candidate(cs, ig)) == -1)
            assert(0 && "This function needs spill. Not implemented yet");

        /* Remove all vertex from this node */
        remove_all_vertex(ig, candidate);

        /* Push this node on the stack */
        _ljit_color_stack_push(cs, candidate, ig->graph[candidate]);
        ig->graph[candidate] = NULL;

        --ig_virtual_size;
    }
}

static int is_in(unsigned char elt, unsigned char *array, unsigned int size)
{
    for (unsigned int i = 0; i < size; ++i)
    {
        if (array[i] == elt)
            return 1;
    }

    return 0;
}

static unsigned char get_color_for_node(ljit_interference_graph *ig,
                                        _ljit_liveness_info *vertex)
{
    unsigned char color = 0;
    unsigned int size = _ljit_liveness_info_size(vertex);
    unsigned int tmp = 0;
    unsigned char *forbidden_colors = alloca(size);

    while (vertex)
    {
        forbidden_colors[tmp++] = ig->colors[vertex->elt];
        vertex = vertex->next;
    }

    while (is_in(color, forbidden_colors, size))
        ++color;

    return color;
}

static void restore_vertex(_ljit_liveness_info *vertex,
                           int edge,
                           ljit_interference_graph *ig)
{
    _ljit_liveness_info *tmp = NULL;
    ig->graph[edge] = vertex;

    while (vertex)
    {
        tmp = _ljit_liveness_info_new(edge);
        ig->graph[vertex->elt] = _ljit_liveness_add_head(ig->graph[vertex->elt],
                                                         tmp);

        vertex = vertex->next;
    }
}

void _ljit_color_graph(ljit_interference_graph *ig)
{
    _ljit_color_stack *cs = NULL;
    int number = 0;
    _ljit_liveness_info *vertex = NULL;

    cs = _ljit_color_stack_new(ig->size);

    _ljit_fill_stack(cs, ig);

    while (!_ljit_color_stack_is_empty(cs))
    {
        vertex = _ljit_color_stack_pop(cs, &number);
        ig->colors[number] = get_color_for_node(ig, vertex);
        restore_vertex(vertex, number, ig);
    }

    _ljit_color_stack_free(cs);
}


text:
NS_ASSUME_NONNULL_BEGIN

@interface _LNWeakRef : NSObject

@property (nonatomic, weak, readonly) id object;

+ (instancetype)refWithObject:(id)object;

@end

NS_ASSUME_NONNULL_END


text:
package io.github.rcarlosdasilva.weixin.api.weixin.impl;

import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

import io.github.rcarlosdasilva.weixin.api.BasicApi;
import io.github.rcarlosdasilva.weixin.api.weixin.CertificateApi;
import io.github.rcarlosdasilva.weixin.common.ApiAddress;
import io.github.rcarlosdasilva.weixin.common.Utils;
import io.github.rcarlosdasilva.weixin.common.dictionary.WebAuthorizeScope;
import io.github.rcarlosdasilva.weixin.core.OpenPlatform;
import io.github.rcarlosdasilva.weixin.core.Registry;
import io.github.rcarlosdasilva.weixin.core.Weixin;
import io.github.rcarlosdasilva.weixin.core.cache.CacheHandler;
import io.github.rcarlosdasilva.weixin.core.exception.CanNotFetchAccessTokenException;
import io.github.rcarlosdasilva.weixin.core.exception.CanNotFetchOpenPlatformLicensorAccessTokenException;
import io.github.rcarlosdasilva.weixin.core.exception.InvalidAccountException;
import io.github.rcarlosdasilva.weixin.core.exception.LostWeixinLicensedRefreshTokenException;
import io.github.rcarlosdasilva.weixin.core.json.Json;
import io.github.rcarlosdasilva.weixin.core.listener.AccessTokenUpdatedListener;
import io.github.rcarlosdasilva.weixin.core.listener.JsTicketUpdatedListener;
import io.github.rcarlosdasilva.weixin.model.AccessToken;
import io.github.rcarlosdasilva.weixin.model.JsTicket;
import io.github.rcarlosdasilva.weixin.model.JsapiSignature;
import io.github.rcarlosdasilva.weixin.model.WeixinAccount;
import io.github.rcarlosdasilva.weixin.model.request.certificate.AccessTokenRequest;
import io.github.rcarlosdasilva.weixin.model.request.certificate.JsTicketRequest;
import io.github.rcarlosdasilva.weixin.model.request.certificate.WaAccessTokenRefreshRequest;
import io.github.rcarlosdasilva.weixin.model.request.certificate.WaAccessTokenRequest;
import io.github.rcarlosdasilva.weixin.model.request.certificate.WaAccessTokenVerifyRequest;
import io.github.rcarlosdasilva.weixin.model.response.certificate.AccessTokenResponse;
import io.github.rcarlosdasilva.weixin.model.response.certificate.JsTicketResponse;
import io.github.rcarlosdasilva.weixin.model.response.certificate.WaAccessTokenResponse;
import io.github.rcarlosdasilva.weixin.model.response.open.auth.OpenPlatformAuthGetLicenseInformationResponse;

/**
 * 认证相关API实现
 *
 * @author Dean Zhao
 */
public class CertificateApiImpl extends BasicApi implements CertificateApi {

  private final Logger logger = LoggerFactory.getLogger(CertificateApiImpl.class);

  public CertificateApiImpl(String accountKey) {
    super(accountKey);
  }

  @Override
  public synchronized String askAccessToken() {
    AccessToken token = CacheHandler.of(AccessToken.class).get(this.accountKey);
    if (token != null && !token.isExpired()) {
      return token.getAccessToken();
    }

    if (null == token) {
      logger.debug("For:{} >> 无缓存过的access_token,请求access_token", this.accountKey);
    } else {
      logger.debug("For:{} >> 因access_token过期,重新请求。失效的access_token:[{}]", this.accountKey, token);
    }

    final WeixinAccount account = Registry.lookup(this.accountKey);
    if (account == null) { // 不应该为空
      throw new InvalidAccountException();
    }

    while (true) {
      token = CacheHandler.of(AccessToken.class).get(this.accountKey);
      if (token != null && !token.isExpired()) {
        break;
      }

      String identifier = CacheHandler.of(AccessToken.class).lock(this.accountKey, 2000, true);
      if (Strings.isNullOrEmpty(identifier)) {
        try {
          Thread.sleep(100);
          continue;
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        }
      }

      if (account.isWithOpenPlatform()) {
        // 使用微信开放平台获取access_token。在公众号授权后,会自动获取第一次授权方的access_token
        final String refreshToken = null == token ? account.getRefreshToken()
            : token.getRefreshToken();
        token = refreshLicensedAccessToken(account.getAppId(), refreshToken);
      } else {
        // 使用公众号appid和appsecret获取access_token
        token = requestAccessToken();
      }
      CacheHandler.of(AccessToken.class).unlock(this.accountKey, identifier);
    }

    if (token == null) {
      logger.error("无法获取微信公众号的access_token");
      throw new CanNotFetchAccessTokenException();
    }

    return token.getAccessToken();
  }

  @Override
  public void refreshAccessToken() {
    requestAccessToken();
  }

  @Override
  public void updateAccessToken(String token, long expiredAt) {
    if (Strings.isNullOrEmpty(token) || expiredAt < 0) {
      logger.warn("For:{} >> 使用错误的数据更新token: {}, {}", this.accountKey, token, expiredAt);
      return;
    }

    long expiresIn = 7200L * 1000L;
    if (expiredAt > 0) {
      expiresIn = expiredAt - System.currentTimeMillis();
    }
    String responseMock = String.format("{'access_token':'%s','expires_in':%s}", token,
        (expiresIn / 1000));
    AccessToken accessToken = Json.fromJson(responseMock, AccessTokenResponse.class);
    accessToken.setAccountMark(this.accountKey);
    CacheHandler.of(AccessToken.class).put(this.accountKey, accessToken);
  }

  /**
   * 更新使用开放平台的授权方的access_token.
   *
   * @return 请求结果
   */
  private synchronized AccessToken refreshLicensedAccessToken(String licensorAppId,
      String refreshToken) {
    Preconditions.checkNotNull(licensorAppId);

    if (Strings.isNullOrEmpty(refreshToken)) {
      logger.error("找不到正确的授权方access_token刷新令牌,或许需要授权方重新授权");
      throw new LostWeixinLicensedRefreshTokenException();
    }

    OpenPlatformAuthGetLicenseInformationResponse response = OpenPlatform.certificate()
        .refreshLicensorAccessToken(licensorAppId, refreshToken);
    if (response == null
        || Strings.isNullOrEmpty(response.getLicensedAccessToken().getAccessToken())) {
      logger.error("获取不到授权方的access_token");
      throw new CanNotFetchOpenPlatformLicensorAccessTokenException();
    }

    AccessToken accessToken = response.getLicensedAccessToken();
    accessToken.setAccountMark(this.accountKey);
    CacheHandler.of(AccessToken.class).put(this.accountKey, accessToken);
    logger.debug("For:{} >> 开放平台更新授权方access_token:[{}]", this.accountKey,
        accessToken.getAccessToken());

    return accessToken;
  }

  /**
   * 真正请求access_token代码.
   *
   * @return 请求结果
   */
  private synchronized AccessToken requestAccessToken() {
    logger.debug("For:{} >> 正在获取access_token", this.accountKey);
    WeixinAccount account = Registry.lookup(this.accountKey);
    AccessTokenRequest requestModel = new AccessTokenRequest();
    requestModel.setAppId(account.getAppId());
    requestModel.setAppSecret(account.getAppSecret());

    AccessToken accessToken = get(AccessTokenResponse.class, requestModel);

    if (accessToken != null) {
      accessToken.setAccountMark(this.accountKey);
      CacheHandler.of(AccessToken.class).put(this.accountKey, accessToken);
      logger.debug("For:{} >> 获取到access_token:[{}]", this.accountKey, accessToken.getAccessToken());

      final AccessTokenUpdatedListener listener = Registry
          .listener(AccessTokenUpdatedListener.class);
      if (listener != null) {
        logger.debug("For:{} >> 调用监听器AccessTokenUpdatedListener", this.accountKey);
        listener.updated(account.getKey(), account.getAppId(), accessToken.getAccessToken(),
            accessToken.getExpiresIn());
      }

      return accessToken;
    }

    return null;
  }

  @Override
  public final String askJsTicket() {
    JsTicket ticket = CacheHandler.of(JsTicket.class).get(this.accountKey);
    if (ticket != null && !ticket.isExpired()) {
      return ticket.getJsTicket();
    }

    if (null == ticket) {
      logger.debug("For:{} >> 无缓存过的jsapi_ticket,请求jsapi_ticket", this.accountKey);
    } else {
      logger.debug("For:{} >> 因jsapi_ticket过期,重新请求。失效的jsapi_ticket:[{}]", this.accountKey, ticket);
    }

    while (true) {
      ticket = CacheHandler.of(JsTicket.class).get(this.accountKey);
      if (ticket != null && !ticket.isExpired()) {
        break;
      }

      String identifier = CacheHandler.of(JsTicket.class).lock(this.accountKey, 2000, true);
      if (Strings.isNullOrEmpty(identifier)) {
        try {
          Thread.sleep(100);
          continue;
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        }
      }

      ticket = requestJsTicket();
      CacheHandler.of(AccessToken.class).unlock(this.accountKey, identifier);
    }

    return null == ticket ? null : ticket.getJsTicket();
  }

  @Override
  public void refreshJsTicket() {
    requestJsTicket();
  }

  @Override
  public void updateJsTicket(String ticket, long expiredAt) {
    if (Strings.isNullOrEmpty(ticket) || expiredAt < 0) {
      logger.warn("For:{} >> 使用错误的数据更新ticket: {}, {}", this.accountKey, ticket, expiredAt);
      return;
    }

    long expiresIn = 7200L * 1000L;
    if (expiredAt > 0) {
      expiresIn = expiredAt - System.currentTimeMillis();
    }
    String responseMock = String.format("{'access_token':'%s','expires_in':%s}", ticket,
        (expiresIn / 1000));
    JsTicketResponse responseModel = Json.fromJson(responseMock, JsTicketResponse.class);
    responseModel.updateExpireAt();
    CacheHandler.of(JsTicket.class).put(this.accountKey, responseModel);
  }

  /**
   * 真正请求jsapi_ticket代码.
   *
   * @return 请求结果
   */
  private synchronized JsTicketResponse requestJsTicket() {
    logger.debug("For:{} >> 正在获取jsapi_ticket", this.accountKey);
    JsTicketRequest requestModel = new JsTicketRequest();

    JsTicketResponse responseModel = get(JsTicketResponse.class, requestModel);

    if (responseModel != null) {
      responseModel.updateExpireAt();
      CacheHandler.of(JsTicket.class).put(this.accountKey, responseModel);
      logger.debug("For:{} >> 获取jsapi_ticket:[{}]", this.accountKey, responseModel.getJsTicket());

      final JsTicketUpdatedListener listener = Registry.listener(JsTicketUpdatedListener.class);
      if (listener != null) {
        logger.debug("For:{} >> 调用监听器JsTicketUpdatedListener", this.accountKey);
        WeixinAccount account = Registry.lookup(this.accountKey);
        listener.updated(account.getKey(), account.getAppId(), responseModel.getJsTicket(),
            responseModel.getExpiresIn());
      }

      return responseModel;
    }

    return null;
  }

  @Override
  public WaAccessTokenResponse askWebAuthorizeAccessToken(String code) {
    WeixinAccount account = Registry.lookup(this.accountKey);
    WaAccessTokenRequest requestModel = new WaAccessTokenRequest();
    requestModel.setAppId(account.getAppId());
    requestModel.setAppSecret(account.getAppSecret());
    requestModel.setCode(code);

    return get(WaAccessTokenResponse.class, requestModel);
  }

  @Override
  public WaAccessTokenResponse refreshWebAuthorizeAccessToken(String refreshToken) {
    WeixinAccount account = Registry.lookup(this.accountKey);
    WaAccessTokenRefreshRequest requestModel = new WaAccessTokenRefreshRequest();
    requestModel.setAppId(account.getAppId());
    requestModel.setRefreshToken(refreshToken);

    return get(WaAccessTokenResponse.class, requestModel);
  }

  @Override
  public boolean verifyWebAuthorizeAccessToken(String accessToken, String openId) {
    WaAccessTokenVerifyRequest requestModel = new WaAccessTokenVerifyRequest();
    requestModel.setAccessToken(accessToken);
    requestModel.setOpenId(openId);

    return get(Boolean.class, requestModel);
  }

  @Override
  public String webAuthorize(WebAuthorizeScope scope, String redirectTo, String param) {
    WeixinAccount account = Registry.lookup(this.accountKey);

    return new StringBuilder(ApiAddress.URL_WEB_AUTHORIZE).append("?appid=")
        .append(account.getAppId()).append("&redirect_uri=").append(Utils.urlEncode(redirectTo))
        .append("&response_type=code&scope=").append(scope)
        .append(Strings.isNullOrEmpty(param) ? "" : ("&state=" + param)).append("#wechat_redirect")
        .toString();
  }

  @Override
  public String webAuthorize(WebAuthorizeScope scope, String redirectTo) {
    return webAuthorize(scope, redirectTo, null);
  }

  @Override
  public JsapiSignature generateJsapiSignature(String url) {
    WeixinAccount account = Registry.lookup(this.accountKey);
    String ticket = Weixin.with(this.accountKey).certificate().askJsTicket();
    String timestamp = Long.toString(System.currentTimeMillis() / 1000);
    String nonce = UUID.randomUUID().toString();

    String raw = new StringBuilder("jsapi_ticket=").append(ticket).append("&noncestr=")
        .append(nonce).append("&timestamp=").append(timestamp).append("&url=").append(url)
        .toString();
    String signature = null;

    signature = DigestUtils.sha1Hex(raw);

    return new JsapiSignature(account.getAppId(), ticket, signature, url, timestamp, nonce);
  }

}


text:
fluent-plugin-influxdb is a buffered output plugin for fluentd and influxDB.

If you are using fluentd as a collector and want to organize your time-series data in influxDB, this is your right choice!

## Requirements

| fluent-plugin-influxdb | fluentd | ruby |
|------------------------|---------|------|
| >= 2.0.0 | >= v1.0.0  | >= 2.3 |
| >= 1.0.0 | >= v0.14.0 | >= 2.1 |
|  < 1.0.0 | >= v0.12.0 | >= 1.9 |

## Installation

    $ fluent-gem install fluent-plugin-influxdb --no-document # for fluentd v1.0 or later
    $ fluent-gem install fluent-plugin-influxdb -v "~> 1.0" --no-document # for fluentd v1.0  or later and ruby 2.2 or earlier
    $ fluent-gem install fluent-plugin-influxdb -v "~> 0.3" --no-document # for fluentd v0.12 or later and ruby 2.0 or earlier

### Ruby 2.0 or earlier

`influxdb` gem requires `cause` gem in Ruby 2.0 or earlier. If you want to use `fluent-plugin-influxdb` with Ruby 2.0 or earlier,
you should install `cause` gem before install `fluent-plugin-influxdb`.

## Usage

Just like other regular output plugins, Use type `influxdb` in your fluentd configuration under `match` scope:

`@type` `influxdb`

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

**Options:**

`host`: The IP or domain of influxDB, separate with comma, default to "localhost"

`port`: The HTTP port of influxDB, default to 8086

`dbname`: The database name of influxDB, default to "fluentd". you should create the database and grant permissions first

`measurement`: The measurement/serise for record insertion. The default is nil.

`user`: The DB user of influxDB, should be created manually, default to "root"

`password`: The password of the user, default to "root"

`retry`: The finite number of retry times. default is infinite

`use_ssl`: Use SSL when connecting to influxDB. default to false

`verify_ssl`: Enable/Disable SSL Certs verification when connecting to influxDB via SSL. default to true

`time_key`: Use value of this tag if it exists in event instead of event timestamp

`time_precision`: The time precision of timestamp. default to "s". should specify either hour (h), minutes (m), second (s), millisecond (ms), microsecond (u), or nanosecond (ns)

`auto_tags`: Enable/Disable auto-tagging behaviour which makes strings tags.

`tag_keys`: The names of the keys to use as influxDB tags.

`sequence_tag`: The name of the tag whose value is incremented for the consecutive simultaneous events and reset to zero for a new event with the different timestamp

`default_retention_policy`: The retention policy applied by default.  influxdb >= 0.2.3 is required to use this functionality.

`retention_policy_key`: The name of the key in the record whose value specifies the retention policy.  The default retention policy will be applied if no such key exists.  influxdb >= 0.2.3 is required to use this functionality.

`cast_number_to_float`: Enable/Disable casting number to float. influxdb can't mix integer/float value in one measurement. If your pipeline can't unify record value, this parameter may help. Avoid 'field type conflict' error.

### Fluentd Tag and InfluxDB Series

influxdb plugin uses Fluentd event tag for InfluxDB series.
So if you have events with `app.event`, influxdb plugin inserts events into `app.event` series in InfluxDB.

If you set `measurement` parameter, use its value instead of event tag.

## Configuration Example

```
<match mylog.*>
  @type influxdb
  host  localhost
  port  8086
  dbname test
  user  testuser
  password  mypwd
  use_ssl false
  time_precision s
  tag_keys ["key1", "key2"]
  sequence_tag _seq
</match>
```

## Cache and multiprocess

fluentd-plugin-influxdb is a buffered output plugin. So additional buffer configuration would be (with default values):

```
<buffer>
  @type memory
  chunk_limit_size 524288 # 512 * 1024
  chunk_limit_records 1024
  flush_interval 60
  retry_limit 17
  retry_wait 1.0
  num_threads 1
</buffer>
```

The details of BufferedOutput is [here](http://docs.fluentd.org/articles/buffer-plugin-overview).

---

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## Licence

This package was distributed under MIT licence, see LICENCE file for details.

This plugin was written by Fang.Li and was inspired by [Uken's](https://github.com/uken/fluent-plugin-elasticsearch) elasticsearch plugin.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<parent>
		<artifactId>orika-parent</artifactId>
		<groupId>ma.glasnost.orika</groupId>
		<version>1.5.1-SNAPSHOT</version>
	</parent>
	<modelVersion>4.0.0</modelVersion>
	<artifactId>orika-tests-jdk8</artifactId>
	<name>Orika - tests for JDK8</name>

	<properties>
		<javassist.version>3.20.0-GA</javassist.version>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>

	<dependencies>

		<dependency>
			<groupId>ma.glasnost.orika</groupId>
			<artifactId>orika-core</artifactId>
			<version>${project.parent.version}</version>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>ma.glasnost.orika</groupId>
			<artifactId>orika-eclipse-tools</artifactId>
			<version>${project.parent.version}</version>
			<scope>compile</scope>
			<exclusions>
				<exclusion>
					<groupId>org.slf4j</groupId>
					<artifactId>slf4j-simple</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-library</artifactId>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-core</artifactId>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<scope>compile</scope>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.3</version>
				<configuration>
					<source>${maven.compiler.source}</source>
					<target>${maven.compiler.target}</target>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.18.1</version>
				<configuration>
					<argLine>-Xmx512m</argLine>
					<systemPropertyVariables>
						<!-- Prevent accidental usage of EclipseJdt compiler strategy (outside of the EclipseJdt-specific tests -->
						<ma.glasnost.orika.test.MappingUtil.noDebug>true</ma.glasnost.orika.test.MappingUtil.noDebug>
					</systemPropertyVariables>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


text:
using Foundation;
using UIKit;

namespace CollectionView {
	/// <summary>
	/// Waterfall collection delegate.
	/// </summary>
	/// <remarks>
	/// Origionally created by Nicholas Tau on 6/30/14.
	/// Copyright (c) 2014 Nicholas Tau. All rights reserved.
	/// Ported from http://nshint.io/blog/2015/07/16/uicollectionviews-now-have-easy-reordering/ to
	/// Xamarin.iOS by Kevin Mullins.
	/// </remarks>
	public class WaterfallCollectionDelegate : UICollectionViewDelegate {
		#region Computed Properties
		public WaterfallCollectionView CollectionView { get; set;}
		#endregion

		#region Constructors
		public WaterfallCollectionDelegate (WaterfallCollectionView collectionView)
		{
			// Initialize
			CollectionView = collectionView;
		}
		#endregion

		#region Overrides Methods
		public override bool ShouldHighlightItem (UICollectionView collectionView, NSIndexPath indexPath)
		{
			// Always allow for highlighting
			return true;
		}

		public override void ItemHighlighted (UICollectionView collectionView, NSIndexPath indexPath)
		{
			// Get cell and change to green background
			var cell = collectionView.CellForItem (indexPath);
			cell.ContentView.BackgroundColor = UIColor.FromRGB (183, 208, 57);
		}

		public override void ItemUnhighlighted (UICollectionView collectionView, NSIndexPath indexPath)
		{
			// Get cell and return to blue background
			var cell = collectionView.CellForItem (indexPath);
			cell.ContentView.BackgroundColor = UIColor.FromRGB (164, 205, 255);
		}
		#endregion
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Opegrapha insignior var. insignior

### Remarks
null


text:
namespace Knapcode.RemindMeWhen.Core.Models
{
    public class MovieReleasedToTheaterEvent : MovieReleasedEvent
    {
    }
}


text:
#ifndef CSM_GPU_CONSTANTS_H
#define CSM_GPU_CONSTANTS_H

#include "Ogre.h"

namespace Ogre
{

class CSMGpuConstants
{
public:
	CSMGpuConstants(size_t cascadeCount);
	void updateCascade(const Ogre::Camera &texCam, size_t index);

private:
	Ogre::GpuSharedParametersPtr mParamsScaleBias;
	Ogre::GpuSharedParametersPtr mParamsShadowMatrix;

	Ogre::Matrix4 mFirstCascadeViewMatrix;
	Ogre::Real mFirstCascadeCamWidth;
	Ogre::Real mViewRange;
		Matrix4 hack;
};

} // namespace Ogre

#endif // CSM_GPU_CONSTANTS_H


text:
package org.apache.jena.hadoop.rdf.io.input.util;

import java.io.IOException;
import java.io.InputStream;

/**
 * A tracked input stream which can is a wrapper around another input stream and
 * can report the number of bytes read
 *
 *
 *
 */
public class TrackedInputStream extends TrackableInputStream {

    protected InputStream input;
    protected long bytesRead = 0, lastMark;

    /**
     * Creates a new tracked input stream
     *
     * @param input
     *            Input stream to track
     */
    public TrackedInputStream(InputStream input) {
        if (input == null)
            throw new NullPointerException("Input cannot be null");
        this.input = input;
    }

    @Override
    public int read() throws IOException {
        int read = this.input.read();
        if (read >= 0)
            this.bytesRead++;
        return read;
    }

    @Override
    public long getBytesRead() {
        return this.bytesRead;
    }

    @Override
    public void close() throws IOException {
        this.input.close();
    }

    @Override
    public int available() throws IOException {
        return this.input.available();
    }

    @Override
    public synchronized void mark(int readlimit) {
        this.input.mark(readlimit);
        this.lastMark = this.bytesRead;
    }

    @Override
    public boolean markSupported() {
        return this.input.markSupported();
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        if (len == 0) return 0;
        int read = this.input.read(b, off, len);
        if (read > 0)
            this.bytesRead += read;
        return read;
    }

    @Override
    public int read(byte[] b) throws IOException {
        return this.read(b, 0, b.length);
    }

    @Override
    public synchronized void reset() throws IOException {
        this.input.reset();
        this.bytesRead = this.lastMark;
    }

    @Override
    public long skip(long n) throws IOException {
        if (n == 0)
            return 0;
        long skipped = 0;
        byte[] buffer = new byte[16];
        int readSize = Math.min(buffer.length, n > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) n);
        int read;
        do {
            if (n - skipped > readSize) {
                read = this.input.read(buffer, 0, readSize);
            } else {
                read = this.input.read(buffer, 0, (int) (n - skipped));
            }
            if (read > 0) {
                this.bytesRead += read;
                skipped += read;
            }
        } while (skipped < n && read >= 0);

        return skipped;
    }
}


text:
% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9)
%
% Copyright (C) 1993-2011, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB.  If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function qd = dot(q, omega)
    E = q.s*eye(3,3) - skew(q.v);
    omega = omega(:);
    qd = Quaternion(-0.5*q.v*omega, 0.5*E*omega);
end


text:
package client

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/nextrevision/rsc/config"
	"github.com/nextrevision/rsc/helper"

	"github.com/nextrevision/go-runscope"
)

// ListTests prints all tests in a given bucket
func (rc *RunscopeClient) ListTests(bucketName string, format string) error {
	rc.Log.Debugf("Listing tests in bucket '%s'", bucketName)
	bucket, err := rc.GetBucketByName(bucketName)
	if err != nil {
		return err
	}

	tests, err := rc.Runscope.ListAllTests(bucket.Key)
	if err != nil {
		return err
	}

	if format == "json" {
		data, err := json.MarshalIndent(tests, "", "  ")
		if err != nil {
			return err
		}
		fmt.Println(string(data))
	} else {
		header := []string{"Name", "Created By", "Last Run", "Last Status", "Description"}
		rows := [][]string{}
		for _, t := range tests {
			lastRun := time.Unix(int64(t.LastRun.FinishedAt), 0)
			rows = append(rows, []string{
				t.Name,
				t.CreatedBy.Name,
				lastRun.Format(time.RFC3339),
				t.LastRun.Status,
				helper.TruncateString(t.Description, 30),
			})
		}
		helper.WriteTable(header, rows)
	}

	return nil
}

// ShowTest prints details for a given test
func (rc *RunscopeClient) ShowTest(bucketName string, testName string, format string) error {
	rc.Log.Debugf("Showing test '%s' in bucket '%s'", testName, bucketName)

	bucket, err := rc.GetBucketByName(bucketName)
	if err != nil {
		return err
	}

	test, err := rc.GetTestByName(bucket.Key, testName)
	if err != nil {
		return err
	}

	test.Schedules, err = rc.Runscope.ListSchedules(bucket.Key, test.ID)
	if err != nil {
		return err
	}

	test.Environments, err = rc.Runscope.ListTestEnvironments(bucket.Key, test.ID)
	if err != nil {
		return err
	}

	test.Steps, err = rc.Runscope.ListSteps(bucket.Key, test.ID)
	if err != nil {
		return err
	}

	// only support json format
	data, err := json.MarshalIndent(test, "", "  ")
	if err != nil {
		return err
	}
	fmt.Println(string(data))

	return nil
}

// GetTestByName searches for a test in the supplied bucket
// and returns a Test object if found
func (rc *RunscopeClient) GetTestByName(bucketKey string, testName string) (runscope.Test, error) {
	var test = runscope.Test{}

	tests, err := rc.Runscope.ListAllTests(bucketKey)
	if err != nil {
		return test, err
	}

	for _, t := range tests {
		if t.Name == testName {
			return t, nil
		}
	}

	return test, fmt.Errorf("No such test: %s", testName)
}

// CreateOrUpdateTest searches for a test in a bucket and
// creates a new test if it does not exists, otherwise the
// test is updated
func (rc *RunscopeClient) CreateOrUpdateTest(tc *config.TestConfig, d bool) error {
	if tc.BucketKey == "" {
		bucket, err := rc.GetBucketByName(tc.Bucket)
		if err != nil && d {
			rc.Log.Infof("Would have created test: %s", tc.Name)
			return nil
		} else if err != nil {
			rc.Log.Errorf("Could determine bucket for test: %s", tc.Name)
			return err
		}

		tc.BucketKey = bucket.Key
	}

	tests, err := rc.Runscope.ListAllTests(tc.BucketKey)
	if err != nil {
		rc.Log.Errorf("Could list tests for bucket: %s", tc.BucketKey)
		return err
	}

	for _, test := range tests {
		if test.Name == tc.Name {
			if d {
				rc.Log.Infof("Would have updated test: %s", tc.Name)
				return nil
			}

			return rc.updateTest(tc, test.ID)
		}
	}

	if d {
		rc.Log.Infof("Would have created test: %s", tc.Name)
		return nil
	}
	return rc.createTest(tc)
}

// DeleteTest deletes a test from a bucket
func (rc *RunscopeClient) DeleteTest(b string, t string) error {
	bucket, err := rc.GetBucketByName(b)
	if err != nil {
		return err
	}

	test, err := rc.GetTestByName(bucket.Key, t)
	if err != nil {
		return err
	}

	rc.Log.Debugf("Deleting test from bucket '%s': %s (%s)", bucket.Name, test.Name, test.ID)
	return rc.Runscope.DeleteTest(bucket.Key, test.ID)
}

func (rc *RunscopeClient) createTest(tc *config.TestConfig) error {
	rc.Log.Debugf("Creating test: %s", tc.Name)

	_, err := rc.Runscope.ImportTest(tc.BucketKey, tc.Bytes)
	if err == nil {
		rc.Log.Infof("Created test: %s", tc.Name)
	} else {
		rc.Log.Errorf("Error creating test: %s", tc.Name)
	}

	return err
}

func (rc *RunscopeClient) updateTest(tc *config.TestConfig, testID string) error {
	rc.Log.Debugf("Updating test: %s", tc.Name)

	_, err := rc.Runscope.ReimportTest(tc.BucketKey, testID, tc.Bytes)
	if err == nil {
		rc.Log.Infof("Updated test: %s", tc.Name)
	} else {
		rc.Log.Errorf("Error updating test: %s", tc.Name)
	}

	return err
}

func (rc *RunscopeClient) printSteps(steps []runscope.Step, indent string) {
	baseIndent := indent + "  "
	fmt.Printf("%sSteps (%d):\n", baseIndent, len(steps))
	for i, s := range steps {
		i = i + 1
		if s.StepType == "request" {
			fmt.Printf("%s  %d. Request: %s %s\n", baseIndent, i, s.Method, s.URL)
		}

		if s.StepType == "condition" {
			fmt.Printf("%s  %d. Condition: %s %s %s\n", baseIndent, i, s.LeftValue, s.Comparison, s.RightValue)
		}

		if len(s.Variables) != 0 {
			fmt.Printf("%s    Variables: (%d):\n", baseIndent, len(s.Variables))
			for _, v := range s.Variables {
				varStr := fmt.Sprintf("%s = %s", v.Name, v.Source)
				if v.Property != "" {
					varStr = varStr + "." + v.Property
				}
				fmt.Printf("%s      %s\n", baseIndent, varStr)
			}
		}

		if len(s.Assertions) != 0 {
			fmt.Printf("%s    Assertions (%d):\n", baseIndent, len(s.Assertions))
			for _, a := range s.Assertions {
				aStr := a.Source
				if a.Property != "" {
					aStr = aStr + "." + a.Property
				}
				fmt.Printf("%s      %s %s %v\n", baseIndent, aStr, a.Comparison, a.Value.(interface{}))
			}
		}

		if len(s.Steps) != 0 {
			rc.printSteps(s.Steps, baseIndent)
		}
		fmt.Println("")
	}
}


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Audio Volume</title>
    <script src="../libs/three.min.js"></script>
    <script src="../libs/dat.gui.min.js"></script>
    <script src="../libs/stats.min.js"></script>
    <script src="../libs/TrackballControls.js"></script>
        <style>
            body {
                /* set margin to 0 and overflow to hidden, to go fullscreen */
                margin: 0;
                overflow: hidden;
            }
        </style>
  </head>
  <body>
<script type="text/javascript">

setupSound()
//基本的初始化函数

// global variables
var renderer;
var scene;
var camera;
var control;
var stats;
var isTweening = false;
var controls;
function init() {
    // create a scene, that will hold all our elements such as objects, cameras and lights.
    scene = new THREE.Scene();
    var boxGeo=new THREE.BoxGeometry(30,60,30,100,30,150);
    var pm=new THREE.ParticleSystemMaterial();
    pm.map=THREE.ImageUtils.loadTexture("../assets/textures/particles/particle.png");
    pm.blending=THREE.AdditiveBlending;
    pm.transparent=true;
    pm.size=1.0;

    var ps=new THREE.ParticleSystem(boxGeo,pm);
    ps.sortParticles = true;
    ps.name='cube';
    ps.position.x=1.75;
    scene.add(ps)

    var pm2=pm.clone();
    pm2.map=THREE.ImageUtils.loadTexture("../assets/textures/particles/particle2.png");
    pm2.blending=THREE.AdditiveBlending;
    pm2.transparent=true;

    var ps2=new THREE.ParticleSystem(boxGeo,pm2);
    ps2.name='cube2';
    ps2.position.x=100;
    scene.add(ps2);

// 增加波形内容

//

    // create a render, sets the background color and the size
    renderer = new THREE.WebGLRenderer();
    renderer.setClearColor(0x000000, 1.0);
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.shadowMap.enabled = true;

    // create a camera, which defines where we're looking at.
    camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
    // position and point the camera to the center of the scene
    camera.position.x = 70;
    camera.position.y = 130;
    camera.position.z = 130;
    camera.lookAt(new THREE.Vector3(10,0,35));
    controls = new THREE.TrackballControls( camera );
    // setup the control object for the control gui

    // setup the control object for the control gui
    control = new function () {
    };

    // add extras
    addControlGui(control);
    addStatsObject();

    document.body.appendChild(renderer.domElement);
    render();
    loadSound("../assets/audio/wagner-short.ogg");
}
function addControlGui(controlObject) {
    var gui = new dat.GUI();
    // gui.add(controlObject,'forward');
    // gui.add(controlObject,'back');
    // gui.add(controlObject,'left');
    // gui.add(controlObject,'right');

}

function addStatsObject() {
    stats = new Stats();
    stats.setMode(0);

    stats.domElement.style.position = 'absolute';
    stats.domElement.style.left = '0px';
    stats.domElement.style.top = '0px';

    document.body.appendChild( stats.domElement );
}

// function createCube(){

var c=0;
function render() {

    // update stats
    c++;
    if(c%2==0){
      updateWaves();
    }
    stats.update();
    updateCubes();
    renderer.render(scene, camera);
    controls.update();
    // render using requestAnimationFrame
    requestAnimationFrame(render);
}
function updateWaves(){
    var array =  new Uint8Array(analyser.frequencyBinCount);
    analyser.getByteTimeDomainData(array);

}
function getAverageVolume(array){
  var values = 0;
  var average;
  var length = array.length;
  for (var i = 0; i < length; i++) {
      values += array[i];
  }
  average = values / length;
  return average;
}
function updateCubes(){
  // get the average for the first channel
  var array =  new Uint8Array(analyser.frequencyBinCount);
  analyser.getByteFrequencyData(array);
  var average = getAverageVolume(array);

  // get the average for the second channel
  var array2 =  new Uint8Array(analyser2.frequencyBinCount);
  analyser2.getByteFrequencyData(array2);
  var average2 = getAverageVolume(array2);

  // clear the current state
  if (scene.getObjectByName('cube')) {
      var cube = scene.getObjectByName('cube');
      var cube2 = scene.getObjectByName('cube2');
      cube.scale.y=average/20;
      cube2.scale.y=average2/20;

  }

}
function handleResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
}

function loadSound(url){
  var request =new XMLHttpRequest();
  request.open('GET',url,true);
 request.responseType = 'arraybuffer';
  request.onload=function(){
    console.log(request.response)
    context.decodeAudioData(request.response,function(buf){
      playSound(buf);
    },onError);
  }
  request.send();
}
function playSound(buf){
  sourceNode.buffer=buf;
  sourceNode.start(0);
}
function onError(){
  console.log('Error occure');
}

function setupSound() {
    if (! window.AudioContext) {
        if (! window.webkitAudioContext) {
            alert('no audiocontext found');
        }
        window.AudioContext = window.webkitAudioContext;
    }
    context = new AudioContext();

    // setup a analyzer
    analyser = context.createAnalyser();
    analyser.smoothingTimeConstant = 0.4;
    analyser.fftSize = 1024;

    analyser2 = context.createAnalyser();
    analyser2.smoothingTimeConstant = 0.4;
    analyser2.fftSize = 1024;

    // create a buffer source node
    sourceNode = context.createBufferSource();
    var splitter = context.createChannelSplitter();

    // connect the source to the analyser and the splitter
    sourceNode.connect(splitter);

    // connect one of the outputs from the splitter to
    // the analyser
    splitter.connect(analyser,0);
    splitter.connect(analyser2,1);

    // and connect to destination
    sourceNode.connect(context.destination);

    // context = new AudioContext();
}

window.onload = init;
window.addEventListener('resize', handleResize, false);

</script>

  </body>
</html>


text:
<!DOCTYPE html>

	<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
	<meta name="robots" content="noindex,follow">

	<link href="../src/skin-win8/ui.fancytree.css" rel="stylesheet" type="text/css">

	<title>Fancytree - Example Browser Nav</title>

Documentation

Project home

Documentation

API reference

 Examples

Welcome

Default options

Complex demo

Bootstrap

Initialization

Event handling

Option configurator

URL navigation and <iframe>

Programming API

Checkbox & select

Theming

Embed in forms

Extensions

Child counter

Column view

Context menu

Drag'n'drop

Filter

Glyph fonts

Inline edit

Persist

Table

ThemeRoller

Wide

Tweaks

Accordion

ui-contextmenu

Context menu (ABS), Copy/paste

font-awesome

Lazy load errors handling

RTL

Embed in forms

Large nodes

Drag multiple nodes

Smart scrolling

Keyboard nav.

Test

Core unit tests

Suite

Drag'n'drop

Benchmarks

DTD

No DTD

HTML4 transitional

HTML4 strict

HTML5

XHTML transitional

XHTML strict

3rd party

Extensions

contextMenu

hotkeys

Samples

ui-contextmenu


text:
% !TeX spellcheck = pt

%% ************************************************
%% Universidade Nova de Lisboa
%% NOVA Information Management School
%% Computação em Estatística e Gestão de Informação
%% Júlio Caineta, 2015
%% ************************************************
\documentclass[addpoints]{exam}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage[portuguese]{babel}
\usepackage[hidelinks,pdfusetitle]{hyperref}
\author{Júlio Caineta}
\title{CEGI 2014/2015 - Exame 2ª Época - Versão A}
\usepackage{lastpage}
\usepackage{minted}
\usepackage{gensymb}
\usepackage{wrapfig}
\usepackage{tabulary}
\usepackage{graphicx}
\usepackage{xfrac}
\usepackage{multirow}
\usepackage[phantomtext]{dashundergaps}
%\usepackage{color}
%\usepackage{draftwatermark}
%\SetWatermarkText{RASCUNHO}
%\SetWatermarkScale{3}
%\SetWatermarkLightness{0.7}
\cfoot{Página \thepage\ de \pageref{LastPage}}
\renewcommand{\solutiontitle}{\noindent\textbf{Solução:}\par\noindent}
\pointpoints{valor}{valores}
\pointsinrightmargin
\bracketedpoints
\marginpointname{ val.}
\renewcommand*\half{.5}
\hqword{Pergunta}
\hpgword{Página}
\hpword{Cotação}
\hsword{Cotação obtida}
\htword{Total}
\newminted{r}{autogobble}
\newmintinline{r}{}

\printanswers
%\shadedsolutions

%\titlegraphic{}

\begin{document}

\noindent\begin{minipage}{0.2\textwidth}% adapt widths of minipages to your needs
	\includegraphics[width=2cm]{logo.png}
\end{minipage}
\hfill
\begin{minipage}{0.8\textwidth}
	\begin{center}
		\textsc {\small NOVA IMS -- Universidade Nova de Lisboa} \\
		\textsc {Computação em Estatística e Gestão de Informação -- 2º Semestre 2014/15}
	\end{center}
\end{minipage}

\begin{center}
%	\vspace{5mm} \\
	{\large Exame 2ª Época -- Versão A -- 20/07/2015}
\end{center}

\vspace{5mm}
\makebox[\textwidth]{Curso: \underline{\phantom{XXXXX}} Número: \underline{\phantom{XXXXXXXX}} Nome:\enspace\hrulefill}
\vspace{5mm}

{{\large\textbf{Leia, por favor, com atenção:}}
\begin{enumerate}
	\item Este enunciado corresponde à primeira parte do exame (\textbf{R}). O enunciado da segunda parte (SAS) será entregue após o aluno entregar a resolução da primeira parte.
	\item Cada parte está cotada para 10 valores e tem a nota mínima de 4 valores.
	\item Esta parte deverá ser realizado com acesso a um computador com o programa \textbf{R} instalado. Só poderá aceder ao programa \textbf{R} e ao sistema de ajuda do mesmo.
	\item Os dados necessários para resolver os problemas já se encontram disponíveis na sua instalação do \textbf{R}.
	\item É proibido o uso de qualquer material de apoio (livros, apontamentos, telemóvel), assim como a troca de qualquer informação com os colegas.
	\item Deverá escrever o seu nome, número e curso no cabeçalho desta folha.
	\item As respostas às questões deverão ser dadas, exclusivamente, na folha do enunciado, no espaço reservado para tal. Estas respostas deverão ser código em \textbf{R}.
	\item O não cumprimento de alguma das regras conduzirá à anulação do exame.
	\item A duração do exame, considerando ambas as partes, é de \textbf{2 horas}.
\end{enumerate}

\vspace{10mm}

\begin{questions}
	\question O vector \rinline{precip} contém a precipitação (chuva) média anual, em polegadas (in), de 70 cidades norte americanas.

	\begin{parts}
		\part[1] Encontre as cidades, e respectivos valores de precipitação, com os 5\% valores de precipitação média anual mais elevados.%~\makeemptybox{1in}

			\begin{solution}
				\begin{rcode}
					> subset(precip, precip >= quantile(precip, 0.95))
					Mobile       Miami New Orleans    San Juan
					67.0        59.8        56.8        59.2
				\end{rcode}
			\end{solution}

		\part[0\half] Em Portugal, a unidade de medida mais usada para precipitação é o milímetro. Sabendo que 1~in~=~25.4~mm, defina uma função que recebe um vector com valores de precipitação em in, e devolve um vector com valores de precipitação em mm. Converta os valores do vector  \rinline{precip} para mm.%~\makeemptybox{1.3in}

		\begin{solution}
			\begin{rcode}
				in2cm = function(precip) {
				  precip * 25.4
				}
				in2cm(precip)
			\end{rcode}
		\end{solution}

		\part[1] Utilize a função \rinline{strsplit} para separar os nomes dos elementos do vector \rinline{precip} por palavras (espaços existentes nos nomes). Guarde o resultado numa nova variável denominada \rinline{cidades}.%~\makeemptybox{1.3in}

		\begin{solution}
			\begin{rcode}
				cidades = strsplit(names(precip), " ")
			\end{rcode}
		\end{solution}

		\part[1\half] Liste os nomes das cidades, existentes no vector \rinline{precip}, cujos nomes são compostos por mais de duas palavras. \textbf{Sugestão:} utilize a lista cidades, criada na alínea anterior.%~\makeemptybox{1.4in}

		\begin{solution}
			\begin{rcode}
				> names(precip)[sapply(cidades, function(x) length(x) > 2)]
				[1] "Sault Ste. Marie" "Salt Lake City"
			\end{rcode}
		\end{solution}

	\end{parts}

%	\question[0\half] Considere o seguinte conteúdo de um ficheiro de nome \textit{notas.dat}:
%
%	\begin{minted}{text}
%		Nome-AM2-CEGI-DP1-Est1-ISC-Mrkt
%		Geraldo-12,1-14,4-15,2-11,7-10,0-15,5
%		Justino-8,2-6,6-12,3-9,9-13,1-16,7
%		Felisberta-13,3-13,3-13,3-13,3-13,3-13,3
%		Enzo-18,0-19,0-20,0-17,0-19,0-15,0
%		Toninha-10,0-11,1-12,2-13,3-14,4-15,5
%	\end{minted}
%
%	Escreva o código necessário para guardar o conteúdo deste ficheiro num \rinline{data.frame} com 5 linhas e 7 colunas.%~\makeemptybox{1in}
%
%	\begin{solution}
%		\begin{rcode}
%			notas = read.table(notas.dat, header=T, sep="-", dec=",")
%		\end{rcode}
%	\end{solution}

	\question O objecto \rinline{Orange} tem 35 linhas e 3 colunas com registos do crescimento de laranjeiras. As variáveis disponibilizadas são:

	\begin{description}
		\item[Tree] \rinline{factor} ordenado que indica em que árvore foi efectuada a medição.
		\item[age] Idade da árvore, dada em dias.
		\item[circumference] Perímetro do tronco da árvore, em mm.
	\end{description}

	\begin{parts}
		\part[1] Calcule o perímetro médio das laranjeiras, para cada idade registada. Não utilize uma estrutura iterativa.%~\makeemptybox{1.3in}

			\begin{solution}
				\begin{rcode}
					by(Orange$circumference, Orange$age, mean)
				\end{rcode}
				ou
				\begin{rcode}
					aggregate(Orange, list(Orange$age), mean)
				\end{rcode}
			\end{solution}

\pagebreak

		\part[2] Assuma que a Taxa de Crescimento ($t_c$)  de uma laranjeira é dada pela \autoref{tc}.

		\begin{equation}
			\label{tc}
			t_c = \frac{\text{circumference}}{\text{age}}
		\end{equation}

		Sem recorrer a um ciclo (explicitamente), calcule a $t_c$ em cada registo. Qual é a árvore com maior Taxa de Crescimento média?%~\makeemptybox{1.3in}

		\begin{solution}
			\begin{rcode}
				orange_tc = transform(Orange, tc = circumference / age)
				> which.max(by(orange_tc$tc, orange_tc$Tree, mean))
				4
				5
			\end{rcode}
			A árvore com maior Taxa de Crescimento é a 4.
		\end{solution}
	\end{parts}

	\question O \rinline{data.frame LifeCycleSavings} contém informações sobre as poupanças das populações, em 50 países, na década de 1960. Considere apenas as colunas \rinline{pop15} e \rinline{pop75}, relativas às percentagens da população abaixo de 15 e acima de 75 anos, respectivamente.

	\begin{parts}
		\part[1] O rácio entre \rinline{pop75} e \rinline{pop15} ($t_e$) é um possível indicador de que a população de um país está envelhecida (\autoref{te}). Crie uma nova tabela, contendo apenas os países em que $t_e >\overline{t_e} + \sigma(t_e)$.

		\begin{equation}
			\label{te}
			t_e = \frac{\text{pop75}}{\text{pop15}}
		\end{equation}%~\makeemptybox{1.3in}

		\begin{solution}
			\begin{rcode}
				> te = LifeCycleSavings$pop75 / LifeCycleSavings$pop15
				> subset(LifeCycleSavings, te > mean(te) + sd(te))
				sr pop15 pop75     dpi ddpi
				Austria        12.07 23.32  4.41 1507.99 3.93
				Belgium        13.17 23.80  4.43 2108.47 3.82
				Denmark        16.85 24.42  3.93 2496.53 3.99
				France         12.64 25.06  4.70 2213.82 4.52
				Germany        12.55 23.31  3.35 2457.12 3.44
				Italy          14.28 24.52  3.48 1390.00 3.54
				Luxembourg     10.35 21.80  3.73 2449.39 1.57
				Norway         10.25 25.95  3.67 2231.03 3.62
				Sweden          6.86 21.44  4.54 3299.49 3.01
				Switzerland    14.13 23.49  3.73 2630.96 2.70
				United Kingdom  7.81 23.27  4.46 1813.93 2.01
			\end{rcode}
		\end{solution}

		\part[0\half] Construa um gráfico que permita identificar o mesmo conjunto de países (não é necessário desenhar o gráfico na folha).%~\makeemptybox{1.3in}

		\begin{solution}
			\begin{rcode}
				barplot(te)
				abline(h = mean(te) + sd(te), las = 2, space = .5))
			\end{rcode}
			Gráfico de barras com uma linha horizontal que permite identificar a condição requerida. Os dois últimos argumentos são opcionais.
		\end{solution}
	\end{parts}

\pagebreak

	\question Para resolver os próximos exercícios, considere o seu número mecanográfico (número de aluno).

	\begin{parts}
		\part[1] Crie um conjunto de 10 números aleatórios, \rinline{x}, a partir da seguinte distribuição:

		\begin{equation*}
			Norm(\mu = xxxx, \sigma= yyy)
		\end{equation*}

		em que $xxxx$ são os primeiros quatro dígitos do seu número mecanográfico, e $yyy$ são os restantes três dígitos.%~\makeemptybox{1.4in}

		\begin{solution}
			\begin{rcode}
				x = rnorm(n = 10, mean = 1999, sd = 123)
			\end{rcode}
		\end{solution}

		\part[0\half] A partir do conjunto criado na alínea anterior, crie um novo conjunto \rinline{y}, com igual número de elementos, através da seguinte linha de código:

		\begin{rcode}
			y = sample(x, 10, rep=T)
		\end{rcode}

		Verifique se as médias de \rinline{x} e \rinline{y} são iguais e explique porquê.

		\textbf{Nota:} se não resolveu a alínea anterior, considere \rinline{x = seq(1234, 4321, length=10)}.%~\makeemptybox{1.4in}

		\begin{solution}
			\begin{rcode}
				> y=sample(x, 10, rep=T)
				> mean(x)
				[1] 2007.595
				> mean(y)
				[1] 1995.478
			\end{rcode}

			As médias são diferentes porque, apesar dos dois vectores terem o mesmo número de elementos, \rinline{y} foi criado a partir de uma amostragem com reposição, sendo, então, mais provável existirem elementos repetidos.
		\end{solution}

	\end{parts}

\end{questions}

\vspace{5mm}
%\centerline
	\begin{center}
		\gradetable[h][questions]
	\end{center}

\end{document}


text:
package rest

import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.server.directives.Credentials
import rest.OAuth2RouteProvider.TokenResponse
import spray.json.DefaultJsonProtocol

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.{Failure, Success}
import scalaoauth2.provider._

trait OAuth2RouteProvider[U] extends Directives with DefaultJsonProtocol{
  import OAuth2RouteProvider.tokenResponseFormat
  import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._

  val oauth2DataHandler : DataHandler[U]

  val tokenEndpoint = new TokenEndpoint {
    override val handlers = Map(
      OAuthGrantType.CLIENT_CREDENTIALS -> new ClientCredentials,
      OAuthGrantType.PASSWORD -> new Password,
      OAuthGrantType.AUTHORIZATION_CODE -> new AuthorizationCode,
      OAuthGrantType.REFRESH_TOKEN -> new RefreshToken
    )
  }

  def grantResultToTokenResponse(grantResult : GrantHandlerResult[U]) : TokenResponse =
    TokenResponse(grantResult.tokenType, grantResult.accessToken, grantResult.expiresIn.getOrElse(1L), grantResult.refreshToken.getOrElse(""))

  def oauth2Authenticator(credentials: Credentials): Future[Option[AuthInfo[U]]] =
    credentials match {
      case p@Credentials.Provided(token) =>
        oauth2DataHandler.findAccessToken(token).flatMap {
          case Some(token) => oauth2DataHandler.findAuthInfoByAccessToken(token)
          case None => Future.successful(None)
        }
      case _ => Future.successful(None)
    }

  def accessTokenRoute = pathPrefix("oauth") {
    path("access_token") {
      post {
        formFieldMap { fields =>
          onComplete(tokenEndpoint.handleRequest(new AuthorizationRequest(Map(), fields.map(m => m._1 -> Seq(m._2))), oauth2DataHandler)) {
            case Success(maybeGrantResponse) =>
              maybeGrantResponse.fold(oauthError => complete(Unauthorized),
                grantResult => complete(tokenResponseFormat.write(grantResultToTokenResponse(grantResult)))
              )
            case Failure(ex) => complete(InternalServerError, s"An error occurred: ${ex.getMessage}")
          }
        }
      }
    }
  }

}

object OAuth2RouteProvider extends DefaultJsonProtocol{
  case class TokenResponse(token_type : String, access_token : String, expires_in : Long, refresh_token : String)
  implicit val tokenResponseFormat = jsonFormat4(TokenResponse)
}


text:
using System;
using System.Diagnostics;
using System.Runtime.Serialization;

namespace STAR.Originations.MegaRunbook.Contracts
{
    [DataContract(Namespace = "http://services.nationstarmtg.net/originations/mrc/2016/01")]
    [DebuggerDisplay("{DebuggerDisplay}")]
    public class Hero
    {
        [DataMember] public int Id { get; set; }
        [DataMember] public string Name { get; set; }
        [DataMember] public string Power { get; set; }
        [DataMember] public string AlterEgo { get; set; }
        [DataMember] public string RayType { get; set; }
        [DataMember] public string Notes { get; set; }

        [DataMember] public bool IsFavorite { get; set; }

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        private string DebuggerDisplay => String.Format("Name: {0}", this.Name);
    }
}


text:
package io.druid.benchmark;

import io.druid.collections.bitmap.BitSetBitmapFactory;
import io.druid.collections.bitmap.BitmapFactory;
import io.druid.collections.bitmap.ConciseBitmapFactory;
import io.druid.collections.bitmap.ImmutableBitmap;
import io.druid.collections.bitmap.MutableBitmap;
import io.druid.collections.bitmap.RoaringBitmapFactory;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.roaringbitmap.IntIterator;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * Benchmarks of bitmap iteration and iteration + something (cumulative cost), the latter is useful for comparing total
 * "usage cost" of different {@link io.druid.segment.data.BitmapSerdeFactory}.
 *
 * @see #iter(IterState)
 * @see #constructAndIter(ConstructAndIterState)
 * @see #intersectionAndIter(BitmapsForIntersection)
 * @see #unionAndIter(BitmapsForUnion)
 */
@State(Scope.Benchmark)
@Fork(1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
public class BitmapIterationBenchmark
{
  @Param({"bitset", "concise", "roaring"})
  public String bitmapAlgo;

  /**
   * Fraction of set bits in the bitmaps to iterate. For {@link #intersectionAndIter} and
   * {@link #unionAndIter}, this is the fraction of set bits in the final result of intersection or union.
   */
  @Param({"0.0", "0.001", "0.1", "0.5", "0.99", "1.0"})
  public double prob;

  /**
   * The size of all bitmaps, i. e. the number of rows in a segment for the most bitmap use cases.
   */
  @Param({"1000000"})
  public int size;

  private BitmapFactory makeFactory()
  {
    switch (bitmapAlgo) {
      case "bitset":
        return new BitSetBitmapFactory();
      case "concise":
        return new ConciseBitmapFactory();
      case "roaring":
        return new RoaringBitmapFactory();
      default:
        throw new IllegalStateException();
    }
  }

  private BitmapFactory factory;

  @Setup
  public void setup()
  {
    factory = makeFactory();
  }

  private ImmutableBitmap makeBitmap(double prob)
  {
    MutableBitmap mutableBitmap = factory.makeEmptyMutableBitmap();
    Random random = ThreadLocalRandom.current();
    for (int bit = 0; bit < size; bit++) {
      if (random.nextDouble() < prob) {
        mutableBitmap.add(bit);
      }
    }
    return factory.makeImmutableBitmap(mutableBitmap);
  }

  @State(Scope.Benchmark)
  public static class IterState
  {
    private ImmutableBitmap bitmap;

    @Setup
    public void setup(BitmapIterationBenchmark state)
    {
      bitmap = state.makeBitmap(state.prob);
    }
  }

  /**
   * General benchmark of bitmap iteration, this is a part of {@link io.druid.segment.IndexMerger#merge} and
   * query processing on both realtime and historical nodes.
   */
  @Benchmark
  public int iter(IterState state)
  {
    ImmutableBitmap bitmap = state.bitmap;
    return iter(bitmap);
  }

  private static int iter(ImmutableBitmap bitmap)
  {
    int consume = 0;
    for (IntIterator it = bitmap.iterator(); it.hasNext();) {
      consume ^= it.next();
    }
    return consume;
  }

  @State(Scope.Benchmark)
  public static class ConstructAndIterState
  {
    private int dataSize;
    private int[] data;

    @Setup
    public void setup(BitmapIterationBenchmark state)
    {
      data = new int[(int) (state.size * state.prob) * 2];
      dataSize = 0;
      Random random = ThreadLocalRandom.current();
      for (int bit = 0; bit < state.size; bit++) {
        if (random.nextDouble() < state.prob) {
          data[dataSize] = bit;
          dataSize++;
        }
      }
    }
  }

  /**
   * Benchmark of cumulative cost of construction of an immutable bitmap and then iterating over it. This is a pattern
   * from realtime nodes, see {@link io.druid.segment.StringDimensionIndexer#fillBitmapsFromUnsortedEncodedKeyComponent}.
   * However this benchmark is yet approximate and to be improved to better reflect actual workloads of realtime nodes.
   */
  @Benchmark
  public int constructAndIter(ConstructAndIterState state)
  {
    int dataSize = state.dataSize;
    int[] data = state.data;
    MutableBitmap mutableBitmap = factory.makeEmptyMutableBitmap();
    for (int i = 0; i < dataSize; i++) {
      mutableBitmap.add(data[i]);
    }
    ImmutableBitmap bitmap = factory.makeImmutableBitmap(mutableBitmap);
    return iter(bitmap);
  }

  @State(Scope.Benchmark)
  public static class BitmapsForIntersection
  {
    /**
     * Number of bitmaps to intersect.
     */
    @Param({"2", "10", "100"})
    public int n;

    private ImmutableBitmap[] bitmaps;

    @Setup
    public void setup(BitmapIterationBenchmark state)
    {
      // prob of intersection = product (probs of intersected bitmaps), prob = intersectedBitmapProb ^ n
      double intersectedBitmapProb = Math.pow(state.prob, 1.0 / n);
      bitmaps = new ImmutableBitmap[n];
      for (int i = 0; i < n; i++) {
        bitmaps[i] = state.makeBitmap(intersectedBitmapProb);
      }
    }
  }

  /**
   * Benchmark of cumulative cost of bitmap intersection with subsequent iteration over the result. This is a pattern
   * from query processing of historical nodes, when {@link io.druid.segment.filter.AndFilter} is used.
   */
  @Benchmark
  public int intersectionAndIter(BitmapsForIntersection state)
  {
    ImmutableBitmap intersection = factory.intersection(Arrays.asList(state.bitmaps));
    return iter(intersection);
  }

  @State(Scope.Benchmark)
  public static class BitmapsForUnion
  {
    /**
     * Number of bitmaps to union.
     */
    @Param({"2", "10", "100"})
    public int n;

    private ImmutableBitmap[] bitmaps;

    @Setup
    public void setup(BitmapIterationBenchmark state)
    {
      double prob = Math.pow(state.prob, 1.0 / n);
      MutableBitmap[] mutableBitmaps = new MutableBitmap[n];
      for (int i = 0; i < n; i++) {
        mutableBitmaps[i] = state.factory.makeEmptyMutableBitmap();
      }
      Random r = ThreadLocalRandom.current();
      for (int i = 0; i < state.size; i++) {
        // unions are usually search/filter/select of multiple values of one dimension, so making bitmaps disjoint will
        // make benchmarks closer to actual workloads
        MutableBitmap bitmap = mutableBitmaps[r.nextInt(n)];
        // In one selected bitmap, set the bit with probability=prob, to have the same fraction of set bit in the union
        if (r.nextDouble() < prob) {
          bitmap.add(i);
        }
      }
      bitmaps = new ImmutableBitmap[n];
      for (int i = 0; i < n; i++) {
        bitmaps[i] = state.factory.makeImmutableBitmap(mutableBitmaps[i]);
      }
    }
  }

  /**
   * Benchmark of cumulative cost of bitmap union with subsequent iteration over the result. This is a pattern from
   * query processing on historical nodes, when filters like {@link io.druid.segment.filter.DimensionPredicateFilter},
   * {@link io.druid.query.filter.RegexDimFilter}, {@link io.druid.query.filter.SearchQueryDimFilter} and similar are
   * used.
   */
  @Benchmark
  public int unionAndIter(BitmapsForUnion state)
  {
    ImmutableBitmap intersection = factory.union(Arrays.asList(state.bitmaps));
    return iter(intersection);
  }

  /**
   * This main() is for debugging from the IDE.
   */
  public static void main(String[] args)
  {
    BitmapIterationBenchmark state = new BitmapIterationBenchmark();
    state.bitmapAlgo = "concise";
    state.prob = 0.001;
    state.size = 1000000;
    state.setup();

    BitmapsForIntersection state2 = new BitmapsForIntersection();
    state2.setup(state);
    state.intersectionAndIter(state2);
  }
}


text:
using System;
using System.Runtime.InteropServices;

namespace MimeKit.MacInterop {
	class CFData : CFObject
	{
		byte[] cached;

		[DllImport (CoreFoundationLibrary)]
		extern static int CFDataGetLength (IntPtr handle);

		[DllImport (CoreFoundationLibrary)]
		extern static void CFDataGetBytes (IntPtr handle, CFRange range, IntPtr buffer);

		[DllImport (CoreFoundationLibrary)]
		extern static IntPtr CFDataCreate (IntPtr allocator, byte[] buffer, int length);

		static byte[] CFDataGetBytes (IntPtr handle)
		{
			if (handle == IntPtr.Zero)
				return null;

			int length = CFDataGetLength (handle);
			if (length < 1)
				return null;

			var buffer = new byte[length];
			unsafe {
				fixed (byte *bufptr = buffer) {
					CFDataGetBytes (handle, new CFRange (0, length), (IntPtr) bufptr);
				}
			}

			return buffer;
		}

		public CFData (IntPtr handle, bool owns) : base (handle, owns)
		{
		}

		public CFData (IntPtr handle) : base (handle, false)
		{
		}

		public CFData (byte[] buffer)
		{
			Handle = CFDataCreate (IntPtr.Zero, buffer, buffer.Length);
			cached = buffer;
		}

		public byte[] GetBuffer ()
		{
			if (cached == null)
				cached = CFDataGetBytes (Handle);

			return cached;
		}
	}
}


text:
var Counter = artifacts.require("./Counter.sol");

contract('Counter', function(accounts) {
  it("should have initial value set to zero", function() {
    return Counter.deployed().then(function(instance) {
      return instance.value.call(accounts[0]);
    }).then(function(value) {
      assert.equal(value.valueOf(), 0, "Initial counter value should be zero");
    });
  });
  it("should have value 1,after a increase", function() {
    return Counter.deployed().then(function(instance) {
      return instance.increase();
    })
  });

});


text:
<?xml version="1.0" ?>
<componentPackage>

    <component id="Controller" class="com.braindumprelief.framework.controller.Controller"/>

    <component id="Presenter" class="com.braindumprelief.framework.mvp.presenter.Presenter"/>
    <component id="ViewPresenter" class="com.braindumprelief.framework.mvp.presenter.ViewPresenter"/>
    <component id="SkinnableViewPresenter" class="com.braindumprelief.framework.mvp.presenter.SkinnableViewPresenter"/>

</componentPackage>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Euler.Lib
{
    public class LargestProductFinder
    {
        private int _range;
        public LargestProductFinder(int range)
        {
            this._range = range;
        }

        public int GetLargestProduct(string series)
        {
            var myseries = this.ConvertToArray(series);
            int found = 0;
            for (int i = 0; i < myseries.Length; i++)
            {
                var product = myseries.Skip(i)
                                    .Take(this._range)
                                    .Aggregate(1, (a,c) => a *= c );

                if ( product > found)
                {
                    found = product;
                }
            }
            return found;
        }

        private int[] ConvertToArray(string series)
        {
            return series.Select(c => (int)Char.GetNumericValue(c)).ToArray();
        }
    }
}


text:
wsgi Package
============

:mod:`middleware` Module
------------------------

.. automodule:: ws4py.server.wsgi.middleware
    :members:
    :undoc-members:
    :show-inheritance:


text:
<?xml version="1.0" encoding="utf-8"?>

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <com.gh4a.widget.IntegerListPreference
        android:defaultValue="1"
        android:entries="@array/theme_items"
        android:entryValues="@array/theme_values"
        android:key="theme"
        android:summary="%s"
        android:title="@string/theme" />

    <ListPreference
        android:defaultValue="newsfeed"
        android:entries="@array/start_page_items"
        android:entryValues="@array/start_page_values"
        android:key="start_page"
        android:summary="%s"
        android:title="@string/start_page" />

    <com.gh4a.widget.IntegerListPreference
        android:defaultValue="2"
        android:entries="@array/text_size_items"
        android:entryValues="@array/text_size_values"
        android:key="webview_initial_zoom"
        android:summary="%s"
        android:title="@string/menu_text_size" />

    <com.gh4a.widget.IntegerListPreference
        android:defaultValue="1"
        android:entries="@array/load_gif_mode_items"
        android:entryValues="@array/load_gif_mode_values"
        android:key="http_gif_load_mode"
        android:summary="%s"
        android:title="@string/menu_gif_load_mode" />

    <SwitchPreference
        android:defaultValue="false"
        android:key="notifications"
        android:title="@string/notifications" />

    <com.gh4a.widget.IntegerListPreference
        android:defaultValue="15"
        android:dependency="notifications"
        android:entries="@array/notification_interval_items"
        android:entryValues="@array/notification_interval_values"
        android:key="notification_interval"
        android:summary="%s"
        android:title="@string/notification_interval" />

    <Preference
        android:key="about"
        android:title="@string/about" />

    <Preference
        android:key="open_source_components"
        android:title="@string/open_source_components" />

</PreferenceScreen>


text:
/**
 *
 */
package eu.codesketch.ws.commons.message.account;

import eu.codesketch.ws.commons.message.Message;

/**
 * @author quirino
 *
 */
public class CreateAccountRequestMessage implements Message {

    private static final long serialVersionUID = -3144415974297929088L;

}


text:
package com.opengamma.strata.math.impl.statistics.distribution;

import java.util.function.Function;

import com.google.common.math.DoubleMath;
import com.opengamma.strata.collect.ArgChecker;
import com.opengamma.strata.math.impl.cern.RandomEngine;

/**
 * StudentT calculator.
 */
// CSOFF: JavadocMethod
public class StudentTOneTailedCriticalValueCalculator implements Function<Double, Double> {

  private final ProbabilityDistribution<Double> _dist;

  public StudentTOneTailedCriticalValueCalculator(double nu) {
    ArgChecker.notNegative(nu, "nu");
    _dist = new StudentTDistribution(nu);
  }

  public StudentTOneTailedCriticalValueCalculator(double nu, RandomEngine engine) {
    ArgChecker.notNegative(nu, "nu");
    ArgChecker.notNull(engine, "engine");
    _dist = new StudentTDistribution(nu, engine);
  }

  @Override
  public Double apply(Double x) {
    ArgChecker.notNull(x, "x");
    ArgChecker.notNegative(x, "x");
    if (DoubleMath.fuzzyEquals(x, 0.5, 1e-14)) {
      return 0.5;
    }
    return _dist.getInverseCDF(x);
  }

}


text:
{% extends "base.html" %}

{% block head_title %}Antibody Detail - {{ object }}{% endblock %}
{% block title %}Antibody Detail - {{ object }}{% endblock %}
{% block content %}

 <tdata>

Antibody	{{object.name}}

Protein	{% for protein in object.protein.all %}{{ protein }} {% endfor %}

Size	{{object.protein_size}}

Dilution	{{ object.dilution }}

Source Species	{{object.source_species}}

Location	{{object.location}}

  {% if object.vendor %}
Vendor	{{ object.vendor }}
{% endif %}
  {% if object.catalog %}
Catalog Number	{{ object.catalog }}
{% endif %}
  {% if object.source %}
Source	{{ object.source }}
{% endif %}
  {% if object.notes %}
Notes	{{ object.notes }}
{% endif %}
  </tdata>

{% if perms.reagents.change_antibody %}
To update antibody details click
{% endif %}

{% with object.experiment_set.all as experiment_list %}
{% include "experiment_list_table.html" %}
{% endwith %}

{% include "comment.html" %}
{% endblock %}


text:
package com.force.five.app.domain;

import com.force.five.app.service.util.ForceConstants;

import javax.persistence.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Objects;

/**
 * A PaySheets.
 */
@Entity
@Table(name = "pay_sheets")
public class PaySheets implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "month")
    private String month;

    @Column(name = "year")
    private String year;

    @Column(name = "regular_days")
    private Integer regularDays;

    @Column(name = "days_worked")
    private Integer daysWorked;

    @Column(name = "weekly_off")
    private Integer weeklyOff;

    @Column(name = "comp_off")
    private Integer compOff;

    @Column(name = "holidays")
    private Integer holidays;

    @Column(name = "overtime")
    private Integer overtime;

    @ManyToOne
    @JoinColumn(name = "assignments_id")
    private Assignments assignments;

    public Long getId() {
        return id;
    }

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

    public String getMonth() {
        return month;
    }

    public void setMonth(String month) {
        this.month = month;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public Integer getRegularDays() {
        return regularDays;
    }

    public void setRegularDays(Integer regularDays) {
        this.regularDays = regularDays;
    }

    public Integer getDaysWorked() {
        return (daysWorked != null ? daysWorked : 0);
    }

    public void setDaysWorked(Integer daysWorked) {
        this.daysWorked = daysWorked;
    }

    public Integer getWeeklyOff() {
        return (weeklyOff != null ? weeklyOff : 0);
    }

    public void setWeeklyOff(Integer weeklyOff) {
        this.weeklyOff = weeklyOff;
    }

    public Integer getCompOff() {
        return (compOff != null ? compOff : 0);
    }

    public void setCompOff(Integer compOff) {
        this.compOff = compOff;
    }

    public Integer getHolidays() {
        return (holidays != null ? holidays : 0);
    }

    public void setHolidays(Integer holidays) {
        this.holidays = holidays;
    }

    public Integer getOvertime() {
        return (overtime != null ? overtime : 0);
    }

    public void setOvertime(Integer overtime) {
        this.overtime = overtime;
    }

    public Assignments getAssignments() {
        return assignments;
    }

    public void setAssignments(Assignments assignments) {
        this.assignments = assignments;
    }

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

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

    @Override
    public String toString() {
        return "PaySheets{" +
            "id=" + id +
            ", month='" + month + "'" +
            ", year='" + year + "'" +
            ", regularDays='" + regularDays + "'" +
            ", daysWorked='" + daysWorked + "'" +
            ", weeklyOff='" + weeklyOff + "'" +
            ", compOff='" + compOff + "'" +
            ", holidays='" + holidays + "'" +
            ", overtime='" + overtime + "'" +
            '}';
    }

    //Calculated columns
    public BigDecimal getTotalWages() {
        BigDecimal basic = this.getAssignments().getEmployee().getBasic();
        BigDecimal allowance = this.getAssignments().getEmployee().getAllowances();
        return basic.add(allowance);

    }

    public BigDecimal getEarnedBasic() {
        BigDecimal basic = this.getAssignments().getEmployee().getBasic();
        return basic.divide(ForceConstants.TOTAL_DAYS, 2, RoundingMode.HALF_EVEN).multiply(new BigDecimal(this.regularDays)).setScale(2, RoundingMode.HALF_EVEN);
    }

    public BigDecimal getOTWages() {
        return getTotalWages().divide(ForceConstants.TOTAL_DAYS, 2, RoundingMode.HALF_EVEN).multiply(new BigDecimal(this.overtime)).setScale(2, RoundingMode.HALF_EVEN);
    }

    public BigDecimal getEarnedAllowances() {
        return getAssignments().getEmployee().getAllowances().divide(ForceConstants.TOTAL_DAYS, 2, RoundingMode.HALF_EVEN).multiply(new BigDecimal(this.regularDays)).setScale(2, RoundingMode.HALF_EVEN);
    }

    public BigDecimal getGrossWages() {
        return getEarnedBasic().add(getOTWages()).add(getEarnedAllowances());
    }

    public BigDecimal getPF() {
        return getEarnedBasic().multiply(ForceConstants.PF_CAL).setScale(2, RoundingMode.HALF_EVEN);
    }

    public BigDecimal getESIC() {
        return getEarnedBasic().multiply(ForceConstants.ESIC).setScale(2, RoundingMode.HALF_EVEN);
    }

    public BigDecimal getCost() {
        return this.getAssignments().getCost();
    }

    public BigDecimal getCostPerDay() {
        BigDecimal cost = getCost();
        Calendar c = Calendar.getInstance();

        int monthMaxDays = c.getActualMaximum(Calendar.DAY_OF_MONTH);
        BigDecimal monthMaxDaysBigDecimal = new BigDecimal(monthMaxDays);

        //costperday = cost/No of days in a month
        BigDecimal costPerDay = cost.divide(monthMaxDaysBigDecimal, 2, RoundingMode.HALF_EVEN);
        return costPerDay;
    }

    public BigDecimal getTotal() {

        BigDecimal total = new BigDecimal(getDaysWorked() + getWeeklyOff() + getCompOff() + getOvertime() + getHolidays());
        return total;
    }

    //GrandTotal = PerDayCost * Total
    public BigDecimal getGrandTotal() {
        return getCostPerDay().multiply(getTotal()).setScale(2, BigDecimal.ROUND_HALF_EVEN);
    }

}