text:
class ReminderListsController < ApplicationController
  before_filter :check_librarian

  def initialize
    @reminder_list_statuses = ReminderList.statuses
    @selected_state = @reminder_list_statuses.collect {|s| s[:id]}
    super
  end

  def index
    flash[:reserve_notice] = ""
    unless params[:do_search].blank?
      query = params[:query].to_s.strip
      @query = query.dup
      query = "#{query}*" if query.size == 1

      tmp_state_list = params[:state] || []
      @selected_state = tmp_state_list.collect {|s| s.to_i }
      logger.info @selected_state
      if @selected_state.blank?
        flash[:reserve_notice] << t('item_list.no_list_condition') + '<br />'
      end
      states = nil
    end
    page = params[:page] || 1

    @libraries = Library.find(:all).collect{|i| [ i.display_name, i.id ] }
    @selected_library = params[:library][:id] unless params[:library].blank?
    state_ids = @selected_state
    library = params[:library][:id] if params[:library] and !params[:library][:id].blank?
    date = 1.days.ago.end_of_day
    date = params[:days_overdue].to_i.days.ago.end_of_day if params[:days_overdue]
    unless params[:user_number].blank?
      @user_number = params[:user_number]
      user_number = User.get_user(params[:user_number]).try(:user_number) || @user_number
      @user = User.where(:user_number => user_number).try(:first)
    end
    full_name = @full_name = params[:full_name]
    if full_name && full_name.size == 1
      full_name = "#{full_name}*"
    end
    @days_overdue = params[:days_overdue]

    #puts "user_number=#{@user_number} present?=#{@user_number.present?}"
    #puts "full_name=#{@full_name} present?=#{@full_name.present?}"

    @reminder_lists = ReminderList.search do
      fulltext query
      with(:library_id, library.to_i) if library
      with(:status, state_ids) if state_ids.present?
      without(:checkin, true) if date
      with(:due_date).less_than(date)
      with(:user_number, user_number) if user_number.present?
      if full_name.present?
        fulltext full_name do
          fields(:full_name)
        end
      end

      order_by(:id, :desc) # asc
      paginate :page => page.to_i, :per_page => ReminderList.default_per_page unless params[:output_pdf] or params[:output_tsv]
    end.results

    # output reminder_list (pdf or tsv)
    unless @selected_state.blank?
      if params[:output_pdf]
        data = ReminderList.output_reminder_list_pdf(@reminder_lists)
        send_data data.generate, :filename => Setting.reminder_list_print_pdf.filename; return
      end
      if params[:output_tsv]
        data = ReminderList.output_reminder_list_tsv(@reminder_lists)
        send_data data, :filename => Setting.reminder_list_print_tsv.filename; return
      end
    end

    if params[:output_reminder_report]
      file, filename = ReminderList.output_reminder_report(@user, @reminder_lists)
      if file
        send_data file, :filename => filename; return
      else
        flash[:notice] = t('reminder_list.failed_create_reminder_report')
      end
    end
  end

  def new
    @reminder_list = ReminderList.new
  end

  def edit
    @reminder_list = ReminderList.find(params[:id])
  end

  def show
    @reminder_list = ReminderList.find(params[:id])
  end

  def create
    @reminder_list = ReminderList.new(params[:reminder_list])
    if @reminder_list.save
      flash[:notice] = t('controller.successfully_created', :model => t('activerecord.models.reminder_list'))
      redirect_to(@reminder_list)
    else
      @reminder_list.checkout_id = nil
      render :action => "new"
    end
  end

  def update
    @reminder_list = ReminderList.find(params[:id])
    if @reminder_list.update_attributes(params[:reminder_list])
      flash[:notice] = t('controller.successfully_updated', :model => t('activerecord.models.reminder_list'))
      redirect_to(@reminder_list)
    else
      render :action => "edit"
    end
  end

  def destroy
    @reminder_list = ReminderList.find(params[:id])
    @reminder_list.destroy
    redirect_to(reminder_lists_url)
  end

  def reminder_postal_card
  end

  def reminder_letter
  end

  def output_reminder_postal_card
    user_number = params[:user_number].strip
    # check exit user
    @user = User.where(:user_number => user_number).first
    unless @user
      flash[:notice] = t('reminder_list.no_user')
      render :reminder_postal_card and return
    end
    # check user has over_due_item
    #@reminder_lists = ReminderList.find(:all, :include => [:checkout => :user], :conditions => {:checkouts => {:users => {:user_number => user_number}}})
    @reminder_lists = ReminderList.includes(:checkout => :user).where(users: { user_number: user_number })
    unless @reminder_lists.size > 0
      flash[:notice] = t('reminder_list.no_item')
      render :reminder_postal_card and return
    end

    begin
      # save
      @reminder_lists.each do |reminder_list|
        reminder_list.type1_printed_at = Time.zone.now
        reminder_list.save!
      end
      # output
      make_file(:reminder_postal_card)
      flash[:notice] = t('reminder_list.successfully__output')
      render :reminder_postal_card
    rescue Exception => e
      logger.error "failed #{e}"
      logger.error $@
      flash[:notice] = t('reminder_list.failed_output')
      render :reminder_postal_card and return
    end
  end

  def output_reminder_letter
    user_number = params[:user_number].strip
    # check exit user
    @user = User.where(:user_number => user_number).first
    unless @user
      flash[:notice] = t('reminder_list.no_user')
      render :reminder_letter and return
    end
    # check user has over_due_item
    @reminder_lists = ReminderList.includes(:checkout => :user).where(["users.user_number = ?", user_number])
    unless @reminder_lists.size > 0
      flash[:notice] = t('reminder_list.no_item')
      render :reminder_letter and return
    end

    begin
      # save
      @reminder_lists.each do |reminder_list|
        reminder_list.type2_printed_at = Time.zone.now
        reminder_list.save!
      end
      # output
      make_file(:reminder_letter)
      flash[:notice] = t('reminder_list.successfully__output')
      render :reminder_letter
    rescue Exception => e
      logger.error "failed #{e}"
      flash[:notice] = t('reminder_list.failed_output')
      render :reminder_letter and return
    end
  end

  def download_file
    path = params[:path]
    if File.exist?(path)
      send_file path, :type => "application/pdf", :disposition => 'inline'
      #send_file path, :type => "application/pdf", :disposition => 'attachment'
    else
      logger.warn "not exist file. path:#{path}"
      render :back and return
    end
  end

  def send_reminder
    reminder_lists = ReminderList.where("id in (#{params[:send_reminder].join(',')})") rescue []
    if reminder_lists.empty?
      flash[:message] = t('reminder_list.failed_sent')
    else
      reminder_lists.each do |reminder_list|
        begin
          if checkout = reminder_list.try(:checkout)
            checkout.user.send_message('recall_overdue_item', :manifestations => [checkout.try(:item).try(:manifestation)])
            reminder_list.update_attributes(:status => 1, :mail_sent_at => Time.zone.now)
            flash[:message] = t('reminder_list.successfully_sent')
          end
        rescue Exception => e
          flash[:message] = e
          logger.error e
        end
      end
    end
    redirect_to :action => :index
  end

  private
  def make_file(output_type)
    logger.info "make_file (1)"
    out_dir = "#{Rails.root}/private/system/reminder_lists/"
    FileUtils.mkdir_p(out_dir) unless FileTest.exist?(out_dir)
    logger.info "output=#{output_type} / out_dir=#{out_dir}"

    case output_type
    when :reminder_postal_card
      filename = out_dir + Setting.reminder_postal_card_print.filename
      logger.info "output=#{output_type} / filename=#{filename}"
      ReminderList.output_reminder_postal_card(filename, @reminder_lists, @user, current_user)
      flash[:path] = filename
    when :reminder_letter
      filename = out_dir + Setting.reminder_letter_print.filename
      logger.info "output=#{output_type} / filename=#{filename}"
      ReminderList.output_reminder_letter(filename, @reminder_lists, @user, current_user)
      flash[:path] = filename
    end
  end
end


text:
Android Studio Plugin for gradle building on external tools

This plugin can run tools (e.g. shell, python, perl, etc) with Gradle arguments and tasks, instead of the default gradle build before run.

# Not maintained

This plugin is not working on AS2.2.

I am not planning to fix this for now.

## Requirements

Android Studio >= 1.5, <= 2.1

## Why use this plugin?

This plugin was created to build on Google Compute Engine instead of my slow machine :)

## How to use

### Install

1. Download latest `GradleExternalBuildPlugin.zip` from "Releases".

2. Open Android Studio's Preferences and go to "Plugins".

3. Select "Install plugin from disk..." and install this plugin from `GradleExternalBuildPlugin.zip`.

4. Restart Android Studio.

### Set up and Run

1. Open Preferences and choose "Gradle External Build" in "Build, Execution, Deployment".

2. Set your build program path and Parameters in "Program" and "Parameters".

    You can insert "Macro"s, then macro texts will be replaced with build environment variables.

    In addition to default "Macro"s, you can replace `$GRADLE_ARGS$` and `$GRADLE_TASKS$` with gradle arguments (e.g. `-Pandroid.optional.compilation=INSTANT_DEV,-Pandroid.injected.build.api=21,`) and gradle tasks (e.g. `:app:assembleDebug,:app:assemble,:app:assembleRelease,`) in "Parameters".

3. Select "Edit Configurations..." on configurations button or in "Run" menu.

4. Add new "Android Configuration" and add "Gradle Make on External Tool" to "Before launch" section.

5. Remove "Gradle-aware Make" and set other configuration preferences.

6. Choose created Build Configuration on configurations button.

7. Run.

### Tips

#### Escape

