text:
class Team < ApplicationRecord
  include Warehousable

  validates :name, uniqueness: { scope: :type }
  validate :valid_role
  validate :deletion_validation

  DEACTIVATED_LABEL = '[DEACTIVATED]'.freeze

  acts_as_tree

  has_paper_trail ignore: [:created_at, :updated_at]

  has_many :user_roles, class_name: 'TeamsUsersRole'
  has_many :users, -> { order(:full_name) }, through: :user_roles
  has_many :properties, class_name: 'TeamProperty', dependent: :delete_all
  has_many :areas, -> { area }, class_name: 'TeamProperty'

  # This can be eager loaded using includes
  has_one :team_leader,
          -> { lead },
          class_name: TeamProperty.to_s

  has_one :old_team, class_name: 'Team', foreign_key: :moved_to_unit_id
  belongs_to :moved_to_unit, class_name: 'Team', optional: true

  scope :with_user, ->(user) {
    includes(:user_roles)
      .where(teams_users_roles: { user_id: user.id })
      .order(:name)
  }

  scope :active, -> { where(deleted_at: nil)}

  def self.hierarchy
    result_set = []
    BusinessGroup.order(:name).each do |bg|
      result_set << bg
      bg.directorates.order(:name).each do |dir|
        result_set << dir
        dir.business_units.order(:name).each { |bu| result_set << bu }
      end
    end
    result_set
  end

  def valid_role
    if role.present?
      errors.add(:role, :present)
    end
  end

  def can_allocate?(correspondence_type)
    properties.where(
      key: 'can_allocate',
      value: correspondence_type.abbreviation
    ).any?
  end

  def enable_allocation(correspondence_type)
    unless can_allocate?(correspondence_type)
      properties << TeamProperty.create!(key: 'can_allocate',
                                         value: correspondence_type.abbreviation)
    end
  end

  def disable_allocation(correspondence_type)
    properties.where(
      key: 'can_allocate',
      value: correspondence_type.abbreviation
    ).delete_all
  end

  def self.allocatable(correspondence_type)
    Team.joins(:properties).where(team_properties: {
                                    key: 'can_allocate',
                                    value: correspondence_type.abbreviation
                                  })
  end

  def policy_class
    TeamPolicy
  end

  def pretty_type
    I18n.t("team_types.#{type.underscore}")
  end

  def pretty_team_lead_title
    I18n.t("team_lead_types.#{type.underscore}")
  end

  def team_leader_name
    team_leader&.value || ''
  end

  def team_lead
    properties.lead.singular_or_nil&.value || ''
  end

  def team_lead=(name)
    if properties.lead.exists?
      properties.lead.singular.update value: name
    else
      TeamProperty.new(key: 'lead', value: name).tap do |property|
        properties << property
      end
    end
  end

  def active_users
    users.where(deleted_at: nil)
  end

  def has_active_children?
    children.active.any?
  end

  def active?
    deleted_at.nil?
  end

  def inactive?
    !active?
  end

  # @note (Mohammed Seedat 2019-04-03) Original Team Name workaround
  #   Team table has no way of storing historical data. On deactivation, the
  #   Team's name is changed - name therefore stores deletion information.
  #   To retrieve the Team name without any of the  deactivation information
  #   we require this string replacement workaround.
  #
  # @todo (Mohammed Seedat 2019-04-03) Investigate implementation further
  #
  # @example '[DEACTIVATED] The Avengers @(2019-01-02 12:32)'
  def original_team_name
    name.remove(DEACTIVATED_LABEL, /@\((.)*\)/).strip
  end

  def deactivated
    deleted_at&.strftime("%d/%m/%Y") || ''
  end

  def moved
    moved_to_unit&.parent&.name || ''
  end

  private

  # This method applies to Business Groups and Directorates only.
  # It is overridden in BusinessUnit.
  def deletion_validation
    if deleted_at.present? && has_active_children?
      errors.add(:base, 'Unable to delete team: team still has active children')
    end
  end
end


text:
COMPOSER=`which composer`
MUST_INSTALL=$?

if [ "$MUST_INSTALL" != 0 ]; then
    EXPECTED_SIGNATURE=$(wget https://composer.github.io/installer.sig -O - -q)
    php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
    ACTUAL_SIGNATURE=$(php -r "echo hash_file('SHA384', 'composer-setup.php');")

    if [ "$EXPECTED_SIGNATURE" = "$ACTUAL_SIGNATURE" ]
    then
        php composer-setup.php --install-dir=.
        rm composer-setup.php
        COMPOSER="/composer.phar";
    else
        >&2 echo 'ERROR: Invalid installer signature'
        rm composer-setup.php
        exit 1
    fi
fi

su -c "cd /flight-spy/ && $COMPOSER install --no-plugins --no-scripts --optimize-autoloader --no-suggest --no-interaction --no-dev --prefer-dist"

redpajama_set_name: RedPajamaGithub


text:
package org.jvnet.sorcerer;

import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.util.TreePath;
import org.jvnet.sorcerer.util.IOUtil;
import org.jvnet.sorcerer.util.JsonWriter;

import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;

/**
 * HTML generator that produces sorcerer report in
 * javadoc-like 3 frame layout.
 *
 *

 * This is the most simple way to use a sorcerer. Just
 * call the {@link #generateAll(File)} method to generate
 * the complete files into the output directory.
 *
 *

 * Most of the generated HTML files use hyphen in the file name,
 * to make sure it doesn't collide with HTMLs generated from classes.
 *
 * @author Kohsuke Kawaguchi
 */
public class FrameSetGenerator extends AbstractWriter {

    private String title = "Sorcerer report";

    /**
     * Reference to the unnamed package.
     */
    private final PackageElement unnamed;

    public final UUID id = UUID.randomUUID();

    public FrameSetGenerator(ParsedSourceSet pss) {
        super(pss);
        this.unnamed = pss.getElements().getPackageElement("");
    }

    /**
     * Sets the window title.
     */
    public void setTitle(String title) {
        this.title = title;
    }

    private String getPackagePath(PackageElement pe) {
        if(pe.equals(unnamed))
            return ".";
        else
            return pe.getQualifiedName().toString().replace('.','/');
    }

    /**
     * Generates all the HTML files into the given directory.
     */
    public void generateAll(File outDir) throws IOException {

        for (CompilationUnitTree cu : pss.getCompilationUnits()) {
            AstGenerator gen = new AstGenerator(pss,id,cu);
            gen.write(outDir);
        }

        generateIndex(new PrintWriter(open(outDir,"index.html")));
        generatePackageListJs(new PrintWriter(openDefault(outDir,"package-list.js")));
        generatePackageList(new PrintWriter(openDefault(outDir,"package-list")));

        for (PackageElement p : pss.getPackageElement()) {
            File dir = new File(outDir,getPackagePath(p));
            dir.mkdirs();

            generateClassListJs(p,new PrintWriter(openDefault(dir,"class-list.js")));
        }

        System.out.println("Generating usage index");
        {// "find usage" index
            generateProjectUsageJs(new PrintWriter(openDefault(outDir,"project-usage.js")));

            ClassUsageJsWriter cujw = new ClassUsageJsWriter(pss);

            for( ParsedType pt : pss.getParsedTypes() ) {
                if(pt.getReferers().length==0)
                    continue;
                // local types can be only referenced from the same compilation unit.
                if(pt.isLocal())
                    continue;
                if(pt.isInvalid())
                    continue;

                File out = new File(outDir, cujw.getRelativePath(pt));
                assert out.getParentFile() != null : out;
                out.getParentFile().mkdirs();

                cujw.write(pt,new PrintWriter(out));
            }
        }

        // resource files
        System.out.println("Generating static resource files");
        // frameset specific resources
        for (String res : RESOURCES) {
            File o = new File(outDir, res);
            o.getParentFile().mkdirs();
            IOUtil.copy(res,o);
        }
    }

    public void generateIndex(PrintWriter w) throws IOException {
        generateWithMacro("index.html", w, "title", title);
    }

    private void generateWithMacro(String resourceName, PrintWriter w, String key, String value) throws IOException {
        BufferedReader r = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(resourceName)));
        String line;

        while((line=r.readLine())!=null) {
            line = line.replaceAll("\\$\\{"+ key +"\\}", value);
            w.println(line);
        }

        r.close();
        w.close();
    }

    public void generatePackageListJs(PrintWriter w) throws IOException {
        PackageSet packageNames = new PackageSet();
        for (PackageElement pe : pss.getPackageElement())
            packageNames.add(pe.getQualifiedName().toString());
        packageNames.sort();

        try {
            w.println("setProject(");
            JsonWriter jw = new JsonWriter(w);
            jw.startArray();
            {// write self
                jw.startObject();
                jw.property("name","Project"); // TODO
                jw.property("id",id.toString());
                jw.propertyUnquoted("linker","linker.self");
                jw.property("packages",packageNames);
                jw.endObject();
            }
            // write dependencies
            for (Dependency dep : pss.getDependencies())
                jw.object(dep);
            jw.endArray();
            w.println(");");
        } finally {
            w.close();
        }
    }

    /**
     * Generates javadoc compatible <tt>package-list</tt>
     */
    public void generatePackageList(PrintWriter w) throws IOException {
        try {
            for (PackageElement pe : pss.getPackageElement()) {
                w.println(pe.getQualifiedName());
            }
        } finally {
            w.close();
        }
    }

    public void generateClassListJs(PackageElement p, PrintWriter w) throws IOException {
        try {
            w.printf("setClassList(\"%s\",",p.getQualifiedName());
            JsonWriter jw = new JsonWriter(w);
            jw.object(id.toString());
            jw.startArray();
            for (TypeElement t : pss.getClassElements(p)) {
                ClassTree ct = pss.getTrees().getTree(t);
                if(ct ==null)   continue;   // not a part of the compilation unit
                TreePath tp = pss.getTreePathByClass(ct);

                String sourceName = tp.getCompilationUnit().getSourceFile().getName();
                sourceName = sourceName.substring(sourceName.lastIndexOf('/')+1);
                sourceName = sourceName.substring(sourceName.lastIndexOf('\\')+1);

                jw.startObject();
                jw.property("name",t.getSimpleName());
                jw.property("kind",getKindString(t.getKind()));
                jw.property("file", sourceName);
                jw.property("line", pss.getPositionOf(tp).line);
                jw.property("access",getAccessLevel(t));
                jw.endObject();
            }
            jw.endArray();
            w.println(");");
        } finally {
            w.close();
        }
    }

    /**
     * Writes out <tt>project-usage.js</tt> that lists all classes for which
     * we have usage index.
     */
    public void generateProjectUsageJs(PrintWriter w) throws IOException {
        Map<PackageElement,Set<ParsedType>> pkgs =
            new TreeMap<PackageElement,Set<ParsedType>>(ParsedSourceSet.PACKAGENAME_COMPARATOR);

        for( ParsedType pt : pss.getParsedTypes() ) {
            if(pt.getReferers().length==0)
                continue;

            PackageElement pkg = pss.getElements().getPackageOf(pt.element);
            Set<ParsedType> types = pkgs.get(pkg);
            if(types==null)
                pkgs.put(pkg,types=new HashSet<ParsedType>());

            if(!pt.isLocal())
                types.add(pt);
        }

        w.println("setProjectUsage(");
        JsonWriter js = new JsonWriter(w);
        js.startArray();
        for (Entry<PackageElement,Set<ParsedType>> pkg : pkgs.entrySet()) {
            js.startObject();
            js.property("package",pkg.getKey().getQualifiedName());
            js.key("classes");
            js.startArray();
            String[] names = new String[pkg.getValue().size()];
            int idx=0;
            for (ParsedType pt : pkg.getValue()) {
                names[idx++] = pt.getPackageLocalName();
            }
            Arrays.sort(names);
            for (String n : names) {
                js.object(n);
            }
            js.endArray();
            js.endObject();
        }
        js.endArray();
        w.println(")");
        w.close();
    }

    public static final List<String> RESOURCES = new ArrayList<String>();

    static {
        RESOURCES.addAll(Arrays.asList(
            "sorcerer.js",
            "style.css",
            "menu/menu.css",
            "menu/rightarrow.gif",
            "menu/menu.js",
            "package-tree.html",
            "package-toolbar.html",
            "package-container.html",
            "outline-view.html",
            "outline-toolbar.html",
            "outline-container.html",
            "search-pane.html",
            "search-toolbar.html",
            "search-container.html",
            "source-view.html",
            "eclipse-public-license.url",
            "left-pane.js",
            "left-pane.css",
            "resource-files/yahoo.js",
            "resource-files/dom.js",
            "resource-files/event.js",
            "resource-files/container.js",
            "resource-files/close.gif",
            "resource-files/opentype.gif",
            "resource-files/package.gif",
            "resource-files/library.gif",
            "resource-files/layout-flat.gif",
            "resource-files/layout-hierarchical.gif",
            "resource-files/tree/noicon.css",
            "resource-files/tree/ln.gif",
            "resource-files/tree/loading.gif",
            "resource-files/tree/tn.gif",
            "resource-files/tree/vline.gif",
            "resource-files/tree/treeview.js",
            "resource-files/tree/license.txt"
        ));

        for(String name : new String[]{"lm","lp","tm","tp"}) {
            for( String folder : new String[]{"noicon"}) {
                RESOURCES.add("resource-files/tree/"+folder+"/"+name+".gif");
                RESOURCES.add("resource-files/tree/"+folder+"/"+name+"h.gif");
            }
        }

        for(String name : new String[]{"file","package","prj","type"}) {
            RESOURCES.add("resource-files/search/"+name+"_mode.gif");
        }

        for(String name : new String[]{"alphab_sort_co.gif","fields_co.gif","localtypes_co.gif","public_co.gif","static_co.gif"}) {
            RESOURCES.add("resource-files/outline-filter/"+name);
        }

        String[] modifiers = new String[]{"public", "protected", "private", "default"};

        for( String kind : new String[]{"annotation","interface","enum","class","field","method"} )
            for( String mod : modifiers)
                RESOURCES.add("resource-files/"+kind+'_'+mod+".gif");
    }

}


