text:
//======= Copyright (c) Valve Corporation, All rights reserved. ===============
//
// Purpose: handles the physics of hands colliding with the world
//
//=============================================================================

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Valve.VR.InteractionSystem
{
    public class HandPhysics : MonoBehaviour
    {
        [Tooltip("Hand collider prefab to instantiate")]
        public HandCollider handColliderPrefab;
        [HideInInspector]
        public HandCollider handCollider;

        [Tooltip("Layers to consider when checking if an area is clear")]
        public LayerMask clearanceCheckMask;

        [HideInInspector]
        public Hand hand;

        // distance at which hand will teleport back to controller
        const float handResetDistance = 0.6f;

        const float collisionReenableClearanceRadius = 0.1f;

        private bool initialized = false;

        private bool collisionsEnabled = true;

        private void Start()
        {
            hand = GetComponent<Hand>();
            //spawn hand collider and link it to us

            handCollider = ((GameObject)Instantiate(handColliderPrefab.gameObject)).GetComponent<HandCollider>();
            Vector3 localPosition = handCollider.transform.localPosition;
            Quaternion localRotation = handCollider.transform.localRotation;

            handCollider.transform.parent = Player.instance.transform;
            handCollider.transform.localPosition = localPosition;
            handCollider.transform.localRotation = localRotation;
            handCollider.hand = this;

            GetComponent<SteamVR_Behaviour_Pose>().onTransformUpdated.AddListener(UpdateHand);
        }

        // cached transformations
        Matrix4x4 wristToRoot;
        Matrix4x4 rootToArmature;
        Matrix4x4 wristToArmature;

        Vector3 targetPosition = Vector3.zero;
        Quaternion targetRotation = Quaternion.identity;

        //bones
        const int wristBone = SteamVR_Skeleton_JointIndexes.wrist;
        const int rootBone = SteamVR_Skeleton_JointIndexes.root;

        private void FixedUpdate()
        {
            if (hand.skeleton == null) return;
            initialized = true;

            UpdateCenterPoint();

            handCollider.MoveTo(targetPosition, targetRotation);

            if ((handCollider.transform.position - targetPosition).sqrMagnitude > handResetDistance * handResetDistance)
                handCollider.TeleportTo(targetPosition, targetRotation);

            UpdateFingertips();
        }

        private void UpdateCenterPoint()
        {
            Vector3 offset = hand.skeleton.GetBonePosition(SteamVR_Skeleton_JointIndexes.middleProximal) - hand.skeleton.GetBonePosition(SteamVR_Skeleton_JointIndexes.root);
            if (hand.HasSkeleton())
            {
                handCollider.SetCenterPoint(hand.skeleton.transform.position + offset);
            }
        }

        Collider[] clearanceBuffer = new Collider[1];

        private void UpdatePositions()
        {
            // disable collisions when holding something
            if (hand.currentAttachedObject != null)
            {
                collisionsEnabled = false;
            }
            else
            {
                // wait for area to become clear before reenabling collisions
                if (!collisionsEnabled)
                {
                    clearanceBuffer[0] = null;
                    Physics.OverlapSphereNonAlloc(hand.objectAttachmentPoint.position, collisionReenableClearanceRadius, clearanceBuffer);
                    // if we don't find anything in the vicinity, reenable collisions!
                    if (clearanceBuffer[0] == null)
                    {
                        collisionsEnabled = true;
                    }
                }
            }

            handCollider.SetCollisionDetectionEnabled(collisionsEnabled);

            if (hand.skeleton == null) return;
            initialized = true;

            // get the desired pose of the wrist in world space. Can't get the wrist bone transform, as this is affected by the resulting physics.

            wristToRoot = Matrix4x4.TRS(ProcessPos(wristBone, hand.skeleton.GetBone(wristBone).localPosition),
                ProcessRot(wristBone, hand.skeleton.GetBone(wristBone).localRotation),
                Vector3.one).inverse;

            rootToArmature = Matrix4x4.TRS(ProcessPos(rootBone, hand.skeleton.GetBone(rootBone).localPosition),
                ProcessRot(rootBone, hand.skeleton.GetBone(rootBone).localRotation),
                Vector3.one).inverse;

            wristToArmature = (wristToRoot * rootToArmature).inverse;

            // step up through virtual transform hierarchy and into world space
            targetPosition = transform.TransformPoint(wristToArmature.MultiplyPoint3x4(Vector3.zero));

            targetRotation = transform.rotation * wristToArmature.GetRotation();

            //bypass physics when game paused
            if (Time.timeScale == 0)
            {
                handCollider.TeleportTo(targetPosition, targetRotation);
            }
        }

        Transform wrist;

        const int thumbBone = SteamVR_Skeleton_JointIndexes.thumbDistal;
        const int indexBone = SteamVR_Skeleton_JointIndexes.indexDistal;
        const int middleBone = SteamVR_Skeleton_JointIndexes.middleDistal;
        const int ringBone = SteamVR_Skeleton_JointIndexes.ringDistal;
        const int pinkyBone = SteamVR_Skeleton_JointIndexes.pinkyDistal;

        void UpdateFingertips()
        {
            wrist = hand.skeleton.GetBone(SteamVR_Skeleton_JointIndexes.wrist);

            // set finger tip positions in wrist space

            for(int finger = 0; finger < 5; finger++)
            {
                int tip = SteamVR_Skeleton_JointIndexes.GetBoneForFingerTip(finger);
                int bone = tip;
                for(int i = 0; i < handCollider.fingerColliders[finger].Length; i++)
                {
                    bone = tip - 1 - i; // start at distal and go down
                    if (handCollider.fingerColliders[finger][i] != null)
                        handCollider.fingerColliders[finger][i].localPosition = wrist.InverseTransformPoint(hand.skeleton.GetBone(bone).position);
                }
            }
            /*
            if(handCollider.tip_thumb != null)
                handCollider.tip_thumb.localPosition = wrist.InverseTransformPoint(hand.skeleton.GetBone(thumbBone).position);

            if(handCollider.tip_index != null)
            handCollider.tip_index.localPosition = wrist.InverseTransformPoint(hand.skeleton.GetBone(indexBone).position);

            if(handCollider.tip_middle != null)
            handCollider.tip_middle.localPosition = wrist.InverseTransformPoint(hand.skeleton.GetBone(middleBone).position);

            if(handCollider.tip_ring != null)
            handCollider.tip_ring.localPosition = wrist.InverseTransformPoint(hand.skeleton.GetBone(ringBone).position);

            if (handCollider.tip_pinky != null)
            handCollider.tip_pinky.localPosition = wrist.InverseTransformPoint(hand.skeleton.GetBone(pinkyBone).position);
            */
        }

        void UpdateHand(SteamVR_Behaviour_Pose pose, SteamVR_Input_Sources inputSource)
        {
            if (!initialized) return;

            UpdateCenterPoint();

            UpdatePositions();

            Quaternion offsetRotation = handCollider.transform.rotation * wristToArmature.inverse.GetRotation();

            hand.mainRenderModel.transform.rotation = offsetRotation;

            Vector3 offsetPosition = handCollider.transform.TransformPoint(wristToArmature.inverse.MultiplyPoint3x4(Vector3.zero));

            hand.mainRenderModel.transform.position = offsetPosition;

            /*
            Vector3 wristPointInArmatureSpace = transform.InverseTransformPoint(handCollider.transform.position);

            Vector3 handTargetPosition =

            hand.mainRenderModel.transform.position = handTargetPosition;

            //Quaternion handTargetRotation = transform.rotation * (wristToArmature.inverse.rotation * (Quaternion.Inverse(transform.rotation) * handCollider.transform.rotation));

            //hand.mainRenderModel.transform.rotation = handTargetRotation;
            */
        }

        Vector3 ProcessPos(int boneIndex, Vector3 pos)
        {
            if(hand.skeleton.mirroring != SteamVR_Behaviour_Skeleton.MirrorType.None)
            {
                return SteamVR_Behaviour_Skeleton.MirrorPosition(boneIndex, pos);
            }

            return pos;
        }

        Quaternion ProcessRot(int boneIndex, Quaternion rot)
        {
            if (hand.skeleton.mirroring != SteamVR_Behaviour_Skeleton.MirrorType.None)
            {
                return SteamVR_Behaviour_Skeleton.MirrorRotation(boneIndex, rot);
            }

            return rot;
        }

    }
}