Tasks and arguments text is joined with commas(`,`). If joined variables contain commas, back slashes (`\`) will be added before them.

#### Remote build example Shell script

See `example.sh`.

# License

See `LICENCE.md`.

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Buellia glomerulosa Malme

### Remarks
null


text:
Distributed Neural Networks for Spark.
Details are available in the [paper](http://arxiv.org/abs/1511.06051).

## Using SparkNet
To run SparkNet, you will need a [Spark](http://spark.apache.org) cluster.
SparkNet apps can be run using [spark-submit](http://spark.apache.org/docs/latest/submitting-applications.html).

### Quick Start
**Start a Spark cluster using our AMI**

1. Create an AWS secret key and access key. Instructions [here](http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSGettingStartedGuide/AWSCredentials.html).
2. Run `export AWS_SECRET_ACCESS_KEY=` and `export AWS_ACCESS_KEY_ID=` with the relevant values.
3. Clone our repository locally.
4. Start a 5-worker Spark cluster on EC2 by running

        SparkNet/ec2/spark-ec2 --key-pair=key --identity-file=key.rsa --region=eu-west-1 --zone=eu-west-1c --instance-type=g2.8xlarge --ami=ami-c0dd7db3 -s 5 --copy-aws-credentials --spark-version 1.5.0 --spot-price 1.5 --no-ganglia --user-data SparkNet/ec2/cloud-config.txt launch sparknet
assuming `key.rsa` is your key pair.

**Train Cifar using SparkNet**

1. SSH to the Spark master as `root`.
2. Run `/root/SparkNet/caffe/data/cifar10/get_cifar10.sh` to get the Cifar data
3. Train Cifar on 5 workers using

        /root/spark/bin/spark-submit --class apps.CifarApp /root/SparkNet/target/scala-2.10/sparknet-assembly-0.1-SNAPSHOT.jar 5
4. That's all! Information is logged on the master in `/root/training_log*.txt`.

### Dependencies
For now, you have to install the following.
We have an AMI with these dependencies already installed (ami-c0dd7db3).
Dependencies:

1. sbt 0.13 - [installation instructions](http://www.scala-sbt.org/0.13/tutorial/Installing-sbt-on-Linux.html)
2. cuda 7.0 - [installation instructions](http://docs.nvidia.com/cuda/cuda-getting-started-guide-for-linux/#axzz3sjNgyLGA)
3. lmdb - `apt-get install liblmdb-dev` (optional, only if you want to use LMDB)
4. leveldb - `apt-get install libleveldb-dev` (optional, only if you want to use LevelDB)

### Setup

**On EC2:**

1. For each worker node, create one volume (e.g., 100GB) and attach it to the worker (e.g., for instance, at `/dev/sdf`)

**On the master:**

1. Clone the SparkNet repository.
2. Set the `SPARKNET_HOME` environment variable to the SparkNet directory.
3. Build Caffe by running the following:

        cd $SPARKNET_HOME
        mkdir build
        cd build
        cmake ../libccaffe
        make -j 30
4. Increase the Java heap space with `export _JAVA_OPTIONS="-Xmx8g"`.
5. Run `mkdir /tmp/spark-events` (Spark does some logging there).
6. Build SparkNet by doing:

        cd $SPARKNET_HOME
        sbt assembly

**On each worker:**

1. Clone the SparkNet repository.
2. Set the `SPARKNET_HOME` environment variable to the SparkNet directory.
3. Build Caffe as on the master.
4. Run `mount /dev/xvdf /mnt2/spark` to mount the volume you created earlier (assuming you attached the volume at `/dev/sdf`). Spark will spill data to disk here. If everything fits in memory, then this may not be necessary.

### Example Apps
#### Cifar

To run CifarApp, do the following:

1. First get the Cifar data with

        $SPARKNET_HOME/caffe/data/cifar10/get_cifar10.sh
2. Set the correct value of `sparkNetHome` in `src/main/scala/apps/CifarApp.scala`.
3. Then submit the job with `spark-submit`

        $SPARK_HOME/bin/spark-submit --class apps.CifarApp SparkNetPreview/target/scala-2.10/sparknetpreview-assembly-0.1-SNAPSHOT.jar 5

#### ImageNet
To run ImageNet, do the following:

1.  Obtain the ImageNet data by following the instructions [here](http://www.image-net.org/download-images). This involves creating an account and submitting a request.
2. Put the training and test data on S3 (see instructions in this [issue](https://github.com/amplab/SparkNet/issues/59)).
3. On the master, create `~/.aws/credentials` with the following content:

        [default]
        aws_access_key_id=
        aws_secret_access_key=
4. Set the correct value of `sparkNetHome` in `src/main/scala/apps/ImageNetApp.scala`.
5. Submit a job on the master with

        spark-submit --class apps.ImageNetApp $SPARKNET_HOME/target/scala-2.10/sparknet-assembly-0.1-SNAPSHOT.jar n
where `n` is the number of worker nodes in your Spark cluster.

## The SparkNet Architecture
SparkNet is a deep learning library for Spark.
Here we describe a bit of the design.
### Calling Caffe from Java and Scala
We use [Java Native Access](https://github.com/java-native-access/jna) to call C code from Java.
Since Caffe is written in C++, we first create a C wrapper for Caffe in `libccaffe/ccaffe.cpp` and `libccaffe/ccaffe.h`.
We then create a Java interface to the C wrapper in `src/main/java/libs/CaffeLibrary.java`.
This library could be called directly, but the easiest way to use it is through the `CaffeNet` class in `src/main/scala/libs/Net.scala`.

To enable Caffe to read data from Spark RDDs, we define a `JavaDataLayer` in `caffe/include/caffe/data_layers.hpp` and `caffe/src/caffe/layers/java_data_layer.cpp`.

### Defining Models
A model is specified in a `NetParameter` object, and a solver is specified in a `SolverParameter` object.
These can be specified directly in Scala, for example:
```
val netParam = NetParam ("LeNet",
  RDDLayer("data", shape=List(batchsize, 1, 28, 28), None),
  RDDLayer("label", shape=List(batchsize, 1), None),
  ConvolutionLayer("conv1", List("data"), kernel=(5,5), numOutput=20),
  PoolingLayer("pool1", List("conv1"), pooling=Pooling.Max, kernel=(2,2), stride=(2,2)),
  ConvolutionLayer("conv2", List("pool1"), kernel=(5,5), numOutput=50),
  PoolingLayer("pool2", List("conv2"), pooling=Pooling.Max, kernel=(2,2), stride=(2,2)),
  InnerProductLayer("ip1", List("pool2"), numOutput=500),
  ReLULayer("relu1", List("ip1")),
  InnerProductLayer("ip2", List("relu1"), numOutput=10),
  SoftmaxWithLoss("loss", List("ip2", "label"))
)
```
Conveniently, they can be loaded from Caffe prototxt files:

```
val sparkNetHome = sys.env("SPARKNET_HOME")
var netParameter = ProtoLoader.loadNetPrototxt(sparkNetHome + "/caffe/models/bvlc_reference_caffenet/train_val.prototxt")
netParameter = ProtoLoader.replaceDataLayers(netParameter, trainBatchSize, testBatchSize, channels, croppedHeight, croppedWidth)
val solverParameter = ProtoLoader.loadSolverPrototxtWithNet(sparkNetHome + "/caffe/models/bvlc_reference_caffenet/solver.prototxt", netParameter, None)
```
The third line modifies the `NetParameter` object to read data from a `JavaDataLayer`.
A `CaffeNet` object can then be created from a `SolverParameter` object:
```
val net = CaffeNet(solverParameter)
```


text:
educational
===========

Educational code samples for my students. It is completely free for anyone to use them as instructional materials.


text:
class PrinTable

    def initialize(style = :simple)
        @default_style = style
    end

    # TODO add pagination

    #
    # example:  puts pt.print(['a', 'b', 'c'], [['11', '22', '33'], ['444', '555', '666'], ['7777', nil, '8888']])
    def print(headers, data, style = @default_style)
        a_headers = headers || @header_cache
        a_data = data || @data_cache

        result = print_table(a_headers, a_data, style)

        @header_cache = a_headers
        @data_cache = a_data

        result
    end

    def print_table(headers, data, style = nil)
        case style
        when :raw
            print_raw_table(headers, data)
        when :simple
            print_simple_table(headers, data)
        when :db
            row_count = 0
            print_fmt_table(headers, data, {}, lambda { |row| row_count += 1 }) + [ "#{row_count} row(s)" ]
        else
            print_simple_table(headers, data)
        end
    end

    def print_simple_table(headers, data, &aggregator)

        print_fmt_table(headers, data, { v: " ", sh: false, pl: 0, pr: 0 }, aggregator)
    end

    def print_raw_table(headers, data)
        result = []

        unless headers.nil?
            result << headers.join(" ")
        end

        result += data.find_all { |row| !row.nil? and row != [] }.map { |row| row.join " " }
        result
    end

    def print_fmt_table(headers, data, fmt = {}, aggregator = nil)
        # pl - padding left, pr - padding right, sh: separate headers
        default_fmt = { node: "+", h: "-", v: "|", pl: 1, pr: 1, sh: true }
        fmt = default_fmt.merge fmt

        def print_fmt_row(row, lengths, deco)
            fmt = lengths.map { |l| "#{' ' * deco[:pl]}%#{l}s#{' ' * deco[:pr]}" }.join(deco[:v])
            frow = (0...lengths.length).map { |i| row[i] || "" }
            (fmt % frow).gsub(/\s*$/, "")
        end

        def print_fmt_separator(lengths, deco)
            fmt = lengths.map { |l| "#{deco[:h] * deco[:pl]}%#{l}s#{deco[:h] * deco[:pr]}" }.join(deco[:node])
            frow = lengths.map { |l| deco[:h] * l }
            fmt % frow
        end

        # if headers are empty or not specified, we leave them out
        local_headers = ((headers.nil? or headers.length == 0) ? [] : [headers])
        local_data = local_headers + data
        field_count = max_field_count(local_data)

        if field_count > 0
            field_lengths = (0...field_count).map { |field_idx| max_field_length(local_data, field_idx) }

            result = []
            if local_headers.length > 0
                result << print_fmt_row(headers, field_lengths.map { |x| x * -1 }, fmt)
                result << print_fmt_separator(field_lengths, fmt) if fmt[:sh]
            end

            result += data.map { |row|
                aggregator.yield row unless aggregator.nil?
                print_fmt_row(row, field_lengths.map { |x| x * -1 }, fmt)
            }
        else
            []
        end
    end

    def max_field_count(data)
        if data.nil? or !data.kind_of?(Array)
            0
        else
            data.collect { |row| (row || []).length }.max || 0
        end
    end

    def max_field_length(data, idx)
        data.map { |row| row[idx].to_s.length }.max || 0
    end
end


text:
[![Build Status](https://travis-ci.org/hapijs/glue.svg)](https://travis-ci.org/hapijs/glue)

Lead Maintainer - [Chris Rempel](https://github.com/csrl)

### A server composer for hapi.js.

Glue provides configuration based composition of hapi's Server object. Specifically it wraps

 * `server = new Hapi.Server(Options)`
 * one or more `server.connection(Options)`
 * zero or more `server.register(Plugin, Options)`

calling each based on the configuration generated from the Glue manifest.

### Interface

Glue's [API](API.md) is a single function `compose` accepting a JSON `manifest` file specifying the hapi server options, connections, and registrations.

### hapi version dependency

Glue can support different versions of hapi. Adding support for a new version of hapi is considered a `minor` change. Removing support for a version of hapi is considered a `major` change.

By default NPM will resolve Glue's dependency on hapi using the most recent supported version of hapi. To force a specific supported hapi version for your project, include hapi in your package dependencies along side of Glue.

Glue currently supports hapi **11**, **12**, **13**, **14**, **15**, and **16**.


text:
layout: post
title: Berlin, Germany
excerpt: "Prost!"
modified: 2016-05-12
tags: [posts, travel]
comments: true
image:
  feature: berlin/header_berlin.png
---

Overview

*  Auto generated table of contents
{:toc}

## Willkommen in Berlin
In February I traveled to Berlin for the first time and it has easily become my favorite European city travelled to thus far. I'm writing this post in May, so some details are hazy. Berlin is just so rich in history which is evident everywhere in the city. You don't need to go to a museum or read about it in a book. All of the past is right in front of you, ripe for the picking. Yet interleaved with the carefully chosen unrestored bullet-hole ridden walls, the sidewalk memorials to Holocaust victims, and remnants of the Berlin wall and the Cold war is a thriving and advanced city, hustling and bustling with intellectuals, politicians, technologists, and hipsters. I think there's more to be said about the city, but for now I'll move on. There's so much I didn't get to see in the 3 days I was there, so I hope to visit again soon.

## Orientation of Berlin
Berlin is a pretty big city, especially compared to the cities I've travelled to in the past. I would advise that you prepare a general itinerary so that you don't spend too much time on the U-Bahn. In my opinion, the historical East Berlin sector has some of the most interesting sights to see and you can spend 1-2 days just there. Museum Island, so called because it is an island filled with 5 different museums, holds interesting artifacts as well as the impressive Ishtar Gate and bust of Nephrotite. We only travelled to West Berlin a couple of times to go to restaurants out there.

## Travelling to Berlin

### When to go
Travelling in **February** meant it was still technically low-season in Berlin, but we didn't encounter any closures due to the timeframe. But like Lisbon, this meant there were few crowds and rarely any lines. It was definitely a chilly trip, but what else can you expect when you travel to northern Germany in February?
The weather was mostly bright and sunny, with temperatures around 40-50F.

### How to get there
There are quick and inexpensive flights to Berlin from Stansted served by most budget airlines. The flight itself is around 2.5 hours. We flew into Berlin Schonefeld ("Beautiful field") which unfortunately is on the outskirts of the city. You will need to take the S-Bahn into the city center (most likely Hackescher Markt or Alexanderplatz) and then transfer to the U-bahn after that. There are clearly marked zones which apply to the type of train ticket you buy. I highly suggest buying the train ticket as soon as you find an opinion ticket machine because the ticket line on the platform took over 30 minutes.

### Where to stay
Since we were traveling during the low season, there were many deals at hotels that would otherwise be expensive. We stayed at the Monbijou Hotel located in the Hackesher Markt which was extremely convenient. It's a short walk to three major U-bahn stations that serve different lines. Our walking tour also started just outside of the hotel. There are also plenty of cafes, supermarket, and restaurants (perhaps not so authentically German, but good nonetheless) just outside of the hotel.

### Public Transportation
Berlin is a large city, so I would plan out where you want to go beforehand. Also, download an offline map of the U-Bahn to get an idea of where you'd like to go. Make sure you buy and validate your ticket, because plain-clothes officers will regularly check your ticket on board. I would recommend getting a day-pass on the U-Bahn. It's worth the price and is less hassle then buying a ticket each time.

## Things to do
Instead of a 3-day itinerary, I've listed the must-sees in Berlin.

*  Walking Tour: A walking tour is always a great way to get an orientation to the city. This particular tour gave an in depth history and view.

* Visit the  Reichstag: The Reichstag was/is the seat of the German government, but has only recently been since the late 1999 after reunification. Prior to that, government was held in Bonn and East Berlin. There is free entry and audio tour of the Reichstag, but you do need to register in advance. I highly recommend visiting -- the dome provides an impressive views of the city and an excellent audio guide. And again... it's free.

* Museum Island: You could realistically spend a whole day on Museum Island, visiting each of the individual museums.

* See the Berlin Wall Memorial: See remnants of the Berlin Wall including guard tower and the no-man's land.

* Take a tour of an underground bunker used for civilians in WWII: http://berliner-unterwelten.de/guided-tours.3.1.html

* Enjoy Currywurst in Berlin at  Curry 61, the birthplace this delicious street food. We may have had it three times in one day...

* Enjoy an authentic German dinner at  Dicke Wirtin in West Germany

* Enjoy a Bavarian German dinner at Weihenstephaner

## Travel Tips!
* This applies to any travel where a cellular data connection isn't available: download an offline Google Map of the city. GPS still works and having a live map is incredibly helpful
* If you are a student, bring your student ID or proof of enrollment for discounts to museums and tours.
* Rick Steve's snapshot guidebook is a great resource to read before and during the trip


text:
To create collision animation effect, you'll need to create a single collision
animator.

## Code
### Objective-C
#### 1) Create an animator for the view controller
```
@interface ViewController ()

@property UIDynamicAnimator *animator;
@property UICollisionBehavior *collision;

@end
```

#### 2) Initialize both animator and behaviors in viewDidLoad, once.
```
- (void)viewDidLoad {
    self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];

    self.collision = [[UICollisionBehavior alloc] init];
    self.collision.translatesReferenceBoundsIntoBoundary = YES;
    [self.animator addBehavior:self.collision];

    [super viewDidLoad];
}

