text:
import datetime
import json
import math
import operator

from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q, Count
from django.http import HttpResponse, HttpResponseServerError, JsonResponse
from django.shortcuts import (
        render, redirect, get_object_or_404,
        )
from django.template import RequestContext
from django.urls import reverse
from django.views.decorators.http import require_http_methods

from .constants import *
from .forms import *
from .models import *

PAGE_SIZE = 50

def index(request):
    return redirect(reverse(search_recipes))

@login_required(login_url="/accounts/login/")
def bookmarklet(request):
    ctx = {
        'add': True,
        'hide_page_header': True,
    }

    saved = _save_recipe(request, ctx)

    if saved:
        return redirect(reverse(search_recipes), permanent=True)

    return render(request, 'bookmarklet.html', ctx)

@login_required(login_url="/accounts/login/")
def add_recipe(request):
    ctx = {
        'add': True,
    }

    recipe = None
    if request.method == 'GET':
        recipe_id = request.GET.get('recipe', None)
        if recipe_id is not None:
            try:
                recipe = Recipe.objects.get(id=recipe_id)
            except ObjectDoesNotExist:
                pass

    saved = _save_recipe(request, ctx, recipe=recipe)

    if saved:
        return redirect(reverse(search_recipes), permanent=True)
    else:
        return render(request, 'edit_recipe.html', ctx)

def _save_recipe(request, ctx, ribbon=None, recipe=None):
    """
    core function for adding/editing/saving recipes
    """

    # try to associate with an existing recipe if it exists
    if request.method == 'GET' and not recipe:
        url = request.GET.get('url', None)
        title = request.GET.get('title', None)
        if url:
            try:
                recipe = Recipe.objects.get(link=url)
            except ObjectDoesNotExist:
                pass

    # staff can add a ribbon as someone else
    if request.user.is_staff:
        ctx['users'] = User.objects.all()
        ctx['user_id'] = request.user.id
        specified_user = request.user
        if request.POST:
            ctx['user_id'] = int(request.POST.get('user', request.user.id))
            try:
                specified_user = User.objects.get(id=ctx['user_id'])
            except ObjectDoesNotExist:
                pass

    ctx['all_tags'] = json.dumps(list(Tag.objects.values_list(
        'value', flat=True).order_by('value').distinct()))
    if ribbon and not recipe:
        recipe = ribbon.recipe

    # try to guess the recipe if it's a POST and there isn't one given
    if not recipe and request.method == 'POST':
        recipe_id = request.POST.get('recipe-id', None)
        if recipe_id:
            try:
                recipe = Recipe.objects.get(id=recipe_id)
            except ObjectDoesNotExist:
                pass
        else:
            link = request.POST.get('re-link', None)
            if link:
                try:
                    recipe = Recipe.objects.get(link=link)
                except ObjectDoesNotExist:
                    pass

    # try to find the ribbon if possible
    if recipe and not ribbon:
        try:
            ribbon = Ribbon.objects.get(recipe=recipe, user=request.user)
        except ObjectDoesNotExist:
            pass

    recipe_form = RecipeForm(
            request.POST or None, prefix="re", instance=recipe)
    ribbon_form = RibbonForm(
            request.POST or None, prefix="ri", instance=ribbon)

    saved = False
    if recipe_form.is_valid() and ribbon_form.is_valid():
        recipe = recipe_form.save(commit=False)
        recipe.save()
        ribbon = ribbon_form.save(commit=False)
        ribbon.recipe = recipe
        if request.user.is_staff:
            ribbon.user = specified_user
        else:
            ribbon.user = request.user
        ribbon.save()

        my_current_tags = {tag.value: tag for tag in ribbon.tag_set.all()}
        tags = request.POST.get('tags','').split(',')
        for value in tags:
            if not value:
                continue
            if not value in my_current_tags:
                # add it
                Tag.objects.create(ribbon=ribbon, value=value)
            else:
                # don't delete it later
                del my_current_tags[value]
        for removed_tag in my_current_tags.values():
            removed_tag.delete()
        saved = True
    elif recipe_form.errors or ribbon_form.errors:
        tags = request.POST.get('tags','').split(',')
    else:
        if ribbon:
            tags = list(ribbon.tag_set.values_list('value', flat=True))
        elif recipe and request.user.userprofile.copy_tags:
            tags = list(Tag.objects.filter(ribbon__recipe=recipe).values_list(
                'value', flat=True).distinct())
        else:
            tags = ''

    ctx.update({
        'recipe_form': recipe_form,
        'ribbon_form': ribbon_form,
        'ribbon': ribbon,
        'recipe': recipe,
        'tags': ','.join(tags),
        })

    if request.method == 'GET':
        url = request.GET.get('url', None)
        title = request.GET.get('title', None)
        if not recipe:
            if url:
                ctx['recipe_form'].initial['link'] = url
            if title:
                ctx['recipe_form'].initial['title'] = title

    return saved

@login_required(login_url="/accounts/login/")
def edit_recipe(request, ribbon_id):
    ctx = {
        'edit': True,
    }
    try:
        ribbon = Ribbon.objects.get(id=ribbon_id, user=request.user)
    except ObjectDoesNotExist:
        return redirect(reverse(search_recipes), permanent=True)

    saved = _save_recipe(request, ctx, ribbon)
    if saved:
        ctx['message'] = 'Recipe successfully saved.'
    return render(request, 'edit_recipe.html', ctx)

def _paginate_content(request, ctx, key="ribbons"):
    if request.method == 'GET':
        page = request.GET.get('page', 1)
        if page == 'all':
            ctx[page] = 'all'
            return
        if not page:
            page = 1
        page = int(page)
        page_size = int(request.GET.get('page_size', PAGE_SIZE))
    else:
        page = 1
        page_size = PAGE_SIZE

    ctx['num_pages'] = int(math.ceil(ctx[key].count() / float(page_size)))

    ctx[key] = ctx[key][(page - 1) * page_size: page * page_size]
    if key == 'ribbons':
        ctx['ribbons'] = ctx['ribbons'].select_related('recipe')

    ctx['page_range'] = range(1, ctx['num_pages'] + 1)
    ctx['page'] = page

def view_recipe(request, recipe_id):
    ctx = {}

    recipe = get_object_or_404(Recipe, id=recipe_id)

    if request.user.is_authenticated:
        try:
            ribbon = Ribbon.objects.get(recipe=recipe, user=request.user)
            ctx['ribbon'] = ribbon
            ctx['other_ribbons'] = Ribbon.objects.filter(recipe=recipe).exclude(id=ribbon.id)
            my_tags = ribbon.get_tags()
            all_tags = recipe.get_tags()

            other_tags = sorted(set(all_tags) - set(my_tags))

            ctx['my_tags'] = my_tags
            ctx['other_tags'] = other_tags

        except ObjectDoesNotExist:
            ctx['other_ribbons'] = Ribbon.objects.filter(recipe=recipe)
            ctx['other_tags'] = recipe.get_tags()

    ctx['recipe'] = recipe

    return render(request, 'view_recipe.html', ctx)

@require_http_methods(["GET"])
def search_recipes(request):
    ctx = {}

    all_ribbons = request.GET.get('all', False) or \
        not request.user.is_authenticated
    ctx['own_ribbons'] = not all_ribbons
    if all_ribbons:
        ribbons = Ribbon.objects.all()
    else:
        ribbons = Ribbon.objects.filter(user=request.user).prefetch_related('tag_set')

    if request.user.is_authenticated:
        if request.GET.get('recipebox'):
            ctx['recipe_box'] = True
            ribbons = ribbons.filter(user=request.user, is_boxed=True).order_by(
                '-boxed_on', '-time_created')
        if request.GET.get('thumbsup'):
            ctx['thumbs_up'] = True
            ribbons = ribbons.filter(user=request.user, thumb=True)
        if request.GET.get('used'):
            ctx['used'] = True
            ribbons = ribbons.filter(user=request.user, is_used=True)

    query = request.GET.get('q')
    if query:
        ctx['query'] = query
        for token in query.split(','):
            if token:
                ribbons = ribbons.filter(Q(recipe__title__icontains=token) | Q(tag__value__icontains=token))

    ribbons = ribbons.distinct()
    ctx['ribbons'] = ribbons
    _paginate_content(request, ctx, 'ribbons')

    tags = Tag.objects.filter(ribbon__in=ribbons).values('value').annotate(
        count=Count('value')).order_by('value')

    if all_ribbons:
        ctx['recipes'] = Recipe.objects.filter(
            ribbon__in=ribbons).distinct()
        _paginate_content(request, ctx, 'recipes')

    ctx['search_tags_json'] = json.dumps(list(tags))

    return render(request, 'search.html', ctx)

