text:
package com.kaeruct.glxy.actor;

import java.util.Iterator;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.Texture.TextureWrap;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.input.GestureDetector;
import com.badlogic.gdx.input.GestureDetector.GestureListener;
import com.badlogic.gdx.math.Circle;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.TimeUtils;
import com.kaeruct.glxy.data.ImageCache;
import com.kaeruct.glxy.model.Particle;
import com.kaeruct.glxy.model.Settings;
import com.kaeruct.glxy.model.Settings.Setting;

public class Universe extends Actor {
    final OrthographicCamera camera;
    final ShapeRenderer sr;
    final Particle protoParticle;
    final Array<Particle> particles;
    TrailParticleManager trailParticles;
    final Vector3 initPos, touchPos, cinitPos, ctouchPos;
    final CameraController controller;
    public final GestureDetector gestureDetector;

    private Particle followedParticle;

    public Settings settings;
    boolean addedParticle;
    public boolean panning;
    public boolean inMenu;

    public final float minRadius = 5;
    public final float maxRadius = 80;
    public final float minZoom = 0.1f;
    public final float maxZoom = 16;
    final float G = 0.1f; // gravity constant
    final float sG = G * 0.5f; // multiplier for slingshot
    final int maxTrails = 500; // max trails for all particles
    private Rectangle bottomBar = null;
    private Texture texture;
    private Texture bg;
    private Matrix4 m4;
    private long start = TimeUtils.millis();
    private int w;
    private int h;

    class CameraController implements GestureListener {
        float initialScale = 1;
        float px, py;

        public boolean touchDown(float x, float y, int pointer, int button) {
            initialScale = camera.zoom;
            return false;
        }

        private Particle getTouchedParticle(float x, float y) {
            Circle tapCircle = new Circle();
            for (Particle p : particles) {
                // check a slightly bigger area to allow for finger inaccuracy
                tapCircle.set(p.x, p.y, p.radius * 1.7f);
                if (tapCircle.contains(x, y)) {
                    return p;
                }
            }
            return null;
        }

        private void singleTap(float tapX, float tapY) {
            if (touchBottomBar(tapX, tapY))
                return;

            touchPos.set(tapX, tapY, 0);
            camera.unproject(touchPos);

            protoParticle.dragged = false;
            protoParticle.vel(new Vector3(0, 0, 0));
            protoParticle.position(touchPos);
            addParticle();
        }

        @Override
        public boolean tap(float x, float y, int count, int button) {
            touchPos.set(x, y, 0);
            camera.unproject(touchPos);

            Particle p = getTouchedParticle(touchPos.x, touchPos.y);

            if (panning) {
                if (p == followedParticle) {
                    // stop following the followed particle if it was tapped
                    followedParticle = null;
                } else if (p != null) {
                    // follow a new particle
                    followedParticle = p;
                }
                return true;
            }

            if (followedParticle == null || p == null) {
                // single tap that wasn't either on another particle or the
                // one already being followed
                singleTap(x, y);
            }

            return true;
        }

        @Override
        public boolean longPress(float x, float y) {
            return false;
        }

        @Override
        public boolean fling(float velocityX, float velocityY, int button) {
            return false;
        }

        @Override
        public boolean pan(float x, float y, float deltaX, float deltaY) {
            if (panning) {
                camera.position.add(-deltaX * camera.zoom, -deltaY
                        * camera.zoom, 0);
            }

            return false;
        }

        @Override
        public boolean panStop(float v, float v1, int i, int i1) {
            return false;
        }

        @Override
        public boolean zoom(float originalDistance, float currentDistance) {
            float ratio = originalDistance / currentDistance;
            float z = initialScale * ratio;

            if (z <= maxZoom && z >= minZoom) {
                float zx = (px - getWidth() / 2) * (camera.zoom - z), zy = (py - getHeight() / 2)
                        * (camera.zoom - z);

                camera.translate(zx, zy);
                px = zx;
                py = zy;
                camera.zoom = z;
            }
            return false;
        }

        @Override
        public boolean pinch(Vector2 initialFirstPointer,
                Vector2 initialSecondPointer, Vector2 firstPointer,
                Vector2 secondPointer) {

            px = (initialFirstPointer.x + initialSecondPointer.x) / 2;
            py = (initialFirstPointer.y + initialSecondPointer.y) / 2;
            return false;
        }

        @Override
        public void pinchStop() {

        }

        public void update() {
            if (followedParticle != null) {
                camera.position.set(followedParticle.x, followedParticle.y, 0);
            }
        }
    }

    public Universe() {
        addedParticle = true;
        panning = false;
        particles = new Array<>();
        sr = new ShapeRenderer();
        touchPos = new Vector3();
        initPos = new Vector3();
        ctouchPos = new Vector3();
        cinitPos = new Vector3();

        protoParticle = (new Particle()).radius(minRadius);
        camera = new OrthographicCamera();

        controller = new CameraController();
        gestureDetector = new GestureDetector(20, 0.5f, 0.5f, 0.15f, controller);
        bottomBar = new Rectangle();

        settings = new Settings();
        w = Gdx.graphics.getWidth();
        h = Gdx.graphics.getHeight();

        resize();
    }

    public void setBottomBar(float w, float h) {
        bottomBar.set(0, 0, w, h);
    }

    public void resize() {
        camera.setToOrtho(true, w, h);
        camera.position.set(w / 2f, h / 2f, 0);

        ImageCache.load();
        texture = ImageCache.getTexture("circle").getTexture();
        texture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);
        trailParticles = new TrailParticleManager(maxTrails, texture);

        bg = new Texture(Gdx.files.internal("data/bg.png"));
        bg.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);
    }

    public void setParticleRadius(float r) {
        protoParticle.radius = r;
    }

    @Override
    public void act(float delta) {
        manageInput();

        if (!settings.get(Setting.PAUSED)) {
            updateParticles();
        }
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        controller.update();
        camera.update();

        if (m4 == null) {
            m4 = batch.getProjectionMatrix().cpy();
        }

        // draw background
        batch.draw(bg, 0, 0, (int)Math.floor(camera.position.x/camera.zoom), (int)Math.floor(camera.position.y/camera.zoom), w, h);

        // draw particles and trails
        batch.setProjectionMatrix(camera.combined);

        renderParticles(batch);
        batch.end();

        // draw black bar on the bottom
        Gdx.gl.glEnable(GL20.GL_BLEND);
        Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
        sr.begin(ShapeType.Filled);
        sr.setColor(0f, 0f, 0f, 0.6f);
        sr.rect(0, 0, bottomBar.width, bottomBar.height);
        sr.end();
        Gdx.gl.glDisable(GL20.GL_BLEND);

        if (!panning && protoParticle.dragged) {
            // draw "slingshot" line

             sr.begin(ShapeType.Line);
             sr.setColor(Color.LIGHT_GRAY);
             float yoff = getTop();

             sr.line(cinitPos.x,
             yoff - cinitPos.y,
             ctouchPos.x,
             yoff - ctouchPos.y);
             sr.end();
        }
        batch.setProjectionMatrix(m4);
        batch.begin();
    }

    public void manageInput() {
        if (panning || inMenu)
            return;

        if (Gdx.input.isTouched(0) && !Gdx.input.isTouched(1)
                && !Gdx.input.justTouched() && // only one finger is touching
                !touchBottomBar(Gdx.input.getX(0), Gdx.input.getY(0))) {

            touchPos.set(Gdx.input.getX(0), Gdx.input.getY(0), 0);
            ctouchPos.set(touchPos);

            camera.unproject(touchPos);
            addedParticle = false;

            if (!protoParticle.dragged) {
                protoParticle.stop();
                protoParticle.dragged = true;
                initPos.set(touchPos);
                cinitPos.set(ctouchPos);
            }

            protoParticle.position(touchPos);
        } else if (!addedParticle) {
            if (protoParticle.dragged) {
                protoParticle.dragged = false;
                Vector3 vel = initPos.sub(touchPos).scl(sG);
                protoParticle.vel(vel);
                protoParticle.position(touchPos);
            }
            addParticle();
        }
    }

    private boolean touchBottomBar(float x, float y) {
        return bottomBar.contains(x, Gdx.graphics.getHeight() - y);
    }

    private void updateParticles() {
        Iterator<Particle> it;
        for (int i = 0; i < particles.size; i++) {
            Particle p = particles.get(i);
            if (p.dead)
                continue;

            for (int j = 0; j < particles.size; j++) {
                Particle p2 = particles.get(j);
                if (p2.dead || i == j)
                    continue;

                float dx = p2.x - p.x;
                float dy = p2.y - p.y;
                float d = (float) Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
                if (d == 0)
                    d = (float) 0.001;

                if (p.collidesWith(p2)) {
                    if (settings.get(Setting.COLLISION)) {
                        // collision
                        float mtd = 2 * (p.radius + p2.radius - d) / d;

                        p2.inc(dx * mtd / p2.radius, dy * mtd / p2.radius);
                        p.inc(-dx * mtd / p.radius, -dy * mtd / p.radius);

                        p2.dx += dx * mtd / p2.mass;
                        p2.dy += dy * mtd / p2.mass;
                        p.dx -= dx * mtd / p.mass;
                        p.dy -= dy * mtd / p.mass;

                    } else {
                        Particle bigger = p.radius >= p2.radius ? p : p2, smaller = p.radius < p2.radius ? p
                                : p2;

                        bigger.radius((float) (p2.radius + Math
                                .sqrt(p.radius / 2)));
                        smaller.kill();

                        if (smaller == followedParticle) {
                            followedParticle = bigger;
                        }

                        if (p2 == smaller)
                            break;
                    }
                } else {
                    // "gravity"
                    float force = (float) (G * p.mass * p2.mass / Math
                            .pow(d, 2));
                    float fscale = force / d;
                    p.dx += fscale * dx / p.mass;
                    p.dy += fscale * dy / p.mass;
                }
            }
        }

        it = particles.iterator();
        while (it.hasNext()) {
            Particle p = it.next();
            if (!p.update()) {
                it.remove();
                fire(new ChangeEvent());
            }
        }
    }

    private void renderParticles(Batch batch) {
        if (followedParticle != null && !followedParticle.dead) {
            float r = 10f;
            // draw red circle around followed particle
            batch.setColor(0.9f, 0.2f, 0.2f, 1);
            batch.draw(
                texture,
                followedParticle.x - followedParticle.radius - r/2,
                followedParticle.y - followedParticle.radius - r/2,
                followedParticle.radius * 2 + r,
                followedParticle.radius * 2 + r
            );
        }

        for (Particle p : particles) {
            Color c = p.color;
            if (settings.get(Setting.TRAILS) && !settings.get(Setting.PAUSED)) {
                if (Math.abs(p.x - p.oldx) > 0.2
                        || Math.abs(p.y - p.oldy) > 0.2) {
                    trailParticles.add(p.x, p.y, p.radius, c);
                }
            }
            batch.setColor(c);
            batch.draw(texture, p.x - p.radius, p.y - p.radius, p.radius * 2,
                    p.radius * 2);
        }

        if (settings.get(Setting.TRAILS)) {
            trailParticles.render(batch, settings.get(Setting.PAUSED));
        }
    }

    private void addParticle() {
        long diff = TimeUtils.timeSinceMillis(start);
        boolean skipParticleAdd = diff < 250;

        if (skipParticleAdd) return; // avoid adding too fast
        if (Gdx.input.isTouched(0)) return; // do not add if finger is still down

        Particle p = new Particle(protoParticle);
        particles.add(p);
        addedParticle = true;
        start = TimeUtils.millis();

        protoParticle.vel(new Vector3(0, 0, 0)); // reset protoParticle vel

        fire(new ChangeEvent());
    }

    public void clearParticles() {
        particles.clear();
        clearTrails();
        followedParticle = null;

        fire(new ChangeEvent());
    }

    public void clearTrails() {
        trailParticles.clear();
    }

    public int getParticleCount() {
        return particles.size;
    }

    public void dispose() {
        sr.dispose();
    }

    public void resetZoom() {
        camera.zoom = 1;
    }
}


