text:
package com.elytradev.teckle.client.render.model;

import com.elytradev.teckle.common.block.BlockItemTube;
import com.elytradev.teckle.common.block.property.UnlistedBool;
import com.google.common.collect.Lists;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ItemOverrideList;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.property.IExtendedBlockState;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class BakedTubeModel implements IBakedModel {

    private HashMap<EnumFacing, IBakedModel> legModels;
    private HashMap<EnumFacing, IBakedModel> legModelsNode;
    private IBakedModel nodeModel;

    public BakedTubeModel(IBakedModel nodeModel, HashMap<EnumFacing, IBakedModel> legModels, HashMap<EnumFacing, IBakedModel> legModelsNode) {
        this.nodeModel = nodeModel;
        this.legModels = legModels;
        this.legModelsNode = legModelsNode;
    }

    @Override
    public List<BakedQuad> getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) {
        if (state instanceof IExtendedBlockState) {
            List<IBakedModel> modelData = getModelData((IExtendedBlockState) state);
            List<BakedQuad> quadData = new ArrayList<>();

            modelData.forEach(bakedModel -> quadData.addAll(bakedModel.getQuads(state, side, rand)));

            return quadData;
        }
        return Collections.emptyList();
    }

    public List<IBakedModel> getModelData(IExtendedBlockState state) {
        List<IBakedModel> result = Lists.newArrayList();

        if (state.getValue(BlockItemTube.NODE)) {
            result.add(nodeModel);
            result.addAll(addLegs(state, legModelsNode));
        } else {
            // No node.
            result.addAll(addLegs(state, legModels));
        }

        return result;
    }

    protected List<IBakedModel> addLegs(IExtendedBlockState state, HashMap<EnumFacing, IBakedModel> sourceModels) {
        List<IBakedModel> models = Lists.newArrayList();
        for (EnumFacing enumFacing : EnumFacing.values()) {
            UnlistedBool property = BlockItemTube.FACE_PROPERTIES.get(enumFacing);
            if (state.getValue(property)) {
                models.add(sourceModels.get(enumFacing));
            }
        }
        return models;
    }

    @Override
    public boolean isAmbientOcclusion() {
        return true;
    }

    @Override
    public boolean isGui3d() {
        return true;
    }

    @Override
    public boolean isBuiltInRenderer() {
        return false;
    }

    @Override
    public TextureAtlasSprite getParticleTexture() {
        return nodeModel.getParticleTexture();
    }

    @Override
    public ItemOverrideList getOverrides() {
        return ItemOverrideList.NONE;
    }
}


text:
permalink: /events/2015/05/14/hack-night/
category: events
layout: events
title: Hack Night (May 14, 2015)
head: Hack Night
subhead: May 14, 2015
description: We welcome everyone to join us and work together to improve their communities.
tags: ["hack nights"]
archived: true
time:
 - dtstart: 2015-05-14 17:30:00
   dtend: 2015-05-14 19:30:00
venue:
 - text: Burlington Generator
   link: http://generatorvt.com/
 - text: Memorial Auditorium Annex
 - text: 250 Main Street
 - text: Burlington, VT 05401
venue_note:  The venue is handicapped accessible.
policies: All Code for BTV and Code for America events and their staff, presenters, and attendees are held to a Code of Conduct and an Anti-Harassment Policy.
registration_required: true
registration_url: http://www.meetup.com/CodeForBTV/events/221661871/
registration_archived: true
---

Collaborate on Community and Civic Projects

{{ page.description }}

Code for BTV Hack Nights are a great opportunity to meet and collaborate with others working on community and civic projects. Whether you are a coder, designer, project manager, or are curious about how you can get involved, please join us. We need a wide variety of skills, experience and perspectives.

If you have a laptop, you may want to bring it. If you don't have a laptop, don't worry—you can still participate.

Learn more about Hack Nights

Hack Night Partner

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.IO;
using OnlineMessenger.Data.Ef.Utils;
using OnlineMessenger.Domain.Entities;
using OnlineMessenger.Domain.Utils;

namespace OnlineMessenger.Data.Ef.Models
{
    public class AppDatabaseInitializer : IDatabaseInitializer<MessengerDbContext>
    {
        public void InitializeDatabase(MessengerDbContext context)
        {
            context.ClearData();
            context.SaveChanges();

            AddAdmin(context);
            AddAllUsers(context);
        }

        private static void AddAdmin(MessengerDbContext context)
        {
            var adminRole = new Role { Name = Role.AdministratorRoleName };
            context.Roles.Add(adminRole);
            var operatorRole = new Role { Name = Role.OperatorRoleName };
            context.Roles.Add(operatorRole);
            var user = new User { Name = "Admin", PasswordHash = PasswordHasher.HashPassword("123456"), Email = "Tes111t@mail.ru", Roles = new List<Role> { adminRole } };
            context.Users.Add(user);
            context.SaveChanges();
        }

        #region userNames

        private static string[] UserNames =
        {
            "Emily",
            "Denise",
            "Samuel",
            "William",
            "Arthur",
            "Judith",
            "Kathleen",
            "Martin",
            "Charles",
            "Stephen",
            "Jesse",
            "Chris",
            "Russell",
            "Jean",
            "David",
            "Edward",
            "Adam",
            "Bruce",
            "Ashley",
            "Betty",
            "Jose",
            "Nancy",
            "Craig",
            "Rachel",
            "Deborah",
            "Fred",
            "Helen",
            "Billy",
            "Jeremy",
            "Melissa",
            "Brian",
            "Walter",
            "Carl",
            "Matthew",
            "Justin",
            "Heather",
            "Bonnie",
            "Joshua",
            "Douglas",
            "Jeffrey",
            "Jennifer",
            "Margaret"
        };

        #endregion

        private static void AddAllUsers(MessengerDbContext context)
        {
            var rand = new Random();

            var operatorRole = context.Roles.Single(x => x.Name == Role.OperatorRoleName);

            var passwordHash = PasswordHasher.HashPassword("123456");
            var users =
                UserNames.ToList()
                    .Select((x, i) =>
                            {
                                var user = new User
                                           {
                                               Email = GetRandomEmail(),
                                               Name = x,
                                               PasswordHash = passwordHash
                                           };
                                user.Roles.Add(operatorRole);
                                return user;
                            }
                    );
            context.Users.AddRange(users);
            context.SaveChanges();

            var random = new Random();

            context.SaveChanges();
            var dbUsers = context.Users;

            var count = dbUsers.Count();
            var messages =
                File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath ?? Environment.CurrentDirectory, "Messages.txt"))
                    .Split(".".ToCharArray())
                    .Select(x => new Message
                                 {
                                     Date = DateTime.Now.AddDays(random.Next(-10,10)),
                                     From = dbUsers.ToList().ElementAt(rand.Next(random.Next(count))),
                                     Text = x
                                 });
            context.Messages.AddRange(messages);
            context.SaveChanges();

            foreach (var user in context.Users.ToList())
            {
                var visUsers = new int[random.Next(1, 5)].Select(x => GetRandomUser());
                user.Clients.AddRange(visUsers);
                user.VisibleClients.AddRange(visUsers);
                context.SaveChanges();
            }
        }

        private static string GetRandomEmail()
        {
            return string.Format("{0}@gmail.com", Path.GetRandomFileName());
        }

        private static int indexer = 0;
        private static readonly Random Random = new Random();
        private static User GetRandomUser()
        {
            indexer++;
            string userName = String.Format("User{0}", indexer);
            return new User
                   {
                       Email = GetRandomEmail(),
                       Name = userName,
                       CreatedDate = DateTime.Now.AddDays(Random.Next(-10, 10)),
                       PasswordHash = PasswordHasher.HashPassword("123456")
                   };
        }

    }
}


text:
/* Author: Ioan Sucan */

#include <srdfdom/model.h>
#include <srdfdom/srdf_writer.h>
#include <urdf_parser/urdf_parser.h>
#include <fstream>
#include <stdexcept>
#include <gtest/gtest.h>

#ifndef TEST_RESOURCE_LOCATION
#define TEST_RESOURCE_LOCATION "."
#endif

struct ScopedLocale
{
  ScopedLocale(const char* name = "C")
  {
    backup_ = setlocale(LC_ALL, nullptr);  // store current locale
    setlocale(LC_ALL, name);
  }
  ~ScopedLocale()
  {
    setlocale(LC_ALL, backup_.c_str());  // restore locale
  }
  std::string backup_;
};

urdf::ModelInterfaceSharedPtr loadURDF(const std::string& filename)
{
  ScopedLocale l("C");
  // get the entire file
  std::string xml_string;
  std::fstream xml_file(filename.c_str(), std::fstream::in);
  if (xml_file.is_open())
  {
    while (xml_file.good())
    {
      std::string line;
      std::getline(xml_file, line);
      xml_string += (line + "\n");
    }
    xml_file.close();
    return urdf::parseURDF(xml_string);
  }
  else
  {
    throw std::runtime_error("Could not open file " + filename + " for parsing.");
    return urdf::ModelInterfaceSharedPtr();
  }
}

TEST(TestCpp, testSimple)
{
  srdf::Model s;
  urdf::ModelInterfaceSharedPtr u = loadURDF(std::string(TEST_RESOURCE_LOCATION) + "/pr2_desc.urdf");
  ASSERT_TRUE(u != NULL);

  EXPECT_TRUE(s.initFile(*u, std::string(TEST_RESOURCE_LOCATION) + "/pr2_desc.1.srdf"));
  EXPECT_TRUE(s.getVirtualJoints().size() == 0);
  EXPECT_TRUE(s.getGroups().size() == 0);
  EXPECT_TRUE(s.getGroupStates().size() == 0);
  EXPECT_TRUE(s.getDisabledCollisionPairs().empty());
  EXPECT_TRUE(s.getEnabledCollisionPairs().empty());
  EXPECT_TRUE(s.getEndEffectors().size() == 0);

  EXPECT_TRUE(s.initFile(*u, std::string(TEST_RESOURCE_LOCATION) + "/pr2_desc.2.srdf"));
  EXPECT_TRUE(s.getVirtualJoints().size() == 1);
  EXPECT_TRUE(s.getGroups().size() == 1);
  EXPECT_TRUE(s.getGroupStates().size() == 0);
  EXPECT_TRUE(s.getDisabledCollisionPairs().empty());
  EXPECT_TRUE(s.getEnabledCollisionPairs().empty());
  EXPECT_TRUE(s.getEndEffectors().size() == 0);

  EXPECT_TRUE(s.initFile(*u, std::string(TEST_RESOURCE_LOCATION) + "/pr2_desc.1.srdf"));
  EXPECT_TRUE(s.getVirtualJoints().size() == 0);
  EXPECT_TRUE(s.getGroups().size() == 0);
  EXPECT_TRUE(s.getGroupStates().size() == 0);
  EXPECT_TRUE(s.getDisabledCollisionPairs().empty());
  EXPECT_TRUE(s.getEnabledCollisionPairs().empty());
  EXPECT_TRUE(s.getEndEffectors().size() == 0);
}

