text:
import { crc32 } from "@stardazed/zlib";

/**
 * Class to apply and create BPS's.
 *
 * @see https://www.romhacking.net/documents/746/
 */
export default class BPS {
  static readonly ACTION_SOURCE_READ = 0;
  static readonly ACTION_TARGET_READ = 1;
  static readonly ACTION_SOURCE_COPY = 2;
  static readonly ACTION_TARGET_COPY = 3;

  public sourceSize: number;
  public targetSize: number;
  private metaDataString: string;
  public meta: object;
  private actionsOffset: number;
  private patchFile: Uint8Array | null;
  private sourceFile: Uint8Array | null;
  private targetFile: Uint8Array | null;
  private sourceChecksum: number;
  private targetChecksum: number;
  private patchSourceChecksum: number;
  private patchTargetChecksum: number;
  private patchChecksum: number;

  constructor() {
    this.sourceSize = 0;
    this.targetSize = 0;
    this.metaDataString = "";
    this.meta = {};
    this.actionsOffset = 0;
    this.sourceFile = null;
    this.sourceChecksum = 0;
    this.targetFile = null;
    this.targetChecksum = 0;
    this.patchSourceChecksum = 0;
    this.patchTargetChecksum = 0;
    this.patchChecksum = 0;
    this.patchFile = null;
  }

  /**
   * Set the patch file to be used.
   *
   * @param file BPS formatted file.
   */
  setPatch(file: ArrayBuffer) {
    this.patchFile = new Uint8Array(file);

    // Check BPS1 at beginning of patch file
    const checkHeader = new Uint32Array(file.slice(0, 4))[0];
    if (checkHeader !== 827543618) {
      throw new Error("Not a valid patch file");
    }

    let seek = 4; // skip BPS1
    const decodedSourceSize = this.decodeBPS(this.patchFile, seek);
    this.sourceSize = decodedSourceSize.number;
    seek += decodedSourceSize.length;
    const decodedTargetSize = this.decodeBPS(this.patchFile, seek);
    this.targetSize = decodedTargetSize.number;
    seek += decodedTargetSize.length;

    const decodedMetaDataLength = this.decodeBPS(this.patchFile, seek);

    seek += decodedMetaDataLength.length;
    if (decodedMetaDataLength.number) {
      const metaArray = this.patchFile.slice(
        seek,
        seek + decodedMetaDataLength.number
      );
      for (let i = 0; i < metaArray.byteLength; ++i) {
        this.metaDataString += String.fromCharCode(metaArray[i]);
      }
      this.meta = JSON.parse(this.metaDataString);
      seek += decodedMetaDataLength.number;
    }

    this.actionsOffset = seek;

    const buf32 = new Int32Array(file.slice(file.byteLength - 12));

    this.patchSourceChecksum = buf32[0];
    this.patchTargetChecksum = buf32[1];
    this.patchChecksum = buf32[2];

    if (
      this.patchChecksum !==
      crc32(this.patchFile.slice(0, this.patchFile.byteLength - 4))
    ) {
      throw new Error("Patch checksum incorrect");
    }

    return this;
  }

  setSource(file: ArrayBuffer) {
    this.sourceFile = new Uint8Array(file);
    this.sourceChecksum = crc32(file);

    return this;
  }

  setTarget(file: ArrayBuffer) {
    this.targetFile = new Uint8Array(file);
    this.targetChecksum = crc32(file);

    return this;
  }

  /**
   * Apply the currently loaded patch to the currently loaded file and return the patched array buffer.
   */
  applyPatch() {
    if (this.patchFile === null) {
      throw new Error("Patch not set");
    }

    if (this.sourceFile === null) {
      throw new Error("Source not set");
    }

    if (this.patchSourceChecksum !== this.sourceChecksum) {
      throw new Error("Source checksum incorrect");
    }

    let newFileSize = 0;
    let seek = this.actionsOffset;

    // determine target filesize
    while (seek < this.patchFile.byteLength - 12) {
      let data = this.decodeBPS(this.patchFile, seek);
      let action = {
        type: data.number & 3,
        length: (data.number >> 2) + 1
      };

      seek += data.length;

      newFileSize += action.length;

      switch (action.type) {
        case BPS.ACTION_TARGET_READ:
          seek += action.length;
          break;
        case BPS.ACTION_SOURCE_COPY:
        case BPS.ACTION_TARGET_COPY:
          seek += this.decodeBPS(this.patchFile, seek).length;
          break;
      }
    }

    const tempFile = new ArrayBuffer(newFileSize);
    const tempFileView = new Uint8Array(tempFile);

    // patch
    let outputOffset = 0;
    let sourceRelativeOffset = 0;
    let targetRelativeOffset = 0;

    seek = this.actionsOffset;

    while (seek < this.patchFile.byteLength - 12) {
      const data = this.decodeBPS(this.patchFile, seek);
      let data2;
      const action = {
        type: data.number & 3,
        length: (data.number >> 2) + 1
      };

      seek += data.length;

      switch (action.type) {
        case BPS.ACTION_SOURCE_READ:
          for (let i = 0; i < action.length; ++i) {
            tempFileView[outputOffset + i] = this.sourceFile[outputOffset + i];
          }
          outputOffset += action.length;
          break;
        case BPS.ACTION_TARGET_READ:
          for (let i = 0; i < action.length; ++i) {
            tempFileView[outputOffset + i] = this.patchFile[seek + i];
          }
          outputOffset += action.length;
          seek += action.length;
          break;
        case BPS.ACTION_SOURCE_COPY:
          data2 = this.decodeBPS(this.patchFile, seek);
          seek += data2.length;
          sourceRelativeOffset +=
            (data2.number & 1 ? -1 : 1) * (data2.number >> 1);
          while (action.length--) {
            tempFileView[outputOffset] = this.sourceFile[sourceRelativeOffset];
            outputOffset++;
            sourceRelativeOffset++;
          }
          break;
        case BPS.ACTION_TARGET_COPY:
          data2 = this.decodeBPS(this.patchFile, seek);
          seek += data2.length;
          targetRelativeOffset +=
            (data2.number & 1 ? -1 : 1) * (data2.number >> 1);
          while (action.length--) {
            tempFileView[outputOffset] = tempFileView[targetRelativeOffset];
            outputOffset++;
            targetRelativeOffset++;
          }
          break;
      }
    }

    this.setTarget(tempFile);

    if (this.patchTargetChecksum !== this.targetChecksum) {
      throw new Error("Target checksum incorrect");
    }

    return tempFile;
  }

  /**
   * Create a patch from the source and target binaries and return it as an
   * array buffer.
   */
  createPatch() {
    throw new Error("Not Currently Implemented");
  }

  /**
   * Convert BPS number format into number.
   *
   * @todo this is inherrently dangerous with while(true)
   *
   * @param dataBytes
   * @param i
   */
  decodeBPS(dataBytes: Uint8Array, i: number) {
    let number = 0;
    let shift = 1;
    let len = 0;
    while (true) {
      let x = dataBytes[i];
      i++;
      len++;
      number += (x & 0x7f) * shift;
      if (x & 0x80) {
        break;
      }
      shift <<= 7;
      number += shift;
    }
    return {
      number: number,
      length: len
    };
  }

  /**
   * Convert number into BPS number format.
   *
   * @todo this is inherrently dangerous with while(true)
   *
   * @param toEncode
   */
  encodeBPS(toEncode: number) {
    let array = [];

    while (true) {
      let x = toEncode & 0x7f;
      toEncode >>= 7;
      if (toEncode === 0) {
        array.push(0x80 | x);

        break;
      }
      array.push(x);
      toEncode--;
    }

    return Uint8Array.from(array);
  }
}


text:
package com.tech.heathcilff.androiddevelopart.view.threeTouchEvent;

import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;

import com.tech.heathcilff.androiddevelopart.view.ViewUtil;

/**
 *
 * Created by zhangliang on 06/09/2017.
 */

public class InnerHorizontalViewGroup2 extends FrameLayout {
	private static final String TAG = "inner";
	private View child;
	public InnerHorizontalViewGroup2(@NonNull Context context) {
		super(context);
	}

	public InnerHorizontalViewGroup2(@NonNull Context context, @Nullable AttributeSet attrs) {
		super(context, attrs);
	}

	public InnerHorizontalViewGroup2(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}

	@Override
	protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
		super.onLayout(changed, left, top, right, bottom);
		child = getChildAt(0);
	}

//	private boolean interceptByParent = false;
	private float lastDispatchX, lastDispatchY;
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
//		float x = ev.getX(), y = ev.getY();
		Log.d(ViewUtil.getTouchTag(TAG, ev), "dispatchTouchEvent-xy:" + ev.getX() + "/" + ev.getY());
//		switch (ev.getAction()) {
//			case MotionEvent.ACTION_DOWN:
//				getParent().requestDisallowInterceptTouchEvent(true);
//				break;
//			case MotionEvent.ACTION_MOVE:
//				float dx = x - lastDispatchX;
//				float dy = y - lastDispatchY;
//				Log.d(TAG, "dXY:" + dx + "/" + dy);
////				interceptByParent = !(Math.abs(dx) > Math.abs(dy));
//				getParent().requestDisallowInterceptTouchEvent(Math.abs(dx) > Math.abs(dy));
//				break;
//			case MotionEvent.ACTION_UP:
//				break;
//		}
//		lastDispatchX = x;
//		lastDispatchY = y;
		return super.dispatchTouchEvent(ev);
	}

	private float lastX;
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		Log.d(ViewUtil.getTouchTag(TAG, event), "onTouchEvent-xy:" + event.getX() + "/" + event.getY());
		float x = event.getX();
		switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				break;
			case MotionEvent.ACTION_MOVE:
				float dx = x - lastX;
				boolean isAtLeftAndMoveToLeft = getScrollX() >= child.getLeft() && dx < 0;
				boolean isAtRightAndMoveToRight = -getScrollX() >= getWidth() - child.getLeft() - child.getWidth() && dx > 0;
				if(isAtLeftAndMoveToLeft) {
					scrollTo(child.getLeft(), 0);
				} else if(isAtRightAndMoveToRight){
					scrollTo(-(getWidth() - child.getLeft() - child.getWidth()), 0);
				} else {
					scrollBy((int) -dx, 0);
				}
				break;
			case MotionEvent.ACTION_UP:
				break;
		}
		lastX = x;
		return true;
	}
}

redpajama_set_name: RedPajamaGithub


text:
const path = require('path');

const userController = require('../db/userController.js');
const api = require('../db/apiController.js');

module.exports = (app) => {
  // Sign in and sign up routes
  app.post('/login', userController.login);
  app.post('/signup', userController.signup);

  // Change user information
  app.post('/changePassword', userController.changePassword);
  app.post('/changeUsername', userController.changeUsername);

  // Receive text from user to insert in database
  app.put('/text', userController.storeText);
  app.put('/speech', userController.storeSpeech);

  // Get text for profile analytics
  app.get('/text', userController.getText);
  app.get('/speech', userController.getSpeech);

  // Route dictionary and thesaurus api calls
  app.get('/dictionary/:word', api.dictionary);
  app.get('/thesaurus/:word', api.thesaurus);

  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, '../../public', 'index.html'));
  });
};


