text:
package io.cattle.platform.async.retry.impl;

import com.google.common.util.concurrent.SettableFuture;
import io.cattle.platform.async.retry.CancelRetryException;
import io.cattle.platform.async.retry.Retry;
import io.cattle.platform.async.retry.RetryTimeoutService;
import io.cattle.platform.async.utils.TimeoutException;
import org.apache.cloudstack.managed.context.NoExceptionRunnable;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class RetryTimeoutServiceImpl implements RetryTimeoutService {

    ExecutorService executorService;
    ScheduledExecutorService scheduledExecutorService;

    public RetryTimeoutServiceImpl(ExecutorService executorService, ScheduledExecutorService scheduledExecutorService) {
        this.executorService = executorService;
        this.scheduledExecutorService = scheduledExecutorService;
    }

    @Override
    public Object submit(Retry retry) {
        return queue(retry);
    }

    public void retry(Retry retry) {
        if (retry.isKeepalive()) {
            retry.setKeepalive(false);
            queue(retry);
        } else {
            retry.increment();

            if (retry.getRetryCount() >= retry.getRetries()) {
                Future<?> future = retry.getFuture();
                if (future instanceof SettableFuture) {
                    ((SettableFuture<?>) future).setException(new TimeoutException());
                } else {
                    future.cancel(true);
                }
            } else {
                try {
                    executorService.execute(() -> {
                        Object cancel = queue(retry);
                        final Runnable run = retry.getRunnable();
                        if (run != null) {
                            new NoExceptionRunnable() {
                                @Override
                                protected void doRun() throws Exception {
                                    try {
                                        run.run();
                                    } catch (CancelRetryException e) {
                                        completed(cancel);
                                    }
                                }
                            }.run();
                        }
                    });
                } catch (RejectedExecutionException e) {
                    queue(retry);
                }
            }
        }
    }

    protected Object queue(Retry retry) {
        return scheduledExecutorService.schedule(() -> retry(retry), retry.getTimeoutMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public void completed(Object obj) {
        ((ScheduledFuture) obj).cancel(false);
    }

}


text:
var debug = require('debug')('magicbook:layouts');
var through = require("through2");
var fs = require("fs");
var tinyliquid = require("tinyliquid");
var helpers = require("../helpers/helpers");
var _ = require("lodash");

var Plugin = function(registry) {
  this.layouts = {};
  registry.after("markdown:convert", "layouts", _.bind(this.addLayouts, this));
};

Plugin.prototype = {
  addLayouts: function(config, stream, extras, callback) {
    var that = this;

    stream = stream.pipe(
      through.obj(function(file, enc, cb) {
        var layout = _.get(file, "layoutLocals.page.layout") || config.layout;
        var includes =
          _.get(file, "layoutLocals.page.includes") || config.liquid.includes;

        if (layout && layout !== "none") {
          // create the object to pass into liquid for this file
          var locals = {
            content: file.contents.toString(),
            format: config.format,
            config: config
          };

          // Add locals set globally
          if (extras.layoutLocals) {
            _.assign(locals, extras.layoutLocals);
          }

          // Add locals set on file
          if (file.layoutLocals) {
            _.assign(locals, file.layoutLocals);
          }

          // if the cache has not been loaded, load the file
          // and create a template from it.
          if (!that.layouts[layout]) {
            try {
              var layoutContent = fs.readFileSync(layout);
              that.layouts[layout] = tinyliquid.compile(
                layoutContent.toString()
              );
            } catch (e) {
              return cb(new Error("Layout not found: " + layout));
            }
          }

          // then render the layout
          helpers.renderLiquidTemplate(
            that.layouts[layout],
            locals,
            includes,
            function(err, data) {
              file.contents = Buffer.from(data);
              file.$el = undefined;

              debug('Finished', file.path);

              cb(err, file);
            }
          );
        } else {

          debug('Skipped', file.path);

          cb(null, file);
        }
      })
    );

    callback(null, config, stream, extras);
  }
};

module.exports = Plugin;

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycoscience 41(2): 163 (2000)

#### Original name
Inocybe leptoclada Takah. Kobay. & Courtec.

### Remarks
null


text:
/*
 * This file is generated by jOOQ.
*/
package top.zbeboy.isy.domain.tables.records;

import java.sql.Date;
import java.sql.Timestamp;

import javax.annotation.Generated;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record14;
import org.jooq.Row14;
import org.jooq.impl.UpdatableRecordImpl;

import top.zbeboy.isy.domain.tables.Users;

/**
 * This class is generated by jOOQ.
 */
@Generated(
    value = {
        "http://www.jooq.org",
        "jOOQ version:3.10.7"
    },
    comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class UsersRecord extends UpdatableRecordImpl<UsersRecord> implements Record14<String, String, Byte, Integer, String, String, String, Byte, String, String, Timestamp, Timestamp, String, Date> {

    private static final long serialVersionUID = 1813961955;

    /**
     * Setter for isy.users.username.
     */
    public void setUsername(String value) {
        set(0, value);
    }

    /**
     * Getter for isy.users.username.
     */
    @NotNull
    @Size(max = 64)
    public String getUsername() {
        return (String) get(0);
    }

    /**
     * Setter for isy.users.password.
     */
    public void setPassword(String value) {
        set(1, value);
    }

    /**
     * Getter for isy.users.password.
     */
    @NotNull
    @Size(max = 300)
    public String getPassword() {
        return (String) get(1);
    }

    /**
     * Setter for isy.users.enabled.
     */
    public void setEnabled(Byte value) {
        set(2, value);
    }

    /**
     * Getter for isy.users.enabled.
     */
    @NotNull
    public Byte getEnabled() {
        return (Byte) get(2);
    }

    /**
     * Setter for isy.users.users_type_id.
     */
    public void setUsersTypeId(Integer value) {
        set(3, value);
    }

    /**
     * Getter for isy.users.users_type_id.
     */
    @NotNull
    public Integer getUsersTypeId() {
        return (Integer) get(3);
    }

    /**
     * Setter for isy.users.real_name.
     */
    public void setRealName(String value) {
        set(4, value);
    }

    /**
     * Getter for isy.users.real_name.
     */
    @Size(max = 30)
    public String getRealName() {
        return (String) get(4);
    }

    /**
     * Setter for isy.users.mobile.
     */
    public void setMobile(String value) {
        set(5, value);
    }

    /**
     * Getter for isy.users.mobile.
     */
    @NotNull
    @Size(max = 15)
    public String getMobile() {
        return (String) get(5);
    }

    /**
     * Setter for isy.users.avatar.
     */
    public void setAvatar(String value) {
        set(6, value);
    }

    /**
     * Getter for isy.users.avatar.
     */
    @Size(max = 500)
    public String getAvatar() {
        return (String) get(6);
    }

    /**
     * Setter for isy.users.verify_mailbox.
     */
    public void setVerifyMailbox(Byte value) {
        set(7, value);
    }

    /**
     * Getter for isy.users.verify_mailbox.
     */
    public Byte getVerifyMailbox() {
        return (Byte) get(7);
    }

    /**
     * Setter for isy.users.mailbox_verify_code.
     */
    public void setMailboxVerifyCode(String value) {
        set(8, value);
    }

    /**
     * Getter for isy.users.mailbox_verify_code.
     */
    @Size(max = 20)
    public String getMailboxVerifyCode() {
        return (String) get(8);
    }

    /**
     * Setter for isy.users.password_reset_key.
     */
    public void setPasswordResetKey(String value) {
        set(9, value);
    }

    /**
     * Getter for isy.users.password_reset_key.
     */
    @Size(max = 20)
    public String getPasswordResetKey() {
        return (String) get(9);
    }

    /**
     * Setter for isy.users.mailbox_verify_valid.
     */
    public void setMailboxVerifyValid(Timestamp value) {
        set(10, value);
    }

    /**
     * Getter for isy.users.mailbox_verify_valid.
     */
    public Timestamp getMailboxVerifyValid() {
        return (Timestamp) get(10);
    }

    /**
     * Setter for isy.users.password_reset_key_valid.
     */
    public void setPasswordResetKeyValid(Timestamp value) {
        set(11, value);
    }

    /**
     * Getter for isy.users.password_reset_key_valid.
     */
    public Timestamp getPasswordResetKeyValid() {
        return (Timestamp) get(11);
    }

    /**
     * Setter for isy.users.lang_key.
     */
    public void setLangKey(String value) {
        set(12, value);
    }

    /**
     * Getter for isy.users.lang_key.
     */
    @Size(max = 20)
    public String getLangKey() {
        return (String) get(12);
    }

    /**
     * Setter for isy.users.join_date.
     */
    public void setJoinDate(Date value) {
        set(13, value);
    }

    /**
     * Getter for isy.users.join_date.
     */
    public Date getJoinDate() {
        return (Date) get(13);
    }

    // -------------------------------------------------------------------------
    // Primary key information
    // -------------------------------------------------------------------------

    /**
     * {@inheritDoc}
     */
    @Override
    public Record1<String> key() {
        return (Record1) super.key();
    }

    // -------------------------------------------------------------------------
    // Record14 type implementation
    // -------------------------------------------------------------------------

    /**
     * {@inheritDoc}
     */
    @Override
    public Row14<String, String, Byte, Integer, String, String, String, Byte, String, String, Timestamp, Timestamp, String, Date> fieldsRow() {
        return (Row14) super.fieldsRow();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Row14<String, String, Byte, Integer, String, String, String, Byte, String, String, Timestamp, Timestamp, String, Date> valuesRow() {
        return (Row14) super.valuesRow();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field1() {
        return Users.USERS.USERNAME;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field2() {
        return Users.USERS.PASSWORD;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<Byte> field3() {
        return Users.USERS.ENABLED;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<Integer> field4() {
        return Users.USERS.USERS_TYPE_ID;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field5() {
        return Users.USERS.REAL_NAME;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field6() {
        return Users.USERS.MOBILE;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field7() {
        return Users.USERS.AVATAR;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<Byte> field8() {
        return Users.USERS.VERIFY_MAILBOX;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field9() {
        return Users.USERS.MAILBOX_VERIFY_CODE;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field10() {
        return Users.USERS.PASSWORD_RESET_KEY;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<Timestamp> field11() {
        return Users.USERS.MAILBOX_VERIFY_VALID;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<Timestamp> field12() {
        return Users.USERS.PASSWORD_RESET_KEY_VALID;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field13() {
        return Users.USERS.LANG_KEY;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<Date> field14() {
        return Users.USERS.JOIN_DATE;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String component1() {
        return getUsername();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String component2() {
        return getPassword();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Byte component3() {
        return getEnabled();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Integer component4() {
        return getUsersTypeId();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String component5() {
        return getRealName();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String component6() {
        return getMobile();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String component7() {
        return getAvatar();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Byte component8() {
        return getVerifyMailbox();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String component9() {
        return getMailboxVerifyCode();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String component10() {
        return getPasswordResetKey();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Timestamp component11() {
        return getMailboxVerifyValid();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Timestamp component12() {
        return getPasswordResetKeyValid();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String component13() {
        return getLangKey();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Date component14() {
        return getJoinDate();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value1() {
        return getUsername();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value2() {
        return getPassword();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Byte value3() {
        return getEnabled();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Integer value4() {
        return getUsersTypeId();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value5() {
        return getRealName();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value6() {
        return getMobile();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value7() {
        return getAvatar();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Byte value8() {
        return getVerifyMailbox();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value9() {
        return getMailboxVerifyCode();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value10() {
        return getPasswordResetKey();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Timestamp value11() {
        return getMailboxVerifyValid();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Timestamp value12() {
        return getPasswordResetKeyValid();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value13() {
        return getLangKey();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Date value14() {
        return getJoinDate();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UsersRecord value1(String value) {
        setUsername(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UsersRecord value2(String value) {
        setPassword(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UsersRecord value3(Byte value) {
        setEnabled(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UsersRecord value4(Integer value) {
        setUsersTypeId(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UsersRecord value5(String value) {
        setRealName(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UsersRecord value6(String value) {
        setMobile(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UsersRecord value7(String value) {
        setAvatar(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UsersRecord value8(Byte value) {
        setVerifyMailbox(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UsersRecord value9(String value) {
        setMailboxVerifyCode(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UsersRecord value10(String value) {
        setPasswordResetKey(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UsersRecord value11(Timestamp value) {
        setMailboxVerifyValid(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UsersRecord value12(Timestamp value) {
        setPasswordResetKeyValid(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UsersRecord value13(String value) {
        setLangKey(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UsersRecord value14(Date value) {
        setJoinDate(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UsersRecord values(String value1, String value2, Byte value3, Integer value4, String value5, String value6, String value7, Byte value8, String value9, String value10, Timestamp value11, Timestamp value12, String value13, Date value14) {
        value1(value1);
        value2(value2);
        value3(value3);
        value4(value4);
        value5(value5);
        value6(value6);
        value7(value7);
        value8(value8);
        value9(value9);
        value10(value10);
        value11(value11);
        value12(value12);
        value13(value13);
        value14(value14);
        return this;
    }

    // -------------------------------------------------------------------------
    // Constructors
    // -------------------------------------------------------------------------

    /**
     * Create a detached UsersRecord
     */
    public UsersRecord() {
        super(Users.USERS);
    }

    /**
     * Create a detached, initialised UsersRecord
     */
    public UsersRecord(String username, String password, Byte enabled, Integer usersTypeId, String realName, String mobile, String avatar, Byte verifyMailbox, String mailboxVerifyCode, String passwordResetKey, Timestamp mailboxVerifyValid, Timestamp passwordResetKeyValid, String langKey, Date joinDate) {
        super(Users.USERS);

        set(0, username);
        set(1, password);
        set(2, enabled);
        set(3, usersTypeId);
        set(4, realName);
        set(5, mobile);
        set(6, avatar);
        set(7, verifyMailbox);
        set(8, mailboxVerifyCode);
        set(9, passwordResetKey);
        set(10, mailboxVerifyValid);
        set(11, passwordResetKeyValid);
        set(12, langKey);
        set(13, joinDate);
    }
}


text:
using System.Collections.Specialized;
using System.Diagnostics;

namespace common
{
    public class HttpFormPostRequest : HttpFormGetRequest
    {
        [DebuggerStepThrough]
        public HttpFormPostRequest()
        {
            FormFields = new NameValueCollection();
        }

        public NameValueCollection FormFields
        {
            get;
            set;
        }
    }
}


text:
FROM java:7

#COPY HelloWorld.java /
COPY src /home/root/javahelloworld/src
#RUN javac HelloWorld.java
WORKDIR /home/root/javahelloworld
RUN mkdir bin
RUN javac -d bin src/HelloWorld.java

ENTRYPOINT ["java", "-cp", "bin", "HelloWorld"]


text:
//
//  DMRemoteRequestRouter.h
//
//  Created by David Muzi on 2014-12-11.
//  Copyright (c) 2014 David Muzi. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "DMRemoteRequestProtocol.h"

/**
 *  Request bloack handler
 *
 *  @param userInfo input dictionary
 *  @param ^callback callback block to be called on completion
 */
typedef void (^DMRemoteRequestBlock)(NSDictionary *userInfo, void(^callback)(NSDictionary *results));

@interface DMRemoteRequestRouter : NSObject

/**
 *  Singleton reference
 *
 *  @return sharedRouter
 */
+ (instancetype)sharedRouter;

/**
 *  Registers a class to handle a command originating from the watch
 *
 *  @param protocolClass a class that will handle the command
 *  @param method method name
 */
- (void)registerClass:(Class <DMRemoteRequestProtocol>)protocolClass forMethod:(NSString *)method;

/**
 *  Registers a block which can perform an asyncronous task before calling its completion handler
 *
 *  @param method  the method to be handled
 *  @param block handler
 */
- (void)registerBlock:(DMRemoteRequestBlock)block forMethod:(NSString *)method;

/**
 *  Convenience method to set handler
 *
 *  @param obj protocol class or request block
 *  @param key method name
 */
- (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying>)key;

/**
 *  Convenience method to get a registered handler
 *
 *  @param key method name
 *
 *  @return a protocol class or registered block
 */
- (id)objectForKeyedSubscript:(id <NSCopying>)key;

/**
 *  This should be called from application:handleWatchKitExtensionRequest:reply:
 *
 *  @param request the command parameters
 *  @param reply   the callback block
 *
 *  @return YES if the command was successfully handled
 */
- (BOOL)handleRequest:(NSDictionary *)request reply:(void (^)(NSDictionary *))reply;

/**
 *  Sends a notifcation to the watch signifying an event has occurred on the host app
 */
- (void)notifyWatch;

@end


text:
// cameras/perspective.cpp*
#include "stdafx.h"
#include "cameras/perspective.h"
#include "paramset.h"
#include "sampler.h"
#include "montecarlo.h"

// PerspectiveCamera Method Definitions
PerspectiveCamera:: PerspectiveCamera(const AnimatedTransform &cam2world,
        const float screenWindow[4], float sopen, float sclose,
        float lensr, float focald, float fov, Film *f)
    : ProjectiveCamera(cam2world, Perspective(fov, 1e-2f, 1000.f),
                       screenWindow, sopen, sclose, lensr, focald, f) {
    // Compute differential changes in origin for perspective camera rays
    dxCamera = RasterToCamera(Point(1,0,0)) - RasterToCamera(Point(0,0,0));
    dyCamera = RasterToCamera(Point(0,1,0)) - RasterToCamera(Point(0,0,0));
}

float PerspectiveCamera::GenerateRay(const CameraSample &sample,
                                     Ray *ray) const {
    // Generate raster and camera samples
    Point Pras(sample.imageX, sample.imageY, 0);
    Point Pcamera;
    RasterToCamera(Pras, &Pcamera);
    *ray = Ray(Point(0,0,0), Vector(Pcamera), 0.f, INFINITY);
    // Modify ray for depth of field
    if (lensRadius > 0.) {
        // Sample point on lens
        float lensU, lensV;
        ConcentricSampleDisk(sample.lensU, sample.lensV, &lensU, &lensV);
        lensU *= lensRadius;
        lensV *= lensRadius;

        // Compute point on plane of focus
        float ft = focalDistance / ray->d.z;
        Point Pfocus = (*ray)(ft);

        // Update ray for effect of lens
        ray->o = Point(lensU, lensV, 0.f);
        ray->d = Normalize(Pfocus - ray->o);
    }
    ray->time = Lerp(sample.time, shutterOpen, shutterClose);
    CameraToWorld(*ray, ray);
    return 1.f;
}

float PerspectiveCamera::GenerateRayDifferential(const CameraSample &sample,
                                                 RayDifferential *ray) const {
    // Generate raster and camera samples
    Point Pras(sample.imageX, sample.imageY, 0);
    Point Pcamera;
    RasterToCamera(Pras, &Pcamera);
    Vector dir = Normalize(Vector(Pcamera.x, Pcamera.y, Pcamera.z));
    *ray = RayDifferential(Point(0,0,0), dir, 0.f, INFINITY);
    // Modify ray for depth of field
    if (lensRadius > 0.) {
        // Sample point on lens
        float lensU, lensV;
        ConcentricSampleDisk(sample.lensU, sample.lensV, &lensU, &lensV);
        lensU *= lensRadius;
        lensV *= lensRadius;

        // Compute point on plane of focus
        float ft = focalDistance / ray->d.z;
        Point Pfocus = (*ray)(ft);

        // Update ray for effect of lens
        ray->o = Point(lensU, lensV, 0.f);
        ray->d = Normalize(Pfocus - ray->o);
    }

    // Compute offset rays for _PerspectiveCamera_ ray differentials
    ray->rxOrigin = ray->ryOrigin = ray->o;
    ray->rxDirection = Normalize(Vector(Pcamera) + dxCamera);
    ray->ryDirection = Normalize(Vector(Pcamera) + dyCamera);
    ray->time = Lerp(sample.time, shutterOpen, shutterClose);
    CameraToWorld(*ray, ray);
    ray->hasDifferentials = true;
    return 1.f;
}

PerspectiveCamera *CreatePerspectiveCamera(const ParamSet &params,
        const AnimatedTransform &cam2world, Film *film) {
    // Extract common camera parameters from _ParamSet_
    float shutteropen = params.FindOneFloat("shutteropen", 0.f);
    float shutterclose = params.FindOneFloat("shutterclose", 1.f);
    if (shutterclose < shutteropen) {
        Warning("Shutter close time [%f] < shutter open [%f].  Swapping them.",
                shutterclose, shutteropen);
        swap(shutterclose, shutteropen);
    }
    float lensradius = params.FindOneFloat("lensradius", 0.f);
    float focaldistance = params.FindOneFloat("focaldistance", 1e30f);
    float frame = params.FindOneFloat("frameaspectratio",
        float(film->xResolution)/float(film->yResolution));
    float screen[4];
    if (frame > 1.f) {
        screen[0] = -frame;
        screen[1] =  frame;
        screen[2] = -1.f;
        screen[3] =  1.f;
    }
    else {
        screen[0] = -1.f;
        screen[1] =  1.f;
        screen[2] = -1.f / frame;
        screen[3] =  1.f / frame;
    }
    int swi;
    const float *sw = params.FindFloat("screenwindow", &swi);
    if (sw && swi == 4)
        memcpy(screen, sw, 4*sizeof(float));
    float fov = params.FindOneFloat("fov", 90.);
    float halffov = params.FindOneFloat("halffov", -1.f);
    if (halffov > 0.f)
        // hack for structure synth, which exports half of the full fov
        fov = 2.f * halffov;
    return new PerspectiveCamera(cam2world, screen, shutteropen,
        shutterclose, lensradius, focaldistance, fov, film);
}


text: Sun Microsystems, Inc.


text:
using System;
using System.ComponentModel;
using PeanutButter.DuckTyping.Extensions;

namespace PeanutButter.DuckTyping.Demo.Strict
{
    public interface IDuck
    {
        void Quack();
        void Walk(int distance);
    }

    public class FrenchDuck
    {
        public void Quack()
        {
            Console.WriteLine("\nLE QUACK!\n");
        }

        public void Walk(int howFar)
        {
            Console.WriteLine($"\nCarried my baguette {howFar}m\n");
        }
    }

    [Order(5)]
    [Description("We can also duck-type methods!")]
    public class DuckingMethods : Demo
    {
        public override void Run()
        {
            var Dominique = new FrenchDuck();
            var duck = Dominique.DuckAs<IDuck>();

            Log("Now we invoke the duck...");

            duck.Quack();
            EmptyLine();
            duck.Walk(3);
        }
    }
}


text:
package org.apache.drill.exec.store.hive;

import java.util.Map;

import com.fasterxml.jackson.annotation.JsonAlias;
import org.apache.drill.common.logical.StoragePluginConfig;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;

@JsonTypeName(HiveStoragePluginConfig.NAME)
public class HiveStoragePluginConfig extends StoragePluginConfig {

  public static final String NAME = "hive";

  private final Map<String, String> configProps;

  @JsonCreator
  public HiveStoragePluginConfig(@JsonProperty("configProps")
                                 // previously two names were allowed due to incorrectly written ser / der logic
                                 // allowing to use both during deserialization for backward compatibility
                                 @JsonAlias("config") Map<String, String> configProps) {
    this.configProps = configProps;
  }

  @JsonProperty
  public Map<String, String> getConfigProps() {
    return configProps;
  }

  @Override
  public int hashCode() {
    return configProps != null ? configProps.hashCode() : 0;
  }

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

    HiveStoragePluginConfig that = (HiveStoragePluginConfig) o;

    if (configProps != null ? !configProps.equals(that.configProps) : that.configProps != null) {
      return false;
    }

    return true;
  }

}


text: OTP Analyst


text:
FROM stanfordlegion/regent

MAINTAINER Elliott Slaughter <slaughter@cs.stanford.edu>

# Install Dependencies.
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && \
    apt-get install -y python3-pip wget && \
    apt-get clean
RUN pip3 install notebook

# Install Tini.
RUN wget --quiet https://github.com/krallin/tini/releases/download/v0.6.0/tini && \
    echo "d5ed732199c36a1189320e6c4859f0169e950692f451c03e7854243b95f4234b *tini" | sha256sum -c - && \
    mv tini /usr/local/bin/tini && \
    chmod +x /usr/local/bin/tini

# Regent kernel configuration files.
RUN mkdir /usr/local/lib/python3.4/dist-packages/notebook/static/components/codemirror/mode/regent
COPY codemirror/regent/regent.js /usr/local/lib/python3.4/dist-packages/notebook/static/components/codemirror/mode/regent/
COPY pygments/lexers/regent.py /usr/local/lib/python3.4/dist-packages/pygments/lexers/
RUN cd /usr/local/lib/python3.4/dist-packages/pygments/lexers && python3 _mapping.py

RUN mkdir -p /usr/local/share/jupyter/kernels/regent
COPY kernels/regent/kernel_plain.json /usr/local/share/jupyter/kernels/regent/kernel.json
COPY kernels/regent/regentkernel.py /usr/local/share/jupyter/kernels/regent/regentkernel.py

ENV NB_USER=jovyan NB_UID=1001
RUN useradd -m -s /bin/bash -N -u $NB_UID $NB_USER && \
    mkdir /home/$NB_USER/notebooks && \
    mkdir /home/$NB_USER/.jupyter && \
    mkdir /home/$NB_USER/.jupyter/custom && \
    chown -R $NB_USER:users /home/$NB_USER

# Configure container startup.
EXPOSE 8888
WORKDIR /home/$NB_USER/notebooks
ENTRYPOINT ["tini", "--"]
CMD ["start-notebook.sh"]

# Configure local files last.
COPY start-notebook.sh /usr/local/bin/
COPY jupyter_notebook_config.py /home/$NB_USER/.jupyter/
COPY static/custom/custom.js /home/$NB_USER/.jupyter/custom/
COPY notebooks/ /home/$NB_USER/notebooks/
RUN chown -R $NB_USER:users /home/$NB_USER


text:
using Pegelalarm.Core.Data;
using Pegelalarm.Core.Network.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pegelalarm.Views
{
    public interface IDetailView
    {
        void ConfigChart(double warnValue, double alarmValue, List<Sample> samples);
        void ShowAlarmSlider();
    }
}


text:
Rule ID | Category | Severity | Notes
--------|----------|----------|-------
HAA0101 | Performance | Warning | CallSiteImplicitAllocationAnalyzer
HAA0102 | Performance | Warning | CallSiteImplicitAllocationAnalyzer
HAA0201 | Performance | Warning | ConcatenationAllocationAnalyzer, [Documentation](http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.110).aspx)
HAA0202 | Performance | Warning | ConcatenationAllocationAnalyzer, [Documentation](http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx)
HAA0301 | Performance | Warning | DisplayClassAllocationAnalyzer
HAA0302 | Performance | Warning | DisplayClassAllocationAnalyzer
HAA0303 | Performance | Warning | DisplayClassAllocationAnalyzer
HAA0401 | Performance | Warning | EnumeratorAllocationAnalyzer
HAA0601 | Performance | Warning | TypeConversionAllocationAnalyzer
HAA0602 | Performance | Warning | TypeConversionAllocationAnalyzer
HAA0603 | Performance | Warning | TypeConversionAllocationAnalyzer
HAA0604 | Performance | Info | TypeConversionAllocationAnalyzer


text:
/* $XConsortium: Dvi.c,v 1.21 94/04/17 20:43:34 keith Exp $ */
/* $XdotOrg: $ */
/*

Copyright (c) 1991  X Consortium

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of the X Consortium shall
not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization
from the X Consortium.

*/
/* $XFree86: xc/programs/xditview/Dvi.c,v 1.3 2001/08/01 00:45:03 tsi Exp $ */

/*
 * Dvi.c - Dvi display widget
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#define XtStrlen(s)	((s) ? strlen(s) : 0)

  /* The following are defined for the reader's convenience.  Any
     Xt..Field macro in this code just refers to some field in
     one of the substructures of the WidgetRec.  */

#include <X11/IntrinsicP.h>
#include <X11/StringDefs.h>
#include <X11/Xmu/Converters.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include "DviP.h"

/****************************************************************
 *
 * Full class record constant
 *
 ****************************************************************/

/* Private Data */
/* Note: default_font_map was too long a token for some machines...
 *       therefor it has been split in to and assigned to resources
 *       in the ClassInitialize routine.
 */
static char default_font_map_1[] =  "\
R	-*-times-medium-r-normal--*-*-*-*-*-*-iso8859-1\n\
I	-*-times-medium-i-normal--*-*-*-*-*-*-iso8859-1\n\
B	-*-times-bold-r-normal--*-*-*-*-*-*-iso8859-1\n\
F	-*-times-bold-i-normal--*-*-*-*-*-*-iso8859-1\n\
TR	-*-times-medium-r-normal--*-*-*-*-*-*-iso8859-1\n\
TI	-*-times-medium-i-normal--*-*-*-*-*-*-iso8859-1\n\
TB	-*-times-bold-r-normal--*-*-*-*-*-*-iso8859-1\n\
TF	-*-times-bold-i-normal--*-*-*-*-*-*-iso8859-1\n\
BI	-*-times-bold-i-normal--*-*-*-*-*-*-iso8859-1\n\
C	-*-courier-medium-r-normal--*-*-*-*-*-*-iso8859-1\n\
CO	-*-courier-medium-o-normal--*-*-*-*-*-*-iso8859-1\n\
CB	-*-courier-bold-r-normal--*-*-*-*-*-*-iso8859-1\n\
CF	-*-courier-bold-o-normal--*-*-*-*-*-*-iso8859-1\n\
H	-*-helvetica-medium-r-normal--*-*-*-*-*-*-iso8859-1\n\
HO	-*-helvetica-medium-o-normal--*-*-*-*-*-*-iso8859-1\n\
HB	-*-helvetica-bold-r-normal--*-*-*-*-*-*-iso8859-1\n\
HF	-*-helvetica-bold-o-normal--*-*-*-*-*-*-iso8859-1\n\
";
static char default_font_map_2[] =  "\
N	-*-new century schoolbook-medium-r-normal--*-*-*-*-*-*-iso8859-1\n\
NI	-*-new century schoolbook-medium-i-normal--*-*-*-*-*-*-iso8859-1\n\
NB	-*-new century schoolbook-bold-r-normal--*-*-*-*-*-*-iso8859-1\n\
NF	-*-new century schoolbook-bold-i-normal--*-*-*-*-*-*-iso8859-1\n\
A	-*-charter-medium-r-normal--*-*-*-*-*-*-iso8859-1\n\
AI	-*-charter-medium-i-normal--*-*-*-*-*-*-iso8859-1\n\
AB	-*-charter-bold-r-normal--*-*-*-*-*-*-iso8859-1\n\
AF	-*-charter-bold-i-normal--*-*-*-*-*-*-iso8859-1\n\
S	-*-symbol-medium-r-normal--*-*-*-*-*-*-adobe-fontspecific\n\
S2	-*-symbol-medium-r-normal--*-*-*-*-*-*-adobe-fontspecific\n\
";

#define offset(field) XtOffsetOf(DviRec, field)

static XtResource resources[] = {
	{XtNfontMap, XtCFontMap, XtRString, sizeof (char *),
	 offset(dvi.font_map_string), XtRString, NULL /* set in code */},
	{XtNforeground, XtCForeground, XtRPixel, sizeof (unsigned long),
	 offset(dvi.foreground), XtRString, XtDefaultForeground},
	{XtNpageNumber, XtCPageNumber, XtRInt, sizeof (int),
	 offset(dvi.requested_page), XtRImmediate, (XtPointer) 1},
	{XtNlastPageNumber, XtCLastPageNumber, XtRInt, sizeof (int),
	 offset (dvi.last_page), XtRImmediate, (XtPointer) 0},
	{XtNfile, XtCFile, XtRFile, sizeof (FILE *),
	 offset (dvi.file), XtRFile, (char *) 0},
	{XtNseek, XtCSeek, XtRBoolean, sizeof (Boolean),
	 offset(dvi.seek), XtRImmediate, (XtPointer) False},
	{XtNfont, XtCFont, XtRFontStruct, sizeof (XFontStruct *),
	 offset(dvi.default_font), XtRString, XtDefaultFont},
	{XtNbackingStore, XtCBackingStore, XtRBackingStore, sizeof (int),
	 offset(dvi.backing_store), XtRString, "default"},
	{XtNnoPolyText, XtCNoPolyText, XtRBoolean, sizeof (Boolean),
	 offset(dvi.noPolyText), XtRImmediate, (XtPointer) False},
	{XtNscreenResolution, XtCScreenResolution, XtRInt, sizeof (int),
	 offset(dvi.screen_resolution), XtRImmediate, (XtPointer) 75},
	{XtNpageWidth, XtCPageWidth, XtRFloat, sizeof (float),
	 offset(dvi.page_width), XtRString, "8.5"},
	{XtNpageHeight, XtCPageHeight, XtRFloat, sizeof (float),
	 offset(dvi.page_height), XtRString, "11"},
	{XtNsizeScale, XtCSizeScale, XtRInt, sizeof (int),
	 offset(dvi.size_scale_set), XtRImmediate, (XtPointer) 0},
};

#undef offset

static void		ClassInitialize(void);
static void		Initialize(Widget, Widget, ArgList, Cardinal *);
static void		Realize(Widget, XtValueMask *, XSetWindowAttributes *);
static void		Destroy(Widget);
static void		Redisplay(Widget, XEvent *, Region);
static Boolean		SetValues(Widget, Widget, Widget, ArgList , Cardinal *);
static Boolean		SetValuesHook(Widget, ArgList, Cardinal	*);
static XtGeometryResult	QueryGeometry(Widget,
				      XtWidgetGeometry *, XtWidgetGeometry *);
static void		RequestDesiredSize(DviWidget);
static void		ShowDvi(DviWidget);
static void		CloseFile(DviWidget);
static void		OpenFile(DviWidget);

#define SuperClass ((SimpleWidgetClass)&simpleClassRec)

DviClassRec dviClassRec = {
{
	(WidgetClass) SuperClass,	/* superclass		  */
	"Dvi",				/* class_name		  */
	sizeof(DviRec),			/* size			  */
	ClassInitialize,		/* class_initialize	  */
	NULL,				/* class_part_initialize  */
	FALSE,				/* class_inited		  */
	Initialize,			/* initialize		  */
	NULL,				/* initialize_hook	  */
	Realize,			/* realize		  */
	NULL,				/* actions		  */
	0,				/* num_actions		  */
	resources,			/* resources		  */
	XtNumber(resources),		/* resource_count	  */
	NULLQUARK,			/* xrm_class		  */
	FALSE,				/* compress_motion	  */
	XtExposeCompressMaximal,    	/* compress_exposure	  */
	TRUE,				/* compress_enterleave    */
	FALSE,				/* visible_interest	  */
	Destroy,			/* destroy		  */
	NULL,				/* resize		  */
	Redisplay,			/* expose		  */
	SetValues,			/* set_values		  */
	SetValuesHook,			/* set_values_hook	  */
	XtInheritSetValuesAlmost,	/* set_values_almost	  */
	NULL,				/* get_values_hook	  */
	NULL,				/* accept_focus		  */
	XtVersion,			/* version		  */
	NULL,				/* callback_private	  */
	NULL,				/* tm_table		  */
	QueryGeometry,			/* query_geometry	  */
	XtInheritDisplayAccelerator,	/* display_accelerator	  */
	NULL,				/* extension		  */
},  /* CoreClass fields initialization */
{
    XtInheritChangeSensitive		/* change_sensitive	*/
},  /* SimpleClass fields initialization */
{
    0,                                     /* field not used    */
},  /* DviClass fields initialization */
};

WidgetClass dviWidgetClass = (WidgetClass) &dviClassRec;

static void
ClassInitialize (void)
{
  int len1 = strlen(default_font_map_1);
  int len2 = strlen(default_font_map_2);
  char *dfm = XtMalloc(len1 + len2 + 1);
  char *ptr = dfm;
  strcpy(ptr, default_font_map_1); ptr += len1;
  strcpy(ptr, default_font_map_2);
  resources[0].default_addr = dfm;

  XtAddConverter( XtRString, XtRBackingStore, XmuCvtStringToBackingStore,
		 NULL, 0 );
}

/****************************************************************
 *
 * Private Procedures
 *
 ****************************************************************/

/* ARGSUSED */
static void
Initialize(Widget request, Widget new, ArgList args, Cardinal *num_args)
{
    DviWidget	dw = (DviWidget) new;

    dw->dvi.tmpFile = NULL;
    dw->dvi.readingTmp = 0;
    dw->dvi.ungot = 0;
    dw->dvi.normal_GC = NULL;
    dw->dvi.file_map = NULL;
    dw->dvi.fonts = NULL;
    dw->dvi.font_map = NULL;
    dw->dvi.current_page = 0;
    dw->dvi.font_size = 0;
    dw->dvi.font_number = 0;
    dw->dvi.device_resolution = 0;
    dw->dvi.line_width = 0;
    dw->dvi.line_style = 0;
    dw->dvi.font = NULL;
    dw->dvi.display_enable = 0;
    dw->dvi.scale = 0.0;
    dw->dvi.state = NULL;
    dw->dvi.cache.index = 0;
    dw->dvi.cache.font = NULL;
    dw->dvi.size_scale = 0;
    dw->dvi.size_scale_set = 0;
    RequestDesiredSize (dw);
}

static void
Realize(Widget w, XtValueMask *valueMask, XSetWindowAttributes *attrs)
{
    DviWidget	dw = (DviWidget) w;
    XGCValues	values;

    if (dw->dvi.backing_store != Always + WhenMapped + NotUseful) {
	attrs->backing_store = dw->dvi.backing_store;
	*valueMask |= CWBackingStore;
    }
    XtCreateWindow (w, (unsigned)InputOutput, (Visual *) CopyFromParent,
		    *valueMask, attrs);
    values.foreground = dw->dvi.foreground;
    dw->dvi.normal_GC = XCreateGC (XtDisplay (w), XtWindow (w),
				    GCForeground, &values);
#ifdef USE_XFT
    {
	int		scr;
	Visual		*visual;
	Colormap	cmap;
	XRenderColor	black;

	scr = XScreenNumberOfScreen (dw->core.screen);
	visual = DefaultVisual (XtDisplay (w), scr);
	cmap = DefaultColormap (XtDisplay (w), scr);
	dw->dvi.draw = XftDrawCreate (XtDisplay (w), XtWindow (w),
				      visual, cmap);

	black.red = black.green = black.blue = 0;
	black.alpha = 0xffff;
	XftColorAllocValue (XtDisplay (w), visual, cmap,
			    &black, &dw->dvi.black);
	dw->dvi.default_font = XftFontOpenName (XtDisplay (w),
						scr,
						"serif-12");
    }
#endif
    if (dw->dvi.file)
	OpenFile (dw);
    ParseFontMap (dw);
}

static void
Destroy(Widget w)
{
	DviWidget	dw = (DviWidget) w;

	XFreeGC (XtDisplay (w), dw->dvi.normal_GC);
	DestroyFontMap (dw->dvi.font_map);
	DestroyFileMap (dw->dvi.file_map);
}

/*
 * Repaint the widget window
 */

/* ARGSUSED */
static void
Redisplay(Widget w, XEvent *event, Region region)
{
	DviWidget	dw = (DviWidget) w;
#ifndef USE_XFT
	XRectangle	extents;
#endif

#ifdef USE_XFT
	XClearArea (XtDisplay (dw),
		    XtWindow (dw),
		    0, 0, 0, 0, False);
	dw->dvi.extents.x1 = 0;
	dw->dvi.extents.y1 = 0;
	dw->dvi.extents.x2 = dw->core.width;
	dw->dvi.extents.y2 = dw->core.height;
#else
	XClipBox (region, &extents);
	dw->dvi.extents.x1 = extents.x;
	dw->dvi.extents.y1 = extents.y;
	dw->dvi.extents.x2 = extents.x + extents.width;
	dw->dvi.extents.y2 = extents.y + extents.height;
#endif
	ShowDvi (dw);
}

static void
RequestDesiredSize (DviWidget dw)
{
    XtWidgetGeometry	req, rep;

    dw->dvi.desired_width = dw->dvi.page_width *
				 dw->dvi.screen_resolution;
    dw->dvi.desired_height = dw->dvi.page_height *
				  dw->dvi.screen_resolution;
    req.request_mode = CWWidth|CWHeight;
    req.width = dw->dvi.desired_width;
    req.height = dw->dvi.desired_height;
    XtMakeGeometryRequest ((Widget) dw, &req, &rep);
}

/*
 * Set specified arguments into widget
 */
/* ARGSUSED */
static Boolean
SetValues (Widget wcurrent, Widget wrequest, Widget wnew,
	   ArgList args, Cardinal *num_args)
{
    DviWidget	current = (DviWidget) wcurrent;
    DviWidget	request = (DviWidget) wrequest;
    DviWidget	new     = (DviWidget) wnew;
    Boolean	redisplay = FALSE;
    char	*new_map;
    int		cur, req;

    req = request->dvi.requested_page;
    cur = current->dvi.requested_page;
    if (cur != req) {
	    if (req < 1)
		req = 1;
	    if (request->dvi.file)
	    {
		if (current->dvi.last_page != 0 &&
		    req > current->dvi.last_page)
			req = current->dvi.last_page;
	    }
	    if (cur != req)
		redisplay = TRUE;
	    new->dvi.requested_page = req;
    }

    if (current->dvi.font_map_string != request->dvi.font_map_string) {
	    new_map = XtMalloc (strlen (request->dvi.font_map_string) + 1);
	    if (new_map) {
		    redisplay = TRUE;
		    strcpy (new_map, request->dvi.font_map_string);
		    new->dvi.font_map_string = new_map;
		    if (current->dvi.font_map_string)
			    XtFree (current->dvi.font_map_string);
		    current->dvi.font_map_string = NULL;
		    ParseFontMap (new);
	    }
    }
    if (current->dvi.screen_resolution != request->dvi.screen_resolution)
    {
	ResetFonts (new);
	new->dvi.line_width = -1;
    }
    if (request->dvi.device_resolution)
	new->dvi.scale = ((double) request->dvi.screen_resolution) /
			     ((double) request->dvi.device_resolution);
    if (current->dvi.page_width !=  request->dvi.page_width ||
	current->dvi.page_height != request->dvi.page_height ||
	current->dvi.screen_resolution != request->dvi.screen_resolution)
    {
	RequestDesiredSize (new);
	redisplay = TRUE;
    }
    return redisplay;
}

/*
 * use the set_values_hook entry to check when
 * the file is set
 */

static Boolean
SetValuesHook (Widget widget, ArgList args, Cardinal *num_argsp)
{
	DviWidget	dw = (DviWidget) widget;
	Cardinal	i;

	for (i = 0; i < *num_argsp; i++) {
		if (!strcmp (args[i].name, XtNfile)) {
			CloseFile (dw);
			OpenFile (dw);
			return TRUE;
		}
	}
	return FALSE;
}

static void
CloseFile (DviWidget dw)
{
    if (dw->dvi.tmpFile)
	fclose (dw->dvi.tmpFile);
    ForgetPagePositions (dw);
}

static void
OpenFile (DviWidget dw)
{
    char	tmpName[sizeof ("/tmp/dviXXXXXX")];
#ifdef HAS_MKSTEMP
    int fd;
#endif

    dw->dvi.tmpFile = NULL;
    if (!dw->dvi.seek) {
	strcpy (tmpName, "/tmp/dviXXXXXX");
#ifndef HAS_MKSTEMP
	mktemp (tmpName);
	dw->dvi.tmpFile = fopen (tmpName, "w+");
#else
	fd = mkstemp(tmpName);
	dw->dvi.tmpFile = fdopen(fd, "w+");
#endif
	unlink (tmpName);
    }
    if (dw->dvi.requested_page < 1)
	dw->dvi.requested_page = 1;
    dw->dvi.last_page = 0;
}

static XtGeometryResult
QueryGeometry (Widget w, XtWidgetGeometry *request,
	       XtWidgetGeometry *geometry_return)
{
	XtGeometryResult	ret;
	DviWidget		dw = (DviWidget) w;

	ret = XtGeometryYes;
	if ((int)request->width < dw->dvi.desired_width
	    || (int)request->height < dw->dvi.desired_height)
		ret = XtGeometryAlmost;
	geometry_return->width = dw->dvi.desired_width;
	geometry_return->height = dw->dvi.desired_height;
	geometry_return->request_mode = CWWidth|CWHeight;
	return ret;
}

void
SetDeviceResolution (DviWidget dw, int resolution)
{
    if (resolution != dw->dvi.device_resolution) {
	dw->dvi.device_resolution = resolution;
	dw->dvi.scale = ((double)  dw->dvi.screen_resolution) /
			((double) resolution);
    }
}

static void
ShowDvi (DviWidget dw)
{
	int	i;
	long	file_position;

	if (!dw->dvi.file)
	  return;

	if (dw->dvi.requested_page < 1)
		dw->dvi.requested_page = 1;

	if (dw->dvi.last_page != 0 && dw->dvi.requested_page > dw->dvi.last_page)
		dw->dvi.requested_page = dw->dvi.last_page;

	file_position = SearchPagePosition (dw, dw->dvi.requested_page);
	if (file_position != -1) {
		FileSeek(dw, file_position);
		dw->dvi.current_page = dw->dvi.requested_page;
	} else {
		for (i=dw->dvi.requested_page; i > 0; i--) {
			file_position = SearchPagePosition (dw, i);
			if (file_position != -1)
				break;
		}
		if (file_position == -1)
			file_position = 0;
		FileSeek (dw, file_position);

		dw->dvi.current_page = i;

		dw->dvi.display_enable = 0;
		while (dw->dvi.current_page != dw->dvi.requested_page) {
			dw->dvi.current_page = ParseInput (dw);
			/*
			 * at EOF, seek back to the begining of this page.
			 */
			if (feof (dw->dvi.file)) {
				file_position = SearchPagePosition (dw,
						dw->dvi.current_page);
				if (file_position != -1)
					FileSeek (dw, file_position);
				break;
			}
		}
	}

	dw->dvi.display_enable = 1;
	ParseInput (dw);
	if (dw->dvi.last_page && dw->dvi.requested_page > dw->dvi.last_page)
		dw->dvi.requested_page = dw->dvi.last_page;
}


text:
Types
######

***************
Neuron Related
***************

===========
Neuron Pool
===========

Imagine you have a similar with three kinds of neurons with different ion channels present in different parts of the cell:

.. code-block:: julia

	filepath="/path/to/file/cell.asc"
	blank_neuron=instantiate(filepath)
	set_nsegs!(blank_neuron)
	myneuron1=add(blank_neuron,HH())
	myneuron2=add(blank_neuron,(HH(),Passive()))
	myneuron3=add(blank_neuron,(HH(),Passive()),(HH(),Passive()),Passive(),Passive());

You could easily construct an array of the neurons above to be accessed during simulations:

.. code-block:: julia

	my_neur_array=Array(Neuron,3)
	my_neur_array[1]=myneuron1
	my_neur_array[2]=myneuron2
	my_neur_array[3]=myneuron3

But this is actually inefficient, because the methods used for solving the equation in the first one are different than the second, which are different than the third because each has different channel types: consequently, the compiler has to figure out which ones to use.

Consequently, you see above that the Network type contains a "Neuron Pool" which for the case above would look like this:

.. code-block:: julia

	type NeuronPool0
		N_1::Array{Neuron_1,1}
		N_2::Array{Neuron_2,1}
		N_3::Array{Neuron_3,1}
	end


text:
define(function (/*require, exports, module*/) {
    "use strict";

    var _ = brackets.getModule("thirdparty/lodash");

    function Repository() {
        this._items = [];
    }

    Repository.prototype.add = function(document) {
        this._items.push(document);
    };

    Repository.prototype.remove = function(document) {
        var i = this._items.indexOf(document);
        if (i !== -1) {
            this._items.splice(i, 1);
        }
    };

    Repository.prototype.clear = function() {
        this._items.splice(0, Number.MAX_VALUE);
    };

    Repository.prototype.items = function() {
        return this._items.slice();
    };

    Repository.prototype.find = function(criteria) {
        return _.find(this._items, criteria);
    };

    Repository.prototype.getByName = function(name) {
        return _.find(this._items, {"name": name});
    };

    Repository.prototype.getById = function(id) {
        return _.find(this._items, {"id": id});
    };

    return Repository;
});


text:
void Map::load(TCODZip &zip) {
	seed=zip.getInt();
    init(false);
	for (int i=0; i < width*height; i++) {
		tiles[i].explored=zip.getInt();
	}
}

void Map::save(TCODZip &zip) {
	zip.putInt(seed);
	for (int i=0; i < width*height; i++) {
		zip.putInt(tiles[i].explored);
	}
}

void Actor::load(TCODZip &zip) {
	x=zip.getInt();
	y=zip.getInt();
	ch=zip.getInt();
	col=zip.getColor();
	name=_strdup(zip.getString());
	blocks=zip.getInt();
	fovOnly=zip.getInt();
	bool hasAttacker=zip.getInt();
	bool hasDestructible=zip.getInt();
	bool hasAi=zip.getInt();
	bool hasPickable=zip.getInt();
	bool hasContainer=zip.getInt();
	if ( hasAttacker ) {
		attacker = new Attacker(0.0f);
		attacker->load(zip);
	}
	if ( hasDestructible ) {
		destructible = Destructible::create(zip);
	}
	if ( hasAi ) {
		ai = Ai::create(zip);
	}
	if ( hasPickable ) {
		pickable = Pickable::create(zip);
	}
	if ( hasContainer ) {
		container = new Container(0);
		container->load(zip);
	}
}

void Actor::save(TCODZip &zip) {
	zip.putInt(x);
	zip.putInt(y);
	zip.putInt(ch);
	zip.putColor(&col);
	zip.putString(name);
	zip.putInt(blocks);
	zip.putInt(fovOnly);
	zip.putInt(attacker != NULL);
	zip.putInt(destructible != NULL);
	zip.putInt(ai != NULL);
	zip.putInt(pickable != NULL);
	zip.putInt(container != NULL);
	if ( attacker ) attacker->save(zip);
	if ( destructible ) destructible->save(zip);
	if ( ai ) ai->save(zip);
	if ( pickable ) pickable->save(zip);
	if ( container ) container->save(zip);
}

void Container::load(TCODZip &zip) {
	size=zip.getInt();
	int nbActors=zip.getInt();
	while ( nbActors > 0 ) {
		Actor *actor=new Actor(0,0,0,NULL,TCODColor::white);
		actor->load(zip);
		inventory.push(actor);
		nbActors--;
	}
}

void Container::save(TCODZip &zip) {
	zip.putInt(size);
	zip.putInt(inventory.size());
	for (Actor **it=inventory.begin(); it != inventory.end(); it++) {
		(*it)->save(zip);
	}
}

void Destructible::load(TCODZip &zip) {
	maxHp=zip.getFloat();
	hp=zip.getFloat();
	defense=zip.getFloat();
	corpseName=strdup(zip.getString());
	xp=zip.getInt();
}

void Destructible::save(TCODZip &zip) {
	zip.putFloat(maxHp);
	zip.putFloat(hp);
	zip.putFloat(defense);
	zip.putString(corpseName);
	zip.putInt(xp);
}

void PlayerDestructible::save(TCODZip &zip) {
	zip.putInt(PLAYER);
	Destructible::save(zip);
}

void MonsterDestructible::save(TCODZip &zip) {
	zip.putInt(MONSTER);
	Destructible::save(zip);
}

Destructible *Destructible::create(TCODZip &zip) {
	DestructibleType type=(DestructibleType)zip.getInt();
	Destructible *destructible=NULL;
	switch(type) {
		case MONSTER : destructible=new MonsterDestructible(0,0,NULL,0); break;
		case PLAYER : destructible=new PlayerDestructible(0,0,NULL); break;
	}
	destructible->load(zip);
	return destructible;
}

void Attacker::load(TCODZip &zip) {
	power=zip.getFloat();
}

void Attacker::save(TCODZip &zip) {
	zip.putFloat(power);
}

void MonsterAi::load(TCODZip &zip) {
	moveCount=zip.getInt();
}

void MonsterAi::save(TCODZip &zip) {
	zip.putInt(MONSTER);
	zip.putInt(moveCount);
}

void ConfusedMonsterAi::load(TCODZip &zip) {
	nbTurns=zip.getInt();
	oldAi=Ai::create(zip);
}

void ConfusedMonsterAi::save(TCODZip &zip) {
	zip.putInt(CONFUSED_MONSTER);
	zip.putInt(nbTurns);
	oldAi->save(zip);
}

void PlayerAi::load(TCODZip &zip) {
	xpLevel=zip.getInt();
}

void PlayerAi::save(TCODZip &zip) {
	zip.putInt(PLAYER);
	zip.putInt(xpLevel);
}

Ai *Ai::create(TCODZip &zip) {
	AiType type=(AiType)zip.getInt();
	Ai *ai=NULL;
	switch(type) {
		case PLAYER : ai = new PlayerAi(); break;
		case MONSTER : ai = new MonsterAi(); break;
		case CONFUSED_MONSTER : ai = new ConfusedMonsterAi(0,NULL); break;
	}
	ai->load(zip);
	return ai;
}

void Healer::load(TCODZip &zip) {
	amount=zip.getFloat();
}

void Healer::save(TCODZip &zip) {
	zip.putInt(HEALER);
	zip.putFloat(amount);
}

void LightningBolt::load(TCODZip &zip) {
	range=zip.getFloat();
	damage=zip.getFloat();
}

void LightningBolt::save(TCODZip &zip) {
	zip.putInt(LIGHTNING_BOLT);
	zip.putFloat(range);
	zip.putFloat(damage);
}

void Confuser::load(TCODZip &zip) {
	nbTurns=zip.getInt();
	range=zip.getFloat();
}

void Confuser::save(TCODZip &zip) {
	zip.putInt(CONFUSER);
	zip.putInt(nbTurns);
	zip.putFloat(range);
}

void Fireball::save(TCODZip &zip) {
	zip.putInt(FIREBALL);
	zip.putFloat(range);
	zip.putFloat(damage);
}

Pickable *Pickable::create(TCODZip &zip) {
	PickableType type=(PickableType)zip.getInt();
	Pickable *pickable=NULL;
	switch(type) {
		case HEALER : pickable=new Healer(0); break;
		case LIGHTNING_BOLT : pickable=new LightningBolt(0,0); break;
		case CONFUSER : pickable=new Confuser(0,0); break;
		case FIREBALL : pickable=new Fireball(0,0); break;
	}
	pickable->load(zip);
	return pickable;
}

void Gui::load(TCODZip &zip) {
	int nbMessages=zip.getInt();
	while (nbMessages > 0) {
		const char *text=zip.getString();
		TCODColor col=zip.getColor();
		message(col,text);
		nbMessages--;
	}
}

void Gui::save(TCODZip &zip) {
	zip.putInt(log.size());
	for (Message **it=log.begin(); it != log.end(); it++) {
		zip.putString((*it)->text);
		zip.putColor(&(*it)->col);
	}
}

const int SAVEGAME_VERSION=0x1100;
void Engine::load(bool pause) {
	TCODZip zip;
	engine.gui->menu.clear();
	engine.gui->menu.addItem(Menu::NEW_GAME,"New game");
	if ( TCODSystem::fileExists("game.sav")) {
		zip.loadFromFile("game.sav");
		int version = zip.getInt();
		if ( version == SAVEGAME_VERSION ) {
			engine.gui->menu.addItem(Menu::CONTINUE,"Continue");
		}
	}
	engine.gui->menu.addItem(Menu::EXIT,"Exit");

	Menu::MenuItemCode menuItem=engine.gui->menu.pick(
		pause ? Menu::PAUSE : Menu::MAIN);
	if ( menuItem == Menu::EXIT || menuItem == Menu::NONE ) {
		// Exit or window closed
		exit(0);
	} else if ( menuItem == Menu::NEW_GAME ) {
		// New game
		engine.term();
		engine.init();
	} else {
		// continue a saved game
		engine.term();
		// load the map
		level=zip.getInt();
		int width=zip.getInt();
		int height=zip.getInt();
		map = new Map(width,height);
		map->load(zip);
		// then the player
		player=new Actor(0,0,0,NULL,TCODColor::white);
		actors.push(player);
		player->load(zip);
		// the stairs
		stairs=new Actor(0,0,0,NULL,TCODColor::white);
		stairs->load(zip);
		actors.push(stairs);
		// then all other actors
		int nbActors=zip.getInt();
		while ( nbActors > 0 ) {
			Actor *actor = new Actor(0,0,0,NULL,TCODColor::white);
			actor->load(zip);
			actors.push(actor);
			nbActors--;
		}
		// finally the message log
		gui->load(zip);
		// to force FOV recomputation
		gameStatus=STARTUP;
	}
}

void Engine::save() {
	if ( player->destructible->isDead() ) {
		TCODSystem::deleteFile("game.sav");
	} else {
		TCODZip zip;
		zip.putInt(SAVEGAME_VERSION);
		zip.putInt(level);
		// save the map first
		zip.putInt(map->width);
		zip.putInt(map->height);
		map->save(zip);
		// then the player
		player->save(zip);
		// then the stairs
		stairs->save(zip);
		// then all the other actors
		zip.putInt(actors.size()-2);
		for (Actor **it=actors.begin(); it!=actors.end(); it++) {
			if ( *it != player && *it != stairs ) {
				(*it)->save(zip);
			}
		}
		// finally the message log
		gui->save(zip);
		zip.saveToFile("game.sav");
	}
}


text:
<?php

namespace AppBundle\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class CrontabCommand extends BaseCommand
{
    protected function configure()
    {
        $this->setName('crontab:schedule');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->setDisableWebCrontab();
        $logger = $this->getContainer()->get('logger');
        $logger->info('Crontab:开始执行定时任务');
        $this->initServiceKernel();
        putenv('IS_RUN_BY_COMMAND=true');
        $this->getServiceKernel()->createService('Crontab:CrontabService')->scheduleJobs();
        $logger->info('Crontab:定时任务执行完毕');
    }

    protected function setDisableWebCrontab()
    {
        $setting = $this->getSettingService()->get('magic', array());
        if (empty($setting['disable_web_crontab'])) {
            $setting['disable_web_crontab'] = 1;
            $this->getSettingService()->set('magic', $setting);
        }
    }

    protected function getSettingService()
    {
        return $this->getServiceKernel()->createService('System:SettingService');
    }
}


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

namespace Universe
{
    using System.Runtime.InteropServices.WindowsRuntime;
    using System.Threading;

    using H3Control.Common;

    using Nancy;
    using Nancy.Bootstrapper;
    using Nancy.ViewEngines.Razor;

    public class UserAgentInfo
    {
        // 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; WOW64; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E; InfoPath.1)'
        // 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; WOW64; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E; InfoPath.1)'
        // 'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.204 Safari/534.16'
        // 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0'
        // 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'
        // 'Mozilla/5.0 (iPad; CPU OS 7_1_1 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D201 Safari/9537.53'
        // IE11: 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko'
        public readonly string UserAgent;

        public int Major { get; private set; }
        public int Minor { get; private set; }
        public BowserFamily Family { get; private set; }

        public UserAgentInfo(string userAgent)
        {
            if (userAgent == null)
                throw new ArgumentNullException("userAgent");

            if (userAgent.Length == 0)
                throw new ArgumentException("userAgent is expected", "userAgent");

            UserAgent = userAgent;

            // Do we throw exception?
            try
            {
                Parse();
            }
            catch (Exception ex)
            {
                Family = BowserFamily.Other;
                Major = Minor = 0;
                NiceTrace.Message("Failed to parse User-Agent '{0}'{1}{2}", UserAgent, Environment.NewLine, ex);
            }

            _IsMobile = new Lazy<bool>(GetIsMobile);
        }

        public bool Is_IE8_OrBelow
        {
            get { return Family == BowserFamily.IE && Major > 0 && Major <= 8; }
        }

        public override string ToString()
        {
            StringBuilder ret = new StringBuilder(Family.ToString());
            if (Major > 0)
            {
                ret.Append("/").Append(Major);
                if (Minor > 0)
                    ret.Append('.').Append(Minor);
            }

            return ret.ToString();
        }

        public bool IsMobile
        {
            get { return _IsMobile.Value; }
        }

        private readonly Lazy<bool> _IsMobile;

        bool GetIsMobile()
        {
            Func<string, bool> hasString = (arg) => UserAgent.IndexOf(arg, StringComparison.InvariantCultureIgnoreCase) >= 0;

            bool isAndroid = hasString(" Android ");
            bool isMobileAndroid = hasString("Mobile") && isAndroid;
            bool is_iOS = hasString("(iPad") || hasString("(iPod") || hasString("(iPhone");
            bool isWindowsPhone = hasString("Windows Phone");
            bool isOperaMobile = hasString("Opera Mobi");
            bool isMobileFirefox = hasString("Firefox") && (hasString("Mobile") || hasString("Tablet"));
            return isWindowsPhone || isMobileAndroid || is_iOS || isAndroid || isOperaMobile || isMobileFirefox;
        }

        private void Parse()
        {
            var probes = Probes;
            BowserFamily family = BowserFamily.Other;
            int major = 0;
            int minor = 0;
            foreach (var probe in probes)
            {
                int p = this.UserAgent.IndexOf(probe.Pattern);
                if (p >= 0)
                {
                    family = probe.Family;
                    if (TryGetVersionByRV(out major, out minor))
                        goto done;
                    if (FindNumber(UserAgent, p + probe.Pattern.Length + 1, out major, out minor))
                        goto done;
                }
            }

            return;

            done:
            Family = family;
            Major = major;
            Minor = minor;
        }

        bool TryGetVersionByRV(out int major, out int minor)
        {
            major = minor = 0;
            if (UserAgent == null)
                return false;

            var arg = " " + UserAgent + " ";
            var p1 = arg.IndexOf("rv:");
            if (p1 > 0)
            {
                if (FindNumber(arg, p1 + 3, out major, out minor))
                    return true;
            }

            return false;
        }

        bool FindNumber(string arg, int p, out int major, out int minor)
        {
            major = minor = 0;
            StringBuilder ret = new StringBuilder();
            for (int i = p; i < arg.Length; i++)
            {
                char c = arg[i];
                if ((c == '.' && ret.ToString().IndexOf(".") >=0 ) || (c >= '0' && c <= '9'))
                    ret.Append(c);
                else
                    break;
            }

            var rawVer = ret.ToString();
            if (rawVer.Length == 0) return false;
            var arr = rawVer.Split('.');
            if (arr.Length == 1)
            {
                if (!int.TryParse(arr[0], out major))
                {
                    major = 0;
                    return false;
                }
                else
                    return major > 0;
            }

            if (!int.TryParse(arr[0], out major) || !int.TryParse(arr[1], out minor))
            {
                major = minor = 0;
                return false;
            }

            return major > 0;
        }

        public enum BowserFamily
        {
            Other,
            Edge,
            IE,
            Firefox,
            Opera,
            Chrome,
            Safary,
        }

        private static readonly Probe[] Probes = new[]
        {
            new Probe("Edge", BowserFamily.Edge),
            new Probe("MSIE", BowserFamily.IE),
            new Probe("Trident", BowserFamily.IE),
            new Probe("Firefox", BowserFamily.Firefox),
            new Probe("Opera", BowserFamily.Opera),
            new Probe("OPR", BowserFamily.Opera),
            new Probe("Chrome", BowserFamily.Chrome),
            new Probe("Safari", BowserFamily.Safary),
        };

        class Probe
        {

            public string Pattern;
            public BowserFamily Family;

            public Probe(string pattern, BowserFamily family)
            {
                Pattern = pattern;
                Family = family;
            }
        }

    }

    public static class NancyUserAgentExtention
    {
        static ThreadLocal<string> _UserAgentFullName = new ThreadLocal<string>(() => null);

        public static void BindUserAgentInfo(this IPipelines applicationPipelines)
        {
            // return;
            applicationPipelines.BeforeRequest.AddItemToStartOfPipeline(delegate(NancyContext context)
            {
                var requestHeaders = context.Request.Headers;
                string raw = requestHeaders.UserAgent;
                var ua = raw;
                _UserAgentFullName.Value = ua == "" ? null : ua;
                FirstRound.Only("Catch User-Agent", RoundCounter.Twice, () =>
                {
                    NiceTrace.Message("Request by '{3}' for {1}{2}           {0}",
                        ua,
                        context.Request.Url,
                        Environment.NewLine,
                        context.GetUserAgent());
                });

                return null;
            });

        }

        // Html Helper
        public static UserAgentInfo GetUserAgent(this HtmlHelpers<dynamic> helpers, NancyRazorViewBase<dynamic> view)
        {
            return view.Context.GetUserAgent();
        }

        // Module
        // [Paranoja]
        public static UserAgentInfo GetUserAgent(this NancyContext nancyContext)
        {
            try
            {
                return new UserAgentInfo(nancyContext.Request.Headers.UserAgent);
            }
            catch (Exception)
            {
                return new UserAgentInfo(UserAgentInfo.BowserFamily.Other.ToString());
            }
        }
    }
}


text:
package org.atlasapi.system.bootstrap.workers;

import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.google.api.client.repackaged.com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.RateLimiter;
import com.metabroadcast.common.queue.Worker;
import com.metabroadcast.common.time.Timestamp;
import org.atlasapi.entity.Id;
import org.atlasapi.entity.util.Resolved;
import org.atlasapi.messaging.ResourceUpdatedMessage;
import org.atlasapi.organisation.Organisation;
import org.atlasapi.organisation.OrganisationResolver;
import org.atlasapi.organisation.OrganisationWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import static com.google.common.base.Preconditions.checkNotNull;

public class OrganisationBootstrapWorker implements Worker<ResourceUpdatedMessage> {

    private static final Logger LOG = LoggerFactory.getLogger(ContentBootstrapWorker.class);

    private final OrganisationResolver resolver;
    private final OrganisationWriter writer;

    private final Timer executionTimer;
    private final Meter messageReceivedMeter;
    private final Meter failureMeter;
    private final Timer latencyTimer;
    @Nullable private final RateLimiter rateLimiter;

    private OrganisationBootstrapWorker(
            OrganisationResolver resolver,
            OrganisationWriter writer,
            String metricPrefix,
            MetricRegistry metricRegistry,
            @Nullable RateLimiter rateLimiter
    ) {
        this.resolver = checkNotNull(resolver);
        this.writer = checkNotNull(writer);

        this.executionTimer = metricRegistry.timer(metricPrefix + "timer.execution");
        this.messageReceivedMeter = metricRegistry.meter(metricPrefix + "meter.received");
        this.failureMeter = metricRegistry.meter(metricPrefix + "meter.failure");
        this.latencyTimer = metricRegistry.timer(metricPrefix + "timer.latency");
        this.rateLimiter = rateLimiter;
        if (this.rateLimiter != null) {
            LOG.info("Limiting rate to a maximum of {} messages per second", this.rateLimiter.getRate());
        }
    }

    public static OrganisationBootstrapWorker create(
            OrganisationResolver resolver,
            OrganisationWriter writer,
            String metricPrefix,
            MetricRegistry metricRegistry,
            @Nullable RateLimiter rateLimiter
    ) {
        return new OrganisationBootstrapWorker(resolver, writer, metricPrefix, metricRegistry, rateLimiter);
    }

    @Override
    public void process(ResourceUpdatedMessage message) {
        if (rateLimiter != null) {
            rateLimiter.acquire();
        }
        messageReceivedMeter.mark();

        LOG.debug("Processing message on id {}, took: PT{}S, message: {}",
                message.getUpdatedResource().getId(),
                getTimeToProcessInMillis(message.getTimestamp()) / 1000L,
                message
        );

        Timer.Context time = executionTimer.time();

        try {
            Id contentId = message.getUpdatedResource().getId();
            Resolved<Organisation> content = Futures.get(
                    resolver.resolveIds(ImmutableList.of(contentId)),
                    ExecutionException.class
            );
            Organisation organisation = content.getResources().first().get();

            writer.write(organisation);

            latencyTimer.update(
                    getTimeToProcessInMillis(message.getTimestamp()),
                    TimeUnit.MILLISECONDS
            );
            LOG.debug("Bootstrapped organisation {}", organisation.toString());
        } catch (Exception e) {
            LOG.error(
                    "Failed to bootstrap organisation {} - {} {}",
                    message.getUpdatedResource(),
                    e,
                    Throwables
                            .getStackTraceAsString(e)
            );
            failureMeter.mark();
        } finally {
            time.stop();
        }
    }

    private long getTimeToProcessInMillis(Timestamp messageTimestamp) {
        return System.currentTimeMillis() - messageTimestamp.millis();
    }
}


text:
/*
Package CloudForest implements ensembles of decision trees for machine
learning in pure Go (golang to search engines). It allows for a number of related algorithms
for classification, regression, feature selection and structure analysis on heterogeneous
numerical/categorical data with missing values. These include:

	* Breiman and Cutler's Random Forest for Classification and Regression

	* Adaptive Boosting (AdaBoost) Classification

	* Gradiant Boosting Tree Regression

	* Entropy and Cost driven classification

	* L1 regression

	* Feature selection with artificial contrasts

	* Proximity and model structure analysis

	* Roughly balanced bagging for unbalanced classification

The API hasn't stabilized yet and may change rapidly. Tests and benchmarks have been performed
only on embargoed data sets and can not yet be released.

Library Documentation is in code and can be viewed with godoc or live at:
http://godoc.org/github.com/ryanbressler/CloudForest

Documentation of command line utilities and file formats can be found in README.md, which can be
viewed fromated on github:
http://github.com/ryanbressler/CloudForest

Pull requests and bug reports are welcome.

CloudForest was created by Ryan Bressler and is being developed in the Shumelivich Lab at
the Institute for Systems Biology for use on genomic/biomedical data with partial support
from The Cancer Genome Atlas and the Inova Translational Medicine Institute.

Goals

CloudForest is intended to provide fast, comprehensible building blocks that can
be used to implement ensembles of decision trees. CloudForest is written in Go to
allow a data scientist to develop and scale new models and analysis quickly instead
of having to modify complex legacy code.

Data structures and file formats are chosen with use in multi threaded and cluster
environments in mind.

Working with Trees

Go's support for function types is used to provide a interface to run code as data
is percolated through a tree. This method is flexible enough that it can extend the tree being
analyzed. Growing a decision tree using Breiman and Cutler's method can be done in an anonymous
function/closure passed to a tree's root node's Recurse method:

	t.Root.Recurse(func(n *Node, innercases []int) {

		if (2 * leafSize) <= len(innercases) {
			SampleFirstN(&candidates, mTry)
			best, impDec := fm.BestSplitter(target, innercases, candidates[:mTry], false, allocs)
			if best != nil && impDec > minImp {
				//not a leaf node so define the splitter and left and right nodes
				//so recursion will continue
				n.Splitter = best
				n.Pred = ""
				n.Left = new(Node)
				n.Right = new(Node)

				return
			}
		}

This allows a researcher to include whatever additional analysis they need (importance scores,
proximity etc) in tree growth. The same Recurse method can also be used to analyze existing forests
to tabulate scores or extract structure. Utilities like leafcount and errorrate use this
method to tabulate data about the tree in collection objects.

Stackable Interfaces

Decision tree's are grown with the goal of reducing "Impurity" which is usually defined as Gini
Impurity for categorical targets or mean squared error for numerical targets. CloudForest grows
trees against the Target interface which allows for alternative definitions of impurity. CloudForest
includes several alternative targets:

 EntropyTarget : For use in entropy minimizing classification
 RegretTarget  : For use in classification driven by differing costs in mis-categorization.
 L1Target      : For use in L1 norm error regression (which may be less sensitive to outliers).
 OrdinalTarget : For ordinal regression

Additional targets can be stacked on top of these target to add boosting functionality:
 GradBoostTarget : For Gradient Boosting Regression
 AdaBoostTarget  : For Adaptive Boosting Classification

Efficient Splitting

Repeatedly splitting the data and searching for the best split at each node of a decision tree
are the most computationally intensive parts of decision tree learning and CloudForest includes
optimized code to perform these tasks.

Go's slices are used extensively in CloudForest to make it simple to interact with optimized code.
Many previous implementations of Random Forest have avoided reallocation by reordering data in
place and keeping track of start and end indexes. In go, slices pointing at the same underlying
arrays make this sort of optimization transparent. For example a function like:

	func(s *Splitter) SplitInPlace(fm *FeatureMatrix, cases []int) (l []int, r []int)

can return left and right slices that point to the same underlying array as the original
slice of cases but these slices should not have their values changed.

Functions used while searching for the best split also accepts pointers to reusable slices and
structs to maximize speed by keeping memory allocations to a minimum. BestSplitAllocs contains
pointers to these items and its use can be seen in functions like:

	func (fm *FeatureMatrix) BestSplitter(target Target,
		cases []int,
		candidates []int,
		extraRandom bool,
		allocs *BestSplitAllocs) (s *Splitter, impurityDecrease float64)

	func (f *Feature) BestSplit(target Target,
		cases *[]int,
		parentImp float64,
		randomSplit bool,
		allocs *BestSplitAllocs) (bestNum float64, bestCat int, bestBigCat *big.Int, impurityDecrease float64)

For categorical predictors, BestSplit will also attempt to intelligently choose between 4
different implementations depending on user input and the number of categories.
These include exhaustive, random, and iterative searches for the best combination of categories
implemented with bitwise operations against int and big.Int. See BestCatSplit, BestCatSplitIter,
BestCatSplitBig and BestCatSplitIterBig.

All numerical predictors are handled by BestNumSplit which
relies on go's sorting package.

Parallelism and Scaling

Training a Random forest is an inherently parallel process and CloudForest is designed
to allow parallel implementations that can tackle large problems while keeping memory
usage low by writing and using data structures directly to/from disk.

Trees can be grown in separate go routines. The growforest utility provides an example
of this that uses go routines and channels to grow trees in parallel and write trees
to disk as the are finished by the "worker" go routines. The few summary statistics
like mean impurity decrease per feature (importance) can be calculated using thread
safe data structures like RunningMean.

Trees can also be grown on separate machines. The .sf stochastic forest format
allows several small forests to be combined by concatenation and the ForestReader
and ForestWriter structs allow these forests to be accessed tree by tree (or even node
by node) from disk.

For data sets that are too big to fit in memory on a single machine Tree.Grow and
FeatureMatrix.BestSplitter can be reimplemented to load candidate features from disk,
distributed database etc.

Missing Values

By default cloud forest uses a fast heuristic for missing values. When proposing a split on a feature
with missing data the missing cases are removed and the impurity value is corrected to use three way impurity
which reduces the bias towards features with lots of missing data:

								I(split) = p(l)I(l)+p(r)I(r)+p(m)I(m)

Missing values in the target variable are left out of impurity calculations.

This provided generally good results at a fraction of the computational costs of imputing data.

Optionally, feature.ImputeMissing or featurematrixImputeMissing can be called before forest growth
to impute missing values to the feature mean/mode which Brieman [2] suggests as a fast method for
imputing values.

This forest could also be analyzed for proximity (using leafcount or tree.GetLeaves) to do the
more accurate proximity weighted imputation Brieman describes.

Experimental support is provided for 3 way splitting which splits missing cases onto a third branch.
[2] This has so far yielded mixed results in testing.

At some point in the future support may be added for local imputing of missing values during tree growth
as described in [3]

[1] http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm#missing1

[2] https://code.google.com/p/rf-ace/

[3] http://projecteuclid.org/DPubS?verb=Display&version=1.0&service=UI&handle=euclid.aoas/1223908043&page=record

Main Structures

In CloudForest data is stored using the FeatureMatrix struct which contains Features.

The Feature struct  implements storage and methods for both categorical and numerical data and
calculations of impurity etc and the search for the best split.

The Target interface abstracts the methods of Feature that are needed for a feature to be predictable.
This allows for the implementation of alternative types of regression and classification.

Trees are built from Nodes and Splitters and stored within a Forest. Tree has a Grow
implements Brieman and Cutler's method (see extract above) for growing a tree. A GrowForest
method is also provided that implements the rest of the method including sampling cases
but it may be faster to grow the forest to disk as in the growforest utility.

Prediction and Voting is done using Tree.Vote and CatBallotBox and NumBallotBox which implement the
VoteTallyer interface.

*/
package CloudForest


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<title>Shake progress diagnostic</title>

Shake Progress Analysis

    The red line represents the real performance, with time to completion on the X axis and predicted time on the Y axis. A perfect progress prediction would follow the gray line.

Loading...


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syll. fung. (Abellini) 5: 375 (1887)

#### Original name
Agaricus caesiozonatus Rabenh.

### Remarks
null


text:
package Game;

import networking.mediator.HostMediator;
import networking.mediator.IMediator;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HostGame implements IGame {

    private static final Logger log = Logger.getLogger(HostGame.class.getName());
    private List<Player> players;
    private List<Team> teams;
    private List<Panel> panels;
    private List<Instruction> instructions;
    private IMediator mediator;
    private Thread mediatorThread;

    public HostGame() {
        this(8085);
    }

    public HostGame(int port) {
        players = new ArrayList<>();
        teams = new ArrayList<>();
        panels = new ArrayList<>();
        instructions = new ArrayList<Instruction>();

        loadPanelsFromFile();

        mediator = new HostMediator(this, port);

        mediatorThread = mediator.mediate();
    }

    public List<Player> getPlayers() {
        return this.players;
    }

    public List<Instruction> getInstructions() {
        return instructions;
    }

    public synchronized List<Team> getTeams() {
        return this.teams;
    }

    /**
     * Gets all panels of the game
     * These are all the panels loaded from the CSV
     * Author Kaj
     *
     * @return the list of panels
     */
    public List<Panel> getPanels() {
        return this.panels;
    }

    /**
     * Create a team and add this team to the teams in the game
     * Author Frank Hartman
     *
     * @param name the name of the team
     */
    @Override
    public synchronized Team createTeam(String name) throws UnsupportedOperationException {
        //check if name is empty
        if (name == null || name.isEmpty()) {
            throw new UnsupportedOperationException("name of the team is empty");
        }
        Team team = new Team(name);
        // Add the team to the teams in the game
        teams.add(team);
        log.log(Level.INFO, "team: " + name + " added to list teams");
        return team;
    }

    /**
     * Author Qun
     * made this method so when you want to change the teamname
     * it resets the teams so it can create new teams
     */
    public void resetTeamName() {
        teams.clear();
    }

    /**
     * Create a player and add this player to the players in the game
     * Author Frank Hartman
     *
     * @param username The username of the player
     * @param ip       The ip address of the player
     */
    @Override
    public synchronized Player createPlayer(String username, String ip) {
        //check if username is empty
        if (username == null || username.isEmpty()) {
            throw new UnsupportedOperationException("name of the user is empty");
        }
        //check if ip is empty
        if (ip == null || ip.isEmpty()) {
            throw new UnsupportedOperationException("ip address the is empty");
        }
        Player player = new Player(username, ip);
        autoAssignTeam(player);
        // Add the player to the players in the game
        players.add(player);
        System.out.println(username + "  " + ip);
        log.log(Level.INFO, "player: " + username + " added to list players");
        return player;
    }

    /**
     * Assign a player to a team in the game and removes the player from his current team if he is in one
     *
     * @param player The player that wants to be assigned to a team
     * @param team   The team that the player wants to join
     */
    @Override
    public synchronized void assignTeam(Player player, Team team) {
        log.log(Level.INFO, "assigning player: {0} to team started", player.getUsername());
        for (Team gameTeam : teams) {
            if (gameTeam.getName().equals(team.getName())) {
                team.addPlayer(player);
            } else {
                gameTeam.removePlayer(player);
            }
        }
        log.log(Level.INFO, "assign player to team ended, Player assigned to team: {0}", team.getName());
    }

    /**
     * Give the loaded panels to every team in the game
     * author Frank Hartman
     *
     * @return The list of panels in the game
     */
    private java.util.List<Panel> generatePanels() {
        for (Team team : teams) {
            team.generatePanels(panels);
        }
        return panels;
    }

    /**
     * Load panels from CSV
     *
     * @return true if panels are correctly loaded
     */
    private boolean loadPanelsFromFile() {
        log.log(Level.INFO, "Started loading panels");

        try (InputStream location = this.getClass().getClassLoader().getResourceAsStream("panels.csv")) {
            String full = IOUtils.toString(location);
            log.log(Level.INFO, "loaded panels from {0}", location.toString());

            // go over each line
            for (String s : full.split("\n")) {
                // If we start with a hashtag the line is commented and we skip it
                if (s.startsWith("#") || s.equals("\r"))
                    continue;

                // get the individual lines
                String[] split = s.split(",");

                // Parse the strings
                int id = Integer.parseInt(split[0].trim());
                int type = Integer.parseInt(split[1].trim());
                String text = split[2];
                int min = Integer.parseInt(split[3].trim());
                int max = Integer.parseInt(split[4].trim());

                // Create the panels
                Panel panel = new Panel(id, min, max, text, PanelTypeEnum.values()[type]);

                panels.add(panel);
                log.log(Level.FINER, "Added panel with text {0}", panel.getText());
            }
            log.log(Level.INFO, "There are {0} panels added from the CSV file", String.valueOf(panels.size()));
        } catch (IOException e) {
            e.printStackTrace();
            log.log(Level.SEVERE, e.toString(), e);
        }

        return panels.size() > 0;
    }

    /**
     * Resets lives, time and instructions for all teams.
     * Author Frank Hartman
     *
     * @param hard Indicates that this is a hard reset. Destroy all data
     */
    @Override()
    public void reset(boolean hard) {
        log.log(Level.INFO, "Resetting teams");
        for (Team team : teams) {
            System.out.println("Reseting teamssize: " + teams.size());
            team.reset(hard);
        }
    }

    /**
     * Start a new round by loading all the panels from the CSV file and give this panels to the team
     * The team will the distribute the panels to the players
     * Author Kamil Wasylkiewicz
     *
     * @return
     */
    @Override
    public HostGame startRound() {

        if (players.size() <= 0) {
            return null;
        }

        for (Player player : players) {
            if (!player.getPlayerStatus())
                return null;
        }

        // iterate over all teams
        for (Team team : teams) {
            // give a team first a hard reset
            team.reset(false);
            // let the team give their players new panels
            team.generatePanels(panels);
        }
        log.log(Level.INFO, "Round is started");
        return this;
    }

    /**
     * this method will first check if the given panel matches one of the active instructions for the team of the player
     * this will be done with te validateInstruction method
     * If the instruction was correct a new instruction must be given to the player that had the active instruction.
     * Author Kaj
     * Author Frank Hartman
     *
     * @param player player that pressed a panel
     * @param panel  The pressed panel
     * @return true if the pressed panel was correct
     */
    @Override
    public synchronized Instruction processPanel(Player player, Panel panel) {
        Instruction currentInstruction;
        Instruction newInstruction = null;
        //check if the pressed panel was from an active instruction
        currentInstruction = validateInstruction(player, panel);
        if (currentInstruction != null) {
            //check if there is a win streak
            changeTimeForTeam(player.getTeam(), 0);
            //list of correct instructions
            currentInstruction.setWasExecutedCorrectly(true);
            instructions.add(currentInstruction);
            //gives the player that had the instruction (not necessarily the one that pressed the panel) a new instruction
            newInstruction = player.getTeam().generateInstructionForPlayer(currentInstruction.getPlayer());
            return newInstruction;
        } else {
            changeTimeForTeam(player.getTeam(), -1);
        }

        return newInstruction;// != null;
    }

    /**
     * Check if the game has ended
     * The game has been ended when all the teams, except for one have a zero amount of lives
     * Author Frank Hartman
     *
     * @return true if the game has ended
     */
    @Override()
    public boolean hasGameEnded() {
        log.log(Level.INFO, "Check if the game has ended");
        int count = 0;

        for (Team team : teams) {
            if (team.getLives() <= 0)
                count++;
        }

        return count >= teams.size() - 1;

    }

    /**
     * Author Kamil Wasylkiewicz
     * Author Frank Hartman
     * Takes an instruction and marks it as invalid, thus generating a new instruction for a player
     *
     * @param instruction The instruction that needs to be marked as invalid
     * @return true if instruction belongs to player and generates a new instruction
     */
    @Override
    public synchronized Instruction registerInvalidInstruction(Instruction instruction) {
        for (Team team : teams) {
            for (Player player : team.getPlayers()) {
                if (player.getActiveInstruction().getPanel().getId() == instruction.getPanel().getId()) {
                    instruction = player.getActiveInstruction();
                }
            }
        }
        log.log(Level.INFO, "registering invalid Instruction for " + instruction.getPlayer().getUsername() + " ,panel name " + instruction.getPanel().getText());
        Player player = instruction.getPlayer();
        Team team = player.getTeam();
        // The instruction was not executed correctly and will be set to false
        instruction.setWasExecutedCorrectly(false);
        instructions.add(instruction);
        changeTimeForTeam(team, -1);
        // Generate new instruction for the player
        return team.generateInstructionForPlayer(player);
    }

    /**
     * Takes an instruction and asserts whether the click was a valid instruction in your team.
     * If correct, true will be returned
     * Author Kaj
     *
     * @param player Player that clicked on a panel
     * @param panel  Panel control that was clicked
     * @return instruction that was correctly performed, else null
     */
    private synchronized Instruction validateInstruction(Player player, Panel panel) {
        log.log(Level.INFO, "validating instruction for panel: {0} started", panel.getText());
        return player.getTeam().validateInstruction(panel);
    }

    /**
     * Change the time for a team and check the amount of time
     * Author Frank Hartman
     *
     * @param team The team that gets a different amount of time
     * @param time The time amount of time
     * @return true if the given team lost a life
     */
    private synchronized boolean changeTimeForTeam(Team team, int time) {
        log.log(Level.INFO, "staring chang time for team");
        team.changeTime(time);
        //win streak of 3, your team gets one second plus
        if (team.getScore() % 3 == 0 && team.getTime() < 9 && team.getScore() != 0) {
            team.changeTime(1);
            log.log(Level.INFO, "win streak of 3");
        }
        //win streak of 5, every other team gets minus one second
        if (team.getScore() % 5 == 0 && team.getScore() != 0) {
            //for all other teams
            for (Team team1 : teams) {
                if (!team1.equals(team)) {
                    team1.changeTime(-1);
                }
            }
            log.log(Level.INFO, "win streak of 5");
        }

        for (Team team1 : teams) {
            if (team1.getTime() <= 3) {
                team1.changeLives(-1);
                // Start a new round when the
                startRound();
                return true;
            }
        }
        return false;
    }

    /**
     * Gives a list with the score of every player in the game
     * Author Frank Hartman
     *
     * @return A list with the players and there score
     */
    public List<String> getScoreboard() {
        List<String> scoreboard = new ArrayList<>();

        for (Player player : players) {
            int playerScore = 0;
            if (instructions.isEmpty()) {
                scoreboard.add("Team: " + player.getTeam().getName());
                scoreboard.add(player.getUsername() + " Score: " + playerScore);
                return scoreboard;
            }
            for (Instruction instruction : instructions) {
                // Increase the score of the player if the instruction was executed correctly
                if (instruction.getPlayer().equals(player) && instruction.getWasExecutedCorrectly())
                    playerScore++;
                else if (instruction.getPlayer().equals(player) && !instruction.getWasExecutedCorrectly())
                    playerScore--;
            }
            // Add the team with the player and his score to the list
            scoreboard.add("Team: " + player.getTeam().getName() + " Name- " + player.getUsername() + " Score: " + playerScore);
        }

        return scoreboard;
    }

    public void autoAssignTeam(Player player) {
        if (teams.get(0).getPlayers().size() < teams.get(1).getPlayers().size()) {
            teams.get(0).addPlayer(player);
            for (Player p : players) {
                if (p == player) {
                    p.setTeam(teams.get(0));
                }
            }
        } else {
            teams.get(1).addPlayer(player);
            for (Player p : players) {
                if (p == player) {
                    p.setTeam(teams.get(1));
                }
            }
        }
    }

    //gets player by IP
    public Player getPlayer(String ipadress) {
        Player returnPlayer = null;
        for (Player player : players) {
            if (player.getIp().equals(ipadress))
                returnPlayer = player;
        }
        return returnPlayer;
    }
}


text:
'use strict';

var Tab = require('./tab');

module.exports = Tab.extend({
  tabIndex: 0,

  formFormElement: function() {
    return element(by.css('.form-pane'));
  },

  genericAddVariableButton: function() {
    return this.formFormElement().element(by.css('[ng-click="addVariable()"]'));
  },

  genericLoadVariablesButton: function() {
    return this.formFormElement().element(
      by.css('[ng-click="loadVariables()"]')
    );
  },

  genericLoadVariables: function() {
    this.genericLoadVariablesButton().click();
  },

  completeButton: function() {
    return this.formFormElement().element(by.css('[ng-click="complete()"]'));
  }
});