TEST(TestCpp, testComplex)
{
  srdf::Model s;
  urdf::ModelInterfaceSharedPtr u = loadURDF(std::string(TEST_RESOURCE_LOCATION) + "/pr2_desc.urdf");
  EXPECT_TRUE(u != NULL);

  EXPECT_TRUE(s.initFile(*u, std::string(TEST_RESOURCE_LOCATION) + "/pr2_desc.3.srdf"));
  EXPECT_TRUE(s.getVirtualJoints().size() == 1);
  EXPECT_TRUE(s.getGroups().size() == 7);
  EXPECT_TRUE(s.getGroupStates().size() == 2);
  EXPECT_TRUE(s.getDisabledCollisionPairs().size() == 2);
  EXPECT_TRUE(s.getDisabledCollisionPairs()[0].reason_ == "adjacent");
  EXPECT_TRUE(s.getEndEffectors().size() == 2);

  EXPECT_TRUE(s.getVirtualJoints()[0].name_ == "world_joint");
  EXPECT_TRUE(s.getVirtualJoints()[0].type_ == "planar");
  for (std::size_t i = 0; i < s.getGroups().size(); ++i)
  {
    if (s.getGroups()[i].name_ == "left_arm" || s.getGroups()[i].name_ == "right_arm")
    {
      EXPECT_TRUE(s.getGroups()[i].chains_.size() == 1);
    }
    if (s.getGroups()[i].name_ == "arms")
    {
      EXPECT_TRUE(s.getGroups()[i].subgroups_.size() == 2);
    }
    if (s.getGroups()[i].name_ == "base")
    {
      EXPECT_TRUE(s.getGroups()[i].joints_.size() == 1);
    }
    if (s.getGroups()[i].name_ == "l_end_effector" || s.getGroups()[i].name_ == "r_end_effector")
    {
      EXPECT_TRUE(s.getGroups()[i].links_.size() == 1);
      EXPECT_TRUE(s.getGroups()[i].joints_.size() == 9);
    }
    if (s.getGroups()[i].name_ == "whole_body")
    {
      EXPECT_TRUE(s.getGroups()[i].joints_.size() == 1);
      EXPECT_TRUE(s.getGroups()[i].subgroups_.size() == 2);
    }
  }
  int index = 0;
  if (s.getGroupStates()[0].group_ != "arms")
    index = 1;

  EXPECT_TRUE(s.getGroupStates()[index].group_ == "arms");
  EXPECT_TRUE(s.getGroupStates()[index].name_ == "tuck_arms");
  EXPECT_TRUE(s.getGroupStates()[1 - index].group_ == "base");
  EXPECT_TRUE(s.getGroupStates()[1 - index].name_ == "home");

  const std::vector<double>& v = s.getGroupStates()[index].joint_values_.find("l_shoulder_pan_joint")->second;
  EXPECT_EQ(v.size(), 1u);
  EXPECT_EQ(v[0], 0.2);
  const std::vector<double>& w = s.getGroupStates()[1 - index].joint_values_.find("world_joint")->second;
  EXPECT_EQ(w.size(), 3u);
  EXPECT_EQ(w[0], 0.4);
  EXPECT_EQ(w[1], 0);
  EXPECT_EQ(w[2], -1);

  index = (s.getEndEffectors()[0].name_[0] == 'r') ? 0 : 1;
  EXPECT_TRUE(s.getEndEffectors()[index].name_ == "r_end_effector");
  EXPECT_TRUE(s.getEndEffectors()[index].component_group_ == "r_end_effector");
  EXPECT_TRUE(s.getEndEffectors()[index].parent_link_ == "r_wrist_roll_link");
}

TEST(TestCpp, testReadWrite)
{
  srdf::Model s;
  urdf::ModelInterfaceSharedPtr u = loadURDF(std::string(TEST_RESOURCE_LOCATION) + "/pr2_desc.urdf");
  ASSERT_TRUE(u != nullptr);

  ASSERT_TRUE(s.initFile(*u, std::string(TEST_RESOURCE_LOCATION) + "/pr2_desc.3.srdf"));
  srdf::SRDFWriter writer;
  writer.initModel(*u, s);

  std::string filename = std::string(TEST_RESOURCE_LOCATION) + "/pr2_desc.3-normalized.srdf";
  std::string xml_content;
  std::fstream xml_file(filename.c_str(), std::fstream::in);
  ASSERT_TRUE(xml_file.is_open());
  while (xml_file.good())
  {
    std::string line;
    std::getline(xml_file, line);
    xml_content += (line + "\n");
  }
  xml_content.erase(xml_content.size() - 1, 1);  // remove extra newline
  xml_file.close();

  EXPECT_EQ(xml_content, writer.getSRDFString());
}

int main(int argc, char** argv)
{
  // use the environment locale so that the unit test can be repeated with various locales easily
  setlocale(LC_ALL, "");
  std::cout << "Using locale: " << setlocale(LC_ALL, nullptr) << std::endl;

  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}


text:
<!DOCTYPE html>

    <button class="govuk-button" onclick="window.print()">Print your </button>

You can print your  by pressing CTRL+P (Windows) or CMD+P (mac)


text:
package com.baidu.unbiz.olap.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Olap多表merge的key字段,多表查询时使用, 若未配置,程序默认按多表keys的交集merge
 *
 * @author wangchongjie
 * @fileName OlapMergeKey.java
 * @dateTime 2014-8-26 上午10:27:27
 */
@Inherited
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OlapMergeKey {

}


text:
conventions
===========

The beginning of an idea.

A framework of sorts to get an idea off the ground.


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.evosec.fotilo.library">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application>
        <activity
            android:name="de.evosec.fotilo.library.FotiloActivity"
            android:screenOrientation="landscape"
            android:theme="@style/AppTheme">
            <intent-filter>
                <action android:name="android.media.action.IMAGE_CAPTURE" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.media.action.STILL_IMAGE_CAMERA" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <intent-filter>
                <action android:name="de.evosec.fotilo" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name="de.evosec.fotilo.library.ReviewPicturesActivity"
            android:label="@string/title_activity_review_pictures"
            android:theme="@style/AppTheme" />
    </application>

</manifest>


text:
"use strict";
// DO NOT EDIT THIS FILE, EDIT THE GRUNT TASK NGCONSTANT SETTINGS INSTEAD WHICH GENERATES THIS FILE
angular.module('eventmanagerApp')

.constant('ENV', 'dev')

.constant('VERSION', '0.0.1-SNAPSHOT')

;


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

<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->

<!-- Imported by recipesb/*/build.xml files to share generic targets. -->

<project name="zookeeperbuildrecipes">

  <property name="name" value="${ant.project.name}"/>
  <property name="root" value="${basedir}"/>

  <property name="zk.root" location="${root}/../../../"/>

  <property name="src.dir"  location="${root}/src/java"/>
  <property name="src.test" location="${root}/src/test"/>

  <property name="build.dir" location="${zk.root}/build/recipes/${name}"/>
  <property name="build.classes" location="${build.dir}/classes"/>
  <property name="build.test" location="${build.dir}/test"/>

  <property name="javac.deprecation" value="on"/>
  <property name="javac.debug" value="on"/>

  <property name="build.encoding" value="utf8"/>

  <!-- to be overridden by sub-projects -->
  <target name="check-recipes"/>
  <target name="init-recipes"/>

  <property name="lib.jars.includes" value="lib/*.jar" />
  <property name="lib.jars.excludes" value="" />

  <!-- prior to ant 1.7.1 fileset always fails if dir doesn't exist
       so just point to bin directory and provide settings that exclude
       everything - user can change as appropriate -->
  <property name="additional.lib.dir" value="${zk.root}/bin" />
  <property name="additional.lib.dir.includes" value="**/*.jar" />
  <property name="additional.lib.dir.excludes" value="**/*.jar" />

  <fileset id="lib.jars" dir="${root}">
    <include name="${lib.jars.includes}" />
    <exclude name="${lib.jars.excludes}" />
  </fileset>

  <path id="classpath">
    <pathelement location="${build.classes}"/>
    <!-- allow the user to override (e.g. if there are local versions) -->
    <fileset dir="${additional.lib.dir}">
      <include name="${additional.lib.dir.includes}" />
      <exclude name="${additional.lib.dir.excludes}" />
    </fileset>
    <fileset refid="lib.jars"/>
    <pathelement location="${zk.root}/build/classes"/>
    <fileset dir="${zk.root}/build/lib">
      <include name="**/*.jar" />
    </fileset>
    <fileset dir="${zk.root}/build/test/lib">
      <include name="**/*.jar"/>
    </fileset>
    <fileset dir="${zk.root}/src/java/lib">
      <include name="**/*.jar" />
    </fileset>
  </path>

  <!-- ====================================================== -->
  <!-- Stuff needed by all targets                            -->
  <!-- ====================================================== -->
  <target name="init" depends="check-recipes" unless="skip.recipes">
    <echo message="recipes: ${name}"/>
    <mkdir dir="${build.dir}"/>
    <mkdir dir="${build.classes}"/>
    <mkdir dir="${build.test}"/>
    <antcall target="init-recipes"/>
  </target>

  <!-- ====================================================== -->
  <!-- Compile a recipes files                                -->
  <!-- ====================================================== -->
  <target name="compile" depends="init" unless="skip.contrib">
    <echo message="contrib: ${name}"/>

    <javac
     encoding="${build.encoding}"
     srcdir="${src.dir}"
     includes="**/*.java"
     destdir="${build.classes}"
     debug="${javac.debug}"
     deprecation="${javac.deprecation}">
      <classpath refid="classpath"/>
    </javac>
  </target>

  <!-- ====================================================== -->
  <!-- Make a recipes jar                                     -->
  <!-- ====================================================== -->
  <target name="jar" depends="compile" unless="skip.recipes">
    <echo message="recipes: ${name}"/>
    <jar
      jarfile="${build.dir}/zookeeper-${version}-recipes-${name}.jar"
      basedir="${build.classes}"
    />
  </target>

  <!-- ====================================================== -->
  <!-- Package a recipes files                                -->
  <!-- ====================================================== -->
  <target name="package" depends="jar" unless="skip.recipes">
    <echo message="recipes: ${name}"/>

    <mkdir dir="${dist.dir}${package.share}/recipes/${name}"/>
    <copy todir="${dist.dir}${package.share}/recipes/${name}" includeEmptyDirs="false"
          flatten="true">
      <fileset dir="${build.dir}">
        <include name="zookeeper-${version}-recipes-${name}.jar" />
      </fileset>
    </copy>
  </target>

  <!-- ================================================================== -->
  <!-- Clean.  Delete the build files, and their directories              -->
  <!-- ================================================================== -->
  <target name="clean">
    <echo message="recipes: ${name}"/>
    <delete dir="${build.dir}"/>
  </target>

  <!-- ================================================================== -->
  <!-- Utility features                                                   -->
  <!-- ================================================================== -->

  <target name="checkMainIsAvailable">
    <available classname="org.apache.zookeeper.ZooKeeperMain"
               property="mainIsCompiled">
      <!-- we can't use id=classpath, because available fails if fileset directory
           doesn't exist -->
      <classpath>
        <pathelement location="${zk.root}/build/classes"/>
      </classpath>
    </available>
  </target>

  <target name="checkMainCompiled" unless="mainIsCompiled" depends="checkMainIsAvailable">
    <fail message="ZooKeeper main must first be compiled (toplevel build.xml)"/>
  </target>

</project>


text:
import logging
logging.basicConfig(level=logging.INFO)

from deepy.dataset import MnistDataset, MiniBatches
from deepy.networks import NeuralClassifier
from deepy.layers import Dense, Softmax
from deepy.trainers import MomentumTrainer, LearningRateAnnealer

"""
Build a neural network with 6 dense layers with ReLU.
"""

def run(initializer, model_path):
    model = NeuralClassifier(input_dim=28 * 28)
    for _ in range(6):
        model.stack(Dense(128, 'relu', init=initializer))
    model.stack(Dense(10, 'linear'),
                Softmax())

    trainer = MomentumTrainer(model)

    annealer = LearningRateAnnealer()

    mnist = MiniBatches(MnistDataset(), batch_size=20)

    trainer.run(mnist, epoch_controllers=[annealer])

    model.save_params(model_path)


text:
/**
 This header is private to the Twitter Kit SDK and not exposed for public SDK consumption
 */

#import <Foundation/Foundation.h>

@class TWTRGuestSession;
@class TWTRSession;
@class TWTRTweet;
@class TWTRTweetUrlEntity;
@class TWTRTweetMediaEntity;
@class TWTRUser;

@interface TWTRFixtureLoader : NSObject