text:
"""An Encoder class for Protocol Buffers that preserves sorting characteristics.

This is used by datastore_sqlite_stub and datastore_types to match the ordering
semantics of the production datastore. Broadly, there are four
changes from regular PB encoding:

 - Strings are escaped and null terminated instead of length-prefixed. The
   escaping replaces \x00 with \x01\x01 and \x01 with \x01\x02, thus preserving
   the ordering of the original string.
 - Variable length integers are encoded using a variable length encoding that
   preserves order. The first byte stores the absolute value if it's between
   -119 to 119, otherwise it stores the number of bytes that follow.
 - Numbers are stored big endian instead of little endian.
 - Negative doubles are entirely negated, while positive doubles have their sign
   bit flipped.

Warning:
  Due to the way nested Protocol Buffers are encoded, this encoder will NOT
  preserve sorting characteristics for embedded protocol buffers!
"""

import array
import struct

from google.net.proto import ProtocolBuffer

_MAX_UNSIGNED_BYTE = 255

_MAX_LONG_BYTES = 8

_MAX_INLINE = (_MAX_UNSIGNED_BYTE - (2 * _MAX_LONG_BYTES)) / 2
_MIN_INLINE = -_MAX_INLINE
_OFFSET = 1 + 8
_POS_OFFSET = _OFFSET + _MAX_INLINE * 2

class Encoder(ProtocolBuffer.Encoder):
  """Encodes Protocol Buffers in a form that sorts nicely."""

  def put16(self, value):
    if value < 0 or value >= (1<<16):
      raise ProtocolBuffer.ProtocolBufferEncodeError, 'u16 too big'
    self.buf.append((value >> 8) & 0xff)
    self.buf.append((value >> 0) & 0xff)
    return

  def put32(self, value):
    if value < 0 or value >= (1L<<32):
      raise ProtocolBuffer.ProtocolBufferEncodeError, 'u32 too big'
    self.buf.append((value >> 24) & 0xff)
    self.buf.append((value >> 16) & 0xff)
    self.buf.append((value >> 8) & 0xff)
    self.buf.append((value >> 0) & 0xff)
    return

  def put64(self, value):
    if value < 0 or value >= (1L<<64):
      raise ProtocolBuffer.ProtocolBufferEncodeError, 'u64 too big'
    self.buf.append((value >> 56) & 0xff)
    self.buf.append((value >> 48) & 0xff)
    self.buf.append((value >> 40) & 0xff)
    self.buf.append((value >> 32) & 0xff)
    self.buf.append((value >> 24) & 0xff)
    self.buf.append((value >> 16) & 0xff)
    self.buf.append((value >> 8) & 0xff)
    self.buf.append((value >> 0) & 0xff)
    return

  def _PutVarInt(self, value):
    if value is None:
      self.buf.append(0)
      return

    if value >= _MIN_INLINE and value <= _MAX_INLINE:
      value = _OFFSET + (value - _MIN_INLINE)
      self.buf.append(value & 0xff)
      return

    negative = False

    if value < 0:
      value = _MIN_INLINE - value
      negative = True
    else:
      value = value - _MAX_INLINE

    len = 0
    w = value
    while w > 0:
      w >>= 8
      len += 1

    if negative:
      head = _OFFSET - len
    else:
      head = _POS_OFFSET + len
    self.buf.append(head & 0xff)

    for i in range(len - 1, -1, -1):
      b = value >> (i * 8)
      if negative:
        b = _MAX_UNSIGNED_BYTE - (b & 0xff)
      self.buf.append(b & 0xff)

  def putVarInt32(self, value):
    if value >= 0x80000000 or value < -0x80000000:
      raise ProtocolBuffer.ProtocolBufferEncodeError, 'int32 too big'
    self._PutVarInt(value)

  def putVarInt64(self, value):
    if value >= 0x8000000000000000 or value < -0x8000000000000000:
      raise ProtocolBuffer.ProtocolBufferEncodeError, 'int64 too big'
    self._PutVarInt(value)

  def putVarUint64(self, value):
    if value < 0 or value >= 0x10000000000000000:
      raise ProtocolBuffer.ProtocolBufferEncodeError, 'uint64 too big'
    self._PutVarInt(value)

  def _isFloatNegative(self, value, encoded):
    if value == 0:
      return encoded[0] == 128
    return value < 0

  def putFloat(self, value):
    encoded = array.array('B')
    encoded.fromstring(struct.pack('>f', value))
    if self._isFloatNegative(value, encoded):

      encoded[0] ^= 0xFF
      encoded[1] ^= 0xFF
      encoded[2] ^= 0xFF
      encoded[3] ^= 0xFF
    else:

      encoded[0] ^= 0x80
    self.buf.extend(encoded)

  def putDouble(self, value):
    encoded = array.array('B')
    encoded.fromstring(struct.pack('>d', value))
    if self._isFloatNegative(value, encoded):

      encoded[0] ^= 0xFF
      encoded[1] ^= 0xFF
      encoded[2] ^= 0xFF
      encoded[3] ^= 0xFF
      encoded[4] ^= 0xFF
      encoded[5] ^= 0xFF
      encoded[6] ^= 0xFF
      encoded[7] ^= 0xFF
    else:

      encoded[0] ^= 0x80
    self.buf.extend(encoded)

  def putPrefixedString(self, value):

    self.buf.fromstring(
        value.replace('\x01', '\x01\x02').replace('\x00', '\x01\x01') + '\x00')

class Decoder(ProtocolBuffer.Decoder):
  def __init__(self, buf, idx=0, limit=None):
    if not limit:
      limit = len(buf)
    ProtocolBuffer.Decoder.__init__(self, buf, idx, limit)

  def get16(self):
    if self.idx + 2 > self.limit:
      raise ProtocolBuffer.ProtocolBufferDecodeError, 'truncated'
    c = self.buf[self.idx]
    d = self.buf[self.idx + 1]
    self.idx += 2
    return (c << 8) | d

  def get32(self):
    if self.idx + 4 > self.limit:
      raise ProtocolBuffer.ProtocolBufferDecodeError, 'truncated'
    c = long(self.buf[self.idx])
    d = self.buf[self.idx + 1]
    e = self.buf[self.idx + 2]
    f = self.buf[self.idx + 3]
    self.idx += 4
    return (c << 24) | (d << 16) | (e << 8) | f

  def get64(self):
    if self.idx + 8 > self.limit:
      raise ProtocolBuffer.ProtocolBufferDecodeError, 'truncated'
    c = long(self.buf[self.idx])
    d = long(self.buf[self.idx + 1])
    e = long(self.buf[self.idx + 2])
    f = long(self.buf[self.idx + 3])
    g = long(self.buf[self.idx + 4])
    h = self.buf[self.idx + 5]
    i = self.buf[self.idx + 6]
    j = self.buf[self.idx + 7]
    self.idx += 8
    return ((c << 56) | (d << 48) | (e << 40) | (f << 32) | (g << 24)
            | (h << 16) | (i << 8) | j)

  def getVarInt64(self):
    b = self.get8()
    if b >= _OFFSET and b <= _POS_OFFSET:
      return b - _OFFSET + _MIN_INLINE
    if b == 0:
      return None

    if b < _OFFSET:
      negative = True
      bytes = _OFFSET - b
    else:
      negative = False
      bytes = b - _POS_OFFSET

    ret = 0
    for _ in range(bytes):
      b = self.get8()
      if negative:
        b = _MAX_UNSIGNED_BYTE - b
      ret = ret << 8 | b

    if negative:
      return _MIN_INLINE - ret
    else:
      return ret + _MAX_INLINE

  def getVarInt32(self):
    result = self.getVarInt64()
    if result >= 0x80000000L or result < -0x80000000L:
      raise ProtocolBuffer.ProtocolBufferDecodeError, 'corrupted'
    return result

  def getVarUint64(self):
    result = self.getVarInt64()
    if result < 0:
      raise ProtocolBuffer.ProtocolBufferDecodeError, 'corrupted'
    return result

  def getFloat(self):
    if self.idx + 4 > self.limit:
      raise ProtocolBuffer.ProtocolBufferDecodeError, 'truncated'
    a = self.buf[self.idx:self.idx+4]
    self.idx += 4
    if a[0] & 0x80:

      a[0] ^= 0x80
    else:

      a = [x ^ 0xFF for x in a]
    return struct.unpack('>f', array.array('B', a).tostring())[0]

  def getDouble(self):
    if self.idx + 8 > self.limit:
      raise ProtocolBuffer.ProtocolBufferDecodeError, 'truncated'
    a = self.buf[self.idx:self.idx+8]
    self.idx += 8
    if a[0] & 0x80:

      a[0] ^= 0x80
    else:

      a = [x ^ 0xFF for x in a]
    return struct.unpack('>d', array.array('B', a).tostring())[0]

  def getPrefixedString(self):
    end_idx = self.idx
    while self.buf[end_idx] != 0:
      end_idx += 1

    data = array.array('B', self.buf[self.idx:end_idx]).tostring()
    self.idx = end_idx + 1
    return data.replace('\x01\x01', '\x00').replace('\x01\x02', '\x01')


text:
#region File Description
//-----------------------------------------------------------------------------
// GameSprite3D.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using RobotGameData.Render;
using RobotGameData.Resource;
using RobotGameData.Collision;
using RobotGameData.GameInterface;
using RobotGameData.Helper;
#endregion

namespace RobotGameData.GameObject
{
    /// <summary>
    /// this sprite constantly looks at the view matrix at anywhere in the 3D world.
    /// A rotation feature, which allows the rotation around the axis that
    /// is pointing toward the view, is provided.
    /// </summary>
    public class GameSprite3D : GameMesh
    {
        #region Sprite3DObject

        /// <summary>
        /// this structure the information of 3D sprite object.
        /// </summary>
        public class Sprite3DObject : INamed
        {
            [Flags]
            public enum UpdateTypes
            {
                None = 0x00000000,
                Position = 0x00000001,
                Texturecoord = 0x00000002,
                Color = 0x00000004,
                Rotation = 0x00000010,
                Flip = 0x00000040,
            }

            String name = String.Empty;
            bool enable = true;
            Vector3 center = new Vector3(0, 0, 0);
            float width = 1.0f;
            float height = 1.0f;
            Color color = new Color(255, 255, 255, 255);
            float rotation = 0.0f;
            Vector2[] uv = new Vector2[2]
                {
                    Vector2.Zero,
                    Vector2.One,
                };
            bool flipX = false;
            bool flipY = false;
            uint updateFlag = 0;

            public string Name
            {
                get { return name; }
                set { name = value; }
            }

            public bool Enable
            {
                get { return this.enable; }
                set { this.enable = value; }
            }

            public Vector3 Center
            {
                get { return this.center; }
                set { this.center = value; }
            }

            public float Width
            {
                get { return this.width; }
                set { this.width = value; }
            }

            public float Height
            {
                get { return this.height; }
                set { this.height = value; }
            }

            public Color Color
            {
                get { return this.color; }
                set { this.color = value; }
            }

            public float Rotation
            {
                get { return this.rotation; }
                set { this.rotation = value; }
            }

            public bool FlipX
            {
                get { return this.flipX; }
                set { this.flipX = value; }
            }

            public bool FlipY
            {
                get { return this.flipY; }
                set { this.flipY = value; }
            }

            public void AddUpdateType(UpdateTypes updateType)
            {
                this.updateFlag |= (uint)updateType;
            }

            public void RemoveUpdateType(UpdateTypes updateType)
            {
                this.updateFlag &= ~(uint)updateType;
            }

            public Vector2 MinUV
            {
                get { return this.uv[0]; }
                set { this.uv[0] = value; }
            }

            public Vector2 MaxUV
            {
                get { return this.uv[1]; }
                set { this.uv[1] = value; }
            }
        }

        #endregion

        #region Fields