```

#### 3) To add the animation to object, you can use ```addItem``` method
```
    // i) Create view to be animated
    UIView *block = [[UIView alloc] initWithFrame:CGRectMake(self.xPosition,
                                                             self.yPosition,
                                                             self.blockSize,
                                                             self.blockSize)];
    block.backgroundColor = [self generateRandomColor];
    [self.view addSubview:block]; //view must be added before behavior addition

    // ii) Add the view into gravity animator
    [self.collision addItem:block];
```

#### 4) Test it
![Collision After Fall](https://lh3.googleusercontent.com/uAkjHPUNEmBcHBTaEqwU1Nb4mw8TbpS_Z_pUK9vNHg77TMCY6btAim8m6Ezu_cHA1dEGhjIQ1xEBMPE2-8v3Mvw2K6snj8GN-nLgWQ3UfCFKEQliAjzRZiAMTE6r2I9QOQlJoZgCwwhU-nPN8JKV8ZecjD7NawXdtNd4-rUawe2Rzpn66JI0gRws_aFIWFH8rQ6M8VWi3O0aAZCfMvn6-AFILiaB2LQqYYmW4ncf8I56z1NBD8z_YV0c1CnABVZAWKWraHP3hKS9j9apa0IUYaWQHjzuk4-JhG30Mh7gGkzYMZl3HQGmPxL3vBU2dol6D86n_eCFVuE64zu_p1WCf3LRkX5IU8CIgUO_O2X55aGQRi3L5zKVDM91dd9wMRY7vnwN_atuVx551mal0mXMe4-sq2pHZugKmR0kOYrDdMSGego2wryF3YXvG5txFxjNr6t3JJrdKUS55tHgzS_d7y5TTo6ekYvzXtdhTZZhoBkUSYDwfZK50ft7-F3sgrk7s739NK5E8pJjL1AE-RL6FqJenDPz6J5Jq1Xltzrpz4kv6SUYfdo0i77x8Wtnpeh8VFOxdA=w480-h885-no)

## References
1. https://www.raywenderlich.com/50197/uikit-dynamics-tutorial
2. http://www.ios-blog.co.uk/tutorials/objective-c/ios-7-how-to-use-uigravitybehavior/
3. http://www.teehanlax.com/blog/introduction-to-uikit-dynamics/
4. https://www.objc.io/issues/5-ios7/collection-views-and-uidynamics/


text:
#pragma once

#ifdef NSTATIC
#	define PRO_EXPORTS __declspec(dllexport)
#else
#	define PRO_EXPORTS
#endif

#ifdef NSTATIC
#	define PRO_C_EXTERN extern "C" __declspec(dllexport)
#else
#	define PRO_C_EXTERN extern "C"
#endif

#if defined(NSTATIC)
#define BOOST_ALL_DYN_LINK
#endif

// testƒvƒƒWƒFƒNƒg'É'ÄLogger'ð•\Ž¦'·'邽'߂̐錾
#define TEST_MESSAGE

#include<string>
#include<ctime>
#include<vector>
#include<opencv2\core\core.hpp>

using std::vector;
using std::string;

/*****************************
 *  warning
 */

// warning C4251 class 'std::basic_string<_Elem,_Traits,_Alloc>' 'Í __export ƒL[ƒ[ƒh'ðŽg'Á'Ä class 'pro::Dir' 'ɃGƒNƒXƒ|[ƒg'µ'Ä''¾'³'¢B
template class PRO_EXPORTS std::basic_string<char, std::char_traits<char>, std::allocator<char> >;

// warning C4251 class 'std::vector<_Ty>' 'Í __export ƒL[ƒ[ƒh'ðŽg'Á'Ä class 'pro::Timer' 'ɃGƒNƒXƒ|[ƒg'µ'Ä''¾'³'¢B
// http://support.microsoft.com/default.aspx?scid=kb;ja-jp;168958
// Timer.h
template class PRO_EXPORTS std::vector<clock_t>;
template class PRO_EXPORTS std::vector<std::string>;
template class PRO_EXPORTS std::vector<int>;
template class PRO_EXPORTS std::vector<short>;
template class PRO_EXPORTS std::vector<cv::Point>;
template class PRO_EXPORTS cv::Point_<float>;
template class PRO_EXPORTS std::vector<cv::Point_<float>>;


text:
<?php

Class signinController Extends baseController {

	public function index(){
        $this->registry->template->signin_index = 'welcome in the signin page';

	if(isset($_SESSION['user']) ){
    	        $this->registry->template->show('category_index');
	}
else
{
    if($_SERVER['REQUEST_METHOD'] != 'POST'){
        $this->registry->template->show('signin_index');
	}
    else
    {	$_POST = array_map('trim', $_POST);
        $errors = array();

        if(empty($_POST['user_name']))
        {
            $errors[] = 'The username field must cannot be empty.';
        }

        if(empty($_POST['user_pass']))
        {
            $errors[] = 'The password field must cannot be empty.';
        }

        if(!empty($errors))
        {
            echo 'Uh-oh.. a couple of fields are not filled in correctly..';
            echo '
';
            foreach($errors as $key => $value)
            {
                echo '
' . $value . '
';
            }
            echo '
';
					header('Refresh: 3; url=/signin');
        }
        else
        {
        $db = new db;
		$db->Connection();
		$db = $db->getConnection();

    	$name = ($_POST['user_name']);
		$pass = ($_POST['user_pass']);

            $sql = "SELECT
                        author_id,
                        author_name,
                        author_level
                    FROM
                        author
                    WHERE
                        author_name = :name
                    AND
                        author_pass = :pass";

			$stmt = $db->prepare($sql);
			$stmt->bindParam (':name', $name, PDO::PARAM_STR);
			$stmt->bindParam (':pass', $pass, PDO::PARAM_STR);

            $stmt->execute();
			$result = $stmt->fetchAll();
            //print_r ($result);
            if(!isset($result))
            {
                echo 'Something went wrong while signing in. Please try again later.';
            }
            else{
                if(count($result) == 0){
                    echo 'You have supplied a wrong user/password combination. Please try again.';
					header('Refresh: 3; url=signin');
                }
                else
                {
                    $_SESSION['user'] = array(

                        'author_id' => $result[0]['author_id'],
                        'author_name'  => $result[0]['author_name'],
                        'author_level' => $result[0]['author_level'],
                        );

                       header('Refresh: 0; url=/category');
                }
            }
        }
    }
}

	}
}
?>


text:
class InRange extends Thread {
	@java.lang.SuppressWarnings("all")
	@javax.annotation.Generated("lombok")
	private static final Integer $JAVA_LANG_INTEGER_5 = 5;
	@java.lang.SuppressWarnings("all")
	@javax.annotation.Generated("lombok")
	private static final Integer $JAVA_LANG_INTEGER_10 = 10;
	@java.lang.SuppressWarnings("all")
	@javax.annotation.Generated("lombok")
	private static final Double $JAVA_LANG_DOUBLE_5 = 5.0;
	@java.lang.SuppressWarnings("all")
	@javax.annotation.Generated("lombok")
	private static final Double $JAVA_LANG_DOUBLE_10 = 10.0;
	@java.lang.SuppressWarnings("all")
	@javax.annotation.Generated("lombok")
	private static final java.util.Date $JAVA_UTIL_DATE_2015_01_01_00_00_00 = new java.text.SimpleDateFormat("yyyy-MM-dd\'T\'HH:mm:ss").parse("2015-01-01T00:00:00", new java.text.ParsePosition(0));
	@java.lang.SuppressWarnings("all")
	@javax.annotation.Generated("lombok")
	private static final java.util.Date $JAVA_UTIL_DATE_2016_01_01_00_00_00 = new java.text.SimpleDateFormat("yyyy-MM-dd\'T\'HH:mm:ss").parse("2016-01-01T00:00:00", new java.text.ParsePosition(0));

	static class Inner {

		static double sameName;
	}

	InRange(@com.develhack.annotation.assertion.InRange(from = "5", to = "10") int arg1) {
		com.develhack.Conditions.checkInRange("arg1", arg1, 5, 10);
		System.out.println(arg1);
	}

	InRange(@com.develhack.annotation.assertion.InRange(from = "5", to = "10") Integer arg1) {
		com.develhack.Conditions.checkInRange("arg1", arg1, $JAVA_LANG_INTEGER_5, $JAVA_LANG_INTEGER_10);
		System.out.println(arg1);
	}

	InRange(@com.develhack.annotation.assertion.InRange(from = "5", to = "10") double arg1) {
		com.develhack.Conditions.checkInRange("arg1", arg1, 5.0, 10.0);
		System.out.println(arg1);
	}

	InRange(@com.develhack.annotation.assertion.InRange(from = "5", to = "10") Double arg1) {
		com.develhack.Conditions.checkInRange("arg1", arg1, $JAVA_LANG_DOUBLE_5, $JAVA_LANG_DOUBLE_10);
		System.out.println(arg1);
	}

	InRange(@com.develhack.annotation.assertion.InRange(from = "2015-01-01T00:00:00", to = "2016-01-01T00:00:00") String arg1) {
		System.out.println(arg1);
	}

	InRange(@com.develhack.annotation.assertion.InRange(from = "5", to = "10") double arg1, @com.develhack.annotation.assertion.InRange(from = "2015-01-01T00:00:00", to = "2016-01-01T00:00:00") java.util.Date arg2) {
		this(String.valueOf(com.develhack.Conditions.checkInRange("arg1", arg1, 5.0, 10.0)));
		com.develhack.Conditions.checkInRange("arg2", arg2, $JAVA_UTIL_DATE_2015_01_01_00_00_00, $JAVA_UTIL_DATE_2016_01_01_00_00_00);
		System.out.println(arg1);
		System.out.println(arg2);
	}

	InRange(@com.develhack.annotation.assertion.InRange(from = "5", to = "10") double arg1, @com.develhack.annotation.assertion.InRange(from = "2015-01-01T00:00:00", to = "2016-01-01T00:00:00") java.util.Date arg2, @com.develhack.annotation.assertion.InRange(from = "5", to = "10") double sameName) {
		super(String.valueOf(Inner.sameName));
		com.develhack.Conditions.checkInRange("sameName", sameName, 5.0, 10.0);
		com.develhack.Conditions.checkInRange("arg2", arg2, $JAVA_UTIL_DATE_2015_01_01_00_00_00, $JAVA_UTIL_DATE_2016_01_01_00_00_00);
		com.develhack.Conditions.checkInRange("arg1", arg1, 5.0, 10.0);
		System.out.println(arg1);
		System.out.println(arg2);
		System.out.println(sameName);
	}

	public void method1(@com.develhack.annotation.assertion.InRange(from = "5", to = "10") double arg1) {
		com.develhack.Conditions.checkInRange("arg1", arg1, 5.0, 10.0);
		System.out.println(arg1);
	}

	public void method2(@com.develhack.annotation.assertion.InRange(from = "5", to = "arg2") double arg1, double arg2) {
		com.develhack.Conditions.checkInRange("arg1", arg1, 5.0, arg2);
		System.out.println(arg1);
		System.out.println(arg2);
	}

	public void method3(double arg1, @com.develhack.annotation.assertion.InRange(from = "Double.MIN_VALUE", to = "Double.MAX_VALUE") double arg2) {
		com.develhack.Conditions.checkInRange("arg2", arg2, Double.MIN_VALUE, Double.MAX_VALUE);
		System.out.println(arg1);
		System.out.println(arg2);
	}

	public void method4(@com.develhack.annotation.assertion.InRange(from = "5", to = "10") Object arg1) {
		System.out.println(arg1);
	}
	@com.develhack.annotation.assertion.InRange(from = "-1", to = "1")
	private int hasSetter;
	@com.develhack.annotation.assertion.InRange(from = "-1", to = "1")
	private int hasNoAnnotationOnSetter;
	@com.develhack.annotation.assertion.InRange(from = "-1", to = "1")
	private int hasDifferentValuesOnSetter;

	public void setHasSetter(@com.develhack.annotation.assertion.InRange(from = "-1", to = "1") int hasSetter) {
		com.develhack.Conditions.checkInRange("hasSetter", hasSetter, -1, 1);
	}

	public void setHasNoAnnotationOnSetter(int hasSetter) {
	}

	public void setHasDifferentValuesOnSetter(@com.develhack.annotation.assertion.InRange(from = "-1", to = "2") int hasSetter) {
		com.develhack.Conditions.checkInRange("hasSetter", hasSetter, -1, 2);
	}
}


text:
package com.blazebit.persistence.view.impl;

import com.blazebit.persistence.ParameterHolder;
import com.blazebit.persistence.parser.expression.ExpressionFactory;
import com.blazebit.persistence.parser.predicate.Predicate;
import com.blazebit.persistence.view.CorrelationBuilder;
import com.blazebit.persistence.view.CorrelationProvider;
import com.blazebit.persistence.view.CorrelationProviderFactory;

import java.util.Map;
import java.util.Set;

/**
 * A static correlation provider implementation.
 *
 * @author Christian Beikov
 * @since 1.2.0
 */
public class StaticCorrelationProvider implements CorrelationProvider, CorrelationProviderFactory {

    private final Class<?> correlated;
    private final String correlationKeyAlias;
    private final int approximateExpressionSize;
    private final Predicate correlationPredicate;
    private final Set<String> rootAliases;

    public StaticCorrelationProvider(Class<?> correlated, String correlationKeyAlias, String correlationExpression, Predicate correlationPredicate, Set<String> rootAliases) {
        this.correlated = correlated;
        this.correlationKeyAlias = correlationKeyAlias;
        this.approximateExpressionSize = correlationExpression.length() * 2;
        this.correlationPredicate = correlationPredicate;
        this.rootAliases = rootAliases;
    }

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

    @Override
    public CorrelationProvider create(ParameterHolder<?> parameterHolder, Map<String, Object> optionalParameters) {
        return this;
    }

    public Predicate getCorrelationPredicate() {
        return correlationPredicate;
    }

    @Override
    public void applyCorrelation(CorrelationBuilder correlationBuilder, String correlationExpression) {
        String alias = correlationBuilder.getCorrelationAlias();

        ExpressionFactory expressionFactory = correlationBuilder.getService(ExpressionFactory.class);
        PrefixingQueryGenerator prefixingQueryGenerator = new PrefixingQueryGenerator(expressionFactory, alias, correlationExpression, correlationKeyAlias, rootAliases, true, false);
        StringBuilder sb = new StringBuilder(approximateExpressionSize);
        prefixingQueryGenerator.setQueryBuffer(sb);
        correlationPredicate.accept(prefixingQueryGenerator);
        String finalExpression = sb.toString();

        correlationBuilder.correlate(correlated).onExpression(finalExpression).end();
    }

}


text:
package org.hibernate.test.annotations.idmanytoone.alphabetical;
import java.io.Serializable;
import javax.persistence.Embeddable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

@Embeddable
public class CId implements Serializable {

	@ManyToOne
	@JoinColumn( name = "aId", nullable = false )
	private A parent;

	private int sequenceNumber;

	public CId() {
	}

	public A getParent() {
		return parent;
	}

	public void setParent(A parent) {
		this.parent = parent;
	}

	public int getSequenceNumber() {
		return sequenceNumber;
	}

	public void setSequenceNumber(int sequenceNumber) {
		this.sequenceNumber = sequenceNumber;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ( ( parent == null ) ? 0 : parent.hashCode() );
		result = prime * result + sequenceNumber;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if ( this == obj )
			return true;
		if ( obj == null )
			return false;
		if ( getClass() != obj.getClass() )
			return false;
		final CId other = (CId) obj;
		if ( parent == null ) {
			if ( other.parent != null )
				return false;
		}
		else if ( !parent.equals( other.parent ) )
			return false;
		if ( sequenceNumber != other.sequenceNumber )
			return false;
		return true;
	}

}


text:
layout: page
title: "Robert Ballard Surles"
comments: true
description: "blanks"
keywords: "Robert Ballard Surles,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: College of Architecture and Planning

**Classes taught**: ENVD 4023, ENVD 4794

#### ENVD 4023: ENVIR IMPACT ASSESSMENT

**Terms taught**: Fall 2006

**Instructor rating**: 5.77

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 3.84

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 2.71

**Standard deviation in workload** (raw): 0.0

#### ENVD 4794: HIST URB DESIGN/PLNNG

**Terms taught**: Fall 2006

**Instructor rating**: 5.74

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 3.72

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 2.58

**Standard deviation in workload** (raw): 0.0


text:
from conary.lib import cfg

from rmake.build import buildcfg
from rmake.lib import apiutils

class _TroveSettingsRegister(type):
    def __init__(class_, *args, **kw):
        type.__init__(class_, *args, **kw)
        apiutils.register_freezable_classmap('TroveSettings', class_)

class TroveSettings(cfg.ConfigFile, buildcfg.FreezableConfigMixin):
    __metaclass__ = _TroveSettingsRegister

    def __init__(self):
        cfg.ConfigFile.__init__(self)
        buildcfg.FreezableConfigMixin.__init__(self)


text:
var Parser = require('./../Parser.js'),
    should = require('should')

describe('Parser Module', function(){

    describe('sync version', function(){

        var parser
        beforeEach(function(){
            parser = Parser.sync()

        })
        describe('regex method', function(){

            var expected, output

            beforeEach(function(){
                expected = 'foo'
                parser.regex(expected)
                output = parser.regex()
            })

            it('should get/set internal regex with arguments', function(){
                should(output).eql(expected)
            })

        })

        describe('when ran', function(){
            describe('before a regex test is set', function(){
                describe('with an argument', function(){

                    var output, testArg

                    beforeEach(function(){
                        testArg = 'foo'
                        output = parser(testArg)
                    })
                    it('should return null', function(){
                        should(output).not.be.ok
                    })
                })
                describe('without an argument', function(){
                    it('should return null', function(){

                        var output

                        beforeEach(function(){
                            output = parser()
                        })
                        it('should return null', function(){
                            should(output).not.be.ok
                        })

                    })
                })

            })
            describe('after a regex test is set', function(){
                describe('with an argument', function(){

                    var output, testArg, testRegex, observedArg,
                        expected

                    beforeEach(function(){

                        expected = 'bar'

                        testArg = 'foo'

                        testRegex = {
                            'parse': function(arg){
                                observedArg = arg
                                return 'bar'
                            }
                        }

                        parser.regex(testRegex)

                        output = parser(testArg)
                    })

                    it('should call parse method on regex with given string', function(){

                        should(observedArg).eql(testArg)

                    })
                    it('should return output of parse', function(){
                        should(output).eql(expected)
                    })
                })
                describe('without an argument', function(){
                    var output, testArg, testRegex, observedArg,
                        expected

                    beforeEach(function(){

                        testRegex = {
                            'parse': function(arg){
                                observedArg = arg
                                return 'bar'
                            }
                        }

                        parser.regex(testRegex)

                        output = parser()
                    })
                    it('should return null', function(){
                        should(output).not.be.ok
                    })
                })

            })

        })

    })

})


text:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using IOER.classes;
using IOER.Library;
using ILPathways.Utilities;

namespace IOER
{
    public partial class PageNotFound : BaseAppPage
    {
        protected void Page_Load( object sender, EventArgs e )
        {
            string exType = "";
            string reason = "";
            string originalUrl = "";
            string errorSourcePage = "Error originated on: " + this.GetRequestKeyValue( "ErrorPage", "Unknown" );
            string url = "";
            string reqUrl = "";
            string remoteIP = "";
            string sessionId = "";
            string userid = "";

            string errorUrl = this.GetSessionItem( "AppErrorUrl" );
            if ( errorUrl.Length > 0 )
            {
                int endPos = 0;
                int pos = errorUrl.ToLower().IndexOf( "nroriginalurl=" );
                if ( pos > -1 )
                {
                    originalUrl = errorUrl.Substring( pos + 14 );
                    endPos = originalUrl.ToLower().IndexOf( "&" );

                    if ( endPos > -1 )
                        originalUrl = errorUrl.Substring( 0, endPos );
                }
            }

            try
            {
                url = Request.Url.ToString();
                reqUrl = Request.UserHostAddress;
                remoteIP = Request.ServerVariables[ "REMOTE_HOST" ];
                if ( Session.SessionID != null || Session.SessionID != "" )
                {
                    sessionId = Session.SessionID.ToString();
                }
                userid = SessionManager.GetCurrentUserName( Session );

                Object obj = Session[ "AppError" ];
                if ( obj == null )
                {
                    exType = "none";
                }
                else
                {
                    Exception ex = obj as Exception;
                    exType = ex.GetType().ToString();
                    reason = ex.Message.ToString();

                }
            }
            catch
            {
                //no request object - continue
            }

            if ( exType == "System.ArgumentOutOfRangeException" )
            {
                //Probable obsolete page
                reason = "The requested page no longer exists. If you arrived at the page in error via a saved link, then you should remove the link.";
            }

            if ( reason.Length > 0 )
            {
                lblInfo.Text = "Additional Information:" + "
";
                lblInfo.Text += errorSourcePage + "
";
                lblInfo.Text += exType + "
";
                lblInfo.Text += reason + "
";
            }

            string serverName = UtilityManager.GetAppKeyValue( "serverName", "" );
            lblInfo.Text += "
Server: " + serverName;

            try
            {
                url = Server.UrlDecode( url );
                string parmsString = "";
                if ( url.IndexOf( "?" ) > -1 )
                {
                    parmsString = url.Substring( url.IndexOf( "?" ) );
                    url = url.Substring( 0, url.IndexOf( "?" ) - 1 );
                }

                //log error page
                //may not want to e-mail as source condition should have already done so
                LoggingHelper.LogPageVisit( sessionId, "errorPage.aspx", url, parmsString, false, userid, "", reason, remoteIP, "" );
            }
            catch
            {
                //ignore errors
            }
        }
    }
}


text: import display, button


text:
package file

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"sync"

	"github.com/pierrre/imageserver"
)

// Cache is a implementation of disk based cache system.
type Cache struct {
	Path string
	mu   sync.RWMutex
}

// Get implements imageserver/cache.Cache.
func (cache *Cache) Get(key string, params imageserver.Params) (*imageserver.Image, error) {
	if cache.Path == "" {
		return nil, fmt.Errorf("file cache path is not")
	}
	cache.mu.RLock()
	defer cache.mu.RUnlock()
	data, err := cache.getData(key)
	if err != nil {
		return nil, err
	}
	if data == nil {
		return nil, nil
	}
	im := new(imageserver.Image)
	if err := im.UnmarshalBinaryNoCopy(data); err != nil {
		return nil, err
	}
	return im, nil
}

func (cache *Cache) getData(key string) ([]byte, error) {
	item, err := ioutil.ReadFile(filepath.Join(cache.Path, key))
	if os.IsNotExist(err) {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return item, nil
}

// Set implements imageserver/cache.Cache.
func (cache *Cache) Set(key string, im *imageserver.Image, params imageserver.Params) error {
	cache.mu.Lock()
	defer cache.mu.Unlock()
	data, err := im.MarshalBinary()
	if err != nil {
		return err
	}
	return cache.setData(key, data)
}

func (cache *Cache) setData(key string, data []byte) error {
	return ioutil.WriteFile(filepath.Join(cache.Path, key), data, 0644)
}


text:
package zj.servlet.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Lzj Created on 2016/3/1.
 */
public class Servlet01 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取自定义ServletContext中设置的属性
        String author = (String) req.getServletContext().getAttribute("author");
        System.err.println(author);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}


text:
package com.ajjpj.adiagram_.geometry

import javafx.geometry.Insets

/**
 * @author arno
 */
case class ARect(topLeft: APoint, dim: ADim) extends GeometricShape {
  def topRight    = topLeft + ((dim.width, .0))
  def bottomLeft  = topLeft + ((.0, dim.height))
  def bottomRight = topLeft + ((dim.width, dim.height))

  def width = dim.width
  def height = dim.height

  def center = topLeft halfWayTo bottomRight

  def withPadding(padding: Double): ARect = withPadding(padding, padding)
  def withPadding(hPadding: Double, vPadding: Double): ARect = withPadding(hPadding, vPadding, hPadding, vPadding)
  def withPadding(leftPadding: Double, topPadding: Double, rightPadding: Double, bottomPadding: Double): ARect = ARect(topLeft - ((leftPadding, topPadding)), ADim(dim.width + leftPadding + rightPadding, dim.height + topPadding + bottomPadding))
  def withPadding(insets: Insets): ARect = withPadding (insets.getLeft, insets.getTop, insets.getRight, insets.getBottom)

  override def contains(p: APoint) =
    topLeft.x <= p.x && topLeft.x+dim.width  >= p.x &&
    topLeft.y <= p.y && topLeft.y+dim.height >= p.y

  override def toString = "ARect{" + topLeft + ", dim " + dim + "}"

  private def segmentIntersectionVertical(p1: APoint, p2: APoint, x: Double, y3: Double, y4: Double): Option[APoint] = {
    if(x < Math.min(p1.x, p2.x) || x > Math.max(p1.x, p2.x)) {
      None
    }
    else {
      val det = (p1.x - p2.x)*(y3 - y4)
      if (det == 0.0) {
        None
      }
      else {
        val y_res = ((p1.x*p2.y - p1.y*p2.x)*(y3 - y4) - x*(p1.y - p2.y)*(y4 - y3)) / det

        if(y_res >= Math.min(y3, y4) && y_res <= Math.max(y3, y4))
          Some(APoint(x, y_res))
        else
          None
      }
    }
  }

  private def segmentIntersectionHorizontal(p1: APoint, p2: APoint, x3: Double, x4: Double, y: Double): Option[APoint] = {
    if(y < Math.min(p1.y, p2.y) || y > Math.max(p1.y, p2.y)) {
      None
    }
    else {
      val det = -(x3 - x4)*(p1.y - p2.y)
      if (det == 0.0) {
        None
      }
      else {
        val x_res = ((p1.x*p2.y - p1.y*p2.x)*(x3 - x4) - y*(p1.x - p2.x)*(x3 - x4)) / det

        if(x_res >= Math.min(x3, x4) && x_res <= Math.max(x3, x4))
          Some(APoint(x_res, y))
        else
          None
      }
    }
  }

  def intersection(inside: APoint, outside: APoint) = {
    val result: APoint =
    segmentIntersectionHorizontal (inside, outside, topLeft.x,         topLeft.x + width, topLeft.y).getOrElse (
    segmentIntersectionHorizontal (inside, outside, topLeft.x,         topLeft.x + width, topLeft.y + height).getOrElse (
    segmentIntersectionVertical   (inside, outside, topLeft.x,         topLeft.y        , topLeft.y + height).getOrElse (
    segmentIntersectionVertical   (inside, outside, topLeft.x + width, topLeft.y        , topLeft.y + height).getOrElse (
    inside // fallback
    ))))

    result
  }
}

object ARect {
  def apply(p0: APoint, p1: APoint): ARect = createWithPadding(0, p0, p1)
  def apply(p: APoint, width: Double, height: Double): ARect = ARect(p, ADim(width, height))

  def fromCoordinates(x0: Double, y0: Double, x1: Double, y1: Double) = apply(APoint(x0, y0), APoint(x1, y1))

  def createWithPadding(padding: Double, p0: APoint, p1: APoint): ARect = {
    val minX = Math.min(p0.x, p1.x) - padding
    val maxX = Math.max(p0.x, p1.x) + padding
    val minY = Math.min(p0.y, p1.y) - padding
    val maxY = Math.max(p0.y, p1.y) + padding

    new ARect(APoint(minX, minY), ADim(maxX-minX, maxY-minY))
  }

  def containingRect(rects: Iterable[ARect]) = {
    if(rects.isEmpty) {
      ARect(APoint.ZERO, 0, 0)
    }
    else {
      var minX = Double.MaxValue
      var maxX = Double.MinValue
      var minY = Double.MaxValue
      var maxY = Double.MinValue

      rects.foreach(r => {
        minX = Math.min(minX, r.topLeft.x)
        maxX = Math.max(maxX, r.bottomRight.x)
        minY = Math.min(minY, r.topLeft.y)
        maxY = Math.max(maxY, r.bottomRight.y)
      })

      fromCoordinates(minX, minY, maxX, maxY)
    }
  }
}


text:
layout: media
title: "Taeyeon SNSD"
modified:
categories: media
excerpt:
tags: []
image:
  feature: taeyeon-1600x800.jpg
  teaser: taeyeon-400x250.jpg
  thumb:
  credit: elapaint
  creditlink: http://www.elapaint.com
ads: false
date: 2014-02-01
---


text:
package org.apache.sysds.runtime.functionobjects;

/**
 * Abstraction for comparison (relational) operators in order to
 * force a proper implementation by all relevant subclasses.
 */
public abstract class ValueComparisonFunction extends ValueFunction
{
	private static final long serialVersionUID = 6021132561216734747L;

	public abstract boolean compare(double in1, double in2);

	public abstract boolean compare(long in1, long in2);

	public abstract boolean compare(boolean in1, boolean in2);

	public abstract boolean compare(String in1, String in2);
}


text:
DECLARE_WINDOW_PROPERTY_TYPE(ui::WindowShowState)

namespace ash {
namespace internal {

namespace {

// Used to remember the show state before the window was minimized.
DEFINE_WINDOW_PROPERTY_KEY(
    ui::WindowShowState, kRestoreShowStateKey, ui::SHOW_STATE_DEFAULT);

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// WorkspaceLayoutManager, public:

WorkspaceLayoutManager::WorkspaceLayoutManager(
    aura::RootWindow* root_window,
    WorkspaceManager* workspace_manager)
    : BaseLayoutManager(root_window),
      workspace_manager_(workspace_manager) {
}

WorkspaceLayoutManager::~WorkspaceLayoutManager() {
}

void WorkspaceLayoutManager::OnWindowResized() {
  // Workspace is updated via OnRootWindowResized.
}

void WorkspaceLayoutManager::OnWindowAddedToLayout(aura::Window* child) {
  BaseLayoutManager::OnWindowAddedToLayout(child);
  if (!workspace_manager_->IsManagedWindow(child))
    return;

  if (child->IsVisible()) {
    workspace_manager_->AddWindow(child);
  } else if (wm::IsWindowNormal(child)) {
    // Align non-maximized/fullscreen windows to a grid.
    SetChildBoundsDirect(
        child, workspace_manager_->AlignBoundsToGrid(child->GetTargetBounds()));
  }
}

void WorkspaceLayoutManager::OnWillRemoveWindowFromLayout(
    aura::Window* child) {
  workspace_manager_->RemoveWindow(child);
  BaseLayoutManager::OnWillRemoveWindowFromLayout(child);
}

void WorkspaceLayoutManager::OnChildWindowVisibilityChanged(
    aura::Window* child,
    bool visible) {
  if (!workspace_manager_->IsManagedWindow(child))
    return;
  if (visible) {
    if (wm::IsWindowMinimized(child)) {
      // Attempting to show a minimized window. Unminimize it.
      child->SetProperty(aura::client::kShowStateKey,
                         child->GetProperty(kRestoreShowStateKey));
      child->ClearProperty(kRestoreShowStateKey);
    }
    workspace_manager_->AddWindow(child);
  } else {
    workspace_manager_->RemoveWindow(child);
  }
}

void WorkspaceLayoutManager::SetChildBounds(
    aura::Window* child,
    const gfx::Rect& requested_bounds) {
  if (GetTrackedByWorkspace(child))
    BaseLayoutManager::SetChildBounds(child, requested_bounds);
  else
    SetChildBoundsDirect(child, requested_bounds);
  workspace_manager_->UpdateShelfVisibility();
}

void WorkspaceLayoutManager::OnMonitorWorkAreaInsetsChanged() {
  // The workspace is currently the only one that updates the shelf, so we can
  // safely ignore this. If we don't there are timing issues when transitioning
  // between maximized/fullscreen windows and normal windows.
}

void WorkspaceLayoutManager::OnWindowPropertyChanged(aura::Window* window,
                                                     const void* key,
                                                     intptr_t old) {
  BaseLayoutManager::OnWindowPropertyChanged(window, key, old);
  if (key == aura::client::kShowStateKey &&
      workspace_manager_->IsManagedWindow(window)) {
    ShowStateChanged(window, static_cast<ui::WindowShowState>(old));
  } else if (key == ash::kWindowTrackedByWorkspaceSplitPropKey &&
             ash::GetTrackedByWorkspace(window)) {
    // We currently don't need to support transitioning from true to false, so
    // we ignore it.
    workspace_manager_->AddWindow(window);
  }
}

void WorkspaceLayoutManager::ShowStateChanged(
    aura::Window* window,
    ui::WindowShowState last_show_state) {
  if (wm::IsWindowMinimized(window)) {
    // Save the previous show state so that we can correctly restore it.
    window->SetProperty(kRestoreShowStateKey, last_show_state);
    workspace_manager_->RemoveWindow(window);
    SetWindowVisibilityAnimationType(
        window, WINDOW_VISIBILITY_ANIMATION_TYPE_MINIMIZE);

    // Hide the window.
    window->Hide();
    // Activate another window.
    if (wm::IsActiveWindow(window))
      wm::DeactivateWindow(window);
    return;
  }
  // We can end up here if the window was minimized and we are transitioning
  // to another state. In that case the window is hidden.
  if ((window->TargetVisibility() ||
       (last_show_state == ui::SHOW_STATE_MINIMIZED)) &&
      !workspace_manager_->IsManagingWindow(window)) {
    workspace_manager_->AddWindow(window);
    if (!window->layer()->visible()) {
      // The layer may be hidden if the window was previously minimized. Make
      // sure it's visible.
      window->Show();
    }
    return;
  }
  workspace_manager_->ShowStateChanged(window);
}

}  // namespace internal
}  // namespace ash


text:
"use strict";
(function (FileAsMapping) {
    FileAsMapping[FileAsMapping["None"] = 0] = "None";
    FileAsMapping[FileAsMapping["SurnameCommaGivenName"] = 1] = "SurnameCommaGivenName";
    FileAsMapping[FileAsMapping["GivenNameSpaceSurname"] = 2] = "GivenNameSpaceSurname";
    FileAsMapping[FileAsMapping["Company"] = 3] = "Company";
    FileAsMapping[FileAsMapping["SurnameCommaGivenNameCompany"] = 4] = "SurnameCommaGivenNameCompany";
    FileAsMapping[FileAsMapping["CompanySurnameGivenName"] = 5] = "CompanySurnameGivenName";
    FileAsMapping[FileAsMapping["SurnameGivenName"] = 6] = "SurnameGivenName";
    FileAsMapping[FileAsMapping["SurnameGivenNameCompany"] = 7] = "SurnameGivenNameCompany";
    FileAsMapping[FileAsMapping["CompanySurnameCommaGivenName"] = 8] = "CompanySurnameCommaGivenName";
    FileAsMapping[FileAsMapping["SurnameGivenNameSuffix"] = 9] = "SurnameGivenNameSuffix";
    FileAsMapping[FileAsMapping["SurnameSpaceGivenNameCompany"] = 10] = "SurnameSpaceGivenNameCompany";
    FileAsMapping[FileAsMapping["CompanySurnameSpaceGivenName"] = 11] = "CompanySurnameSpaceGivenName";
    FileAsMapping[FileAsMapping["SurnameSpaceGivenName"] = 12] = "SurnameSpaceGivenName";
    FileAsMapping[FileAsMapping["DisplayName"] = 13] = "DisplayName";
    FileAsMapping[FileAsMapping["GivenName"] = 14] = "GivenName";
    FileAsMapping[FileAsMapping["SurnameGivenNameMiddleSuffix"] = 15] = "SurnameGivenNameMiddleSuffix";
    FileAsMapping[FileAsMapping["Surname"] = 16] = "Surname";
    FileAsMapping[FileAsMapping["Empty"] = 17] = "Empty";
})(exports.FileAsMapping || (exports.FileAsMapping = {}));
var FileAsMapping = exports.FileAsMapping;


text:
<?php

namespace BingAds\CampaignManagement;

/**
 * Defines an object that you can use to determine the component of an ad extension that failed editorial review, and the reason for the failure.
 *
 * @link http://msdn.microsoft.com/en-us/library/jj134398(v=msads.90).aspx AdExtensionEditorialReason Data Object
 *
 * @used-by AdExtensionEditorialReasonCollection
 */
final class AdExtensionEditorialReason
{
    /**
     * The component of the ad extension that failed editorial review.
     *
     * @var string
     */
    public $Location;
    /**
     * The list of publisher countries whose editorial guidelines do not allow the specified term.
     *
     * @var string[]
     */
    public $PublisherCountries;
    /**
     * A code that identifies the reason for the failure.
     *
     * @var int
     */
    public $ReasonCode;
    /**
     * The term that failed editorial review.
     *
     * @var string
     */
    public $Term;
}


text:
/**
 * Instructions for the validation controller's validate method.
 */
export interface ValidateInstruction {
    /**
     * The object to validate.
     */
    object: any;
    /**
     * The property to validate. Optional.
     */
    propertyName?: any;
    /**
     * The rules to validate. Optional.
     */
    rules?: any;
}


text:
#ifndef OBJ_H
#define OBJ_H

#include <stdlib.h>
#include <string.h>

#include "util.h"

/*
 * obj.h
 *
 * Object definition, creation and modification functions.
 */

typedef enum {
    NUMBER,
    BOOL,
    CHAR,
    STRING,
    NIL,
    PAIR,
    SYMBOL,
    MAP,
    PROC_NATIVE,
    PROC_COMPOUND,
    ENV
} obj_type;

typedef struct obj_t* (*proc)(struct obj_t*);

typedef struct obj_t env;    // env is a list of scopes.

struct map_t;

typedef struct obj_t {
    obj_type type;
    union {
        double num_value;
        int bool_value;
        char char_value;
        char* string_value;
        char* symbol_value;
        struct map_t* map_value;
        struct {
            struct obj_t* car;
            struct obj_t* cdr;
        } pair;
        struct {
            char* name;
            proc call;
        } proc_native;
        struct {
            char* name;
            struct obj_t* arg_list;
            struct obj_t* body;
            env* env;
        } proc_compound;
    };
} obj;

obj* new_obj(obj_type type);

obj* clone_obj(obj*);

void del_obj(obj*);

obj* new_number(double input);

void del_number(obj*);

obj* new_boolean(int input);

obj* new_char(char input);

void del_char(obj*);

obj* new_string(char* input);

void del_string(obj*);

obj* new_omap();

void del_omap(obj*);

obj* new_proc(char*, proc);

obj* new_compound_proc(char*, obj*, obj*, env*);

obj* cons(obj*, obj*);

void del_list(obj*);

obj* car(obj*);

obj* cdr(obj*);

int list_len(obj*);

#define caar(obj) car(car(obj))
#define cadr(obj) car(cdr(obj))
#define cdar(obj) cdr(car(obj))
#define cddr(obj) cdr(cdr(obj))
#define caaar(obj) car(car(car(obj)))
#define caadr(obj) car(car(cdr(obj)))
#define cadar(obj) car(cdr(car(obj)))
#define caddr(obj) car(cdr(cdr(obj)))
#define cdaar(obj) cdr(car(car(obj)))
#define cdadr(obj) cdr(car(cdr(obj)))
#define cddar(obj) cdr(cdr(car(obj)))
#define cdddr(obj) cdr(cdr(cdr(obj)))

obj* new_symbol(char* input);

int is_equal(obj*, obj*);

#endif


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace TCPServer
{
	public class CompositeDisposable : IDisposable
	{
		public CompositeDisposable()
		{

		}
		public List<IDisposable> Children
		{
			get; set;
		} = new List<IDisposable>();
		public void Dispose()
		{
			foreach(var c in Children)
				c.Dispose();
		}
	}
}


text:
--------------------------------
-- @function [parent=#CardinalSplineBy] clone
-- @param self
-- @return CardinalSplineBy#CardinalSplineBy ret (return value: cc.CardinalSplineBy)

--------------------------------
-- @function [parent=#CardinalSplineBy] updatePosition
-- @param self
-- @param #point_table point

--------------------------------
-- @function [parent=#CardinalSplineBy] reverse
-- @param self
-- @return CardinalSplineBy#CardinalSplineBy ret (return value: cc.CardinalSplineBy)

--------------------------------
-- @function [parent=#CardinalSplineBy] CardinalSplineBy
-- @param self

return nil


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

  <title>standard.lib.str.StrReplace</title>
  <link href="css/style.css" rel="stylesheet" type="text/css">
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >

    Concept Framework 2.2 documentation
  	Contents | Index

standard.lib.str.StrReplace

     Name
     Version
     Deprecated

     StrReplace
     version 1.0
     no

Prototype:

string StrReplace(string String_to_look, string replace_source, string replace_with);

Description:

Replaces every replace_source in String_to_look with the replace_with.

Returns:

Returns the obtained string.

Documented by Eduard Suica, generation time: Sun Jan 27 18:15:13 2013
 GMT	(c)2013 Devronium Applications


text:
module HarvestTracker

  class Client
    attr_reader :subdomain

    def initialize(subdomain)
      @subdomain = subdomain
    end

    def credentials
      @credentials ||= Credentials.new
    end

    def connection
      @connection ||= Connection.new subdomain, credentials
    end

    def timesheet(date = Date.today)
      unless @current_date == date
        @current_date = date
        @timesheet = Timesheet.new(date).tap {|timesheet| timesheet.client = self}
      end

      @timesheet
    end
  end

end


text:
dofile('test/test-lib/init/no-suite.lua')

local run_tests,
      make_suite
      = import 'lua-nucleo/suite.lua'
      {
        'run_tests',
        'make_suite'
      }

assert(pcall(function() make_suite() end) == false)

--------------------------------------------------------------------------------

local parameters_list = {}
parameters_list.seed_value = 123456

--------------------------------------------------------------------------------
-- TODO: don't use global variables in suite tests
-- https://github.com/lua-nucleo/lua-nucleo/issues/5

assert(
  not is_declared("suite_tests_results"),
  "global suite_tests_results variable already declared"
)
declare("suite_tests_results")

--------------------------------------------------------------------------------
-- test, case, run
do
  suite_tests_results =
  {
    to_call =
    {
      ["1"] = true,
      ["2"] = true,
      ["3"] = true
    },
    next_i = 1
  }
  local nok, errs = run_tests(
      { "test/data/suite/simple-test-1.lua" },
      parameters_list
    )

  assert(nok == 1, "1 tests must be successfull")
  assert(#errs == 0, "0 test must be fail")
  assert(suite_tests_results.to_call['1'] == nil, "to_call['1'] must be nil")
  assert(suite_tests_results.next_i == 2, "next_i must equals 2")
end

do
  suite_tests_results =
  {
    to_call =
    {
      ["1"] = true,
      ["2"] = true,
      ["3"] = true
    },
    next_i = 1
  }
  local nok, errs = run_tests(
      { "test/data/suite/simple-test-2.lua" },
      parameters_list
    )

  assert(nok == 0, "0 tests must be successfull")
  assert(#errs == 1, "1 test must be fail")
  assert(
      errs[1].err:find(
          "Suite `simple%-test%-2' failed:\n"
       .. " %* Test `2':(.-) this error is expected\n"
        ) ~= nil,
      "expected fail message must match"
    )
  assert(suite_tests_results.next_i == true, "next_i must be true")
  assert(next(suite_tests_results.to_call) == nil, "to_call must be empty")