+ (TWTRUser *)obamaUser;
+ (TWTRTweet *)obamaTweet;
+ (TWTRTweet *)googleTweet;
+ (TWTRTweet *)gatesTweet;
+ (TWTRTweet *)videoTweet;
+ (TWTRTweet *)tooShortOn6PlusTweet;
+ (TWTRTweet *)tooShortOn6Tweet;
+ (TWTRTweet *)retweetTweet;
+ (TWTRTweet *)manyEntitiesTweet;
+ (TWTRTweet *)cashtagTweet;
+ (TWTRTweet *)vineTweetV13;
+ (TWTRTweet *)extendedTweet;
+ (TWTRTweet *)quoteTweet;
+ (TWTRTweet *)quoteTweetWithPlayableVideo;
+ (TWTRTweet *)quoteTweetInConversation;
+ (TWTRTweet *)punyURLTweet;
+ (TWTRTweet *)sendTweet;
+ (NSArray *)manyTweets;
+ (NSData *)singleTweetData;
+ (NSData *)gatesTweetData;
+ (NSData *)obamaTweetData;
+ (NSData *)retweetTweetData;
+ (NSData *)manyTweetsData;
+ (NSData *)likedTweetData;
+ (NSData *)alreadyLikedTweetData;
+ (NSData *)userResponseData;
+ (NSData *)userWithEmailResponseData;
+ (NSData *)userWithEmptyEmailResponseData;
+ (NSData *)userWithNullEmailResponseData;
+ (NSData *)blackLivesMatterSearchResultData;
+ (NSData *)jackUserTimelineData;
+ (NSData *)oauthDancerCollectionData;
+ (NSData *)twitterSyndicationTeamListTimelineData;
+ (NSData *)sendTweetData;
+ (NSData *)videoData;
+ (TWTRTweetMediaEntity *)obamaTweetMediaEntity;
+ (TWTRTweetMediaEntity *)largeTweetMediaEntity;
+ (NSURL *)videoFileURL;
+ (NSDictionary *)vineCard;
+ (NSDictionary *)collectionAPIResponse;

+ (NSDictionary *)dictFromJSONFile:(NSString *)path;
+ (NSData *)dataFromFile:(NSString *)name ofType:(NSString *)type;

+ (TWTRTweetUrlEntity *)tweetURLEntity;

@end


text:
using namespace arangodb;
using namespace arangodb::application_features;

AgencyCallback::AgencyCallback(AgencyComm& agency, std::string const& key,
                               std::function<bool(VPackSlice const&)> const& cb,
                               bool needsValue, bool needsInitialValue)
    : key(key),
      _agency(agency),
      _cb(cb),
      _needsValue(needsValue),
      _wasSignaled(false) {
  if (_needsValue && needsInitialValue) {
    refetchAndUpdate(true, false);
  }
}

void AgencyCallback::refetchAndUpdate(bool needToAcquireMutex, bool forceCheck) {
  if (!_needsValue) {
    // no need to pass any value to the callback
    if (needToAcquireMutex) {
      CONDITION_LOCKER(locker, _cv);
      executeEmpty();
    } else {
      executeEmpty();
    }
    return;
  }

  AgencyCommResult result = _agency.getValues(key);

  if (!result.successful()) {
    auto& server = ApplicationServer::server();
    if (!server.isStopping()) {
      // only log errors if we are not already shutting down...
      // in case of shutdown this error is somewhat expected
      LOG_TOPIC("fb402", ERR, arangodb::Logger::CLUSTER)
          << "Callback getValues to agency was not successful: " << result.errorCode()
          << " " << result.errorMessage();
    }
    return;
  }

  std::vector<std::string> kv =
      basics::StringUtils::split(AgencyCommManager::path(key), '/');
  kv.erase(std::remove(kv.begin(), kv.end(), ""), kv.end());

  auto newData = std::make_shared<VPackBuilder>();
  newData->add(result.slice()[0].get(kv));

  if (needToAcquireMutex) {
    CONDITION_LOCKER(locker, _cv);
    checkValue(std::move(newData), forceCheck);
  } else {
    checkValue(std::move(newData), forceCheck);
  }
}

void AgencyCallback::checkValue(std::shared_ptr<VPackBuilder> newData, bool forceCheck) {
  // Only called from refetchAndUpdate, we always have the mutex when
  // we get here!
  if (!_lastData || !arangodb::basics::VelocyPackHelper::equal(_lastData->slice(), newData->slice(), false) || forceCheck) {
    LOG_TOPIC("2bd14", DEBUG, Logger::CLUSTER)
        << "AgencyCallback: Got new value " << newData->slice().typeName()
        << " " << newData->toJson() << " forceCheck=" << forceCheck;
    if (execute(newData)) {
      _lastData = newData;
    } else {
      LOG_TOPIC("337dc", DEBUG, Logger::CLUSTER)
          << "Callback was not successful for " << newData->toJson();
    }
  }
}

bool AgencyCallback::executeEmpty() {
  // only called from refetchAndUpdate, we always have the mutex when
  // we get here!
  LOG_TOPIC("96022", DEBUG, Logger::CLUSTER) << "Executing (empty)";
  bool result = _cb(VPackSlice::noneSlice());
  if (result) {
    _wasSignaled = true;
    _cv.signal();
  }
  return result;
}

bool AgencyCallback::execute(std::shared_ptr<VPackBuilder> newData) {
  // only called from refetchAndUpdate, we always have the mutex when
  // we get here!
  LOG_TOPIC("add4e", DEBUG, Logger::CLUSTER) << "Executing";
  bool result = _cb(newData->slice());
  if (result) {
    _wasSignaled = true;
    _cv.signal();
  }
  return result;
}

bool AgencyCallback::executeByCallbackOrTimeout(double maxTimeout) {
  // One needs to acquire the mutex of the condition variable
  // before entering this function!
  auto& server = ApplicationServer::server();
  if (!server.isStopping()) {
    if (_wasSignaled) {
      // ok, we have been signaled already, so there is no need to wait at all
      // directly refetch the values
      _wasSignaled = false;
      LOG_TOPIC("67690", DEBUG, Logger::CLUSTER)
          << "We were signaled already";
      return false;
    }

    // we haven't yet been signaled. so let's wait for a signal or
    // the timeout to occur
    if (!_cv.wait(static_cast<uint64_t>(maxTimeout * 1000000.0))) {
      LOG_TOPIC("1514e", DEBUG, Logger::CLUSTER)
          << "Waiting done and nothing happended. Refetching to be sure";
      // mop: watches have not triggered during our sleep...recheck to be sure
      refetchAndUpdate(false, true);  // Force a check
      return true;
    }
  }
  return false;
}


text:
package com.facebook.buck.lua;

import com.facebook.buck.rules.AddToRuleKey;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildTargetSourcePath;
import com.facebook.buck.rules.BuildableContext;
import com.facebook.buck.rules.CommandTool;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SymlinkTree;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.WriteFileStep;
import com.facebook.buck.util.Escaper;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.io.Resources;

import org.stringtemplate.v4.ST;

import java.io.IOException;
import java.nio.file.Path;

public class LuaInPlaceBinary extends LuaBinary {

  private static final String RUN_INPLACE_RESOURCE = "com/facebook/buck/lua/run_inplace.lua.in";

  // TODO(andrewjcg): Task #8098647: This rule has no steps, so it
  // really doesn't need a rule key.
  //
  // However, Lua tests will never be re-run if the rule key
  // doesn't change, so we use the rule key to force the test runner
  // to re-run the tests if the input changes.
  //
  // We should upate the Lua test rule to account for this.
  @AddToRuleKey
  private final Tool lua;
  @AddToRuleKey
  private final LuaPackageComponents components;
  private final SymlinkTree linkTree;
  @AddToRuleKey
  private final Supplier<String> script;

  public LuaInPlaceBinary(
      BuildRuleParams params,
      SourcePathResolver resolver,
      Tool lua,
      String mainModule,
      LuaPackageComponents components,
      SymlinkTree linkTree,
      String extension) {
    super(params, resolver, lua, mainModule, components, extension);
    this.lua = lua;
    this.components = components;
    this.linkTree = linkTree;
    this.script =
        getScript(
            resolver,
            lua,
            mainModule,
            getProjectFilesystem()
                .resolve(getBinPath())
                .getParent()
                .relativize(linkTree.getRoot()));
  }

  private static String getRunInplaceResource() {
    try {
      return Resources.toString(Resources.getResource(RUN_INPLACE_RESOURCE), Charsets.UTF_8);
    } catch (IOException e) {
      throw Throwables.propagate(e);
    }
  }

  private static Supplier<String> getScript(
      final SourcePathResolver pathResolver,
      final Tool lua,
      final String mainModule,
      final Path relativeLinkTreeRoot) {
    final String relativeLinkTreeRootStr =
        Escaper.escapeAsPythonString(relativeLinkTreeRoot.toString());
    return new Supplier<String>() {
      @Override
      public String get() {
        ImmutableList<String> luaCommand = lua.getCommandPrefix(pathResolver);
        Preconditions.checkArgument(luaCommand.size() == 1);
        return new ST(getRunInplaceResource())
            .add("SHEBANG", luaCommand.get(0))
            .add("LUA", Escaper.escapeAsPythonString(luaCommand.get(0)))
            .add("MAIN_MODULE", Escaper.escapeAsPythonString(mainModule))
            .add("MODULES_DIR", relativeLinkTreeRootStr)
            .render();
      }
    };
  }

  @Override
  public ImmutableList<Step> getBuildSteps(
      BuildContext context,
      BuildableContext buildableContext) {
    Path binPath = getBinPath();
    buildableContext.recordArtifact(binPath);
    return ImmutableList.<Step>of(
        new WriteFileStep(getProjectFilesystem(), script, binPath, /* executable */ true));
  }

  @Override
  public Tool getExecutableCommand() {
    return new CommandTool.Builder(lua)
        .addArg(new BuildTargetSourcePath(getBuildTarget()))
        .addDep(linkTree)
        .addInputs(components.getModules().values())
        .addInputs(components.getNativeLibraries().values())
        .build();
  }

  @Override
  public ImmutableSortedSet<BuildRule> getRuntimeDeps() {
    return ImmutableSortedSet.<BuildRule>naturalOrder()
        .add(linkTree)
        .addAll(getResolver().filterBuildRuleInputs(components.getModules().values()))
        .addAll(getResolver().filterBuildRuleInputs(components.getNativeLibraries().values()))
        .addAll(super.getRuntimeDeps())
        .build();
  }

}


text:
package main

import (
	"context"

	reservation "cloud.google.com/go/bigquery/reservation/apiv1"

	reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := reservation.NewClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &reservationpb.UpdateBiReservationRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1#UpdateBiReservationRequest.
	}
	resp, err := c.UpdateBiReservation(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

// [END bigqueryreservation_v1_generated_ReservationService_UpdateBiReservation_sync]


text:
module.exports = function(app, db) {
  app.use('/api', function(req, res, next) {
    var authKey = req.headers['x-auth-key'];
    req.user = db('users').find({
      authKey: authKey
    });
    next();
  });
};


text:
package org.mvel2.tests.core.res;

public interface MapObject {
  public int getId();
}


text:
  min-width: 800px;
  margin-top: -1px;
  margin-bottom: 17px;
}

#exampleTable1 .progress {
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 0;
  width: 80%;
}

#exampleTable1 .progress-percent {
  display: inline-block;
  width: 20%;
  font-size: 14px;
  text-align: right;
  vertical-align: middle;
  color: #76838f;
}

#exampleTable1 td {
  vertical-align: middle;
}

#exampleTable1 thead th {
  border-bottom-width: 0;
}

#exampleTable1 .example {
  margin-top: 0;
  border: 1px solid #e4eaec;
  border-top: none;
}

#exampleTable1 .example-title {
  border: 1px solid #e4eaec;
  margin-bottom: 0;
  padding: 15px 20px;
}

#exampleReport table {
  min-width: 800px;
  margin-bottom: 0;
}

#exampleReport table td {
  vertical-align: middle;
}

#exampleReport .panel-heading {
  border-bottom: 0;
}

#exampleReport .panel-title {
  border: 1px solid #e4eaec;
  margin-bottom: 0;
  padding: 15px 20px;
}