text:
package com.kzmen.sczxjf.test.download;
import android.util.Log;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadThread extends Thread {
	private static final String TAG = "DownloadThread";
	private File saveFile;
	private URL downUrl;
	private int block;
	/* 下载开始位置 */
	private int threadId = -1;
	private int downLength;
	private boolean finish = false;
	private FileDownloader downloader;

	public DownloadThread(FileDownloader downloader, URL downUrl,
						  File saveFile, int block, int downLength, int threadId) {
		this.downUrl = downUrl;
		this.saveFile = saveFile;
		this.block = block;
		this.downloader = downloader;
		this.threadId = threadId;
		this.downLength = downLength;
	}

	@Override
	public void run() {
		if (downLength < block) {// 未下载完成
			try {
				HttpURLConnection http = (HttpURLConnection) downUrl
						.openConnection();
				http.setConnectTimeout(5 * 1000); // 设置连接超时
				http.setRequestMethod("GET"); // 设置请求方法,这里是"GET"
				// 浏览器可接受的MIME类型
				http.setRequestProperty(
						"Accept",
						"image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
				http.setRequestProperty("Accept-Language", "zh-CN"); // 浏览器所希望的语言种类,当服务器能够提供一种以上的语言版本时要用到
				http.setRequestProperty("Referer", downUrl.toString());// 包含一个URL,用户从该URL代表的页面出发访问当前请求的页面。
				http.setRequestProperty("Charset", "UTF-8"); // 字符集
				int startPos = block * (threadId - 1) + downLength;// 开始位置
				int endPos = block * threadId - 1;// 结束位置
				http.setRequestProperty("Range", "bytes=" + startPos + "-"
						+ endPos);// 设置获取实体数据的范围
				// 浏览器类型,如果Servlet返回的内容与浏览器类型有关则该值非常有用。
				http.setRequestProperty(
						"User-Agent",
						"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
				http.setRequestProperty("Connection", "Keep-Alive"); // 设置为持久连接

				// 得到输入流
				InputStream inStream = http.getInputStream();
				byte[] buffer = new byte[1024];
				int offset = 0;
				print("Thread " + this.threadId
						+ " start download from position " + startPos);
				// 随机访问文件
				RandomAccessFile threadfile = new RandomAccessFile(
						this.saveFile, "rwd");
				// 定位到pos位置
				threadfile.seek(startPos);
				while (!downloader.getExit()
						&& (offset = inStream.read(buffer, 0, 1024)) != -1) {
					// 写入文件
					threadfile.write(buffer, 0, offset);
					downLength += offset; // 累加下载的大小
					downloader.update(this.threadId, downLength); // 更新指定线程下载最后的位置
					downloader.append(offset); // 累加已下载大小
				}
				threadfile.close();
				inStream.close();
				print("Thread " + this.threadId + " download finish");
				this.finish = true;
			} catch (Exception e) {
				this.downLength = -1;
				print("Thread " + this.threadId + ":" + e);
			}
		}
	}

	private static void print(String msg) {
		Log.i(TAG, msg);
	}

	/**
	 * 下载是否完成
	 *
	 * @return
	 */
	public boolean isFinish() {
		return finish;
	}

	/**
	 * 已经下载的内容大小
	 *
	 * @return 如果返回值为-1,代表下载失败
	 */
	public long getDownLength() {
		return downLength;
	}
}


text:
namespace ph
{

TransformedIntersectable::TransformedIntersectable(const Intersectable* intersectable,
                                                   const Transform*     localToWorld,
                                                   const Transform*     worldToLocal) :
	m_intersectable(intersectable),
	m_localToWorld(localToWorld),
	m_worldToLocal(worldToLocal)
{
	PH_ASSERT(intersectable != nullptr);
	PH_ASSERT(localToWorld  != nullptr);
	PH_ASSERT(worldToLocal  != nullptr);
}

TransformedIntersectable::TransformedIntersectable(const TransformedIntersectable& other) :
	m_intersectable(other.m_intersectable),
	m_localToWorld(other.m_localToWorld),
	m_worldToLocal(other.m_worldToLocal)
{}

// FIXME: intersecting routines' time correctness

bool TransformedIntersectable::isIntersecting(const Ray& ray) const
{
	Ray localRay;
	m_worldToLocal->transform(ray, &localRay);
	return m_intersectable->isIntersecting(localRay);
}

bool TransformedIntersectable::isIntersecting(const Ray& ray, HitProbe& probe) const
{
	Ray localRay;
	m_worldToLocal->transform(ray, &localRay);
	if(m_intersectable->isIntersecting(localRay, probe))
	{
		probe.pushIntermediateHit(this);
		return true;
	}
	else
	{
		return false;
	}
}

void TransformedIntersectable::calcIntersectionDetail(const Ray& ray, HitProbe& probe,
                                                      HitDetail* const out_detail) const
{
	probe.popIntermediateHit();

	Ray localRay;
	m_worldToLocal->transform(ray, &localRay);

	HitDetail localDetail;
	probe.getCurrentHit()->calcIntersectionDetail(localRay, probe, &localDetail);

	*out_detail = localDetail;
	m_localToWorld->transform(localDetail.getHitInfo(ECoordSys::WORLD),
	                          &(out_detail->getHitInfo(ECoordSys::WORLD)));
}

// FIXME: this is broken under timed environment
bool TransformedIntersectable::isIntersectingVolumeConservative(const AABB3D& aabb) const
{
	AABB3D localAABB;
	m_worldToLocal->transform(aabb, &localAABB);
	return m_intersectable->isIntersectingVolumeConservative(localAABB);
}

// FIXME: static intersectable do not need to consider time
void TransformedIntersectable::calcAABB(AABB3D* const out_aabb) const
{
	PH_ASSERT(out_aabb);

	AABB3D localAABB, worldAABB;
	m_intersectable->calcAABB(&localAABB);
	m_localToWorld->transform(localAABB, &worldAABB);

	// TODO: modify time interval base on transform properties or aabb size

	// TODO: motions

	//for(size_t i = 0; i < 101; i++)
	//{
	//	Time time;
	//	time.absoluteS = 0;// HACK
	//	time.relativeS = 0;// HACK
	//	time.relativeT = static_cast<real>(1.0 / 100.0 * i);

	//	AABB3D aabb;
	//	m_localToWorld->transform(localAABB, time, &aabb);
	//	worldAABB.unionWith(aabb);
	//}

	*out_aabb = worldAABB;
}

TransformedIntersectable& TransformedIntersectable::operator = (const TransformedIntersectable& rhs)
{
	m_intersectable = rhs.m_intersectable;
	m_localToWorld  = rhs.m_localToWorld;
	m_worldToLocal  = rhs.m_worldToLocal;

	return *this;
}

}// end namespace ph


text:
namespace switches {

extern const char kHstsHosts[];

}  // namespace switches

#endif  // NET_BASE_SWITCHES_H_


text:
package main

import (
	"log"

	"github.com/jason0x43/go-alfred"
)

// TokenCommand is a command
type TokenCommand struct{}

// About returns information about this command
func (c TokenCommand) About() alfred.CommandDef {
	return alfred.CommandDef{
		Keyword:     "token",
		Description: "Manually enter a Toggl API token",
		IsEnabled:   config.APIKey == "",
		Arg: &alfred.ItemArg{
			Keyword: "token",
			Mode:    alfred.ModeDo,
		},
	}
}

// Do runs the command
func (c TokenCommand) Do(data string) (string, error) {
	btn, token, err := workflow.GetInput("API token", "", false)
	if err != nil {
		return "", err
	}

	if btn != "Ok" {
		log.Println("User didn't click OK")
		return "", nil
	}
	log.Printf("token: %s", token)

	config.APIKey = token
	err = alfred.SaveJSON(configFile, &config)
	if err != nil {
		return "", err
	}

	workflow.ShowMessage("Token saved!")
	return "", nil
}


text:
layout: post
title: "The Optimality of Posterior Contraction Rate and Priors (2)"
comments: true
---

A few days ago, [Nurzhan Nurushev](http://www.math.vu.nl/en/about-the-department/people/phd-students/nurushevn.aspx) commented on my previous post ["The Optimality of Posterior Contraction Rate and Priors (1)"]({% post_url 2016-07-04-170943%}) at [J ISBA fabook group](https://www.facebook.com/groups/843187915745360/) as follows:

>Shin Minsuk , I think you are partly true. You missed the one case: if you consider gaussian prior(N(mu, sigma^2)) and use empirical Bayes approach wrt mu parameter, then you will avoid over-shrinkage problem. You can read this paper([http://arxiv.org/abs/1511.01803](http://arxiv.org/abs/1511.01803)). In particular, we obtained all consistency results for gaussian prior.
What he is saying is that some empirical Gaussian priors on $$\theta$$ can resolve the issue of using Gaussian tailed priors in the minimax posterior contraction rate.

Recall that the setting is $$y_i\mid \theta \overset{i.i.d.}{\sim}N(\theta,1)$$ for $$i=1,\dots,n$$.

In the previous post, I mentioned that using Gaussian tailed priors could hurt the optimal minimax rate of posterior contraction, e.g., $$\theta \sim N(0,\tau^2)$$. So the resulting supremum of the risk of the posterior mean can be expressed as

$$
\sup_{\theta_0} E_{\theta_0}[\{\theta_0 - E(\theta\mid y)\}^2] = \infty
$$

Instead, we can consider an empirical prior such as $$\theta \sim N(\bar y, \tau^2)$$, where $$\bar y$$ is the sample mean. This is not full Bayes prior, because the prior depends on the data. Then, the resulting risk is

$$
\begin{eqnarray*}
\sup_{\theta_0} E_{\theta_0}[\{\theta_0 - E(\theta\mid y)\}^2] = \frac{1}{n}.
\end{eqnarray*}
$$

Actually, their model in [the paper](http://arxiv.org/abs/1511.01803) is Gaussian sequence models that can be defined as
$$
\begin{eqnarray*}
y_i\mid\theta_i \sim N(\theta_i,\sigma^2),
\end{eqnarray*}
$$
for $$i=1,\dots,n$$. Then, the prior that they consider is $$\theta\sim N(y_i,\sigma^2\tau^2)$$ for $$i\in {\bf k}$$ for some model $${\bf k}$$; $$\theta_i = 0$$ for $$i\not\in {\bf k}$$. Because the prior mean is the data itself, it could avoid *over-shrinkage* effects. It is not only simple, but also interesting.


text:
package com.example.bigquery;

// [START all]
// [START create_client]
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.FieldValue;
import com.google.cloud.bigquery.QueryRequest;
import com.google.cloud.bigquery.QueryResponse;
import com.google.cloud.bigquery.QueryResult;

import java.util.Iterator;
import java.util.List;
// [END create_client]

public class SimpleApp {
  public static void main(String... args) throws Exception {
    // [START create_client]
    BigQuery bigquery = BigQueryOptions.defaultInstance().service();
    // [END create_client]
    // [START run_query]
    QueryRequest queryRequest =
        QueryRequest
            .builder(
                "SELECT "
                    + "APPROX_TOP_COUNT(corpus, 10) as title, "
                    + "COUNT(*) as unique_words "
                    + "FROM `publicdata.samples.shakespeare`;")
            // Use standard SQL syntax for queries.
            // See: https://cloud.google.com/bigquery/sql-reference/
            .useLegacySql(false)
            .build();
    QueryResponse response = bigquery.query(queryRequest);
    // [END run_query]

    // [START print_results]
    QueryResult result = response.result();

    while (result != null) {
      Iterator<List<FieldValue>> iter = result.iterateAll();

      while (iter.hasNext()) {
        List<FieldValue> row = iter.next();
        List<FieldValue> titles = row.get(0).repeatedValue();
        System.out.println("titles:");

        for (FieldValue titleValue : titles) {
          List<FieldValue> titleRecord = titleValue.recordValue();
          String title = titleRecord.get(0).stringValue();
          long uniqueWords = titleRecord.get(1).longValue();
          System.out.printf("\t%s: %d\n", title, uniqueWords);
        }

        long uniqueWords = row.get(1).longValue();
        System.out.printf("total unique words: %d\n", uniqueWords);
      }

      result = result.nextPage();
    }
    // [END print_results]
  }
}
// [END all]


text:
package com.example.bigquery;

// [START bigquery_create_table_partitioned]
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.Field;
import com.google.cloud.bigquery.Schema;
import com.google.cloud.bigquery.StandardSQLTypeName;
import com.google.cloud.bigquery.StandardTableDefinition;
import com.google.cloud.bigquery.TableId;
import com.google.cloud.bigquery.TableInfo;
import com.google.cloud.bigquery.TimePartitioning;

// Sample to create a partition table
public class CreatePartitionedTable {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String datasetName = "MY_DATASET_NAME";
    String tableName = "MY_TABLE_NAME";
    Schema schema =
        Schema.of(
            Field.of("name", StandardSQLTypeName.STRING),
            Field.of("post_abbr", StandardSQLTypeName.STRING),
            Field.of("date", StandardSQLTypeName.DATE));
    createPartitionedTable(datasetName, tableName, schema);
  }

  public static void createPartitionedTable(String datasetName, String tableName, Schema schema) {
    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      TableId tableId = TableId.of(datasetName, tableName);

      TimePartitioning partitioning =
          TimePartitioning.newBuilder(TimePartitioning.Type.DAY)
              .setField("date") //  name of column to use for partitioning
              .setExpirationMs(7776000000L) // 90 days
              .build();

      StandardTableDefinition tableDefinition =
          StandardTableDefinition.newBuilder()
              .setSchema(schema)
              .setTimePartitioning(partitioning)
              .build();
      TableInfo tableInfo = TableInfo.newBuilder(tableId, tableDefinition).build();

      bigquery.create(tableInfo);
      System.out.println("Partitioned table created successfully");
    } catch (BigQueryException e) {
      System.out.println("Partitioned table was not created. \n" + e.toString());
    }
  }
}
// [END bigquery_create_table_partitioned]


text:
package prometheus

import (
	"errors"
	"net/http"
	"testing"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	dto "github.com/prometheus/client_model/go"

	"istio.io/mixer/adapter/prometheus/config"
	"istio.io/mixer/pkg/adapter"
	"istio.io/mixer/pkg/adapter/test"
)

type testServer struct {
	server

	errOnStart bool
}

func (t testServer) Start(adapter.Env, http.Handler) error {
	if t.errOnStart {
		return errors.New("could not start server")
	}
	return nil
}

var (
	gaugeNoLabels = &adapter.MetricDefinition{
		Name:        "/funky::gauge",
		Description: "funky all the time",
		Kind:        adapter.Gauge,
		Labels:      map[string]adapter.LabelType{},
	}

	histogramNoLabels = &adapter.MetricDefinition{
		Name:        "happy_histogram",
		Description: "fun with buckets",
		Kind:        adapter.Distribution,
		Labels:      map[string]adapter.LabelType{},
		Buckets:     &adapter.ExplicitBuckets{Bounds: []float64{0.5434}},
	}

	counterNoLabels = &adapter.MetricDefinition{
		Name:        "the.counter",
		Description: "count all the tests",
		Kind:        adapter.Counter,
		Labels:      map[string]adapter.LabelType{},
	}

	gaugeNoLabelsNoDesc = &adapter.MetricDefinition{
		Name:   "/funky::gauge.nodesc",
		Kind:   adapter.Gauge,
		Labels: map[string]adapter.LabelType{},
	}

	counterNoLabelsNoDesc = &adapter.MetricDefinition{
		Name:   "the.counter.nodesc",
		Kind:   adapter.Counter,
		Labels: map[string]adapter.LabelType{},
	}

	histogramNoLabelsNoDesc = &adapter.MetricDefinition{
		Name:    "happy_histogram_the_elder",
		Kind:    adapter.Distribution,
		Labels:  map[string]adapter.LabelType{},
		Buckets: &adapter.LinearBuckets{Count: 5, Offset: 45, Width: 12},
	}

	counter = &adapter.MetricDefinition{
		Name:        "special_counter",
		Description: "count all the special tests",
		Kind:        adapter.Counter,
		Labels: map[string]adapter.LabelType{
			"bool":   adapter.Bool,
			"string": adapter.String,
			"email":  adapter.EmailAddress,
		},
	}

	histogram = &adapter.MetricDefinition{
		Name:        "happy_histogram_the_younger",
		Description: "fun with buckets",
		Kind:        adapter.Distribution,
		Buckets:     &adapter.ExponentialBuckets{Scale: .14, GrowthFactor: 2, Count: 198},
		Labels: map[string]adapter.LabelType{
			"bool":   adapter.Bool,
			"string": adapter.String,
			"email":  adapter.EmailAddress,
		},
	}

	unknown = &adapter.MetricDefinition{
		Name:        "unknown",
		Description: "unknown",
		Kind:        adapter.Gauge - 2,
		Labels:      map[string]adapter.LabelType{},
	}

	counterVal = adapter.Value{
		Definition: counter,
		Labels: map[string]interface{}{
			"bool":   true,
			"string": "testing",
			"email":  "test@istio.io",
		},
		MetricValue: float64(45),
	}

	histogramVal = adapter.Value{
		Definition: histogram,
		Labels: map[string]interface{}{
			"bool":   true,
			"string": "testing",
			"email":  "test@istio.io",
		},
		MetricValue: float64(234.23),
	}

	gaugeVal = newGaugeVal(int64(993))
)

func TestInvariants(t *testing.T) {
	test.AdapterInvariants(Register, t)
}

func TestFactory_NewMetricsAspect(t *testing.T) {
	f := newFactory(&testServer{})

	tests := []struct {
		name    string
		metrics []*adapter.MetricDefinition
	}{
		{"No Metrics", []*adapter.MetricDefinition{}},
		{"One Gauge", []*adapter.MetricDefinition{gaugeNoLabels}},
		{"One Counter", []*adapter.MetricDefinition{counterNoLabels}},
		{"Distribution", []*adapter.MetricDefinition{histogramNoLabels}},
		{"Multiple Metrics", []*adapter.MetricDefinition{counterNoLabels, gaugeNoLabels, histogramNoLabels}},
		{"With Labels", []*adapter.MetricDefinition{counter, histogram}},
		{"No Descriptions", []*adapter.MetricDefinition{counterNoLabelsNoDesc, gaugeNoLabelsNoDesc, histogramNoLabelsNoDesc}},
	}

	for _, v := range tests {
		t.Run(v.name, func(t *testing.T) {
			if _, err := f.NewMetricsAspect(test.NewEnv(t), &config.Params{}, makeMetricMap(v.metrics...)); err != nil {
				t.Errorf("NewMetricsAspect() => unexpected error: %v", err)
			}
		})
	}
}

func TestFactory_NewMetricsAspectServerFail(t *testing.T) {
	f := newFactory(&testServer{errOnStart: true})
	if _, err := f.NewMetricsAspect(test.NewEnv(t), &config.Params{}, makeMetricMap()); err == nil {
		t.Error("NewMetricsAspect() => expected error on server startup")
	}
}

func TestNewMetricsAspect_MetricDefinitionErrors(t *testing.T) {
	f := newFactory(&testServer{})
	tests := []struct {
		name    string
		metrics []*adapter.MetricDefinition
	}{
		{"Unknown MetricKind", []*adapter.MetricDefinition{unknown}},
	}
	for _, v := range tests {
		t.Run(v.name, func(t *testing.T) {
			if _, err := f.NewMetricsAspect(test.NewEnv(t), &config.Params{}, makeMetricMap(v.metrics...)); err == nil {
				t.Errorf("Expected error for NewMetricsAspect(%#v)", v.metrics)
			}
		})
	}
}

func TestFactory_NewMetricsAspect_MetricDefinitionConflicts(t *testing.T) {
	f := newFactory(&testServer{})

	gaugeWithLabels := &adapter.MetricDefinition{
		Name:        "/funky::gauge",
		Description: "funky all the time",
		Kind:        adapter.Gauge,
		Labels: map[string]adapter.LabelType{
			"test": adapter.String,
		},
	}

	altCounter := &adapter.MetricDefinition{
		Name:        "special_counter",
		Description: "count all the special tests",
		Kind:        adapter.Counter,
		Labels: map[string]adapter.LabelType{
			"email": adapter.EmailAddress,
		},
	}

	altHistogram := &adapter.MetricDefinition{
		Name:        "happy_histogram",
		Description: "fun with buckets",
		Kind:        adapter.Distribution,
		Labels: map[string]adapter.LabelType{
			"test": adapter.String,
		},
	}

	tests := []struct {
		name    string
		metrics []*adapter.MetricDefinition
	}{
		{"Gauge Definition Conflicts", []*adapter.MetricDefinition{gaugeNoLabels, gaugeWithLabels}},
		{"Counter Definition Conflicts", []*adapter.MetricDefinition{counter, altCounter}},
		{"Histogram Definition Conflicts", []*adapter.MetricDefinition{histogramNoLabels, altHistogram}},
	}

	for _, v := range tests {
		t.Run(v.name, func(t *testing.T) {
			for i, met := range v.metrics {
				_, err := f.NewMetricsAspect(test.NewEnv(t), &config.Params{}, makeMetricMap(met))
				if i > 0 && err == nil {
					t.Error("NewMetricsAspect() => expected error during metrics registration")
				}
			}
		})
	}
}

func TestProm_Close(t *testing.T) {
	f := newFactory(&testServer{})
	prom, _ := f.NewMetricsAspect(test.NewEnv(t), &config.Params{}, makeMetricMap())
	if err := prom.Close(); err != nil {
		t.Errorf("Close() should not have returned an error: %v", err)
	}
}

func TestProm_Record(t *testing.T) {
	duration, _ := time.ParseDuration("386ms")

	f := newFactory(&testServer{})
	tests := []struct {
		name    string
		metrics []*adapter.MetricDefinition
		values  []adapter.Value
	}{
		{"Increment Counter", []*adapter.MetricDefinition{counter}, []adapter.Value{counterVal}},
		{"Histogram Observation", []*adapter.MetricDefinition{histogram}, []adapter.Value{histogramVal}},
		{"Change Gauge", []*adapter.MetricDefinition{gaugeNoLabels}, []adapter.Value{gaugeVal}},
		{"Counter and Gauge", []*adapter.MetricDefinition{counterNoLabels, gaugeNoLabels}, []adapter.Value{gaugeVal, newCounterVal(float64(16))}},
		{"Int64", []*adapter.MetricDefinition{gaugeNoLabels}, []adapter.Value{newGaugeVal(int64(8))}},
		{"Duration", []*adapter.MetricDefinition{gaugeNoLabels}, []adapter.Value{newGaugeVal(duration)}},
		{"String", []*adapter.MetricDefinition{gaugeNoLabels}, []adapter.Value{newGaugeVal("8.243543")}},
	}

	for _, v := range tests {
		t.Run(v.name, func(t *testing.T) {
			aspect, err := f.NewMetricsAspect(test.NewEnv(t), &config.Params{}, makeMetricMap(v.metrics...))
			if err != nil {
				t.Errorf("NewMetricsAspect() => unexpected error: %v", err)
			}
			err = aspect.Record(v.values)
			if err != nil {
				t.Errorf("Record() => unexpected error: %v", err)
			}
			// Check tautological recording of entries.
			pr := aspect.(*prom)
			for _, adapterVal := range v.values {
				c, ok := pr.metrics[adapterVal.Definition.Name]
				if !ok {
					t.Errorf("Record() could not find metric with name %s:", adapterVal.Definition.Name)
					continue
				}

				m := new(dto.Metric)
				switch c.(type) {
				case *prometheus.CounterVec:
					if err := c.(*prometheus.CounterVec).With(promLabels(adapterVal.Labels)).Write(m); err != nil {
						t.Errorf("Error writing metric value to proto: %v", err)
						continue
					}
				case *prometheus.GaugeVec:
					if err := c.(*prometheus.GaugeVec).With(promLabels(adapterVal.Labels)).Write(m); err != nil {
						t.Errorf("Error writing metric value to proto: %v", err)
						continue
					}
				case *prometheus.HistogramVec:
					if err := c.(*prometheus.HistogramVec).With(promLabels(adapterVal.Labels)).Write(m); err != nil {
						t.Errorf("Error writing metric value to proto: %v", err)
						continue
					}
				}

				got := metricValue(m)
				want, err := promValue(adapterVal)
				if err != nil {
					t.Errorf("Record(%s) could not get desired value: %v", adapterVal.Definition.Name, err)
				}
				if got != want {
					t.Errorf("Record(%s) => %f, want %f", adapterVal.Definition.Name, got, want)
				}
			}
		})
	}
}

func TestProm_RecordFailures(t *testing.T) {
	f := newFactory(&testServer{})
	tests := []struct {
		name    string
		metrics []*adapter.MetricDefinition
		values  []adapter.Value
	}{
		{"Not Found", []*adapter.MetricDefinition{counterNoLabels}, []adapter.Value{newGaugeVal(true)}},
		{"Bool", []*adapter.MetricDefinition{gaugeNoLabels}, []adapter.Value{newGaugeVal(true)}},
		{"Text String (Gauge)", []*adapter.MetricDefinition{gaugeNoLabels}, []adapter.Value{newGaugeVal("not a value")}},
		{"Text String (Counter)", []*adapter.MetricDefinition{counterNoLabels}, []adapter.Value{newCounterVal("not a value")}},
		{"Text String (Histogram)", []*adapter.MetricDefinition{histogramNoLabels}, []adapter.Value{newHistogramVal("not a value")}},
	}

	for _, v := range tests {
		t.Run(v.name, func(t *testing.T) {
			aspect, err := f.NewMetricsAspect(test.NewEnv(t), &config.Params{}, makeMetricMap(v.metrics...))
			if err != nil {
				t.Errorf("NewMetricsAspect() => unexpected error: %v", err)
			}
			err = aspect.Record(v.values)
			if err == nil {
				t.Error("Record() - expected error, got none")
			}
		})
	}
}

func metricValue(m *dto.Metric) float64 {
	if c := m.GetCounter(); c != nil {
		return *c.Value
	}
	if c := m.GetGauge(); c != nil {
		return *c.Value
	}
	if c := m.GetHistogram(); c != nil {
		return *c.SampleSum
	}
	if c := m.GetUntyped(); c != nil {
		return *c.Value
	}
	return -1
}

func newGaugeVal(val interface{}) adapter.Value {
	return adapter.Value{
		Definition:  gaugeNoLabels,
		Labels:      map[string]interface{}{},
		MetricValue: val,
	}
}

func newCounterVal(val interface{}) adapter.Value {
	return adapter.Value{
		Definition:  counterNoLabels,
		Labels:      map[string]interface{}{},
		MetricValue: val,
	}
}

func newHistogramVal(val interface{}) adapter.Value {
	return adapter.Value{
		Definition:  histogramNoLabels,
		Labels:      map[string]interface{}{},
		MetricValue: val,
	}
}

func makeMetricMap(metrics ...*adapter.MetricDefinition) map[string]*adapter.MetricDefinition {
	m := make(map[string]*adapter.MetricDefinition, len(metrics))
	for _, metric := range metrics {
		m[metric.Name] = metric
	}

	return m
}


text:
package org.apache.aries.application.runtime.itests;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.CoreOptions.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.apache.aries.application.management.AriesApplication;
import org.apache.aries.application.management.AriesApplicationContext;
import org.apache.aries.application.management.AriesApplicationManager;
import org.apache.aries.itest.AbstractIntegrationTest;
import org.apache.aries.unittest.fixture.ArchiveFixture;
import org.apache.aries.unittest.fixture.ArchiveFixture.ZipFixture;
import org.apache.aries.util.filesystem.FileSystem;
import org.apache.felix.bundlerepository.Repository;
import org.apache.felix.bundlerepository.RepositoryAdmin;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.blueprint.container.BlueprintEvent;
import org.osgi.service.blueprint.container.BlueprintListener;

@RunWith(PaxExam.class)
@ExamReactorStrategy(PerClass.class)
public class MinimumImportsTest extends AbstractIntegrationTest {

    /* Use @Before not @BeforeClass so as to ensure that these resources
     * are created in the paxweb temp directory, and not in the svn tree
     */
    static boolean createdApplications = false;
    static String fake_app_management = "application.management.fake";

    @Before
    public void createApplications() throws Exception {

        if (createdApplications) {
            return;
        }

        // need to fake a application manager to export the service in order to pass the resolving for the client
        // In the real situation, we don't allow customers' bundles to explicitly import the runtime services.
        ZipFixture bundle = ArchiveFixture.newJar().manifest()
                .attribute(Constants.BUNDLE_SYMBOLICNAME, fake_app_management)
                .attribute(Constants.BUNDLE_MANIFESTVERSION, "2")
                .attribute(Constants.BUNDLE_VERSION, "1.0.0").end();

        OutputStream out = new FileOutputStream(fake_app_management + ".jar");
        bundle.writeOut(out);
        out.close();

        ZipFixture testEba = ArchiveFixture.newZip()
                .jar("org.apache.aries.application.itests.minimports.jar")
                .manifest().symbolicName("org.apache.aries.application.itests.minimports")
                .attribute("Bundle-Version", "1.0.0")
                .attribute("Import-Package", "org.apache.aries.application.management")
                .end()
                .binary("org/apache/aries/application/sample/appmgrclient/AppMgrClient.class",
                        MinimumImportsTest.class.getClassLoader().getResourceAsStream("org/apache/aries/application/sample/appmgrclient/AppMgrClient.class"))
                .binary("OSGI-INF/blueprint/app-mgr-client.xml",
                        MinimumImportsTest.class.getClassLoader().getResourceAsStream("app-mgr-client.xml"))
                .end();

        FileOutputStream fout = new FileOutputStream("appmgrclienttest.eba");
        testEba.writeOut(fout);
        fout.close();

        StringBuilder repositoryXML = new StringBuilder();

        BufferedReader reader = new BufferedReader(new InputStreamReader(MinimumImportsTest.class.getResourceAsStream("/basic/fakeAppMgrServiceRepo.xml")));
        String line;

        while ((line = reader.readLine()) != null) {
            repositoryXML.append(line);
            repositoryXML.append("\r\n");
        }

        String repo = repositoryXML.toString().replaceAll("bundle_location", new File(fake_app_management + ".jar").toURI().toString());

        System.out.println(repo);

        FileWriter writer = new FileWriter("repository.xml");
        writer.write(repo);
        writer.close();
        createdApplications = true;
    }

    public static class AppMgrClientBlueprintListener implements BlueprintListener {

        Boolean success = null;

        public void blueprintEvent(BlueprintEvent event) {
            if (event.getBundle().getSymbolicName().equals(
                    "org.apache.aries.application.itests.minimports")) {
                if (event.getType() == event.FAILURE) {
                    success = Boolean.FALSE;
                }
                if (event.getType() == event.CREATED) {
                    success = Boolean.TRUE;
                }
            }
        }
    }

    @Test
    public void testAppUsingAriesApplicationManager() throws Exception {

        // Register a BlueprintListener to listen for the events from the BlueprintContainer for the bundle in the appmgrclienttest.eba

        AppMgrClientBlueprintListener acbl = new AppMgrClientBlueprintListener();
        ServiceRegistration sr = bundleContext.registerService("org.osgi.service.blueprint.container.BlueprintListener", acbl, null);

        AriesApplicationManager manager = context().getService(AriesApplicationManager.class);
        AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("appmgrclienttest.eba")));
        RepositoryAdmin repositoryAdmin = context().getService(RepositoryAdmin.class);

        Repository[] repos = repositoryAdmin.listRepositories();
        for (Repository repo : repos) {
            repositoryAdmin.removeRepository(repo.getURI());
        }

        repositoryAdmin.addRepository(new File("repository.xml").toURI().toURL());

        AriesApplicationContext ctx = manager.install(app);
        ctx.start();

        int sleepfor = 3000;
        while ((acbl.success == null || acbl.success == false) && sleepfor > 0) {
            Thread.sleep(100);
            sleepfor -= 100;
        }
        assertNotNull("Timed out - didn't receive Blueprint CREATED or FAILURE event", acbl.success);
        assertTrue("Received Blueprint FAILURE event", acbl.success);

        ctx.stop();
        manager.uninstall(ctx);
        sr.unregister();
    }

    @Configuration
    public static Option[] configuration() {
        return options(

                // framework / core bundles
                mavenBundle("org.osgi", "org.osgi.core").versionAsInProject(),
                mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(),
                mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject(),

                // Logging
                systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"),

                // Bundles
                junitBundles(),
                mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(),

                // Bundles
                mavenBundle("org.apache.aries.application", "org.apache.aries.application.api").versionAsInProject(),
                mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils").versionAsInProject(),
                mavenBundle("org.apache.aries.application", "org.apache.aries.application.management").versionAsInProject(),
                mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime").versionAsInProject(),
                mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.itest.interfaces").versionAsInProject(),
                mavenBundle("org.apache.aries.application", "org.apache.aries.application.default.local.platform").versionAsInProject(),
                mavenBundle("org.apache.aries", "org.apache.aries.util").versionAsInProject(),
                mavenBundle("org.apache.felix", "org.apache.felix.bundlerepository").versionAsInProject(),
                mavenBundle("org.apache.aries.application", "org.apache.aries.application.resolver.obr").versionAsInProject(),
                mavenBundle("org.apache.aries.application", "org.apache.aries.application.modeller").versionAsInProject(),
                mavenBundle("org.apache.aries.application", "org.apache.aries.application.deployment.management").versionAsInProject(),
                mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint").versionAsInProject(),
                mavenBundle("org.ow2.asm", "asm-all").versionAsInProject(),
                mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy").versionAsInProject());
    }

}


text:
package com.breadwallet.tools.qrcode.xzing.open;

public enum CameraFacing {

  BACK,  // must be value 0!
  FRONT, // must be value 1!

}


text:
package ch.epfl.bbp.uima.ae;

import static ch.epfl.bbp.uima.typesystem.TypeSystem.POS_TAG;
import static ch.epfl.bbp.uima.typesystem.TypeSystem.POS_VERB;
import static ch.epfl.bbp.uima.typesystem.TypeSystem.TOKEN;
import static com.google.common.collect.Sets.newHashSet;
import static org.apache.uima.fit.util.JCasUtil.select;

import java.util.Set;

import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.fit.component.JCasAnnotator_ImplBase;
import org.apache.uima.fit.descriptor.TypeCapability;
import org.apache.uima.jcas.JCas;

import ch.epfl.bbp.uima.types.POSAdverb;
import ch.epfl.bbp.uima.types.POSSkip;
import ch.epfl.bbp.uima.types.POSVerb;
import ch.epfl.bbp.uima.types.POSWh;
import de.julielab.jules.types.Token;

/**
 * Annotate (flags) tokens that have an "uninteresting" POS, like V.., W.., DT
 * or TO, IN, ...
 *
 * @author renaud.richardet@epfl.ch
 */
@TypeCapability(inputs = TOKEN, outputs = { POS_VERB, POS_TAG })
public class SkipSomePosAnnotator extends JCasAnnotator_ImplBase {

    public static final Set<String> POS_SKIP = newHashSet("CC", "DT", "EX", "IN",
    		"LS", "MD", "PDT", "POS", "PRP", "PRP$", "RP",  "TO");

    @Override
    public void process(JCas jCas) throws AnalysisEngineProcessException {

        for (Token t : select(jCas, Token.class)) {

            // filter by POS
            String pos = t.getPos();
            if (pos == null)
                pos = "UNKNOWN";

            // switch
            if (pos.startsWith("V")) { // verb
                (new POSVerb(jCas, t.getBegin(), t.getEnd())).addToIndexes();

            } else if (pos.startsWith("W")) { // Wh-thing
                (new POSWh(jCas, t.getBegin(), t.getEnd())).addToIndexes();

            } else if (pos.startsWith("R")) { // Adverb
               (new POSAdverb(jCas, t.getBegin(), t.getEnd())).addToIndexes();

            } else if (POS_SKIP.contains(pos)) { // to be skipped
                (new POSSkip(jCas, t.getBegin(), t.getEnd())).addToIndexes();
            }
        }
    }
}


text:
var wd = require('wd');
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);
chai.should();
chaiAsPromised.transferPromiseness = wd.transferPromiseness;

module.exports = function () {

  wd.configureHttp({
    timeout: 60000,
    retryDelay: 15000,
    retries: 5
  });

  this.init = function (done, browserName) {
    var browserName = browserName || process.env.BROWSER;
    var desired = {
      browserName: browserName,
      name: 'example with ' + browserName,
      tags: ['tests']
    };

    var username = process.env.SAUCE_USERNAME;
    var accessKey = process.env.SAUCE_ACCESS_KEY;

    var browser = wd.promiseChainRemote("ondemand.saucelabs.com", 80, username, accessKey);
    if (process.env.VERBOSE){
      // optional logging
      browser.on('status', function(info) {
        console.log(info.cyan);
      });
      browser.on('command', function(meth, path, data) {
        console.log(' > ' + meth.yellow, path.grey, data || '');
      });
    }

    browser
      .init(desired)
      .nodeify(done);

    return browser;
  };
  return this

}();

/*
describe('mocha spec examples', function () {
  this.timeout(60000);
  var browser;

  it("should get home page", function (done) {
    browser
      .get("http://wk.com/")
      .title()
      .should.become("Wieden+Kennedy | Full Service Integrated Advertising Agency")
      .nodeify(done);
  });

});
*/


text:
package org.thoughts.on.java.model;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityResult;
import javax.persistence.FieldResult;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.SqlResultSetMapping;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;

@Entity
@SqlResultSetMapping(
		name = "BookMapping",
		entities = @EntityResult(
						entityClass = Book.class,
						fields = {
								@FieldResult(name = "id", column = "bookId"),
								@FieldResult(name = "version", column = "version"),
								@FieldResult(name = "title", column = "title"),
								@FieldResult(name = "publishingDate", column = "publishingDate"),
								@FieldResult(name = "publisher", column = "publisherid")}))
public class Book {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "id", updatable = false, nullable = false)
	private Long id;

	@Version
	private int version;

	private String title;

	@Temporal(TemporalType.DATE)
	private Date publishingDate;

	@ManyToOne
	@JoinColumn(name = "publisherid")
	private Publisher publisher;

	@ManyToMany
	@JoinTable(name = "BookAuthor", joinColumns = { @JoinColumn(name = "bookId", referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "authorId", referencedColumnName = "id") })
	private Set<Author> authors = new HashSet<Author>();

	public Long getId() {
		return this.id;
	}

	public int getVersion() {
		return this.version;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public Date getPublishingDate() {
		return publishingDate;
	}

	public void setPublishingDate(Date publishingDate) {
		this.publishingDate = publishingDate;
	}

	public Publisher getPublisher() {
		return this.publisher;
	}

	public void setPublisher(final Publisher publisher) {
		this.publisher = publisher;
	}

	public Set<Author> getAuthors() {
		return authors;
	}

	public void setAuthors(Set<Author> authors) {
		this.authors = authors;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (!(obj instanceof Book)) {
			return false;
		}
		Book other = (Book) obj;
		if (id != null) {
			if (!id.equals(other.id)) {
				return false;
			}
		}
		return true;
	}

	@Override
	public int hashCode() {
		return 31;
	}

	@Override
	public String toString() {
		String result = getClass().getSimpleName() + " ";
		if (title != null && !title.trim().isEmpty())
			result += "title: " + title;
		return result;
	}
}


text:
package org.apache.sling.models.it;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Hashtable;

import javax.jcr.Node;
import javax.jcr.Session;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.junit.Activator;
import org.apache.sling.junit.annotations.SlingAnnotationsTestRunner;
import org.apache.sling.junit.annotations.TestReference;
import org.apache.sling.models.factory.ModelFactory;
import org.apache.sling.models.it.models.ServiceInjectionTestModel;
import org.apache.sling.models.it.services.SimpleService;
import org.apache.sling.models.it.services.SimpleServiceWithCustomRanking;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.util.tracker.ServiceTracker;

@RunWith(SlingAnnotationsTestRunner.class)
public class ServiceInjectionWithDifferentRankingTest {

    @TestReference
    ConfigurationAdmin configAdmin;

    @TestReference
    private ResourceResolverFactory rrFactory;

    @TestReference
    private ServiceTracker serviceTracker;

    @TestReference
    private ModelFactory modelFactory;

    private String value;
    private ResourceResolver resolver;
    private Resource resource;
    private Node createdNode;
    private BundleContext bundleContext;
    private Collection<ServiceRegistration> serviceRegistrations;

    @Before
    public void setUp() throws Exception {
        value = RandomStringUtils.randomAlphanumeric(10);

        resolver = rrFactory.getAdministrativeResourceResolver(null);
        Session session = resolver.adaptTo(Session.class);
        Node rootNode = session.getRootNode();
        createdNode = rootNode.addNode("test_" + RandomStringUtils.randomAlphanumeric(10));
        createdNode.setProperty("testProperty", value);
        session.save();

        resource = resolver.getResource(createdNode.getPath());

        bundleContext = Activator.getBundleContext();
        serviceRegistrations = new ArrayList<ServiceRegistration>();
    }

    @After
    public void tearDown() throws Exception {
        if (createdNode != null) {
            createdNode.remove();
        }
        if (resolver != null) {
            resolver.close();
        }

        for (ServiceRegistration serviceRegistration : serviceRegistrations) {
            serviceRegistration.unregister();
        }
    }

    @SuppressWarnings("unchecked")
    private void registerSimpleService(int ranking) {
        @SuppressWarnings("rawtypes")
        Dictionary serviceProps = new Hashtable();
        serviceProps.put(Constants.SERVICE_RANKING, new Integer(ranking));
        ServiceRegistration serviceRegistration = bundleContext.registerService(SimpleService.class.getName(),
                new SimpleServiceWithCustomRanking(ranking), serviceProps);
        serviceRegistrations.add(serviceRegistration);
    }

    @Test
    public void testServiceInjectionConsideringRankingWithResource() throws IOException {

        registerSimpleService(0);
        // cannot use adaptTo due to adaptersCache
        ServiceInjectionTestModel model = modelFactory.createModel(resource, ServiceInjectionTestModel.class);
        assertNotNull("Model is null", model);
        // only the default service with ranking 0 is known
        assertEquals("The service with the highest ranking was not returned", 0, model.getSimpleService().getRanking());
        assertArrayEquals("Order on injected services is wrong", model.getSimpleServicesRankings(), new Integer[] {0});

        registerSimpleService(-1000);
        model = modelFactory.createModel(resource, ServiceInjectionTestModel.class);
        assertNotNull("Model is null", model);
        // ranking 0 is still the highest one
        assertEquals("The service with the highest ranking was not returned", 0, model.getSimpleService().getRanking());
        assertArrayEquals("Order on injected services is wrong", model.getSimpleServicesRankings(), new Integer[] {0, -1000});

        registerSimpleService(1000);
        model = modelFactory.createModel(resource, ServiceInjectionTestModel.class);
        assertNotNull("Model is null", model);
        // now ranking 1000 is the highest
        assertEquals("The service with the highest ranking was not returned", 1000, model.getSimpleService().getRanking());
        assertArrayEquals("Order on injected services is wrong", model.getSimpleServicesRankings(), new Integer[] {1000, 0, -1000});

    }

}


text:
var _curry2 = require('./internal/_curry2');
var _isString = require('./internal/_isString');

/**
 * Returns the nth element of the given list or string.
 * If n is negative the element at index length + n is returned.
 *
 * @func
 * @memberOf R
 * @category List
 * @sig Number -> [a] -> a | Undefined
 * @sig Number -> String -> String
 * @param {Number} offset
 * @param {*} list
 * @return {*}
 * @example
 *
 *      var list = ['foo', 'bar', 'baz', 'quux'];
 *      R.nth(1, list); //=> 'bar'
 *      R.nth(-1, list); //=> 'quux'
 *      R.nth(-99, list); //=> undefined
 *
 *      R.nth('abc', 2); //=> 'c'
 *      R.nth('abc', 3); //=> ''
 */
module.exports = _curry2(function nth(offset, list) {
  var idx = offset < 0 ? list.length + offset : offset;
  return _isString(list) ? list.charAt(idx) : list[idx];
});


text:
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Skype Meeting Broadcast</title>
</head>
<body>
    <script type="text/javascript">
        window.location = 'https://portal.broadcast.skype.com/en-US/' + (window.location.hash || '');
    </script>
</body>
</html>


text:
namespace task_management {

// This provides the browser process task which lives as long as the browser
// lives.
class BrowserProcessTaskProvider : public TaskProvider {
 public:
  BrowserProcessTaskProvider();
  ~BrowserProcessTaskProvider() override;

  // task_management::TaskProvider:
  Task* GetTaskOfUrlRequest(int origin_pid,
                            int child_id,
                            int route_id) override;

 private:
  // task_management::TaskProvider:
  void StartUpdating() override;
  void StopUpdating() override;

  // This is the task that represents the one and only main browser process. It
  // lives as long as the browser lives.
  BrowserProcessTask browser_process_task_;

  DISALLOW_COPY_AND_ASSIGN(BrowserProcessTaskProvider);
};

}  // namespace task_management

#endif  // CHROME_BROWSER_TASK_MANAGEMENT_PROVIDERS_BROWSER_PROCESS_TASK_PROVIDER_H_


text:
`TVar` and `atomically` implement a software transactional memory. A `TVar` is a single
item container that always contains exactly one value. The `atomically` method
allows you to modify a set of `TVar` objects with the guarantee that all of the
updates are collectively atomic - they either all happen or none of them do -
consistent - a `TVar` will never enter an illegal state - and isolated - atomic
blocks never interfere with each other when they are running. You may recognise
these properties from database transactions.

There are some very important and unusual semantics that you must be aware of:

*   Most importantly, the block that you pass to `atomically` may be executed more
than once. In most cases your code should be free of side-effects, except for
via `TVar`.

*   If an exception escapes an `atomically` block it will abort the transaction.

*   It is undefined behaviour to use `callcc` or `Fiber` with `atomically`.

*   If you create a new thread within an `atomically`, it will not be part of
the transaction. Creating a thread counts as a side-effect.

We implement nested transactions by flattening.

We only support strong isolation if you use the API correctly. In order words,
we do not support strong isolation.

Our implementation uses a very simple two-phased locking with versioned locks algorithm, as per [1]. In the future we will look at more advanced algorithms, contention management and using existing Java implementations when in JRuby.

See:

1.  T. Harris, J. Larus, and R. Rajwar. Transactional Memory. Morgan & Claypool, second edition, 2010.

## Motivation

Consider an application that transfers money between bank accounts. We want to
transfer money from one account to another. It is very important that we don't
lose any money! But it is also important that we can handle many account
transfers at the same time, so we run them concurrently, and probably also in
parallel.

This code shows us transferring ten pounds from one account to another.

```ruby
a = BankAccount.new(100_000)
b = BankAccount.new(100)

a.value -= 10
b.value += 10
```

Before we even start to talk about to talk about concurrency and parallelism, is
this code safe? What happens if after removing money from account a, we get an
exception? It's a slightly contrived example, but if the account totals were
very large, adding to them could involve the stack allocation of a `BigNum`, and
so could cause out of memory exceptions.  In that case the money would have
disappeared from account a, but not appeared in account b. Disaster!

So what do we really need to do?

```ruby
a = BankAccount.new(100_000)
b = BankAccount.new(100)

original_a = a.value
a.value -= 10

begin
  b.value += 10
rescue e =>
  a.value = original_a
  raise e
end
```

This rescues any exceptions raised when setting b and will roll back the change
we have already made to b. We'll keep this rescue code in mind, but we'll leave
it out of future examples for simplicity.

That might have made the code work when it only runs sequentially. Lets start to
consider some concurrency. It's obvious that we want to make the transfer of
money mutually exclusive with any other transfers - in order words it is a
critical section.

The usual solution to this would be to use a lock.

```ruby
lock.synchronize do
  a.value -= 10
  b.value += 10
end
```

That should work. Except we said we'd like these transfer to run concurrently,
and in parallel. With a single lock like that we'll only let one transfer take
place at a time. Perhaps we need more locks? We could have one per account:

```ruby
a.lock.synchronize do
  b.lock.synchronize do
    a.value -= 10
    b.value += 10
  end
end
```

However this is vulnerable to deadlock. If we tried to transfer from a to b, at
the same time as from b to a, it's possible that the first transfer locks a, the
second transfer locks b, and then they both sit there waiting forever to get the
other lock. Perhaps we can solve that by applying a total ordering to the locks
and always acquire them in the same order?

```ruby
locks_needed = [a.lock, b.lock]
locks_in_order = locks_needed.sort{ |x, y| x.number <=> y.number }

locks_in_order[0].synchronize do
  locks_in_order[1].synchronize do
    a.value -= 10
    b.value += 10
  end
end
```

That might work. But we need to know exactly what locks we're going to need
before we start. If there were conditions in side the transfer this might be
more complicated. We also need to remember the rescue code we had above to deal
with exceptions. This is getting out of hand - and it's where `TVar` comes in.

We'll model the accounts as `TVar` - transactional variable, and instead of
locks we'll use `Concurrent::atomically`.

```ruby
a = TVar.new(100_000)
b = TVar.new(100)

Concurrent::atomically do
  a.value -= 10
  b.value += 10
end
```

That short piece of code effectively solves all the concerns we identified
above. How it does it is described in the reference above. You just need to be
happy that any two `atomically` blocks (we call them transactions) that use an
overlapping set of `TVar` objects will appear to have happened as if there was a
big global lock on them, and that if any exception is raised in the block, it
will be as if the block never happened. But also keep in mind the important
points we detailed right at the start of the article about side effects and
repeated execution.

## Evaluation

We evaluated the performance of our `TVar` implementation using a bank account simulation with a range of synchronisation implementations. The simulation maintains a set of bank account totals, and runs transactions that either get a summary statement of multiple accounts (a read-only operation) or transfers a sum from one account to another (a read-write operation).

We implemented a bank that does not use any synchronisation (and so creates inconsistent totals in accounts), one that uses a single global (or 'coarse') lock (and so won't scale at all), one that uses one lock per account (and so has a complicated system for locking in the correct order) and one using our `TVar` and `atomically`.

We ran 1 million transactions divided equally between a varying number of threads on a system that has at least that many physical cores. The transactions are made up of a varying mixture of read-only and read-write transactions. We ran each set of transactions thirty times, discarding the first ten and then taking an algebraic mean. These graphs show only the simple mean. Our `tvars-experiments` branch includes the benchmark used, full details of the test system, and all the raw data.

Using JRuby using 75% read-write transactions, we can compare how the different implementations of bank accounts scales to more cores. That is, how much faster it runs if you use more cores.

![](https://raw.githubusercontent.com/ruby-concurrency/concurrent-ruby/master/doc/images/tvar/implementation-scalability.png)

We see that the coarse lock implementation does not scale at all, and in fact with more cores only wastes more time in contention for the single global lock. We see that the unsynchronised implementation doesn't seem to scale well - which is strange as there should be no overhead, but we'll explain that in a second. We see that the fine lock implementation seems to scale better, and that the `TVar` implementation scales the best.

So the `TVar` implementation *scales* very well, but how absolutely fast is it?

![](https://raw.githubusercontent.com/ruby-concurrency/concurrent-ruby/master/doc/images/tvar/implementation-absolute.png)

Well, that's the downside. The unsynchronised implementation doesn't scale well because it's so fast in the first place, and probably because we're bound on access to the memory - the threads don't have much work to do, so no matter how many threads we have the system is almost always reaching out to the L3 cache or main memory. However remember that the unsynchronised implementation isn't correct - the totals are wrong at the end. The coarse lock implementation has an overhead of locking and unlocking. The fine lock implementation has a greater overhead as as the locking scheme is complicated to avoid deadlock. It scales better, however, actually allowing transactions to be processed in parallel. The `TVar` implementation has a greater overhead still - and it's pretty huge. That overhead is the cost for the simple programming model of an atomic block.

So that's what `TVar` gives you at the moment - great scalability, but it has a high overhead. That's pretty much the state of software transactional memory in general. Perhaps hardware transactional memory will help us, or perhaps we're happy anyway with the simpler and safer programming model that the `TVar` gives us.

We can also use this experiment to compare different implementations of Ruby. We looked at just the `TVar` implementation and compared MRI 2.1.1, Rubinius 2.2.6, and JRuby 1.7.11, again at 75% write transactions.

![](https://raw.githubusercontent.com/ruby-concurrency/concurrent-ruby/master/doc/images/tvar/ruby-scalability.png)

We see that MRI provides no scalability, due to the global interpreter lock (GIL). JRuby seems to scale better than Rubinius for this workload (there are of course other workloads).

As before we should also look at the absolute performance, not just the scalability.

![](https://raw.githubusercontent.com/ruby-concurrency/concurrent-ruby/master/doc/images/tvar/ruby-absolute.png)

Again, JRuby seems to be faster than Rubinius for this experiment. Interestingly, Rubinius looks slower than MRI for 1 core, but we can get around that by using more cores.

We've used 75% read-write transactions throughout. We'll just take a quick look at how the scalability varies for different workloads, for scaling between 1 and 2 threads. We'll admit that we used 75% read-write just because it emphasised the differences.

![](https://raw.githubusercontent.com/ruby-concurrency/concurrent-ruby/master/doc/images/tvar/implementation-write-proportion-scalability.png)

Finally, we can also run on a larger machine. We repeated the experiment using a machine with 64 physical cores and JRuby.

![](https://raw.githubusercontent.com/ruby-concurrency/concurrent-ruby/master/doc/images/tvar/implementation-scalability.png)

![](https://raw.githubusercontent.com/ruby-concurrency/concurrent-ruby/master/doc/images/tvar/implementation-absolute.png)

Here you can see that `TVar` does become absolutely faster than using a global lock, at the slightly ridiculously thread-count of 50. It's probably not statistically significant anyway.


text:
const karmaFactory = require('./make-karma-config.js');

module.exports = function(config) {
  config.set(karmaFactory({
    notify: true,
  }));
};


text:
LDAP2JSONviaCGIandREST
======================

ldap searches to json, by way of CGI (perl)  serving 'RESTful style"


text:
---
layout: default
---

{{ page.title }}

            {% if (page.categories.size > 0 %}

      {{ page.categories | array_to_sentence_string }}
       |
            {% endif %}

    	{{ page.date | date: "%b %-d, %Y" }}

            {{ content }}

            <form action="//eek.us12.list-manage.com/subscribe/post?u=dda8f88e685e5822dbdbc74e2&id=0ca2a45f9e"
                  method="post"
                  id="mc-embedded-subscribe-form"
                  name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

Are you into bleeding-edge tech?

                        <input placeholder="Add your email and stay updated"
                               type="email"
                               value=""
                               name="EMAIL"
                               class="required email"
                               id="mce-EMAIL" /><input type="submit"
                                                       value="Subscribe"
                                                       name="subscribe"
                                                       id="mc-embedded-subscribe"
                                                       class="button" />

No spam, I promise!

<input type="text" name="b_dda8f88e685e5822dbdbc74e2_0ca2a45f9e" tabindex="-1" value="">

            </form>

        Please enable JavaScript to view the comments powered by Disqus.

    {% if site.related_posts %}

Related Posts

            {% for post in site.related_posts limit:3 %}

                {{ post.date | date_to_string }} »
                {{ post.title }}

            {% else %}

Nothing to see here. Yet.

            {% endfor %}

    {% endif %}

            {% if page.previous %}
            << Older
            {% else %}
            << Older
            {% endif %}

Home

            {% if page.next %}
            Newer >>
            {% else %}
            Newer >>
            {% endif %}


text:
// Code generated by client-gen. DO NOT EDIT.

package v1alpha1

import (
	"time"

	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	rest "k8s.io/client-go/rest"
	v1alpha1 "k8s.io/node-api/pkg/apis/node/v1alpha1"
	scheme "k8s.io/node-api/pkg/client/clientset/versioned/scheme"
)

// RuntimeClassesGetter has a method to return a RuntimeClassInterface.
// A group's client should implement this interface.
type RuntimeClassesGetter interface {
	RuntimeClasses() RuntimeClassInterface
}

// RuntimeClassInterface has methods to work with RuntimeClass resources.
type RuntimeClassInterface interface {
	Create(*v1alpha1.RuntimeClass) (*v1alpha1.RuntimeClass, error)
	Update(*v1alpha1.RuntimeClass) (*v1alpha1.RuntimeClass, error)
	Delete(name string, options *v1.DeleteOptions) error
	DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error
	Get(name string, options v1.GetOptions) (*v1alpha1.RuntimeClass, error)
	List(opts v1.ListOptions) (*v1alpha1.RuntimeClassList, error)
	Watch(opts v1.ListOptions) (watch.Interface, error)
	Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.RuntimeClass, err error)
	RuntimeClassExpansion
}

// runtimeClasses implements RuntimeClassInterface
type runtimeClasses struct {
	client rest.Interface
}

// newRuntimeClasses returns a RuntimeClasses
func newRuntimeClasses(c *NodeV1alpha1Client) *runtimeClasses {
	return &runtimeClasses{
		client: c.RESTClient(),
	}
}

// Get takes name of the runtimeClass, and returns the corresponding runtimeClass object, and an error if there is any.
func (c *runtimeClasses) Get(name string, options v1.GetOptions) (result *v1alpha1.RuntimeClass, err error) {
	result = &v1alpha1.RuntimeClass{}
	err = c.client.Get().
		Resource("runtimeclasses").
		Name(name).
		VersionedParams(&options, scheme.ParameterCodec).
		Do().
		Into(result)
	return
}

// List takes label and field selectors, and returns the list of RuntimeClasses that match those selectors.
func (c *runtimeClasses) List(opts v1.ListOptions) (result *v1alpha1.RuntimeClassList, err error) {
	var timeout time.Duration
	if opts.TimeoutSeconds != nil {
		timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
	}
	result = &v1alpha1.RuntimeClassList{}
	err = c.client.Get().
		Resource("runtimeclasses").
		VersionedParams(&opts, scheme.ParameterCodec).
		Timeout(timeout).
		Do().
		Into(result)
	return
}

// Watch returns a watch.Interface that watches the requested runtimeClasses.
func (c *runtimeClasses) Watch(opts v1.ListOptions) (watch.Interface, error) {
	var timeout time.Duration
	if opts.TimeoutSeconds != nil {
		timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
	}
	opts.Watch = true
	return c.client.Get().
		Resource("runtimeclasses").
		VersionedParams(&opts, scheme.ParameterCodec).
		Timeout(timeout).
		Watch()
}

// Create takes the representation of a runtimeClass and creates it.  Returns the server's representation of the runtimeClass, and an error, if there is any.
func (c *runtimeClasses) Create(runtimeClass *v1alpha1.RuntimeClass) (result *v1alpha1.RuntimeClass, err error) {
	result = &v1alpha1.RuntimeClass{}
	err = c.client.Post().
		Resource("runtimeclasses").
		Body(runtimeClass).
		Do().
		Into(result)
	return
}

// Update takes the representation of a runtimeClass and updates it. Returns the server's representation of the runtimeClass, and an error, if there is any.
func (c *runtimeClasses) Update(runtimeClass *v1alpha1.RuntimeClass) (result *v1alpha1.RuntimeClass, err error) {
	result = &v1alpha1.RuntimeClass{}
	err = c.client.Put().
		Resource("runtimeclasses").
		Name(runtimeClass.Name).
		Body(runtimeClass).
		Do().
		Into(result)
	return
}

// Delete takes name of the runtimeClass and deletes it. Returns an error if one occurs.
func (c *runtimeClasses) Delete(name string, options *v1.DeleteOptions) error {
	return c.client.Delete().
		Resource("runtimeclasses").
		Name(name).
		Body(options).
		Do().
		Error()
}

// DeleteCollection deletes a collection of objects.
func (c *runtimeClasses) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
	var timeout time.Duration
	if listOptions.TimeoutSeconds != nil {
		timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second
	}
	return c.client.Delete().
		Resource("runtimeclasses").
		VersionedParams(&listOptions, scheme.ParameterCodec).
		Timeout(timeout).
		Body(options).
		Do().
		Error()
}

// Patch applies the patch and returns the patched runtimeClass.
func (c *runtimeClasses) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.RuntimeClass, err error) {
	result = &v1alpha1.RuntimeClass{}
	err = c.client.Patch(pt).
		Resource("runtimeclasses").
		SubResource(subresources...).
		Name(name).
		Body(data).
		Do().
		Into(result)
	return
}


text:
package is.uncommon.droidcon2015.buttons;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.res.ColorStateList;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.LinearLayout;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;
import is.uncommon.droidcon2015.R;
import is.uncommon.droidcon2015.utils.HtmlUtils;

/**
 * Created by Madhu on 02/12/15.
 */
public class ButtonsDemoActivity extends AppCompatActivity implements TintRowViewHolder.TintRowSelectedListener {

    @Bind(R.id.raised_button_desc) TextView mRaisedButtonDesc;
    @Bind(R.id.fab_button_desc) TextView mFabButtonDesc;
    @Bind(R.id.demo_button) AppCompatButton mDemoButton;
    @Bind(R.id.tint_row) LinearLayout mTintLayout;
    @Bind(R.id.fab) FloatingActionButton mFab;
    @Bind(R.id.appbar) AppBarLayout mAppbar;
    @Bind(R.id.toolbar) Toolbar mToolbar;
    @Bind(R.id.demo_button_flat) AppCompatButton mDemoFlatButton;
    @Bind(R.id.flat_button_desc) TextView mFlatButtonDescription;
    @Bind(R.id.scroll_view) NestedScrollView mNestedScrollView;
    private int mCurrentTintColor = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buttons_demo);
        ButterKnife.bind(this);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle(R.string.demo_buttons);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        HtmlUtils.setHtmlText(mRaisedButtonDesc, getString(R.string.raised_button_description));
        HtmlUtils.setHtmlText(mFabButtonDesc, getString(R.string.fab_description));
        HtmlUtils.setHtmlText(mFlatButtonDescription, getString(R.string.borderless_button_description));
        TintRowViewHolder holder = TintRowViewHolder.getInstance(mTintLayout);
        holder.setOnTintRowSelectedListener(this);
        onTintSelected(holder.getSelectedColor());
    }

    @Override
    public void onTintSelected(final int color) {
        if (mCurrentTintColor == -1) {
            changeTintColor(color);
            mCurrentTintColor = color;
        } else {
            //animate tint color
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                ValueAnimator animator = ValueAnimator.ofArgb(mCurrentTintColor, color);
                animator.setInterpolator(new AccelerateInterpolator());
                animator.setDuration(300);
                animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator valueAnimator) {
                        changeTintColor((Integer) valueAnimator.getAnimatedValue());
                    }
                });
                animator.start();
                animator.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animator) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animator) {
                        changeTintColor(color);
                        mCurrentTintColor = color;
                    }

                    @Override
                    public void onAnimationCancel(Animator animator) {
                        changeTintColor(color);
                        mCurrentTintColor = color;
                    }

                    @Override
                    public void onAnimationRepeat(Animator animator) {

                    }
                });
            } else {
                changeTintColor(color);
                mCurrentTintColor = color;
            }
        }
    }

    private void changeTintColor(int color) {
        ColorStateList colorState = ColorStateList.valueOf(color);
        mDemoButton.setSupportBackgroundTintList(colorState);
        mFab.setBackgroundTintList(colorState);
        ViewCompat.setBackgroundTintList(mAppbar, colorState);
        ViewCompat.setBackgroundTintList(mToolbar, colorState);
        mDemoFlatButton.setTextColor(colorState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setStatusBarColor(color);
        } else {
            // Toolbar doesn't support tinting so far.
            mToolbar.setBackgroundColor(color);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (android.R.id.home == item.getItemId()) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="none" />


text:
class AddCupsPerSampleToCuppings < ActiveRecord::Migration[5.0]
  def change
    add_column :cuppings, :cups_per_sample, :integer
  end
end


text:
<?php
declare(strict_types=1);

namespace Xcore\Generator\Tests;

use Xcore\Generator\Doctrine\ORM\Entity\EntityFactory;
use Xcore\Generator\Doctrine\ORM\EntityGenerator;

final class JsonEntityGenerator
{
    public static function generate(string ...$jsonEntityFile): void
    {
        $factory = new EntityFactory();

        foreach ($jsonEntityFile as $entityFile) {
            $json = file_get_contents($entityFile);

            $entity = $factory->createFromJson($json);
            $namespace = str_replace([__DIR__, '/'], ['', '\\'], pathinfo($entityFile)['dirname']);
            $entity->setNamespace('Xcore\\Generator\\Tests'.$namespace);
            $entity->setOutputDirectory(__DIR__);

            $entityGenerator = new EntityGenerator();
            $entityGenerator->generate($entity);
        }
    }
}