text:
layout: post
title:  "How to Deploy Rails using Passenger - Part 2"
description: "How to setup and deploy rails using passenger and nginx"
date:   2016-06-05 21:10:10
categories: post
post_id: 22
---

## Recap

This post is a continuation from [here]({% post_url 2016-06-04-deploy-rails-passenger-rubyconf %}). Previously we have installed Ruby, Rails, Nginx, Passenger and PostgreSQL. On this post we will install git, configure nginx config file to deploy rails app and git push the rails app from your development machine to the VPS. The step number will continue from the previous one, which is eleven.

## Step Eleven - Install git and creating a repository

Install git on the VPS using this command :
sudo apt-get install git

After installing Git, we will now create a bare git repository named awesomeapp.git and a folder to store the source code awesomeapp, let's put the repository on your user folder for this tutorial ( you can of course change to other location ).
cd ~
mkdir awesomeapp
mkdir repo && cd repo
mkdir awesomeapp.git && cd awesomeapp.git
git init --bare

--bare indicates that the repository will have no working files / source code, just the version control.

Type pwd to get your present working directory, you will need this later. My output looks like this :
![pwd](https://littlefoximage.s3.amazonaws.com/post22/pwd.png)

Next, we will dive into the git hooks to add a work tree directory (where your source code will be stored), more info about [git hooks here](http://githooks.com/). We will use the post-receive hook as it is executed after a git push has finished receiving.

Inside awesomeapp.git directory, if you type ls, you can see the list of files and folders like this :
![git inner mysteries](https://littlefoximage.s3.amazonaws.com/post22/git_inner.png)

Go to the hooks folder
cd hooks
Create a file named 'post-receive' :
cat > post-receive

When you execute the command above, you will see a blank line indicating that everything you type will be saved to this file. Let's proceed to type :

#!/bin/sh
git --work-tree=/home/soulchild/awesomeapp --git-dir=/home/soulchild/repo/awesomeapp.git checkout -f

Replace the work-tree directory with your desired location, this is the place where the source code will be saved.
Replace the git-dir directory with the bare git repository you created just now.

After finish typing, press Ctrl + D to save. We need to allow permissions for the file to be executable :
chmod +x post-receive

Now the source code will be saved in the work-tree every time a git push is received by the awesomeapp.git repository.

{% comment %}
### Optional but recommended step - Set up git hooks

[Git hooks](http://githooks.com/) are trigger points which you can define commands that will be executed whenever a specific event is triggered. ( eg : restart Nginx server after a git push is received )
Continuing from previous step, we will edit the post-receive hook for the awesomeapp git repository.
cd .git

We are inside the inner working of git now, if you type ls to list the directories, you will see output similar to this :
![Inner mysteries of how git works...or not](https://littlefoximage.s3.amazonaws.com/post22/git_inner.png)

Now lets go to hooks folder

{% endcomment %}

## Step Twelve - Push the Rails app from your local machine to VPS

Now on your local machine ( your laptop/pc ), locate to your existing Rails application or create one if you don't have one :
rails new awesomeapp -d postgresql

If you are creating a new Rails application, make sure to point the root route to a controller action first.

Open /config/database.yml of the rails app, scroll to the bottom and edit the production database username to look like this :

We will also generate a secret key for the production secret key base.
cd awesomeapp
rake secret

![Keep this a secret! Shhh](https://littlefoximage.s3.amazonaws.com/post22/rake_secret.png)
Copy down the string generated, we will need it later for setting environment variables.

Remember the present working directory from the previous step? We will add it to the git remote of the Rails app. If your local rails application has not initialize a git repository yet,
#inside awesomeapp rails root folder
#cd awesomeapp
git init

Then add the remote :

git remote add live ssh://user@YOUR_SERVER_IP_OR_DOMAIN_NAME/repo_location

live is the name of the remote, you can change this to whatever name you like.
user is the username you used to login to the ssh, change this to your ssh username.
YOUR_SERVER_IP_OR_DOMAIN_NAME is pretty much self-explanatory.
repo_location is the location of the repository in the VPS, replace this with the bare git repository mentioned in the previous step (eg: 'home/soulchild/repo/awesomeapp.git').

And now you are ready to push to the remote VPS, replace live with the remote name you have chosen just now.
git add -A
git commit -m "Awesome app first commit"
git push live master

Sweet! Next, let's edit the Nginx configuration to serve the Rails app and include environment variables as well.

## Step Thirteen - Edit Nginx Configuration file and deploy

Connect to your VPS using ssh
ssh demo@SERVER_IP_ADDRESS
Edit the Nginx configuration file using nano
sudo nano /opt/nginx/conf/nginx.conf

In the server block inside http block, edit it to look like this :

server {
        listen       80;
        server_name  localhost;
        root /path/to/rails_app_root/public; # <-- be sure to point to 'public'
        passenger_app_root /path/to/rails_app_root;
        passenger_enabled on;
        rack_env production;
        passenger_env_var SECRET_KEY_BASE d6532f57f0e1f5150f38ef413fd85c2c9081195431177950d6e44248822ab3d05bb2619871c29a8367d95ff04abaaba84bfc4433f37d089c9437c3e2e1efadc6;
        passenger_env_var AWESOMEAPP_DATABASE_USERNAME demo;
        passenger_env_var AWESOMEAPP_DATABASE_PASSWORD correcthorsebatterystaple;
}

1. Replace the /path/to/rails_app_root/ with the work tree you defined in previous step.
2. rack_env is the environment of the rails app, we set it to production.
3. passenger_env_var is used to define environment variables, you can define multiple environment variables in the config file. Replace the value of environment variables above with yours.

Press Ctrl + X to finish editing, type 'Y' and press Enter when prompted to save.

Your nginx.conf will look similar to this :

Now we will move to the Rails application root directory (the work tree),
cd ~/awesomeapp

Run bundle install
bundle install

Precompile assets, remember to set the RAILS_ENV to production
rake assets:precompile RAILS_ENV=production

Restart the Nginx server first so that the environment variables will be loaded :
sudo service nginx restart

Run rake:db create to create database
rake db:create RAILS_ENV=production

Run rake:db migrate to migrate database
rake db:migrate RAILS_ENV=production

And finally restart the Passenger app to update the changes
passenger-config restart-app /path/to/rails_app_root

## Step Fourteen - Cheers!

Now navigate to your VPS IP /domain name in the browser, you should see your Rails app running. 🍻
![Bye Heroku](https://littlefoximage.s3.amazonaws.com/post22/deployed.png "Bye Heroku!")

Next time whenever you git push a new update to remote, remember to login to the VPS and run these commands :

1. bundle install
2. rake assets:precompile RAILS_ENV=production
3. rake db:migrate RAILS_ENV=production
4. passenger-config restart-app /path/to/rails_app_root

Passenger app server must be restarted to reflect the changes after every git push.

Wait.... why do we need to repetitively execute these commands after git push, there must be a better way to automate this right? Yes there is! we can add these command to run in the post-receive hook, remember?

## Step Fifteen - Adding deployment task to post-receive hooks

Lets go to the repository of the rails app again and edit the post-receive hook :
cd ~/repo/awesomeapp.git
cd hooks
nano post-receive

We will edit it to look like this :

Replace the work tree and git dir accordingly, press Ctrl + X to end editing.

Edited 19 July 2016 : I found that restarting the Passenger app is sufficient without restarting Nginx, no sudo permission is required for restarting passenger app.

<s>
Notice that there is a sudo command which is the sudo service nginx restart, executing a sudo command requires a password input hence the restart command will not run in this post-receive hook. We have to manually set that no password is required for this command (nginx) for the user (the sudo user you created).

Let's edit the user file in sudoers.d directory, replace demo with your username :

sudo visudo -f /etc/sudoers.d/90-demo

Add this line to the end of the file , replace demo with your username :

demo ALL=(ALL) NOPASSWD:/etc/init.d/nginx
Press Ctrl + X to finish editing, type 'Y' and press Enter to save.
</s>

Now you should be good to go. In your local machine development repository, make a commit and push it the remote, you will see an output like this :
![Git push looks more magical now](https://littlefoximage.s3.amazonaws.com/post22/git_deploy_success.png "Git push looks more magical now")

And after receiving push, the server will run those deployment commands automatically and the web pages has changed :
![Look! No manual restart!](https://littlefoximage.s3.amazonaws.com/post22/deployed_with_auto.png "Look! No more manual deploy and restart!")

Now every time you push master branch to remote, the remote will deploy automatically. Sounds like Heroku? 😜

Congratulation for making this far! 🎉 You have learnt how to deploy Rails app on a bare VPS using git flow.

{% comment %}
https://www.digitalocean.com/community/tutorials/how-to-deploy-a-rails-app-with-git-hooks-on-ubuntu-14-04
{% endcomment %}


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

#include "net/third_party/quiche/src/quic/quartc/quartc_multiplexer.h"

#include <cstdint>
#include <utility>

#include "net/third_party/quiche/src/quic/core/quic_buffer_allocator.h"
#include "net/third_party/quiche/src/quic/core/quic_data_writer.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_mem_slice.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_mem_slice_span.h"
#include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h"

namespace quic {

QuartcSendChannel::QuartcSendChannel(QuartcMultiplexer* multiplexer,
                                     uint64_t id,
                                     QuicBufferAllocator* allocator,
                                     Delegate* delegate)
    : multiplexer_(multiplexer),
      id_(id),
      encoded_length_(QuicDataWriter::GetVarInt62Len(id_)),
      allocator_(allocator),
      delegate_(delegate) {}

QuartcStream* QuartcSendChannel::CreateOutgoingBidirectionalStream() {
  if (!session_) {
    QUIC_LOG(DFATAL) << "Session is not ready to write yet; channel_id=" << id_;
    return nullptr;
  }
  QuicMemSlice id_slice = EncodeChannelId();

  QuartcStream* stream = session_->CreateOutgoingBidirectionalStream();
  QuicConsumedData consumed =
      stream->WriteMemSlices(QuicMemSliceSpan(&id_slice), /*fin=*/false);
  DCHECK_EQ(consumed.bytes_consumed, encoded_length_);
  return stream;
}

bool QuartcSendChannel::SendOrQueueMessage(QuicMemSliceSpan message,
                                           int64_t datagram_id) {
  if (!session_) {
    QUIC_LOG(DFATAL) << "Session is not ready to write yet; channel_id=" << id_
                     << "datagram size=" << message.total_length();
    return false;
  }
  QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);  // Empty storage.
  storage.Append(EncodeChannelId());

  message.ConsumeAll(
      [&storage](QuicMemSlice slice) { storage.Append(std::move(slice)); });

  // Allocate a unique datagram id so that notifications can be routed back to
  // the right send channel.
  int64_t unique_datagram_id = multiplexer_->AllocateDatagramId(this);
  multiplexer_to_user_datagram_ids_[unique_datagram_id] = datagram_id;

  return session_->SendOrQueueMessage(storage.ToSpan(), unique_datagram_id);
}

void QuartcSendChannel::OnMessageSent(int64_t datagram_id) {
  // Map back to the caller-chosen |datagram_id|.
  datagram_id = multiplexer_to_user_datagram_ids_[datagram_id];
  delegate_->OnMessageSent(datagram_id);
}

void QuartcSendChannel::OnMessageAcked(int64_t datagram_id,
                                       QuicTime receive_timestamp) {
  // Map back to the caller-chosen |datagram_id|.
  auto it = multiplexer_to_user_datagram_ids_.find(datagram_id);
  if (it == multiplexer_to_user_datagram_ids_.end()) {
    QUIC_LOG(DFATAL) << "Datagram acked/lost multiple times; datagram_id="
                     << datagram_id;
    return;
  }
  delegate_->OnMessageAcked(it->second, receive_timestamp);
  multiplexer_to_user_datagram_ids_.erase(it);
}

void QuartcSendChannel::OnMessageLost(int64_t datagram_id) {
  // Map back to the caller-chosen |datagram_id|.
  auto it = multiplexer_to_user_datagram_ids_.find(datagram_id);
  if (it == multiplexer_to_user_datagram_ids_.end()) {
    QUIC_LOG(DFATAL) << "Datagram acked/lost multiple times; datagram_id="
                     << datagram_id;
    return;
  }
  delegate_->OnMessageLost(it->second);
  multiplexer_to_user_datagram_ids_.erase(it);
}

void QuartcSendChannel::OnSessionCreated(QuartcSession* session) {
  session_ = session;
}

QuicMemSlice QuartcSendChannel::EncodeChannelId() {
  QuicUniqueBufferPtr buffer = MakeUniqueBuffer(allocator_, encoded_length_);
  QuicDataWriter writer(encoded_length_, buffer.get());
  writer.WriteVarInt62(id_);
  return QuicMemSlice(std::move(buffer), encoded_length_);
}

QuartcMultiplexer::QuartcMultiplexer(
    QuicBufferAllocator* allocator,
    QuartcSessionEventDelegate* session_delegate,
    QuartcReceiveChannel* default_receive_channel)
    : allocator_(allocator),
      session_delegate_(session_delegate),
      default_receive_channel_(default_receive_channel) {
  CHECK_NE(session_delegate_, nullptr);
  CHECK_NE(default_receive_channel_, nullptr);
}

QuartcSendChannel* QuartcMultiplexer::CreateSendChannel(
    uint64_t channel_id,
    QuartcSendChannel::Delegate* delegate) {
  send_channels_.push_back(std::make_unique<QuartcSendChannel>(
      this, channel_id, allocator_, delegate));
  if (session_) {
    send_channels_.back()->OnSessionCreated(session_);
  }
  return send_channels_.back().get();
}

void QuartcMultiplexer::RegisterReceiveChannel(uint64_t channel_id,
                                               QuartcReceiveChannel* channel) {
  if (channel == nullptr) {
    receive_channels_.erase(channel_id);
    return;
  }
  auto& registered_channel = receive_channels_[channel_id];
  if (registered_channel) {
    QUIC_LOG(DFATAL) << "Attempted to overwrite existing channel_id="
                     << channel_id;
    return;
  }
  registered_channel = channel;
}

int64_t QuartcMultiplexer::AllocateDatagramId(QuartcSendChannel* channel) {
  send_channels_by_datagram_id_[next_datagram_id_] = channel;
  return next_datagram_id_++;
}

void QuartcMultiplexer::OnSessionCreated(QuartcSession* session) {
  for (auto& channel : send_channels_) {
    channel->OnSessionCreated(session);
  }
  session_ = session;
  session_delegate_->OnSessionCreated(session);
}

void QuartcMultiplexer::OnCryptoHandshakeComplete() {
  session_delegate_->OnCryptoHandshakeComplete();
}

void QuartcMultiplexer::OnConnectionWritable() {
  session_delegate_->OnConnectionWritable();
}

void QuartcMultiplexer::OnIncomingStream(QuartcStream* stream) {
  stream->SetDelegate(this);
}

void QuartcMultiplexer::OnCongestionControlChange(
    QuicBandwidth bandwidth_estimate,
    QuicBandwidth pacing_rate,
    QuicTime::Delta latest_rtt) {
  session_delegate_->OnCongestionControlChange(bandwidth_estimate, pacing_rate,
                                               latest_rtt);
}

void QuartcMultiplexer::OnConnectionClosed(
    const QuicConnectionCloseFrame& frame,
    ConnectionCloseSource source) {
  session_delegate_->OnConnectionClosed(frame, source);
}

void QuartcMultiplexer::OnMessageReceived(quiche::QuicheStringPiece message) {
  QuicDataReader reader(message);
  QuicVariableLengthIntegerLength channel_id_length =
      reader.PeekVarInt62Length();

  uint64_t channel_id;
  if (!reader.ReadVarInt62(&channel_id)) {
    QUIC_LOG(DFATAL) << "Received message without properly encoded channel id";
    return;
  }

  QuartcReceiveChannel* channel = default_receive_channel_;
  auto it = receive_channels_.find(channel_id);
  if (it != receive_channels_.end()) {
    channel = it->second;
  }

  channel->OnMessageReceived(channel_id, message.substr(channel_id_length));
}

void QuartcMultiplexer::OnMessageSent(int64_t datagram_id) {
  auto it = send_channels_by_datagram_id_.find(datagram_id);
  if (it == send_channels_by_datagram_id_.end()) {
    return;
  }
  it->second->OnMessageSent(datagram_id);
}

void QuartcMultiplexer::OnMessageAcked(int64_t datagram_id,
                                       QuicTime receive_timestamp) {
  auto it = send_channels_by_datagram_id_.find(datagram_id);
  if (it == send_channels_by_datagram_id_.end()) {
    return;
  }
  it->second->OnMessageAcked(datagram_id, receive_timestamp);
  send_channels_by_datagram_id_.erase(it);
}

void QuartcMultiplexer::OnMessageLost(int64_t datagram_id) {
  auto it = send_channels_by_datagram_id_.find(datagram_id);
  if (it == send_channels_by_datagram_id_.end()) {
    return;
  }
  it->second->OnMessageLost(datagram_id);
  send_channels_by_datagram_id_.erase(it);
}

size_t QuartcMultiplexer::OnReceived(QuartcStream* stream,
                                     iovec* iov,
                                     size_t iov_length,
                                     bool /*fin*/) {
  if (iov == nullptr || iov_length <= 0) {
    return 0;
  }

  QuicDataReader reader(static_cast<char*>(iov[0].iov_base), iov[0].iov_len);
  QuicVariableLengthIntegerLength channel_id_length =
      reader.PeekVarInt62Length();

  uint64_t channel_id;
  if (reader.BytesRemaining() >= channel_id_length) {
    // Fast path, have enough data to read immediately.
    if (!reader.ReadVarInt62(&channel_id)) {
      return 0;
    }
  } else {
    // Slow path, need to coalesce multiple iovecs.
    std::string data;
    for (size_t i = 0; i < iov_length; ++i) {
      data += std::string(static_cast<char*>(iov[i].iov_base), iov[i].iov_len);
    }
    QuicDataReader combined_reader(data);
    if (!combined_reader.ReadVarInt62(&channel_id)) {
      return 0;
    }
  }

  QuartcReceiveChannel* channel = default_receive_channel_;
  auto it = receive_channels_.find(channel_id);
  if (it != receive_channels_.end()) {
    channel = it->second;
  }
  channel->OnIncomingStream(channel_id, stream);
  return channel_id_length;
}

void QuartcMultiplexer::OnClose(QuartcStream* /*stream*/) {}

void QuartcMultiplexer::OnBufferChanged(QuartcStream* /*stream*/) {}

}  // namespace quic

redpajama_set_name: RedPajamaGithub


text:
package org.eclipse.moquette.spi.impl.events;

import org.eclipse.moquette.server.ServerChannel;

/**
 * Used to model the connection lost event
 *
 * @author andrea
 */
public class LostConnectionEvent extends MessagingEvent {
//    public final ServerChannel session;
    public final String clientID;

    public LostConnectionEvent(/*ServerChannel session, */String clientID) {
//        this.session = session;
        this.clientID = clientID;
    }
}


text:
package com.parse;

import java.util.concurrent.CancellationException;

import bolts.AggregateException;
import bolts.Continuation;
import bolts.Task;
import bolts.TaskCompletionSource;

/** package */ class ParseTaskUtils {

  /**
   * Converts a task execution into a synchronous action.
   */
  //TODO (grantland): Task.cs actually throws an AggregateException if the task was cancelled with
  // TaskCancellationException as an inner exception or an AggregateException with the original
  // exception as an inner exception if task.isFaulted().
  // https://msdn.microsoft.com/en-us/library/dd235635(v=vs.110).aspx
  /* package */ static <T> T wait(Task<T> task) throws ParseException {
    try {
      task.waitForCompletion();
      if (task.isFaulted()) {
        Exception error = task.getError();
        if (error instanceof ParseException) {
          throw (ParseException) error;
        }
        if (error instanceof AggregateException) {
          throw new ParseException(error);
        }
        if (error instanceof RuntimeException) {
          throw (RuntimeException) error;
        }
        throw new RuntimeException(error);
      } else if (task.isCancelled()) {
        throw new RuntimeException(new CancellationException());
      }
      return task.getResult();
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
  }

  //region Task to Callbacks

  /**
   * Calls the callback after a task completes on the main thread, returning a Task that completes
   * with the same result as the input task after the callback has been run.
   */
  /* package */ static Task<Void> callbackOnMainThreadAsync(Task<Void> task,
      final ParseCallback1<ParseException> callback) {
    return callbackOnMainThreadAsync(task, callback, false);
  }

  /**
   * Calls the callback after a task completes on the main thread, returning a Task that completes
   * with the same result as the input task after the callback has been run. If reportCancellation
   * is false, the callback will not be called if the task was cancelled.
   */
  /* package */ static Task<Void> callbackOnMainThreadAsync(Task<Void> task,
      final ParseCallback1<ParseException> callback, final boolean reportCancellation) {
    if (callback == null) {
      return task;
    }
    return callbackOnMainThreadAsync(task, new ParseCallback2<Void, ParseException>() {
      @Override
      public void done(Void aVoid, ParseException e) {
        callback.done(e);
      }
    }, reportCancellation);
  }

  /**
   * Calls the callback after a task completes on the main thread, returning a Task that completes
   * with the same result as the input task after the callback has been run.
   */
  /* package */ static <T> Task<T> callbackOnMainThreadAsync(Task<T> task,
      final ParseCallback2<T, ParseException> callback) {
    return callbackOnMainThreadAsync(task, callback, false);
  }

  /**
   * Calls the callback after a task completes on the main thread, returning a Task that completes
   * with the same result as the input task after the callback has been run. If reportCancellation
   * is false, the callback will not be called if the task was cancelled.
   */
  /* package */ static <T> Task<T> callbackOnMainThreadAsync(Task<T> task,
      final ParseCallback2<T, ParseException> callback, final boolean reportCancellation) {
    if (callback == null) {
      return task;
    }
    final TaskCompletionSource<T> tcs = new TaskCompletionSource();
    task.continueWith(new Continuation<T, Void>() {
      @Override
      public Void then(final Task<T> task) throws Exception {
        if (task.isCancelled() && !reportCancellation) {
          tcs.setCancelled();
          return null;
        }
        ParseExecutors.main().execute(new Runnable() {
          @Override
          public void run() {
            try {
              Exception error = task.getError();
              if (error != null && !(error instanceof ParseException)) {
                error = new ParseException(error);
              }
              callback.done(task.getResult(), (ParseException) error);
            } finally {
              if (task.isCancelled()) {
                tcs.setCancelled();
              } else if (task.isFaulted()) {
                tcs.setError(task.getError());
              } else {
                tcs.setResult(task.getResult());
              }
            }
          }
        });
        return null;
      }
    });
    return tcs.getTask();
  }

  //endregion
}


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">
    <parent>
        <artifactId>voxelwind</artifactId>
        <groupId>com.voxelwind</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>voxelwind-api</artifactId>

    <build>
        <finalName>voxelwind-api-${project.version}</finalName>
        <plugins>
            <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>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.4.3</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.21</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.flowpowered</groupId>
            <artifactId>flow-math</artifactId>
            <version>1.0.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>net.sf.trove4j</groupId>
            <artifactId>trove4j</artifactId>
            <version>3.0.3</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.8.2</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
</project>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Pokemon
{

    public string EvolutionType { get; set; }

    public int EvolutionIndex { get; set; }

    public Pokemon(string type, int index)
    {

        this.EvolutionType = type;

        this.EvolutionIndex = index;
    }
}

class Rask04PokemonEvolution
    {
        static void Main(string[] args)
        {

        var input = Console.ReadLine()
            .Split(new char[] {' ','-','>'},StringSplitOptions.RemoveEmptyEntries);

        var evolutionData = new Dictionary<string, List<Pokemon>>();

        while (input[0]!= "wubbalubbadubdub")
        {
            if (input.Length == 1)
            {
                string currentName = input[0];

                if (evolutionData.ContainsKey(currentName))
                {
                    Console.WriteLine($"# {currentName}");
                    foreach (var evolutionPair in evolutionData[currentName])
                    {
                        Console.WriteLine($"{evolutionPair.EvolutionType} <-> {evolutionPair.EvolutionIndex}");
                    }
                }
            }
            else
            {
                string currentName = input[0];

                string currentEvolutionType = input[1];

                int currentEvolutionIndex = int.Parse(input[2]);

                Pokemon currentPokemon = new Pokemon(currentEvolutionType,currentEvolutionIndex);

                if (!evolutionData.ContainsKey(currentName))
                {
                    evolutionData[currentName] = new List<Pokemon>();
                }

                evolutionData[currentName].Add(currentPokemon);

            }

            input = Console.ReadLine()
            .Split(new char[] { ' ', '-', '>' }, StringSplitOptions.RemoveEmptyEntries);
        }

        foreach (var pokemonPair in evolutionData)
        {
            Console.WriteLine($"# {pokemonPair.Key}");

            foreach (var evolutionPair in pokemonPair.Value.OrderByDescending(n=>n.EvolutionIndex))
            {
                Console.WriteLine($"{evolutionPair.EvolutionType} <-> {evolutionPair.EvolutionIndex}");
            }
        }
        }
    }


text:
title: LinearGauge Pointer and Range Size
page_title: LinearGauge Pointer and Range Size - RadGauge
description: Check our Web Forms article about LinearGauge Pointer and Range Size.
slug: gauge/appearance-and-styling/lineargauge-pointer-and-range-size
tags: lineargauge,pointer,and,range,size
published: True
position: 0
---

# LinearGauge Pointer and Range Size

## Configure Ranges Size

Changing the width of the ranges in RadLinearGauge can be done through the Size property of the MinorTicks:

````ASP.NET
<telerik:RadLinearGauge runat="server" id="RadLinearGauge_MinorTicksSize" Height="100px" Width="300px">
	<Pointer Value="22" Color="Silver">
	</Pointer>
	<Scale Min="-25" Max="50" MajorUnit="15" MinorUnit="1" MajorTicks-Size="50" MinorTicks-Size="25" Vertical="false">
		<Labels Format="{0} °C" />
		<Ranges>
			<telerik:GaugeRange From="-25" To="-5" Color="Blue" />
			<telerik:GaugeRange From="-5" To="15" Color="LightBlue" />
			<telerik:GaugeRange From="15" To="30" Color="GreenYellow" />
			<telerik:GaugeRange From="30" To="50" Color="Red" />
		</Ranges>
	</Scale>
</telerik:RadLinearGauge>
````

MinorTick size property is set to "25":

![gauge-range-size-1](images/gauge-range-size-1.png)

MinorTick size property is set to "40":

![gauge-range-size-2](images/gauge-range-size-2.png)

## Configure Pointer Size

* When shape property of the Pointer is set to BarIndicator - the width of the Track must be used

* When shape property of the Pointer is set to Arrow - the size of the Pointer must be used

If Pointer size of the LinearGauge is not set it will be set proportionately by the current size of the MajorTicks.

````ASP.NET
<telerik:RadLinearGauge runat="server" ID="RadLinearGauge_MajorTicksSize" Height="100px" Width="300px">
	<Pointer Value="22" Color="Silver">
	</Pointer>
	<Scale Min="-25" Max="50" MajorUnit="15" MinorUnit="1" MajorTicks-Size="20" MinorTicks-Size="10" Vertical="false">
		<Labels Format="{0} °C" />
		<Ranges>
			<telerik:GaugeRange From="-25" To="-5" Color="Blue" />
			<telerik:GaugeRange From="-5" To="15" Color="LightBlue" />
			<telerik:GaugeRange From="15" To="30" Color="GreenYellow" />
			<telerik:GaugeRange From="30" To="50" Color="Red" />
		</Ranges>
	</Scale>
</telerik:RadLinearGauge>
````

Pointer Size property is not set, MajorTicks-Size is set to "20" and MinorTicks-Size is set to "10":

![gauge-major-ticks-1](images/gauge-major-ticks-1.png)

Pointer Size property is not set, MajorTicks-Size is set to "40" and MinorTicks-Size is set to "10":

![gauge-major-ticks-2](images/gauge-major-ticks-2.png)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright (C) 2012 Red Hat, Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

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

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

-->
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.commonjava.maven.ext.integration-test</groupId>
  <artifactId>pluginMgmt1</artifactId>
  <version>1.0</version>
  <packaging>pom</packaging>

  <name>Plugin Management POM to use with integration tests</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>

    <maven.compiler.argument.target>${maven.compiler.target}</maven.compiler.argument.target>
    <maven.compiler.argument.source>${maven.compiler.source}</maven.compiler.argument.source>

    <maven.compiler.plugin.version>3.8.1</maven.compiler.plugin.version>

  </properties>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-jar-plugin</artifactId>
          <version>2.6</version>
          <dependencies>
            <dependency>
              <groupId>org.wildfly.core</groupId>
              <artifactId>wildfly-core-parent</artifactId>
              <version>2.0.10.Final</version>
              <type>pom</type>
            </dependency>
          </dependencies>
        </plugin>

        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>${maven.compiler.plugin.version}</version>
          <configuration>
              <debug>true</debug>
              <source>${maven.compiler.argument.target}</source>
              <target>${maven.compiler.argument.target}</target>
          </configuration>
        </plugin>

        <!-- Set properties containing the scm revision and build timestamp -->
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>buildnumber-maven-plugin</artifactId>
          <version>1.4</version>
          <executions>
            <execution>
              <id>get-build-timestamp</id>
              <phase>initialize</phase>
              <goals>
                <goal>create-timestamp</goal>
              </goals>
              <configuration>
                <!-- Example date: Wed, 4 Jul 2001 12:08:56 -0700 -->
                <timestampFormat>EEE, d MMM yyyy HH:mm:ss Z</timestampFormat>
                <timestampPropertyName>build.datetime</timestampPropertyName>
              </configuration>
            </execution>
            <execution>
              <id>get-scm-revision</id>
              <phase>initialize</phase>
              <goals>
                <goal>create</goal>
              </goals>
              <configuration>
                <doCheck>false</doCheck>
                <doUpdate>false</doUpdate>
                <revisionOnScmFailure>UNKNOWN</revisionOnScmFailure>
                <getRevisionOnlyOnce>true</getRevisionOnlyOnce>
              </configuration>
            </execution>
          </executions>
          <dependencies>
            <dependency>
              <groupId>commons-lang</groupId>
              <artifactId>commons-lang</artifactId>
              <version>2.5</version>
            </dependency>
          </dependencies>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>

</project>


text:
.class Lcom/android/server/display/DisplayPowerState$3;
.super Ljava/lang/Object;
.source "DisplayPowerState.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/display/DisplayPowerState;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/display/DisplayPowerState;

# direct methods
.method constructor <init>(Lcom/android/server/display/DisplayPowerState;)V
    .locals 0

    .prologue
    .line 378
    iput-object p1, p0, Lcom/android/server/display/DisplayPowerState$3;->this$0:Lcom/android/server/display/DisplayPowerState;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 5

    .prologue
    const/4 v0, 0x0

    const/4 v4, 0x1

    .line 381
    iget-object v1, p0, Lcom/android/server/display/DisplayPowerState$3;->this$0:Lcom/android/server/display/DisplayPowerState;

    # setter for: Lcom/android/server/display/DisplayPowerState;->mScreenUpdatePending:Z
    invoke-static {v1, v0}, Lcom/android/server/display/DisplayPowerState;->access$202(Lcom/android/server/display/DisplayPowerState;Z)Z

    .line 383
    iget-object v1, p0, Lcom/android/server/display/DisplayPowerState$3;->this$0:Lcom/android/server/display/DisplayPowerState;

    # getter for: Lcom/android/server/display/DisplayPowerState;->mScreenState:I
    invoke-static {v1}, Lcom/android/server/display/DisplayPowerState;->access$300(Lcom/android/server/display/DisplayPowerState;)I

    move-result v1

    if-eq v1, v4, :cond_0

    iget-object v1, p0, Lcom/android/server/display/DisplayPowerState$3;->this$0:Lcom/android/server/display/DisplayPowerState;

    # getter for: Lcom/android/server/display/DisplayPowerState;->mColorFadeLevel:F
    invoke-static {v1}, Lcom/android/server/display/DisplayPowerState;->access$400(Lcom/android/server/display/DisplayPowerState;)F

    move-result v1

    const/4 v2, 0x0

    cmpl-float v1, v1, v2

    if-lez v1, :cond_0

    iget-object v1, p0, Lcom/android/server/display/DisplayPowerState$3;->this$0:Lcom/android/server/display/DisplayPowerState;

    # getter for: Lcom/android/server/display/DisplayPowerState;->mScreenBrightness:I
    invoke-static {v1}, Lcom/android/server/display/DisplayPowerState;->access$500(Lcom/android/server/display/DisplayPowerState;)I

    move-result v0

    .line 387
    .local v0, "brightness":I
    :cond_0
    # getter for: Lcom/android/server/display/DisplayPowerState;->DEBUG_ON:Z
    invoke-static {}, Lcom/android/server/display/DisplayPowerState;->access$600()Z

    move-result v1

    if-eqz v1, :cond_1

    .line 388
    if-nez v0, :cond_1

    iget-object v1, p0, Lcom/android/server/display/DisplayPowerState$3;->this$0:Lcom/android/server/display/DisplayPowerState;

    # getter for: Lcom/android/server/display/DisplayPowerState;->mScreenState:I
    invoke-static {v1}, Lcom/android/server/display/DisplayPowerState;->access$300(Lcom/android/server/display/DisplayPowerState;)I

    move-result v1

    if-eq v1, v4, :cond_1

    .line 389
    const-string v1, "XAN-DPS"

    new-instance v2, Ljava/lang/StringBuilder;

    invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V

    const-string v3, "mSUR bn="

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    iget-object v3, p0, Lcom/android/server/display/DisplayPowerState$3;->this$0:Lcom/android/server/display/DisplayPowerState;

    # getter for: Lcom/android/server/display/DisplayPowerState;->mScreenBrightness:I
    invoke-static {v3}, Lcom/android/server/display/DisplayPowerState;->access$500(Lcom/android/server/display/DisplayPowerState;)I

    move-result v3

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v2

    invoke-static {v1, v2}, Landroid/util/Slog;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 394
    :cond_1
    iget-object v1, p0, Lcom/android/server/display/DisplayPowerState$3;->this$0:Lcom/android/server/display/DisplayPowerState;

    # getter for: Lcom/android/server/display/DisplayPowerState;->mPhotonicModulator:Lcom/android/server/display/DisplayPowerState$PhotonicModulator;
    invoke-static {v1}, Lcom/android/server/display/DisplayPowerState;->access$700(Lcom/android/server/display/DisplayPowerState;)Lcom/android/server/display/DisplayPowerState$PhotonicModulator;

    move-result-object v1

    iget-object v2, p0, Lcom/android/server/display/DisplayPowerState$3;->this$0:Lcom/android/server/display/DisplayPowerState;

    # getter for: Lcom/android/server/display/DisplayPowerState;->mScreenState:I
    invoke-static {v2}, Lcom/android/server/display/DisplayPowerState;->access$300(Lcom/android/server/display/DisplayPowerState;)I

    move-result v2

    invoke-virtual {v1, v2, v0}, Lcom/android/server/display/DisplayPowerState$PhotonicModulator;->setState(II)Z

    move-result v1

    if-eqz v1, :cond_4

    .line 395
    # getter for: Lcom/android/server/display/DisplayPowerState;->DEBUG:Z
    invoke-static {}, Lcom/android/server/display/DisplayPowerState;->access$800()Z

    move-result v1

    if-eqz v1, :cond_2

    .line 396
    const-string v1, "XAN-DPS"

    const-string v2, "Screen ready"

    invoke-static {v1, v2}, Landroid/util/Slog;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 398
    :cond_2
    iget-object v1, p0, Lcom/android/server/display/DisplayPowerState$3;->this$0:Lcom/android/server/display/DisplayPowerState;

    # setter for: Lcom/android/server/display/DisplayPowerState;->mScreenReady:Z
    invoke-static {v1, v4}, Lcom/android/server/display/DisplayPowerState;->access$902(Lcom/android/server/display/DisplayPowerState;Z)Z

    .line 399
    iget-object v1, p0, Lcom/android/server/display/DisplayPowerState$3;->this$0:Lcom/android/server/display/DisplayPowerState;

    # invokes: Lcom/android/server/display/DisplayPowerState;->invokeCleanListenerIfNeeded()V
    invoke-static {v1}, Lcom/android/server/display/DisplayPowerState;->access$1000(Lcom/android/server/display/DisplayPowerState;)V

    .line 405
    :cond_3
    :goto_0
    return-void

    .line 401
    :cond_4
    # getter for: Lcom/android/server/display/DisplayPowerState;->DEBUG:Z
    invoke-static {}, Lcom/android/server/display/DisplayPowerState;->access$800()Z

    move-result v1

    if-eqz v1, :cond_3

    .line 402
    const-string v1, "XAN-DPS"

    const-string v2, "Screen not ready"

    invoke-static {v1, v2}, Landroid/util/Slog;->d(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_0
.end method


text:
require 'spec_helper'

module SuperTues
  module Board
    module Events
      module Notices
        describe Notice do
        end
      end
    end
  end
end


text:
package com.ricardo.casarez.flighsearch.data.entities.search.response;

import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;

import java.util.Date;

/**
 * Class that model the QPX Express API response.
 * @link https://developers.google.com/qpx-express/v1/trips/search#response
 * Created by Ricardo Casarez on 10/19/2016.
 */
@Entity
public class SearchWrapper {
    @PrimaryKey(autoGenerate = true)
    private transient long id;
    private String kind;
    private Trips trips;

    public String getKind() {
        return kind;
    }

    public void setKind(String kind) {
        this.kind = kind;
    }

    public Trips getTrips() {
        return trips;
    }

    public void setTrips(Trips trips) {
        this.trips = trips;
    }

    public long getId() {
        return id;
    }

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


text:
<html>
<head>
    <title>Tests</title>

    <link rel="stylesheet" type="text/css" href="css/main.css" />
    <script data-main="main" src="lib/require.js"></script>
</head>
<body>
</body>
</html>


text:
class CreateBacktraces < ActiveRecord::Migration[4.2]
  def change
    create_table :backtraces do |t|
      t.string :fingerprint
      t.timestamps
    end

    add_index :backtraces, :fingerprint
  end
end


text:
package com.samsung.sec.dexter.core.config;

import com.google.common.base.Strings;
import com.samsung.sec.dexter.core.analyzer.AnalysisConfig;

import java.io.File;
import java.util.List;
import java.util.Map;

public interface IDexterConfigFile {
    public enum Type {
        FILE, FOLDER, PROJECT, SNAPSHOT;

        public static boolean hasValue(final String value) {
            if (Strings.isNullOrEmpty(value))
                return false;

            for (Type type : Type.values()) {
                if (type.toString().equals(value)) {
                    return true;
                }
            }

            return false;
        }
    };

    void setSnapshotId(String snapshotId);

    String getSnapshotId();

    String getFirstFileName();

    List<String> generateSourceFileFullPathList();

    void setType(Type type);

    Type getType();

    void setResultFileFullPath(String resultFileFullPath);

    String getResultFileFullPath();

    void setFileNameList(List<String> fileNameList);

    List<String> getFileNameList();

    void setModulePath(String modulePath);

    String getModulePath();

    void setLanguage(String language);

    String getLanguage();

    void setBinDir(String binDir);

    String getBinDir();

    void setLibDirList(List<String> libDirList);

    List<String> getLibDirList();

    void setSourceEncoding(String sourceEncoding);

    String getSourceEncoding();

    void setFunctionList(List<String> functionList);

    List<String> getFunctionList();

    void setHeaderDirList(List<String> headerDirList);

    List<String> getHeaderDirList();

    void setSourceDirList(List<String> sourceDirList);

    List<String> getSourceDirList();

    void setProjectFullPath(String projectFullPath);

    String getProjectFullPath();

    void setProjectName(String projectName);

    String getProjectName();

    void setDexterServerPort(int dexterServerPort);

    int getDexterServerPort();

    void setDexterServerIp(String dexterServerIp);

    String getDexterServerIp();

    void setDexterHome(String dexterHome);

    String getDexterHome();

    void setFields(final Map<String, Object> params);

    AnalysisConfig toAnalysisConfig();

    void loadFromFile(final File file);

}


text:
package org.apache.velocity.test;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.VelocityException;
import org.apache.velocity.runtime.RuntimeConstants;

/**
 * Test strict reference mode turned on by the velocity property
 * runtime.references.strict
 */
public class StrictReferenceTestCase extends BaseTestCase
{
    public StrictReferenceTestCase(String name)
    {
        super(name);
    }

    // second engine to test WITH conversions
    VelocityEngine engine2;

    @Override
    public void setUp() throws Exception
    {
        super.setUp();

        /* first engine without conversions */
        engine.setProperty(RuntimeConstants.RUNTIME_REFERENCES_STRICT, Boolean.TRUE);
        engine.setProperty(RuntimeConstants.CONVERSION_HANDLER_CLASS, "none");

        /* second engine with conversions */
        engine2 = createEngine();
        engine.setProperty(RuntimeConstants.RUNTIME_REFERENCES_STRICT, Boolean.TRUE);

        context.put("NULL", null);
        context.put("bar", null);
        context.put("TRUE", Boolean.TRUE);
    }

    /**
     * Test the modified behavior of #if in strict mode.  Mainly, that
     * single variables references in #if statements use non strict rules
     */
    public void testIfStatement()
    {
        Fargo fargo = new Fargo();
        fargo.next = new Fargo();
        context.put("fargo", fargo);
        assertEvalEquals("", "#if($bogus)xxx#end");
        assertEvalEquals("xxx", "#if($fargo)xxx#end");
        assertEvalEquals("", "#if( ! $fargo)xxx#end");
        assertEvalEquals("xxx", "#if($bogus || $fargo)xxx#end");
        assertEvalEquals("", "#if($bogus && $fargo)xxx#end");
        assertEvalEquals("", "#if($fargo != $NULL && $bogus)xxx#end");
        assertEvalEquals("xxx", "#if($fargo == $NULL || ! $bogus)xxx#end");
        assertEvalEquals("xxx", "#if(! $bogus1 && ! $bogus2)xxx#end");
        assertEvalEquals("xxx", "#if($fargo.prop == \"propiness\" && ! $bogus && $bar == $NULL)xxx#end");
        assertEvalEquals("", "#if($bogus && $bogus.foo)xxx#end");

        assertMethodEx("#if($bogus.foo)#end");
        assertMethodEx("#if(!$bogus.foo)#end");
    }

    /**
     * We make sure that variables can actuall hold null
     * values.
     */
    public void testAllowNullValues()
        throws Exception
    {
        evaluate("$!bar");
        assertEvalEquals("true", "#if($bar == $NULL)true#end");
        assertEvalEquals("true", "#set($foobar = $NULL)#if($foobar == $NULL)true#end");
        assertEvalEquals("13", "#set($list = [1, $NULL, 3])#foreach($item in $list)#if($item != $NULL)$item#end#end");
    }

    /**
     * Test that variables references that have not been defined throw exceptions
     */
    public void testStrictVariableRef()
        throws Exception
    {
        // We expect a Method exception on the following
        assertMethodEx("$bogus");
        assertMethodEx("#macro(test)$bogus#end #test()");

        assertMethodEx("#set($bar = $bogus)");

        assertMethodEx("#if($bogus == \"bar\") #end");
        assertMethodEx("#if($bogus != \"bar\") #end");
        assertMethodEx("#if(\"bar\" == $bogus) #end");
        assertMethodEx("#if($bogus > 1) #end");
        assertMethodEx("#foreach($item in $bogus)#end");

        // make sure no exceptions are thrown here
        evaluate("#set($foo = \"bar\") $foo");
        evaluate("#macro(test1 $foo1) $foo1 #end #test1(\"junk\")");
        evaluate("#macro(test2) #set($foo2 = \"bar\") $foo2 #end #test2()");
    }

    /**
     * Test that exceptions are thrown when methods are called on
     * references that contains objects that do not contains those
     * methods.
     */
    public void testStrictMethodRef()
    {
        Fargo fargo = new Fargo();
        fargo.next = new Fargo();
        context.put("fargo", fargo);

        // Mainly want to make sure no exceptions are thrown here
        assertEvalEquals("propiness", "$fargo.prop");
        assertEvalEquals("", "$!fargo.nullVal");
        assertEvalEquals("propiness", "$fargo.next.prop");

        assertMethodEx("$fargo.foobar");
        assertMethodEx("$fargo.next.foobar");
        assertMethodEx("$fargo.foobar()");
        assertMethodEx("#set($fargo.next.prop = $TRUE)");
        assertMethodEx("$fargo.next.setProp($TRUE)");
    }

    /**
     * Make sure exceptions are thrown when when we attempt to call
     * methods on null values.
     */
    public void testStrictMethodOnNull()
    {
        Fargo fargo = new Fargo();
        fargo.next = new Fargo();
        context.put("fargo", fargo);

        assertVelocityEx("$NULL.bogus");
        assertVelocityEx("$fargo.nullVal.bogus");
        assertVelocityEx("$fargo.next.nullVal.bogus");
        assertVelocityEx("#if (\"junk\" == $fargo.nullVal.bogus)#end");
        assertVelocityEx("#if ($fargo.nullVal.bogus > 2)#end");
        assertVelocityEx("#set($fargo.next.nullVal.bogus = \"junk\")");
        assertVelocityEx("#set($foo = $NULL.bogus)");
        assertVelocityEx("#foreach($item in $fargo.next.nullVal.bogus)#end");

        evaluate("$fargo.prop.toString()");
        assertVelocityEx("#set($fargo.prop = $NULL)$fargo.prop.next");

        // make sure no exceptions are thrown here
        evaluate("$!fargo.next.next");
        evaluate("$!fargo.next.nullVal");
        evaluate("#foreach($item in $fargo.nullVal)#end");
    }

    /**
     * Make sure undefined macros throw exceptions
     */
    public void testMacros()
    {
        assertVelocityEx("#bogus()");
        assertVelocityEx("#bogus (  )");
        assertVelocityEx("#bogus( $a )");
        assertVelocityEx("abc#bogus ( $a )a ");

        assertEvalEquals(" true ", "#macro(test1) true #end#test1()");
        assertEvalEquals(" true ", "#macro(test2 $a) $a #end#test2 ( \"true\")");
        assertEvalEquals("#CCFFEE", "#CCFFEE");
        assertEvalEquals("#F - ()", "#F - ()");
        assertEvalEquals("#F{}", "#F{}");
    }

    public void testRenderingNull()
    {
        Fargo fargo = new Fargo();
        fargo.next = new Fargo();
        context.put("fargo", fargo);

        assertVelocityEx("#set($foo = $NULL)$foo");
        assertEvalEquals("", "#set($foo = $NULL)$!foo");
        assertVelocityEx("$fargo.nullVal");
        assertEvalEquals("", "$!fargo.nullVal");
        assertVelocityEx("$fargo.next.next");
        assertEvalEquals("", "$!fargo.next.next");
        assertVelocityEx("$fargo.next.nullVal");
        assertEvalEquals("", "$!fargo.next.nullVal");
    }

    /**
     * Assert that we get a MethodInvocationException when calling evaluate
     */
    public void assertMethodEx(String template)
    {
        assertEvalException(template, MethodInvocationException.class);
    }

    /**
     * Assert that we get a VelocityException when calling evaluate
     */
    public void assertVelocityEx(String template)
    {
        assertEvalException(template, VelocityException.class);
    }

    /**
     * Assert that we get a MethodInvocationException when calling evaluate
     */
    public void assertParseEx(String template)
    {
        assertEvalException(template, ParseErrorException.class);
    }

    public static class Fargo
    {
        String prop = "propiness";
        Fargo next = null;

        public String getProp()
        {
            return prop;
        }

        public void setProp(String val)
        {
            this.prop = val;
        }

        public String getNullVal()
        {
            return null;
        }

        public Fargo getNext()
        {
            return next;
        }
    }
}


text:
package com.github.krr.mongodb.aggregate.support.config;

import com.github.krr.mongodb.aggregate.support.factory.NonReactiveAggregateQuerySupportingRepositoryFactoryBean;
import com.github.krr.mongodb.aggregate.support.repository.nonreactive.TestAggregateRepositoryMarker;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

/**
 * Created by rkolliva
 * 4/28/18.
 */

@Configuration
@EnableMongoRepositories(basePackageClasses = TestAggregateRepositoryMarker.class,
                         repositoryFactoryBeanClass = NonReactiveAggregateQuerySupportingRepositoryFactoryBean.class,
                         mongoTemplateRef = "mongoOperations")

public class NonReactiveTestMongoRepositoryConfiguration {

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Umbraco.Core;
using Umbraco.Core.Logging;
using umbraco.cms.presentation.Trees;

namespace Umbraco.Web.Trees
{
    /// <summary>
    /// A class used to render the legacy JS requirements for trees and IActions.
    /// </summary>
    internal static class LegacyTreeJavascript
    {
        /// <summary>
        /// If any legacy tree requires any JS rendering then we will compile a JS output of the combination.
        /// </summary>
        /// <returns></returns>
        public static string GetLegacyTreeJavascript()
        {
            //find all tree defs that exists for the current application regardless of if they are active
            List<TreeDefinition> appTreeDefs = TreeDefinitionCollection.Instance;
            //Create the BaseTree's based on the tree definitions found
            var legacyTrees = appTreeDefs.Select(treeDef => treeDef.CreateInstance()).ToList();
            var javascript = new StringBuilder();
            foreach (var bTree in legacyTrees)
            {
                bTree.RenderJS(ref javascript);
            }
            return javascript.ToString();
        }

        /// <summary>
        /// Returns a string with javascript proxy methods for IActions that are using old javascript
        /// </summary>
        /// <returns></returns>
        public static string GetLegacyIActionJavascript()
        {
            var js = new StringBuilder();
            foreach (var a in ActionsResolver.Current.Actions.ToList())
            {
                // NH: Added a try/catch block to this as an error in a 3rd party action can crash the whole menu initialization
                try
                {
                    if (string.IsNullOrEmpty(a.Alias) == false && (string.IsNullOrEmpty(a.JsFunctionName) == false || string.IsNullOrEmpty(a.JsSource) == false))
                    {
                        // if the action is using invalid javascript we need to do something about this
                        if (global::umbraco.BusinessLogic.Actions.Action.ValidateActionJs(a) == false)
                        {
                            js.AppendLine("function IActionProxy_" + a.Alias.ToSafeAlias() + "() {");
                            js.AppendLine(global::umbraco.BusinessLogic.Actions.Action.ConvertLegacyJs(a.JsFunctionName));
                            js.AppendLine("}");
                        }
                    }
                }
                catch (Exception ee)
                {
                    LogHelper.Error(typeof(LegacyTreeJavascript), "Error initializing tree action", ee);
                }
            }

            if (js.Length != 0)
            {
                js.Insert(0, "// This javascript is autogenerated by Umbraco to ensure legacy compatiblity with old context menu items\n\n");
            }

            return js.ToString();
        }
    }
}


text:
package net.sandius.rembulan.lib.luajava;

import net.sandius.rembulan.Conversions;
import net.sandius.rembulan.LuaObject;
import net.sandius.rembulan.runtime.Coroutine;
import net.sandius.rembulan.runtime.LuaFunction;

final class Unmapper {

	private Unmapper() {
		// not to be instantiated
	}

	public static Object unmapFrom(Object o) {
		if (o instanceof Class) {
			return ClassWrapper.of((Class<?>) o);
		}
		else {
			if (o == null || o instanceof Boolean || o instanceof String) {
				return o;
			}
			else if (o instanceof Number) {
				return Conversions.toCanonicalNumber((Number) o);
			}
			else if (o instanceof Character) {
				return Long.valueOf(((Character) o).charValue());
			}
			else if (o instanceof LuaFunction || o instanceof Coroutine || o instanceof LuaObject) {
				return o;
			}
			else return ObjectWrapper.of(o);
		}
	}

}


text:
export { default as Container } from './container';
export * from './dict';
export * from './factory';
export { RegistryReader, RegistryWriter, RegistryAccessor, default as Registry, Injection, RegistrationOptions } from './registry';
export { Resolver } from './resolver';
export { Owner, getOwner, setOwner, OWNER } from './owner';
export { Specifier, isSpecifierStringAbsolute, isSpecifierObjectAbsolute, serializeSpecifier, deserializeSpecifier } from './specifier';


text:
#ifndef GWEBENGINEVIEW_H
#define GWEBENGINEVIEW_H
#include "ringqt.h"
#include <QWebEngineView>
extern "C" {
#include "ring.h"
}

class GWebEngineView : public QWebEngineView
{

  Q_OBJECT

  public:

    struct VM *pVM;

    struct List *pParaList;

    char cloadFinishedEvent[RINGQT_EVENT_SIZE];
    char cloadProgressEvent[RINGQT_EVENT_SIZE];
    char cloadStartedEvent[RINGQT_EVENT_SIZE];
    char cselectionChangedEvent[RINGQT_EVENT_SIZE];
    char ctitleChangedEvent[RINGQT_EVENT_SIZE];
    char curlChangedEvent[RINGQT_EVENT_SIZE];

    GWebEngineView(QWidget *parent,VM *pVM );

    ~GWebEngineView();

    void geteventparameters(void) ;

    void setloadFinishedEvent(const char *cStr);
    void setloadProgressEvent(const char *cStr);
    void setloadStartedEvent(const char *cStr);
    void setselectionChangedEvent(const char *cStr);
    void settitleChangedEvent(const char *cStr);
    void seturlChangedEvent(const char *cStr);

    const char *getloadFinishedEvent(void);
    const char *getloadProgressEvent(void);
    const char *getloadStartedEvent(void);
    const char *getselectionChangedEvent(void);
    const char *gettitleChangedEvent(void);
    const char *geturlChangedEvent(void);

  public slots:

    void loadFinishedSlot();
    void loadProgressSlot();
    void loadStartedSlot();
    void selectionChangedSlot();
    void titleChangedSlot();
    void urlChangedSlot();

};

#endif


text:
package com.example.administrator.catemenu.activity;

import android.app.Activity;
import android.os.Bundle;

import com.example.administrator.catemenu.R;

/**
 * Created by Administrator on 2016/11/9.
 */
public class MenuFileActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cate_clip);
    }
}


text:
/**
 * @class EZ3.Engine
 * @constructor
 * @param {HTMLElement} canvas
 * @param {EZ3.Screen} [screen]
 * @param {Object} [options]
 */
EZ3.Engine = function(canvas, screen, options) {
  var device = EZ3.Device;

  /**
   * @property {EZ3.AnimationFrame} _animationFrame
   * @private
   */
  this._animationFrame = null;
  /**
   * @property {EZ3.Renderer} _renderer
   * @private
   */
  this._renderer = null;

  /**
   * @property {EZ3.Time} time
   */
  this.time = null;
  /**
   * @property {EZ3.Input} input
   */
  this.input = null;
  /**
   * @property {EZ3.ScreenManager} screens
   */
  this.screens = null;

  device.onReady(this._init, this, [
    canvas,
    screen,
    options
  ]);
};

/**
 * @method EZ3.Engine#_init
 * @private
 * @param {HTMLElement} canvas
 * @param {EZ3.Screen} [screen]
 * @param {Object} [options]
 */
EZ3.Engine.prototype._init = function(canvas, screen, options) {
  var bounds = canvas.getBoundingClientRect();

  this._animationFrame = new EZ3.AnimationFrame(false);
  this._renderer = new EZ3.Renderer(canvas, options);

  this.time = new EZ3.Time();
  this.input = new EZ3.InputManager(canvas, bounds);
  this.screens = new EZ3.ScreenManager(canvas, bounds, this._renderer, this.time, this.input, screen);

  this._renderer.initContext();
  this.time.start();
  this._update();
};

/**
 * @method EZ3.Engine#_update
 * @private
 */
EZ3.Engine.prototype._update = function() {
  this.screens.update();
  this.time.update();
  this._animationFrame.request(this._update.bind(this));
};


text:
import contextlib
from collections import namedtuple
from datetime import timedelta
from functools import partial
from unittest.mock import ANY, patch

import pytest

import marge.commit
import marge.interval
import marge.git
import marge.gitlab
import marge.job
import marge.project
import marge.single_merge_job
import marge.user
from marge.gitlab import GET, PUT
from marge.job import Fusion
from marge.merge_request import MergeRequest
from tests.git_repo_mock import RepoMock
from tests.gitlab_api_mock import Error, Ok, MockLab
from tests.test_project import INFO as TEST_PROJECT_INFO
import tests.test_commit as test_commit

INITIAL_MR_SHA = test_commit.INFO['id']

def _commit(commit_id, status):
    return {
        'id': commit_id,
        'short_id': commit_id,
        'author_name': 'J. Bond',
        'author_email': 'jbond@mi6.gov.uk',
        'message': 'Shaken, not stirred',
        'status': status,
    }

def _branch(name, protected=False):
    return {
        'name': name,
        'protected': protected,
    }

def _pipeline(sha1, status, ref='useless_new_feature'):
    return {
        'id': 47,
        'status': status,
        'ref': ref,
        'sha': sha1,
    }

class SingleJobMockLab(MockLab):
    def __init__(
        self,
        *,
        initial_master_sha,
        rewritten_sha,
        gitlab_url=None,
        fork=False,
        expect_gitlab_rebase=False,
        merge_request_options=None,
    ):
        super().__init__(
            initial_master_sha,
            gitlab_url,
            fork=fork,
            merge_request_options=merge_request_options,
        )
        api = self.api
        self.rewritten_sha = rewritten_sha
        if expect_gitlab_rebase:
            api.add_transition(
                PUT(
                    '/projects/{project_id}/merge_requests/{iid}/rebase'.format(
                        project_id=self.merge_request_info['project_id'],
                        iid=self.merge_request_info['iid'],
                    ),
                ),
                Ok(True),
                from_state='initial',
                to_state='rebase-in-progress',
            )
            api.add_merge_request(
               dict(self.merge_request_info, rebase_in_progress=True),
               from_state='rebase-in-progress',
               to_state='rebase-finished'
            )
            api.add_merge_request(
               dict(
                 self.merge_request_info,
                 rebase_in_progress=False,
                 sha=rewritten_sha,
               ),
               from_state='rebase-finished',
               to_state='pushed',
            )

        api.add_pipelines(
            self.merge_request_info['source_project_id'],
            _pipeline(sha1=rewritten_sha, status='running', ref=self.merge_request_info['source_branch']),
            from_state='pushed', to_state='passed',
        )
        api.add_pipelines(
            self.merge_request_info['source_project_id'],
            _pipeline(sha1=rewritten_sha, status='success', ref=self.merge_request_info['source_branch']),
            from_state=['passed', 'merged'],
        )
        source_project_id = self.merge_request_info['source_project_id']
        api.add_transition(
            GET(
                '/projects/{}/repository/branches/{}'.format(
                    source_project_id, self.merge_request_info['source_branch'],
                ),
            ),
            Ok({'commit': _commit(commit_id=rewritten_sha, status='running')}),
            from_state='pushed',
        )
        api.add_transition(
            GET(
                '/projects/{}/repository/branches/{}'.format(
                    source_project_id, self.merge_request_info['source_branch'],
                ),
            ),
            Ok({'commit': _commit(commit_id=rewritten_sha, status='success')}),
            from_state='passed'
        )
        api.add_transition(
            PUT(
                '/projects/1234/merge_requests/{iid}/merge'.format(iid=self.merge_request_info['iid']),
                dict(sha=rewritten_sha, should_remove_source_branch=True, merge_when_pipeline_succeeds=True),
            ),
            Ok({}),
            from_state=['passed', 'skipped'], to_state='merged',
        )
        api.add_merge_request(dict(self.merge_request_info, state='merged'), from_state='merged')
        api.add_transition(
            GET('/projects/1234/repository/branches/{}'.format(self.merge_request_info['target_branch'])),
            Ok({'commit': {'id': self.rewritten_sha}}),
            from_state='merged'
        )
        api.expected_note(
            self.merge_request_info,
            "My job would be easier if people didn't jump the queue and push directly... *sigh*",
            from_state=['pushed_but_master_moved', 'merge_rejected'],
        )
        api.expected_note(
            self.merge_request_info,
            "I'm broken on the inside, please somebody fix me... :cry:"
        )

    def push_updated(self, remote_url, remote_branch, old_sha, new_sha):
        source_project = self.forked_project_info or self.project_info
        assert remote_url == source_project['ssh_url_to_repo']
        assert remote_branch == self.merge_request_info['source_branch']
        assert old_sha == INITIAL_MR_SHA
        assert new_sha == self.rewritten_sha
        self.api.state = 'pushed'

    @contextlib.contextmanager
    def expected_failure(self, message):
        author_assigned = False

        def assign_to_author():
            nonlocal author_assigned
            author_assigned = True

        self.api.add_transition(
            PUT(
                '/projects/1234/merge_requests/{iid}'.format(iid=self.merge_request_info['iid']),
                args={'assignee_id': self.author_id},
            ),
            assign_to_author,
        )
        error_note = "I couldn't merge this branch: %s" % message
        self.api.expected_note(self.merge_request_info, error_note)

        yield

        assert author_assigned
        assert error_note in self.api.notes

class TestUpdateAndAccept:  # pylint: disable=too-many-public-methods
    Mocks = namedtuple('Mocks', 'mocklab api job')

    @pytest.fixture(params=[True, False])
    def fork(self, request):
        return request.param

    @pytest.fixture(params=list(Fusion))
    def fusion(self, request):
        return request.param

    @pytest.fixture(params=[True, False])
    def add_tested(self, request):
        return request.param

    @pytest.fixture(params=[True, False])
    def add_part_of(self, request):
        return request.param

    @pytest.fixture(params=[False])  # TODO: Needs support in mocklab
    def add_reviewers(self, request):
        return request.param

    @pytest.fixture()
    def options_factory(self, fusion, add_tested, add_reviewers, add_part_of):
        def make_options(**kwargs):
            fixture_opts = {
                'fusion': fusion,
                'add_tested': add_tested,
                'add_part_of': add_part_of,
                'add_reviewers': add_reviewers,
            }
            assert not set(fixture_opts).intersection(kwargs)
            kwargs.update(fixture_opts)
            return marge.job.MergeJobOptions.default(**kwargs)
        yield make_options

    @pytest.fixture()
    def update_sha(self, fusion):
        def new_sha(new, old):
            pats = {
                marge.job.Fusion.rebase: 'rebase(%s onto %s)',
                marge.job.Fusion.merge: 'merge(%s with %s)',
                marge.job.Fusion.gitlab_rebase: 'rebase(%s onto %s)',
            }
            return pats[fusion] % (new, old)
        yield new_sha

    @pytest.fixture()
    def rewrite_sha(self, fusion, add_tested, add_reviewers, add_part_of):
        def new_sha(sha):
            # NB. The order matches the one used in the Git mock to run filters
            if add_tested and fusion == marge.job.Fusion.rebase:
                sha = 'add-tested-by(%s)' % sha

            if add_reviewers and fusion != marge.job.Fusion.gitlab_rebase:
                sha = 'add-reviewed-by(%s)' % sha

            if add_part_of and fusion != marge.job.Fusion.gitlab_rebase:
                sha = 'add-part-of(%s)' % sha

            return sha
        yield new_sha

    @pytest.fixture(autouse=True)
    def patch_sleep(self):
        with patch('time.sleep'):
            yield

    @pytest.fixture()
    def mocklab_factory(self, fork, fusion):
        expect_rebase = fusion is Fusion.gitlab_rebase
        return partial(SingleJobMockLab, fork=fork, expect_gitlab_rebase=expect_rebase)

    @pytest.fixture()
    def mocks_factory(self, mocklab_factory, options_factory, update_sha, rewrite_sha):
        # pylint: disable=too-many-locals
        def make_mocks(
            initial_master_sha=None, rewritten_sha=None,
            extra_opts=None, extra_mocklab_opts=None,
            on_push=None
        ):
            options = options_factory(**(extra_opts or {}))
            initial_master_sha = initial_master_sha or '505050505e'

            if not rewritten_sha:
                rewritten_sha = rewrite_sha(update_sha(INITIAL_MR_SHA, initial_master_sha))

            mocklab = mocklab_factory(
                initial_master_sha=initial_master_sha,
                rewritten_sha=rewritten_sha,
                **(extra_mocklab_opts or {})
            )
            api = mocklab.api

            project_id = mocklab.project_info['id']
            merge_request_iid = mocklab.merge_request_info['iid']

            project = marge.project.Project.fetch_by_id(project_id, api)
            forked_project = None
            if mocklab.forked_project_info:
                forked_project_id = mocklab.forked_project_info['id']
                forked_project = marge.project.Project.fetch_by_id(forked_project_id, api)

            merge_request = MergeRequest.fetch_by_iid(project_id, merge_request_iid, api)

            def assert_can_push(*_args, **_kwargs):
                assert options.fusion is not Fusion.gitlab_rebase

            callback = on_push or mocklab.push_updated
            repo = RepoMock.init_for_merge_request(
                merge_request=merge_request,
                initial_target_sha=mocklab.initial_master_sha,
                project=project,
                forked_project=forked_project,
            )
            repo.mock_impl.on_push_callbacks.append(assert_can_push)
            repo.mock_impl.on_push_callbacks.append(callback)

            user = marge.user.User.myself(api)
            job = marge.single_merge_job.SingleMergeJob(
                api=api, user=user,
                project=project, merge_request=merge_request, repo=repo,
                options=options,
            )
            return self.Mocks(mocklab=mocklab, api=api, job=job)

        yield make_mocks

    @pytest.fixture()
    def mocks(self, mocks_factory):
        yield mocks_factory()

    def test_succeeds_first_time(self, mocks):
        _, api, job = mocks
        job.execute()
        assert api.state == 'merged'
        assert api.notes == []

    def test_succeeds_with_updated_branch(self, mocks):
        mocklab, api, job = mocks
        api.add_transition(
            GET(
                '/projects/1234/repository/branches/{source}'.format(
                    source=mocklab.merge_request_info['source_branch'],
                ),
            ),
            Ok({'commit': {'id': mocklab.rewritten_sha}}),
            from_state='initial', to_state='pushed',
        )
        job.execute()

        assert api.state == 'merged'
        assert api.notes == []

    def test_succeeds_if_skipped(self, mocks):
        mocklab, api, job = mocks
        api.add_pipelines(
            mocklab.merge_request_info['source_project_id'],
            _pipeline(sha1=mocklab.rewritten_sha, status='running'),
            from_state='pushed', to_state='skipped',
        )
        api.add_pipelines(
            mocklab.merge_request_info['source_project_id'],
            _pipeline(sha1=mocklab.rewritten_sha, status='skipped'),
            from_state=['skipped', 'merged'],
        )
        job.execute()

        assert api.state == 'merged'
        assert api.notes == []

    def test_succeeds_if_source_is_master(self, mocks_factory):
        mocklab, api, job = mocks_factory(
            extra_mocklab_opts=dict(merge_request_options={
                'source_branch': 'master',
                'target_branch': 'production',
            }),
        )
        api.add_transition(
            GET(
                '/projects/1234/repository/branches/{source}'.format(
                    source=mocklab.merge_request_info['source_branch'],
                ),
            ),
            Ok({'commit': {'id': mocklab.rewritten_sha}}),
            from_state='initial', to_state='pushed',
        )
        job.execute()

        assert api.state == 'merged'
        assert api.notes == []

    def test_fails_if_ci_fails(self, mocks):
        mocklab, api, job = mocks
        api.add_pipelines(
            mocklab.merge_request_info['source_project_id'],
            _pipeline(sha1=mocklab.rewritten_sha, status='running'),
            from_state='pushed', to_state='failed',
        )
        api.add_pipelines(
            mocklab.merge_request_info['source_project_id'],
            _pipeline(sha1=mocklab.rewritten_sha, status='failed'),
            from_state=['failed'],
        )

        with mocklab.expected_failure("CI failed!"):
            job.execute()

        assert api.state == 'failed'

    def test_fails_if_ci_canceled(self, mocks):
        mocklab, api, job = mocks
        api.add_pipelines(
            mocklab.merge_request_info['source_project_id'],
            _pipeline(sha1=mocklab.rewritten_sha, status='running'),
            from_state='pushed', to_state='canceled',
        )
        api.add_pipelines(
            mocklab.merge_request_info['source_project_id'],
            _pipeline(sha1=mocklab.rewritten_sha, status='canceled'),
            from_state=['canceled'],
        )

        with mocklab.expected_failure("Someone canceled the CI."):
            job.execute()

        assert api.state == 'canceled'

    def test_fails_on_not_acceptable_if_master_did_not_move(self, mocks):
        mocklab, api, job = mocks
        new_branch_head_sha = '99ba110035'
        api.add_transition(
            GET(
                '/projects/{source_project_id}/repository/branches/useless_new_feature'.format(
                    source_project_id=mocklab.merge_request_info['source_project_id'],
                ),
            ),
            Ok({'commit': _commit(commit_id=new_branch_head_sha, status='success')}),
            from_state='pushed', to_state='pushed_but_head_changed'
        )
        with mocklab.expected_failure("Someone pushed to branch while we were trying to merge"):
            job.execute()

        assert api.state == 'pushed_but_head_changed'
        assert api.notes == [
            "I couldn't merge this branch: Someone pushed to branch while we were trying to merge",
        ]

    def test_fails_if_branch_is_protected(self, mocks_factory, fusion):
        def reject_push(*_args, **_kwargs):
            raise marge.git.GitError()

        mocklab, api, job = mocks_factory(on_push=reject_push)
        api.add_transition(
            GET(
                '/projects/{source_project_id}/repository/branches/useless_new_feature'.format(
                    source_project_id=mocklab.merge_request_info['source_project_id'],
                ),
            ),
            Ok(_branch('useless_new_feature', protected=True)),
            from_state='initial', to_state='protected'
        )

        if fusion is Fusion.gitlab_rebase:
            api.add_transition(
                PUT(
                    '/projects/{project_id}/merge_requests/{iid}/rebase'.format(
                        project_id=mocklab.merge_request_info['project_id'],
                        iid=mocklab.merge_request_info['iid'],
                    ),
                ),
                Error(marge.gitlab.MethodNotAllowed(405, {'message': '405 Method Not Allowed'})),
                from_state='initial',
            )

        with mocklab.expected_failure("Sorry, I can't modify protected branches!"):
            job.execute()

        assert api.state == 'protected'

    def test_second_time_if_master_moved(self, mocks_factory, fusion, update_sha, rewrite_sha):
        initial_master_sha = 'eaeaea9e9e'
        moved_master_sha = 'fafafa'
        first_rewritten_sha = rewrite_sha(update_sha(INITIAL_MR_SHA, initial_master_sha))
        second_rewritten_sha = rewrite_sha(update_sha(first_rewritten_sha, moved_master_sha))

        # pylint: disable=unused-argument
        def push_effects(remote_url, remote_branch, old_sha, new_sha):
            nonlocal mocklab, target_branch, remote_target_repo

            if api.state == 'initial':
                assert old_sha == INITIAL_MR_SHA
                assert new_sha == first_rewritten_sha
                api.state = 'pushed_but_master_moved'
                remote_target_repo.set_ref(target_branch, moved_master_sha)
            elif api.state == 'merge_rejected':
                assert new_sha == second_rewritten_sha
                api.state = 'pushed'

        mocklab, api, job = mocks_factory(
            initial_master_sha=initial_master_sha,
            rewritten_sha=second_rewritten_sha,
            on_push=push_effects,
        )

        source_project_info = mocklab.forked_project_info or mocklab.project_info
        target_project_info = mocklab.project_info

        source_project_url = source_project_info['ssh_url_to_repo']
        target_project_url = target_project_info['ssh_url_to_repo']

        source_branch = mocklab.merge_request_info['source_branch']
        target_branch = mocklab.merge_request_info['target_branch']

        remote_source_repo = job.repo.mock_impl.remote_repos[source_project_url]
        remote_target_repo = job.repo.mock_impl.remote_repos[target_project_url]

        api.add_merge_request(
            dict(
                mocklab.merge_request_info,
                sha=first_rewritten_sha,
            ),
            from_state=['pushed_but_master_moved', 'merge_rejected'],
        )
        api.add_pipelines(
            mocklab.merge_request_info['source_project_id'],
            _pipeline(sha1=first_rewritten_sha, status='success'),
            from_state=['pushed_but_master_moved', 'merge_rejected'],
        )
        api.add_transition(
            PUT(
                '/projects/1234/merge_requests/{iid}/merge'.format(iid=mocklab.merge_request_info['iid']),
                dict(
                    sha=first_rewritten_sha,
                    should_remove_source_branch=True,
                    merge_when_pipeline_succeeds=True,
                ),
            ),
            Error(marge.gitlab.NotAcceptable()),
            from_state='pushed_but_master_moved', to_state='merge_rejected',
        )
        api.add_transition(
            GET(
                '/projects/{source_project_id}/repository/branches/useless_new_feature'.format(
                    source_project_id=mocklab.merge_request_info['source_project_id'],
                ),
            ),
            Ok({'commit': _commit(commit_id=first_rewritten_sha, status='success')}),
            from_state='pushed_but_master_moved'
        )
        api.add_transition(
            GET('/projects/1234/repository/branches/master'),
            Ok({'commit': _commit(commit_id=moved_master_sha, status='success')}),
            from_state='merge_rejected'
        )
        if fusion is Fusion.gitlab_rebase:
            rebase_url = '/projects/{project_id}/merge_requests/{iid}/rebase'.format(
                project_id=mocklab.merge_request_info['project_id'],
                iid=mocklab.merge_request_info['iid'],
            )

            api.add_transition(
                PUT(rebase_url), Ok(True),
                from_state='initial', to_state='pushed_but_master_moved',
                side_effect=lambda: (
                    remote_source_repo.set_ref(source_branch, first_rewritten_sha),
                    remote_target_repo.set_ref(target_branch, moved_master_sha)
                )
            )
            api.add_transition(
                PUT(rebase_url), Ok(True),
                from_state='merge_rejected', to_state='rebase-in-progress',
                side_effect=lambda: remote_source_repo.set_ref(source_branch, second_rewritten_sha)
            )

        job.execute()
        assert api.state == 'merged'
        assert api.notes == [
            "My job would be easier if people didn't jump the queue and push directly... *sigh*",
        ]

    def test_handles_races_for_merging(self, mocks):
        mocklab, api, job = mocks
        rewritten_sha = mocklab.rewritten_sha
        api.add_transition(
            PUT(
                '/projects/1234/merge_requests/{iid}/merge'.format(iid=mocklab.merge_request_info['iid']),
                dict(sha=rewritten_sha, should_remove_source_branch=True, merge_when_pipeline_succeeds=True),
            ),
            Error(marge.gitlab.NotFound(404, {'message': '404 Branch Not Found'})),
            from_state='passed', to_state='someone_else_merged',
        )
        api.add_merge_request(
            dict(mocklab.merge_request_info, state='merged'),
            from_state='someone_else_merged',
        )
        job.execute()
        assert api.state == 'someone_else_merged'
        assert api.notes == []

    @pytest.mark.parametrize("only_allow_merge_if_pipeline_succeeds", [True, False])
    def test_calculates_merge_when_pipeline_succeeds_correctly(
        self, mocks, only_allow_merge_if_pipeline_succeeds
    ):
        mocklab, api, job = mocks
        rewritten_sha = mocklab.rewritten_sha
        project_info = dict(TEST_PROJECT_INFO)
        project_info["only_allow_merge_if_pipeline_succeeds"] = only_allow_merge_if_pipeline_succeeds
        api.add_project(project_info)
        api.add_transition(
            PUT(
                '/projects/{pid}/merge_requests/{iid}/merge'.format(
                    iid=mocklab.merge_request_info['iid'],
                    pid=project_info["id"]
                ),
                dict(
                    sha=rewritten_sha,
                    should_remove_source_branch=True,
                    merge_when_pipeline_succeeds=only_allow_merge_if_pipeline_succeeds
                ),
            ),
            Ok(True),
            to_state='merged',
        )
        job.execute()
        assert api.state == 'merged'

    def test_handles_request_becoming_wip_after_push(self, mocks):
        mocklab, api, job = mocks
        rewritten_sha = mocklab.rewritten_sha
        api.add_transition(
            PUT(
                '/projects/1234/merge_requests/{iid}/merge'.format(iid=mocklab.merge_request_info['iid']),
                dict(sha=rewritten_sha, should_remove_source_branch=True, merge_when_pipeline_succeeds=True),
            ),
            Error(marge.gitlab.MethodNotAllowed(405, {'message': '405 Method Not Allowed'})),
            from_state='passed', to_state='now_is_wip',
        )
        api.add_merge_request(
            dict(mocklab.merge_request_info, work_in_progress=True),
            from_state='now_is_wip',
        )
        message = 'The request was marked as WIP as I was processing it (maybe a WIP commit?)'
        with mocklab.expected_failure(message):
            job.execute()
        assert api.state == 'now_is_wip'
        assert api.notes == ["I couldn't merge this branch: %s" % message]

    def test_guesses_git_hook_error_on_merge_refusal(self, mocks):
        mocklab, api, job = mocks
        rewritten_sha = mocklab.rewritten_sha
        api.add_transition(
            PUT(
                '/projects/1234/merge_requests/{iid}/merge'.format(iid=mocklab.merge_request_info['iid']),
                dict(sha=rewritten_sha, should_remove_source_branch=True, merge_when_pipeline_succeeds=True),
            ),
            Error(marge.gitlab.MethodNotAllowed(405, {'message': '405 Method Not Allowed'})),
            from_state='passed', to_state='rejected_by_git_hook',
        )
        api.add_merge_request(
            dict(mocklab.merge_request_info, state='reopened'),
            from_state='rejected_by_git_hook',
        )
        message = (
            'GitLab refused to merge this branch. I suspect that a Push Rule or a git-hook '
            'is rejecting my commits; maybe my email needs to be white-listed?'
        )
        with mocklab.expected_failure(message):
            job.execute()
        assert api.state == 'rejected_by_git_hook'
        assert api.notes == ["I couldn't merge this branch: %s" % message]

    def test_assumes_unresolved_discussions_on_merge_refusal(self, mocks):
        mocklab, api, job = mocks
        rewritten_sha = mocklab.rewritten_sha
        api.add_transition(
            PUT(
                '/projects/1234/merge_requests/{iid}/merge'.format(iid=mocklab.merge_request_info['iid']),
                dict(sha=rewritten_sha, should_remove_source_branch=True, merge_when_pipeline_succeeds=True),
            ),
            Error(marge.gitlab.MethodNotAllowed(405, {'message': '405 Method Not Allowed'})),
            from_state='passed', to_state='unresolved_discussions',
        )
        api.add_merge_request(
            dict(mocklab.merge_request_info),
            from_state='unresolved_discussions',
        )
        message = (
            "Gitlab refused to merge this request and I don't know why! "
            "Maybe you have unresolved discussions?"
        )
        with mocklab.expected_failure(message):
            with patch.dict(mocklab.project_info, only_allow_merge_if_all_discussions_are_resolved=True):
                job.execute()
        assert api.state == 'unresolved_discussions'
        assert api.notes == ["I couldn't merge this branch: %s" % message]

    def test_discovers_if_someone_closed_the_merge_request(self, mocks):
        mocklab, api, job = mocks
        rewritten_sha = mocklab.rewritten_sha
        api.add_transition(
            PUT(
                '/projects/1234/merge_requests/{iid}/merge'.format(iid=mocklab.merge_request_info['iid']),
                dict(sha=rewritten_sha, should_remove_source_branch=True, merge_when_pipeline_succeeds=True),
            ),
            Error(marge.gitlab.MethodNotAllowed(405, {'message': '405 Method Not Allowed'})),
            from_state='passed', to_state='oops_someone_closed_it',
        )
        api.add_merge_request(
            dict(mocklab.merge_request_info, state='closed'),
            from_state='oops_someone_closed_it',
        )
        message = 'Someone closed the merge request while I was attempting to merge it.'
        with mocklab.expected_failure(message):
            job.execute()
        assert api.state == 'oops_someone_closed_it'
        assert api.notes == ["I couldn't merge this branch: %s" % message]

    def test_tells_explicitly_that_gitlab_refused_to_merge(self, mocks):
        mocklab, api, job = mocks
        rewritten_sha = mocklab.rewritten_sha
        api.add_transition(
            PUT(
                '/projects/1234/merge_requests/{iid}/merge'.format(iid=mocklab.merge_request_info['iid']),
                dict(sha=rewritten_sha, should_remove_source_branch=True, merge_when_pipeline_succeeds=True),
            ),
            Error(marge.gitlab.MethodNotAllowed(405, {'message': '405 Method Not Allowed'})),
            from_state='passed', to_state='rejected_for_mysterious_reasons',
        )
        message = "Gitlab refused to merge this request and I don't know why!"
        with mocklab.expected_failure(message):
            job.execute()
        assert api.state == 'rejected_for_mysterious_reasons'
        assert api.notes == ["I couldn't merge this branch: %s" % message]

    def test_wont_merge_wip_stuff(self, mocks):
        mocklab, api, job = mocks
        wip_merge_request = dict(mocklab.merge_request_info, work_in_progress=True)
        api.add_merge_request(wip_merge_request, from_state='initial')

        with mocklab.expected_failure("Sorry, I can't merge requests marked as Work-In-Progress!"):
            job.execute()

        assert api.state == 'initial'
        assert api.notes == [
            "I couldn't merge this branch: Sorry, I can't merge requests marked as Work-In-Progress!",
        ]

    def test_wont_merge_branches_with_autosquash_if_rewriting(self, mocks):
        mocklab, api, job = mocks

        autosquash_merge_request = dict(mocklab.merge_request_info, squash=True)
        api.add_merge_request(autosquash_merge_request, from_state='initial')

        admin_user = dict(mocklab.user_info, is_admin=True)
        api.add_user(admin_user, is_current=True)

        if job.opts.requests_commit_tagging:
            message = "Sorry, merging requests marked as auto-squash would ruin my commit tagging!"
            with mocklab.expected_failure(message):
                job.execute()
            assert api.state == 'initial'
        else:
            job.execute()
            assert api.state == 'merged'

    @patch('marge.job.log', autospec=True)
    def test_waits_for_approvals(self, mock_log, mocks_factory):
        five_secs = timedelta(seconds=5)
        _, api, job = mocks_factory(
            extra_opts=dict(approval_timeout=five_secs, reapprove=True)
        )
        job.execute()

        mock_log.info.assert_any_call('Checking if approvals have reset')
        mock_log.debug.assert_any_call('Approvals haven\'t reset yet, sleeping for %s secs', ANY)
        assert api.state == 'merged'

    def test_fails_if_changes_already_exist(self, mocks):
        mocklab, api, job = mocks

        source_project_info = mocklab.forked_project_info or mocklab.project_info
        source_project_url = source_project_info['ssh_url_to_repo']
        target_project_url = mocklab.project_info['ssh_url_to_repo']
        remote_source_repo = job.repo.mock_impl.remote_repos[source_project_url]
        remote_target_repo = job.repo.mock_impl.remote_repos[target_project_url]
        source_branch = mocklab.merge_request_info['source_branch']
        target_branch = mocklab.merge_request_info['target_branch']

        remote_target_repo.set_ref(target_branch, remote_source_repo.get_ref(source_branch))
        expected_message = 'these changes already exist in branch `%s`' % target_branch

        with mocklab.expected_failure(expected_message):
            job.execute()

        assert api.state == 'initial'
        assert api.notes == ["I couldn't merge this branch: {}".format(expected_message)]


text:
// Copyright (c) 2017 Andrew Vardeman.  Published under the MIT license.
// See license.txt in the FileSharper distribution or repository for the
// full text of the license.

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using FileSharperCore.Util;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;

namespace FileSharperCore.Processors.Image
{

    public class ImageResizeParameters
    {
        [PropertyOrder(1, UsageContextEnum.Both)]
        public string NewPath { get; set; } = @"{DirectoryName}\{NameWithoutExtension}.jpg";
        [PropertyOrder(2, UsageContextEnum.Both)]
        public ImageSaveFormat Format { get; set; } = ImageSaveFormat.Jpeg;
        [PropertyOrder(3, UsageContextEnum.Both)]
        public MediaDimension ResizeBy { get; set; } = MediaDimension.Width;
        [PropertyOrder(4, UsageContextEnum.Both)]
        public int Size { get; set; } = 48;
        [PropertyOrder(5, UsageContextEnum.Both)]
        public bool Overwrite { get; set; } = false;
    }

    public class ImageResizeProcessor : SingleFileProcessorBase
    {
        private ImageResizeParameters m_Parameters = new ImageResizeParameters();

        public override string Name => "Create resized image";

        public override string Category => "Image";

        public override string Description => "Export a resized image";

        public override object Parameters => m_Parameters;

        protected internal override ProcessingResult Process(FileInfo file, string[] values,
            CancellationToken token)
        {
            int width;
            int height;
            bool isBitmap = false;
            string outPath = null;
            FileInfo[] generatedFiles = new FileInfo[0];

            ProcessingResultType resultType = ProcessingResultType.Failure;
            string message = "Success";
            Bitmap b = null;
            try
            {
                b = new Bitmap(file.FullName);
                isBitmap = true;
            }
            catch (Exception ex)
            {
                resultType = ProcessingResultType.NotApplicable;
            }
            if (isBitmap)
            {
                try
                {
                    if (m_Parameters.ResizeBy == MediaDimension.Width)
                    {
                        width = m_Parameters.Size;
                        height = (int)Math.Round((double)b.Height * width / b.Width);
                    }
                    else
                    {
                        height = m_Parameters.Size;
                        width = (int)Math.Round((double)b.Width * height / b.Height);
                    }
                    using (Bitmap bout = new Bitmap(b, new Size(width, height)))
                    {
                        outPath = ReplaceUtil.Replace(m_Parameters.NewPath, file);
                        ImageFormat format = ImageFormat.Jpeg;
                        switch (m_Parameters.Format)
                        {
                            case ImageSaveFormat.Bitmap:
                                format = ImageFormat.Bmp;
                                break;
                            case ImageSaveFormat.Exif:
                                format = ImageFormat.Exif;
                                break;
                            case ImageSaveFormat.Gif:
                                format = ImageFormat.Gif;
                                break;
                            case ImageSaveFormat.Jpeg:
                                format = ImageFormat.Jpeg;
                                break;
                            case ImageSaveFormat.Png:
                                format = ImageFormat.Png;
                                break;
                            case ImageSaveFormat.Tiff:
                                format = ImageFormat.Tiff;
                                break;
                        }
                        if (m_Parameters.Overwrite || !File.Exists(outPath))
                        {
                            string outDirPath = Path.GetDirectoryName(outPath);
                            Directory.CreateDirectory(outDirPath);
                            bout.Save(outPath, format);
                            resultType = ProcessingResultType.Success;
                            generatedFiles = new FileInfo[] { new FileInfo(outPath) };
                        }
                        else
                        {
                            resultType = ProcessingResultType.Failure;
                            message = "Target file exists";
                            generatedFiles = new FileInfo[0];
                        }

                    }
                }
                catch(Exception ex)
                {
                    RunInfo.ExceptionInfos.Enqueue(new ExceptionInfo(ex, file));
                    message = ex.Message;
                    resultType = ProcessingResultType.Failure;
                }
                finally
                {
                    b?.Dispose();
                }
            }
            return new ProcessingResult(resultType, message, generatedFiles);
        }
    }
}


text:
one_flow_service 'test_simple_instance_by_id' do
  action :delete
end


text:
using Java.IO;
using Android.Graphics;

namespace PrimusFlex.Mobile.Common
{
    public static class App
    {
        public static string AppName { get { return Constant.APPLICATION_NAME; } }

        public static File File;
        public static File Dir;
        public static Bitmap Bitmap;
    }
}