#exampleReport .panel-actions {
  right: 15px;
}

#exampleReport .example {
  margin-top: 0;
  border: 1px solid #e4eaec;
  border-top: none;
}


text:
module Pione
  module Command
    # `PionePackageUpdate` is a subcommand that updates PIONE package.
    class PionePackageUpdate < BasicCommand
      #
      # informations
      #

      define(:name, "update")
      define(:desc, "Update the package to package database")

      #
      # arguments
      #

      argument(:location) do |item|
        item.type    = :location
        item.desc    = "the package location that you want to update"
        item.missing = "There are no PIONE documents or packages."
      end

      #
      # options
      #

      option CommonOption.color
      option CommonOption.debug

      option(:force) do |item|
        item.type    = :boolean
        item.long    = "--force"
        item.desc    = "Update pacakge information files"
        item.default = true
      end

      #
      # command lifecycle: execution phase
      #

      phase(:execution) do |seq|
        seq << :update
      end

      execution(:update) do |item|
        item.desc = "Update update info files"

        item.process do
          Package::PackageHandler.write_info_files(model[:location], force: model[:force])
        end

        item.exception(Package::InvalidScenario) do |e|
          cmd.abort(e)
        end
      end
    end

    PionePackage.define_subcommand("update", PionePackageUpdate)
  end
end


text:
package org.saiku.datasources.connection;

import java.sql.Connection;
import java.util.Properties;

/**
 * @author pmac
 */
public interface ISaikuConnection {

  public static final String OLAP_DATASOURCE = "OLAP"; //$NON-NLS-1$
  public static final String NAME_KEY = "name"; //$NON-NLS-1$
  public static final String DRIVER_KEY = "driver"; //$NON-NLS-1$
  public static final String URL_KEY = "location"; //$NON-NLS-1$
  public static final String USERNAME_KEY = "username"; //$NON-NLS-1$
  public static final String PASSWORD_KEY = "password"; //$NON-NLS-1$
  public static final String SECURITY_ENABLED_KEY = "security.enabled"; //$NON-NLS-1$
  public static final String SECURITY_TYPE_KEY = "security.type"; //$NON-NLS-1$
  public static final String SECURITY_TYPE_SPRING2MONDRIAN_VALUE = "one2one"; //$NON-NLS-1$
  public static final String SECURITY_TYPE_SPRINGLOOKUPMONDRIAN_VALUE = "lookup"; //$NON-NLS-1$
  public static final String SECURITY_TYPE_PASSTHROUGH_VALUE = "passthrough"; //$NON-NLS-1$
  public static final String SECURITY_LOOKUP_KEY = "security.mapping"; //$NON-NLS-1$
  public static final String DATASOURCE_PROCESSORS = "datasource.processors"; //$NON-NLS-1$
  public static final String CONNECTION_PROCESSORS = "connection.processors"; //$NON-NLS-1$

  public static final String[] KEYS = new String[] { NAME_KEY, DRIVER_KEY, URL_KEY,
    USERNAME_KEY, PASSWORD_KEY, SECURITY_ENABLED_KEY, SECURITY_TYPE_KEY, SECURITY_TYPE_PASSTHROUGH_VALUE,
    SECURITY_TYPE_SPRING2MONDRIAN_VALUE, SECURITY_TYPE_SPRINGLOOKUPMONDRIAN_VALUE, DATASOURCE_PROCESSORS,
    CONNECTION_PROCESSORS };

  public static final String[] DATASOURCES = new String[] { OLAP_DATASOURCE };

  /**
   * Sets the properties to be used when the connection is made. The standard keys for the properties are defined in
   * this interface
   *
   * @param props
   */
  void setProperties( Properties props );

  /**
   * @param props Datasource connection properties
   * @return true if the connection was successful
   */
  boolean connect( Properties props ) throws Exception;

  boolean connect() throws Exception;

  boolean clearCache() throws Exception;

  /**
   * @return true if the connection has been properly initialized.
   */
  public boolean initialized();

  /**
   * returns the type of connection
   *
   * @return
   */
  public String getDatasourceType();

  public Connection getConnection();

  public String getName();

}


text:
namespace lightfields {

namespace {

template <typename T>
T getComponent(const nlohmann::json& json, const std::string& key) {
	auto it = json.find(key);
	if(it == json.end())
		throw std::runtime_error("Error reading Bayer component - missing '" + key + "' value.");
	return it->get<T>();
}

}  // namespace

template <typename T>
Bayer::Value<T>::Value() : r(0), gr(0), gb(0), b(0) {
}

template <typename T>
Bayer::Value<T>::Value(const nlohmann::json& json) {
	b = getComponent<T>(json, "b");
	gb = getComponent<T>(json, "gb");
	gr = getComponent<T>(json, "gr");
	r = getComponent<T>(json, "r");

	max = std::max(std::max(b, gb), std::max(gr, r));
	min = std::min(std::min(b, gb), std::min(gr, r));
}

template <typename T>
T Bayer::Value<T>::operator[](unsigned id) const {
	assert(id < 4 && "Bayer value ID should be in range 0..3");
	return reinterpret_cast<const T*>(this)[id];
}

template <typename T>
template <typename U>
Bayer::Value<T>& Bayer::Value<T>::operator=(const Value<U>& val) {
	b = val.b;
	gb = val.gb;
	gr = val.gr;
	r = val.r;

	max = val.max;
	min = val.min;

	return *this;
}

Bayer::Bayer(const nlohmann::json& meta) {
	m_black = lightfields::Bayer::Value<uint16_t>(meta["image"]["rawDetails"]["pixelFormat"]["black"]);
	m_white = lightfields::Bayer::Value<uint16_t>(meta["image"]["rawDetails"]["pixelFormat"]["white"]);

	const std::string upperLeftPixel = meta["devices"]["sensor"]["mosaic"]["upperLeftPixel"].get<std::string>();

	if(upperLeftPixel == "b") {
		m_mozaic = kBG;
	}
	else if(upperLeftPixel == "gb") {
		m_mozaic = kGB;
	}
	else if(upperLeftPixel == "gr") {
		m_mozaic = kGR;
	}
	else if(upperLeftPixel == "r") {
		m_mozaic = kRG;
	}
	else
		throw std::runtime_error("Unknown 'upperLeftPixel' value '" + upperLeftPixel + "' in image metadata");

	m_width = meta["image"]["width"].get<int>();
	m_height = meta["image"]["height"].get<int>();

	if(meta["devices"]["sensor"]["bitsPerPixel"].get<int>() != 12)
		throw std::runtime_error("Only 12 bits per pixel supported at the moment");

	m_gain = lightfields::Bayer::Value<float>(meta["devices"]["sensor"]["analogGain"]);
}

Bayer::MozaicType Bayer::mozaic() const {
	return m_mozaic;
}

cv::Mat Bayer::decode(const unsigned char* raw) const {
	cv::Mat tmp(m_width, m_height, CV_16UC1);

	tbb::parallel_for(0, m_width * m_height, [&](int i) {
		const uint16_t c1 = raw[i / 2 * 3];
		const uint16_t c2 = raw[i / 2 * 3 + 1];
		const uint16_t c3 = raw[i / 2 * 3 + 2];

		uint16_t val;
		if(i % 2 == 0)
			val = (c1 << 4) + (c2 >> 4);
		else
			val = ((c2 & 0x0f) << 8) + c3;

		tmp.at<uint16_t>(i / m_width, i % m_width) = val;
	});

	return tmp;
}

cv::Mat Bayer::uint16ToFloatMat(const cv::Mat& m, const Flags& f) const {
	cv::Mat result = cv::Mat::zeros(m.rows, m.cols, CV_MAKETYPE(CV_32F, m.channels()));

	tbb::parallel_for(tbb::blocked_range<int>(0, m_width * m_height),
	                  [&result, &m, this, &f](const tbb::blocked_range<int>& range) {
		                  for(int i = range.begin(); i != range.end(); ++i) {
			                  const uint16_t* val = m.ptr<uint16_t>(i / m_width, i % m_width);

			                  for(int chan = 0; chan < m.channels(); ++chan) {
				                  float fval = val[chan];

				                  // for 1-channel pics use bayer; 3-channel use the values directly
				                  unsigned patternId;
				                  if(m.channels() == 1)
					                  patternId = ((i % m_width) % 2 + ((i / m_width) % 2) * 2 + (int)m_mozaic) % 4;
				                  else {
					                  switch(chan) {
						                  case 0:
							                  patternId = 0;  // blue
							                  break;
						                  case 1:
							                  patternId = 1;  // green; assuming GB == GR
							                  break;
						                  case 2:
							                  patternId = 3;  // red
							                  break;
					                  }
				                  }

				                  // adjust based on normalized gain
				                  // This is tricky - gain adjustment introduces "purple edges" in oversatureated
				                  // regions. Needs more work.
				                  if(f & kCorrectGain)
					                  fval *= m_gain[patternId] / m_gain.min;

				                  // make sure the value is in black-white range to avoid negative values
				                  if(fval < m_black[patternId])
					                  fval = m_black[patternId];
				                  if(fval > m_white[patternId])
					                  fval = m_white[patternId];

				                  // normalize to 0..1 for black..white
				                  fval = (fval - m_black[patternId]) / (m_white[patternId] - m_black[patternId]);

				                  // and set the output value
				                  result.ptr<float>(i / m_width, i % m_width)[chan] = fval;
			                  }
		                  }
	                  });

	return result;
}

}  // namespace lightfields


text:
package clockworktest.bullet;

import com.clockwork.app.SimpleApplication;
import com.clockwork.bullet.BulletAppState;
import com.clockwork.bullet.PhysicsSpace;
import com.clockwork.bullet.collision.shapes.MeshCollisionShape;
import com.clockwork.bullet.collision.shapes.PlaneCollisionShape;
import com.clockwork.bullet.collision.shapes.SphereCollisionShape;
import com.clockwork.bullet.control.RigidBodyControl;
import com.clockwork.math.Plane;
import com.clockwork.math.Vector3f;
import com.clockwork.scene.Node;
import com.clockwork.scene.shape.Sphere;

/**
 *
 */
public class TestKinematicAddToPhysicsSpaceIssue extends SimpleApplication {

    public static void main(String[] args) {
        TestKinematicAddToPhysicsSpaceIssue app = new TestKinematicAddToPhysicsSpaceIssue();
        app.start();
    }
    BulletAppState bulletAppState;

    @Override
    public void simpleInitApp() {

        bulletAppState = new BulletAppState();
        stateManager.attach(bulletAppState);
        bulletAppState.getPhysicsSpace().enableDebug(assetManager);
        // Add a physics sphere to the world
        Node physicsSphere = PhysicsTestHelper.createPhysicsTestNode(assetManager, new SphereCollisionShape(1), 1);
        physicsSphere.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(3, 6, 0));
        rootNode.attachChild(physicsSphere);

        //Setting the rigidBody to kinematic before adding it to the physic space
        physicsSphere.getControl(RigidBodyControl.class).setKinematic(true);
        //adding it to the physic space
        getPhysicsSpace().add(physicsSphere);
        //Making it not kinematic again, it should fall under gravity, it doesn't
        physicsSphere.getControl(RigidBodyControl.class).setKinematic(false);