end

-- run_tests, fail_on_first_error
do
  local names =
  {
    "test/data/suite/expected-error-suite.lua",
    "test/data/suite/no-error-suite.lua"
  }

  local parameters_list = {}
  parameters_list.seed_value = 123456

  --missing fail_on_first_error, default is false
  local nok, errs = run_tests(names, parameters_list)
  assert(nok == 1)

  parameters_list.fail_on_first_error = true
  local nok, errs = run_tests(names, parameters_list)
  assert(nok == 0)

  parameters_list.fail_on_first_error = false
  local nok, errs = run_tests(names, parameters_list)
  assert(nok == 1)
end

print("------> Simple suite tests suite PASSED")


text:
from appartment import Appartment
import codecs
import sys

def preprocessData1(filename_input, filename_output="foo.txt"):
	f = codecs.open(filename_input, 'rU', 'utf-8')
	f_out = codecs.open(filename_output, 'w+', 'utf-8')
	new_data = []
	for line in f:
		appartment = parseLine(line)
		new_line = appartment.preprocessData1()
		if len(new_line) == 9:
			new_line = u'	'.join(new_line)
			f_out.write(new_line)
			f_out.write(u'\n')
	f.close()
	f_out.close()

def parseLine(line):
	array = line.split("	")
	#print repr(array).decode("unicode-escape")
	address = array[0]
	metro = array[1]
	transportation = array[2]
	rooms = array[3]
	space = [array[4], array[5], array[6]]
	price = array[7]
	floor = array[8]
	addInfo = array[9]
	appartment = Appartment(address, metro, transportation, rooms, space, price, floor, addInfo)
	return appartment