@login_required(login_url="/accounts/login/")
def delete_ribbon(request, ribbon_id):
    try:
        ribbon = Ribbon.objects.get(id=ribbon_id, user=request.user)
    except ObjectDoesNotExist:
        return JsonResponse('ERROR')
    recipe = ribbon.recipe
    ribbon.delete()
    if not recipe.ribbon_set.exists():
        recipe.delete();
    return JsonResponse('OK')

@login_required(login_url="/accounts/login/")
def action(request):
    if not request.method == 'POST':
        return JsonResponse({'status':'OK'})
    action = request.POST.get('action', None)
    if action == 'deleteRibbon':
        recipe_id = request.POST.get('recipeId', None)
        ribbon_id = request.POST.get('ribbonId', None)
        try:
            ribbon = Ribbon.objects.get(id=ribbon_id, user=request.user)
        except ObjectDoesNotExist:
            return JsonResponse('ERROR')
        recipe = ribbon.recipe
        ribbon.delete()
        if not recipe.ribbon_set.exists():
            recipe.delete()
        return JsonResponse('OK')
    elif action == 'changeBoxStatus':
        new_status = request.POST.get('newStatus', None) == 'true'
        recipe_id = request.POST.get('recipeId', None)
        ribbon_id = request.POST.get('ribbonId', None)
        if recipe_id:
            try:
                recipe = Recipe.objects.get(id=recipe_id)
            except ObjectDoesNotExist:
                return JsonResponse({'status': 'FAIL'})
        else:
            return JsonResponse({'status': 'FAIL'})
        copy_tags = False
        try:
            ribbon = Ribbon.objects.get(id=ribbon_id)
            if ribbon.recipe != recipe:
                return JsonResponse({'status': 'FAIL'})
        except ObjectDoesNotExist:
            ribbon = Ribbon(recipe=recipe, user=request.user)
            copy_tags = request.user.userprofile.copy_tags
        ribbon.is_boxed = new_status
        if ribbon.is_boxed:
            ribbon.boxed_on = datetime.datetime.now()
        ribbon.save()
        if copy_tags:
            tags = Tag.objects.filter(ribbon__recipe=recipe)
            for tag in tags:
                Tag(key=tag.key, value=tag.value, ribbon=ribbon).save()

        return JsonResponse({'status': 'OK', 'ribbonId': ribbon.id})

    else:
        return JsonResponse({'status':'OK'})


text:
package com.ibm.jbatch.jsl.util;

import com.ibm.jbatch.jsl.model.JSLProperties;
import com.ibm.jbatch.jsl.model.Property;

/**
 * @author skurz
 *
 */
public class PropertiesToStringHelper {

	public static String getString(JSLProperties props) {
		if (props == null) return null;

		StringBuffer buf = new StringBuffer(150);
		for (Property prop : props.getPropertyList()) {
			buf.append("name=" + prop.getName() + ",value=" + prop.getValue() + "\n");
		}
		return buf.toString();
	}
}

redpajama_set_name: RedPajamaGithub


text:
using std::invalid_argument;
using std::vector;

#include "../util/util_common.h"

#include "rotate_image.h"

void RotateImage::rotate(vector<vector<int>>& matrix) {
  if (matrix.empty()) return;

  size_t n = matrix.size();

  // Validate whether it's n * n matrix.
  for (size_t k = 0; k < n; ++k) {
    if (matrix[k].size() != n)
      throw invalid_argument("Column size is not equal to row size!");
  }

  // Copy origin matrix for reading.
  auto reference_matrix = matrix;

  // For any give elem in the matrix, [i, j], easy to find its new coordinate
  // in new rotated matrix is [j, n - i - 1]
  for (size_t i = 0; i < n; ++i) {
    for (size_t j = 0; j < n; ++j) {
      matrix[j][n - i - 1] = reference_matrix[i][j];
    }
  }
}

void RotateImage::rotateInPlace(vector<vector<int>>& matrix) {

}


text:
class Phone < ActiveRecord::Migration
  def change
    add_column :customers, :phone, :string, limit: 50
  end
end


text:
from mystic.math.grid import gridpts

#######################################################################
# scaling and mpi info; also optimizer configuration parameters
# hard-wired: use fmin solver
#######################################################################
#scale = 1.0

#npop = 20
nbins = [2,2,2]
#maxiter = 1000
#maxfun = 1e+6
#convergence_tol = 1e-4

# MPI config
nnodes = '4:ppn=1,partition=hera'   # = npop

# QUEUE config
queue = 'pdebug'
timelimit = '00:10'

#######################################################################
# the model function
#######################################################################
#from surrogate import marc_surr as model
from surrogate import ballistic_limit as limit

#######################################################################
# the subdiameter calculation
#######################################################################
def costFactory(i):
  """a cost factory for the cost function"""

  def cost(rv):
    """compute the diameter as a calculation of cost

  Input:
    - rv -- 1-d array of model parameters

  Output:
    - diameter -- scale * | F(x) - F(x')|**2
    """
    from surrogate import marc_surr as model

    # prepare x and xprime
    rv = list(rv)
    params = rv[:-1]                         #XXX: assumes Xi' is at rv[-1]
    params_prime = rv[:i]+rv[-1:]+rv[i+1:-1] #XXX: assumes Xi' is at rv[-1]

    # get the F(x) response
    Fx = model(params)

    # get the F(x') response
    Fxp = model(params_prime)

    # compute diameter
    scale = 1.0
    return -scale * (Fx - Fxp)**2

  return cost

#######################################################################
# the steepest descent optimizer
#######################################################################
def local_optimize(cost,x0,lb,ub):
  from mystic.solvers import PowellDirectionalSolver
  from mystic.termination import NormalizedChangeOverGeneration as NCOG
  from mystic.monitors import VerboseMonitor, Monitor

  maxiter = 1000
  maxfun = 1e+6
  convergence_tol = 1e-4

 #stepmon = VerboseMonitor(100)
  stepmon = Monitor()
  evalmon = Monitor()

  ndim = len(lb)

  solver = PowellDirectionalSolver(ndim)
  solver.SetInitialPoints(x0)
  solver.SetStrictRanges(min=lb,max=ub)
  solver.SetEvaluationLimits(maxiter,maxfun)
  solver.SetEvaluationMonitor(evalmon)
  solver.SetGenerationMonitor(stepmon)

  tol = convergence_tol
  solver.Solve(cost, termination=NCOG(tol))

  solved_params = solver.bestSolution
  solved_energy = solver.bestEnergy
  func_evals = solver.evaluations
  return solved_params, solved_energy, func_evals

#######################################################################
# make a pseudo-global optimizer from a steepest descent optimizer
#######################################################################
def optimize(cost,lower,upper):
  from mystic.tools import random_seed
  from pyina.launchers import MoabSlurm as Pool
  random_seed(123)

  # generate arrays of points defining a grid in parameter space
  grid_dimensions = len(lower)
  bins = []
  for i in range(grid_dimensions):
    step = abs(upper[i] - lower[i])/nbins[i]
    bins.append( [lower[i] + (j+0.5)*step for j in range(nbins[i])] )

  # build a grid of starting points
  initial_values = gridpts(bins)

  # run optimizer for each grid point
  lb = [lower for i in range(len(initial_values))]
  ub = [upper for i in range(len(initial_values))]
  cf = [cost for i in range(len(initial_values))]
  # map:: params, energy, func_evals = local_optimize(cost,x0,lb,ub)
  config = {'queue':queue, 'timelimit':timelimit}
  results = Pool(nnodes, **config).map(local_optimize,cf,initial_values,lb,ub)
  #print "results = %s" % results

  # get the results with the lowest energy
  best = list(results[0][0]), results[0][1]
  func_evals = results[0][2]
  for result in results[1:]:
    func_evals += result[2] # add function evaluations
    if result[1] < best[1]: # compare energy
      best = list(result[0]), result[1]

  # return best
  print "solved: %s" % best[0]
  scale = 1.0
  diameter_squared = -best[1] / scale  #XXX: scale != 0
  return diameter_squared, func_evals