        // Add a physics sphere to the world using the collision shape from sphere one
        Node physicsSphere2 = PhysicsTestHelper.createPhysicsTestNode(assetManager, new SphereCollisionShape(1), 1);
        physicsSphere2.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(5, 6, 0));
        rootNode.attachChild(physicsSphere2);

        //Adding the rigid body to physic space
        getPhysicsSpace().add(physicsSphere2);
        //making it kinematic
        physicsSphere2.getControl(RigidBodyControl.class).setKinematic(false);
        //Making it not kinematic again, it works properly, the rigidbody is affected by grvity.
        physicsSphere2.getControl(RigidBodyControl.class).setKinematic(false);

        // an obstacle mesh, does not move (mass=0)
        Node node2 = PhysicsTestHelper.createPhysicsTestNode(assetManager, new MeshCollisionShape(new Sphere(16, 16, 1.2f)), 0);
        node2.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(2.5f, -4, 0f));
        rootNode.attachChild(node2);
        getPhysicsSpace().add(node2);

        // the floor mesh, does not move (mass=0)
        Node node3 = PhysicsTestHelper.createPhysicsTestNode(assetManager, new PlaneCollisionShape(new Plane(new Vector3f(0, 1, 0), 0)), 0);
        node3.getControl(RigidBodyControl.class).setPhysicsLocation(new Vector3f(0f, -6, 0f));
        rootNode.attachChild(node3);
        getPhysicsSpace().add(node3);

    }

    private PhysicsSpace getPhysicsSpace() {
        return bulletAppState.getPhysicsSpace();
    }
}


text:
package org.apache.lens.server.metrics;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import org.apache.lens.api.query.QueryStatus.Status;
import org.apache.lens.server.BaseLensService;
import org.apache.lens.server.EventServiceImpl;
import org.apache.lens.server.LensServices;
import org.apache.lens.server.api.LensConfConstants;
import org.apache.lens.server.api.events.AsyncEventListener;
import org.apache.lens.server.api.events.LensEventService;
import org.apache.lens.server.api.health.HealthStatus;
import org.apache.lens.server.api.metastore.CubeMetastoreService;
import org.apache.lens.server.api.metrics.*;
import org.apache.lens.server.api.query.QueryExecutionService;
import org.apache.lens.server.api.query.StatusChange;
import org.apache.lens.server.api.session.*;
import org.apache.lens.server.healthcheck.LensServiceHealthCheck;
import org.apache.lens.server.query.QueryExecutionServiceImpl;
import org.apache.lens.server.quota.QuotaServiceImpl;
import org.apache.lens.server.scheduler.AlarmService;
import org.apache.lens.server.scheduler.SchedulerServiceImpl;
import org.apache.lens.server.session.DatabaseResourceService;
import org.apache.lens.server.session.HiveSessionService;

import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hive.service.AbstractService;

import org.glassfish.jersey.server.ContainerRequest;
import org.glassfish.jersey.server.model.ResourceMethod;

import com.codahale.metrics.*;
import com.codahale.metrics.ganglia.GangliaReporter;
import com.codahale.metrics.graphite.Graphite;
import com.codahale.metrics.graphite.GraphiteReporter;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.codahale.metrics.jvm.GarbageCollectorMetricSet;
import com.codahale.metrics.jvm.MemoryUsageGaugeSet;
import com.codahale.metrics.jvm.ThreadStatesGaugeSet;
import info.ganglia.gmetric4j.gmetric.GMetric;
import info.ganglia.gmetric4j.gmetric.GMetric.UDPAddressingMode;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

/**
 * The Class MetricsServiceImpl.
 */
@Slf4j
public class MetricsServiceImpl extends AbstractService implements MetricsService {

  /** The query status listener. */
  private AsyncEventListener<StatusChange> queryStatusListener;

  private AsyncEventListener<SessionEvent> sessionEventListener;

  /** The metric registry. */
  @Getter
  private MetricRegistry metricRegistry;

  /** The reporters. */
  @Getter
  private List<ScheduledReporter> reporters;

  /** The health check. */
  @Getter
  private HealthCheckRegistry healthCheck;

  /** The total opened sessions*/
  private Counter totalOpenedSessions;

  /** The total closed sessions*/
  private Counter totalClosedSessions;

  /** The total expired sessions*/
  private Counter totalExpiredSessions;

  /** The total errors while persisting server state */
  private Counter totalServerStatePersistenceErrors;

  /** The total accepted queries. */
  private Counter totalAcceptedQueries;

  /** The total successful queries. */
  private Counter totalSuccessfulQueries;

  /** The total finished queries. */
  private Counter totalFinishedQueries;

  /** The total failed queries. */
  private Counter totalFailedQueries;

  /** The total cancelled queries. */
  private Counter totalCancelledQueries;

  /** The total errors while loading database resources */
  private Counter totalDatabaseResourceLoadErrors;

  /** The opened sessions */
  private Gauge<Integer> activeSessions;

  /** The queued queries. */
  private Gauge<Long> queuedQueries;

  /** The running queries. */
  private Gauge<Long> runningQueries;

  /** The waiting queries. */
  private Gauge<Long> waitingQueries;

  /** The queries being launched. */
  private Gauge<Long> launchingQueries;

  /** The finished queries. */
  private Gauge<Long> finishedQueries;

  /** All method meters. Factory for creation + caching */
  @Getter
  private MethodMetricsFactory methodMetricsFactory;

  @Getter
  private boolean enableResourceMethodMetering;

  public void setEnableResourceMethodMetering(boolean enableResourceMethodMetering) {
    log.info("setEnableResourceMethodMetering: " + enableResourceMethodMetering);
    this.enableResourceMethodMetering = enableResourceMethodMetering;
    if (!enableResourceMethodMetering) {
      methodMetricsFactory.clear();
    }
  }

  /**
   * The listener interface for receiving asyncQueryStatus events. The class that is interested in processing a
   * asyncQueryStatus event implements this interface, and the object created with that class is registered with a
   * component using the component's addAsyncQueryStatusListener method.
   * When the asyncQueryStatus event occurs, that object's appropriate method is invoked.
   */
  public class AsyncQueryStatusListener extends AsyncEventListener<StatusChange> {

    /*
     * (non-Javadoc)
     *
     * @see org.apache.lens.server.api.events.AsyncEventListener#process(org.apache.lens.server.api.events.LensEvent)
     */
    @Override
    public void process(StatusChange event) {
      processCurrentStatus(event.getCurrentValue());
    }

    /**
     * Process current status.
     *
     * @param currentValue the current value
     */
    protected void processCurrentStatus(Status currentValue) {
      switch (currentValue) {
      case QUEUED:
        totalAcceptedQueries.inc();
        break;
      case CANCELED:
        totalCancelledQueries.inc();
        totalFinishedQueries.inc();
        break;
      case FAILED:
        totalFailedQueries.inc();
        totalFinishedQueries.inc();
        break;
      case SUCCESSFUL:
        totalSuccessfulQueries.inc();
        totalFinishedQueries.inc();
        break;
      default:
        break;
      }
    }
  }

  /**
   * The listener interface for receiving asyncSession events. The class that is interested in processing a
   * asyncSession event implements this interface, and the object created with that class is registered with a
   * component using the component's addAsyncSessionEventListener method.
   * When the asyncSessionEvent event occurs, that object's appropriate method is invoked.
   */
  public class AsyncSessionEventListener extends AsyncEventListener<SessionEvent> {

    /*
     * (non-Javadoc)
     *
     * @see org.apache.lens.server.api.events.AsyncEventListener#process(org.apache.lens.server.api.events.LensEvent)
     */
    @Override
    public void process(SessionEvent event) {
      if (event instanceof SessionOpened) {
        totalOpenedSessions.inc();
      } else if (event instanceof SessionExpired) {
        totalExpiredSessions.inc();
        totalClosedSessions.inc();
      } else if (event instanceof SessionClosed) {
        totalClosedSessions.inc();
      }
    }
  }

  /**
   * Instantiates a new metrics service impl.
   *
   * @param name the name
   */
  public MetricsServiceImpl(String name) {
    super(NAME);
  }

  private QueryExecutionService getQuerySvc() {
    return LensServices.get().getService(QueryExecutionService.NAME);
  }

  /** The time between polls. */
  private static int timeBetweenPolls = 10;

  /*
   * (non-Javadoc)
   *
   * @see org.apache.hive.service.AbstractService#init(org.apache.hadoop.hive.conf.HiveConf)
   */
  @Override
  public synchronized void init(HiveConf hiveConf) {
    queryStatusListener = new AsyncQueryStatusListener();
    sessionEventListener = new AsyncSessionEventListener();
    LensEventService eventService = LensServices.get().getService(LensEventService.NAME);
    eventService.addListenerForType(queryStatusListener, StatusChange.class);
    eventService.addListenerForType(sessionEventListener, SessionEvent.class);
    metricRegistry = LensMetricsRegistry.getStaticRegistry();
    methodMetricsFactory = new MethodMetricsFactory(metricRegistry);
    setEnableResourceMethodMetering(hiveConf.getBoolean(LensConfConstants.ENABLE_RESOURCE_METHOD_METERING, false));
    healthCheck = new HealthCheckRegistry();
    healthCheck.register(CubeMetastoreService.NAME, new LensServiceHealthCheck(CubeMetastoreService.NAME));
    healthCheck.register(HiveSessionService.NAME, new LensServiceHealthCheck(HiveSessionService.NAME));
    healthCheck.register(QueryExecutionServiceImpl.NAME, new LensServiceHealthCheck(QueryExecutionServiceImpl.NAME));
    healthCheck.register(SchedulerServiceImpl.NAME, new LensServiceHealthCheck(SchedulerServiceImpl.NAME));
    healthCheck.register(QuotaServiceImpl.NAME, new LensServiceHealthCheck(QuotaServiceImpl.NAME));
    healthCheck.register(MetricsServiceImpl.NAME, new LensServiceHealthCheck(MetricsServiceImpl.NAME));
    healthCheck.register(EventServiceImpl.NAME, new LensServiceHealthCheck(EventServiceImpl.NAME));
    healthCheck.register(AlarmService.NAME, new LensServiceHealthCheck(AlarmService.NAME));
    initCounters();
    timeBetweenPolls = hiveConf.getInt(LensConfConstants.REPORTING_PERIOD, 10);

    reporters = new ArrayList<ScheduledReporter>();
    if (hiveConf.getBoolean(LensConfConstants.ENABLE_CONSOLE_METRICS, false)) {
      // Start console reporter
      ConsoleReporter reporter = ConsoleReporter.forRegistry(metricRegistry).convertRatesTo(TimeUnit.SECONDS)
        .convertDurationsTo(TimeUnit.MILLISECONDS).build();
      reporters.add(reporter);
    }
    if (hiveConf.getBoolean(LensConfConstants.ENABLE_CSV_METRICS, false)) {
      File f = new File(hiveConf.get(LensConfConstants.CSV_METRICS_DIRECTORY_PATH, "metrics/"));
      f.mkdirs();
      CsvReporter reporter = CsvReporter.forRegistry(metricRegistry)
        .formatFor(Locale.US)
        .convertRatesTo(TimeUnit.SECONDS)
        .convertDurationsTo(TimeUnit.MILLISECONDS)
        .build(f);
      reporters.add(reporter);
    }
    if (hiveConf.getBoolean(LensConfConstants.ENABLE_GANGLIA_METRICS, false)) {
      GMetric ganglia;
      try {
        ganglia = new GMetric(hiveConf.get(LensConfConstants.GANGLIA_SERVERNAME), hiveConf.getInt(
          LensConfConstants.GANGLIA_PORT, LensConfConstants.DEFAULT_GANGLIA_PORT), UDPAddressingMode.MULTICAST, 1);
        GangliaReporter greporter = GangliaReporter.forRegistry(metricRegistry).convertRatesTo(TimeUnit.SECONDS)
          .convertDurationsTo(TimeUnit.MILLISECONDS).build(ganglia);

        reporters.add(greporter);
      } catch (IOException e) {
        log.error("Could not start ganglia reporter", e);
      }
    }
    if (hiveConf.getBoolean(LensConfConstants.ENABLE_GRAPHITE_METRICS, false)) {
      final GraphiteReporter reporter;
      try {
        Graphite graphite = new Graphite(new InetSocketAddress(hiveConf.get(LensConfConstants.GRAPHITE_SERVERNAME),
          hiveConf.getInt(LensConfConstants.GRAPHITE_PORT, LensConfConstants.DEFAULT_GRAPHITE_PORT)));
        reporter = GraphiteReporter.forRegistry(metricRegistry)
          .prefixedWith(InetAddress.getLocalHost().getHostName())
          .convertRatesTo(TimeUnit.SECONDS)
          .convertDurationsTo(TimeUnit.MILLISECONDS)
          .filter(MetricFilter.ALL)
          .build(graphite);
        reporters.add(reporter);
      } catch (UnknownHostException e) {
        log.error("Couldn't get localhost. So couldn't setup graphite reporting", e);
      }
    }
    log.info("Started metrics service");
    super.init(hiveConf);
  }