        const int vertexStride = 4;
        const int indexStride = 6;

        List<Sprite3DObject> spriteList = new List<Sprite3DObject>();

        RenderingSpace renderingSpace = RenderingSpace.World;
        Matrix lastViewMatrix;
        int count = 0;

        bool needToUpdate = false;
        bool alwaysUpdate = false;

        #endregion

        #region Properties

        public int Count
        {
            get { return this.count; }
        }

        #endregion

        /// <summary>
        /// updates the vertex data and draws
        /// </summary>
        /// <param name="renderTracer">render information</param>
        protected override void OnDraw(RenderTracer renderTracer)
        {
            int objectCount = 0;

            for (int i = 0; i < this.count; i++)
            {
                if (spriteList[i].Enable == false) continue;
                objectCount++;
            }

            if (objectCount == 0) return;

            PrimitiveCount = objectCount * 2;
            UpdateVertexCount = this.count * vertexStride;

            //  needs to update?
            if (renderTracer.View != lastViewMatrix)
            {
                needToUpdate = true;
                this.lastViewMatrix = renderTracer.View;
            }

            if (alwaysUpdate || needToUpdate)
            {
                int vertexOffset = 0;
                int indexOffset = 0;

                for (int i = 0; i < this.count; i++)
                {
                    Sprite3DObject obj = spriteList[i];

                    if (obj.Enable == false) continue;

                    //  rotates the paticle by z-axis. (Sprite3D can rotate)
                    Matrix transformMatrix = Matrix.CreateRotationZ(obj.Rotation) *
                                            Helper3D.Transpose(
                                            this.TransformedMatrix * renderTracer.View);

                    //  updates vertex positions.
                    SetBufferPosition(ref vertexData, obj, vertexOffset,
                                      transformMatrix, this.renderingSpace);

                    //  updates texture coordinates.
                    SetBufferTextureCoord(ref vertexData, obj, vertexOffset,
                                          this.renderingSpace);

                    //  updates vertex colors.
                    SetBufferColor(ref vertexData, obj, vertexOffset);

                    indexData[indexOffset + 0] = (short)(vertexOffset + 0);
                    indexData[indexOffset + 1] = (short)(vertexOffset + 2);
                    indexData[indexOffset + 2] = (short)(vertexOffset + 1);
                    indexData[indexOffset + 3] = (short)(vertexOffset + 1);
                    indexData[indexOffset + 4] = (short)(vertexOffset + 2);
                    indexData[indexOffset + 5] = (short)(vertexOffset + 3);

                    vertexOffset += vertexStride;
                    indexOffset += indexStride;
                }

                if (userPrimitive == false)
                {
                    //  binds the vertex buffer.
                    BindVertexBuffer();

                    //  binds the index buffer.
                    BindIndexBuffer();
                }

                if (needToUpdate)
                    needToUpdate = false;
            }

            // draws mesh
            base.OnDraw(renderTracer);
        }

        /// <summary>
        /// create 3D sprite objects using the texture.
        /// </summary>
        /// <param name="count">sprite object count</param>
        /// <param name="fileName">texture file name</param>
        /// <param name="space">3D render space</param>
        /// <param name="bAlwaysUpdate"></param>
        public void Create(int count, string fileName, RenderingSpace space,
                            bool bAlwaysUpdate)
        {
            //  Load texture
            GameResourceTexture2D resource =
                                FrameworkCore.ResourceManager.LoadTexture(fileName);

            Create(count, resource.Texture2D, space, bAlwaysUpdate);
        }

        /// <summary>
        /// create 3D sprite objects using the texture.
        /// </summary>
        /// <param name="count">sprite object count</param>
        /// <param name="texture">texture resource</param>
        /// <param name="space">3D render space</param>
        /// <param name="bAlwaysUpdate"></param>
        public void Create(int count, Texture2D texture, RenderingSpace space,
                           bool bAlwaysUpdate)
        {
            this.count = count;
            this.renderingSpace = space;
            alwaysUpdate = bAlwaysUpdate;

            for (int i = 0; i < count; i++)
                spriteList.Add(new Sprite3DObject());

            base.Create(count * vertexStride, count * indexStride, texture);
        }

        protected override void UnloadContent()
        {
            spriteList.Clear();

            base.UnloadContent();
        }

        /// <summary>
        /// enables/disables all sprite objects.
        /// </summary>
        /// <param name="enable"></param>
        public void SetObjectEnable(bool enable)
        {
            for (int i = 0; i < spriteList.Count; i++)
                SetObjectEnable(i, enable);
        }

        /// <summary>
        /// enables/disables an individual sprite object.
        /// </summary>
        public void SetObjectEnable(int index, bool enable)
        {
            if (spriteList.Count <= index || 0 > index)
                throw new ArgumentException("Invalid index.");

            if (spriteList[index].Enable != enable)
            {
                spriteList[index].Enable = enable;
                needToUpdate = true;
            }
        }

        /// <summary>
        /// configures a center position of each sprite object.
        /// </summary>
        /// <param name="index">an index of sprite object</param>
        /// <param name="position">a center position</param>
        public void SetCenter(int index, Vector3 position)
        {
            if (spriteList.Count <= index || 0 > index)
                throw new ArgumentException("Invalid index.");

            spriteList[index].Center = position;
            spriteList[index].AddUpdateType(Sprite3DObject.UpdateTypes.Position);

            needToUpdate = true;
        }

        /// <summary>
        /// gets a left top position of each sprite object.
        /// </summary>
        /// <param name="index">an index of sprite object</param>
        /// <param name="vec">out vector</param>
        public void GetLeftTop(int index, ref Vector3 vec)
        {
            if (spriteList.Count <= index || 0 > index)
                throw new ArgumentException("Invalid index.");

            vec.X = spriteList[index].Center.X - (spriteList[index].Width * 0.5f);
            vec.Y = spriteList[index].Center.Y - (spriteList[index].Height * 0.5f);
            vec.Z = spriteList[index].Center.Z;
        }

        /// <summary>
        /// gets a right down position of each sprite object.
        /// </summary>
        /// <param name="index">an index of sprite object</param>
        /// <param name="vec">out vector</param>
        public void GetRightBottom(int index, ref Vector3 vec)
        {
            if (spriteList.Count <= index || 0 > index)
                throw new ArgumentException("Invalid index.");

            vec.X = spriteList[index].Center.X + (spriteList[index].Width * 0.5f);
            vec.Y = spriteList[index].Center.Y + (spriteList[index].Height * 0.5f);
            vec.Z = spriteList[index].Center.Z;
        }

        /// <summary>
        /// configures a rotation value of each sprite object.
        /// </summary>
        /// <param name="index">an index of sprite object</param>
        /// <param name="rotation">rotation angle</param>
        public void SetRotation(int index, float amount)
        {
            if (spriteList.Count <= index || 0 > index)
                throw new ArgumentException("Invalid index.");

            spriteList[index].Rotation = amount;
            spriteList[index].AddUpdateType(Sprite3DObject.UpdateTypes.Rotation);
            needToUpdate = true;
        }

        /// <summary>
        /// flips each sprite object around x-axis and/or y-axis.
        /// </summary>
        /// <param name="index">an index of sprite object</param>
        /// <param name="flipX">specifies whether to rotate around x-axis</param>
        /// <param name="flipY">specifies whether to rotate around y-axis</param>
        public void SetFlip(int index, bool flipX, bool flipY)
        {
            if (spriteList.Count <= index || 0 > index)
                throw new ArgumentException("Invalid index.");

            spriteList[index].FlipX = flipX;
            spriteList[index].FlipY = flipY;

            spriteList[index].AddUpdateType(Sprite3DObject.UpdateTypes.Flip);
            needToUpdate = true;
        }

        /// <summary>
        /// configures the size of each sprite object.
        /// </summary>
        /// <param name="index">an index of sprite object</param>
        /// <param name="size">size vector</param>
        public void SetSize(int index, Vector2 size)
        {
            if (spriteList.Count <= index || 0 > index)
                throw new ArgumentException("Invalid index.");

            spriteList[index].Width = size.X;
            spriteList[index].Height = size.Y;

            spriteList[index].AddUpdateType(Sprite3DObject.UpdateTypes.Position);
            needToUpdate = true;
        }

        /// <summary>
        /// configures the size of each sprite object.
        /// </summary>
        /// <param name="index">an index of sprite object</param>
        /// <param name="width">size of width</param>
        /// <param name="height">size of height</param>
        public void SetSize(int index, float width, float height)
        {
            SetSize(index, new Vector2(width, height));
        }

        /// <summary>
        /// configures the texture coordinates of each sprite object.
        /// </summary>
        /// <param name="index">an index of sprite object</param>
        /// <param name="min">texture coordinates of minimum</param>
        /// <param name="max">texture coordinates of maximum</param>
        public void SetTextureCoord(int index, Vector2 min, Vector2 max)
        {
            if (spriteList.Count <= index || 0 > index)
                throw new ArgumentException("Invalid index.");

            spriteList[index].MinUV = min;
            spriteList[index].MaxUV = max;

            spriteList[index].AddUpdateType(Sprite3DObject.UpdateTypes.Texturecoord);
            needToUpdate = true;
        }

        /// <summary>
        /// configures the texture coordinates of each sprite object.
        /// </summary>
        /// <param name="index">an index of sprite object</param>
        /// <param name="u1">texture "u1" coordinate</param>
        /// <param name="v1">texture "v1" coordinate</param>
        /// <param name="u2">texture "u2" coordinate</param>
        /// <param name="v2">texture "v2" coordinate</param>
        public void SetTextureCoord(int index, float u1, float v1, float u2, float v2)
        {
            SetTextureCoord(index, new Vector2(u1, v1), new Vector2(u2, v2));
        }

        /// <summary>
        /// configures the vertex color of each sprite object.
        /// </summary>
        /// <param name="index">an index of sprite object</param>
        /// <param name="color">color</param>
        public void SetColor(int index, Color color)
        {
            if (spriteList.Count <= index || 0 > index)
                throw new ArgumentException("Invalid index.");

            spriteList[index].Color = color;
            spriteList[index].AddUpdateType(Sprite3DObject.UpdateTypes.Color);

            needToUpdate = true;
        }

        /// <summary>
        /// configures the vertex color of each sprite object.
        /// </summary>
        /// <param name="index">an index of sprite object</param>
        /// <param name="r">a red component of color</param>
        /// <param name="g">a green component of color</param>
        /// <param name="b">a blue component of color</param>
        /// <param name="a">an alpha component of color</param>
        public void SetColor(int index, byte r, byte g, byte b, byte a)
        {
            SetColor(index, new Color(r,g,b,a));
        }

        /// <summary>
        /// configures a transformed matrix to the vertex component data
        /// using the sprite object.
        /// </summary>
        /// <param name="vertexData">target vertex component data</param>
        /// <param name="obj">source sprite object</param>
        /// <param name="startIndex">start index of the vertex component data</param>
        /// <param name="transformMatrix">transformed matrix</param>
        /// <param name="space">3D render space</param>
        private static void SetBufferPosition(
            ref VertexPositionColorTexture[] vertexData, Sprite3DObject obj,
            int startIndex, Matrix transformMatrix, RenderingSpace space)
        {
            float cx = obj.Width * 0.5f;
            float cy = obj.Height * 0.5f;

            vertexData[startIndex + 0].Position = new Vector3(-cx, +cy, 0.0f);
            vertexData[startIndex + 1].Position = new Vector3(+cx, +cy, 0.0f);
            vertexData[startIndex + 2].Position = new Vector3(-cx, -cy, 0.0f);
            vertexData[startIndex + 3].Position = new Vector3(+cx, -cy, 0.0f);

            for (int i = 0; i < 4; i++)
            {
                int arrayIndex = startIndex + i;

                Vector3.TransformNormal(ref vertexData[arrayIndex].Position,
                                        ref transformMatrix,
                                        out vertexData[arrayIndex].Position);

                vertexData[arrayIndex].Position += obj.Center;

                if (space == RenderingSpace.Screen)
                    vertexData[arrayIndex].Position =
                                HelperMath.Make2DCoord(vertexData[arrayIndex].Position);
            }
        }