text:
package com.longluo.demo.contact;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.longluo.demo.R;

public class ContactDetailActivity extends Activity {
    private Button mBtnOpenContactDetail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_detail_demo);

        initViews();
    }

    private void initViews() {
        mBtnOpenContactDetail = (Button) findViewById(R.id.btn_open_contact_detail);
        mBtnOpenContactDetail.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

            }
        });
    }

    private void start() {
        Cursor cursor = getContentResolver().query(
                ContactsContract.Contacts.CONTENT_URI, null,
                ContactsContract.Contacts.STARRED + " = 1 ", null, null);

        if (cursor == null) {
            return;
        }

        int count = 0;

        try {
            if (cursor.moveToFirst()) {
                do {
                    count++;

                    long id = cursor.getLong(cursor.getColumnIndex("_id"));

                    Cursor pCur = getContentResolver().query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                    + "=" + Long.toString(id), null, null);

                    pCur.moveToFirst();

                    String phoneNumber = pCur
                            .getString(pCur
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    pCur.close();

                    String name = cursor.getString(cursor
                            .getColumnIndex("display_name"));

                    Log.d("test00", "getFavoriteContacts, name=" + name
                            + ",phoneNumbers=" + phoneNumber);

                    if (count >= 3) {
                        break;
                    }
                } while (cursor.moveToNext());
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
package javazoo.forum.entity;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "categories")
public class Category {
    private Integer id;
    private String name;
    private Integer orderNo;
    private Set<Subcategory> subcategories;
    private Set<Question> questions;

    public Category(){
        this.subcategories = new HashSet<>();
        this.questions = new HashSet<>();
    }

    public Category(String name, Integer orderNo){
        this.name = name;
        this.orderNo = orderNo;

        this.subcategories = new HashSet<>();
        this.questions= new HashSet<>();
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer getId() {
        return id;
    }

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

    @Column(nullable = false, unique = true)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(nullable = false)
    public Integer getOrderNo() {
        return orderNo;
    }

    public void setOrderNo(Integer orderNo) {
        this.orderNo = orderNo;
    }

    @OneToMany(mappedBy = "category")
    public Set<Subcategory> getSubcategories() {
        return subcategories;
    }

    public void setSubcategories(Set<Subcategory> subcategories) {
        this.subcategories = subcategories;
    }

    @OneToMany(mappedBy = "category")
    public Set<Question> getQuestions() {
        return questions;
    }

    public void setQuestions(Set<Question> questions) {
        this.questions = questions;
    }
}


text:
include("Stubs.jl")

using DandelionWebSockets
using DandelionWebSockets: HTTPHandshake
using .Stubs
using .Stubs: write, read, InProcessIO
using Test
using Random

# These are the actions that the server will take.
serverscript = [
    WaitForOpen(),
    SendTextFrame("1234"),
    ShortWait(),
    SendTextFrame("2345"),
    ShortWait(),
    SendTextFrame("5678"),
]

clientscript = [
    WaitForOpen(),
    SendTextFrame("abcd"),
    ShortWait(),
    SendTextFrame("bcde"),
    ShortWait(),
    SendTextFrame("cdef"),
    ShortWait(),
    SendTextFrame("defg"),
    ShortWait(),
    SendTextFrame("efgh"),
    ShortWait(),
    CloseConnection()
]

# Create server, and the handshake adapter that creates the connection when the client requests a
# handshake.
server = ScriptedServer(serverscript)
handshakeadapter = InProcessHandshakeAdapter(server)

# Create the WebSocket client, with a custom handshake adapter.
# Instead of making an actual HTTP request, the custom handshake adapter creates an in-process
# `IO` that is used in place of an actual network socket.
# Note that the HTTP handshake logic is still the same, it's only the actual transport method that
# is different.
client = WSClient(; handshake=HTTPHandshake(RandomDevice(), handshakeadapter))

# Create a client that runs the script above.
clienthandler = ScriptedClientHandler(clientscript)

# Request that the connection be opened, which starts the scripts for both server and client.
wsconnect(client, "ws://the/uri/does/not/matter/here", clienthandler)

# Wait for both client and server to close.
waitforscriptdone(server, clienthandler)

@testset "Sent messages    " begin
    @test server.statistics.texts_received == 5
end

@testset "Received messages" begin
    @test clienthandler.statistics.texts_received == 3
end


text:
object ForceScalaDoc {
  // The entire purpose of this code is to for sbt to run scaladoc instead of javadoc, because
  // there are lots of javadoc errors that I don't want to fix.
}


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

/**
 * GeoIp data file parsing test.
 */
class core_iplookup_geoip_testcase extends advanced_testcase {

    public function setUp() {
        global $CFG;
        require_once("$CFG->libdir/filelib.php");
        require_once("$CFG->dirroot/iplookup/lib.php");

        if (!PHPUNIT_LONGTEST) {
            // this may take a long time
            $this->markTestSkipped('PHPUNIT_LONGTEST is not defined');
        }

        $this->resetAfterTest();

        // let's store the file somewhere
        $gzfile = "$CFG->dataroot/phpunit/geoip/GeoLite2-City.mmdb.gz";
        check_dir_exists(dirname($gzfile));
        if (file_exists($gzfile) and (filemtime($gzfile) < time() - 60*60*24*30)) {
            // delete file if older than 1 month
            unlink($gzfile);
        }

        if (!file_exists($gzfile)) {
            download_file_content('http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz',
                null, null, false, 300, 20, false, $gzfile);
        }

        $this->assertTrue(file_exists($gzfile));

        $geoipfile = str_replace('.gz', '', $gzfile);

        // Open our files (in binary mode).
        $file = gzopen($gzfile, 'rb');
        $geoipfilebuf = fopen($geoipfile, 'wb');

        // Keep repeating until the end of the input file.
        while (!gzeof($file)) {
            // Read buffer-size bytes.
            // Both fwrite and gzread and binary-safe.
            fwrite($geoipfilebuf, gzread($file, 4096));
        }

        // Files are done, close files.
        fclose($geoipfilebuf);
        gzclose($file);

        $this->assertTrue(file_exists($geoipfile));

        $CFG->geoip2file = $geoipfile;
    }

    public function test_ipv4() {

        $result = iplookup_find_location('131.111.150.25');

        $this->assertEquals('array', gettype($result));
        $this->assertEquals('Cambridge', $result['city']);
        $this->assertEquals(0.1167, $result['longitude'], 'Coordinates are out of accepted tolerance', 0.01);
        $this->assertEquals(52.2, $result['latitude'], 'Coordinates are out of accepted tolerance', 0.01);
        $this->assertNull($result['error']);
        $this->assertEquals('array', gettype($result['title']));
        $this->assertEquals('Cambridge', $result['title'][0]);
        $this->assertEquals('United Kingdom', $result['title'][1]);
    }

    public function test_ipv6() {
        // NOTE: these tests can be altered by the geoip dataset, there has been an attempt to get
        // a 'reliable' result.

        $result = iplookup_find_location('2607:f010:3fe:fff1::ff:fe00:25');

        $this->assertEquals('array', gettype($result));
        $this->assertEquals('Los Angeles', $result['city']);
        $this->assertEquals(-118.2987, $result['longitude'], 'Coordinates are out of accepted tolerance', 0.01);
        $this->assertEquals(33.7866, $result['latitude'], 'Coordinates are out of accepted tolerance', 0.01);
        $this->assertNull($result['error']);
        $this->assertEquals('array', gettype($result['title']));
        $this->assertEquals('Los Angeles', $result['title'][0]);
        $this->assertEquals('United States', $result['title'][1]);
    }
}


text:
package codes.thischwa.bacoma.rest;

import org.springframework.beans.factory.annotation.Autowired;

import codes.thischwa.bacoma.model.pojo.site.Site;
import codes.thischwa.bacoma.rest.service.ContextUtility;
import codes.thischwa.bacoma.rest.util.FileSystemUtil;

public abstract class AbstractController {

	@Autowired
	protected FileSystemUtil fileSystemUtil;

	@Autowired
	protected ContextUtility cu;

	@Autowired
	private SiteConfiguration siteConfiguration;

	protected Site getSite(String siteUrl) {
		return cu.getSite(siteUrl);
	}

	protected String getProperty(Site site, String key) {
		return siteConfiguration.getSite().get(key);
	}
}


text:
<?php

namespace Impensavel\Spoil;

class SPRecycleBinItem extends SPObject
{
    use SPPropertiesTrait;

    /**
     * SharePoint Recycle Bin Item States (SharePoint 2013)
     *
     * @link  https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.recyclebinitemstate.aspx
     * @var   array
     */
    public static $states = [
        0 => 'None',                  // Unspecified state
        1 => 'FirstStageRecycleBin',  // Item is in the User Recycle Bin (first stage)
        2 => 'SecondStageRecycleBin', // Item is in the Site Collection Recycle Bin (second stage)
    ];

    /**
     * SharePoint Recycle Bin Item Types (SharePoint 2013)
     *
     * @link  https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.recyclebinitemtype.aspx
     * @var   array
     */
    public static $types = [
        0 => 'None',            // Unspecified type
        1 => 'File',            // File
        2 => 'FileVersion',     // Historical version of a File
        3 => 'ListItem',        // List Item
        4 => 'List',            // List
        5 => 'Folder',          // Folder
        6 => 'FolderWithLists', // Folder containing a List
        7 => 'Attachment',      // Attachment
        8 => 'ListItemVersion', // Historical version of a List Item
        9 => 'CascadeParent',   // Parent List Item of one or more List Items
    ];

    /**
     * SharePoint Site
     *
     * @var  SPSite
     */
    protected $site;

    /**
     * Item State
     *
     * @var  int
     */
    protected $state;

    /**
     * Item Type
     *
     * @var  int
     */
    protected $type;

    /**
     * Item Deletion Time
     *
     * @var  \Carbon\Carbon
     */
    protected $deleted;

    /**
     * Relative Directory
     *
     * @var  string
     */
    protected $relativeDir;

    /**
     * Item Name
     *
     * @var  string
     */
    protected $name;

    /**
     * Item Size
     *
     * @var  int
     */
    protected $size = 0;

    /**
     * Item Author
     *
     * @var  string
     */
    protected $author;

    /**
     * Item Deleter
     *
     * @var  string
     */
    protected $deleter;

    /**
     * SharePoint Recycle Bin Item constructor
     *
     * @param   SPSite $site    SharePoint Site
     * @param   array  $payload OData response payload
     * @param   array  $extra   Extra properties to map
     * @throws  \Impensavel\Spoil\Exception\SPBadMethodCallException
     */
    public function __construct(SPSite $site, array $payload, array $extra = [])
    {
        $this->mapper = array_merge([
            'spType'      => 'odata.type',
            'state'       => 'ItemState',
            'type'        => 'ItemType',
            'guid'        => 'Id',
            'title'       => 'Title',
            'relativeDir' => 'DirName',
            'name'        => 'LeafName',
            'size'        => 'Size',
            'deleted'     => 'DeletedDate',
            'author'      => 'AuthorName',
            'deleter'     => 'DeletedByName',
        ], $extra);

        $this->site = $site;

        $this->hydrate($payload);
    }

    /**
     * {@inheritdoc}
     */
    public function toArray()
    {
        return [
            'sp_type'      => $this->spType,
            'state'        => $this->state,
            'type'         => $this->type,
            'guid'         => $this->guid,
            'title'        => $this->title,
            'relative_dir' => $this->relativeDir,
            'name'         => $this->name,
            'size'         => $this->size,
            'deleted'      => $this->deleted,
            'author'       => $this->author,
            'deleter'      => $this->deleter,
            'extra'        => $this->extra,
        ];
    }

    /**
     * Get Item State
     *
     * @return  int
     */
    public function getState()
    {
        return $this->state;
    }

    /**
     * Get Item Type
     *
     * @return  int
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Get Relative Directory
     *
     * @return  string
     */
    public function getRelativeDir()
    {
        return $this->relativeDir;
    }

    /**
     * Get Item Name
     *
     * @return  string|null
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Get Item Size (in KiloBytes)
     *
     * @return  int
     */
    public function getSize()
    {
        return $this->size;
    }

    /**
     * Get Deletion Time
     *
     * @return  \Carbon\Carbon
     */
    public function getTimeDeleted()
    {
        return $this->deleted;
    }

    /**
     * Get Author
     *
     * @return  string
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * Get Deleter
     *
     * @return  string
     */
    public function getDeleter()
    {
        return $this->deleter;
    }

    /**
     * Get a SharePoint RecycleBinItem by GUID
     *
     * @param   SPSite $site  SharePoint Site
     * @param   string $guid  SharePoint RecycleBinItem GUID
     * @param   array  $extra Extra properties to map
     * @throws  \Impensavel\Spoil\Exception\SPRuntimeException
     * @return  SPRecycleBinItem
     */
    public static function getByGUID(SPSite $site, $guid, array $extra = [])
    {
        $json = $site->request("_api/web/RecycleBin('".$guid."')", [
            'headers' => [
                'Authorization' => 'Bearer '.$site->getSPAccessToken(),
                'Accept'        => 'application/json',
            ],
        ]);

        return new static($site, $json, $extra);
    }

    /**
     * Restore a SharePoint RecycleBin Item
     *
     * @throws  \Impensavel\Spoil\Exception\SPRuntimeException
     * @return  bool
     */
    public function restore()
    {
        $this->site->request("_api/web/RecycleBin('".$this->guid."')/restore()", [
            'headers' => [
                'Authorization' => 'Bearer '.$this->site->getSPAccessToken(),
                'Accept'        => 'application/json',
            ],
        ], 'POST');

        return true;
    }

    /**
     * Permanently delete a SharePoint RecycleBin Item
     *
     * @throws  \Impensavel\Spoil\Exception\SPRuntimeException
     * @return  bool
     */
    public function delete()
    {
        $this->site->request("_api/web/RecycleBin('".$this->guid."')/deleteObject()", [
            'headers' => [
                'Authorization' => 'Bearer '.$this->site->getSPAccessToken(),
                'Accept'        => 'application/json',
            ],
        ], 'POST');

        return true;
    }
}


text:
<?php

use Plank\Metable\Tests\Mocks\SampleMetable;
use Plank\Metable\Tests\Mocks\SampleMetableSoftDeletes;

$factory->define(SampleMetable::class, function (Faker\Generator $faker) {
    return [];
});

$factory->define(SampleMetableSoftDeletes::class, function (Faker\Generator $faker) {
    return [];
});


text:
require 'faker'

FactoryGirl.define do
  factory :user do
    sequence(:email) { |n| Faker::Internet.email }
    password '12345'
    password_confirmation '12345'
    locale 'ru'
    sequence(:authentication_token) { |n| SecureRandom.urlsafe_base64(nil, false) }
  end
end


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.mojo.bindings;

import org.chromium.mojo.bindings.Struct.DataHeader;
import org.chromium.mojo.system.DataPipe;
import org.chromium.mojo.system.Handle;
import org.chromium.mojo.system.InvalidHandle;
import org.chromium.mojo.system.MessagePipeHandle;
import org.chromium.mojo.system.SharedBufferHandle;

import java.nio.ByteOrder;
import java.nio.charset.Charset;

/**
 * A Decoder is a helper class for deserializing a mojo struct. It enables deserialization of basic
 * types from a {@link Message} object at a given offset into it's byte buffer.
 */
public class Decoder {

    /**
     * Helper class to validate the decoded message.
     */
    static final class Validator {

        /**
         * Minimal value for the next handle to deserialize.
         */
        private int mMinNextClaimedHandle = 0;
        /**
         * Minimal value of the start of the next memory to claim.
         */
        private long mMinNextMemory = 0;

        /**
         * The maximal memory accessible.
         */
        private final long mMaxMemory;

        /**
         * Constructor.
         */
        Validator(long maxMemory) {
            mMaxMemory = maxMemory;
        }

        public void claimHandle(int handle) {
            if (handle < mMinNextClaimedHandle) {
                throw new DeserializationException(
                        "Trying to access handle out of order.");
            }
            mMinNextClaimedHandle = handle + 1;
        }

        public void claimMemory(long start, long end) {
            if (start < mMinNextMemory) {
                throw new DeserializationException("Trying to access memory out of order.");
            }
            if (end < start) {
                throw new DeserializationException("Incorrect memory range.");
            }
            if (end > mMaxMemory) {
                throw new DeserializationException("Trying to access out of range memory.");
            }
            if (start % BindingsHelper.ALIGNMENT != 0 || end % BindingsHelper.ALIGNMENT != 0) {
                throw new DeserializationException("Incorrect alignment.");
            }
            mMinNextMemory = end;
        }
    }

    /**
     * The message to deserialize from.
     */
    private final Message mMessage;

    /**
     * The base offset in the byte buffer.
     */
    private final int mBaseOffset;

    /**
     * Validator for the decoded message.
     */
    private final Validator mValidator;

    /**
     * Constructor.
     *
     * @param message The message to decode.
     */
    public Decoder(Message message) {
        this(message, new Validator(message.buffer.limit()), 0);
    }

    private Decoder(Message message, Validator validator, int baseOffset) {
        mMessage = message;
        mMessage.buffer.order(ByteOrder.nativeOrder());
        mBaseOffset = baseOffset;
        mValidator = validator;
        // Claim the memory for the header.
        mValidator.claimMemory(mBaseOffset, mBaseOffset + DataHeader.HEADER_SIZE);
    }

    /**
     * Deserializes a {@link DataHeader} at the given offset.
     */
    public DataHeader readDataHeader() {
        int size = readInt(DataHeader.SIZE_OFFSET);
        int numFields = readInt(DataHeader.NUM_FIELDS_OFFSET);
        // The memory for the header has already been claimed.
        mValidator.claimMemory(mBaseOffset + DataHeader.HEADER_SIZE, mBaseOffset + size);
        DataHeader res = new DataHeader(size, numFields);
        return res;
    }

    /**
     * Deserializes a byte at the given offset.
     */
    public byte readByte(int offset) {
        return mMessage.buffer.get(mBaseOffset + offset);
    }

    /**
     * Deserializes a boolean at the given offset, re-using any partially read byte.
     */
    public boolean readBoolean(int offset, int bit) {
        return (readByte(offset) & (1 << bit)) != 0;
    }

    /**
     * Deserializes a short at the given offset.
     */
    public short readShort(int offset) {
        return mMessage.buffer.getShort(mBaseOffset + offset);
    }

    /**
     * Deserializes an int at the given offset.
     */
    public int readInt(int offset) {
        return mMessage.buffer.getInt(mBaseOffset + offset);
    }

    /**
     * Deserializes a float at the given offset.
     */
    public float readFloat(int offset) {
        return mMessage.buffer.getFloat(mBaseOffset + offset);
    }

    /**
     * Deserializes a long at the given offset.
     */
    public long readLong(int offset) {
        return mMessage.buffer.getLong(mBaseOffset + offset);
    }

    /**
     * Deserializes a double at the given offset.
     */
    public double readDouble(int offset) {
        return mMessage.buffer.getDouble(mBaseOffset + offset);
    }

    /**
     * Deserializes a pointer at the given offset. Returns a Decoder suitable to decode the content
     * of the pointer.
     */
    public Decoder readPointer(int offset) {
        int basePosition = mBaseOffset + offset;
        long pointerOffset = readLong(offset);
        if (pointerOffset == 0) {
            return null;
        }
        int newPosition = (int) (basePosition + pointerOffset);
        // The method |getDecoderAtPosition| will validate that the pointer address is valid.
        return getDecoderAtPosition(newPosition);

    }

    /**
     * Deserializes an array of boolean at the given offset.
     */
    public boolean[] readBooleans(int offset) {
        Decoder d = readPointer(offset);
        if (d == null) {
            return null;
        }
        DataHeader si = d.readDataHeader();
        byte[] bytes = new byte[si.numFields + 7 / BindingsHelper.ALIGNMENT];
        d.mMessage.buffer.position(d.mBaseOffset + DataHeader.HEADER_SIZE);
        d.mMessage.buffer.get(bytes);
        boolean[] result = new boolean[si.numFields];
        for (int i = 0; i < bytes.length; ++i) {
            for (int j = 0; j < BindingsHelper.ALIGNMENT; ++j) {
                int booleanIndex = i * BindingsHelper.ALIGNMENT + j;
                if (booleanIndex < result.length) {
                    result[booleanIndex] = (bytes[i] & (1 << j)) != 0;
                }
            }
        }
        return result;
    }

    /**
     * Deserializes an array of bytes at the given offset.
     */
    public byte[] readBytes(int offset) {
        Decoder d = readPointer(offset);
        if (d == null) {
            return null;
        }
        DataHeader si = d.readDataHeader();
        byte[] result = new byte[si.numFields];
        d.mMessage.buffer.position(d.mBaseOffset + DataHeader.HEADER_SIZE);
        d.mMessage.buffer.get(result);
        return result;
    }

    /**
     * Deserializes an array of shorts at the given offset.
     */
    public short[] readShorts(int offset) {
        Decoder d = readPointer(offset);
        if (d == null) {
            return null;
        }
        DataHeader si = d.readDataHeader();
        short[] result = new short[si.numFields];
        d.mMessage.buffer.position(d.mBaseOffset + DataHeader.HEADER_SIZE);
        d.mMessage.buffer.asShortBuffer().get(result);
        return result;
    }

    /**
     * Deserializes an array of ints at the given offset.
     */
    public int[] readInts(int offset) {
        Decoder d = readPointer(offset);
        if (d == null) {
            return null;
        }
        DataHeader si = d.readDataHeader();
        int[] result = new int[si.numFields];
        d.mMessage.buffer.position(d.mBaseOffset + DataHeader.HEADER_SIZE);
        d.mMessage.buffer.asIntBuffer().get(result);
        return result;
    }

    /**
     * Deserializes an array of floats at the given offset.
     */
    public float[] readFloats(int offset) {
        Decoder d = readPointer(offset);
        if (d == null) {
            return null;
        }
        DataHeader si = d.readDataHeader();
        float[] result = new float[si.numFields];
        d.mMessage.buffer.position(d.mBaseOffset + DataHeader.HEADER_SIZE);
        d.mMessage.buffer.asFloatBuffer().get(result);
        return result;
    }

    /**
     * Deserializes an array of longs at the given offset.
     */
    public long[] readLongs(int offset) {
        Decoder d = readPointer(offset);
        if (d == null) {
            return null;
        }
        DataHeader si = d.readDataHeader();
        long[] result = new long[si.numFields];
        d.mMessage.buffer.position(d.mBaseOffset + DataHeader.HEADER_SIZE);
        d.mMessage.buffer.asLongBuffer().get(result);
        return result;
    }

    /**
     * Deserializes an array of doubles at the given offset.
     */
    public double[] readDoubles(int offset) {
        Decoder d = readPointer(offset);
        if (d == null) {
            return null;
        }
        DataHeader si = d.readDataHeader();
        double[] result = new double[si.numFields];
        d.mMessage.buffer.position(d.mBaseOffset + DataHeader.HEADER_SIZE);
        d.mMessage.buffer.asDoubleBuffer().get(result);
        return result;
    }

    /**
     * Deserializes an |Handle| at the given offset.
     */
    public Handle readHandle(int offset) {
        int index = readInt(offset);
        if (index == -1) {
            return InvalidHandle.INSTANCE;
        }
        mValidator.claimHandle(index);
        return mMessage.handles.get(index);
    }

    /**
     * Deserializes a |ConsumerHandle| at the given offset.
     */
    public DataPipe.ConsumerHandle readConsumerHandle(int offset) {
        return readHandle(offset).toUntypedHandle().toDataPipeConsumerHandle();
    }

    /**
     * Deserializes a |ProducerHandle| at the given offset.
     */
    public DataPipe.ProducerHandle readProducerHandle(int offset) {
        return readHandle(offset).toUntypedHandle().toDataPipeProducerHandle();
    }

    /**
     * Deserializes a |MessagePipeHandle| at the given offset.
     */
    public MessagePipeHandle readMessagePipeHandle(int offset) {
        return readHandle(offset).toUntypedHandle().toMessagePipeHandle();
    }

    /**
     * Deserializes a |SharedBufferHandle| at the given offset.
     */
    public SharedBufferHandle readSharedBufferHandle(int offset) {
        return readHandle(offset).toUntypedHandle().toSharedBufferHandle();
    }

    /**
     * Deserializes a |ServiceHandle| at the given offset.
     */
    public <S extends Interface> S readServiceInterface(int offset, Object builder) {
        // TODO(qsr): To be implemented when interfaces proxy and stubs are implemented.
        throw new UnsupportedOperationException("Unimplemented operation");
    }

    /**
     * Deserializes a |InterfaceRequest| at the given offset.
     */
    public <S extends Interface> InterfaceRequest<S> readInterfaceRequest(int offset) {
        // TODO(qsr): To be implemented when interfaces proxy and stubs are implemented.
        throw new UnsupportedOperationException("Unimplemented operation");
    }

    /**
     * Deserializes a string at the given offset.
     */
    public String readString(int offset) {
        byte[] bytes = readBytes(offset);
        if (bytes == null) {
            return null;
        }
        return new String(bytes, Charset.forName("utf8"));
    }

    /**
     * Deserializes an array of |Handle| at the given offset.
     */
    public Handle[] readHandles(int offset) {
        Decoder d = readPointer(offset);
        if (d == null) {
            return null;
        }
        DataHeader si = d.readDataHeader();
        Handle[] result = new Handle[si.numFields];
        for (int i = 0; i < result.length; ++i) {
            result[i] = d.readHandle(
                    DataHeader.HEADER_SIZE + BindingsHelper.SERIALIZED_HANDLE_SIZE * i);
        }
        return result;
    }

    /**
     * Deserializes an array of |ConsumerHandle| at the given offset.
     */
    public DataPipe.ConsumerHandle[] readConsumerHandles(int offset) {
        Decoder d = readPointer(offset);
        if (d == null) {
            return null;
        }
        DataHeader si = d.readDataHeader();
        DataPipe.ConsumerHandle[] result = new DataPipe.ConsumerHandle[si.numFields];
        for (int i = 0; i < result.length; ++i) {
            result[i] = d.readConsumerHandle(
                    DataHeader.HEADER_SIZE + BindingsHelper.SERIALIZED_HANDLE_SIZE * i);
        }
        return result;
    }

    /**
     * Deserializes an array of |ProducerHandle| at the given offset.
     */
    public DataPipe.ProducerHandle[] readProducerHandles(int offset) {
        Decoder d = readPointer(offset);
        if (d == null) {
            return null;
        }
        DataHeader si = d.readDataHeader();
        DataPipe.ProducerHandle[] result = new DataPipe.ProducerHandle[si.numFields];
        for (int i = 0; i < result.length; ++i) {
            result[i] = d.readProducerHandle(
                    DataHeader.HEADER_SIZE + BindingsHelper.SERIALIZED_HANDLE_SIZE * i);
        }
        return result;

    }

    /**
     * Deserializes an array of |MessagePipeHandle| at the given offset.
     */
    public MessagePipeHandle[] readMessagePipeHandles(int offset) {
        Decoder d = readPointer(offset);
        if (d == null) {
            return null;
        }
        DataHeader si = d.readDataHeader();
        MessagePipeHandle[] result = new MessagePipeHandle[si.numFields];
        for (int i = 0; i < result.length; ++i) {
            result[i] = d.readMessagePipeHandle(
                    DataHeader.HEADER_SIZE + BindingsHelper.SERIALIZED_HANDLE_SIZE * i);
        }
        return result;

    }

    /**
     * Deserializes an array of |SharedBufferHandle| at the given offset.
     */
    public SharedBufferHandle[] readSharedBufferHandles(int offset) {
        Decoder d = readPointer(offset);
        if (d == null) {
            return null;
        }
        DataHeader si = d.readDataHeader();
        SharedBufferHandle[] result = new SharedBufferHandle[si.numFields];
        for (int i = 0; i < result.length; ++i) {
            result[i] = d.readSharedBufferHandle(
                    DataHeader.HEADER_SIZE + BindingsHelper.SERIALIZED_HANDLE_SIZE * i);
        }
        return result;

    }

    /**
     * Deserializes an array of |ServiceHandle| at the given offset.
     */
    public <S extends Interface> S[] readServiceInterfaces(int offset, Object builder) {
        // TODO(qsr): To be implemented when interfaces proxy and stubs are implemented.
        throw new UnsupportedOperationException("Unimplemented operation");
    }

    /**
     * Deserializes an array of |InterfaceRequest| at the given offset.
     */
    public <S extends Interface> InterfaceRequest<S>[] readInterfaceRequests(int offset) {
        Decoder d = readPointer(offset);
        if (d == null) {
            return null;
        }
        DataHeader si = d.readDataHeader();
        @SuppressWarnings("unchecked")
        InterfaceRequest<S>[] result = new InterfaceRequest[si.numFields];
        for (int i = 0; i < result.length; ++i) {
            result[i] = d.readInterfaceRequest(
                    DataHeader.HEADER_SIZE + BindingsHelper.SERIALIZED_HANDLE_SIZE * i);
        }
        return result;
    }

    /**
     * Returns a view of this decoder at the offset |offset|.
     */
    private Decoder getDecoderAtPosition(int offset) {
        return new Decoder(mMessage, mValidator, offset);
    }

}


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

<title>org.canova.hadoop.formats.input</title>
<meta name="date" content="2016-06-19">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.canova.hadoop.formats.input

Classes

SVMLightInputFormat


text:
package osgi.enroute.examples.component.examples;

import org.osgi.service.component.annotations.Component;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;

@Component(property=EventConstants.EVENT_TOPIC+"=osgi/enroute/*")
public class EventListener implements EventHandler {

	@Override
	public void handleEvent(Event event) {
		System.out.println("Event: " + event.getTopic());
	}
}


text:
#region Copyright Information
// Sentience Lab Unity Framework
// (C) Sentience Lab (sentiencelab@aut.ac.nz), Auckland University of Technology, Auckland, New Zealand
#endregion Copyright Information

using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;

namespace SentienceLab.OSC
{
	[AddComponentMenu("OSC/Slider Variable")]
	[RequireComponent(typeof(Slider))]
	public class OSC_SliderVariable : MonoBehaviour, IOSCVariableContainer
	{
		public string variableName = "/slider1";

		public void Start()
		{
			m_slider = GetComponent<Slider>();
			m_slider.onValueChanged.AddListener(delegate { OnSliderChanged(); });

			m_variable       = new OSC_FloatVariable();
			m_variable.Name  = variableName;
			m_variable.Min   = m_slider.minValue;
			m_variable.Max   = m_slider.maxValue;
			m_variable.Value = m_slider.value;

			m_variable.OnDataReceived += OnReceivedOSC_Data;

			m_updating = false;
		}

		protected void OnReceivedOSC_Data(OSC_Variable var)
		{
			if (!m_updating)
			{
				m_updating = true;
				m_slider.value = m_variable.Value;
				m_updating = false;
			}
		}

		protected void OnSliderChanged()
		{
			if (!m_updating)
			{
				m_updating = true;
				m_variable.Value = m_slider.value;
				m_variable.SendUpdate();
				m_updating = false;
			}
		}

		public List<OSC_Variable> GetOSC_Variables()
		{
			return new List<OSC_Variable>(new OSC_Variable[] { m_variable });
		}

		private Slider            m_slider;
		private OSC_FloatVariable m_variable;
		private bool              m_updating;
	}
}


text:
export abstract class View {
  protected container: HTMLElement;
  protected divNode: HTMLElement;
  protected abstract createViewElement(): HTMLElement;

  constructor(idOrContainer: string | HTMLElement) {
    this.container = typeof idOrContainer == "string" ? document.getElementById(idOrContainer) : idOrContainer;
    this.divNode = this.createViewElement();
  }

  public show(): void {
    this.container.appendChild(this.divNode);
  }

  public hide(): void {
    this.container.removeChild(this.divNode);
  }
}

export abstract class PhaseView extends View {
  public abstract initializeContent(data: any, rememberedSelection: Set<any>): void;
  public abstract detachSelection(): Set<string>;
  public abstract onresize(): void;
  public abstract searchInputAction(searchInput: HTMLInputElement, e: Event, onlyVisible: boolean): void;

  constructor(idOrContainer: string | HTMLElement) {
    super(idOrContainer);
  }
}


text:
//
//  ROUSession.h
//  RoUTPTests
//
//  Created by Yan Rabovik on 27.06.13.
//  Copyright (c) 2013 Yan Rabovik. All rights reserved.
//

#import <Foundation/Foundation.h>

@class ROUSession;

@protocol ROUSessionDelegate <NSObject>
-(void)session:(ROUSession *)session receivedData:(NSData *)data;
-(void)session:(ROUSession *)session preparedDataForSending:(NSData *)data;
@end

@interface ROUSession : NSObject
/**
 @discussion Session automatically starts on first data sent. Use this method to start
 session earlier.
 */
-(void)start;
-(void)sendData:(NSData *)data;
-(void)receiveData:(NSData *)data;
-(void)setDelegate:(id<ROUSessionDelegate>)delegate;
/**
 @queue The queue where the delegate methods will be dispatched.
 The queue is retained by session.
 If no queue specified then dispatch_get_main_queue() will be used.
 */
-(void)setDelegate:(id<ROUSessionDelegate>)delegate
             queue:(dispatch_queue_t)queue;
@end


text:
using System;
using System.Data;
using SharpData.Databases;
using Xunit;
using SharpData.Databases.Oracle;
using SharpData.Schema;
using SharpData.Tests.Integration.Data;
using SharpData.Util;

namespace SharpData.Tests.Integration.Oracle {

    public class OracleManagedDatabaseTests : DatabaseTests {

        public OracleManagedDatabaseTests() {
            CleanTables();
        }
        protected override DbProviderType GetDataProviderName() {
            return DbProviderType.OracleManaged;
        }

        public override void Can_bulk_insert_stored_procedure() {
            DataClient.AddTable(TableFoo, Column.Int32("colInt"));
            try {
                Database.ExecuteSql("drop procedure pr_bulk");
            }
            catch { }
            Database.ExecuteSql("create or replace procedure pr_bulk(v_value in number) is begin insert into foo (colInt) values (v_value); end pr_bulk;");

            var v1s = new[] { 1, 2, 3, 4 };

            Database.ExecuteBulkStoredProcedure("pr_bulk", In.Named("v_value", v1s));
            var res = DataClient.Select
                                .Columns("colInt")
                                .From(TableFoo)
                                .AllRows();
            Assert.Equal(4, res.Count);
        }

        public override void Can_bulk_insert_stored_procedure_with_nullable() {
            DataClient.AddTable(TableFoo, Column.Decimal("colDecimal"));
            try {
                Database.ExecuteSql("drop procedure pr_bulk");
            }
            catch { }
            Database.ExecuteSql("create or replace procedure pr_bulk(v_value in float) is begin insert into foo (colDecimal) values (v_value); end pr_bulk;");

            var v1s = new decimal?[] { 1, 2, 3, 4, null };

            Database.ExecuteBulkStoredProcedure("pr_bulk", In.Named("v_value", v1s));
            var res = DataClient.Select
                .Columns("colDecimal")
                .From(TableFoo)
                .AllRows();

            Assert.Equal(5, res.Count);
        }

        [Fact]
        public override void Can_bulk_insert_stored_procedure_with_first_item_null() {
            DataClient.AddTable(TableFoo, Column.Decimal("colDecimal"));
            try {
                Database.ExecuteSql("drop procedure pr_bulk");
            }
            catch { }
            Database.ExecuteSql("create or replace procedure pr_bulk(v_value in float) is begin insert into foo (colDecimal) values (v_value); end pr_bulk;");

            var v1s = new decimal?[] { null, 2, null, 4, null };

            Database.ExecuteBulkStoredProcedure("pr_bulk", In.Named("v_value", v1s));
            var res = DataClient.Select
                .Columns("colDecimal")
                .From(TableFoo)
                .AllRows();

            Assert.Equal(5, res.Count);
        }

        [Fact]
        public override void Can_bulk_insert_stored_procedure_with_all_items_null() {
            DataClient.AddTable(TableFoo, Column.Decimal("colDecimal"));
            try {
                Database.ExecuteSql("drop procedure pr_bulk");
            }
            catch { }
            Database.ExecuteSql("create or replace procedure pr_bulk(v_value in float) is begin insert into foo (colDecimal) values (v_value); end pr_bulk;");

            var v1s = new decimal?[] { null, null, null, null, null };

            Database.ExecuteBulkStoredProcedure("pr_bulk", In.Named("v_value", v1s));
            ResultSet res = DataClient.Select
                .Columns("colDecimal")
                .From(TableFoo)
                .AllRows();

            Assert.Equal(5, res.Count);
        }

        public override void Can_bulk_insert_stored_procedure_with_nullable_and_dates() {
            DataClient.AddTable(TableFoo, Column.Decimal("colDecimal"), Column.Date("colDate"));
            try {
                Database.ExecuteSql("drop procedure pr_bulkDate");
            }
            catch { }
            Database.ExecuteSql("create or replace procedure pr_bulkDate(v_value in float, v_date in date) is begin insert into foo (colDecimal, colDate) values (v_value, v_date); end pr_bulkDate;");

            var v1s = new decimal?[] { 1, 2, 3, 4, null };
            var v2s = new[] { DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now };

            Database.ExecuteBulkStoredProcedure("pr_bulkDate", In.Named("v_value", v1s), In.Named("v_date", v2s));
            var res = DataClient.Select
                .Columns("colDecimal", "colDate")
                .From(TableFoo)
                .AllRows();
            Assert.Equal(5, res.Count);
        }

        public override void Can_call_stored_function_with_return_as_string() {
            Database.ExecuteSql("create or replace function fn_test(par1 in varchar2, par2 in varchar2) return varchar2 is begin return upper(par1 || par2); end fn_test;");
            var result = Database.CallStoredFunction(DbType.String, "fn_test", In.Named("par1", "a"), In.Named("par2", "b"));
            Assert.Equal("AB", result);
        }

        public override void Can_call_stored_function_with_return_as_int() {
            Database.ExecuteSql("create or replace function fn_test(par1 in varchar2, par2 in varchar2) return int is begin return 1; end fn_test;");
            var result = Database.CallStoredFunction(DbType.Int32, "fn_test", In.Named("par1", "a"), In.Named("par2", "b"));
            Assert.Equal(1, result);
        }

        public override void Dispose() {
            base.Dispose();
            typeof(OracleManagedProvider).GetField("_reflectionCache", ReflectionHelper.NoRestrictions)
                                         .SetValue(null, new OracleReflectionCache());
        }
    }
}


text:
DEFAULT=/etc/default/influxdb

# Daemon options
INFLUXD_OPTS=

# Process name ( For display )
NAME=influxdb

# User and group
USER=influxdb
GROUP=influxdb

# Check for sudo or root privileges before continuing
if [ "$UID" != "0" ]; then
    echo "You must be root to run this script"
    exit 1
fi

# Daemon name, where is the actual executable If the daemon is not
# there, then exit.
DAEMON=/usr/bin/influxd
if [ ! -x $DAEMON ]; then
    echo "Executable $DAEMON does not exist!"
    exit 5
fi

# Configuration file
CONFIG=/etc/influxdb/influxdb.conf

# PID file for the daemon
PIDFILE=/var/run/influxdb/influxd.pid
PIDDIR=`dirname $PIDFILE`
if [ ! -d "$PIDDIR" ]; then
    mkdir -p $PIDDIR
    chown $USER:$GROUP $PIDDIR
fi

# Max open files
OPEN_FILE_LIMIT=65536

if [ -r /lib/lsb/init-functions ]; then
    source /lib/lsb/init-functions
fi

# Logging
if [ -z "$STDOUT" ]; then
    STDOUT=/dev/null
fi

if [ ! -f "$STDOUT" ]; then
    mkdir -p $(dirname $STDOUT)
fi

if [ -z "$STDERR" ]; then
    STDERR=/var/log/influxdb/influxd.log
fi

if [ ! -f "$STDERR" ]; then
    mkdir -p $(dirname $STDERR)
fi

# Override init script variables with DEFAULT values
if [ -r $DEFAULT ]; then
    source $DEFAULT
fi

function log_failure_msg() {
    echo "$@" "[ FAILED ]"
}

function log_success_msg() {
    echo "$@" "[ OK ]"
}

function start() {
    # Check if config file exist
    if [ ! -r $CONFIG ]; then
        log_failure_msg "config file $CONFIG doesn't exist (or you don't have permission to view)"
        exit 4
    fi

    # Check that the PID file exists, and check the actual status of process
    if [ -f $PIDFILE ]; then
        PID="$(cat $PIDFILE)"
        if kill -0 "$PID" &>/dev/null; then
            # Process is already up
            log_success_msg "$NAME process is already running"
            return 0
        fi
    else
        su -s /bin/sh -c "touch $PIDFILE" $USER &>/dev/null
        if [ $? -ne 0 ]; then
            log_failure_msg "$PIDFILE not writable, check permissions"
            exit 5
        fi
    fi

    # Bump the file limits, before launching the daemon. These will
    # carry over to launched processes.
    ulimit -n $OPEN_FILE_LIMIT
    if [ $? -ne 0 ]; then
        log_failure_msg "Unable to set ulimit to $OPEN_FILE_LIMIT"
        exit 1
    fi

    # Launch process
    echo "Starting $NAME..."
    if command -v start-stop-daemon &>/dev/null; then
        start-stop-daemon \
            --chuid $USER:$GROUP \
            --start \
            --quiet \
            --pidfile $PIDFILE \
            --exec $DAEMON \
            -- \
            -pidfile $PIDFILE \
            -config $CONFIG \
            $INFLUXD_OPTS >>$STDOUT 2>>$STDERR &
    else
        local CMD="$DAEMON -pidfile $PIDFILE -config $CONFIG $INFLUXD_OPTS >>$STDOUT 2>>$STDERR &"
        su -s /bin/sh -c "$CMD" $USER
    fi

    # Sleep to verify process is still up
    sleep 1
    if [ -f $PIDFILE ]; then
        # PIDFILE exists
        if kill -0 $(cat $PIDFILE) &>/dev/null; then
            # PID up, service running
            log_success_msg "$NAME process was started"
            return 0
        fi
    fi
    log_failure_msg "$NAME process was unable to start"
    exit 1
}

function stop() {
    # Stop the daemon.
    if [ -f $PIDFILE ]; then
        local PID="$(cat $PIDFILE)"
        if kill -0 $PID &>/dev/null; then
            echo "Stopping $NAME..."
            # Process still up, send SIGTERM and remove PIDFILE
            kill -s TERM $PID &>/dev/null && rm -f "$PIDFILE" &>/dev/null
            n=0
            while true; do
                # Enter loop to ensure process is stopped
                kill -0 $PID &>/dev/null
                if [ "$?" != "0" ]; then
                    # Process stopped, break from loop
                    log_success_msg "$NAME process was stopped"
                    return 0
                fi

                # Process still up after signal, sleep and wait
                sleep 1
                n=$(expr $n + 1)
                if [ $n -eq 30 ]; then
                    # After 30 seconds, send SIGKILL
                    echo "Timeout exceeded, sending SIGKILL..."
                    kill -s KILL $PID &>/dev/null
                elif [ $? -eq 40 ]; then
                    # After 40 seconds, error out
                    log_failure_msg "could not stop $NAME process"
                    exit 1
                fi
            done
        fi
    fi
    log_success_msg "$NAME process already stopped"
}

function restart() {
    # Restart the daemon.
    stop
    start
}

function status() {
    # Check the status of the process.
    if [ -f $PIDFILE ]; then
        PID="$(cat $PIDFILE)"
        if kill -0 $PID &>/dev/null; then
            log_success_msg "$NAME process is running"
            exit 0
        fi
    fi
    log_failure_msg "$NAME process is not running"
    exit 1
}

case $1 in
    start)
        start
        ;;

    stop)
        stop
        ;;

    restart)
        restart
        ;;

    status)
        status
        ;;

    version)
        $DAEMON version
        ;;

    *)
        # For invalid arguments, print the usage message.
        echo "Usage: $0 {start|stop|restart|status|version}"
        exit 2
        ;;
esac