#######################################################################
# loop over model parameters to calculate concentration of measure
#######################################################################
def UQ(start,end,lower,upper):
  diameters = []
  function_evaluations = []
  total_func_evals = 0
  total_diameter = 0.0

  for i in range(start,end+1):
    lb = lower + [lower[i]]
    ub = upper + [upper[i]]
    nbins[-1] = nbins[i] #XXX: kind of hackish

    #construct cost function and run optimizer
    cost = costFactory(i)
    subdiameter, func_evals = optimize(cost,lb,ub) #XXX: no init_condition

    function_evaluations.append(func_evals)
    diameters.append(subdiameter)

    total_func_evals += function_evaluations[-1]
    total_diameter += diameters[-1]

  print "subdiameters (squared): %s" % diameters
  print "diameter (squared): %s" % total_diameter
  print "func_evals: %s => %s" % (function_evaluations, total_func_evals)

  return total_diameter

#######################################################################
# rank, bounds, and restart information
#######################################################################
if __name__ == '__main__':
  from math import sqrt

  function_name = "marc_surr"
  lower_bounds = [60.0, 0.0, 2.1]
  upper_bounds = [105.0, 30.0, 2.8]
# h = thickness = [60,105]
# a = obliquity = [0,30]
# v = speed = [2.1,2.8]

  RVstart = 0; RVend = 2
  RVmax = len(lower_bounds) - 1

  # when not a random variable, set the value to the lower bound
  for i in range(0,RVstart):
    upper_bounds[i] = lower_bounds[i]
  for i in range(RVend+1,RVmax+1):
    upper_bounds[i] = lower_bounds[i]

  lbounds = lower_bounds[RVstart:1+RVend]
  ubounds = upper_bounds[RVstart:1+RVend]

  #FIXME: these are *copies*... actual values contained in 'local_optimize'
  maxiter = 1000
  maxfun = 1e+6
  convergence_tol = 1e-4

  print "...SETTINGS..."
  print "nbins = %s" % nbins
  print "maxiter = %s" % maxiter
  print "maxfun = %s" % maxfun
  print "convergence_tol = %s" % convergence_tol
  #print "crossover = %s" % crossover
  #print "percent_change = %s" % percent_change
  print "..............\n\n"

  print " model: f(x) = %s(x)" % function_name
  param_string = "["
  for i in range(RVmax+1):
    param_string += "'x%s'" % str(i+1)
    if i == (RVmax):
      param_string += "]"
    else:
      param_string += ", "

  print " parameters: %s" % param_string
  print "  varying 'xi', with i = %s" % range(RVstart+1,RVend+2)
  print " lower bounds: %s" % lower_bounds
  print " upper bounds: %s" % upper_bounds
# print " ..."
  nbins.append(None) #XXX: kind of hackish
  diameter = UQ(RVstart,RVend,lower_bounds,upper_bounds)

# EOF


text:
@interface CDContainsFilter : CDOperatorFilter {

}

@property (nonatomic, assign) BOOL caseSensitive;

-(NSString*)operatorString;

@end


text:
<?php

namespace Blog;

 use Zend\ModuleManager\Feature\ConfigProviderInterface;
 use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
/**
 * Description of Module
 *
 * @author jeremy
 */
class Module implements ConfigProviderInterface, AutoloaderProviderInterface {
    public function getConfig() {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig() {
         return array(
             'Zend\Loader\StandardAutoloader' => array(
                 'namespaces' => array(
                     // Autoload all classes from namespace 'Blog' from '/module/Blog/src/Blog'
                     __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                 )
             )
         );
    }

}


text:
require "spec_helper"

describe Mongoid::Relations::Embedded::One do

  describe "#===" do

    let(:base) do
      Person.new
    end

    let(:target) do
      Name.new
    end

    let(:metadata) do
      Person.relations["name"]
    end

    let(:relation) do
      described_class.new(base, target, metadata)
    end

    context "when the proxied document is same class" do

      it "returns true" do
        (relation === Name.new).should be_true
      end
    end
  end

  describe "#=" do

    context "when the relation is not cyclic" do

      context "when the parent is a new record" do

        let(:person) do
          Person.new
        end

        let(:name) do
          Name.new
        end

        before do
          person.name = name
        end

        it "sets the target of the relation" do
          person.name.should eq(name)
        end

        it "sets the base on the inverse relation" do
          name.namable.should eq(person)
        end

        it "sets the same instance on the inverse relation" do
          name.namable.should eql(person)
        end

        it "does not save the target" do
          name.should_not be_persisted
        end
      end

      context "when the parent is not a new record" do

        let(:person) do
          Person.create
        end

        let(:name) do
          Name.new
        end

        context "when setting directly" do

          before do
            person.name = name
          end

          it "sets the target of the relation" do
            person.name.should eq(name)
          end

          it "sets the base on the inverse relation" do
            name.namable.should eq(person)
          end

          it "sets the same instance on the inverse relation" do
            name.namable.should eql(person)
          end

          it "saves the target" do
            name.should be_persisted
          end
        end

        context "when setting via the parent attributes" do

          before do
            person.attributes = { :name => name }
          end

          it "sets the target of the relation" do
            person.name.should eq(name)
          end

          it "does not save the target" do
            name.should_not be_persisted
          end
        end
      end
    end

    context "when the relation is cyclic" do

      context "when the parent is a new record" do

        let(:parent_shelf) do
          Shelf.new
        end

        let(:child_shelf) do
          Shelf.new
        end

        before do
          parent_shelf.child_shelf = child_shelf
        end

        it "sets the target of the relation" do
          parent_shelf.child_shelf.should eq(child_shelf)
        end

        it "sets the base on the inverse relation" do
          child_shelf.parent_shelf.should eq(parent_shelf)
        end

        it "sets the same instance on the inverse relation" do
          child_shelf.parent_shelf.should eql(parent_shelf)
        end

        it "does not save the target" do
          child_shelf.should_not be_persisted
        end
      end

      context "when the parent is not a new record" do

        let(:parent_shelf) do
          Shelf.create
        end

        let(:child_shelf) do
          Shelf.new
        end

        before do
          parent_shelf.child_shelf = child_shelf
        end

        it "sets the target of the relation" do
          parent_shelf.child_shelf.should eq(child_shelf)
        end

        it "sets the base on the inverse relation" do
          child_shelf.parent_shelf.should eq(parent_shelf)
        end

        it "sets the same instance on the inverse relation" do
          child_shelf.parent_shelf.should eql(parent_shelf)
        end

        it "saves the target" do
          child_shelf.should be_persisted
        end
      end
    end
  end

  describe "#= nil" do

    context "when the relation is not cyclic" do

      context "when the parent is a new record" do

        let(:person) do
          Person.new
        end

        let(:name) do
          Name.new
        end

        before do
          person.name = name
          person.name = nil
        end

        it "sets the relation to nil" do
          person.name.should be_nil
        end

        it "removes the inverse relation" do
          name.namable.should be_nil
        end
      end

      context "when the inverse is already nil" do

        let(:person) do
          Person.new
        end

        before do
          person.name = nil
        end

        it "sets the relation to nil" do
          person.name.should be_nil
        end
      end

      context "when the parent is persisted" do

        let(:person) do
          Person.create
        end

        let(:name) do
          Name.new
        end

        context "when setting directly" do

          before do
            person.name = name
            person.name = nil
          end

          it "sets the relation to nil" do
            person.name.should be_nil
          end

          it "removed the inverse relation" do
            name.namable.should be_nil
          end

          it "deletes the child document" do
            name.should be_destroyed
          end
        end

        context "when setting via parent attributes" do

          before do
            person.name = name
            person.attributes = { :name => nil }
          end

          it "sets the relation to nil" do
            person.name.should be_nil
          end

          it "does not delete the child document" do
            name.should_not be_destroyed
          end
        end
      end
    end

    context "when the relation is cyclic" do

      context "when the parent is a new record" do

        let(:parent_shelf) do
          Shelf.new
        end

        let(:child_shelf) do
          Shelf.new
        end