        /// <summary>
        /// configures texture coordinates to the vertex component data
        /// using the sprite object.
        /// </summary>
        /// <param name="vertexData">target vertex component data</param>
        /// <param name="obj">source sprite object</param>
        /// <param name="startIndex">start index of the vertex component data</param>
        /// <param name="space">3D render space</param>
        private static void SetBufferTextureCoord(
            ref VertexPositionColorTexture[] vertexData, Sprite3DObject obj,
            int startIndex, RenderingSpace space)
        {
            float u1 = 0.0f, v1 = 0.0f, u2 = 0.0f, v2 = 0.0f;

            // Differ Y axis of the 3D and 2D
            bool flipY = (space == RenderingSpace.Screen ? !obj.FlipY : obj.FlipY);

            if (obj.FlipX)
            {
                if (flipY)
                {
                    u1 = obj.MaxUV.X;
                    v1 = obj.MaxUV.Y;
                    u2 = obj.MinUV.X;
                    v2 = obj.MinUV.Y;
                }
                else
                {
                    u1 = obj.MaxUV.X;
                    v1 = obj.MinUV.Y;
                    u2 = obj.MinUV.X;
                    v2 = obj.MaxUV.Y;
                }
            }
            else
            {
                if (flipY)
                {
                    u1 = obj.MinUV.X;
                    v1 = obj.MaxUV.Y;
                    u2 = obj.MaxUV.X;
                    v2 = obj.MinUV.Y;
                }
                else
                {
                    u1 = obj.MinUV.X;
                    v1 = obj.MinUV.Y;
                    u2 = obj.MaxUV.X;
                    v2 = obj.MaxUV.Y;
                }
            }

            vertexData[startIndex + 0].TextureCoordinate = new Vector2(u1, v1);
            vertexData[startIndex + 1].TextureCoordinate = new Vector2(u2, v1);
            vertexData[startIndex + 2].TextureCoordinate = new Vector2(u1, v2);
            vertexData[startIndex + 3].TextureCoordinate = new Vector2(u2, v2);
        }

        /// <summary>
        /// configures vertex color to the vertex component data using the sprite object.
        /// </summary>
        /// <param name="vertexData">target vertex component data</param>
        /// <param name="obj">source sprite object</param>
        /// <param name="startIndex">start index of the vertex component data</param>
        private static void SetBufferColor(ref VertexPositionColorTexture[] vertexData,
                                    Sprite3DObject obj, int startIndex)
        {
            for( int i = 0; i < 4; i++)
                vertexData[startIndex + i].Color = obj.Color;
        }
    }
}


text:
solutely beside him in the passage. Then
in the darkness he took the boy's hand andthe answer is sunfishes  pressed it.

"Come in, come in!" he repeated in a gentle whisper. "Oh, what can I
do for him?" he thought, and opening the door he let the boy pass in
first.

When the boy had entered the hut, Petya sat down at a distance
from him, considering it beneath his dignity to pay attention


text:
function(get_swift_host_arch result_var_name)
  if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64")
    set("${result_var_name}" "x86_64" PARENT_SCOPE)
  elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "aarch64")
    set("${result_var_name}" "aarch64" PARENT_SCOPE)
  elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64")
    set("${result_var_name}" "powerpc64" PARENT_SCOPE)
  elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64le")
    set("${result_var_name}" "powerpc64le" PARENT_SCOPE)
  elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "s390x")
    set("${result_var_name}" "s390x" PARENT_SCOPE)
  elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv6l")
    set("${result_var_name}" "armv6" PARENT_SCOPE)
  elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7l")
    set("${result_var_name}" "armv7" PARENT_SCOPE)
  elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7-a")
    set("${result_var_name}" "armv7" PARENT_SCOPE)
  elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "AMD64")
    set("${result_var_name}" "x86_64" PARENT_SCOPE)
  elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "IA64")
    set("${result_var_name}" "itanium" PARENT_SCOPE)
  elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86")
    set("${result_var_name}" "i686" PARENT_SCOPE)
  elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "i686")
    set("${result_var_name}" "i686" PARENT_SCOPE)
  else()
    message(FATAL_ERROR "Unrecognized architecture on host system: ${CMAKE_SYSTEM_PROCESSOR}")
  endif()
endfunction()

# Returns the os name in a variable
#
# Usage:
#   get_swift_host_os(result_var_name)
#
#
# Sets ${result_var_name} with the converted OS name derived from
# CMAKE_SYSTEM_NAME.
function(get_swift_host_os result_var_name)
  if(CMAKE_SYSTEM_NAME STREQUAL Darwin)
    set(${result_var_name} macosx PARENT_SCOPE)
  else()
    string(TOLOWER ${CMAKE_SYSTEM_NAME} cmake_system_name_lc)
    set(${result_var_name} ${cmake_system_name_lc} PARENT_SCOPE)
  endif()
endfunction()

function(_install_target module)
  get_swift_host_os(swift_os)
  get_target_property(type ${module} TYPE)

  if(type STREQUAL STATIC_LIBRARY)
    set(swift swift_static)
  else()
    set(swift swift)
  endif()

  install(TARGETS ${module}
    ARCHIVE DESTINATION lib/${swift}/${swift_os}
    LIBRARY DESTINATION lib/${swift}/${swift_os}
    RUNTIME DESTINATION bin)
  if(type STREQUAL EXECUTABLE)
    return()
  endif()

  get_swift_host_arch(swift_arch)
  get_target_property(module_name ${module} Swift_MODULE_NAME)
  if(NOT module_name)
    set(module_name ${module})
  endif()

  if(CMAKE_SYSTEM_NAME STREQUAL Darwin)
    install(FILES $<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module_name}.swiftdoc
      DESTINATION lib/${swift}/${swift_os}/${module_name}.swiftmodule
      RENAME ${swift_arch}.swiftdoc)
    install(FILES $<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module_name}.swiftmodule
      DESTINATION lib/${swift}/${swift_os}/${module_name}.swiftmodule
      RENAME ${swift_arch}.swiftmodule)
  else()
    install(FILES
      $<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module_name}.swiftdoc
      $<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module_name}.swiftmodule
      DESTINATION lib/${swift}/${swift_os}/${swift_arch})
  endif()
endfunction()


text:
package com.jjforever.wgj.maincalendar.common.util;

import android.app.Activity;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.Window;
import android.view.WindowManager;

/**
 * 获取屏幕宽高等信息、全屏切换、保持屏幕常亮、截屏等
 *
 * @author liyujiang[QQ:1032694760]
 * @since 2015/11/26
 */
public final class ScreenUtils {
    private static boolean isFullScreen = false;

    /**
     * Display metrics display metrics.
     *
     * @param context the context
     * @return the display metrics
     */
    public static DisplayMetrics displayMetrics(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        LogUtils.debug("screen width=" + dm.widthPixels + "px, screen height=" + dm.heightPixels
                + "px, densityDpi=" + dm.densityDpi + ", density=" + dm.density);
        return dm;
    }

    /**
     * Width pixels int.
     *
     * @param context the context
     * @return the int
     */
    public static int widthPixels(Context context) {
        return displayMetrics(context).widthPixels;
    }

    /**
     * Height pixels int.
     *
     * @param context the context
     * @return the int
     */
    public static int heightPixels(Context context) {
        return displayMetrics(context).heightPixels;
    }

    /**
     * Density float.
     *
     * @param context the context
     * @return the float
     */
    public static float density(Context context) {
        return displayMetrics(context).density;
    }

    /**
     * Density dpi int.
     *
     * @param context the context
     * @return the int
     */
    public static int densityDpi(Context context) {
        return displayMetrics(context).densityDpi;
    }

    /**
     * Is full screen boolean.
     *
     * @return the boolean
     */
    public static boolean isFullScreen() {
        return isFullScreen;
    }

    /**
     * Toggle full displayMetrics.
     *
     * @param activity the activity
     */
    public static void toggleFullScreen(Activity activity) {
        Window window = activity.getWindow();
        int flagFullscreen = WindowManager.LayoutParams.FLAG_FULLSCREEN;
        if (isFullScreen) {
            window.clearFlags(flagFullscreen);
            isFullScreen = false;
        } else {
            window.setFlags(flagFullscreen, flagFullscreen);
            isFullScreen = true;
        }
    }

    /**
     * 保持屏幕常亮
     *
     * @param activity the activity
     */
    public static void keepBright(Activity activity) {
        //需在setContentView前调用
        int keepScreenOn = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        activity.getWindow().setFlags(keepScreenOn, keepScreenOn);
    }

}


text:
import sinon from 'auto-release-sinon';
import searchResponse from 'fixtures/search_response';
import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern';

export default function stubSearchSource(Private, $q, Promise) {
  let deferedResult = $q.defer();
  const indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider);

  return {
    sort: sinon.spy(),
    size: sinon.spy(),
    fetch: sinon.spy(),
    destroy: sinon.spy(),
    get: function (param) {
      switch (param) {
        case 'index':
          return indexPattern;
        default:
          throw new Error('Param "' + param + '" is not implemented in the stubbed search source');
      }
    },
    crankResults: function () {
      deferedResult.resolve(searchResponse);
      deferedResult = $q.defer();
    },
    onResults: function () {
      // Up to the test to resolve this manually
      // For example:
      // someHandler.resolve(require('fixtures/search_response'))
      return deferedResult.promise;
    },
    onError: function () { return $q.defer().promise; },
    _flatten: function () {
      return Promise.resolve({ index: indexPattern, body: {} });
    }
  };

}


text:
@implementation OrgApacheLuceneUtilGeoDistanceUtils

J2OBJC_IGNORE_DESIGNATED_BEGIN
- (instancetype)init {
  OrgApacheLuceneUtilGeoDistanceUtils_init(self);
  return self;
}
J2OBJC_IGNORE_DESIGNATED_END

+ (jdouble)vincentyDistanceWithDouble:(jdouble)lonA
                           withDouble:(jdouble)latA
                           withDouble:(jdouble)lonB
                           withDouble:(jdouble)latB {
  return OrgApacheLuceneUtilGeoDistanceUtils_vincentyDistanceWithDouble_withDouble_withDouble_withDouble_(lonA, latA, lonB, latB);
}

+ (jdouble)distanceToDegreesLonWithDouble:(jdouble)lat
                               withDouble:(jdouble)distance {
  return OrgApacheLuceneUtilGeoDistanceUtils_distanceToDegreesLonWithDouble_withDouble_(lat, distance);
}