  /**
   * Inits the counters.
   */
  protected void initCounters() {
    activeSessions = metricRegistry.register(MetricRegistry.name(SessionService.class, ACTIVE_SESSIONS),
      new Gauge<Integer>() {
        @Override
        public Integer getValue() {
          return BaseLensService.getNumberOfSessions();
        }
      });

    queuedQueries = metricRegistry.register(MetricRegistry.name(QueryExecutionService.class, QUEUED_QUERIES),
      new Gauge<Long>() {
        @Override
        public Long getValue() {
          return getQuerySvc().getQueuedQueriesCount();
        }
      });

    runningQueries = metricRegistry.register(MetricRegistry.name(QueryExecutionService.class, RUNNING_QUERIES),
      new Gauge<Long>() {
        @Override
        public Long getValue() {
          return getQuerySvc().getRunningQueriesCount();
        }
      });

    waitingQueries = metricRegistry.register(MetricRegistry.name(QueryExecutionService.class, WAITING_QUERIES),
      new Gauge<Long>() {
        @Override
        public Long getValue() {
          return getQuerySvc().getWaitingQueriesCount();
        }
      });

    launchingQueries = metricRegistry.register(MetricRegistry.name(QueryExecutionService.class, LAUNCHING_QUERIES),
      new Gauge<Long>() {
        @Override
        public Long getValue() {
          return getQuerySvc().getLaunchingQueriesCount();
        }
      });

    finishedQueries = metricRegistry.register(MetricRegistry.name(QueryExecutionService.class, FINISHED_QUERIES),
      new Gauge<Long>() {
        @Override
        public Long getValue() {
          return getQuerySvc().getFinishedQueriesCount();
        }
      });

    totalDatabaseResourceLoadErrors = metricRegistry.counter(MetricRegistry.name(DatabaseResourceService.class,
        DatabaseResourceService.LOAD_RESOURCES_ERRORS));

    totalAcceptedQueries = metricRegistry.counter(MetricRegistry.name(QueryExecutionService.class, "total-"
      + ACCEPTED_QUERIES));

    totalSuccessfulQueries = metricRegistry.counter(MetricRegistry.name(QueryExecutionService.class,
      "total-success-queries"));

    totalFinishedQueries = metricRegistry.counter(MetricRegistry.name(QueryExecutionService.class, "total-"
      + FINISHED_QUERIES));

    totalFailedQueries = metricRegistry.counter(MetricRegistry.name(QueryExecutionService.class, "total-"
      + FAILED_QUERIES));

    totalCancelledQueries = metricRegistry.counter(MetricRegistry.name(QueryExecutionService.class, "total-"
        + CANCELLED_QUERIES));

    totalOpenedSessions = metricRegistry.counter(MetricRegistry.name(QueryExecutionService.class, "total-"
        + OPENED_SESSIONS));

    totalClosedSessions = metricRegistry.counter(MetricRegistry.name(QueryExecutionService.class, "total-"
      + CLOSED_SESSIONS));

    totalExpiredSessions = metricRegistry.counter(MetricRegistry.name(QueryExecutionService.class, "total-"
        + EXPIRED_SESSIONS));

    totalServerStatePersistenceErrors = metricRegistry.counter(MetricRegistry.name(LensServices.class,
        LensServices.SERVER_STATE_PERSISTENCE_ERRORS));

    metricRegistry.register("gc", new GarbageCollectorMetricSet());
    metricRegistry.register("memory", new MemoryUsageGaugeSet());
    metricRegistry.register("threads", new ThreadStatesGaugeSet());
    metricRegistry.register("jvm", new JvmAttributeGaugeSet());
  }

  /**
   * Called by LensRequestListener in start event. marks the method meter, starts a timer, returns timer context
   * returned by the start timer call.
   *
   * @param method           the resource method
   * @param containerRequest container request
   * @return
   * @see org.apache.lens.server.api.metrics.MetricsService#getMethodMetricsContext(
   *org.glassfish.jersey.server.model.ResourceMethod, org.glassfish.jersey.server.ContainerRequest)
   */
  @Override
  public MethodMetricsContext getMethodMetricsContext(ResourceMethod method, ContainerRequest containerRequest) {
    // if method is null then it means no matching resource method was found.
    return enableResourceMethodMetering ? methodMetricsFactory.get(method, containerRequest).newContext()
      : DisabledMethodMetricsContext.getInstance();
  }

  /*
   * (non-Javadoc)
   *
   * @see org.apache.hive.service.AbstractService#start()
   */
  @Override
  public synchronized void start() {
    for (ScheduledReporter reporter : reporters) {
      reporter.start(timeBetweenPolls, TimeUnit.SECONDS);
    }
    super.start();

  }

  /*
   * (non-Javadoc)
   *
   * @see org.apache.hive.service.AbstractService#stop()
   */
  @Override
  public synchronized void stop() {
    // unregister
    LensEventService eventService = LensServices.get().getService(LensEventService.NAME);
    if (eventService != null) {
      eventService.removeListener(queryStatusListener);
    }

    if (queryStatusListener != null) {
      queryStatusListener.stop();
    }

    if (reporters != null) {
      for (ScheduledReporter reporter : reporters) {
        reporter.stop();
      }
    }

    log.info("Stopped metrics service");
    super.stop();
  }

  /*
   * (non-Javadoc)
   *
   * @see org.apache.lens.server.api.metrics.MetricsService#incrCounter(java.lang.String)
   */
  @Override
  public void incrCounter(String counter) {
    incrCounter(MetricsService.class, counter);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.apache.lens.server.api.metrics.MetricsService#decrCounter(java.lang.String)
   */
  @Override
  public void decrCounter(String counter) {
    decrCounter(MetricsService.class, counter);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.apache.lens.server.api.metrics.MetricsService#incrCounter(java.lang.Class, java.lang.String)
   */
  @Override
  public void incrCounter(Class<?> cls, String counter) {
    metricRegistry.counter(MetricRegistry.name(cls, counter)).inc();
  }

  /*
   * (non-Javadoc)
   *
   * @see org.apache.lens.server.api.metrics.MetricsService#decrCounter(java.lang.Class, java.lang.String)
   */
  @Override
  public void decrCounter(Class<?> cls, String counter) {
    metricRegistry.counter(MetricRegistry.name(cls, counter)).dec();
  }

  /*
   * (non-Javadoc)
   *
   * @see org.apache.lens.server.api.metrics.MetricsService#getCounter(java.lang.String)
   */
  @Override
  public long getCounter(String counter) {
    return getCounter(MetricsService.class, counter);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.apache.lens.server.api.metrics.MetricsService#getCounter(java.lang.Class, java.lang.String)
   */
  @Override
  public long getCounter(Class<?> cls, String counter) {
    return metricRegistry.counter(MetricRegistry.name(cls, counter)).getCount();
  }

  @Override
  public long getTotalDatabaseResourceLoadErrors() {
    return totalDatabaseResourceLoadErrors.getCount();
  }

  @Override
  public long getQueuedQueries() {
    return queuedQueries.getValue();
  }

  @Override
  public long getRunningQueries() {
    return runningQueries.getValue();
  }

  @Override
  public long getWaitingQueries() {
    return waitingQueries.getValue();
  }

  @Override
  public long getFinishedQueries() {
    return finishedQueries.getValue();
  }

  @Override
  public long getTotalAcceptedQueries() {
    return totalAcceptedQueries.getCount();
  }

  @Override
  public long getTotalFinishedQueries() {
    return totalFinishedQueries.getCount();
  }

  @Override
  public long getTotalCancelledQueries() {
    return totalCancelledQueries.getCount();
  }

  @Override
  public long getTotalFailedQueries() {
    return totalFailedQueries.getCount();
  }

  @Override
  public int getActiveSessions() {
    return activeSessions.getValue();
  }

  @Override
  public HealthStatus getHealthStatus() {
    boolean isHealthy = true;
    StringBuilder details = new StringBuilder();

    if (!this.getServiceState().equals(STATE.STARTED)) {
      details.append("Metric service is down.");
      isHealthy = false;
    }

    if (!isHealthy) {
      log.error(details.toString());
    }

    return isHealthy
        ? new HealthStatus(true, "Metric service is healthy.")
        : new HealthStatus(false, details.toString());
  }

  @Override
  public long getTotalOpenedSessions() {
    return totalOpenedSessions.getCount();
  }

  @Override
  public long getTotalClosedSessions() {
    return totalClosedSessions.getCount();
  }

  @Override
  public long getTotalExpiredSessions() {
    return totalExpiredSessions.getCount();
  }

  @Override
  public long getTotalServerStatePersistenceErrors() {
    return totalServerStatePersistenceErrors.getCount();
  }

  /*
     * (non-Javadoc)
     *
     * @see org.apache.lens.server.api.metrics.MetricsService#publishReport()
     */
  @Override
  public void publishReport() {
    if (reporters != null) {
      for (ScheduledReporter reporter : reporters) {
        reporter.report();
      }
    }
  }

  @Override
  public long getTotalSuccessfulQueries() {
    return totalSuccessfulQueries.getCount();
  }

}


text:
<?php

final class ZendX_Dropbox_Endpoints_Revision implements
        ZendX_Dropbox_Interfaces_Endpoint
{

    private $_path = '';

    private $_root = 'sandbox';

    private $_revlimit = 10;

    private $_locale = 'DE';

    /**
     * The path to the file.
     *
     * @param string $path
     * @return ZendX_Dropbox_Endpoints_Revision
     */
    public function setPath ($path)
    {
        $this->_path = (string) $path;
        return $this;
    }

    /**
     * set sandbox or dropbox.
     *
     * @param string $root
     * @return ZendX_Dropbox_Endpoints_Revision
     */
    public function setRoot ($root)
    {
        $this->_root = (string) $root;
        return $this;
    }

    /**
     * set the given locale.
     *
     * @param string $locale
     * @return ZendX_Dropbox_Endpoints_Revision
     */
    public function setLocale ($locale)
    {
        $this->_locale = (string) $locale;
        return $this;
    }

    /**
     * set a revision limit default is 10. Max is 1,000.
     *
     * @param int $revlimit
     * @return ZendX_Dropbox_Endpoints_Revision
     */
    public function setRevisionLimit ($revlimit)
    {
        $this->_revlimit = (int) $revlimit;
        return $this;
    }

    /**
     * return GET-Parameter
     *
     * (non-PHPdoc)
     * @see ZendX_Dropbox_Interfaces_Endpoint::getData()
     * @return array
     */
    public function getData ()
    {
        $data = array(
                'rev_limit' => $this->_revlimit,
                'locale' => $this->_locale
        );

        return $data;
    }

    /**
     * return url params
     *
     * (non-PHPdoc)
     * @see ZendX_Dropbox_Interfaces_Endpoint::getUrl()
     * @return array
     */
    public function getUrl ()
    {
        return array(
                'endpointurl' => 'https://api.dropbox.com/1/revisions/' .
                         $this->_root . '/' . $this->_path,
                        'method' => 'get'
        );
    }
}


text:
package elastic

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"strings"

	"gopkg.in/olivere/elastic.v7/uritemplates"
)

// Flush allows to flush one or more indices. The flush process of an index
// basically frees memory from the index by flushing data to the index
// storage and clearing the internal transaction log.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/indices-flush.html
// for details.
type IndicesFlushService struct {
	client *Client

	pretty     *bool       // pretty format the returned JSON response
	human      *bool       // return human readable values for statistics
	errorTrace *bool       // include the stack trace of returned errors
	filterPath []string    // list of filters used to reduce the response
	headers    http.Header // custom request-level HTTP headers

	index             []string
	force             *bool
	waitIfOngoing     *bool
	ignoreUnavailable *bool
	allowNoIndices    *bool
	expandWildcards   string
}

// NewIndicesFlushService creates a new IndicesFlushService.
func NewIndicesFlushService(client *Client) *IndicesFlushService {
	return &IndicesFlushService{
		client: client,
		index:  make([]string, 0),
	}
}

// Pretty tells Elasticsearch whether to return a formatted JSON response.
func (s *IndicesFlushService) Pretty(pretty bool) *IndicesFlushService {
	s.pretty = &pretty
	return s
}

// Human specifies whether human readable values should be returned in
// the JSON response, e.g. "7.5mb".
func (s *IndicesFlushService) Human(human bool) *IndicesFlushService {
	s.human = &human
	return s
}

// ErrorTrace specifies whether to include the stack trace of returned errors.
func (s *IndicesFlushService) ErrorTrace(errorTrace bool) *IndicesFlushService {
	s.errorTrace = &errorTrace
	return s
}

// FilterPath specifies a list of filters used to reduce the response.
func (s *IndicesFlushService) FilterPath(filterPath ...string) *IndicesFlushService {
	s.filterPath = filterPath
	return s
}

// Header adds a header to the request.
func (s *IndicesFlushService) Header(name string, value string) *IndicesFlushService {
	if s.headers == nil {
		s.headers = http.Header{}
	}
	s.headers.Add(name, value)
	return s
}

// Headers specifies the headers of the request.
func (s *IndicesFlushService) Headers(headers http.Header) *IndicesFlushService {
	s.headers = headers
	return s
}

// Index is a list of index names; use `_all` or empty string for all indices.
func (s *IndicesFlushService) Index(indices ...string) *IndicesFlushService {
	s.index = append(s.index, indices...)
	return s
}

// Force indicates whether a flush should be forced even if it is not
// necessarily needed ie. if no changes will be committed to the index.
// This is useful if transaction log IDs should be incremented even if
// no uncommitted changes are present. (This setting can be considered as internal).
func (s *IndicesFlushService) Force(force bool) *IndicesFlushService {
	s.force = &force
	return s
}

// WaitIfOngoing, if set to true, indicates that the flush operation will
// block until the flush can be executed if another flush operation is
// already executing. The default is false and will cause an exception
// to be thrown on the shard level if another flush operation is already running..
func (s *IndicesFlushService) WaitIfOngoing(waitIfOngoing bool) *IndicesFlushService {
	s.waitIfOngoing = &waitIfOngoing
	return s
}

// IgnoreUnavailable indicates whether specified concrete indices should be
// ignored when unavailable (missing or closed).
func (s *IndicesFlushService) IgnoreUnavailable(ignoreUnavailable bool) *IndicesFlushService {
	s.ignoreUnavailable = &ignoreUnavailable
	return s
}

// AllowNoIndices indicates whether to ignore if a wildcard indices expression
// resolves into no concrete indices. (This includes `_all` string or when
// no indices have been specified).
func (s *IndicesFlushService) AllowNoIndices(allowNoIndices bool) *IndicesFlushService {
	s.allowNoIndices = &allowNoIndices
	return s
}

// ExpandWildcards specifies whether to expand wildcard expression to
// concrete indices that are open, closed or both..
func (s *IndicesFlushService) ExpandWildcards(expandWildcards string) *IndicesFlushService {
	s.expandWildcards = expandWildcards
	return s
}

// buildURL builds the URL for the operation.
func (s *IndicesFlushService) buildURL() (string, url.Values, error) {
	// Build URL
	var err error
	var path string

	if len(s.index) > 0 {
		path, err = uritemplates.Expand("/{index}/_flush", map[string]string{
			"index": strings.Join(s.index, ","),
		})
	} else {
		path = "/_flush"
	}
	if err != nil {
		return "", url.Values{}, err
	}

	// Add query string parameters
	params := url.Values{}
	if v := s.pretty; v != nil {
		params.Set("pretty", fmt.Sprint(*v))
	}
	if v := s.human; v != nil {
		params.Set("human", fmt.Sprint(*v))
	}
	if v := s.errorTrace; v != nil {
		params.Set("error_trace", fmt.Sprint(*v))
	}
	if len(s.filterPath) > 0 {
		params.Set("filter_path", strings.Join(s.filterPath, ","))
	}
	if s.force != nil {
		params.Set("force", fmt.Sprintf("%v", *s.force))
	}
	if s.waitIfOngoing != nil {
		params.Set("wait_if_ongoing", fmt.Sprintf("%v", *s.waitIfOngoing))
	}
	if s.ignoreUnavailable != nil {
		params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable))
	}
	if s.allowNoIndices != nil {
		params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices))
	}
	if s.expandWildcards != "" {
		params.Set("expand_wildcards", s.expandWildcards)
	}
	return path, params, nil
}