        before do
          parent_shelf.child_shelf = child_shelf
          parent_shelf.child_shelf = nil
        end

        it "sets the relation to nil" do
          parent_shelf.child_shelf.should be_nil
        end

        it "removes the inverse relation" do
          child_shelf.parent_shelf.should be_nil
        end
      end

      context "when the inverse is already nil" do

        let(:parent_shelf) do
          Shelf.new
        end

        before do
          parent_shelf.child_shelf = nil
        end

        it "sets the relation to nil" do
          parent_shelf.child_shelf.should be_nil
        end
      end

      context "when the documents are not new records" do

        let(:parent_shelf) do
          Shelf.create
        end

        let(:child_shelf) do
          Shelf.new
        end

        before do
          parent_shelf.child_shelf = child_shelf
          parent_shelf.child_shelf = nil
        end

        it "sets the relation to nil" do
          parent_shelf.child_shelf.should be_nil
        end

        it "removed the inverse relation" do
          child_shelf.parent_shelf.should be_nil
        end

        it "deletes the child document" do
          child_shelf.should be_destroyed
        end
      end
    end
  end

  describe "#build_#\{name}" do

    context "when providing mass assignment scoping" do

      let(:person) do
        Person.new
      end

      let(:quiz) do
        person.build_quiz(
          { :topic => "Testing", :name => "Test" }, :as => :admin
        )
      end

      it "sets the attributes for the role" do
        quiz.topic.should eq("Testing")
      end

      it "does not set attributes not for the role" do
        quiz.name.should be_nil
      end
    end

    context "when the relation is not cyclic" do

      context "when the parent is a new record" do

        context "when not providing any attributes" do

          context "when building once" do

            let(:person) do
              Person.new
            end

            let!(:name) do
              person.build_name
            end

            it "sets the target of the relation" do
              person.name.should eq(name)
            end

            it "sets the base on the inverse relation" do
              name.namable.should eq(person)
            end

            it "sets no attributes" do
              name.first_name.should be_nil
            end

            it "does not save the target" do
              name.should_not be_persisted
            end
          end

          context "when building twice" do

            let(:person) do
              Person.new
            end

            let!(:name) do
              person.build_name
              person.build_name
            end

            it "sets the target of the relation" do
              person.name.should eq(name)
            end

            it "sets the base on the inverse relation" do
              name.namable.should eq(person)
            end

            it "sets no attributes" do
              name.first_name.should be_nil
            end

            it "does not save the target" do
              name.should_not be_persisted
            end
          end
        end

        context "when passing nil as the attributes" do

          let(:person) do
            Person.new
          end

          let!(:name) do
            person.build_name(nil)
          end

          it "sets the target of the relation" do
            person.name.should eq(name)
          end

          it "sets the base on the inverse relation" do
            name.namable.should eq(person)
          end

          it "sets no attributes" do
            name.first_name.should be_nil
          end

          it "does not save the target" do
            name.should_not be_persisted
          end
        end

        context "when providing attributes" do

          let(:person) do
            Person.new
          end

          let!(:name) do
            person.build_name(:first_name => "James")
          end

          it "sets the target of the relation" do
            person.name.should eq(name)
          end

          it "sets the base on the inverse relation" do
            name.namable.should eq(person)
          end

          it "sets the attributes" do
            name.first_name.should eq("James")
          end

          it "does not save the target" do
            name.should_not be_persisted
          end
        end
      end

      context "when the parent is not a new record" do

        let(:person) do
          Person.create
        end

        let!(:name) do
          person.build_name(:first_name => "James")
        end

        it "does not save the target" do
          name.should_not be_persisted
        end
      end
    end

    context "when the relation is cyclic" do

      context "when the parent is a new record" do

        let(:parent_shelf) do
          Shelf.new
        end

        let!(:child_shelf) do
          parent_shelf.build_child_shelf(:level => 1)
        end

        it "sets the target of the relation" do
          parent_shelf.child_shelf.should eq(child_shelf)
        end

        it "sets the base on the inverse relation" do
          child_shelf.parent_shelf.should eq(parent_shelf)
        end

        it "sets the attributes" do
          child_shelf.level.should eq(1)
        end

        it "does not save the target" do
          child_shelf.should_not be_persisted
        end
      end

      context "when the parent is not a new record" do

        let(:parent_shelf) do
          Shelf.create
        end

        let!(:child_shelf) do
          parent_shelf.build_child_shelf(:level => 2)
        end

        it "does not save the target" do
          child_shelf.should_not be_persisted
        end
      end
    end
  end

  describe ".builder" do

    let(:base) do
      Person.new
    end

    let(:target) do
      Name.new
    end

    let(:metadata) do
      Person.relations["name"]
    end

    let(:builder_klass) do
      Mongoid::Relations::Builders::Embedded::One
    end

    it "returns the embedded one builder" do
      described_class.builder(base, metadata, target).should be_a(builder_klass)
    end
  end

  describe "#create_#\{name}" do

    context "when providing mass assignment scoping" do

      let(:person) do
        Person.new
      end

      let(:quiz) do
        person.create_quiz(
          { :topic => "Testing", :name => "Test" }, :as => :admin
        )
      end

      it "sets the attributes for the role" do
        quiz.topic.should eq("Testing")
      end

      it "does not set attributes not for the role" do
        quiz.name.should be_nil
      end
    end

    context "when the parent is a new record" do

      context "when not providing any attributes" do

        let(:person) do
          Person.new
        end

        let!(:name) do
          person.create_name
        end

        it "sets the target of the relation" do
          person.name.should eq(name)
        end

        it "sets the base on the inverse relation" do
          name.namable.should eq(person)
        end

        it "sets no attributes" do
          name.first_name.should be_nil
        end

        it "saves the target" do
          name.should be_persisted
        end
      end

      context "when passing nil as the attributes" do

        let(:person) do
          Person.new
        end

        let!(:name) do
          person.create_name(nil)
        end

        it "sets the target of the relation" do
          person.name.should eq(name)
        end

        it "sets the base on the inverse relation" do
          name.namable.should eq(person)
        end

        it "sets no attributes" do
          name.first_name.should be_nil
        end

        it "saves the target" do
          name.should be_persisted
        end
      end

      context "when providing attributes" do

        let(:person) do
          Person.new
        end

        let!(:name) do
          person.create_name(:first_name => "James")
        end

        it "sets the target of the relation" do
          person.name.should eq(name)
        end

        it "sets the base on the inverse relation" do
          name.namable.should eq(person)
        end

        it "sets the attributes" do
          name.first_name.should eq("James")
        end

        it "saves the target" do
          name.should be_persisted
        end
      end

      context "when the parent is not a new record" do

        let(:person) do
          Person.create
        end

        let!(:name) do
          person.create_name(:first_name => "James")
        end

        it "does not save the target" do
          name.should be_persisted
        end
      end
    end
  end

  describe ".embedded?" do

    it "returns true" do
      described_class.should be_embedded
    end
  end

  describe ".macro" do

    it "returns embeds_one" do
      described_class.macro.should eq(:embeds_one)
    end
  end

  describe ".nested_builder" do

    let(:nested_builder_klass) do
      Mongoid::Relations::Builders::NestedAttributes::One
    end

    let(:metadata) do
      Person.relations["name"]
    end

    let(:attributes) do
      {}
    end

    it "returns the single nested builder" do
      described_class.nested_builder(metadata, attributes, {}).should
        be_a(nested_builder_klass)
    end
  end

  describe "#respond_to?" do

    let(:person) do
      Person.new
    end

    let!(:name) do
      person.build_name(:first_name => "Tony")
    end

    let(:document) do
      person.name
    end

    Mongoid::Document.public_instance_methods(true).each do |method|

      context "when checking #{method}" do

        it "returns true" do
          document.respond_to?(method).should be_true
        end
      end
    end

    it "responds to persisted?" do
      document.should respond_to(:persisted?)
    end
  end

  describe ".valid_options" do

    it "returns the valid options" do
      described_class.valid_options.should eq(
        [ :as, :cascade_callbacks, :cyclic ]
      )
    end
  end

  describe ".validation_default" do

    it "returns true" do
      described_class.validation_default.should be_true
    end
  end

  context "when the embedded document has an array field" do

    let!(:person) do
      Person.create
    end