if __name__ == "__main__":
	filename_input = str(sys.argv[1])
	filename_output = str(sys.argv[2])
	preprocessData1(filename_input, filename_output)
	print "Done"


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE121_Stack_Based_Buffer_Overflow__CWE806_char_alloca_snprintf_16.c
Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE806.label.xml
Template File: sources-sink-16.tmpl.c
*/
/*
 * @description
 * CWE: 121 Stack Based Buffer Overflow
 * BadSource:  Initialize data as a large string
 * GoodSource: Initialize data as a small string
 * Sink: snprintf
 *    BadSink : Copy data to string using snprintf
 * Flow Variant: 16 Control flow: while(1)
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#ifdef _WIN32
#define SNPRINTF _snprintf
#else
#define SNPRINTF snprintf
#endif

#ifndef OMITBAD

void CWE121_Stack_Based_Buffer_Overflow__CWE806_char_alloca_snprintf_16_bad()
{
    char * data;
    char * dataBuffer = (char *)ALLOCA(100*sizeof(char));
    data = dataBuffer;
    while(1)
    {
        /* FLAW: Initialize data as a large buffer that is larger than the small buffer used in the sink */
        memset(data, 'A', 100-1); /* fill with 'A's */
        data[100-1] = '\0'; /* null terminate */
        break;
    }
    {
        char dest[50] = "";
        /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
        SNPRINTF(dest, strlen(data), "%s", data);
        printLine(data);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() - use goodsource and badsink by changing the conditions on the while statements */
static void goodG2B()
{
    char * data;
    char * dataBuffer = (char *)ALLOCA(100*sizeof(char));
    data = dataBuffer;
    while(1)
    {
        /* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */
        memset(data, 'A', 50-1); /* fill with 'A's */
        data[50-1] = '\0'; /* null terminate */
        break;
    }
    {
        char dest[50] = "";
        /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
        SNPRINTF(dest, strlen(data), "%s", data);
        printLine(data);
    }
}

void CWE121_Stack_Based_Buffer_Overflow__CWE806_char_alloca_snprintf_16_good()
{
    goodG2B();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE121_Stack_Based_Buffer_Overflow__CWE806_char_alloca_snprintf_16_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE121_Stack_Based_Buffer_Overflow__CWE806_char_alloca_snprintf_16_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
#region license
// ==============================================================================
// Infrastructure Application Block
// ==============================================================================
// Copyright © 2017 Ihar Yakimush
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
// ==============================================================================
#endregion --------------------------------------------------------------------------------------------------------------------

using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Security;

[assembly: AssemblyTitle("Infrastructure Application Block - Tests")]
[assembly: AssemblyDescription("Infrastructure Application Block - Tests")]

//[assembly: SecurityTransparent]
[assembly: SecurityCritical]

[assembly: AssemblyVersion("1.0.1.0")]
[assembly: AssemblyFileVersion("1.0.1.0")]

[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]


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

import org.activiti.bpmn.model.BaseElement;
import org.activiti.bpmn.model.ParallelGateway;
import org.activiti.engine.impl.bpmn.parser.BpmnParse;

/**
 * @author Joram Barrez
 */
public class ParallelGatewayParseHandler extends AbstractActivityBpmnParseHandler<ParallelGateway> {

  public Class<? extends BaseElement> getHandledType() {
    return ParallelGateway.class;
  }

  protected void executeParse(BpmnParse bpmnParse, ParallelGateway gateway) {
    gateway.setBehavior(bpmnParse.getActivityBehaviorFactory().createParallelGatewayActivityBehavior(gateway));
  }

}


text:
package org.apache.hyracks.dataflow.std.sort.buffermanager;

public interface IFrameFreeSlotPolicy {

    /**
     * Find the best fit frame id which can hold the data, and then pop it out from the index.
     * Return -1 is failed to find any.
     *
     * @param tobeInsertedSize the actual size of the data which should include
     *                         the meta data like the field offset and the tuple
     *                         count extra size
     * @return the best fit frame id
     */
    int popBestFit(int tobeInsertedSize);

    /**
     * Register the new free slot into the index
     *
     * @param frameID
     * @param freeSpace
     */
    void pushNewFrame(int frameID, int freeSpace);

    /**
     * Clear all the existing free slot information.
     */
    void reset();

}


text:
import {EventEmitter, Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class HeaderService {
    visible$ = new BehaviorSubject(false);
    onSearch = new BehaviorSubject<string>('');
    onSearchReset = new EventEmitter();
    shareDashboardEmitter = new EventEmitter();
    gotoZenDeepSeeEmitter = new EventEmitter();
    mobileFilterToggle = new EventEmitter<boolean>();
    mobileFilterDialogToggle = new EventEmitter();

    // onSetTitle = new BehaviorSubject<string>('');

    constructor() {

    }

    resetSearch() {
        this.onSearchReset.emit();
    }

    shareDashboard() {
        this.shareDashboardEmitter.emit();
    }

    gotoZenDeepSee() {
        this.gotoZenDeepSeeEmitter.emit();
    }

    showMobileFilterButton() {
        this.mobileFilterToggle.emit(true);
    }

    hideMobileFilterButton() {
        this.mobileFilterToggle.emit(false);
    }

    toggleMobileFilterDialog() {
        this.mobileFilterDialogToggle.emit();
    }
}


text:
package org.example.domain;

import io.ebean.Model;

import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.UUID;

@Entity
public class Content extends Model {

  @Id
  UUID id;

  String name;

  public Content(String name) {
    this.name = name;
  }

  public UUID getId() {
    return id;
  }

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

  public String getName() {
    return name;
  }

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


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using libtcod;
using Magecrawl.Utilities;

namespace Magecrawl.GameUI.SkillTree
{
    internal class SkillTreeTabXMLHelper
    {
        private SkillTreeTab m_tabLoading;

        // Square is 7x7, 4 between columns, 2 between rows
        private const int SquareSize = 7;
        private const int OffsetToCenterOfSize = 3;
        private const int GapBetweenColumns = 4;
        private const int GapBetweenRows = 2;
        private const int ColumnOffSetPer = SquareSize + GapBetweenColumns;
        private const int RowOffSetPer = SquareSize + GapBetweenRows;

        private int m_maxRow;
        private int m_largestColumn;
        private int m_largestRow;

        private List<Pair<Point, string>> m_iconTextLines;

        internal SkillTreeTabXMLHelper(SkillTreeTab tabLoading)
        {
            m_iconTextLines = new List<Pair<Point, string>>();

            m_largestColumn = int.MinValue;
            m_largestRow = int.MinValue;

            m_tabLoading = tabLoading;
        }

        private Point CalculatePosition(int column, int row)
        {
            if (row > m_maxRow)
                throw new InvalidOperationException("SkillTreeTabXMLHelper - Row larger than max row?");

            // Row count from the bottom to make adding new elements on top of tree easier
            // | (0,1)    (1,1)
            // | (0,0)    (1,0)
            // ------------------
            return new Point(column * ColumnOffSetPer, (m_maxRow - row) * RowOffSetPer);
        }

        private void HandleNewPoint(int column, int row)
        {
            m_largestColumn = Math.Max(m_largestColumn, column);
            m_largestRow = Math.Max(m_largestRow, row);
        }

        public void LoadMappings(string resourceToRead)
        {
            XMLResourceReaderBase.ParseFile(Path.Combine("Skill Tree", resourceToRead), ReadFileCallback);

            int width = m_largestColumn * ColumnOffSetPer + SquareSize;
            int height = m_largestRow * RowOffSetPer + SquareSize;
            m_tabLoading.CharArray = new char[width, height];
            m_tabLoading.Width = width;
            m_tabLoading.Height = height;

            DrawCharArray();
        }

        private void SetChar(Point p, char c)
        {
            m_tabLoading.CharArray[p.X, p.Y] = c;
        }

        private void DrawCharArray()
        {
            // Draw squares
            foreach (SkillSquare s in m_tabLoading.SkillSquares)
            {
                SetChar(s.UpperLeft, (char)TCODSpecialCharacter.NW);
                SetChar(s.UpperLeft + new Point(6,0), (char)TCODSpecialCharacter.NE);
                SetChar(s.UpperLeft + new Point(0,6), (char)TCODSpecialCharacter.SW);
                SetChar(s.UpperLeft + new Point(6,6), (char)TCODSpecialCharacter.SE);
                for (int i = 1 ; i < SquareSize - 1 ; i++)
                {
                    SetChar(s.UpperLeft + new Point(i, 0), (char)TCODSpecialCharacter.HorzLine);
                    SetChar(s.UpperLeft + new Point(i, SquareSize - 1), (char)TCODSpecialCharacter.HorzLine);

                    SetChar(s.UpperLeft + new Point(0, i), (char)TCODSpecialCharacter.VertLine);
                    SetChar(s.UpperLeft + new Point(SquareSize - 1, i), (char)TCODSpecialCharacter.VertLine);
                }
            }

            // Draw text
            foreach (Pair<Point, string> textBlob in m_iconTextLines)
            {
                int i = 0;
                foreach (char c in textBlob.Second)
                {
                    SetChar(textBlob.First + new Point(i, 0), c);
                    i++;
                }
            }

            // Draw dependency lines
            foreach (SkillSquare skill in m_tabLoading.SkillSquares)
            {
                foreach (string dependentSkillName in skill.DependentSkills)
                {
                    SkillSquare dependentSkill = m_tabLoading.SkillSquares.Where(x => x.SkillName == dependentSkillName).First();
                    DrawDependencyLine(skill, dependentSkill);
                }
            }
        }

        // Drawing each dependency line is a special case,
        // so drawing between x and an adjacent row/column is a case
        //  5  1  4
        //  3  x  2
        private void DrawDependencyLine(SkillSquare current, SkillSquare dependent)
        {
            // Flip the polarity of the rows sine we're counting bottom up for those (backwards)
            int rowDifference = -1 * ((current.UpperLeft.Y - dependent.UpperLeft.Y) / RowOffSetPer);
            int columnDifference = (current.UpperLeft.X - dependent.UpperLeft.X) / ColumnOffSetPer;

            if (rowDifference >= 1 && columnDifference == 0)
            {
                // 1
                for (int i = 1; i <= GapBetweenRows + ((rowDifference - 1) * (GapBetweenRows + SquareSize)); ++i)
                    SetChar(current.UpperLeft + new Point(OffsetToCenterOfSize, i + SquareSize - 1), (char)TCODSpecialCharacter.VertLine);
                return;
            }
            else if (rowDifference == 0 && columnDifference == 1)
            {
                // 2
                for (int i = 1; i <= GapBetweenColumns; ++i)
                    SetChar(current.UpperLeft + new Point(-i, OffsetToCenterOfSize), (char)TCODSpecialCharacter.HorzLine);
                return;
            }
            else if (rowDifference == 0 && columnDifference == -1)
            {
                // 3
                for (int i = 1; i <= GapBetweenColumns; ++i)
                    SetChar(current.UpperLeft + new Point(SquareSize + i, OffsetToCenterOfSize), (char)TCODSpecialCharacter.HorzLine);
                return;
            }
            else if (rowDifference == 1 && columnDifference == 1)
            {
                // 4
                for (int i = 0; i < GapBetweenColumns; ++i)
                    SetChar(dependent.UpperLeft + new Point(SquareSize + i, -i), (char)224);
                return;
            }
            else if (rowDifference == 1 && columnDifference == -1)
            {
                // 5
                for (int i = 0; i < GapBetweenColumns; ++i)
                    SetChar(dependent.UpperLeft + new Point(-i - 1, -i), (char)225);
                return;
            }

            throw new InvalidDataException(string.Format("SkillTreeTabXMLHelper drawing dependency I don't know how to draw - {0} to {1}", current.SkillName, dependent.SkillName));
        }

        private void ReadFileCallback(XmlReader reader, object data)
        {
            if (reader.LocalName != "Skills")
                throw new System.InvalidOperationException("Bad skill defination file");

            m_tabLoading.DefaultCurorPosition = new Point(int.Parse(reader.GetAttribute("DefaultX")), int.Parse(reader.GetAttribute("DefaultY")));

            m_maxRow = int.Parse(reader.GetAttribute("MaxRow"));

            SkillSquare currentSquare = null;
            bool inIcon = false;
            bool inDependencies = false;
            while (true)
            {
                reader.Read();
                if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "Skills")
                    break;

                if (reader.LocalName == "Skill")
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        string name = reader.GetAttribute("Name");
                        int column = int.Parse(reader.GetAttribute("Column"));
                        int row = int.Parse(reader.GetAttribute("Row"));
                        currentSquare = new SkillSquare(CalculatePosition(column, row), name);
                        m_tabLoading.SkillSquares.Add(currentSquare);
                        HandleNewPoint(column, row);
                    }
                }
                else if (reader.LocalName == "Icon")
                {
                    if (reader.NodeType == XmlNodeType.Element)
                        inIcon = true;
                    else if (reader.NodeType == XmlNodeType.EndElement)
                        inIcon = false;
                }
                else if (reader.LocalName.StartsWith("Row") && reader.NodeType == XmlNodeType.Element)
                {
                    // reader.ReadElementContentAsString() apparently moves us to the next row, so do this while we have a row
                    do
                    {
                        if (!inIcon)
                            throw new InvalidOperationException("SkillTreeTabXMLHelper - Found a row outside of an icon?");
                        int rowNumber = int.Parse(reader.LocalName.Substring(3));

                        string value = reader.ReadElementContentAsString();
                        if (rowNumber != 0 && rowNumber != 1 && rowNumber != 2 && rowNumber != 3)
                            throw new InvalidOperationException("SkillTreeTabXMLHelper - Invalid row in icon?");

                        // Icon text is offset from the upper left
                        Point position = currentSquare.UpperLeft + new Point(1, 2 + rowNumber);
                        m_iconTextLines.Add(new Pair<Point, string>(position, value));
                    }
                    while (reader.LocalName.StartsWith("Row") && reader.NodeType == XmlNodeType.Element);
                }
                else if (reader.LocalName == "Dependencies" && reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.NodeType == XmlNodeType.Element)
                        inDependencies = true;
                    else if (reader.NodeType == XmlNodeType.EndElement)
                        inDependencies = false;
                }
                else if (reader.LocalName == "Dependency" && reader.NodeType == XmlNodeType.Element)
                {
                    if (!inDependencies)
                        throw new InvalidOperationException("SkillTreeTabXMLHelper - Found a dependency outside of a dependencies?");

                    currentSquare.AddDependency(reader.GetAttribute("Name"));
                }
            }
        }
    }
}


text: google-site-verification: google601214287df4345e.html


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.unitybars</groupId>
    <artifactId>r2d2</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.15.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.3.1</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>RELEASE</version>
        </dependency>

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.23</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <argLine>-Dfile.encoding=UTF-8</argLine>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>