text:
/*global angular */

'use strict';

var angular = require('angular');

describe('Unit: Constants', function() {

  var constants;

  beforeEach(function() {
    // instantiate the app module
    angular.mock.module('app');

    // mock the directive
    angular.mock.inject(function(AppSettings) {
      constants = AppSettings;
    });
  });

  it('should exist', function() {
    expect(constants).toBeDefined();
  });

  xit('should have an application name', function() {
    expect(constants.appTitle).toEqual('Example Application');
  });

});

redpajama_set_name: RedPajamaGithub


text:
<?php namespace Skovachev\Fakefactory\Model;

class Reflector
{
    public function instantiate()
    {
        $args = func_get_args();
        $class = array_shift($args);

        $reflection = new \ReflectionClass($class);
        $instance = $reflection->newInstanceArgs($args);

        return $instance;
    }

    public function methodExists($object, $method)
    {
        return method_exists($object, $method);
    }

    public function isModel($object)
    {
        return $object instanceof \Illuminate\Database\Eloquent\Model;
    }

    public function isRelation($object)
    {
        return $object instanceof \Illuminate\Database\Eloquent\Relations\Relation;
    }

    public function getClass($object)
    {
        return get_class($object);
    }
}


text:
package jp.dcworks.test.entity;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * サンプルAPIテスト用レスポンスパラメータクラス。
 * @author tomo-sato
 */
public class SampleResponse extends AppResponse {

	/** レスポンス:トークン */
	public String token;

	/**
	 * デフォルトコンストラクタ。
	 */
	public SampleResponse() {}

	/**
	 * コンストラクタ。
	 * @param result 結果
	 */
	public SampleResponse(Integer result) {
		this.result = result;
	}