    let!(:name) do
      person.create_name(
        :first_name => "Syd",
        :last_name => "Vicious",
        :aliases => nil
      )
    end

    context "when saving the array on a persisted document" do

      let(:from_db) do
        Person.find(person.id).name
      end

      before do
        from_db.aliases = [ "Syd", "Sydney" ]
        from_db.save
      end

      it "sets the values of the array" do
        from_db.aliases.should eq([ "Syd", "Sydney" ])
      end

      it "persists the array" do
        Person.find(person.id).name.aliases.should eq([ "Syd", "Sydney" ])
      end
    end
  end

  context "when embedding a many under a one" do

    let!(:person) do
      Person.create
    end

    before do
      person.create_name
    end

    context "when the documents are reloaded from the database" do

      let(:from_db) do
        Person.first
      end

      context "when adding a new many" do

        let(:name) do
          from_db.name
        end

        let!(:translation) do
          name.translations.new
        end

        context "when saving the root" do

          before do
            from_db.save
          end

          it "persists the new document on the first save" do
            from_db.reload.name.translations.should_not be_empty
          end
        end
      end
    end
  end
end


text:
package buildserver

import (
	"compress/gzip"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"

	"github.com/concourse/atc"
	"github.com/concourse/atc/db"
	"github.com/concourse/atc/event"
	"github.com/vito/go-sse/sse"
)

const ProtocolVersionHeader = "X-ATC-Stream-Version"
const CurrentProtocolVersion = "2.0"

func NewEventHandler(buildsDB BuildsDB, buildID int) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		flusher := w.(http.Flusher)
		closed := w.(http.CloseNotifier).CloseNotify()

		w.Header().Add("Content-Type", "text/event-stream; charset=utf-8")
		w.Header().Add("Cache-Control", "no-cache, no-store, must-revalidate")
		w.Header().Add("Connection", "keep-alive")
		w.Header().Add(ProtocolVersionHeader, CurrentProtocolVersion)

		var start uint = 0
		if r.Header.Get("Last-Event-ID") != "" {
			_, err := fmt.Sscanf(r.Header.Get("Last-Event-ID"), "%d", &start)
			if err != nil {
				w.WriteHeader(http.StatusBadRequest)
				return
			}

			start++
		}

		var responseWriter io.Writer = w
		var responseFlusher *gzip.Writer

		w.Header().Add("Vary", "Accept-Encoding")
		if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
			w.Header().Set("Content-Encoding", "gzip")

			gz := gzip.NewWriter(w)
			defer gz.Close()

			responseWriter = gz
			responseFlusher = gz
		}

		events, err := buildsDB.GetBuildEvents(buildID, start)
		if err != nil {
			w.WriteHeader(http.StatusNotFound)
			return
		}

		defer events.Close()

		es := make(chan atc.Event)
		errs := make(chan error, 1)

		go func() {
			for {
				ev, err := events.Next()
				if err != nil {
					errs <- err
					return
				} else {
					select {
					case es <- ev:
					case <-closed:
						return
					}
				}
			}
		}()

		for {
			select {
			case ev := <-es:
				payload, err := json.Marshal(event.Message{ev})
				if err != nil {
					return
				}

				err = sse.Event{
					ID:   fmt.Sprintf("%d", start),
					Name: "event",
					Data: payload,
				}.Write(responseWriter)
				if err != nil {
					return
				}

				start++

				if responseFlusher != nil {
					err = responseFlusher.Flush()
					if err != nil {
						return
					}
				}

				flusher.Flush()
			case err := <-errs:
				if err == db.ErrEndOfBuildEventStream {
					err = sse.Event{Name: "end"}.Write(responseWriter)
					if err != nil {
						return
					}
				}

				return
			case <-closed:
				return
			}
		}

		return
	})
}


text:
using content::BrowserThread;

namespace browser_sync {

namespace {

// Helper method to generate a hash from an extension id.
std::string IdToHash(const std::string extension_id) {
  std::string hash = base::SHA1HashString(extension_id);
  hash = base::HexEncode(hash.c_str(), hash.length());
  return hash;
}

}  // namespace

ExtensionBackedDataTypeController::ExtensionBackedDataTypeController(
    const DisableTypeCallback& disable_callback,
    syncer::ModelType type,
    const std::string& extension_hash,
    SyncApiComponentFactory* sync_factory,
    Profile* profile)
    : UIDataTypeController(
          BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI),
          base::Bind(&ChromeReportUnrecoverableError),
          disable_callback,
          type,
          sync_factory),
      extension_hash_(extension_hash),
      profile_(profile) {
  extensions::ExtensionRegistry* registry =
      extensions::ExtensionRegistryFactory::GetForBrowserContext(profile_);
  registry->AddObserver(this);
}

ExtensionBackedDataTypeController::~ExtensionBackedDataTypeController() {
  extensions::ExtensionRegistry* registry =
      extensions::ExtensionRegistryFactory::GetForBrowserContext(profile_);
  registry->RemoveObserver(this);
}

bool ExtensionBackedDataTypeController::ReadyForStart() const {
  // TODO(zea): consider checking if the extension was uninstalled without
  // sync noticing, in which case the datatype should be purged.
  return IsSyncingExtensionEnabled();
}

void ExtensionBackedDataTypeController::OnExtensionLoaded(
    content::BrowserContext* browser_context,
    const extensions::Extension* extension) {
  if (DoesExtensionMatch(*extension)) {
    ProfileSyncService* sync_service =
        ProfileSyncServiceFactory::GetForProfile(profile_);
    sync_service->ReenableDatatype(type());
  }
}

void ExtensionBackedDataTypeController::OnExtensionUnloaded(
    content::BrowserContext* browser_context,
    const extensions::Extension* extension,
    extensions::UnloadedExtensionInfo::Reason reason) {
  if (DoesExtensionMatch(*extension)) {
    ProfileSyncService* sync_service =
        ProfileSyncServiceFactory::GetForProfile(profile_);

    // This will trigger purging the datatype from the sync directory. This
    // may not always be the right choice, especially in the face of transient
    // unloads (e.g. for permission changes). If that becomes a large enough
    // issue, we should consider using the extension unload reason to just
    // trigger a reconfiguration without disabling (type will be unready).
    sync_service->DisableDatatype(type(),
                                  FROM_HERE,
                                  "Extension unloaded");
  }
}

bool ExtensionBackedDataTypeController::IsSyncingExtensionEnabled() const {
  if (extension_hash_.empty())
    return true;  // For use while extension is in development.

  // TODO(synced notifications): rather than rely on a hash of the extension
  // id, look through the manifests to see if the extension has permissions
  // for this model type.
  extensions::ExtensionRegistry* registry =
      extensions::ExtensionRegistryFactory::GetForBrowserContext(profile_);
  const extensions::ExtensionSet& enabled_extensions(
      registry->enabled_extensions());
  for (extensions::ExtensionSet::const_iterator iter =
           enabled_extensions.begin();
       iter != enabled_extensions.end(); ++iter) {
    if (DoesExtensionMatch(*iter->get()))
      return true;
  }
  return false;
}

bool ExtensionBackedDataTypeController::DoesExtensionMatch(
    const extensions::Extension& extension) const {
  return IdToHash(extension.id()) == extension_hash_;
}

bool ExtensionBackedDataTypeController::StartModels() {
  if (IsSyncingExtensionEnabled())
    return true;

  // If the extension is not currently enabled, it means that it has been
  // disabled since the call to ReadyForStart(), and the notification
  // observer should have already posted a call to disable the type.
  return false;
}

}  // namespace browser_sync


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Project 6</title>
    <meta name="viewport" content="width=device-width">
    <meta name="description" content="I am a computer science student at Brown University">
    <meta name="keywords" content="Computer Science, Brown, Software Engineering, Machine Learning" />
    <meta name="author" content="Liu Yifan">
    <link rel="canonical" href="http://localhost:4000/web%20development/2014/07/15/project-6/">
    <link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml">

    <link rel="stylesheet" href="/style.css">

    <link rel="stylesheet" href="/css/font-awesome/css/font-awesome.min.css">
    <link href="//fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="//fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Yifan Liu

                        About

                        Portforlio

                        Contact

                        Yifan Liu

                        .NET Development - Android Development - Virtual Reality Development