+ (jdouble)distanceToDegreesLatWithDouble:(jdouble)lat
                               withDouble:(jdouble)distance {
  return OrgApacheLuceneUtilGeoDistanceUtils_distanceToDegreesLatWithDouble_withDouble_(lat, distance);
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x1, -1, -1, -1, -1, -1, -1 },
    { NULL, "D", 0x19, 0, 1, -1, -1, -1, -1 },
    { NULL, "D", 0x9, 2, 3, -1, -1, -1, -1 },
    { NULL, "D", 0x9, 4, 3, -1, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(init);
  methods[1].selector = @selector(vincentyDistanceWithDouble:withDouble:withDouble:withDouble:);
  methods[2].selector = @selector(distanceToDegreesLonWithDouble:withDouble:);
  methods[3].selector = @selector(distanceToDegreesLatWithDouble:withDouble:);
  #pragma clang diagnostic pop
  static const void *ptrTable[] = { "vincentyDistance", "DDDD", "distanceToDegreesLon", "DD", "distanceToDegreesLat" };
  static const J2ObjcClassInfo _OrgApacheLuceneUtilGeoDistanceUtils = { "GeoDistanceUtils", "org.apache.lucene.util", ptrTable, methods, NULL, 7, 0x1, 4, 0, -1, -1, -1, -1, -1 };
  return &_OrgApacheLuceneUtilGeoDistanceUtils;
}

@end

void OrgApacheLuceneUtilGeoDistanceUtils_init(OrgApacheLuceneUtilGeoDistanceUtils *self) {
  NSObject_init(self);
}

OrgApacheLuceneUtilGeoDistanceUtils *new_OrgApacheLuceneUtilGeoDistanceUtils_init() {
  J2OBJC_NEW_IMPL(OrgApacheLuceneUtilGeoDistanceUtils, init)
}

OrgApacheLuceneUtilGeoDistanceUtils *create_OrgApacheLuceneUtilGeoDistanceUtils_init() {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneUtilGeoDistanceUtils, init)
}

jdouble OrgApacheLuceneUtilGeoDistanceUtils_vincentyDistanceWithDouble_withDouble_withDouble_withDouble_(jdouble lonA, jdouble latA, jdouble lonB, jdouble latB) {
  OrgApacheLuceneUtilGeoDistanceUtils_initialize();
  jdouble L = JavaLangStrictMath_toRadiansWithDouble_(lonB - lonA);
  jdouble oF = 1 - OrgApacheLuceneUtilGeoProjectionUtils_FLATTENING;
  jdouble U1 = JavaLangStrictMath_atanWithDouble_(oF * JavaLangStrictMath_tanWithDouble_(JavaLangStrictMath_toRadiansWithDouble_(latA)));
  jdouble U2 = JavaLangStrictMath_atanWithDouble_(oF * JavaLangStrictMath_tanWithDouble_(JavaLangStrictMath_toRadiansWithDouble_(latB)));
  jdouble sU1 = JavaLangStrictMath_sinWithDouble_(U1);
  jdouble cU1 = JavaLangStrictMath_cosWithDouble_(U1);
  jdouble sU2 = JavaLangStrictMath_sinWithDouble_(U2);
  jdouble cU2 = JavaLangStrictMath_cosWithDouble_(U2);
  jdouble sigma;
  jdouble sinSigma;
  jdouble cosSigma;
  jdouble sinAlpha;
  jdouble cos2Alpha;
  jdouble cos2SigmaM;
  jdouble lambda = L;
  jdouble lambdaP;
  jdouble iters = 100;
  jdouble sinLambda;
  jdouble cosLambda;
  jdouble c;
  do {
    sinLambda = JavaLangStrictMath_sinWithDouble_(lambda);
    cosLambda = JavaLangMath_cosWithDouble_(lambda);
    sinSigma = JavaLangMath_sqrtWithDouble_((cU2 * sinLambda) * (cU2 * sinLambda) + (cU1 * sU2 - sU1 * cU2 * cosLambda) * (cU1 * sU2 - sU1 * cU2 * cosLambda));
    if (sinSigma == 0) {
      return 0;
    }
    cosSigma = sU1 * sU2 + cU1 * cU2 * cosLambda;
    sigma = JavaLangMath_atan2WithDouble_withDouble_(sinSigma, cosSigma);
    sinAlpha = cU1 * cU2 * sinLambda / sinSigma;
    cos2Alpha = 1 - sinAlpha * sinAlpha;
    cos2SigmaM = cosSigma - 2 * sU1 * sU2 / cos2Alpha;
    c = OrgApacheLuceneUtilGeoProjectionUtils_FLATTENING / 16 * cos2Alpha * (4 + OrgApacheLuceneUtilGeoProjectionUtils_FLATTENING * (4 - 3 * cos2Alpha));
    lambdaP = lambda;
    lambda = L + (1 - c) * OrgApacheLuceneUtilGeoProjectionUtils_FLATTENING * sinAlpha * (sigma + c * sinSigma * (cos2SigmaM + c * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));
  }
  while (JavaLangStrictMath_absWithDouble_(lambda - lambdaP) > 1E-12 && --iters > 0);
  if (iters == 0) {
    return 0;
  }
  jdouble uSq = cos2Alpha * (OrgApacheLuceneUtilGeoProjectionUtils_SEMIMAJOR_AXIS2 - OrgApacheLuceneUtilGeoProjectionUtils_SEMIMINOR_AXIS2) / (OrgApacheLuceneUtilGeoProjectionUtils_SEMIMINOR_AXIS2);
  jdouble A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
  jdouble B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
  jdouble deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)));
  return (OrgApacheLuceneUtilGeoProjectionUtils_SEMIMINOR_AXIS * A * (sigma - deltaSigma));
}

jdouble OrgApacheLuceneUtilGeoDistanceUtils_distanceToDegreesLonWithDouble_withDouble_(jdouble lat, jdouble distance) {
  OrgApacheLuceneUtilGeoDistanceUtils_initialize();
  JreDivideAssignDoubleD(&distance, 1000.0);
  lat = JavaLangStrictMath_toRadiansWithDouble_(lat);
  jdouble diameter = OrgApacheLuceneUtilSloppyMath_earthDiameterWithDouble_(JavaLangStrictMath_toRadiansWithDouble_(lat));
  jdouble a = JavaLangStrictMath_sinWithDouble_(distance / diameter);
  jdouble h = JavaLangStrictMath_minWithDouble_withDouble_(1, a);
  JreTimesAssignDoubleD(&h, h);
  jdouble cLat = JavaLangStrictMath_cosWithDouble_(lat);
  return JavaLangStrictMath_toDegreesWithDouble_(JavaLangStrictMath_acosWithDouble_(1 - ((2.0 * h) / (cLat * cLat))));
}

jdouble OrgApacheLuceneUtilGeoDistanceUtils_distanceToDegreesLatWithDouble_withDouble_(jdouble lat, jdouble distance) {
  OrgApacheLuceneUtilGeoDistanceUtils_initialize();
  jdouble diameter = OrgApacheLuceneUtilSloppyMath_earthDiameterWithDouble_(JavaLangStrictMath_toRadiansWithDouble_(lat));
  JreDivideAssignDoubleD(&distance, 1000.0);
  jdouble a = JavaLangStrictMath_sinWithDouble_(distance / diameter);
  jdouble h = JavaLangStrictMath_minWithDouble_withDouble_(1, a);
  JreTimesAssignDoubleD(&h, h);
  return JavaLangStrictMath_toDegreesWithDouble_(JavaLangStrictMath_acosWithDouble_(1 - (2.0 * h)));
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(OrgApacheLuceneUtilGeoDistanceUtils)


text:
package com.nfcwormhole.liquor;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.ButterKnife;

public class Main2Activity extends AppCompatActivity {
    public static String EXTRA_1 = "EXTRA_1";

    @BindView(R.id.tx1)
    TextView textView1;
    @BindView(R.id.tx2)
    TextView textView2;
    @BindView(R.id.tx3)
    TextView textView3;
    @BindView(R.id.tx4)
    TextView textView4;
    @BindView(R.id.button3)
    Button button3;

    String[] msgs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        ButterKnife.bind(this);

        Bundle extras = getIntent().getExtras();
        if (extras == null) {
            return;
        }
        String sReadNdef = extras.getString(EXTRA_1);
        if (sReadNdef != null) {
            msgs = sReadNdef.split("\\r\\n");
            if (msgs.length < 5)
                return;

            if (msgs[1].equals("1")) {
                textView1.setText("是");
            } else {
                textView1.setText("否");
            }
            textView2.setText(msgs[2]);
            textView3.setText(msgs[3]);
            textView4.setText(msgs[4]);

            MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.jinjiu);
            mediaPlayer.start();
        }

        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}


text:
create_ssh_config() {
  profile="$1"
  server="$2"
  ssh_key="$3"
  lower_server=$(echo "${server}" | tr '[:upper:]' '[:lower:]')
  new_ip=$(aws ec2 describe-instances \
    --filters \
      "Name=instance-state-code,Values=16" \
      "Name=tag:aws:autoscaling:groupName,Values=asg${server}2" \
    --profile "${profile}" \
    --query "Reservations[*].Instances[*].PublicIpAddress" \
    --output text)
  if [ "${new_ip}" = "" ]; then
    return
  fi
  cat << EOF > "$HOME/.ssh/config.d/vp-${profile}-${lower_server}"
Host vp-${profile}-${lower_server}
  HostName ${new_ip}
  User ec2-user
  Port 22
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile ~/.ssh/${ssh_key}
  IdentitiesOnly yes
  LogLevel FATAL
EOF
}

create_ssh_config prod JBoss nov159128-frankfurt.pem
create_ssh_config prod Tomcat nov159128-frankfurt.pem
create_ssh_config apptest JBoss nov015388-frankfurt.pem
create_ssh_config apptest Tomcat nov015388-frankfurt.pem


text: <version branch='TRUNK' buildId='manual-20121102'>4.8-GA</version>


text:
/**
 * openwhyd bookmarklet v2
 * @author adrienjoly, whyd
 **/

// prevents bug in firefox 3
if (undefined == window.console)
	console = {log:function(){}, info:function(){}, error:function(){}, warn:function(){}};

console.log("-= openwhyd bookmarklet v2 =-");