	/**
	 * レスポンスマッピング処理。
	 * @param json レスポンスjson
	 * @return レスポンスマッピングオブジェクト
	 */
	public static SampleResponse parseResponse(String json) {
		SampleResponse res = null;
		try {
			ObjectMapper mapper = new ObjectMapper();
			res = mapper.readValue(json, SampleResponse.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return res;
	}
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.lachesis.mnisqm.module.event.dao.EventReportMapper" >
  <resultMap id="BaseResultMap" type="com.lachesis.mnisqm.module.event.domain.EventReport" >
    <id column="SEQ_ID" property="seqId" jdbcType="BIGINT" />
    <result column="REPORT_CODE" property="reportCode" jdbcType="VARCHAR" />
    <result column="DEPT_CODE" property="deptCode" jdbcType="VARCHAR" />
    <result column="DEPT_NAME" property="deptName" jdbcType="VARCHAR" />
    <result column="DAMAGE_LEVEL" property="damageLevel" jdbcType="VARCHAR" />
    <result column="DAMAGE_REMARK" property="damageRemark" jdbcType="VARCHAR" />
    <result column="EVENT_TIME" property="eventTime" jdbcType="TIMESTAMP" />
    <result column="EVENT_TYPE_CODE" property="eventTypeCode" jdbcType="VARCHAR" />
    <result column="EVENT_TYPE_NAME" property="eventTypeName" jdbcType="VARCHAR" />
    <result column="STATUS" property="status" jdbcType="CHAR" />
    <result column="USER_CODE" property="userCode" jdbcType="VARCHAR" />
    <result column="USER_NAME" property="userName" jdbcType="VARCHAR" />
    <result column="USER_ROLE" property="userRole" jdbcType="VARCHAR" />
    <result column="PATIENT_BED_NO" property="patientBedNo" jdbcType="VARCHAR" />
    <result column="PATIENT_NAME" property="patientName" jdbcType="VARCHAR" />
    <result column="PATIENT_GENDER" property="patientGender" jdbcType="CHAR" />
    <result column="PATIENT_AGE" property="patientAge" jdbcType="VARCHAR" />
    <result column="PATIENT_HOSP_NO" property="patientHospNo" jdbcType="VARCHAR" />
    <result column="PATIENT_IN_DATE" property="patientInDate" jdbcType="TIMESTAMP" />
    <result column="PATIENT_DIAGNOSE" property="patientDiagnose" jdbcType="VARCHAR" />
    <result column="PATIENT_OTHER" property="patientOther" jdbcType="VARCHAR" />
    <result column="EVENT_DESCRIBE" property="eventDescribe" jdbcType="VARCHAR" />
    <result column="CREATE_PERSON" property="createPerson" jdbcType="VARCHAR" />
    <result column="UPDATE_PERSON" property="updatePerson" jdbcType="VARCHAR" />
    <result column="TASK_CODE" property="taskCode" jdbcType="VARCHAR" />
  </resultMap>
  <!-- 逻辑删除 -->
  <update id="deleteByPrimaryKey" parameterType="EventReport" >
    update EVENT_REPORT
    set
      STATUS = #{status,jdbcType=CHAR},
      UPDATE_TIME = GETDATE(),
      UPDATE_PERSON = #{updatePerson,jdbcType=VARCHAR}
    where SEQ_ID = #{seqId,jdbcType=BIGINT}
  </update>
  <!-- 数据插入-->
  <insert id="insert" parameterType="EventReport" >
    insert into EVENT_REPORT (REPORT_CODE, DEPT_CODE,
      DEPT_NAME, DAMAGE_LEVEL, DAMAGE_REMARK,
      EVENT_TIME, EVENT_TYPE_CODE, EVENT_TYPE_NAME,
      STATUS, USER_CODE, USER_NAME,
      USER_ROLE, PATIENT_BED_NO, PATIENT_NAME,
      PATIENT_GENDER, PATIENT_AGE, PATIENT_HOSP_NO,
      PATIENT_IN_DATE, PATIENT_DIAGNOSE, PATIENT_OTHER,
      EVENT_DESCRIBE, CREATE_TIME, CREATE_PERSON,
      UPDATE_TIME, UPDATE_PERSON,TASK_CODE)
    values (#{reportCode,jdbcType=VARCHAR}, #{deptCode,jdbcType=VARCHAR},
      #{deptName,jdbcType=VARCHAR}, #{damageLevel,jdbcType=VARCHAR}, #{damageRemark,jdbcType=VARCHAR},
      #{eventTime,jdbcType=VARCHAR}, #{eventTypeCode,jdbcType=VARCHAR}, #{eventTypeName,jdbcType=VARCHAR},
      #{status,jdbcType=CHAR}, #{userCode,jdbcType=VARCHAR}, #{userName,jdbcType=VARCHAR},
      #{userRole,jdbcType=VARCHAR}, #{patientBedNo,jdbcType=VARCHAR}, #{patientName,jdbcType=VARCHAR},
      #{patientGender,jdbcType=CHAR}, #{patientAge,jdbcType=VARCHAR}, #{patientHospNo,jdbcType=VARCHAR},
      #{patientInDate,jdbcType=VARCHAR}, #{patientDiagnose,jdbcType=VARCHAR}, #{patientOther,jdbcType=VARCHAR},
      #{eventDescribe,jdbcType=VARCHAR}, GETDATE(), #{createPerson,jdbcType=VARCHAR},
      GETDATE(), #{updatePerson,jdbcType=VARCHAR},#{taskCode,jdbcType=VARCHAR})
  </insert>
  <update id="updateByPrimaryKey" parameterType="EventReport" >
    update EVENT_REPORT
    set REPORT_CODE = #{reportCode,jdbcType=VARCHAR},
      DEPT_CODE = #{deptCode,jdbcType=VARCHAR},
      DEPT_NAME = #{deptName,jdbcType=VARCHAR},
      DAMAGE_LEVEL = #{damageLevel,jdbcType=VARCHAR},
      DAMAGE_REMARK = #{damageRemark,jdbcType=VARCHAR},
      EVENT_TIME = #{eventTime,jdbcType=TIMESTAMP},
      EVENT_TYPE_CODE = #{eventTypeCode,jdbcType=VARCHAR},
      EVENT_TYPE_NAME = #{eventTypeName,jdbcType=VARCHAR},
      STATUS = #{status,jdbcType=CHAR},
      USER_CODE = #{userCode,jdbcType=VARCHAR},
      USER_NAME = #{userName,jdbcType=VARCHAR},
      USER_ROLE = #{userRole,jdbcType=VARCHAR},
      PATIENT_BED_NO = #{patientBedNo,jdbcType=VARCHAR},
      PATIENT_NAME = #{patientName,jdbcType=VARCHAR},
      PATIENT_GENDER = #{patientGender,jdbcType=CHAR},
      PATIENT_AGE = #{patientAge,jdbcType=VARCHAR},
      PATIENT_HOSP_NO = #{patientHospNo,jdbcType=VARCHAR},
      PATIENT_IN_DATE = #{patientInDate,jdbcType=TIMESTAMP},
      PATIENT_DIAGNOSE = #{patientDiagnose,jdbcType=VARCHAR},
      PATIENT_OTHER = #{patientOther,jdbcType=VARCHAR},
      EVENT_DESCRIBE = #{eventDescribe,jdbcType=VARCHAR},
      UPDATE_TIME = GETDATE(),
      UPDATE_PERSON = #{updatePerson,jdbcType=VARCHAR},
      TASK_CODE = #{taskCode,jdbcType=VARCHAR}
    where SEQ_ID = #{seqId,jdbcType=BIGINT}
  </update>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select SEQ_ID, REPORT_CODE, DEPT_CODE, DEPT_NAME, DAMAGE_LEVEL, DAMAGE_REMARK, EVENT_TIME,
    EVENT_TYPE_CODE, EVENT_TYPE_NAME, STATUS, USER_CODE, USER_NAME, USER_ROLE, PATIENT_BED_NO,
    PATIENT_NAME, PATIENT_GENDER, PATIENT_AGE, PATIENT_HOSP_NO, PATIENT_IN_DATE, PATIENT_DIAGNOSE,
    PATIENT_OTHER, EVENT_DESCRIBE, CREATE_TIME, CREATE_PERSON, UPDATE_TIME, UPDATE_PERSON,TASK_CODE
    from EVENT_REPORT
    where SEQ_ID = #{seqId,jdbcType=BIGINT}
  </select>
  <!-- 查询所有的上报信息 -->
  <select id="selectEventList" resultType="EventReport" parameterType="EventReport">
    select
		r.SEQ_ID seqId,
		r.REPORT_CODE reportCode,
		r.DEPT_CODE deptCode,
	    r.DEPT_NAME deptName,
	    r.DAMAGE_LEVEL damageLevel,
	    l.DAMAGE_LEVEL_NAME damageLevelName,
	    r.DAMAGE_REMARK damageRemark,
	    r.EVENT_TIME eventTime,
	    r.EVENT_TYPE_CODE eventTypeCode,
	    r.EVENT_TYPE_NAME eventTypeName,
	    r.USER_CODE userCode,
	    r.USER_NAME userName,
	    r.STATUS	status,
	    r.USER_ROLE userRole,
	    r.PATIENT_BED_NO patientBedNo,
	    r.PATIENT_NAME patientName,
	    r.PATIENT_GENDER patientGender,
	    r.PATIENT_AGE patientAge,
	    r.PATIENT_HOSP_NO patientHospNo,
	    r.PATIENT_IN_DATE patientInDate,
	    r.PATIENT_DIAGNOSE patientDiagnose,
	    r.PATIENT_OTHER patientOther,
	    r.EVENT_DESCRIBE eventDescribe,
	    r.CREATE_PERSON createPerson,
	    r.UPDATE_PERSON updatePerson,
	    r.TASK_CODE taskCode,
	    t.TASK_STATUS taskStatus
    from EVENT_REPORT r
    	inner join EVENT_LEVEL l on r.DAMAGE_LEVEL = l.DAMAGE_LEVEL
    	left join SYS_TASK t on r.TASK_CODE = t.TASK_CODE
    WHERE r.STATUS !='09'
    <if test="deptCode !=null and deptCode !=''">
    	and r.DEPT_CODE = #{deptCode}
    	or t.HANDLE_DEPT = #{deptCode}
    </if>
    <if test="userCode !=null and userCode !=''">
    	and r.USER_CODE = #{userCode}
    </if>
    <if test="reportCode != null and reportCode !=''">
    	and r.REPORT_CODE = #{reportCode}
    </if>
    	order by r.CREATE_TIME DESC
  </select>
  	<!-- 查询科室护士长 -->
	<select id="selectDeptHeader" parameterType="EventReport" resultType="ComDept">
	SELECT top 1 d.DEPT_NURSE_HEADER deptNurseHeader
		FROM COM_DEPT d
		where d.STATUS!='09'
		and d.DEPT_CODE=#{deptCode}
	</select>
</mapper>


text:
package com.google.inject;

import static com.google.inject.Asserts.assertEqualsBothWays;
import static com.google.inject.Asserts.assertNotSerializable;

import java.io.IOException;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.List;

import junit.framework.TestCase;

import com.google.common.collect.ImmutableList;
import com.google.inject.util.Types;

/**
 * @author crazybob@google.com (Bob Lee)
 */
public class TypeLiteralTest extends TestCase {

    public void testWithParameterizedType() {
        TypeLiteral<List<String>> a = new TypeLiteral<List<String>>() {
        };
        TypeLiteral<List<String>> b = new TypeLiteral<List<String>>(
                Types.listOf(String.class)) {
        };
        assertEqualsBothWays(a, b);
    }

    public void testEquality() {
        TypeLiteral<List<String>> t1 = new TypeLiteral<List<String>>() {
        };
        TypeLiteral<List<String>> t2 = new TypeLiteral<List<String>>() {
        };
        TypeLiteral<List<Integer>> t3 = new TypeLiteral<List<Integer>>() {
        };
        TypeLiteral<String> t4 = new TypeLiteral<String>() {
        };

        assertEqualsBothWays(t1, t2);

        assertFalse(t2.equals(t3));
        assertFalse(t3.equals(t2));

        assertFalse(t2.equals(t4));
        assertFalse(t4.equals(t2));

        TypeLiteral<String> t5 = TypeLiteral.get(String.class);
        assertEqualsBothWays(t4, t5);
    }

    public List<? extends CharSequence> wildcardExtends;

    public void testWithWildcardType()
            throws NoSuchFieldException, IOException {
        TypeLiteral<?> a = TypeLiteral
                .get(getClass().getField("wildcardExtends").getGenericType());
        TypeLiteral<?> b = TypeLiteral
                .get(Types.listOf(Types.subtypeOf(CharSequence.class)));
        TypeLiteral<?> c = new TypeLiteral<List<? extends CharSequence>>() {
        };
        assertEqualsBothWays(a, b);
        assertEqualsBothWays(b, c);
        assertEquals("java.util.List<? extends java.lang.CharSequence>",
                a.toString());
        assertEquals("java.util.List<? extends java.lang.CharSequence>",
                b.toString());
        assertEquals("java.util.List<? extends java.lang.CharSequence>",
                c.toString());
        assertNotSerializable(a);
        assertNotSerializable(b);
        assertNotSerializable(c);
    }

    public void testMissingTypeParameter() {
        try {
            new TypeLiteral() {
            };
            fail();
        } catch (RuntimeException e) { /* expected */
        }
    }

    public void testTypesInvolvingArraysForEquality() {
        TypeLiteral<String[]> stringArray = new TypeLiteral<String[]>() {
        };
        assertEquals(stringArray, new TypeLiteral<String[]>() {
        });

        TypeLiteral<List<String[]>> listOfStringArray = new TypeLiteral<List<String[]>>() {
        };
        assertEquals(listOfStringArray, new TypeLiteral<List<String[]>>() {
        });
    }

    public void testEqualityOfGenericArrayAndClassArray() {
        TypeLiteral<String[]> arrayAsClass = TypeLiteral.get(String[].class);
        TypeLiteral<String[]> arrayAsType = new TypeLiteral<String[]>() {
        };
        assertEquals(arrayAsClass, arrayAsType);
    }

    public void testEqualityOfMultidimensionalGenericArrayAndClassArray() {
        TypeLiteral<String[][][]> arrayAsClass = TypeLiteral
                .get(String[][][].class);
        TypeLiteral<String[][][]> arrayAsType = new TypeLiteral<String[][][]>() {
        };
        assertEquals(arrayAsClass, arrayAsType);
    }

    /**
     * Unlike Key, TypeLiteral retains full type information and differentiates
     * between {@code int.class} and {@code Integer.class}.
     */
    public void testDifferentiationBetweenWrappersAndPrimitives() {
        Class[] primitives = new Class[] { boolean.class, byte.class,
                short.class, int.class, long.class, float.class, double.class,
                char.class, void.class };
        Class[] wrappers = new Class[] { Boolean.class, Byte.class, Short.class,
                Integer.class, Long.class, Float.class, Double.class,
                Character.class, Void.class };

        for (int t = 0; t < primitives.length; t++) {
            @SuppressWarnings("unchecked")
            TypeLiteral primitiveTl = TypeLiteral.get(primitives[t]);
            @SuppressWarnings("unchecked")
            TypeLiteral wrapperTl = TypeLiteral.get(wrappers[t]);

            assertFalse(primitiveTl.equals(wrapperTl));
            assertEquals(primitives[t], primitiveTl.getType());
            assertEquals(wrappers[t], wrapperTl.getType());
            assertEquals(primitives[t], primitiveTl.getRawType());
            assertEquals(wrappers[t], wrapperTl.getRawType());
        }
    }

    public void testSerialization() throws IOException {
        assertNotSerializable(new TypeLiteral<List<String>>() {
        });
    }

    public void testTypeVariableWithNoBound() {
        TypeVariable<Class<HasTypeParameters>>[] typeVariables = HasTypeParameters.class
                .getTypeParameters();

        TypeLiteral<?> aTl = TypeLiteral.get(typeVariables[0]);
        assertEquals(Object.class, aTl.getRawType());
        assertEquals("A", aTl.toString());
        TypeVariable<?> aTv = (TypeVariable) aTl.getType();
        assertEquals(HasTypeParameters.class, aTv.getGenericDeclaration());
        assertEquals("A", aTv.getName());
        assertEquals(ImmutableList.<Type> of(Object.class),
                ImmutableList.copyOf(aTv.getBounds()));
        assertEquals("A", aTv.toString());
        assertEqualsBothWays(aTl, TypeLiteral
                .get(HasTypeParameters.class.getTypeParameters()[0]));
    }

    class HasTypeParameters<A, B extends List<A> & Runnable, C extends Runnable> {
        A a;
        B b;
        C c;
    }
}


text:
Web application that demonstrates functionality from [hystrix-examples](https://github.com/Netflix/Hystrix/tree/master/hystrix-examples) and functionality from [hystrix-request-servlet](https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-request-servlet) and [hystrix-metrics-event-stream](https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-metrics-event-stream).

The [hystrix-dashboard](https://github.com/Netflix/Hystrix/tree/master/hystrix-dashboard) can be used on this example app to monitor its metrics.

# Run via Gradle

```
$ git clone git@github.com:Netflix/Hystrix.git
$ cd Hystrix/hystrix-examples-webapp
$ ../gradlew jettyRun
> Building > :hystrix-examples-webapp:jettyRun > Running at http://localhost:8989/hystrix-examples-webapp
```

Once running, open http://localhost:8989/hystrix-examples-webapp.


text:
Pattern: Use of `this` in `asyncData/fetch`

Issue: -

## Description

This rule is for preventing using `this` in `asyncData/fetch`.

Examples of **incorrect** code for this rule:

```js

export default {
  ...foo,
  async asyncData() {
    if (this.$route.path === 'foo') {

    }
  }
}

```

Examples of **correct** code for this rule:

```js

export default {
  ...foo,
  async asyncData() {
    // no this
  }
}

```

## Further Reading

* [GitHub - nuxt/no-this-in-fetch-data](https://github.com/nuxt/eslint-plugin-nuxt/blob/master/docs/rules/no-this-in-fetch-data.md)


text:
dbMayaTextureToolkit
====================

dbMayaTextureToolkit is a tool design to quickly manage and manipulate textures inside Maya

![MTT main view](https://raw.githubusercontent.com/wiki/Bioeden/dbMayaTextureToolkit/images/MTT_main.png)

In his compact UI, dbMayaTextureToolkit will smooth your texture workflow inside Maya. It gives you the possibility to quickly search a texture in your scene, automatically reload textures when you edited them or simply copy all files to your current workspace. On top of that, it gives you access to an internal viewer, that let's you preview tilling or compare 2 textures.
For a complete description of all features look at the [wiki](https://github.com/Bioeden/dbMayaTextureToolkit/wiki).

Features
========

 * clean and compact UI
 * different filters (filter from selection, search field, quick filters...)
 * autoreload, autorename
 * internal viewer
 * node creation from selected files

For a quick overview in french, look at this video :
![Youtube icon](https://raw.githubusercontent.com/wiki/Bioeden/dbMayaTextureToolkit/images/icons/YouTube.png) MTT Overview (French)


text:
package com.devsolutions.camelus.auditing;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.List;

public class GenerateAudits {

	public static void generate(String filename, int duration)
			throws IOException {
		List<Audit> audits = AuditManager.getBySpecificTime(duration);
		StringBuilder stringBuilder = new StringBuilder();
		for (Audit audit : audits) {
			stringBuilder.append(audit.getCreated_at() + " : "
					+ audit.getAction_user() + " " + audit.getDescription()
					+ System.getProperty("line.separator"));
		}
		RandomAccessFile file = new RandomAccessFile(filename, "rw");
		FileChannel fileChannel = file.getChannel();
		ByteBuffer buf = ByteBuffer.wrap(stringBuilder.toString().getBytes(
				Charset.forName("UTF-8")));
		while (buf.hasRemaining()) {
			fileChannel.write(buf);
		}
		fileChannel.close();
		file.close();
	}
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.synapse.generated;

import com.azure.core.util.Context;

/** Samples for SqlPoolGeoBackupPolicies List. */
public final class SqlPoolGeoBackupPoliciesListSamples {
    /*
     * x-ms-original-file: specification/synapse/resource-manager/Microsoft.Synapse/stable/2021-06-01/examples/SqlPoolGeoBackupPolicies_List.json
     */
    /**
     * Sample code: Get Sql pool geo backup policy.
     *
     * @param manager Entry point to SynapseManager.
     */
    public static void getSqlPoolGeoBackupPolicy(com.azure.resourcemanager.synapse.SynapseManager manager) {
        manager.sqlPoolGeoBackupPolicies().list("sqlcrudtest-4799", "sqlcrudtest-5961", "testdw", Context.NONE);
    }
}


text:
<?php

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;

/**
 * appDevUrlMatcher.
 *
 * This class has been auto-generated
 * by the Symfony Routing Component.
 */
class appDevUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher
{
    /**
     * Constructor.
     */
    public function __construct(RequestContext $context)
    {
        $this->context = $context;
    }

    public function match($pathinfo)
    {
        $allow = array();
        $pathinfo = rawurldecode($pathinfo);
        $context = $this->context;
        $request = $this->request;

        if (0 === strpos($pathinfo, '/_')) {
            // _wdt
            if (0 === strpos($pathinfo, '/_wdt') && preg_match('#^/_wdt/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => '_wdt')), array (  '_controller' => 'web_profiler.controller.profiler:toolbarAction',));
            }

            if (0 === strpos($pathinfo, '/_profiler')) {
                // _profiler_home
                if (rtrim($pathinfo, '/') === '/_profiler') {
                    if (substr($pathinfo, -1) !== '/') {
                        return $this->redirect($pathinfo.'/', '_profiler_home');
                    }

                    return array (  '_controller' => 'web_profiler.controller.profiler:homeAction',  '_route' => '_profiler_home',);
                }

                if (0 === strpos($pathinfo, '/_profiler/search')) {
                    // _profiler_search
                    if ($pathinfo === '/_profiler/search') {
                        return array (  '_controller' => 'web_profiler.controller.profiler:searchAction',  '_route' => '_profiler_search',);
                    }

                    // _profiler_search_bar
                    if ($pathinfo === '/_profiler/search_bar') {
                        return array (  '_controller' => 'web_profiler.controller.profiler:searchBarAction',  '_route' => '_profiler_search_bar',);
                    }

                }

                // _profiler_purge
                if ($pathinfo === '/_profiler/purge') {
                    return array (  '_controller' => 'web_profiler.controller.profiler:purgeAction',  '_route' => '_profiler_purge',);
                }

                // _profiler_info
                if (0 === strpos($pathinfo, '/_profiler/info') && preg_match('#^/_profiler/info/(?P<about>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_info')), array (  '_controller' => 'web_profiler.controller.profiler:infoAction',));
                }

                // _profiler_phpinfo
                if ($pathinfo === '/_profiler/phpinfo') {
                    return array (  '_controller' => 'web_profiler.controller.profiler:phpinfoAction',  '_route' => '_profiler_phpinfo',);
                }

                // _profiler_search_results
                if (preg_match('#^/_profiler/(?P<token>[^/]++)/search/results$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_search_results')), array (  '_controller' => 'web_profiler.controller.profiler:searchResultsAction',));
                }

                // _profiler
                if (preg_match('#^/_profiler/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler')), array (  '_controller' => 'web_profiler.controller.profiler:panelAction',));
                }

                // _profiler_router
                if (preg_match('#^/_profiler/(?P<token>[^/]++)/router$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_router')), array (  '_controller' => 'web_profiler.controller.router:panelAction',));
                }

                // _profiler_exception
                if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception')), array (  '_controller' => 'web_profiler.controller.exception:showAction',));
                }

                // _profiler_exception_css
                if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception\\.css$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception_css')), array (  '_controller' => 'web_profiler.controller.exception:cssAction',));
                }

            }

            // _twig_error_test
            if (0 === strpos($pathinfo, '/_error') && preg_match('#^/_error/(?P<code>\\d+)(?:\\.(?P<_format>[^/]++))?$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => '_twig_error_test')), array (  '_controller' => 'twig.controller.preview_error:previewErrorPageAction',  '_format' => 'html',));
            }

        }

        // myapp_accueil
        if (rtrim($pathinfo, '/') === '') {
            if (substr($pathinfo, -1) !== '/') {
                return $this->redirect($pathinfo.'/', 'myapp_accueil');
            }

            return array (  '_controller' => 'BibliothequeBundle\\Controller\\DefaultController::indexAction',  '_route' => 'myapp_accueil',);
        }

        if (0 === strpos($pathinfo, '/autheur')) {
            // myapp_autheur_lister
            if (rtrim($pathinfo, '/') === '/autheur') {
                if (substr($pathinfo, -1) !== '/') {
                    return $this->redirect($pathinfo.'/', 'myapp_autheur_lister');
                }

                return array (  '_controller' => 'BibliothequeBundle\\Controller\\AutheurController::listerAction',  '_route' => 'myapp_autheur_lister',);
            }

            // myapp_autheur_ajouter
            if ($pathinfo === '/autheur/ajouter') {
                return array (  '_controller' => 'BibliothequeBundle\\Controller\\AutheurController::editerAction',  '_route' => 'myapp_autheur_ajouter',);
            }

            // myapp_autheur_modifier
            if (0 === strpos($pathinfo, '/autheur/modifier') && preg_match('#^/autheur/modifier/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'myapp_autheur_modifier')), array (  '_controller' => 'BibliothequeBundle\\Controller\\AutheurController::editerAction',));
            }

            // myapp_autheur_supprimer
            if (0 === strpos($pathinfo, '/autheur/supprimer') && preg_match('#^/autheur/supprimer/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'myapp_autheur_supprimer')), array (  '_controller' => 'BibliothequeBundle\\Controller\\AutheurController::supprimerAction',));
            }

        }

        if (0 === strpos($pathinfo, '/livre')) {
            // myapp_livre_lister
            if (rtrim($pathinfo, '/') === '/livre') {
                if (substr($pathinfo, -1) !== '/') {
                    return $this->redirect($pathinfo.'/', 'myapp_livre_lister');
                }

                return array (  '_controller' => 'BibliothequeBundle\\Controller\\LivreController::listerAction',  '_route' => 'myapp_livre_lister',);
            }

            // myapp_livre_ajouter
            if ($pathinfo === '/livre/ajouter') {
                return array (  '_controller' => 'BibliothequeBundle\\Controller\\LivreController::editerAction',  '_route' => 'myapp_livre_ajouter',);
            }

            // myapp_livre_modifier
            if (0 === strpos($pathinfo, '/livre/modifier') && preg_match('#^/livre/modifier/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'myapp_livre_modifier')), array (  '_controller' => 'BibliothequeBundle\\Controller\\LivreController::editerAction',));
            }

            // myapp_livre_supprimer
            if (0 === strpos($pathinfo, '/livre/supprimer') && preg_match('#^/livre/supprimer/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'myapp_livre_supprimer')), array (  '_controller' => 'BibliothequeBundle\\Controller\\LivreController::supprimerAction',));
            }

            // myapp_livre_voir
            if (0 === strpos($pathinfo, '/livre/voir') && preg_match('#^/livre/voir/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'myapp_livre_voir')), array (  '_controller' => 'BibliothequeBundle\\Controller\\LivreController::voirAction',));
            }

        }

        // myapp_insert_data
        if ($pathinfo === '/insert') {
            return array (  '_controller' => 'BibliothequeBundle\\Controller\\InsertDataController::insertAction',  '_route' => 'myapp_insert_data',);
        }

        throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException();
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Ipiaú</logradouro><bairro>Rio Grande</bairro><cidade>Barreiras</cidade><uf>BA</uf><cep>47800608</cep></feed>


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

<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
	>

	<!--
		/properties/exceptionHandling/exceptionHandling.xml
		The configuration file for domain services.
		This file is referenced by /properties/applicationContext.xml.
	-->

	<bean
		id="exceptionServiceFactory"
		class="org.esupportail.commons.services.exceptionHandling.CachingEmailExceptionServiceFactoryImpl"
		parent="abstractApplicationAwareBean">
		<property name="authenticationService" ref="${auth.bean}" />
		<property name="smtpService" ref="smtpService" />
		<property name="recipientEmail" value="${exceptionHandling.email}" />
		<property name="exceptionViews">
			<map>
				<entry key="javax.faces.application.ViewExpiredException" value="go_welcome" />
				<entry key="java.lang.Exception" value="go_exception"/>
			</map>
		</property>
		<property name="noEmailExceptions" >
			<list>
				<value>javax.faces.application.ViewExpiredException</value>
				<value>org.esupportail.commons.services.ldap.LdapConnectionException</value>
			</list>
		</property>
		<property name="cacheManager" ref="cacheManager" />
		<property name="logLevel" value="${exceptionHandling.logLevel}" />
	</bean>

</beans>


text:
<?xml version="1.0" encoding="macroman"?>
<!--
SkipUnless:  __import__('codecs').lookup('macroman')
Description: \x80 character in macroman encoding
Expect:      not bozo and feed['title'] == '\xc4'
-->
<feed version="0.3" xmlns="http://purl.org/atom/ns#">
<title>€</title>
</feed>


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_window_focused="false" android:state_enabled="true" android:drawable="@drawable/semc_btn_default_normal_holo_dark" />
    <item android:state_window_focused="false" android:state_enabled="false" android:drawable="@drawable/semc_btn_default_disabled_holo_dark" />
    <item android:state_pressed="true" android:drawable="@drawable/semc_btn_default_pressed_holo_dark" />
    <item android:state_focused="true" android:state_enabled="true" android:drawable="@drawable/semc_btn_default_focused_holo_dark" />
    <item android:state_enabled="true" android:drawable="@drawable/semc_btn_default_normal_holo_dark" />
    <item android:state_focused="true" android:drawable="@drawable/semc_btn_default_disabled_focused_holo_dark" />
    <item android:drawable="@drawable/semc_btn_default_disabled_holo_dark" />
</selector>


text:
"""
    robustness_functions
    ~~~~~~~~~~~~~~~~~~~~

    Contains functions used for genotype and phenotype robustness computations.

    :author: Fahad Khalid
    :license: MIT, see LICENSE for more details.
"""

import numpy as np
from tqdm import tqdm

class RobustnessAnalyzer:
    # Constructor
    def __init__(self, network, netBuilder, is_double_stranded, verbose):
        # Reference to the network on which to perform this
        # analysis
        self.network = network

        # Get a reference to the NetworkUtils object
        self.netBuilder = netBuilder

        # Get a reference to the BitSeqManipulator in use
        self.bitManip = netBuilder.bitManip

        # Flag indicating whether the genotypes correspond to double
        # stranded molecules
        self.is_double_stranded = is_double_stranded

        # Reference to the list of tuples, (seq, robustness)
        # populated when required
        self.robustnessVals = None

        self._verbose = verbose

    # Returns the arithmetic mean of the all values in the
    # robustness list.
    def getAvgRobustness(self):
        # Calculate the mean of all robustness values for the network
        return np.mean(self.getRobustnessAll())

    # Returnes a list of tuples of the form (sequence, robustness) that
    # consist of robustness values for all sequences represented by
    # vertices of the given network.
    def getRobustnessAll(self, recompute=False):
        if self._verbose:
            print('\n')

        # If either the robustness values have not been computed already,
        # or the caller has explicitly requested re-computing,
        if not self.robustnessVals or recompute:
            if self._verbose:
                iterable = tqdm(self.network.vs["sequences"])
            else:
                iterable = self.network.vs["sequences"]

            # Get robustness values for all sequences in the network
            self.robustnessVals = [
                self.getGenotypeRobustness(seq)
                for seq in iterable
            ]

        return self.robustnessVals

    # Calculates sequence robustness, which is defined as Genotype
    # robustness in,
    # Ref: "Robustness and evolvability: a paradox resolved". Andreas
    # Wagner, Proc. R. Soc. B 2008 275 91-100;
    # DOI: 10.1098/rspb.2007.1137. Published 7 January 2008
    def getGenotypeRobustness(self, sequence):
        # Degree of the vertex corresponding to the sequence
        degree = self.network.degree(sequence)

        # Get a list of all possible 1-neighbors for this sequence
        allNeighbors = self.bitManip.generateNeighbors(
            self.bitManip.seqToBits(sequence))

        # If reverse complements should be considered,
        if self.is_double_stranded:
            # Reverse complement of the focal genotype
            rc = self.bitManip.get_reverse_complement(
                self.bitManip.seqToBits(sequence))

            # If the reverse complement is also a 1-mutant,
            if rc in allNeighbors:
                # Do not consider it as one of all possible 1-mutants
                allNeighbors.remove(rc)

            # Make sure a genotype and its reverse complement are not both
            # considered separate neighbors
            for neighbor in list(allNeighbors):
                # Reverse complement of the neighbor
                rc_n = self.bitManip.get_reverse_complement(neighbor)

                # If the reverse complement is not the same as the neighbor,
                # and the reverse complement is already in the list of
                # external neighbors, remove the neighbor itself from the
                # list.
                if rc_n != neighbor and rc_n in allNeighbors:
                    allNeighbors.remove(neighbor)

        # Count the number of all possible 1-neighbors of this sequence
        numNeighbors = len(allNeighbors)

        try:
            return float(degree) / float(numNeighbors)
        except ZeroDivisionError:
            return 0


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

<TITLE>
RExecTask.AntRExecClient (Apache Ant API)
</TITLE>

<META NAME="date" CONTENT="2013-07-08">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.tools.ant.taskdefs.optional.net

Class RExecTask.AntRExecClient

java.lang.Object
  org.apache.commons.net.SocketClient
      org.apache.commons.net.bsd.RExecClient
          org.apache.tools.ant.taskdefs.optional.net.RExecTask.AntRExecClient

Enclosing class:
RExecTask

public class RExecTask.AntRExecClient
extends org.apache.commons.net.bsd.RExecClient

This class handles the abstraction of the rexec protocol.
  Currently it is a wrapper around Jakarta
  Commons Net.

Field Summary

Fields inherited from class org.apache.commons.net.bsd.RExecClient

_errorStream_, DEFAULT_PORT

Fields inherited from class org.apache.commons.net.SocketClient

_defaultPort_, _input_, _isConnected_, _output_, _socket_, _socketFactory_, _timeout_, NETASCII_EOL

Constructor Summary

RExecTask.AntRExecClient()

Method Summary

 void
sendString(java.lang.String s,
           boolean echoString)

          Write this string to the rexec session.

 void
waitForEOF(java.lang.Integer timeout)

          Read from the rexec session until the EOF is found or
 the timeout has been reached

 void
waitForString(java.lang.String s)

          Read from the rexec session until the string we are
 waiting for is found

 void
waitForString(java.lang.String s,
              java.lang.Integer timeout)

          Read from the rexec session until the string we are
 waiting for is found or the timeout has been reached

Methods inherited from class org.apache.commons.net.bsd.RExecClient

disconnect, getErrorStream, getInputStream, getOutputStream, isRemoteVerificationEnabled, rexec, rexec, setRemoteVerificationEnabled

Methods inherited from class org.apache.commons.net.SocketClient

_connectAction_, connect, connect, connect, connect, connect, connect, getDefaultPort, getDefaultTimeout, getLocalAddress, getLocalPort, getRemoteAddress, getRemotePort, getSoLinger, getSoTimeout, getTcpNoDelay, isConnected, setDefaultPort, setDefaultTimeout, setSocketFactory, setSoLinger, setSoTimeout, setTcpNoDelay, verifyRemote

Methods inherited from class java.lang.Object

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

Constructor Detail

RExecTask.AntRExecClient

public RExecTask.AntRExecClient()

Method Detail

waitForString

public void waitForString(java.lang.String s)

Read from the rexec session until the string we are
 waiting for is found

Parameters:
s - The string to wait on

waitForString

public void waitForString(java.lang.String s,
                          java.lang.Integer timeout)

Read from the rexec session until the string we are
 waiting for is found or the timeout has been reached

Parameters:
s - The string to wait on
timeout - The maximum number of seconds to wait

sendString

public void sendString(java.lang.String s,
                       boolean echoString)

Write this string to the rexec session.

Parameters:
s - the string to write
echoString - if true log the string sent

waitForEOF

public void waitForEOF(java.lang.Integer timeout)

Read from the rexec session until the EOF is found or
 the timeout has been reached

Parameters:
timeout - The maximum number of seconds to wait

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
import { combingPathKey, isInteger } from '../util'
import normalizePath from './normalizePath'

const _computePath = (path: string, direction: 'prev' | 'next'): string | null => {
  const index = +(combingPathKey({ path }).keys.pop() as string)

  if (!isInteger(index)) return null

  if (direction === 'prev') return normalizePath(path, '..', index - 1)
  if (direction === 'next') return normalizePath(path, '..', index + 1)
  return null
}

export default _computePath


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Aglaia clementis Merr.

### Remarks
null


text:
require File.dirname(__FILE__) + '/../../../spec_helper'
require 'complex'
require File.dirname(__FILE__) + '/shared/atanh'

describe "Math#atanh" do
  it_behaves_like :complex_math_atanh, :_, IncludesMath.new

  it "should be private" do
    IncludesMath.should have_private_instance_method(:atanh)
  end
end

ruby_version_is ""..."1.9" do
  describe "Math#atanh!" do
    it_behaves_like :complex_math_atanh_bang, :_, IncludesMath.new

    it "should be private" do
      IncludesMath.should have_private_instance_method(:atanh!)
    end
  end
end

describe "Math.atanh" do
  it_behaves_like :complex_math_atanh, :_, Math
end

ruby_version_is ""..."1.9" do
  describe "Math.atanh!" do
    it_behaves_like :complex_math_atanh_bang, :_, Math
  end
end


text:
#pragma once

#include <map>
#include <ros/console.h>

#include "AbstractCameraQueue.hpp"

/**
 * Uses one AbstractCameraQueue per quadcopter to schedule
 * the camera data. Dequeueing is done round-robin style
 * for the quadcopter id. The camera data itself is selected
 * by the underlying AbstractCameraQueue.
 *
 * @author Sebastian Schmidt
 * @param T The implementation of AbstractCameraQueue to use.
 */
template<class T>
class TrackingQueue {
public:
	TrackingQueue();
	~TrackingQueue();

	void enqueue(std::vector<CameraData> data);
	void enqueue(CameraData data);

	size_t getSize();

	std::vector<CameraData> dequeue();
	bool dataAvailable();

private:
	std::map<int, AbstractCameraQueue*> queues;
	std::vector<int> ids;
	int rrIndex;
	size_t size;
};

/**
 * Creates a new empty TrackingQueue.
 */
template<class T>
TrackingQueue<T>::TrackingQueue()
{
	size = 0;
	rrIndex = 0;
}

/**
 * Deletes the TrackingQueue.
 */
template<class T>
TrackingQueue<T>::~TrackingQueue()
{
	for (std::map<int, AbstractCameraQueue*>::iterator it = queues.begin(); it != queues.end(); it++) {
		delete it->second;
	}
}

/**
 * Enqueues the given CameraData.
 *
 * @param data A vector containing CameraData.
 */
template<class T>
void TrackingQueue<T>::enqueue(std::vector<CameraData> data)
{
	for (std::vector<CameraData>::iterator it = data.begin(); it != data.end(); it++) {
		enqueue(*it);
	}
}

/**
 * Enqueues the given CameraData.
 *
 * @param data The CameraData.
 */
template<class T>
void TrackingQueue<T>::enqueue(CameraData data)
{
	if (queues.count(data.quadcopterId) == 0) {
		// Since the RRCameraQueue is missing this constructor, this part has to be
		// edited if it should be used.
		queues[data.quadcopterId] = new T(15L * 100 * 1000 * 1000 / 30,
		                                  2L * 1000 * 1000 * 1000 / 30,
		                                  2L * 1000 * 1000 * 1000 / 30,
		                                  true);
		ids.push_back(data.quadcopterId);
	}

	size++;
	queues[data.quadcopterId]->enqueue(data);
}

/**
 * Returns the amount of CameraData that is currently enqueued.
 *
 * @return The current size of the queue.
 */
template<class T>
size_t TrackingQueue<T>::getSize()
{
	return size;
}

/**
 * Dequeues one set of CameraData from the queue.
 * The quadcopter ids are run through round-robin style.
 * Per quadcopter, the underlying AbstractCameraQueue is used.
 *
 * @return A set of CameraData to be evaluated.
 */
template<class T>
std::vector<CameraData> TrackingQueue<T>::dequeue()
{
	if (size == 0) {
		return std::vector<CameraData>();
	}

	int index = rrIndex;
	int loopCount = 0;

	do {
		index  = (index + 1) % ids.size();
		loopCount++;

		if (queues[ids[index]]->dataAvailable()) {
			break;
		}
	} while (index != rrIndex);

	if (loopCount > ids.size()) {
		return std::vector<CameraData>();
	} else {
		rrIndex = index;
		std::vector<CameraData> result = queues[ids[index]]->dequeue();
		size -= result.size();

		return result;
	}
}

/**
 * Returns true if one of the underlying AbstractCameraQueues
 * return true for this function.
 *
 * @return True, if one of the underlying camera queues has data available.
 */
template<class T>
bool TrackingQueue<T>::dataAvailable()
{
	for (std::map<int, AbstractCameraQueue*>::iterator it = queues.begin(); it != queues.end(); it++) {
		if (it->second->dataAvailable()) {
			return true;
		}
	}

	return false;
}


text:
/// <reference path='fourslash.ts' />

////xyz => x/*1*/y

goTo.marker("1");
verify.completionListContains("xyz");


text:
from pygw.config import geowave_pkg
from pygw.config import java_pkg
from pygw.store import DataStoreOptions

class DynamoDBOptions(DataStoreOptions):
    """
    DynamoDB data store options.
    """

    def __init__(self):
        super().__init__(geowave_pkg.datastore.dynamodb.config.DynamoDBOptions())

    def set_region(self, region):
        """
        Sets the AWS region of the DynamoDB data store. For example `us-east-1`
        (specify either endpoint or region not both).

        Args:
            region (str, None): The AWS region to use.
        """
        if region is None:
            j_region = None
        else:
            j_region = java_pkg.com.amazonaws.regions.Regions.fromName(region)
        self._java_ref.setRegion(j_region)

    def get_region(self):
        """
        Returns:
            The AWS regiion of the DynamoDB data store.
        """
        j_region = self._java_ref.getRegion()
        if j_region is None:
            return j_region
        return j_region.getName()

    def set_endpoint(self, endpoint):
        """
        Sets the endpoint to connect to (specify either endpoint or region not both).

        Args:
            endpoint (str): The endpoint to connect to.
        """
        self._java_ref.setEndpoint(endpoint)

    def get_endpoint(self):
        """
        Returns:
            The endpoint to connect to.
        """
        return self._java_ref.getEndpoint()

    def set_write_capacity(self, write_capacity):
        """
        Sets the write capacity of the DynamoDB data store.

        Args:
            write_capacity (int): The write capacity.
        """
        self._java_ref.setWriteCapacity(write_capacity)

    def get_write_capacity(self):
        """
        Returns:
            The write capacity of the data store.
        """
        return self._java_ref.getWriteCapacity()

    def set_read_capacity(self, read_capacity):
        """
        Sets the read capacity of the DynamoDB data store.

        Args:
            read_capacity (int): The read capacity.
        """
        self._java_ref.setReadCapacity(read_capacity)

    def get_read_capacity(self):
        """
        Returns:
            The read capacity of the data store.
        """
        return self._java_ref.getReadCapacity()

    def set_enable_cache_response_metadata(self, enable_cache_response_metadata):
        """
        Sets whether or not to cache response metadata.

        Args:
            enable_cache_response_metadata (bool): Whether or not to cache response metadata.
        """
        self._java_ref.setEnableCacheResponseMetadata(enable_cache_response_metadata)

    def is_enable_cache_response_metadata(self):
        """
        Returns:
            True if response metadata will be cached, False otherwise.
        """
        return self._java_ref.isEnableCacheResponseMetadata()

    def set_protocol(self, protocol):
        """
        Sets the protocol of the connection to use. Either 'http' or 'https'.

        Args:
            protocol (str, None): The protocol to use.
        """
        if protocol is None:
            j_protocol = None
        else:
            j_protocol = java_pkg.com.amazonaws.Protocol.valueOf(protocol.upper())
        self._java_ref.setProtocol(j_protocol)

    def get_protocol(self):
        """
        Returns:
            The protocol of the connection to the data store.
        """
        j_protocol = self._java_ref.getProtocol()
        if j_protocol is None:
            return j_protocol
        return j_protocol.name()

    def set_max_connections(self, max_connections):
        """
        Sets the maximum number of connections to the data store.

        Args:
            max_connections (int): The maximum number of connections.
        """
        self._java_ref.setMaxConnections(max_connections)

    def get_max_connections(self):
        """
        Returns:
            The maximum number of connections.
        """
        return self._java_ref.getMaxConnections()


text:
from __future__ import division

import json
import os
import sys
from shutil import (rmtree, move)

class CountDB(object):

    @staticmethod
    def open(filename):
        self = CountDB(filename)
        self.load()
        return self

    @staticmethod
    def open_for_counting(filename, clean=True):
        self = CountDB(filename, "count")
        if not clean:
            try:
                self.load()
            except:
                pass
        self.counter += 1
        return self

    @staticmethod
    def open_for_extending(filename, clean=True):
        self = CountDB(filename, "extend")
        if not clean:
            try:
                self.load()
            except:
                pass
        return self

    def __init__(self, filename, mode="readonly"):
        self.filename = filename
        self.data = {}
        self.counter = 0
        self.mode = mode

    def load(self):
        with self._open_file(self.filename) as data_file:
            tmp = json.load(data_file)
            self.data = tmp.get("data", {})
            self.counter = tmp.get("counter", 0)

    def dump(self, format=None, stream=None):
        if not format:
            format = "text"
        if not stream:
            stream = sys.stdout
        getattr(self, "dump_" + format)(stream)

    def dump_text(self, stream):
        for key, count in sorted(self.convert_to_relative().items()):
            stream.write("%s %.3f\n" % (key, count))

    def convert_to_relative(self):
        tmp = self.data.copy()
        for key in tmp:
            tmp[key] = tmp[key] / self.counter
        return tmp

    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        if self.mode != "readonly":
            self.persist()

    def count(self, key, increment=1):
        if self.mode != "count":
            raise Exception("countdb not opened for count (consider using open_for_counting)")
        self.data[key] = self.data.get(key, 0) + increment

    def extend(self, other):
        if self.mode != "extend":
            raise Exception("countdb not opened for extend (consider using open_for_extending)")
        self.counter += other.counter
        for key, count in other.data.items():
            self.data[key] = self.data.get(key, 0) + count

    def persist(self):
        if self.mode == "readonly":
            raise Exception("countdb not opened for modifications "
                            "(consider using open_for_counting or open_for_extending)")
        makedirs(self.filename)
        with self._open_file(self.filename, "w") as data_file:
            json.dump({"data": self.data, "counter": self.counter}, data_file, indent=4)
            data_file.write("\n")

    def finalize(self, final_filename):
        makedirs(final_filename)
        with self._open_file(final_filename, "w") as final_file:
            json.dump(self.convert_to_relative(), final_file, indent=4)
            final_file.write("\n")

    @staticmethod
    def _open_file(filename, mode="r"):
        return open(filename, mode)

def makedirs(filename):
    dirname = os.path.dirname(filename)
    if not dirname:
        return
    try:
        os.makedirs(dirname)
    except OSError as e:
        if e.errno != 17:
            raise

def aggregate(dirname):
    if not os.path.isdir(dirname):
        return
    for subdir in os.listdir(dirname):
        aggregate(os.path.join(dirname, subdir))
    tmp_filename = dirname + ".tmp"
    with CountDB.open_for_extending(tmp_filename) as db:
        for f in os.listdir(dirname):
            sub_db = CountDB.open(os.path.join(dirname, f))
            db.extend(sub_db)
    rmtree(dirname)
    move(tmp_filename, dirname)


text:
use UC
--select * from ScBzaTrains
CREATE VIEW Scbza as
select s1.arrivaltimeminutes-s2.arrivaltimeminutes as timegap,
case when s1.stationcode='bza' then 'bza2sc'
else 'sc2bza'
end route,s1.trainno,s1.trainname,s1.arrivaltimeminutes arrivalTimeStation1,s2.arrivaltimeminutes arrivalTimeStation2 from sc2bzaonly s1
inner join sc2bzaonly s2
on s1.trainno=s2.trainno
where s1.stationcode!=s2.stationcode
and s1.arrivaltimeminutes-s2.arrivaltimeminutes<0

select * from scbza
where route='bza2sc'
order by arrivalTimeStation1

select * from [dbo].[ScBzaOnlyOneStation]
where stationcode='bza'
order by arrivaltimeminutes


text:
<link href="<?php echo sfConfig::get('app_base_url'); ?>sfFormExtraPlugin/css/jquery.autocompleter.css" media="screen" type="text/css" rel="stylesheet">

<link href="<?php echo sfConfig::get('app_base_url'); ?>PubsPlugin/css/facebox.css" media="screen" type="text/css" rel="stylesheet">

    <?php echo image_tag('/PubsPlugin/images/logo_thumb.png','align=left border=0')?>
    <form method="GET" action="<?php echo sfConfig::get('app_base_url') ?>search" id="search-form" class="search-form">

        <?php echo $form['username']->render(array("size" => "40", "placeholder" => __("Search",null,'pubs'))) ?>
    </form>

    <?php if (in_array('follow', sfConfig::get('sf_enabled_modules', array()))) { ?>
        <?php include_component('follow', 'boxCount') ?>
    <?php } ?>

    <?php if (in_array('inbox', sfConfig::get('sf_enabled_modules', array()))) { ?>
        <?php include_component('inbox', 'boxCount') ?>
    <?php } ?>

    <?php if (in_array('pubs', sfConfig::get('sf_enabled_modules', array()))) { ?>
        <?php include_component('pubs', 'boxCount') ?>
    <?php } ?>

<?php echo __('Home', null, 'pubs') ?>

<?php echo __('My Profile', null, 'pubs') ?>

<?php echo __('Who to follow', null, 'pubs') ?>

                <?php echo $sf_user->getGuardUser()->getUsername() ?>
                <?php echo image_tag($sf_user->getGuardUser()->getImage(), 'width=40'); ?>

                <?php if (in_array('inbox', sfConfig::get('sf_enabled_modules', array()))) { ?>

<a id="inbox_link"  href="<?php echo url_for('@inbox') ?>"><?php echo __('Inbox', null, 'pubs') ?>

                <?php } ?>
                <?php if (in_array('follow', sfConfig::get('sf_enabled_modules', array()))) { ?>

<a id="follow_link"  href="<?php echo url_for('@follow') ?>"><?php echo __('Follows', null, 'pubs') ?>

                <?php } ?>
                <?php if (in_array('audio', sfConfig::get('sf_enabled_modules', array()))) { ?>

<a id="audio_link" accesskey="s" href="<?php echo url_for('@audio') ?>"><?php echo __('Audios', null, 'pubs') ?>

                <?php } ?>
                <?php if (in_array('event', sfConfig::get('sf_enabled_modules', array()))) { ?>

<a id="event_link" accesskey="s" href="<?php echo url_for('@event') ?>"><?php echo __('Events', null, 'pubs') ?>

                <?php } ?>
                <?php if (in_array('photo', sfConfig::get('sf_enabled_modules', array()))) { ?>

<a id="photo_link" accesskey="s" href="<?php echo url_for('@photo') ?>"><?php echo __('Photos', null, 'pubs') ?>

                <?php } ?>

<a id="settings_link" accesskey="s" href="<?php echo url_for('settings', array('config' => 'basicinfo')); ?>"><?php echo __('Configuration', null, 'pubs') ?>

<a id="help_link" accesskey="?" href="<?php echo url_for('@sf_guard_signout') ?>"><?php echo __('Logout', null, 'pubs') ?>


text:
require 'rails_helper'

RSpec.describe Ability, type: :model do
  subject(:ability) { Ability.new(user) }

  describe 'for guest' do
    let(:user) { nil }

    it { should be_able_to :read, Question }
    it { should be_able_to :read, Answer }
    it { should be_able_to :read, Comment }

    it { should_not be_able_to :manage, :all }
  end

  describe 'for admin' do
    let(:user) { create :user, admin: true }

    it { should be_able_to :manage, :all }
  end

  describe 'for user' do
    let(:user) { create :user }
    let(:other) { create :user }
    let(:comment) { create(:comment, user: user) }
    let(:others_comment) { create(:comment) }

    it { should_not be_able_to :manage, :all }
    it { should be_able_to :read, :all }

    it { should be_able_to :create, Question }
    it { should be_able_to :create, Answer }
    it { should be_able_to :create, Comment }
    it { should be_able_to :create, Subscription }

    it { should be_able_to :update, create(:question, user: user), user: user }
    it { should_not be_able_to :update, create(:question, user: other), user: user }

    it { should be_able_to :update, create(:answer, user: user), user: user }
    it { should_not be_able_to :update, create(:answer, user: other), user: user }

    it { should be_able_to :create, Comment }

    it { should be_able_to :destroy, comment }
    it { should_not be_able_to :destroy, others_comment }
    it { should be_able_to :destroy, create(:subscription, user: user) }
  end
end


text:
package scuff

trait Feed {
  type Selector
  type Consumer

  /** Start subscription. */
  def subscribe(include: Selector => Boolean = Function.const(true))(s: Consumer): Subscription
}


text:
#include <device.h>
#include <i2c.h>
#include <misc/util.h>
#include <nanokernel.h>
#include <sensor.h>

#include "sensor_lis3dh.h"

int lis3dh_trigger_set(struct device *dev,
		       const struct sensor_trigger *trig,
		       sensor_trigger_handler_t handler)
{
	struct lis3dh_data *drv_data = dev->driver_data;

	if (trig->type != SENSOR_TRIG_DATA_READY) {
		return -ENOTSUP;
	}

	gpio_pin_disable_callback(drv_data->gpio, CONFIG_LIS3DH_GPIO_PIN_NUM);

	drv_data->data_ready_handler = handler;
	if (handler == NULL) {
		return 0;
	}
	drv_data->data_ready_trigger = *trig;

	gpio_pin_enable_callback(drv_data->gpio, CONFIG_LIS3DH_GPIO_PIN_NUM);

	return 0;
}

static void lis3dh_gpio_callback(struct device *dev,
				 struct gpio_callback *cb, uint32_t pins)
{
	struct lis3dh_data *drv_data =
		CONTAINER_OF(cb, struct lis3dh_data, gpio_cb);

	ARG_UNUSED(pins);

	gpio_pin_disable_callback(dev, CONFIG_LIS3DH_GPIO_PIN_NUM);

#if defined(CONFIG_LIS3DH_TRIGGER_OWN_FIBER)
	nano_sem_give(&drv_data->gpio_sem);
#elif defined(CONFIG_LIS3DH_TRIGGER_GLOBAL_FIBER)
	nano_work_submit(&drv_data->work);
#endif
}

static void lis3dh_fiber_cb(void *arg)
{
	struct device *dev = arg;
	struct lis3dh_data *drv_data = dev->driver_data;

	if (drv_data->data_ready_handler != NULL) {
		drv_data->data_ready_handler(dev,
					     &drv_data->data_ready_trigger);
	}

	gpio_pin_enable_callback(drv_data->gpio, CONFIG_LIS3DH_GPIO_PIN_NUM);
}

#ifdef CONFIG_LIS3DH_TRIGGER_OWN_FIBER
static void lis3dh_fiber(int dev_ptr, int unused)
{
	struct device *dev = INT_TO_POINTER(dev_ptr);
	struct lis3dh_data *drv_data = dev->driver_data;

	ARG_UNUSED(unused);

	while (1) {
		nano_fiber_sem_take(&drv_data->gpio_sem, TICKS_UNLIMITED);
		lis3dh_fiber_cb(dev);
	}
}
#endif

#ifdef CONFIG_LIS3DH_TRIGGER_GLOBAL_FIBER
static void lis3dh_work_cb(struct nano_work *work)
{
	struct lis3dh_data *drv_data =
		CONTAINER_OF(work, struct lis3dh_data, work);

	lis3dh_fiber_cb(drv_data->dev);
}
#endif

int lis3dh_init_interrupt(struct device *dev)
{
	struct lis3dh_data *drv_data = dev->driver_data;

	/* setup data ready gpio interrupt */
	drv_data->gpio = device_get_binding(CONFIG_LIS3DH_GPIO_DEV_NAME);
	if (drv_data->gpio == NULL) {
		SYS_LOG_DBG("Cannot get pointer to %s device",
			    CONFIG_LIS3DH_GPIO_DEV_NAME);
		return -EINVAL;
	}

	gpio_pin_configure(drv_data->gpio, CONFIG_LIS3DH_GPIO_PIN_NUM,
			   GPIO_DIR_IN | GPIO_INT | GPIO_INT_EDGE |
			   GPIO_INT_ACTIVE_HIGH | GPIO_INT_DEBOUNCE);

	gpio_init_callback(&drv_data->gpio_cb,
			   lis3dh_gpio_callback,
			   BIT(CONFIG_LIS3DH_GPIO_PIN_NUM));

	if (gpio_add_callback(drv_data->gpio, &drv_data->gpio_cb) < 0) {
		SYS_LOG_DBG("Could not set gpio callback");
		return -EIO;
	}

	/* clear data ready interrupt line by reading sample data */
	if (lis3dh_sample_fetch(dev, SENSOR_CHAN_ALL) < 0) {
		SYS_LOG_DBG("Could not clear data ready interrupt line.");
		return -EIO;
	}

	/* enable data ready interrupt on INT1 line */
	if (i2c_reg_write_byte(drv_data->i2c, LIS3DH_I2C_ADDRESS,
			       LIS3DH_REG_CTRL3, LIS3DH_EN_DRDY1_INT1) < 0) {
		SYS_LOG_DBG("Failed to enable data ready interrupt.");
		return -EIO;
	}

#if defined(CONFIG_LIS3DH_TRIGGER_OWN_FIBER)
	nano_sem_init(&drv_data->gpio_sem);

	fiber_start(drv_data->fiber_stack, CONFIG_LIS3DH_FIBER_STACK_SIZE,
		    (nano_fiber_entry_t)lis3dh_fiber, POINTER_TO_INT(dev),
		    0, CONFIG_LIS3DH_FIBER_PRIORITY, 0);
#elif defined(CONFIG_LIS3DH_TRIGGER_GLOBAL_FIBER)
	drv_data->work.handler = lis3dh_work_cb;
	drv_data->dev = dev;
#endif

	gpio_pin_enable_callback(drv_data->gpio, CONFIG_LIS3DH_GPIO_PIN_NUM);

	return 0;
}


text:
import { Router } from 'express';
const router = new Router();

// Get all Posts
router.route('/').get((req, res, next) => {
  console.log('redirecting...'); // eslint-disable-line
  // res.redirect('/login');
  next();
});

export default router;


text:
<?php

use Famework\Registry\Famework_Registry;

class Otheruser extends User {

    /**
     * Get only local user by name
     * @param string $name
     * @param int $callerId
     * @return \Otheruser
     */
    public static function getLocalByName($name, $callerId) {
        $gid = User::generateGid($name, Security::getRealEnvoyDomain(Server::getMyHost()));
        return self::getLocalByGid($gid, $callerId);
    }

    public static function getLocalByGid($gid, $callerId = NULL) {
        $stm = Famework_Registry::getDb()->prepare('SELECT id FROM user WHERE gid = ? AND host_gid IS NULL LIMIT 1');
        $stm->execute(array($gid));
        $res = $stm->fetch();
        if (!empty($res)) {
            return new Otheruser($res['id'], $callerId);
        }
        return NULL;
    }

    public static function getLocalById($id, $callerId = NULL) {
        $stm = Famework_Registry::getDb()->prepare('SELECT id FROM user WHERE id = ? AND host_gid IS NULL LIMIT 1');
        $stm->execute(array($id));
        $res = $stm->fetch();
        if (!empty($res)) {
            return new Otheruser($res['id'], $callerId);
        }
        return NULL;
    }

    /**
     * Get foreign or local user by gid
     * @param string $gid
     * @param int $callerId
     * @return \Otheruser|\Foreignotheruser
     */
    public static function getByGid($gid, $callerId) {
        $stm = Famework_Registry::getDb()->prepare('SELECT u.id, u.host_gid FROM user u JOIN user_data d ON d.user_id = u.id WHERE u.gid = ? AND d.activated = 1 LIMIT 1');
        $stm->execute(array($gid));
        $res = $stm->fetch();
        if (!empty($res)) {
            if (empty($res['host_gid'])) {
                return new Otheruser($res['id'], $callerId);
            } else {
                return new Foreignotheruser($res['id'], $callerId);
            }
        }
        return NULL;
    }

    protected $_callerID;

    /**
     * Construct Otheruser object
     * @param int $id
     * @param int $callerId
     */
    public function __construct($id, $callerId) {
        $this->initDb();
        $this->_id = (int) $id;
        $this->loadMeta();
        $this->_callerID = (int) $callerId;
    }

    public function getPicturePath($size) {
        $stm = $this->_db->prepare('SELECT g.id FROM user_groups g
                                        JOIN user_to_groups utg ON utg.group_id = g.id AND utg.user_id = ?
                                    WHERE g.user_id = ? LIMIT 1');
        $stm->execute(array($this->_callerID, $this->getId()));

        $groupinfo = $stm->fetch();

        $path = NULL;

        if (!empty($groupinfo)) {
            // special group pic
            $filename = Picture::getUserPicName($this->getId(), $size, $groupinfo['id']);
            $path = Picture::PROFILEPIC_PATH . $filename;
        }

        if (!is_readable($path)) {
            // default pic
            $filename = Picture::getUserPicName($this->getId(), $size);
            $path = Picture::PROFILEPIC_PATH . $filename;
        }

        return $path;
    }

    public function getAllPossiblePicturePaths($size) {
        $stm = $this->_db->prepare('SELECT g.id FROM user_groups g
                                        JOIN user_to_groups utg ON utg.group_id = g.id AND utg.user_id = ?
                                    WHERE g.user_id = ? ORDER BY g.prio DESC');
        $stm->execute(array($this->_callerID, $this->getId()));

        $res = array();

        // add default pic
        $filename = Picture::getUserPicName($this->getId(), $size);
        $res['default'] = Picture::PROFILEPIC_PATH . $filename;

        foreach ($stm->fetchAll() as $groupinfo) {
            $filename = Picture::getUserPicName($this->getId(), $size, $groupinfo['id']);
            $path = Picture::PROFILEPIC_PATH . $filename;

            if (is_readable($path)) {
                $res[$groupinfo['id']] = $path;
            }
        }

        return $res;
    }

    public function getPublicPosts() {
        $groupID = $this->getPublicGroupId();
        $stm = $this->_db->prepare('SELECT p.id FROM user_posts p
                                        JOIN user_posts_data d ON p.id = d.post_id AND d.group_id = ?
                                    WHERE p.user_id = ?  AND p.post_id IS NULL
                                    GROUP BY p.id ORDER BY p.datetime DESC LIMIT 30');
        $stm->execute(array($groupID, $this->getId()));

        $res = array();

        foreach ($stm->fetchAll() as $row) {
            $res[] = Post::getById($row['id']);
        }

        return $res;
    }

    /**
     * Get posts which are viewable by given user (only works if there is any kind of friendship/followership)
     * @param Currentuser $user
     * @return array <b>array(array('post' => Post, 'comments' => array('comment' => Post, 'subcomments' => array(Post))))</b>
     */
    public function getViewablePosts(Currentuser $user = NULL) {
        if ($user !== NULL) {
            $groups = $user->getMyMemberships();
        } else {
            $groups = $this->getPublicGroupId();
        }
        $stm = $this->_db->prepare('SELECT p.id FROM user_posts p
                                        JOIN user_posts_data d ON p.id = d.post_id AND p.user_id = ?
                                    WHERE p.post_id IS NULL AND d.group_id IN (' . implode(',', $groups) . ')
                                    GROUP BY p.id ORDER BY p.datetime DESC LIMIT 30');
        $stm->execute(array($this->getId()));

        $res = array();

        foreach ($stm->fetchAll() as $row) {
            $post = Post::getById($row['id']);
            $comments = $post->getEntireComments();
            $res[] = array('post' => $post, 'comments' => $comments);
        }

        return $res;
    }

    public function follow(Currentuser $user) {
        $user_id = $user->getId();
        $groupId = $this->getPublicGroupId();
        $stm = $this->_db->prepare('INSERT IGNORE INTO user_to_groups (user_id, group_id) VALUES (?, ?)');
        $stm->execute(array($user_id, $groupId));
    }

    public function unfollow(Currentuser $user) {
        $user_id = $user->getId();
        $groupIDs = array_flip($this->getGroupOverview());
        if ($groupIDs !== NULL) {
            $stm = $this->_db->prepare('DELETE FROM user_to_groups WHERE user_id = ? AND group_id IN (' . implode(',', $groupIDs) . ')');
            $stm->execute(array($user_id));
        }
    }

    public function groupsImIn(Currentuser $user) {
        $stm = $this->_db->prepare('SELECT ug.id id  FROM user_to_groups utg
                                        JOIN user_groups ug ON ug.user_id = ? AND utg.group_id = ug.id
                                    WHERE utg.user_id = ? GROUP BY ug.id');
        $stm->execute(array($user->getId(), $this->getId()));

        $res = array();

        foreach ($stm->fetchAll() as $row) {
            $res[$row['id']] = Group::getNameById($row['id']);
        }

        return $res;
    }

}


text:
<?php
require_once('includes/connect.php');
require_once('includes/general_functions.php');

$msg = '';
$top_msg = 'Nie jesteś zalogowany. Zaloguj się, lub Zarejestruj';
if (!empty($_POST['r_login']) and !empty($_POST['r_email']) and !empty($_POST['r_pass']) and !empty($_POST['r_pass2']) and !empty($_POST['r_name']) and !empty($_POST['r_pos'])) {
	$arr_pos = array(1, 2, 3, 4);
	$login = secure(preg_replace("/[^a-zA-Z0-9]+/", "", $_POST['r_login']));
	$name = secure($_POST['r_name']);
	$pass = secure($_POST['r_pass']);
	$pass2 = secure($_POST['r_pass2']);
	$email = secure($_POST['r_email']);
	if (in_array($_POST['r_pos'], $arr_pos) and $login == $_POST['r_login'] and $name == $_POST['r_name'] and $pass == $_POST['r_pass'] and $pass2 == $_POST['r_pass2'] and $email == $_POST['r_email']) {
		if (strlen($login) > 3 and strlen($login) <= 16 and strlen($name) > 2 and strlen($name) <= 12 and $pass == $pass2 and strlen($pass) >= 5 and strlen($pass) <= 16 and strlen($email) > 4 and strlen($email) <= 32) {
			if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
				$existing_users = mysql_query("SELECT `id` FROM `mp_users` WHERE `login` = '".$login."' or `char_name` = '".$name."'");
				if (mysql_num_rows($existing_users) == 0) {
					$arr_stats = array(5, 5, 5, 5, 5);
					$stats = implode(',', $arr_stats);
					$query = "INSERT INTO `mp_users` (`login`, `pass`, `pass_md5`, `email`, `pos`, `char_name`, `stats`) VALUES ('".$login."', '".$pass."', '".md5($pass)."', '".$email."', '".$_POST['r_pos']."', '".$name."', '".$stats."')";
					if (mysql_query($query)) {
						$msg .= 'Rejestracja zakończona pomyślnie. Możesz się zalogować.';
					}
					else {
						$msg .= 'Błąd serwera.';
					}
				}
				else {
					if (mysql_num_rows(mysql_query("SELECT `id` FROM `mp_users` WHERE `login` = '".$login."'")) > 0) {
						$msg .= 'Login w użyciu.';
					}
					elseif (mysql_num_rows(mysql_query("SELECT `id` FROM `mp_users` WHERE `char_name` = '".$name."'")) > 0) {
						$msg .= 'Nazwa gracza w użyciu.';
					}
				}
			}
			else {
				$msg .= 'Nieprawidłowy adres e-mail.';
			}
		}
		else {
			$msg .= 'Nieprawidłowa długość.';
		}
	}
	else {
		$msg .= 'Nieprawidłowe dane.';
	}
}
elseif (!empty($_POST['l_login']) and !empty($_POST['l_pass'])) {
	$login = secure($_POST['l_login']);
	$pass = secure($_POST['l_pass']);
	if ($user = mysql_fetch_assoc(mysql_query("SELECT `id` FROM `mp_users` WHERE `login` = '".$login."' AND `pass` = '".$pass."' AND `access` > 0"))) {
		$_SESSION['login'] = $login;
		$_SESSION['pass'] = md5($pass);
		$msg .= 'Logowanie zakończone pomyślnie.';
		$top_msg = 'Zalogowany jako: '.$login.' Przejdź do gry, lub Wyloguj';
	}
	else {
		$msg .= 'Nieprawidłowy login i / lub hasło.';
	}
}
elseif (!empty($_SESSION['email']) and !empty($_SESSION['pass'])) {
	$email = secure($_SESSION['email']);
	$pass = secure($_SESSION['pass']);
	if ($user = mysql_fetch_assoc(mysql_query("SELECT `id` FROM `mp_users` WHERE `email` = '".$email."' AND `pass_md5` = '".$pass."' AND `access` > 0"))) {
		$top_msg = 'Zalogowany jako: '.$email.' Przejdź do gry, lub Wyloguj';
	}
	else {
		$msg .= 'Nieprawidłowy login i / lub hasło.';
		$top_msg = 'Nie jesteś zalogowany. Zaloguj się, lub Zarejestruj';
	}
}
else {
	$top_msg = 'Nie jesteś zalogowany. Zaloguj się, lub Zarejestruj';
}

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

		<title>Mercenary Player</title>
		<link rel="shortcut icon" type="image/x-icon" href="img/favicon.ico" />
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<meta name="Description" content="Przeglądarkowa gra RPG" />
		<meta name="Keywords" content="Mercenary Player" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
		<link rel="stylesheet" type="text/css" href="css/style.css" />
		<link rel="stylesheet" type="text/css" href="css/index.css" />

			'.$top_msg.'

			'.$msg.'

Start

Logowanie

Rejestracja

Poradnik

Galeria

Informacje

Kontakt

				Start
				Witaj w Mercenary Player!

				<form action="index.php" method="post">
					Logowanie

						Adres e-mail:
						<input id="l_login" name="l_login" type="text" maxlength="16" />

						Hasło:
						<input id="l_pass" name="l_pass" type="password" maxlength="16" />

						<input style="float: none; display: block; margin: 0 auto; text-align: center; width: auto;" type="submit" value="Logowanie" />

				</form>

				<form action="index.php" method="post">
					Rejestracja

						Login:
						<input id="r_login" name="r_login" type="text" maxlength="16" />

						Adres e-mail:
						<input id="r_email" name="r_email" type="text" maxlength="32" />

						Hasło:
						<input id="r_pass" name="r_pass" type="password" maxlength="16" />

						Powtórz hasło:
						<input id="r_pass2" name="r_pass2" type="password" maxlength="16" />

						Nazwa postaci:
						<input id="r_name" name="r_name" type="text" maxlength="12" />

						Pozycja:
						<select style="width: auto;" name="r_pos">
							<option value="1">Napastnik</option>
							<option value="2">Obrońca</option>
							<option value="3">Pomocnik</option>
							<option value="4">Bramkarz</option>
						</select>

						<input style="float: none; display: block; margin: 0 auto; text-align: center; width: auto;" type="submit" value="Rejestracja" />

				</form>

			2013 Mercenary Player All Rights Reserved

';

?>


text:
package com.dak.duty.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import lombok.Getter;

@Service
@Getter
public class VersionService {

	private final String version;
	private final String commitId;
	private final String timestamp;

	public VersionService(
			@Value("${info.build.version:}") final String version,
			@Value("${git.commit.id:}") final String commitId,
			@Value("${info.build.timestamp:}") final String timestamp) {
		this.version = version;
		this.commitId = commitId;
		this.timestamp = timestamp;
	}

}


text:
module JsAssetPaths
  class Generator
    cattr_accessor :environment

    def self.generate!
      asset_hash.to_json
    end

    private

    # Note: In sprockets 2, `each_file` yields a `Pathname`. In 3,
    # it yields a string. This method supports both.
    def self.asset_hash
      assets.each_file.each_with_object({}) do |filepath, memo|
        path = ::Pathname.new(filepath.to_s)
        relative_path = path.relative_path_from(base_asset_path)

        memo[relative_path] = output_path(path) if local?(relative_path)
      end
    end

    def self.base_asset_path
      @base_asset_path ||= Rails.root.join('app', 'assets')
    end

    def self.output_path(filepath)
      unless digest?.in?([true, false])
        raise TypeError.new('Expected ::Rails.application.config.assets.digest to be boolean')
      end

      if digest?
        # Convert the byte string into hexadecimal
        dgst = assets.file_digest(filepath).unpack('H*')[0]
        "#{filepath.basename(filepath.extname)}-#{dgst}#{filepath.extname}"
      else
        filepath.basename.to_s
      end
    end

    def self.assets
      environment.assets
    end

    def self.digest?
      ::Rails.application.config.assets.digest
    end

    def self.local?(filepath)
      !(filepath.to_s =~ /\.\.\//)
    end
  end
end


text:
"""K-Nearest-Neighbors glyph classification."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tensorflow as tf
from tensorflow_estimator.python.estimator.canned import prediction_keys

from moonlight.protobuf import musicscore_pb2

# k = 3 has the best performance for noteheads, clefs, and sharps. k = 5 seems
# to increase false negatives, so we probably don't want to increase k further
# with our current data.
K_NEAREST_VALUE = 3

NUM_GLYPHS = len(musicscore_pb2.Glyph.Type.keys())

def knn_kmeans_model(centroids, labels, patches=None):
  """The KNN k-means classifier model.

  Args:
    centroids: The k-means centroids NumPy array. Shape `(num_centroids,
      patch_height, patch_width)`.
    labels: The centroid labels NumPy array. Vector with length `num_centroids`.
    patches: Optional input tensor for the patches. If None, a placeholder will
      be used.

  Returns:
    The predictions (class ids) tensor determined from the input patches. Vector
    with the same length as `patches`.
  """
  with tf.name_scope('knn_model'):
    centroids = tf.identity(
        _to_float(tf.constant(_to_uint8(centroids))), name='centroids')
    labels = tf.constant(labels, name='labels')
    centroids_shape = tf.shape(centroids)
    num_centroids = centroids_shape[0]
    patch_height = centroids_shape[1]
    patch_width = centroids_shape[2]
    flattened_centroids = tf.reshape(
        centroids, [num_centroids, patch_height * patch_width],
        name='flattened_centroids')
    if patches is None:
      patches = tf.placeholder(
          tf.float32, (None, centroids.shape[1], centroids.shape[2]),
          name='patches')
    patches_shape = tf.shape(patches)
    flattened_patches = tf.reshape(
        patches, [patches_shape[0], patches_shape[1] * patches_shape[2]],
        name='flattened_patches')
    with tf.name_scope('distance_matrix'):
      distance_matrix = _squared_euclidean_distance_matrix(
          flattened_patches, flattened_centroids)

    # Take the k centroids with the lowest distance to each patch. Wrap the k
    # constant in a tf.identity, which tests can use to feed in another value.
    k_value = tf.identity(tf.constant(K_NEAREST_VALUE), name='k_nearest_value')
    nearest_centroid_inds = tf.nn.top_k(-distance_matrix, k=k_value)[1]
    # Get the label corresponding to each nearby centroids, and reshape the
    # labels back to the original shape.
    nearest_labels = tf.reshape(
        tf.gather(labels, tf.reshape(nearest_centroid_inds, [-1])),
        tf.shape(nearest_centroid_inds),
        name='nearest_labels')
    # Make a histogram of counts for each glyph type in the nearest centroids,
    # for each row (patch).
    length = NUM_GLYPHS
    bins = tf.map_fn(
        lambda row: tf.bincount(row, minlength=length, maxlength=length),
        tf.to_int32(nearest_labels),
        name='bins')
    with tf.name_scope('mode_out_of_k'):
      # Take the argmax of the histogram to get the top prediction. Discard
      # glyph type 1 (NONE) for now.
      mode_out_of_k = tf.argmax(
          bins[:, musicscore_pb2.Glyph.NONE + 1:], axis=1) + 2
      # Force predictions to NONE only if all k nearby centroids were NONE.
      # Otherwise, the non-NONE nearby centroids will contribute to the
      # prediction.
      mode_out_of_k = tf.where(
          tf.equal(bins[:, musicscore_pb2.Glyph.NONE], k_value),
          tf.fill(
              tf.shape(mode_out_of_k), tf.to_int64(musicscore_pb2.Glyph.NONE)),
          mode_out_of_k)
    return tf.identity(mode_out_of_k, name='predictions')

def _to_uint8(values):
  return np.rint(values * 255).astype(np.uint8)

def _to_float(values_t):
  return tf.to_float(values_t) / tf.constant(255.)

def export_knn_model(centroids, labels, export_path):
  """Writes the KNN saved model.

  Args:
    centroids: The k-means centroids NumPy array.
    labels: The labels of the k-means centroids.
    export_path: The output saved model directory.
  """
  g = tf.Graph()
  with g.as_default():
    predictions = knn_kmeans_model(centroids, labels)
    patches = g.get_tensor_by_name('knn_model/patches:0')
    predictions_info = tf.saved_model.utils.build_tensor_info(predictions)
    patches_info = tf.saved_model.utils.build_tensor_info(patches)
    with tf.Session(graph=g) as sess:
      builder = tf.saved_model.builder.SavedModelBuilder(export_path)
      builder.add_meta_graph_and_variables(
          sess, ['serve'],
          signature_def_map={
              tf.saved_model.signature_constants
              .DEFAULT_SERVING_SIGNATURE_DEF_KEY:
                  tf.saved_model.signature_def_utils.build_signature_def(
                      inputs={'input': patches_info},
                      outputs={
                          prediction_keys.PredictionKeys.CLASS_IDS:
                              predictions_info
                      }),
          })
      builder.save()

def _squared_euclidean_distance_matrix(a, b):
  # Trick for computing the squared Euclidean distance matrix.
  # Entry (i, j) = a[i].sum() + b[j].sum() - 2 * (a[i] * b[j]).sum()
  #              = sum_k (a[i, k] + b[j, k] - 2 * a[i, k] * b[j, k])
  #              = sum_k (a[i, k] - b[j, k]) ** 2
  a_sum = tf.reshape(tf.reduce_sum(a, axis=1), [-1, 1])  # column vector
  b_sum = tf.reshape(tf.reduce_sum(b, axis=1), [1, -1])  # row vector

  return a_sum + b_sum - 2 * tf.matmul(a, b, transpose_b=True)