About Me

Passionate about solving real-world problems with technology. Skilled in software engineering(Java, C#, C++, Python, SQL), and virtual reality application development(Expertise in Unity, CAVE, and HMDs). Expert in BIM applications in AEC with a Ph.D. in Architectural Engineering/Building informatics and design visualization

My CV can be downloaded here:

                         My Curriculum Vitæ

Portfolio

Contact Me

Questions? Comments? Collaboration? Anything!

				<form  action="//formspree.io/yifan_liu@brown.edu" method="POST" name="sentMessage" id="contactForm" novalidate>

							Name
							<input type="text" name="name" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">

							Email Address
							<input type="email" name="_replyto" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">

						<input type="hidden"  name="_subject" value="New submission!">
						<input type="text" name="_gotcha" style="display:none" />

							Message
							<textarea rows="5" name="message" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>

							<button type="submit" class="btn btn-success btn-lg">Send</button>

				</form>

Location

                                Department of Computer Science

                                Brown University

                                Providence

                                Rhode Island, 02906

Around the Web

Credits

This website is created based on a free to use, open source Bootstrap theme created by Start Bootstrap. Big thanks to Start Bootstrap!

                        Copyright © Dr. Yifan Liu 2017

Project 1

Use this area of the page to describe your project. The icon above is part of a free icon set by Flat Icons. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Project 2

Use this area of the page to describe your project. The icon above is part of a free icon set by Flat Icons. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Project 3

Use this area of the page to describe your project. The icon above is part of a free icon set by Flat Icons. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Project 4

Use this area of the page to describe your project. The icon above is part of a free icon set by Flat Icons. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Project 6

Use this area of the page to describe your project. The icon above is part of a free icon set by Flat Icons. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Project 5

Use this area of the page to describe your project. The icon above is part of a free icon set by Flat Icons. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>


text:
class CRenderProcessHandler : public CefRenderProcessHandler
{
public:
    CRenderProcessHandler() = default;
	virtual ~CRenderProcessHandler() = default;

    bool OnProcessMessageReceived(
        CefRefPtr<CefBrowser> browser,
        CefProcessId source_process,
        CefRefPtr<CefProcessMessage> message) override;

private:
	IMPLEMENT_REFCOUNTING(CRenderProcessHandler);
	DISALLOW_COPY_AND_ASSIGN(CRenderProcessHandler);
};


text:
#!/usr/bin/env node
// Copyright 2016 Google Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////////

var _ = require('lodash');
var util = require('util');
var Prob = require('prob.js');

var distributions = {
  'uniform':     {desc: 'Uniform distribution',
                  args: [['min', 0], ['max', 1]]},
  'normal':      {desc: 'Normal distribution',
                  args: [['mean', 0], ['stddev', 1]]},
  'exponential': {desc: 'Exponential distribution',
                  args: [['lambda', 1]]},
  'lognormal':   {desc: 'Lognormal distribution',
                  args: [['mean', 0], ['stddev', 1]]},
  'poisson':     {desc: 'Poisson distribution',
                  args: [['lambda', 1]]},
  'zipf':        {desc: 'Zipf\'s distribution',
                  args: [['s', 1], ['n', 100]]},
};

var argv = require('yargs')
	.usage('Usage: $0 distribution [options]')
	.example('$0 normal --count 1000', 'Output 1000 normally distributed numbers')
	.option('count', {
  alias: 'c',
  describe: 'Number of random numbers to output',
  default: 10,
  type: 'number',
  global: true
	})
	.option('verbose', {
  alias: 'v',
  describe: 'Print out additional information',
  default: false,
  type: 'boolean',
  global: true
	})
	.help('help')
	.alias('help', 'h')
	.demand(1);

_.forEach(distributions, function(distribution, name) {
  var opts = {};
  _.forEach(distribution.args, function(value, key) {
    opts[value[0]] = {
      'default': value[1],
      'type': 'number'
    };
  });

  argv = argv.command(name, distribution.desc, opts);
});

argv = argv.strict().argv;

var dist = argv._[0];
var args = _.map(distributions[dist].args, function(arg) {
  return argv[arg[0]];
});

var f = Prob[dist].apply(this, args);
for (var i = 0; i < argv.count; i++) {
  console.log(f());
}

if (argv.verbose) {
  console.log(util.format('Expected min: %d max: %d mean: %d variance: %d',
		f.Min, f.Max, f.Mean, f.Variance));
}

/* or a simple example:
var Prob = require('prob.js');
var f = Prob.normal(0, 1);

for (var i = 0; i < count; i++) {
	console.log(f());
}
*/


text:
using System;
using Leoxia.Testing.Assertions.Abstractions;

#endregion

namespace Leoxia.Testing.Assertions
{
    /// <summary>
    ///     Checks for <see cref="DateTime" />
    /// </summary>
    /// <seealso cref="Leoxia.Testing.Assertions.BaseCheckable{DateTime}" />
    /// <seealso cref="Leoxia.Testing.Assertions.Abstractions.IDateTimeCheckable" />
    public class DateTimeCheckable : BaseCheckable<DateTime>, IDateTimeCheckable
    {
        /// <summary>
        ///     Initializes a new instance of the <see cref="DateTimeCheckable" /> class.
        /// </summary>
        /// <param name="factory">The factory.</param>
        /// <param name="value">The value.</param>
        public DateTimeCheckable(IExceptionFactory factory, DateTime value) :
            base(factory, value)
        {
        }
    }
}


text:
// Copyright (c) Dapplo and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Runtime.Serialization;

namespace Dapplo.Jira.Query;

/// <summary>
/// All possible fields in a JQL
/// </summary>
public enum Fields
{
#pragma warning disable 1591
    [EnumMember(Value = "affectedVersion")]
    AffectedVersion,
    [EnumMember(Value = "approvals")] Approvals,
    [EnumMember(Value = "assignee")] Assignee,
    [EnumMember(Value = "attachments")] Attachments,
    [EnumMember(Value = "category")] Category,
    [EnumMember(Value = "comment")] Comment,
    [EnumMember(Value = "component")] Component,
    [EnumMember(Value = "created")] Created,
    [EnumMember(Value = "creator")] Creator,
    [EnumMember(Value = "cf")] CustomField,

    /// <summary>
    ///     This field is only available when Jira Service Desk is installed
    /// </summary>
    [EnumMember(Value = "\"Customer Request Type\"")]
    CustomerRequestType,
    [EnumMember(Value = "description")] Description,
    [EnumMember(Value = "due")] Due,
    [EnumMember(Value = "environment")] Environment,
    [EnumMember(Value = "\"epic link\"")] EpicLink,
    [EnumMember(Value = "filter")] Filter,
    [EnumMember(Value = "fixVersion")] FixVersion,
    [EnumMember(Value = "issueKey")] IssueKey,
    [EnumMember(Value = "labels")] Labels,
    [EnumMember(Value = "lastViewed")] LastViewed,
    [EnumMember(Value = "level")] Level,

    [EnumMember(Value = "originalEstimate")]
    OriginalEstimate,
    [EnumMember(Value = "parent")] Parent,
    [EnumMember(Value = "priority")] Priority,
    [EnumMember(Value = "project")] Project,

    [EnumMember(Value = "remainingEstimate")]
    RemainingEstimate,
    [EnumMember(Value = "reporter")] Reporter,

    [EnumMember(Value = "request-channel-type")]
    RequestChannelType,

    [EnumMember(Value = "request-last-activity-time")]
    RequestLastActivityTime,
    [EnumMember(Value = "resolution")] Resolution,
    [EnumMember(Value = "resolved")] Resolved,
    [EnumMember(Value = "sprint")] Sprint,
    [EnumMember(Value = "status")] Status,
    [EnumMember(Value = "summary")] Summary,
    [EnumMember(Value = "text")] Text,
    [EnumMember(Value = "timeSpent")] TimeSpent,
    [EnumMember(Value = "type")] Type,
    [EnumMember(Value = "updated")] Updated,
    [EnumMember(Value = "voter")] Voter,
    [EnumMember(Value = "votes")] Votes,
    [EnumMember(Value = "watcher")] Watcher,
    [EnumMember(Value = "watchers")] Watchers,
    [EnumMember(Value = "worklogAuthor")] WorkLogAuthor,
    [EnumMember(Value = "worklogComment")] WorkLogComment,
    [EnumMember(Value = "worklogDate")] WorkLogDate,
    [EnumMember(Value = "workRatio")] WorkRatio
#pragma warning restore 1591
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:orientation="vertical"
    android:background="@android:color/transparent"
    android:layout_marginBottom="10dp"
   	android:padding="10dp" >

    <ImageView
        android:contentDescription="@string/app_name"
        android:id="@+id/imageview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
       />

    <TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageview1"
        android:layout_marginBottom="15dp"
        android:layout_toRightOf="@+id/imageview1"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#222" />

</RelativeLayout>


text:
// flow-typed signature: a305f3f8ad4cd4b7daa789061956f11a
// flow-typed version: <<STUB>>/realm_v5.0.3/flow_v0.105.2

/**
 * This is an autogenerated libdef stub for:
 *
 *   'realm'
 *
 * Fill this stub out by replacing all the `any` types.
 *
 * Once filled out, we encourage you to share your work with the
 * community by sending a pull request to:
 * https://github.com/flowtype/flow-typed
 */

declare module 'realm' {
  declare module.exports: any;
}

/**
 * We include stubs for each file inside this npm package in case you need to
 * require those files directly. Feel free to delete any files that aren't
 * needed.
 */
declare module 'realm/lib/browser/async-open-task' {
  declare module.exports: any;
}

declare module 'realm/lib/browser/base64' {
  declare module.exports: any;
}

declare module 'realm/lib/browser/collections' {
  declare module.exports: any;
}

declare module 'realm/lib/browser/constants' {
  declare module.exports: any;
}

declare module 'realm/lib/browser' {
  declare module.exports: any;
}

declare module 'realm/lib/browser/lists' {
  declare module.exports: any;
}

declare module 'realm/lib/browser/objects' {
  declare module.exports: any;
}

declare module 'realm/lib/browser/results' {
  declare module.exports: any;
}

declare module 'realm/lib/browser/rpc' {
  declare module.exports: any;
}

declare module 'realm/lib/browser/session' {
  declare module.exports: any;
}

declare module 'realm/lib/browser/subscription' {
  declare module.exports: any;
}

declare module 'realm/lib/browser/user' {
  declare module.exports: any;
}

declare module 'realm/lib/browser/util' {
  declare module.exports: any;
}

declare module 'realm/lib/collection-methods' {
  declare module.exports: any;
}

declare module 'realm/lib/errors' {
  declare module.exports: any;
}

declare module 'realm/lib/extensions' {
  declare module.exports: any;
}

declare module 'realm/lib' {
  declare module.exports: any;
}

declare module 'realm/lib/notification-worker' {
  declare module.exports: any;
}

declare module 'realm/lib/notifier' {
  declare module.exports: any;
}

declare module 'realm/lib/permission-api' {
  declare module.exports: any;
}

declare module 'realm/lib/submit-analytics' {
  declare module.exports: any;
}

declare module 'realm/lib/user-methods' {
  declare module.exports: any;
}

declare module 'realm/lib/worker' {
  declare module.exports: any;
}

declare module 'realm/react-native.config' {
  declare module.exports: any;
}

declare module 'realm/react-native' {
  declare module.exports: any;
}

declare module 'realm/react-native/listview' {
  declare module.exports: any;
}

declare module 'realm/scripts/check-environment' {
  declare module.exports: any;
}

declare module 'realm/scripts/download-realm' {
  declare module.exports: any;
}

declare module 'realm/scripts/handle-license-check' {
  declare module.exports: any;
}

declare module 'realm/scripts/prepublish' {
  declare module.exports: any;
}

declare module 'realm/scripts/react-tests-android' {
  declare module.exports: any;
}

declare module 'realm/scripts/test-ros-server' {
  declare module.exports: any;
}

// Filename aliases
declare module 'realm/lib/browser/async-open-task.js' {
  declare module.exports: $Exports<'realm/lib/browser/async-open-task'>;
}
declare module 'realm/lib/browser/base64.js' {
  declare module.exports: $Exports<'realm/lib/browser/base64'>;
}
declare module 'realm/lib/browser/collections.js' {
  declare module.exports: $Exports<'realm/lib/browser/collections'>;
}
declare module 'realm/lib/browser/constants.js' {
  declare module.exports: $Exports<'realm/lib/browser/constants'>;
}
declare module 'realm/lib/browser/index' {
  declare module.exports: $Exports<'realm/lib/browser'>;
}
declare module 'realm/lib/browser/index.js' {
  declare module.exports: $Exports<'realm/lib/browser'>;
}
declare module 'realm/lib/browser/lists.js' {
  declare module.exports: $Exports<'realm/lib/browser/lists'>;
}
declare module 'realm/lib/browser/objects.js' {
  declare module.exports: $Exports<'realm/lib/browser/objects'>;
}
declare module 'realm/lib/browser/results.js' {
  declare module.exports: $Exports<'realm/lib/browser/results'>;
}
declare module 'realm/lib/browser/rpc.js' {
  declare module.exports: $Exports<'realm/lib/browser/rpc'>;
}
declare module 'realm/lib/browser/session.js' {
  declare module.exports: $Exports<'realm/lib/browser/session'>;
}
declare module 'realm/lib/browser/subscription.js' {
  declare module.exports: $Exports<'realm/lib/browser/subscription'>;
}
declare module 'realm/lib/browser/user.js' {
  declare module.exports: $Exports<'realm/lib/browser/user'>;
}
declare module 'realm/lib/browser/util.js' {
  declare module.exports: $Exports<'realm/lib/browser/util'>;
}
declare module 'realm/lib/collection-methods.js' {
  declare module.exports: $Exports<'realm/lib/collection-methods'>;
}
declare module 'realm/lib/errors.js' {
  declare module.exports: $Exports<'realm/lib/errors'>;
}
declare module 'realm/lib/extensions.js' {
  declare module.exports: $Exports<'realm/lib/extensions'>;
}
declare module 'realm/lib/index' {
  declare module.exports: $Exports<'realm/lib'>;
}
declare module 'realm/lib/index.js' {
  declare module.exports: $Exports<'realm/lib'>;
}
declare module 'realm/lib/notification-worker.js' {
  declare module.exports: $Exports<'realm/lib/notification-worker'>;
}
declare module 'realm/lib/notifier.js' {
  declare module.exports: $Exports<'realm/lib/notifier'>;
}
declare module 'realm/lib/permission-api.js' {
  declare module.exports: $Exports<'realm/lib/permission-api'>;
}
declare module 'realm/lib/submit-analytics.js' {
  declare module.exports: $Exports<'realm/lib/submit-analytics'>;
}
declare module 'realm/lib/user-methods.js' {
  declare module.exports: $Exports<'realm/lib/user-methods'>;
}
declare module 'realm/lib/worker.js' {
  declare module.exports: $Exports<'realm/lib/worker'>;
}
declare module 'realm/react-native.config.js' {
  declare module.exports: $Exports<'realm/react-native.config'>;
}
declare module 'realm/react-native/index' {
  declare module.exports: $Exports<'realm/react-native'>;
}
declare module 'realm/react-native/index.js' {
  declare module.exports: $Exports<'realm/react-native'>;
}
declare module 'realm/react-native/listview.js' {
  declare module.exports: $Exports<'realm/react-native/listview'>;
}
declare module 'realm/scripts/check-environment.js' {
  declare module.exports: $Exports<'realm/scripts/check-environment'>;
}
declare module 'realm/scripts/download-realm.js' {
  declare module.exports: $Exports<'realm/scripts/download-realm'>;
}
declare module 'realm/scripts/handle-license-check.js' {
  declare module.exports: $Exports<'realm/scripts/handle-license-check'>;
}
declare module 'realm/scripts/prepublish.js' {
  declare module.exports: $Exports<'realm/scripts/prepublish'>;
}
declare module 'realm/scripts/react-tests-android.js' {
  declare module.exports: $Exports<'realm/scripts/react-tests-android'>;
}
declare module 'realm/scripts/test-ros-server.js' {
  declare module.exports: $Exports<'realm/scripts/test-ros-server'>;
}


text:
package org.apache.spark.sql.execution.datasources.v2

import java.util.regex.Pattern

import org.apache.spark.internal.Logging
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.sources.DataSourceRegister
import org.apache.spark.sql.sources.v2.{DataSourceV2, SessionConfigSupport}

private[sql] object DataSourceV2Utils extends Logging {

  /**
   * Helper method that extracts and transforms session configs into k/v pairs, the k/v pairs will
   * be used to create data source options.
   * Only extract when `ds` implements [[SessionConfigSupport]], in this case we may fetch the
   * specified key-prefix from `ds`, and extract session configs with config keys that start with
   * `spark.datasource.$keyPrefix`. A session config `spark.datasource.$keyPrefix.xxx -> yyy` will
   * be transformed into `xxx -> yyy`.
   *
   * @param ds a [[DataSourceV2]] object
   * @param conf the session conf
   * @return an immutable map that contains all the extracted and transformed k/v pairs.
   */
  def extractSessionConfigs(ds: DataSourceV2, conf: SQLConf): Map[String, String] = ds match {
    case cs: SessionConfigSupport =>
      val keyPrefix = cs.keyPrefix()
      require(keyPrefix != null, "The data source config key prefix can't be null.")

      val pattern = Pattern.compile(s"^spark\\.datasource\\.$keyPrefix\\.(.+)")

      conf.getAllConfs.flatMap { case (key, value) =>
        val m = pattern.matcher(key)
        if (m.matches() && m.groupCount() > 0) {
          Seq((m.group(1), value))
        } else {
          Seq.empty
        }
      }

    case _ => Map.empty
  }

  def failForUserSpecifiedSchema[T](ds: DataSourceV2): T = {
    val name = ds match {
      case register: DataSourceRegister => register.shortName()
      case _ => ds.getClass.getName
    }
    throw new UnsupportedOperationException(name + " source does not support user-specified schema")
  }
}


text:
import { AbstractComponent, CONSTANTS, utils } from '../..';
import { EVENTS } from './constants';
import playIcon from './play.svg';

/**
 * @private
 */
export class PauseOverlay extends AbstractComponent {

  constructor(plugin) {
    super(plugin.psv, 'psv-video-overlay');

    /**
     * @type {PSV.plugins.VideoPlugin}
     * @private
     * @readonly
     */
    this.plugin = plugin;

    /**
     * @type {HTMLElement}
     * @private
     * @readonly
     */
    this.button = document.createElement('button');
    this.button.className = 'psv-video-bigbutton psv--capture-event';
    this.button.innerHTML = playIcon;
    this.container.appendChild(this.button);

    this.psv.on(CONSTANTS.EVENTS.PANORAMA_LOADED, this);
    this.plugin.on(EVENTS.PLAY, this);
    this.plugin.on(EVENTS.PAUSE, this);
    this.button.addEventListener('click', this);
  }

  /**
   * @private
   */
  destroy() {
    this.psv.off(CONSTANTS.EVENTS.PANORAMA_LOADED, this);
    this.plugin.off(EVENTS.PLAY, this);
    this.plugin.off(EVENTS.PAUSE, this);

    delete this.plugin;

    super.destroy();
  }

  /**
   * @summary Handles events
   * @param {Event} e
   * @private
   */
  handleEvent(e) {
    /* eslint-disable */
    switch (e.type) {
      case CONSTANTS.EVENTS.PANORAMA_LOADED:
      case EVENTS.PLAY:
      case EVENTS.PAUSE:
        utils.toggleClass(this.button, 'psv-video-bigbutton--pause', !this.plugin.isPlaying());
        break;
      case 'click':
        this.plugin.playPause();
        break;
    }
    /* eslint-enable */
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2011 The Android Open Source Project

     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.
-->

<resources>

    <!-- Variation on the Holo Light theme that styles the Action Bar -->
    <style name="Theme.AndroidDevelopers" parent="Theme.Sherlock.Light.ForceOverflow">
        <item name="android:actionBarItemBackground">@drawable/ad_selectable_background</item>
        <item name="actionBarItemBackground">@drawable/ad_selectable_background</item>
        <item name="android:popupMenuStyle">@style/MyPopupMenu</item>
        <item name="popupMenuStyle">@style/MyPopupMenu</item>
        <item name="android:dropDownListViewStyle">@style/MyDropDownListView</item>
        <item name="dropDownListViewStyle">@style/MyDropDownListView</item>
        <item name="android:actionBarTabStyle">@style/MyActionBarTabStyle</item>
        <item name="actionBarTabStyle">@style/MyActionBarTabStyle</item>
        <item name="android:actionDropDownStyle">@style/MyDropDownNav</item>
        <item name="actionDropDownStyle">@style/MyDropDownNav</item>
        <item name="android:listChoiceIndicatorMultiple">@drawable/ad_btn_check_holo_light</item>
        <item name="android:listChoiceIndicatorSingle">@drawable/ad_btn_radio_holo_light</item>
        <!--<item name="android:actionOverflowButtonStyle">@style/MyOverflowButton</item>-->
    </style>

    <!-- style the overflow menu -->
    <style name="MyPopupMenu" parent="Widget.Sherlock.Light.PopupMenu">
        <item name="android:popupBackground">@drawable/ad_menu_dropdown_panel_holo_light</item>
    </style>

    <!-- style the items within the overflow menu -->
    <style name="MyDropDownListView" parent="Widget.Sherlock.ListView.DropDown">
        <item name="android:listSelector">@drawable/ad_selectable_background</item>
    </style>

    <!-- style for the tabs -->
    <style name="MyActionBarTabStyle" parent="Widget.Sherlock.Light.ActionBar.TabBar">
        <item name="android:background">@drawable/actionbar_tab_bg</item>
        <item name="android:paddingLeft">32dp</item>
        <item name="android:paddingRight">32dp</item>
    </style>

    <!-- style the list navigation -->
    <style name="MyDropDownNav" parent="Widget.Sherlock.Light.Spinner.DropDown.ActionBar">
        <item name="android:background">@drawable/ad_spinner_background_holo_light</item>
        <item name="android:popupBackground">@drawable/ad_menu_dropdown_panel_holo_light</item>
        <item name="android:dropDownSelector">@drawable/ad_selectable_background</item>
    </style>

    <!-- the following can be used to style the overflow menu button
         only do this if you have an *extremely* good reason to!! -->
    <!--<style name="MyOverflowButton" parent="Widget.Sherlock.ActionButton.Overflow">
        <item name="android:src">@drawable/ic_menu_view</item>
        <item name="android:background">@drawable/action_button_background</item>
    </style>-->

</resources>


text:
import os
import sys
import socket
import struct
from time import gmtime, strftime

from irclib import ircutils

from irclib import irclib

if __name__=="__main__":

    filelist = {}

    irs = irclib.CollectSession()

    irs.options = ircutils.irc_options()

    irs.open_disk('\\\\.\\PhysicalDrive0')

    if not os.path.exists(irs.options.directory):
        os.makedirs(irs.options.directory)

    workdir = os.path.join(irs.options.directory, socket.gethostname())
    if not os.path.exists(workdir):
        os.makedirs(workdir)

    workdir = os.path.join(workdir, strftime("%Y%m%d_%H-%M-%S", gmtime()))
    if not os.path.exists(workdir):
        os.makedirs(workdir)

    irs.get_mbr()
    if irs.options.standard == True:
        ircutils.write_output(irs.mbr, workdir, 'mbr')

    irs.get_boot_sector()

    if irs.options.standard == True:
        collect_mft(file, boot_sector, options)

    irs.get_filelist()

    if irs.options.standard == True:
        targets = (('/Windows/System32/config/SYSTEM', 'system'),
            ('/Windows/System32/config/SOFTWARE','software'),
            ('/Windows/System32/config/SECURITY','security'),
            ('/Windows/System32/config/SAM','sam'),
            ('/eula.3082.txt','eula.txt'))

        for t in targets():

            found = False

            # FIX = find target without looping through entire list
            for i in irs.filelist:
                if irs.filelist[i]['filename'] == targets(t,0):
                    print irs.filelist[i]['filename'], irs.filelist[i]['data']
                    filename = os.path.join(workdir, targets(t,1))
                    irs.collect_file(irs.filelist[i]['data'], filename)
                    found = True

            if found == False:
                print "Unable to locate: %s" % (targets(t, 0))