// Validate checks if the operation is valid.
func (s *IndicesFlushService) Validate() error {
	return nil
}

// Do executes the service.
func (s *IndicesFlushService) Do(ctx context.Context) (*IndicesFlushResponse, error) {
	// Check pre-conditions
	if err := s.Validate(); err != nil {
		return nil, err
	}

	// Get URL for request
	path, params, err := s.buildURL()
	if err != nil {
		return nil, err
	}

	// Get HTTP response
	res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
		Method:  "POST",
		Path:    path,
		Params:  params,
		Headers: s.headers,
	})
	if err != nil {
		return nil, err
	}

	// Return operation response
	ret := new(IndicesFlushResponse)
	if err := s.client.decoder.Decode(res.Body, ret); err != nil {
		return nil, err
	}
	return ret, nil
}

// -- Result of a flush request.

type IndicesFlushResponse struct {
	Shards *ShardsInfo `json:"_shards"`
}


text:
<!DOCTYPE html>

    <link rel="import" href="x-hr.html">

Element Lifecycle Methods, `polymer-ready` Event

Execute method when element is created, ready, attached, DOM ready, detached or value of attribute changed.

Interact with elements after `polymer-ready` event has been triggered.

<x-hr></x-hr>
<x-hr width="200"></x-hr>


text:
/* global define */

define(['sulfur/util/factory'], function (Factory) {

  'use strict';

  /**
   * @api public
   *
   * @abstract
   *
   * @implement {sulfur/schema/value/simple} .parse({string})
   * @implement {boolean} #eq({sulfur/schema/value/simple})
   * @implememt {string} #toString()
   */
  return Factory.clone({

    isValidLiteral: function (s) {
      try {
        this.parse(s);
      } catch (e) {
        return false;
      }
      return true;
    }

  });

});


text:
import _ from 'underscore';

import { restRequest } from '@girder/core/rest';

var MetadataMixin = {
    _sendMetadata: function (metadata, successCallback, errorCallback, opts) {
        opts = opts || {};
        restRequest({
            url: opts.path ||
                ((this.altUrl || this.resourceName) + `/${this.id}/metadata?allowNull=true`),
            contentType: 'application/json',
            data: JSON.stringify(metadata),
            method: 'PUT',
            error: null
        }).done((resp) => {
            this.set(opts.field || 'meta', resp.meta);
            if (_.isFunction(successCallback)) {
                successCallback();
            }
        }).fail((err) => {
            err.message = err.responseJSON.message;
            if (_.isFunction(errorCallback)) {
                errorCallback(err);
            }
        });
    },

    addMetadata: function (key, value, successCallback, errorCallback, opts) {
        opts = opts || {};
        var datum = {};
        datum[key] = value;
        var meta = this.get(opts.field || 'meta');
        if (meta && _.has(meta, key)) {
            if (_.isFunction(errorCallback)) {
                errorCallback({ message: key + ' is already a metadata key' });
            }
        } else {
            this._sendMetadata(datum, successCallback, errorCallback, opts);
        }
    },

    removeMetadata: function (key, successCallback, errorCallback, opts) {
        if (!_.isArray(key)) {
            key = [key];
        }
        restRequest({
            url: opts.path ||
                ((this.altUrl || this.resourceName) + `/${this.id}/metadata`),
            contentType: 'application/json',
            data: JSON.stringify(key),
            method: 'DELETE',
            error: null
        }).done((resp) => {
            this.set(opts.field || 'meta', resp.meta);
            if (_.isFunction(successCallback)) {
                successCallback();
            }
        }).fail((err) => {
            err.message = err.responseJSON.message;
            if (_.isFunction(errorCallback)) {
                errorCallback(err);
            }
        });
    },

    editMetadata: function (newKey, oldKey, value, successCallback, errorCallback, opts) {
        opts = opts || {};

        if (newKey === oldKey) {
            var datum = {};
            datum[newKey] = value;
            this._sendMetadata(datum, successCallback, errorCallback, opts);
        } else {
            if (_.has(this.get(opts.field || 'meta'), newKey)) {
                if (_.isFunction(errorCallback)) {
                    errorCallback({ message: newKey + ' is already a metadata key' });
                }
            } else {
                var metas = {};
                metas[oldKey] = null;
                metas[newKey] = value;
                this._sendMetadata(metas, successCallback, errorCallback, opts);
            }
        }
    }
};

export default MetadataMixin;


text:
module Trade
  class Admin::TradePromotesController < Admin::BaseController
    before_action :set_trade_promote, only: [:show, :edit, :update, :destroy]

    def index
      @trade_promotes = TradePromote.page(params[:page])
    end

    def new
      @trade_promote = TradePromote.new
    end

    def create
      @trade_promote = TradePromote.new(trade_promote_params)

      unless @trade_promote.save
        render :new, locals: { model: @trade_promote }, status: :unprocessable_entity
      end
    end

    def show
    end

    def edit
    end

    def update
      @trade_promote.assign_attributes(trade_promote_params)

      unless @trade_promote.save
        render :edit, locals: { model: @trade_promote }, status: :unprocessable_entity
      end
    end

    def destroy
      @trade_promote.destroy
    end

    private
    def set_trade_promote
      @trade_promote = TradePromote.find(params[:id])
    end

    def trade_promote_params
      p = params.fetch(:trade_promote, {}).permit(
        :amount,
        :note
      )
      p.merge! edited: true
    end

  end
end


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.teamlet.jartools;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @author David
 * @since 2007-01-12
 *
 *        WhereIsClass 用于查找目录中包含的所有jar是否存在指定的class文件
 *
 *        $Id
 */
public class WhereIsClass {

	private int resultCounts = 0;

	// =================================================================================================================
	/**
	 * Main
	 *
	 * @param args
	 */
	public static void main(String[] args) {

		if (args.length != 2) {
			usage();
		}

		new WhereIsClass(args[0], args[1]);

	}

	public WhereIsClass(String folders, String className) {
		router(folders, className);
	}

	// ===============================================================================================================
	/**
	 *
	 * @param folders
	 * @param className
	 */
	private void router(String folders, String className) {
		searchInMutiplePath(folders, className);
	}

	// ===============================================================================================================
	/**
	 * 在多个路径下查找class
	 *
	 * @param classToFind
	 */
	public void searchInMutiplePath(String folders, String classToFind) {

		String targetFolders[] = folders.split(";");
		for (int i = 0; i < targetFolders.length; i++) {
			findClassInSingleFolder(targetFolders[i], classToFind);
		}
	}

	// ===============================================================================================================
	/**
	 * 在单个路径下查找class
	 *
	 * @param baseDir
	 * @param classToFind
	 */
	public void findClassInSingleFolder(String baseDir, String classToFind) {
		if (!isValidedFolder(baseDir)) {
			log("\n*** Error:invalidated folder\n");
			usage();
		}
		classToFind = classToFind.replaceAll("\\.", "/");

		File rootFolder = new File(baseDir);

		log("Result:");
		log("=======");
		new FindHandler(classToFind).find(rootFolder, 1);
		log("=======");
		log("Path  : " + baseDir);
		log("Target: " + classToFind);
		log("Counts: " + resultCounts + "\n");
		resultCounts = 0;
	}