(function(){

	var FILENAME = "/js/bookmarkletdev.js"; // TODO

	// close the bookmarklet by pressing ESC

	window.onkeydownBackup = window.onkeydownBackup || window.document.onkeydown;

	window.closeWhydBk = function() {
		document.body.removeChild(document.getElementById('whydBookmarklet'));
		window.document.onkeydown = window.onkeydownBackup;
		delete window.onkeydownBackup;
		delete window.closeWhydBk;
	};

	window.document.onkeydown = function(e){
		if ((e || event).keyCode == 27)
			closeWhydBk();
	};

	// utility functions

	function findScriptHost(scriptPathName) {
		var els = document.getElementsByTagName("script");
		for(var i = els.length - 1; i > -1; --i) {
			var whydPathPos = els[i].src.indexOf(scriptPathName);
			if(whydPathPos > -1)
				return els[i].src.substr(0, whydPathPos);
		}
	}

	function getSelText() {
		var SelText = '';
		if (window.getSelection) {
			SelText = window.getSelection();
		} else if (document.getSelection) {
			SelText = document.getSelection();
		} else if (document.selection) {
			SelText = document.selection.createRange().text;
		}
		return SelText;
	}

	function getNodeText(node){
		return node.innerText || node.textContent;
	}

	function unwrapFacebookLink(src) {
		// e.g. http://www.facebook.com/l.php?u=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKhXn0anD1lE&h=AAQFjMJBoAQFTPOP4HzFCv0agQUHB6Un31ArdmwvxzZxofA
		var fbLink = src.split("facebook.com/l.php?u=");
		if (fbLink.length>1) {
			fbLink = decodeURIComponent(fbLink.pop().split("&").shift());
			var result = fbLink.indexOf("//www.facebook.com/") == -1 ? fbLink : src;
			return result;
		}
		return src;
	}

	function include(src, cb) {
		var inc, timer;
		if (src.split(/[\#\?]/)[0].split(".").pop().toLowerCase() == "css") {
			inc = document.createElement("link");
			inc.rel = "stylesheet";
			inc.type = "text/css";
			inc.media = "screen";
			inc.href = src;
		}
		else {
			inc = document.createElement("script");
			inc.onload = function(loaded) {
				timer = timer ? clearInterval(timer) : null;
				cb && cb();
			}
			function check() {
				if (inc.readyState && (inc.readyState == "loaded" || inc.readyState == "complete" || inc.readyState == 4))
					inc.onload();
			}
			timer = cb ? setInterval(check, 500) : undefined;
			inc.onreadystatechange = check;
			inc.type = "text/javascript";
			inc.src = src;
		}
		document.getElementsByTagName("head")[0].appendChild(inc);
	};

	// PARAMETERS

	var urlPrefix = findScriptHost(FILENAME) || "https://openwhyd.org",
		urlSuffix = "?" + (new Date()).getTime();

	// user interface

	function BkUi(){

		this.nbTracks = 0;

		var div = document.getElementById("whydBookmarklet");
		if (!div) {
			document.body.appendChild(document.createElement('div')).id = "whydBookmarklet";
			div = document.getElementById("whydBookmarklet");
		}

		div.innerHTML = [
			'
',
				'',
				'

',
			'
',
			'
',
				'
',
					'
Extracting tracks,
',
					'
please wait...
',
					'',
				'
',
			'
'
		].join('\n');

		function showForm(thumb) {
			var text = getSelText();
			var href = urlPrefix + '/post?embed=' + encodeURIComponent(thumb.url)
				+ (thumb.title ? '&title=' + encodeURIComponent(thumb.title) : '')
				+ '&refUrl=' + encodeURIComponent(window.location.href)
				+ '&refTtl=' + encodeURIComponent(document.title)
				+ (text ? '&text=' + encodeURIComponent(text) : '');
			var whydPop = window.open(href, "whydPop", "height=330,width=510,location=no,menubar=no,resizable=no,scrollbars=no,toolbar=no");
		}

		function renderThumb(thumb) {
			var divThumb = document.createElement("div");
			divThumb.setAttribute("id", thumb.id);
			divThumb.setAttribute("class", "whydThumb");
			divThumb.setAttribute("title", thumb.title);
			var divCont = document.createElement("div");
			divCont.setAttribute("class", "whydCont");
			divCont.appendChild(thumb.element);
			var textNode = document.createTextNode(thumb.title);
			var title = document.createElement("p");
			title.appendChild(textNode);
			divThumb.appendChild(divCont);
			divThumb.appendChild(title);
			var btnShareIt = document.createElement("img");
			btnShareIt.setAttribute("src", urlPrefix + "/images/btn-shareit.png");
			divThumb.appendChild(btnShareIt);
			return divThumb;
		}

		var contentDiv = document.getElementById("whydContent");

		this.addThumb = function(thumb) {
			thumb.id = 'whydThumb' + (this.nbTracks++);
			thumb.element = document.createElement("img");
			thumb.element.src = thumb.img;
			var divThumb = renderThumb(thumb);
			divThumb.onclick = function() {
				showForm(thumb);
			};
			contentDiv.appendChild(divThumb);
		}

		this.addSearchThumb = function(track) {
			var img = document.createElement("img");
			img.src = urlPrefix + "/images/cover-track.png";
			var divThumb = renderThumb({
				id: 'whydThumb' + (this.nbTracks++),
				title: track.name || track.title || "Search Whyd",
				element: img,
			}), href = "http://openwhyd.org/search?q=" + encodeURIComponent(track.name);
			divThumb.onclick = function() {
				var whydPop = window.open(href, "whydSearch");
			};
			contentDiv.appendChild(divThumb);
		}

		this.finish = function(html) {
			document.getElementById("whydLoading").innerHTML = this.nbTracks ? ""
				: "No tracks were detected on this page, sorry..." + (html || "");
		}

		return this;
	}

	// Track detectors

	function makeFileDetector(eidSet){
		var eidSet = {}; // to prevent duplicates
		return function detectMusicFiles(url, cb, e) {
			var title = decodeURIComponent((url.match(/([^\/]+)\.(?:mp3|ogg)$/) || []).pop() || ""),
				alt = [e.title, e.innerText, e.textContent];
			if (eidSet[url] || !title)
				return cb();
			for (var i = 0; i < alt.length; ++i) {
				var trimmed = e.title.replace(/^\s+|\s+$/g, '');
				if (trimmed) {
					title = trimmed;
					break;
				}
			}
			eidSet[url] = true;
			cb({
				id: url,
				title: title,
				img: urlPrefix + '/images/cover-audiofile.png',
			});
		};
	}

	function makePlayemStreamDetector(eidSet){
		window.SOUNDCLOUD_CLIENT_ID = "eb257e698774349c22b0b727df0238ad";
		window.DEEZER_APP_ID = 190482;
		window.DEEZER_CHANNEL_URL = urlPrefix + "/html/deezer.channel.html";
		window.JAMENDO_CLIENT_ID = "c9cb2a0a";
		var players = { // playem-all.js must be loaded at that point
				yt: new YoutubePlayer({}, {playerContainer: document.getElementById("videocontainer")}),
				sc: new SoundCloudPlayer({}),
				vi: new VimeoPlayer({}),
				dm: new DailymotionPlayer({}),
				dz: new DeezerPlayer({}),
				bc: new BandcampPlayer({}),
				ja: new JamendoPlayer({}),
			}, eidSet = {}; // to prevent duplicates
		function getPlayerId(url){
			for (var i in players) {
				var player = players[i];
				var eId = player.getEid(url);
				if (eId)
					return i;
			}
		}
		function detect(url, cb){
			var playerId = getPlayerId(url);
			var player = playerId && players[playerId];
			cb(player && ("/" + playerId + "/" + player.getEid(url)), player);
		}
		return function detectPlayemStreams(url, cb){
			detect(url, function(eid, player){
				if (!eid || eidSet[eid])
					return cb();
				eidSet[eid] = true;
				if (!player || !player.fetchMetadata)
					return cb({eId: eId});
				else
					player.fetchMetadata(url, function(track){
						track = track || {};
						track.eId = eid;
						cb(track);
					});
			});
		};
	}

	// each page detector is called once, without parameters, and returns a list of fake element objects
	// (with fields {name:} or {src:}) to extract streams from.
	var PAGE_DETECTORS = [
		function detectPandoraTrack(){
			if (window.location.href.indexOf("pandora.com") == -1)
				return null;
			var artist = getNodeText(document.getElementsByClassName("playerBarArtist")[0] || {}),
				title = getNodeText(document.getElementsByClassName("playerBarSong")[0] || {});
			return artist && title ? [{ name: artist + " - " + title }] : [];
		},
		function detectDeezerTrack(){
			var dzTrackId = window.dzPlayer && window.dzPlayer.getSongId();
			return dzTrackId ? [{ src: "https://www.deezer.com/track/" + dzTrackId }] : [];
		},
		function detectTrackFromTitle() {
			var title = document.title.replace(/[▶\<\>\"\']+/g, " ").replace(/[ ]+/g, " ");
			var titleParts = [" - Spotify", " | www.deezer.com", " - Xbox Music", " - Royalty Free Music - Jamendo"];
			for(var i=0; i<titleParts.length; ++i)
				if (title.indexOf(titleParts[i]) > -1)
					return [{name: title.replace(titleParts[i], "")}];
		},
	];

	// each track detector is called once, without parameters, and returns a list of fake element objects
	// (with fields {href:} or {src:}) to extract streams from.
	var TRACK_DETECTORS = [
		function extractBandcampTracks(){
			var toDetect = [];
			// list Bandcamp track URLs
			var bandcampPageUrl = document.querySelector && document.querySelector('meta[property="og:url"]');
			if (!bandcampPageUrl)
				return [];
			bandcampPageUrl = bandcampPageUrl.getAttribute("content");
			if (bandcampPageUrl.indexOf("bandcamp.com/track/") != -1)
				toDetect.push({src: bandcampPageUrl});
			else {
				var pathPos = bandcampPageUrl.indexOf("/", 10);
				if (pathPos != -1)
					bandcampPageUrl = bandcampPageUrl.substr(0, pathPos); // remove path
				var elts = document.querySelectorAll('a[href^="/track/"]');
				for (var j=0; j<elts.length; ++j)
					toDetect.push({href: bandcampPageUrl + elts[j].getAttribute("href")});
			}
			return toDetect;
			// TODO: document.querySelectorAll('script[title*="bandcamp.com/download/track"]') // only works on track and album pages
		},
	];

	function detectTracks(ui, URL_DETECTORS) {

		var elementNames = ["iframe", "object", "embed", "a", "audio", "source"];

		// an url-based detector must callback with a track Object (with fields: {id, eId, title, img}) as parameter, if detected
		var URL_DETECTORS = [
			makeFileDetector(),
			makePlayemStreamDetector(),
		];

		function detectTrack(url, cb, element) {
			//console.info("testing URL", url, "...");
			var urlDetectors = URL_DETECTORS.slice();
			(function processNext() {
				if (!urlDetectors.length)
					cb();
				else
					urlDetectors.shift()(url, function(track){
						//console.info("=>", track);
						if (track && track.id)
							cb(track);
						else
							processNext();
					}, element);
			})()
		}

		function detectEmbed(e, cb){
			var url = unwrapFacebookLink(e.href || e.src || e.data || "");
			if (!url)
				return cb && cb();
			detectTrack(url, function(track){
				if (track){
					console.info("=> detected", track);
					track = track || {};
					track.url = url;
					track.title = track.title || e.textNode || e.title || e.alt || track.eId || url; // || p.label;
					ui.addThumb(track);
				}
				cb();
			}, e);
		}

		function whenDone(){
			console.info("finished detecting tracks!");
			if (!ui.nbTracks)
				ui.addSearchThumb({name: document.title});
			ui.finish();
		}

		var toDetect = new (function ElementStack(){
			// this class holds a collections of elements that potentially reference streamable tracks
			var set = {};
			this.push = function(elt){
				var url = unwrapFacebookLink(elt.href || elt.src || elt.data || "").split("#")[0];
				if (!elt || !url || url.indexOf("javascript:") == 0 || url.indexOf("#") == 0)
					return;
				set[url] = elt;
			};
			this.pushAll = function(elts){
				for (var j=0; j<elts.length; ++j)
					this.push(elts[j]);
			};
			this.shift = function(){
				var keys = Object.keys(set), val;
				if (keys.length){
					val = set[keys[0]];
					delete set[keys[0]];
				}
				return val;
			};
		})();

		console.info("detecting tracks from page...");
		toDetect.push({ src: window.location.href });

		console.info("1/4 parse page metadata...");
		PAGE_DETECTORS.map(function(detect){
			var res = detect();
			if (!res)
				return;
			res.map(function(track){
				if (track && track.name)
					ui.addSearchThumb(track);
				else if (track && track.src)
					toDetect.push(track);
			});
		});

		console.info("2/4 parse elements...");
		elementNames.map(function(elName){
			toDetect.pushAll(document.getElementsByTagName(elName));
		});

		console.info("3/4 parse other elements...");
		TRACK_DETECTORS.map(function(detect){
			var tracks = detect();
			//if (tracks && tracks.length)
				toDetect.pushAll(tracks);
		});

		console.info("4/4 detecting streamable tracks...");
		(function processNext() {
			var elt = toDetect.shift();
			if (!elt)
				whenDone();
			else
				detectEmbed(elt, processNext);
		})();
	}

	console.info("initWhydBookmarklet...");
	include(urlPrefix + "/css/bookmarklet.css" + urlSuffix);
	var ui = new BkUi();
	console.info("loading PlayemJS...");
	include(urlPrefix + "/js/playem-min.js" + urlSuffix, function(){
		detectTracks(ui);
	});
})();


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Monogr. Discom. Bohem. (Prague) 120 (1934)

#### Original name
Mollisia chenopodii Velen.

### Remarks
null


text:
layout: post
title: The great answer on stackoverflow
---

I recently found out that I got an "Great Answer" badge on [stackoverflow](http://stackoverflow.com). This means that I answered a question that has received a hundered upvotes - meaning that I helped many people with my answer.

[The question](http://stackoverflow.com/questions/1785744/) was about someone creating an instance of `Random` in a loop, then generating a random number with it but then he got every time the same result(in the loop). He wondered why, and how he could fix this. The question has now been viewed 63187 times.

[Then I posted](http://stackoverflow.com/a/18267477/2622807) somewhat irrelevantely this:
{% highlight csharp %}
Random rand = new Random(Guid.NewGuid().GetHashCode());
{% endhighlight %}

And now it has 101 upvotes, and 2 downvotes.

Now, you may wonder, how did I come up with this?  Finding a solution to seeding a random generator that's not time-based and is still random and thus the result unique? This might be a little hacky, but this helped a lot of people for a lot of scenarios(like when two programs launch at roughly exact the same time).

I don't know. I was 14 back then and relatively new to programming - [my first code](http://web.archive.org/web/20151110205042/http://mcdzienny.cba.pl/viewtopic.php?f=19&t=1565) was almost  one year ago at that time(technically not my first, but that was the first time I _knew_ I was coding). My grammar was bad nor did I understand stackoverflow(not that I do now). This is magic to me.

This answer _does_ solve OPs problem, but not in a good way and without an explanation. I don't even know why I posted this and how I got there. The question already was roughly 4 years old already at that time.

All my other answers and questions arround that time weren't very high quality either.

I feel a little odd about the two downvotes: They took place the day before yesterday, which is pretty weird if you consider the timespan of this question.

I don't know. I do stuff on the internet, seemingly without any quality control, and sometimes something good happens with it.

Which brings me to the question: Why exactly do I have no quality control and should I do something about it?

Heh. I'm getting some more tea.


text:
#ifndef SELECTION_H
#define SELECTION_H

#include "common.h"
#include "ShaderProgram.h"
#include "Texture.h"
#include "PointSprite.h"

/** Selection class.
 * This class is responsible for determining which particle is located at a given screen position.
 */
class Selection
{
public:
	/** Constructor.
	 */
	Selection (void);
	/** Destruction.
	 */
	~Selection (void);

	/** Get particle from screen position.
	 * Determines the particle at the given screen coordinates, if any.
	 * \param positionbuffer buffer object storing the particle positions
	 * \param numparticles number of particles in the buffer
	 * \param x x coordinate
	 * \param y y coordinate
	 * \returns the particle id or -1 if there is no particle at the given position
	 */
	GLint GetParticle (GLuint positionbuffer, GLuint numparticles, float x, float y);
private:
    /** Selection shader program.
     * Shader program for selecting particles.
     */
    ShaderProgram selectionprogram;

    /** Depth texture.
     * Texture for the depth buffer of the selection framebuffer.
     */
    Texture depthtexture;

    /** Selection texture.
     * Texture for the selection framebuffer.
     */
    Texture selectiontexture;

    union {
    	struct {
    		/** Selection framebuffer.
    		 * Framebuffer object used to determine which object resides at a specific screen
    		 * space position.
    		 */
    		GLuint selectionfb;
    	};
    	/** Framebuffer objects.
    	 * The framebuffer objects are stored in a union, so that it is possible
    	 * to create/delete all texture objects with a single OpenGL call.
    	 */
    	GLuint framebuffers[1];
    };

    /** Point sprite object.
     * This is used to render point sprites for the particles.
     */
    PointSprite pointsprite;
};

#endif /* SELECTION_H */


text:
package com.intellij.util.lang;

import org.jetbrains.annotations.NotNull;

import java.io.InputStream;
import java.nio.ByteBuffer;

final class DirectByteBufferBackedInputStream extends InputStream {
  private ByteBuffer buffer;
  private final boolean isPooled;

  DirectByteBufferBackedInputStream(ByteBuffer buffer, boolean isPooled) {
    this.buffer = buffer;
    this.isPooled = isPooled;
  }

  @Override
  public int read() {
    return buffer.hasRemaining() ? buffer.get() & 0xff : -1;
  }

  @Override
  public int read(byte[] bytes, int offset, int length) {
    if (!buffer.hasRemaining()) {
      return -1;
    }

    int actualLength = Math.min(length, buffer.remaining());
    buffer.get(bytes, offset, actualLength);
    return actualLength;
  }

  @Override
  public byte[] readNBytes(int length) {
    byte[] result = new byte[Math.min(length, buffer.remaining())];
    buffer.get(result);
    return result;
  }

  @Override
  public int readNBytes(byte[] bytes, int offset, int length) {
    int actualLength = Math.min(length, buffer.remaining());
    buffer.get(bytes, offset, actualLength);
    return actualLength;
  }

  @Override
  public int available() {
    return buffer.remaining();
  }

  @Override
  public byte @NotNull [] readAllBytes() {
    byte[] result = new byte[buffer.remaining()];
    buffer.get(result);
    return result;
  }

  @Override
  public long skip(long length) {
    int actualLength = Math.min((int)length, buffer.remaining());
    buffer.position(buffer.position() + actualLength);
    return actualLength;
  }

  @Override
  public void close() {
    ByteBuffer buffer = this.buffer;
    if (buffer == null) {
      // already closed
      return;
    }

    this.buffer = null;
    if (isPooled) {
      DirectByteBufferPool.DEFAULT_POOL.release(buffer);
    }
  }
}


text:
package org.gradle.testkit.runner;

import org.gradle.api.Incubating;
import org.gradle.api.internal.GradleDistributionLocator;
import org.gradle.api.internal.classpath.DefaultGradleDistributionLocator;
import org.gradle.internal.classloader.ClasspathUtil;
import org.gradle.testkit.runner.internal.DefaultGradleRunner;

import java.io.File;
import java.util.List;

/**
 * Executes a Gradle build, allowing inspection of the outcome.
 *

 * A Gradle runner can be used to functionally test build logic, by executing a contrived build.
 * Assertions can then be made on the outcome of the build, such as the state of files created by the build,
 * or what tasks were actually executed during the build.
 *

 * A runner can be created via the {@link #create()} method.
 *

 * Typically, the test code using the runner will programmatically create a build (e.g. by writing Gradle build files to a temporary space) to execute.
 * The build to execute is effectively specified by the {@link #withProjectDir(File)}} method.
 * It is a requirement that a project directory be set.
 *

 * The {@link #withArguments(String...)} method allows the build arguments to be specified,
 * just as they would be on the command line.
 *

 * The {@link #build()} method can be used to invoke the build when it is expected to succeed,
 * while the {@link #buildAndFail()} method can be used when the build is expected to fail.
 *

 * GradleRunner instances are not thread safe and cannot be used concurrently.
 * However, multiple instances are able to be used concurrently.
 *

 * Please see the Gradle TestKit User Guide chapter for more information.
 *
 * @since 2.6
 */
@Incubating
public abstract class GradleRunner {

    /**
     * Creates a new Gradle runner.
     *

     * The runner requires a Gradle distribution (and therefore a specific version of Gradle) in order to execute builds.
     * This method will find a Gradle distribution, based on the filesystem location of this class.
     * That is, it is expected that this class is loaded from a Gradle distribution.
     *

     * When using the runner as part of tests being executed by Gradle (i.e. a build using the {@code gradleTestKit()} dependency),
     * this means that the same distribution of Gradle that is executing the tests will be used by runner returned by this method.
     *

     * When using the runner as part of tests being executed by an IDE,
     * this means that the same distribution of Gradle that was used when importing the project will be used.
     *
     * @return a new Gradle runner
     */
    public static GradleRunner create() {
        GradleDistributionLocator gradleDistributionLocator = new DefaultGradleDistributionLocator(GradleRunner.class);
        final File gradleHome = gradleDistributionLocator.getGradleHome();
        if (gradleHome == null) {
            try {
                File classpathForClass = ClasspathUtil.getClasspathForClass(GradleRunner.class);
                throw new IllegalStateException("Could not create a GradleRunner, as the GradleRunner class was loaded from " + classpathForClass + " which is not a Gradle distribution");
            } catch (Exception e) {
                throw new IllegalStateException("Could not create a GradleRunner, as the GradleRunner class was not loaded from a Gradle distribution");
            }
        }
        return new DefaultGradleRunner(gradleHome);
    }

    /**
     * Sets the directory to use for Test Kit's working storage needs.
     *

     * This directory is used internally to store various files required by the runner.
     * If no explicit Gradle user home is specified via the build arguments (i.e. the {@code -g «dir»} option}),
     * this directory will also be used for the Gradle user home for the test build.
     *

     * If no value has been specified when the build is initiated, a directory unique to the current operating system
     * user will be created and used within the JVM's temporary directory as advertised by the {@code java.io.tmpdir} system property.
     * This directory is not deleted by the runner after the test build.
     *

     * You may wish to specify a location that is within your project and regularly cleaned, such as the project's build directory.
     *

     * The actual contents of this directory are an internal implementation detail and may change at any time.
     *
     * @param testKitDir the test kit directory
     * @return {@code this}
     * @since 2.7
     */
    public abstract GradleRunner withTestKitDir(File testKitDir);

    /**
     * The directory that the build will be executed in.
     *

     * This is analogous to the current directory when executing Gradle from the command line.
     *
     * @return the directory to execute the build in
     */
    public abstract File getProjectDir();

    /**
     * Sets the directory that the Gradle will be executed in.
     *

     * This is typically set to the root project of the build under test.
     *

     * A project directory must be set.
     * This method must be called before {@link #build()} or {@link #buildAndFail()}.
     *

     * All builds executed with the runner effectively implicitly add the {@code --no-search-upwards} argument.
     * This suppresses Gradle's default behaviour of searching upwards through the file system in order to find the root of the current project tree.
     * This default behaviour is often utilised when focusing on a particular build within a multi-project build.
     * This behaviour is suppressed due to test builds being executed potentially being created within a "real build"
     * (e.g. under the {@code /build} directory of the plugin's project directory).
     *
     * @param projectDir the project directory
     * @return {@code this}
     * @see #getProjectDir()
     */
    public abstract GradleRunner withProjectDir(File projectDir);

    /**
     * The build arguments.
     *

     * Effectively, the command line arguments to Gradle.
     * This includes all tasks, flags, properties etc.
     *

     * The returned list is immutable.
     *
     * @return the build arguments
     */
    public abstract List<String> getArguments();

    /**
     * Sets the build arguments.
     *
     * @param arguments the build arguments
     * @return this
     * @see #getArguments()
     */
    public abstract GradleRunner withArguments(List<String> arguments);

    /**
     * Sets the build arguments.
     *
     * @param arguments the build arguments
     * @return this
     * @see #getArguments()
     */
    public abstract GradleRunner withArguments(String... arguments);

    /**
     * The injected plugin classpath for the build.
     *

     * The returned list is immutable.
     * Returns an empty list if no classpath was provided with {@link #withPluginClasspath(Iterable)}.
     *
     * @return the classpath of plugins to make available to the build under test
     * @since 2.8
     */
    public abstract List<? extends File> getPluginClasspath();

    /**
     * Sets the injected plugin classpath for the build.
     *

     * Plugins from the given classpath are able to be resolved using the plugins { } syntax in the build under test.
     * Please consult the "Test Kit" Gradle User Guide chapter for more information and usage examples.
     *
     * @param classpath the classpath of plugins to make available to the build under test
     * @return this
     * @see #getPluginClasspath()
     * @since 2.8
     */
    public abstract GradleRunner withPluginClasspath(Iterable<? extends File> classpath);

    /**
     * Executes a build, expecting it to complete without failure.
     *
     * @throws InvalidRunnerConfigurationException if the configuration of this runner is invalid (e.g. project directory not set)
     * @throws UnexpectedBuildFailure if the build does not succeed
     * @return the build result
     */
    public abstract BuildResult build() throws InvalidRunnerConfigurationException, UnexpectedBuildFailure;

    /**
     * Executes a build, expecting it to complete with failure.
     *
     * @throws InvalidRunnerConfigurationException if the configuration of this runner is invalid (e.g. project directory not set)
     * @throws UnexpectedBuildSuccess if the build succeeds
     * @return the build result
     */
    public abstract BuildResult buildAndFail() throws InvalidRunnerConfigurationException, UnexpectedBuildSuccess;

}


text:
<?xml version="1.0" encoding="us-ascii"?>
<AssetDeclaration xmlns="uri:ea.com:eala:asset" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<Tags></Tags>
	<Includes></Includes>
	<GameObject
		id="GDIAPCShockwaveCannonProjectile"
		Side="GDI"
		EditorSorting="SYSTEM"
		KindOf="PROJECTILE INERT DEFLECT_BY_SPECIAL_POWER NO_COLLIDE HIDE_IF_FOGGED"
		EditorName="GDIAPCShockwaveCannonProjectile">
		<ArmorSet
			Armor="NoArmor" />
		<Draws>
			<ScriptedModelDraw
				id="ModuleTag_Draw">
				<ModelConditionState
					ParseCondStateType="PARSE_DEFAULT">
					<Model
						Name="" />
					<ParticleSysBone
						BoneName="NONE"
						FXParticleSystemTemplate="orcamissiletrail"
						FollowBone="true" />
				</ModelConditionState>
			</ScriptedModelDraw>
			<StreakDraw
				id="ModuleTag_W3DStreakDraw"
				Length="8"
				Width="4"
				NumSegments="3"
				Texture="EXFireScroll3">
				<Color
					r="1"
					g="1"
					b="1" />
			</StreakDraw>
		</Draws>
		<Behaviors>
			<DestroyDie
				id="ModuleTag_Die">
				<DieMuxData
					DeathTypes="ALL" />
			</DestroyDie>
			<BezierProjectile
				id="ModuleTag_BezierProjectile"
				FirstHeightMin="0"
				FirstHeightMax="0"
				SecondHeightMin="0"
				SecondHeightMax="0"
				FirstPercentIndent="33"
				SecondPercentIndent="66"
				GroundHitFX="FX_RocketImpact"
				OrientToFlightPath="true"></BezierProjectile>
			<LifetimeUpdate
				id="ModuleTag_LifetimeUpdate"
				MinLifetime="4.0s"
				MaxLifetime="4.0s"
				IgnoreProjectileState="true" />
			<FireWeaponUpdate
				id="ModuleTag_FireWeaponUpdate">
				<FireWeaponNugget
					WeaponName="GDIAPCShockwaveCannonWeapon"
					FireDelay="2s"
					OneShot="false" />
			</FireWeaponUpdate>
		</Behaviors>
		<Body>
			<ActiveBody
				id="ModuleTag_ActiveBody"
				MaxHealth="100.0" />
		</Body>
		<Geometry
			IsSmall="true">
			<Shape
				Type="SPHERE"
				MajorRadius="0.8"></Shape>
		</Geometry>
		<VisionInfo
			VisionRange="0" />
	</GameObject>
</AssetDeclaration>


text:
/*	$NetBSD: aout_machdep.h,v 1.2 1997/04/09 23:34:29 thorpej Exp $	*/

/*
 * Copyright (c) 1993 Christopher G. Demetriou
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef _M68K_EXEC_H_
#define _M68K_EXEC_H_

#define __LDPGSZ	8192

/*
 * Override the N_PAGSIZ() macro.
 * XXX Nicer way to do this?
 */
#undef N_PAGSIZ
#define	N_PAGSIZ(ex)	(N_GETMID((ex)) == MID_M68K4K ? 4096 : __LDPGSZ)

/* Relocation format. */
struct relocation_info_m68k {
	int r_address;			/* offset in text or data segment */
	unsigned int r_symbolnum : 24,	/* ordinal number of add symbol */
			 r_pcrel :  1,	/* 1 if value should be pc-relative */
			r_length :  2,	/* log base 2 of value's width */
			r_extern :  1,	/* 1 if need to add symbol to value */
		       r_baserel :  1,	/* linkage table relative */
		      r_jmptable :  1,	/* relocate to jump table */
		      r_relative :  1,	/* load address relative */
			  r_copy :  1;	/* run time copy */
};
#define relocation_info	relocation_info_m68k

#endif  /* _M68K_EXEC_H_ */


text:
typedef NS_ENUM(NSInteger, YiSlideDirection) {
    YiLeftDirection,
    YiRightDirection,
};

@protocol YiSlideMenuDelegate;

@interface YiSlideMenu : UIScrollView{
    id<YiSlideMenuDelegate> slideMenuDelegate;
}
@property id<YiSlideMenuDelegate> slideMenuDelegate;
@property UIView *centerView;
@property UIButton *navLeftBt;
@property UIButton *navRightBt;
@property UILabel *navTitleLabel;
-(void)navLeftBtAction;
-(void)navRightBtAction;
@end

@protocol YiSlideMenuDelegate<NSObject>
- (void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath slide:(YiSlideDirection)slideDirection;
@end


text:
require 'spec_helper'
require 'yaml'

{ :product_pages      => LCBO::ProductPage,
  :store_pages        => LCBO::StorePage,
  :inventory_pages    => LCBO::InventoryPage,
  :product_list_pages => LCBO::ProductListPage,
  :store_list_pages   => LCBO::StoreListPage
}.each_pair do |type, page|

  describe(page) do
    requests = YAML.load_file("spec/pages/#{type}.yml")

    requests.each do |req|
      body = File.read("spec/pages/#{type}/#{req[:file]}")
      req[:body] = body
      SpecHelper.hydrastub(req[:method], req[:uri], :body => req[:body])
    end

    requests.each do |req|
      describe "given a #{req[:desc]}" do
        before do
          @page = page.process(req[:query_params], req[:body_params])
        end

        req[:expectation].each_pair do |key, value|
          it "should have the expected value for :#{key}" do
            @page[key].must_equal value
          end
        end
      end
    end
  end

end


text:
package core

import (
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common"
)

// ClusterNetwork A cluster network is a group of high performance computing (HPC) bare metal instances that are connected
// with an ultra low latency network. For more information about cluster networks, see
// Managing Cluster Networks (https://docs.cloud.oracle.com/iaas/Content/Compute/Tasks/managingclusternetworks.htm).
type ClusterNetwork struct {

	// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the cluster network.
	Id *string `mandatory:"true" json:"id"`

	// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the compartment containing the cluster netowrk.
	CompartmentId *string `mandatory:"true" json:"compartmentId"`

	// The current state of the cluster network.
	LifecycleState ClusterNetworkLifecycleStateEnum `mandatory:"true" json:"lifecycleState"`

	// The date and time the resource was created, in the format defined by RFC3339 (https://tools.ietf.org/html/rfc3339).
	// Example: `2016-08-25T21:10:29.600Z`
	TimeCreated *common.SDKTime `mandatory:"true" json:"timeCreated"`

	// The date and time the resource was updated, in the format defined by RFC3339 (https://tools.ietf.org/html/rfc3339).
	// Example: `2016-08-25T21:10:29.600Z`
	TimeUpdated *common.SDKTime `mandatory:"true" json:"timeUpdated"`

	// Defined tags for this resource. Each key is predefined and scoped to a
	// namespace. For more information, see Resource Tags (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
	// Example: `{"Operations": {"CostCenter": "42"}}`
	DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`

	// A user-friendly name. Does not have to be unique, and it's changeable.
	DisplayName *string `mandatory:"false" json:"displayName"`

	// Free-form tags for this resource. Each tag is a simple key-value pair with no
	// predefined name, type, or namespace. For more information, see Resource Tags (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
	// Example: `{"Department": "Finance"}`
	FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`

	// The instance pools in the cluster network.
	// Each cluster network can have one instance pool.
	InstancePools []InstancePool `mandatory:"false" json:"instancePools"`

	PlacementConfiguration *ClusterNetworkPlacementConfigurationDetails `mandatory:"false" json:"placementConfiguration"`
}

func (m ClusterNetwork) String() string {
	return common.PointerString(m)
}

// ClusterNetworkLifecycleStateEnum Enum with underlying type: string
type ClusterNetworkLifecycleStateEnum string

// Set of constants representing the allowable values for ClusterNetworkLifecycleStateEnum
const (
	ClusterNetworkLifecycleStateProvisioning ClusterNetworkLifecycleStateEnum = "PROVISIONING"
	ClusterNetworkLifecycleStateScaling      ClusterNetworkLifecycleStateEnum = "SCALING"
	ClusterNetworkLifecycleStateStarting     ClusterNetworkLifecycleStateEnum = "STARTING"
	ClusterNetworkLifecycleStateStopping     ClusterNetworkLifecycleStateEnum = "STOPPING"
	ClusterNetworkLifecycleStateTerminating  ClusterNetworkLifecycleStateEnum = "TERMINATING"
	ClusterNetworkLifecycleStateStopped      ClusterNetworkLifecycleStateEnum = "STOPPED"
	ClusterNetworkLifecycleStateTerminated   ClusterNetworkLifecycleStateEnum = "TERMINATED"
	ClusterNetworkLifecycleStateRunning      ClusterNetworkLifecycleStateEnum = "RUNNING"
)

var mappingClusterNetworkLifecycleState = map[string]ClusterNetworkLifecycleStateEnum{
	"PROVISIONING": ClusterNetworkLifecycleStateProvisioning,
	"SCALING":      ClusterNetworkLifecycleStateScaling,
	"STARTING":     ClusterNetworkLifecycleStateStarting,
	"STOPPING":     ClusterNetworkLifecycleStateStopping,
	"TERMINATING":  ClusterNetworkLifecycleStateTerminating,
	"STOPPED":      ClusterNetworkLifecycleStateStopped,
	"TERMINATED":   ClusterNetworkLifecycleStateTerminated,
	"RUNNING":      ClusterNetworkLifecycleStateRunning,
}

// GetClusterNetworkLifecycleStateEnumValues Enumerates the set of values for ClusterNetworkLifecycleStateEnum
func GetClusterNetworkLifecycleStateEnumValues() []ClusterNetworkLifecycleStateEnum {
	values := make([]ClusterNetworkLifecycleStateEnum, 0)
	for _, v := range mappingClusterNetworkLifecycleState {
		values = append(values, v)
	}
	return values
}