	// ===============================================================================================================
	/**
	 * 检查输入的文件夹参数是否有效
	 *
	 * @param folder
	 * @return
	 */
	private boolean isValidedFolder(String folder) {
		File dir = new File(folder);
		return dir.isDirectory() && dir.exists();
	}

	// ================================================================================================================
	/**
	 * 输出信息
	 *
	 * @param info
	 */
	protected void log(String info) {
		System.out.println(info);
	}

	// ===============================================================================================================
	/**
	 * 使用方法提示
	 */
	private static void usage() {
		System.out.println("Usage: ");
		System.out.println("java -jar WhereIsClass.jar dir[;dir] className");
		System.exit(1);
	}

	// ===============================================================================================================
	class FindHandler {

		private String className = null;

		public FindHandler(String className) {
			this.className = className;
		}

		// ==========================================================================================================
		/**
		 * 循环遍历目录下的子目录
		 *
		 * @param rootFolder
		 * @param level
		 */
		public void find(File rootFolder, int level) {

			File[] subFiles = rootFolder.listFiles();

			for (int i = 0; i < subFiles.length; i++) {
				if (subFiles[i].isFile()) {
					if (subFiles[i].getName().toLowerCase().indexOf(".jar") != -1) {
						searchInJar(subFiles[i].getAbsolutePath());
					}
				} else {
					find(subFiles[i], level + 1);
				}
			}

		}

		// ===========================================================================================================
		/**
		 * 遍历jar内文件名称
		 *
		 * @param jarFile
		 */
		private void searchInJar(String jarFile) {
			try {
				FileInputStream fInStream = new FileInputStream(jarFile);
				BufferedInputStream bInStream = new BufferedInputStream(fInStream);
				ZipInputStream zInStream = new ZipInputStream(bInStream);
				ZipEntry zipEntry = null;

				while ((zipEntry = zInStream.getNextEntry()) != null) {
					if (zipEntry.isDirectory()) {
						continue;
					}

					if (zipEntry.getName().indexOf(className) != -1) {
						log(zipEntry.getName() + "   ->   (" + jarFile + ")");
						resultCounts++;
					}
				}
				zInStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	// ===============================================================================================================
}


text:
<title>Nils Mustelin: Bland miljarder stjärnor</title>

             Bland
miljarder
stjärnor

              Hästhuvudnebulosan är
ett enormt mörkt stoftmoln
som kan ses i Orions bälte

         Raketenfahrt av Max Valier, en klassiker från 1929

         Wernher v. Brauns första förslag till en bemannad resa till Mars (1952)

         Arthur C. Clarkes
Interplanetary Flight,
          boken som fick mig att avbryta arbetet på min egen bok...

          "Vägen till stjärnorna"

Under pojkåren läste jag allt jag kom över om astronomi och rymdfart. I hemmets
       bibliotek fanns det gott om böcker som vältaligt och med fantasieggande bilder
       skildrade världsrymdens mysterier, och på Stadsbiblioteket i Åbo hittade jag ännu mera.
       För mina blygsamma veckopengar köpte jag gärna pojkböcker som beskrev den första resan
       till Mars eller Venus – ofta med hjälp av en rymdfarkost som byggdes i hemlighet av
       någon genial uppfinnare och en handfull medhjälpare.

När jag småningom i skolan lärde mig tillräckligt tyska, upptäckte jag att
       det speciellt på 1920-talet hade skrivits böcker som seriöst och övertygande hävdade,
       att det bara var en tidsfråga när människan med hjälp av raketdrivna farkoster skulle
       kunna färdas ut i rymden och besöka andra planeter.

Under de första studieåren vaknade sedan hos mig en hisnande tanke: jag skulle själv
       skriva en saklig men fängslande bok om människans kommande erövring av världsrymden.
       Full av entusiasm började jag planera boken. Vägen till stjärnorna skulle den heta
       och det dröjde inte länge förrän jag hade hela uppläggningen i stort sett klar för mig,
       inklusive vad de sammanlagt elva kapitlen skulle heta.

Jag skrev det ena avsnittet efter det andra – men det blev inte vad jag ville. Jag
       försökte frambesvärja kosmiska visioner och svindlande perspektiv, men själva den
       litterära framställningsförmågan svek mig. Det blev banaliteter och platityder som efter
       hand hamnade i papperskorgen.

Den definitiva dödsstöten fick projektet när jag av en händelse, i en boklåda i Stockholm,
       fann en bok av en då alldeles okänd författare vid namn Arthur C. Clarke. Boken hette
       Interplanetary Flight – och när jag läste den insåg jag att det jag hade velat
       skriva redan var skrivet, med en kraft och en klarhet och en förmåga att trollbinda läsaren,
       som jag aldrig ens kommit i närheten av. (I ännu högre grad gällde detta Clarkes följande bok
       om rymdfart, The Exploration of Space, som vände sig till en betydligt vidare
       läsekrets än den föregående.)

Vägen till stjärnorna blev oskriven – men några skärvor togs till vara och
       omarbetades till ett radioprogram med samma namn, som sändes i två avsnitt (30.12.1953
       och 6.1.1954). Som uppläsare av citat medverkade några av mina studiekamrater, bland dem
       Rolf Kullberg, Anders G. Lindqvist och Ralf Långbacka, som alla senare har
       gjort sig kända i helt andra sammanhang.

        Ett modernt radioteleskop med
40 meters reflektor

        Galaxen M101
har samma spiralstruktur som
vår egen galax Vintergatan

           Stanley L. Miller, som visade att organiska molekyler
           kan ha uppkommit spontant på den unga jorden

        "Grannar i Vintergatan"

Under de närmast följande åren, medan de första satelliterna sändes upp i kretslopp
        kring jorden och rymdforskningen tog sina första stapplande steg, skrev jag då och då
        tidningsartiklar eller smärre radioprogram med anknytning till rymden. Men de akademiska
        studierna tog allt mera av min tid, som jag dessutom till stor del tillbringade
        utomlands. Världsrymden hamnade ohjälpligt i skuggan av det krävande arbetet att
        försörja en växande familj och samtidigt åstadkomma en doktorsavhandling om
        impulsmomentens kopplingar i tvåatomiga molekyler.

Först i mitten av 1960-talet började jag åter känna suget från rymden allt starkare.
        Men nu var det inte längre vårt solsystem och dess planeter som stod i förgrunden för
        mitt intresse. Det hade skett mycket inom astronomin sedan mina pojkår. Radioastronomin
        hade utvecklats till ett kraftfullt verktyg för utforskning av den ofattbart stora
        arkipelag av stjärnor som vi kallar Vintergatan. Radioteleskopen hade blivit så känsliga
        att man med dem skulle kunna uppfånga radiosignaler utsända av främmande civilisationer
        på vår egen teknologiska nivå. Astronomerna hade funnit allt starkare stöd för
        uppfattningen att en stor del av stjärnorna runt omkring oss i Vintergatan troligen är
        försedda med egna planetsystem.

Sist men inte minst hade nobelpristagaren i kemi, Harold C. Urey, och hans elev
        Stanley L. Miller på 1950-talet genomfört en intressant serie experiment som visade
        att rätt komplicerade organiska molekyler, de levande varelsernas byggstenar, kan ha
        uppstått spontant här på jorden under de förhållanden som rådde på vår planet i dess
        tidiga barndom för fyra miljarder år sedan.

Allt detta återuppväckte hos mig de visioner om liv i universum som en gång i tiden
        hade drabbat mig vid läsningen av Bebodda världar och andra fantasieggande
        böcker av den franska astronomen och författaren Camille Flammarion.

Det blev åter tidningsartiklar och radioprogram, nu med fokusering på fakta och
        spekulationer om livets utbredning i Universum och våra möjligheter att få kontakt och
        kommunicera med utomjordiska intelligenta varelser, om sådana finns. En vändpunkt blev
        ett 45 minuters radioprogram med titeln Grannar i Vintergatan,
        som sändes ut på Nyårsdagen 1966 med bl.a. Lars Svedberg som uppläsare av citat.

Efter detta fanns det inte längre någon återvändo. Mitt förra bokprojekt, tolv år
        tidigare, hade krympt ihop till ett radioprogram – men nu kände jag att Grannar i
        Vintergatan hade öppnat så många fascinerande perspektiv, att jag helt enkelt
        måste fortsätta och bygga ut detta program till en bok.

Jag hade räknat med att använda några månader av min fritid, på sin höjd ett år, för
        att skriva boken. Om jag hade anat att det skulle ta mig över tio år, skulle jag
        troligen ha avstått från hela projektet...

       En dröm från mina pojkår, att en gång få se jorden utifrån, som en planet
          i rymden, uppfylldes åtminstone indirekt genom de bilder som togs på de första
          månfärderna
(NASA)

           Camille Flammarion
1842-1925

        "Liv bland miljarder stjärnor"

En snöslaskig vinterdag i början av år 1977, då jag var på tjänsteresa i Stockholm,
        vandrade jag upp till Bokförlaget Natur och Kultur, som jag hade valt ut av den
        anledningen, att så många goda populärvetenskapliga böcker i mitt barndomshem hade
        varit utgivna av Natur och Kultur. Med mig hade jag det nästan färdiga manuskriptet
        till en bok som jag hade kallat Under främmande solar.

Efter några veckor kom svaret. Natur och Kultur ville gärna ge ut boken, men titeln
        måste ändras eftersom den förde tankarna till en exotisk reseskildring snarare än till
        världsrymden...

Jag föreslog Liv bland miljarder stjärnor och lade för säkerhets skull
        till en undertitel som skulle undanröja all osäkerhet om bokens tema:
        Civilisationer i Vintergatan – och därbortom? Förslaget godkändes.

Efter ett år av kompletteringar, omarbetningar och intensivt samarbete med tecknarna
        som gjorde illustrationer kom boken ut i början av år 1978. Inga ord kan beskriva hur det
        kändes att hålla det första exemplaret i min hand, att se resultatet av drygt tio års
        möda förvandlat till en elegant formgiven bok och på nytt läsa de rader av Camille
        Flammarion som jag hade valt till motto för boken, i en tidstypisk översättning:

Och då under sublima nätter med all deras storslagna skönhet dessa
        diamantgnistrande konstellationer rinna upp i öster och på en himmel utan gräns utveckla
        sin hemlighetsfulla ljusglans – bland världarnas omätlighet, på de stjärnbeströdda
        vidderna, under de aflägsna nebulosornas silfverslöjor, i oändlighetens outgrundliga
        djup och långt bortom den eviga praktens och härlighetens okända regioner, låtom oss,
        mina bröder, låtom oss alla hälsa: Det är mänskligheterna, våra syskon, som tåga
        förbi däruppe!

            Camille Flammarion: Bebodda världar (slutorden)

Naturligtvis gladde det mig att recensionerna var positiva, både i Sverige och i Finland,
        och att boken hade god åtgång. Som en speciell hedersbevisning upplevde jag det faktum,
        att min bok nästan genast togs i användning i undervisningen vid universiten i Lund,
        Stockholm och Uppsala.

Snart blev det också aktuellt med översättningar till andra nordiska språk. En dansk
        utgåva kom redan 1979 (Samlerens Forlag) och en finsk 1980 (WSOY). År 1980 kom också
        en ny reviderad upplaga på svenska, och 1982 följde den norska utgåvan (Tanum og Nordli).

De olika upplagorna är inte identiska. Eftersom det hände mycket inom rymdforskningen
        i slutet av 1970-talet och början av 1980-talet, försökte jag beakta de nyaste rönen var
        gång en ny utgåva blev aktuell.

När den finska utgåvan hade kommit ut 1980, fick jag till min glädje följande år
        statens informationspris.

        Av tekniska skäl har jag delat upp denna sida på två sidor.
Sida 2 är inte
        nämnd i menyn, men du kan komma till den genom att klicka på ikonen till vänster.

             Denna sida har senast ändrats 6.9.2002

Kommentarer och frågor är välkomna per e-post:
               nils.mustelin@dlc.fi