text:
<?php
namespace lsa\PortfolioBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

use lsa\PortfolioBundle\Entity\Cv;
use lsa\PortfolioBundle\Form\CvType;

class CvController extends Controller {

    /**
     * Show Cv list
     */
    public function indexAction(){
        $users = array();
        $em = $this->getDoctrine()->getManager();
        if( !$this->get('security.context')->isGranted('ROLE_ADMIN')){
            throw new AccessDeniedHttpException('Accès limité aux administratuer');
        }

        $user = $this->get('security.context')->getToken()->getUser();
        if($user=='anon'){ throw $this->createNotFoundException(" Vous n'etes pas connecté !! "); }

       $cvs = $em->getRepository('PortfolioBundle:Cv')->findAll();
       return $this->render('PortfolioBundle:cv:index.html.twig',array('cvs'=>$cvs));
    }

    /**
     * Add new cv
     */
    public function addAction(){
        $em        = $this->getDoctrine()->getManager();
        $cv      = new Cv();
        $form      = $this->createForm(new CvType, $cv);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST') {
            $form->bind($request);
            if ($form->isValid()) {
                $em->persist($cv);
                $em->flush();
                // On définit un message flash
                $this->get('session')->getFlashBag()->add('info', 'cv bien ajouté');
                return $this->redirect($this->generateUrl('portfolio_cv_admin'));
            }
        }

        return $this->render('PortfolioBundle:Cv:add.html.twig', array(
                    'cv'=>$cv,
                    'form'=>$form->createView())
                );
    }

    /**
     * Edit cv row
     */
    public function editAction(Cv $cv){
        if(!is_null($cv) ){
            $em        = $this->getDoctrine()->getManager();

            $form      = $this->createForm(new CvType, $cv);

            $request = $this->get('request');
            if ($request->getMethod() == 'POST') {
                $form->bind($request);
                if ($form->isValid()) {
                    $em->persist($cv);
                    $em->flush();
                    // On définit un message flash
                    $this->get('session')->getFlashBag()->add('info', 'Cv bien modifié');
                    return $this->redirect($this->generateUrl('portfolio_cv_admin'));
                }
            }

            return $this->render('PortfolioBundle:Cv:edit.html.twig', array(
                        'cv'=>$cv,
                        'form'=>$form->createView())
                    );
        }
    }

    /**
     * Delete cv row
     */
    public function deleteAction(Cv $cv){
        if(!is_null($cv) ){
            $em        = $this->getDoctrine()->getManager();
            $em->remove($cv);
            $em->flush();
            // On définit un message flash
            $this->get('session')->getFlashBag()->add('info', 'Cv bien supprimé');
        }

       return $this->redirect($this->generateUrl('portfolio_cv_admin'));
    }

}


text:
package com.mircea.sotan.model;

import com.google.gson.annotations.SerializedName;

/**
 * Created by mircea
 */
public class Paging<T> extends BasePaging<T> {
    @SerializedName("offset")
    private int offset;
    @SerializedName("prev")
    private int prev;

    public int getOffset() {
        return offset;
    }

    public int getPrev() {
        return prev;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.fodrive.demo.service;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *

 *
 *
在另一线程开启保存日志的服务,调试用,正式发布取消
 *
 *
日志等级*:v , *:d , *:w , *:e , *:f , *:s
 *
 *
eg:如果定义*:e等级的日志那么e f s 这三个等级的日志将会打印
 *
 *
 *
eg cmds = "logcat *:e *:w | grep \"(" + mPID + ")\"";
 *
 * cmds = "logcat  | grep \"(" + mPID + ")\"";
 *
 *
打印某个进程中的日志信息
 *
 * cmds = "logcat -s way";
 *
 *
打印标签过滤信息
 *
 *
cmds = "logcat *:e *:i | grep \"(" + mPID + ")\"";
 *
 *

 *
 * @author leequer
 */
public class Service_SaveLog extends Service implements Runnable
{
    private static final String TAG = "Service_SaveLog";

    SaveLog.Stub mStub = new SaveLog.Stub()
    {

        @Override
        public void startSaveLog() throws RemoteException
        {
            // TODO Auto-generated method stub
            CLog.i(TAG, "startSaveLog");
            runing = true;
            startSavelogThread();
        }

        @Override
        public void StopSaveLog() throws RemoteException
        {
            // TODO Auto-generated method stub
            CLog.i(TAG, "StopSaveLog");
            runing = false;
            stopSelf();
        }
    };
    private boolean runing = true;

    @Override
    public IBinder onBind(Intent intent)
    {
        // TODO Auto-generated method stub

        return mStub;
    }

    @Override
    public void onCreate()
    {
        // TODO Auto-generated method stub
        super.onCreate();
        runing = true;
        CLog.i(TAG, "onCreate");
        startSavelogThread();

    }

    @SuppressWarnings("deprecation")
    @Override
    public void onStart(Intent intent, int startId)
    {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        CLog.i(TAG, "onstart");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        // TODO Auto-generated method stub
        CLog.i(TAG, "onstartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean onUnbind(Intent intent)
    {
        // TODO Auto-generated method stub
        CLog.i(TAG, "onunbind");
        stopService(intent);
        return super.onUnbind(intent);

    }

    private void startSavelogThread()
    {
        Thread _saveLogThread = new Thread(Service_SaveLog.this);
        _saveLogThread.setName("save_log");
        _saveLogThread.start();
    }

    public static String getCurrentTime(String format)
    {
        SimpleDateFormat dateformat1 = new SimpleDateFormat(format);
        String time = dateformat1.format(new Date());
        return time;
    }

    public static void isHavePath(String path)
    {
        File _file = new File(path);
        if (!_file.exists())
        {
            _file.mkdirs();
        }
    }

    @Override
    public void run()
    {
        // TODO Auto-generated method stub
        Process _Process = null;
        BufferedReader _BufferedReader = null;
        FileOutputStream _FileOutputStream = null;

        String _path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ijiazu/logs/";

        CLog.i(TAG, _path);
        String _logFileName = getCurrentTime("yyyy-MM-dd-hh-mm-ss") + ".txt";

        try
        {
            isHavePath(_path);
            File _file = new File(_path + _logFileName);

            _Process = Runtime.getRuntime().exec("logcat -v time *:v  ");
            // 保存某个进程的所有日志
            // _Process = Runtime.getRuntime().exec("logcat *:e *:i | grep \"("
            // + _PID + ")\"");
            // 保存指定tag的日志
            // _Process = Runtime.getRuntime().exec(new String
            // []{"logcat",你定义的tag的名字":I *:S"});
            _BufferedReader = new BufferedReader(new InputStreamReader(_Process.getInputStream()));
            _FileOutputStream = new FileOutputStream(_file);
            String _line;
            while ((_line = _BufferedReader.readLine()) != null && runing)
            {
                _line += "\r\n";
                _FileOutputStream.write(_line.getBytes());
            }
            _FileOutputStream.flush();
            _FileOutputStream.close();
            _BufferedReader.close();
        } catch (Exception e)
        {
        }
    }

}


text:
<?php
namespace Directorzone\Form\Company;

use Netsensia\Form\NetsensiaForm;

class CompanyFinancialsForm extends NetsensiaForm
{
    public function __construct($name = null, $options = array())
    {
        parent::__construct($name, $options);
    }

    public function prepare()
    {
        $this->setFieldPrefix('account-contact-');
        $this->setDefaultIcon('user');

        $this->addSelect([
            'name' => 'companytype',
            'label' => 'Market Group',
        ]);

        $this->addTextArea('business-description');

        $this->addMultiTable([
            'groupname' => 'Keywords',
            'jointablemodel' => 'CompanyKeyword',
            'jointablekeycolumn' => 'companykeywordid',
            'fields' => [
                ['type' => 'text', 'name' => 'companykeyword', 'label' => 'Keyword'],
            ],
        ]);

        $this->addDate('incorporation-date');
        $this->addDate('closure-date');
        $this->addSelect(['name' => 'companystatus', 'label' => 'Company Status']);
        $this->addSelect(['name' => 'countryoforigin', 'label' => 'Country of Origin', 'table' => 'country']);
        $this->addSelect('exchange');
        $this->addSelect(['name' => 'companycategory', 'label' => 'Company Category']);
        $this->addText('trading-symbol');
        $this->addText(['name' => 'actualemployees', 'label' => 'Number of Employees']);
        $this->addDate(['name' => 'employeecountdate', 'label' => 'Date of Employee Count']);
        $this->addText(['name' => 'actualrevenue', 'label' => 'Revenue']);
        $this->addText(['name' => 'revenueyear', 'label' => 'Year of Reported Revenue']);
        $this->addText(['name' => 'actualrevenuegrowth', 'label' => 'Revenue Growth %']);
        $this->addText(['name' => 'revenuegrowthyear', 'label' => 'Year of Revenue Growth']);
        $this->addSelect(['name' => 'financialyearend', 'table' => 'month', 'label' => 'Financial Year End']);
        $this->addMultiTable([
            'groupname' => 'Past Company Names',
            'jointablemodel' => 'CompanyPastName',
            'jointablekeycolumn' => 'companydirectoryid',
            'fields' => [
                ['type' => 'text', 'name' => 'companypastname', 'label' => 'Previous Name'],
            ],
        ]);
        $this->addSelect(['name' => 'companyphase', 'label' => 'Company Phase/Size']);

        $this->addSelectWithInvisibleOther(
            [
                'name' => 'companyranking',
                'label' => 'Company Ranking',
            ]);
        $this->addSelect(['name' => 'companyprofit', 'label' => 'Company Profit']);
        $this->addSelect(['name' => 'investmentstatus', 'label' => 'Investment Status']);

        $this->addMultiTable([
            'groupname' => 'Patents',
            'jointablemodel' => 'CompanyPatent',
            'jointablekeycolumn' => 'companydirectoryid',
            'fields' => [
                ['type' => 'text', 'name' => 'companypatent', 'label' => 'Patent'],
            ],
        ]);

        $this->addSubmit('Submit');

        parent::prepare();
    }
}


text:
module CitizenBankDataHelper
end


text:
class Relationships::OrganizationUsersController < ApplicationController
  before_filter :authenticate_user!

  # GET /relationships/organization_users
  # GET /relationships/organization_users.json
  def index
    @relationships_organization_users = Relationships::OrganizationUser.paginate(:page => params[:page])

    authorize! :index, Relationships::OrganizationUser

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @relationships_organization_users }
    end
  end

  # GET /relationships/organization_users/1
  # GET /relationships/organization_users/1.json
  def show
    @relationships_organization_user = Relationships::OrganizationUser.find(params[:id])

    authorize! :show, @relationships_organization_user

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @relationships_organization_user }
    end
  end

  # GET /relationships/organization_users/new
  # GET /relationships/organization_users/new.json
  def new
    @relationships_organization_user = Relationships::OrganizationUser.new

    authorize! :new, @relationships_organization_user

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @relationships_organization_user }
    end
  end

  # GET /relationships/organization_users/1/edit
  def edit
    @relationships_organization_user = Relationships::OrganizationUser.find(params[:id])

    authorize! :edit, @relationships_organization_user
  end

  # POST /relationships/organization_users
  # POST /relationships/organization_users.json
  def create
    @relationships_organization_user = Relationships::OrganizationUser.new(permitted_params)

    authorize! :create, @relationships_organization_user

    respond_to do |format|
      if @relationships_organization_user.save
        format.html { redirect_to @relationships_organization_user, notice: 'Organization user was successfully created.' }
        format.json { render json: @relationships_organization_user, status: :created, location: @relationships_organization_user }
      else
        format.html { render action: "new" }
        format.json { render json: @relationships_organization_user.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /relationships/organization_users/1
  # PUT /relationships/organization_users/1.json
  def update
    @relationships_organization_user = Relationships::OrganizationUser.find(params[:id])

    authorize! :update, @relationships_organization_user

    respond_to do |format|
      if @relationships_organization_user.update_attributes(permitted_params)
        format.html { redirect_to @relationships_organization_user, notice: 'Organization user was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @relationships_organization_user.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /relationships/organization_users/1
  # DELETE /relationships/organization_users/1.json
  def destroy
    @relationships_organization_user = Relationships::OrganizationUser.find(params[:id])

    authorize! :destroy, @relationships_organization_user

    @relationships_organization_user.destroy

    respond_to do |format|
      format.html { redirect_to relationships_organization_users_url }
      format.json { head :no_content }
    end
  end

  # POST /relationships/organization_users/favorite
  # POST /relationships/organization_users/favorite.js
  # POST /relationships/organization_users/favorite.json
  def favorite
    @organization = Organization.find(params[:organization_id])
    @relationships_organization_user = current_user.favorite!(@organization)

    respond_to do |format|
      format.html { redirect_to @organization }
      format.json { render json: @relationships_organization_user, status: :created }
      format.js
    end
  end

  # DELETE /relationships/organization_users/unfavorite
  # DELETE /relationships/organization_users/unfavorite.js
  # DELETE /relationships/organization_users/unfavorite.json
  def unfavorite
    @organization = Organization.find(params[:organization_id])
    @relationships_organization_user = current_user.unfavorite!(@organization)

    respond_to do |format|
      format.html { redirect_to @organization }
      format.json { render json: @relationships_organization_user, status: :created }
      format.js
    end
  end

  protected

  def permitted_params
    params.require(:relationships_organization_user).permit(:organization_id, :user_id)
  end
end


text:
![alt tag](https://img.shields.io/badge/build-passing-brightgreen.svg)

Simple socket server and client in nodejs for sqlite that allows sqlite usage in multithreaded nodejs applications.

Build dependencies (Linux): g++, gcc, make, python (v2.7 recommended, v3.x.x is not supported)

   To build the server run ./build.sh

   Below is the code in example.js (how to connect to socket server and make some queries).
The socket file (sqliteserver.socket) and database (database.db) are created where example.js file is located. The daemon (socket server) pid file (socketserver.pid) is created on folder node_modules/luisvmfsqliteserver.

****All the supported functions to query the database are currently vulnerable to sql injection attack.****

   The daemon is started when the module is loaded. When the server is ready the code inside "sqlitedbaccess.serverStatus.on('serverReady', function(){" runs. If a query is made before this event "error" is returned as "data" variable.

```javascript
var sqlitedbaccess=require("luisvmfsqliteserver");
//Simple tests to check if it is working.
sqlitedbaccess.serverStatus.on('serverReady', function(){
//All the functions bellow are asynchronous. Normaly the last one finishes first.
sqlitedbaccess.insertsqlitedb("CREATE TABLE test (info TEXT);",function (data){
	console.log(""+data);
});
sqlitedbaccess.insertsqlitedb("INSERT INTO test (info) VALUES ('1');",function (data){
	console.log(""+data);
});
sqlitedbaccess.insertsqlitedb("INSERT INTO test (info) VALUES ('2');",function (data){
	console.log(""+data);
});
sqlitedbaccess.insertsqlitedb("INSERT INTO test (info) VALUES ('3');",function (data){
	console.log(""+data);
});
sqlitedbaccess.querysqlitedb("SELECT rowid AS id, info FROM test",function (data){
	console.log(""+data);
});
});

```

If the server doesn't start automaticaly try to remove line 7 on https://github.com/luisvmf/sqlite-server/blob/master/node_modules/luisvmfsqliteserver/writesocket.js and start ./daemonize before connecting to the server.


text:
package main

import (
	"encoding/json"
	"fmt"

	"github.com/nasermirzaei89/telegram-bot-api"
)

// StatResult is stat result structure for stat request
type StatResult struct {
	Albums int `json:"albums"`
	Items  int `json:"items"`
}

func statsFunc(update tgbotapi.Update) (tgbotapi.Chattable, error) {
	resBytes, err := request(baseURL + "/stats")
	if err != nil {
		return nil, err
	}

	var result StatResult
	err = json.Unmarshal(resBytes, &result)
	if err != nil {
		return nil, err
	}

	msg := tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf("We have %d Album(s) and %d Item(s)!", result.Albums, result.Items))
	msg.ReplyToMessageID = update.Message.MessageID
	msg.ReplyMarkup = tgbotapi.NewHideKeyboard(false)

	return &msg, nil
}


text:
function makeTimeString(deciSeconds) {
  var d = "." + (deciSeconds % 10);
  var seconds = parseInt(deciSeconds / 10);

  var s = ("0" + seconds % 60).slice(-2);
  var minutes = parseInt(seconds / 60);

  var m = ("0" + minutes % 60).slice(-2) + ":";
  var h = parseInt(minutes / 60) + ":";

  // Put each part together to make the actual time display
  var timeString = h + m + s + d;

  // Remove all the leading 0s and : from the timestring, so we don't show hours
  // when we're down to 10 seconds
  while (timeString.length > 3 && (timeString[0] === "0" || timeString[0] === ":")) {
    timeString = timeString.slice(-1 * (timeString.length - 1));
  }

  return timeString;
}

function stopTimer() {
  // Clear the timeout and reset everything to 0s
  clearTimeout(window.timerTimeout);
  $("#pauseButton").css("color", "black");
  $("#pauseButton").attr("disabled", true);
  $("#timerBar").animate({width: "0"}, 1);
}

function continueTimer(deciSeconds) {
  if (deciSeconds === 0) {
    $("#timeLeft").html("Time's up!");
    stopTimer();
  } else {
    $("#timeLeft").html(makeTimeString(deciSeconds));

    // Each pass, we reduce this by 1
    var newDeciSeconds = window.lastTime = deciSeconds - 1;

    var percent = parseInt((1 - (newDeciSeconds / window.startCounter)) * 10000) / 100;
    $("#timerBar").animate({width: "" + percent + "%"}, 1);

    // Create the timeout outside the scope of this function (so we can stop it)
    window.timerTimeout = setTimeout(function(){continueTimer(newDeciSeconds);}, 100);
  }
}

function pauseTimer() {
  if (window.timerTimeout === null) {
    $("#pauseButton").css("color", "black");
    continueTimer(window.lastTime);
  } else {
    $("#pauseButton").css("color", "red");
    clearTimeout(window.timerTimeout);
    window.timerTimeout = null;
  }
}

function startTimer() {
  clearTimeout(window.timerTimeout); // Does nothing if not already set

  $("#pauseButton").attr("disabled", false);
  $("#timerBar").animate({width: "0%"}, 1);

  // Split XX:XX:XX into it's component parts
  var timeArr = $("#timer").val().split(":").reverse();

  // The last part might have decimal places, so split it further
  var secsArr = timeArr[0].split(".");

  // Convert (parse) the string that was typed into numbers (Int = integer)
  var secondsDecimal = parseInt(secsArr[1]);
  var seconds = parseInt(secsArr[0]);
  var minutes = parseInt(timeArr[1]);
  var hours = parseInt(timeArr[2]);

  // isNaN() checks the variable for something that isn't a number (NaN = Not a Number)
  // Set each component to it's default of 0 if not set
  if (isNaN(secondsDecimal)) {secondsDecimal = 0;}
  if (isNaN(seconds)) {seconds = 0;}
  if (isNaN(minutes)) {minutes = 0;}
  if (isNaN(hours)) {hours = 0;}

  while (secondsDecimal > 10) {
    secondsDecimal = parseInt(secondsDecimal / 10);
  }

  // count up the number of deci-seconds for ease of calculating
  var deciSeconds = secondsDecimal + (seconds * 10) + (minutes * 600) + (hours * 36000);
  window.startCounter = deciSeconds;
  continueTimer(deciSeconds);
}


text:
pre {
    font-family: monospace !important;
    overflow: auto;
}

.download-button {
    margin-top: 10px;
}

@media screen and (max-device-width: 400px) {
    .download-button {
        overflow: hidden;
    }
}


text:
package net.techreadiness.persistence.criteriaquery;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;

public class Criteria {
	private String queryName;
	private String fullTextSearch;
	private boolean delimitFullTextSearch = true;

	private List<CriteriaSort> sorts = new ArrayList<>();
	private List<CriteriaFilter> filters = new ArrayList<>();
	private Multimap<String, Object> parameters = HashMultimap.create();
	private Integer firstResults = null;
	private Integer pageSize = null;

	public Criteria(String queryName, Integer firstResults, Integer pageSize) {
		this.queryName = queryName;
		this.firstResults = firstResults;
		this.pageSize = pageSize;
	}

	public Criteria(Integer firstResults, Integer pageSize) {
		this.firstResults = firstResults;
		this.pageSize = pageSize;
	}

	public Criteria() {
	}

	/**
	 * Name of the query to be executed. This query must be defined in the CMOS meta-data table (CM_QUERY_SQL).
	 *
	 * @return query name
	 */
	@XmlElement(required = true)
	public String getQueryName() {
		return queryName;
	}

	/**
	 * Sets the name of the query to be executed. This query must be defined in the CMOS meta-data table (CM_QUERY_SQL).
	 *
	 * @param queryName
	 *            name of query to be executed.
	 */
	public void setQueryName(String queryName) {
		this.queryName = queryName;
	}

	/**
	 * Set the first result (starting at 1) to be retrieved. This can be used in combination with {@code setPageSize} to do
	 * paging.
	 *
	 * @return first result (starting at 1) to be retrieved
	 */
	public Integer getFirstResults() {
		return firstResults;
	}

	/**
	 * Set the first row (starting at 1) to be retrieved.
	 *
	 * @param firstResults
	 *            first row to be retrieved
	 */
	public void setFirstResults(Integer firstResults) {
		this.firstResults = firstResults;
	}

	/**
	 * Returns the limit upon the number of rows to be retrieved.
	 * @return Maximum number of results to display on a single page.
	 */
	@XmlElement(required = true)
	public Integer getPageSize() {
		return pageSize;
	}

	/**
	 * Set a limit upon the number of rows to be retrieved.
	 *
	 * @param pageSize
	 *            max number of rows to be retrieved
	 */
	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append(queryName);
		if (sorts != null && sorts.size() > 0) {
			sb.append(" ( sortOrder=[");
			for (CriteriaSort sort : sorts) {
				sb.append(sort.fieldName + (sort.isDescending() ? "asc " : "desc "));
			}
			sb.append(")");
		}
		if (firstResults != null) {
			sb.append(", firstResults=" + firstResults);
		}
		if (pageSize != null) {
			sb.append(", pageSize=" + pageSize);
		}
		sb.append(", parameters=[");
		if (filters == null) {
			sb.append("none");
		} else {
			for (CriteriaFilter filter : filters) {
				sb.append(filter + ",");
			}
			// sb.append(StringUtils.join(parameters, ','));
		}
		sb.append("]");
		return sb.toString();
	}

	public String getFullTextSearch() {
		return fullTextSearch;
	}

	public void setFullTextSearch(String fullTextSearch) {
		this.fullTextSearch = fullTextSearch;
	}

	public List<CriteriaFilter> getFilters() {
		return filters;
	}

	public void setFilters(List<CriteriaFilter> filters) {
		this.filters = filters;
	}

	public void addFilter(CriteriaFilter filter) {
		filters.add(filter);
	}

	public void addSimpleFilter(String field, String value) {
		filters.add(new CriteriaFilter(field, value));
	}

	public void addSort(CriteriaSort sort) {
		sorts.add(sort);
	}

	public List<CriteriaSort> getSorts() {
		return sorts;
	}

	public void setSorts(List<CriteriaSort> sorts) {
		this.sorts = sorts;
	}

	public boolean isPagingActive() {
		return pageSize != null && firstResults != null;
	}

	public Multimap<String, Object> getParameters() {
		return parameters;
	}

	public void setParameters(Multimap<String, Object> parameters) {
		this.parameters = parameters;
	}

	public boolean getDelimitFullTextSearch() {
		return delimitFullTextSearch;
	}

	public void setDelimitFullTextSearch(boolean delimitFullTextSearch) {
		this.delimitFullTextSearch = delimitFullTextSearch;
	}
}


text:
.class Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter$1;
.super Lcom/google/common/collect/AbstractMapEntry;
.source "WellBehavedMap.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter;->apply(Ljava/lang/Object;)Ljava/util/Map$Entry;
.end annotation

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

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Lcom/google/common/collect/AbstractMapEntry",
        "<TK;TV;>;"
    }
.end annotation

# instance fields
.field final synthetic this$0:Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter;

.field final synthetic val$key:Ljava/lang/Object;

# direct methods
.method constructor <init>(Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter;Ljava/lang/Object;)V
    .locals 0

    .prologue
    .line 74
    .local p0, "this":Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter$1;, "Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter.1;"
    iput-object p1, p0, Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter$1;->this$0:Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter;

    iput-object p2, p0, Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter$1;->val$key:Ljava/lang/Object;

    invoke-direct {p0}, Lcom/google/common/collect/AbstractMapEntry;-><init>()V

    return-void
.end method

# virtual methods
.method public getKey()Ljava/lang/Object;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()TK;"
        }
    .end annotation

    .prologue
    .line 76
    .local p0, "this":Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter$1;, "Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter.1;"
    iget-object v0, p0, Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter$1;->val$key:Ljava/lang/Object;

    return-object v0
.end method

.method public getValue()Ljava/lang/Object;
    .locals 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()TV;"
        }
    .end annotation

    .prologue
    .line 79
    .local p0, "this":Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter$1;, "Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter.1;"
    iget-object v0, p0, Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter$1;->this$0:Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter;

    iget-object v0, v0, Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter;->map:Ljava/util/Map;

    iget-object v1, p0, Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter$1;->val$key:Ljava/lang/Object;

    invoke-interface {v0, v1}, Ljava/util/Map;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    return-object v0
.end method

.method public setValue(Ljava/lang/Object;)Ljava/lang/Object;
    .locals 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(TV;)TV;"
        }
    .end annotation

    .prologue
    .line 82
    .local p0, "this":Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter$1;, "Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter.1;"
    .local p1, "value":Ljava/lang/Object;, "TV;"
    iget-object v0, p0, Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter$1;->this$0:Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter;

    iget-object v0, v0, Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter;->map:Ljava/util/Map;

    iget-object v1, p0, Lcom/google/common/collect/WellBehavedMap$KeyToEntryConverter$1;->val$key:Ljava/lang/Object;

    invoke-interface {v0, v1, p1}, Ljava/util/Map;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    return-object v0
.end method


text:
"""
    Sahana Eden Stats Controller
"""

if not settings.has_module(c):
    raise HTTP(404, body="Module disabled: %s" % c)

# -----------------------------------------------------------------------------
def index():
    """ Module's Home Page """

    return s3db.cms_index(c, alt_function="index_alt")

# -----------------------------------------------------------------------------
def index_alt():
    """
        Module homepage for non-Admin users when no CMS content found
    """

    # Just redirect to the Demographic Data
    s3_redirect_default(URL(f = "demographic_data",
                            args = "summary",
                            ))

# -----------------------------------------------------------------------------
def parameter():
    """ REST Controller """

    return s3_rest_controller()

# -----------------------------------------------------------------------------
def data():
    """ REST Controller """

    return s3_rest_controller()

# -----------------------------------------------------------------------------
def source():
    """ REST Controller """

    return s3_rest_controller()

# -----------------------------------------------------------------------------
def demographic():
    """ REST Controller """

    return s3_rest_controller()

# -----------------------------------------------------------------------------
def demographic_data():
    """ REST Controller """

    return s3_rest_controller()

# -----------------------------------------------------------------------------
def demographic_aggregate():
    """ REST Controller """

    def clear_aggregates(r, **attr):
        if not auth.s3_has_role("ADMIN"):
            auth.permission.fail()
        s3db.stats_demographic_rebuild_all_aggregates()
        redirect(URL(c = "stats",
                     f = "demographic_aggregate",
                     args = "",
                     ))

    s3db.set_method("stats", "demographic_aggregate",
                    method = "clear",
                    action = clear_aggregates,
                    )

    output = s3_rest_controller()
    return output

# -----------------------------------------------------------------------------
def impact_type():
    """ REST Controller for impact types """

    return s3_rest_controller()

# END =========================================================================


text:
import sys
import os
import sublime_kattis.requests as requests

if sys.version_info[0] >= 3:
    # Python 3
    import configparser
else:
    # Python 2
    import ConfigParser as configparser

class KattisConfig:
    """
    Contains the logic for managing the .kattisrc configuration file,
    and creating KattisConfig objects that can be passed to the L{KattisClient}
    """

    @staticmethod
    def create_from_file(path="/usr/local/etc/kattisrc"):
        """
        Loads a KattisConfig from a .kattisrc file. Looks in the given path,
        the current directory, and the home directory of the current user

        @type path: String
        @param path: A default path to look in

        @raise KattisConfigException: Raised if the .kattisrc file can not be found, or is corrupted

        @rtype: KattisConfig
        @return: A KattisConfig object based on the .kattisrc file
        """
        cfg = configparser.ConfigParser()

        print(os.path.expanduser("~"))

        if not cfg.read([
            path,
            os.path.join(os.getenv('HOME'), '.kattisrc'),
            os.path.join(os.path.expanduser("~"), '.kattisrc'),
            os.path.join(os.path.dirname(
                os.path.realpath(__file__)), '.kattisrc')
        ]):
            raise KattisConfigException(
                "Could not locate .kattisrc! Make sure it is placed under your home directory!")

        username = token = password = loginurl = submissionurl = None

        try:
            username = cfg.get("user", "username")
        except configparser.NoOptionError:
            pass

        try:
            token = cfg.get("user", "token")
        except configparser.NoOptionError:
            pass

        try:
            password = cfg.get("user", "password")
        except configparser.NoOptionError:
            pass

        try:
            loginurl = cfg.get("kattis", "loginurl")
        except configparser.NoOptionError:
            pass

        try:
            submissionurl = cfg.get("kattis", "submissionurl")
        except configparser.NoOptionError:
            pass

        if (password is None and token is None) or username is None or loginurl is None or submissionurl is None:
            raise KattisConfigException(
                "Your .kattisrc seems to be corrupted, please redownload it")

        return KattisConfig(username, token, password, loginurl, submissionurl)

    def __init__(self, username, token, password, loginurl, submissionurl):
        """
        Instantiates a new KattisConfig object with the given parameters

        @type username: String
        @param username: The username of the user

        @type token: String
        @param token: The access token of the user, can be None

        @type password: String
        @param password: The password of the user, can be None if token is not None

        @type loginurl: String
        @param loginurl: The login url, used to differentiate between open/kth Kattis

        @type submissionurl: String
        @param submissionurl: The submission url, used to differentiate between open/kth Kattis
        """
        self.username = username
        self.token = token
        self.password = password,
        self.loginurl = loginurl
        self.submissionurl = submissionurl

        if password is None and token is None:
            raise KattisConfigException(
                "Either token or password must be provided, currently neither are.")

class KattisSubmission:
    """
    Contains the logic for creating a kattis submission that can be passed to the L{KattisClient}.
    """

    LANGUAGE_GUESS = {
        '.java': 'Java',
        '.c': 'C',
        '.cpp': 'C++',
        '.h': 'C++',
        '.cc': 'C++',
        '.cxx': 'C++',
        '.c++': 'C++',
        '.py': 'Python 3',
        '.cs': 'C#',
        '.c#': 'C#',
        '.go': 'Go',
        '.m': 'Objective-C',
        '.hs': 'Haskell',
        '.pl': 'Prolog',
        '.js': 'JavaScript',
        '.php': 'PHP',
        '.rb': 'Ruby'
    }

    GUESS_MAINCLASS = {'Java', 'Python'}

    @staticmethod
    def create_from_file(files):
        """
        Creates a new KattisSubmission from the given files

        @type files: [String]
        @param files: List of the paths of files to be included in the submission

        @raise KattisSubmissionException: Raised when the no files are provided or when
        the specifics of the submission can not be guessed

        @rtype: KattisSubmission
        @return: A KattisSubmission object based on the files provided
        """
        if len(files) == 0:
            raise KattisSubmissionException(
                "No files provided. Make sure your file list is not empty")

        for file in files:
            if not os.path.isfile(file):
                raise KattisSubmissionException("One or more of the given files do not exist")

        problem, ext = os.path.splitext(os.path.basename(files[0]))
        language = KattisSubmission.LANGUAGE_GUESS.get(ext, None)
        if language is None:
            raise KattisSubmissionException(
                "Could not guess submission language. Make sure your files have the correct extensions")

        mainclass = problem if language in KattisSubmission.GUESS_MAINCLASS else None

        return KattisSubmission(problem, language, files, mainclass)

    def __init__(self, problem, language, files, mainclass=""):
        """
        Instantiates a new KattisSubmission object.

        @type problem: String
        @param problem: The name of the problem for this submission

        @type language: String
        @param language: The programming language of this submission

        @type files: [String]
        @param files: The list of files to include in this submission

        @type mainclass: String
        @param mainclass: The main class of the submission
        """
        self.problem = problem
        self.language = language
        self.files = files
        self.mainclass = mainclass

class KattisSubmissionResult:
    """
    Contains logic for handling successful submission results.
    """

    @staticmethod
    def create_from_response(response, config):
        """
        Creates a new submission result from the response object.

        @type response: Requests response
        @param response: Response object of a returned by a submission request.

        @type config: KattisConfig
        @param config: The configuration of the client. Used to generate a submission link.

        @rtype: KattisSubmissionResult
        @return: The submission result object created from the response
        """
        split = response.text.split(" ")
        submission_id = split[len(split) - 1][:-1]
        message = response.text
        link = config.submissionurl[:-7] + "/submissions/" + submission_id

        return KattisSubmissionResult(submission_id, message, link)

    def __init__(self, submission_id, text, link):
        """
        Instantiates a new KattisSubmissionResult object with the given parameters.

        @type submission_id: String
        @param submission_id: The id of the problem of the submission

        @type text: String
        @param: The response text of the submission

        @type link: String
        @param link: The link to the result page
        """
        self.submission_id = submission_id
        self.text = text
        self.link = link

class KattisClient:
    """
    A client for executing Kattis requests
    """

    HEADERS = {'User-Agent': 'kattis-cli-submit'}

    @staticmethod
    def create_from_config(kattis_config):
        """
        Authenticates the user with the given KattisConfig

        @type kattis_config: KattisConfig
        @param kattis_config: The KattisConfig used to authenticate with Kattis

        @rtype: KattisClient
        @return: The authenticated KattisClient
        """
        if kattis_config is None:
            raise KattisClientException(
                "No config provided. Make sure you are not passing None values")

        if kattis_config.password is None and kattis_config.token is None:
            raise KattisConfigException(
                "Your .kattisrc seems to be corrupted. Please download a new one.")

        login_args = {'user': kattis_config.username, 'script': 'true'}
        if kattis_config.password:
            login_args['password'] = kattis_config.password
        if kattis_config.token:
            login_args['token'] = kattis_config.token

        res = requests.post(kattis_config.loginurl,
                            data=login_args, headers=KattisClient.HEADERS)
        if not res.status_code == 200:
            raise KattisClientException(
                "Could not log in to Kattis. Status code: " + str(res.status_code))

        return KattisClient(kattis_config, res.cookies)

    def __init__(self, kattis_config, auth_cookies):
        """
        Instantiate a new KattisClient object

        @type kattis_config: KattisConfig
        @param kattis_config: The configuration of the client

        @type auth_cookies: Dict
        @param auth_cookies: The authentication cookies obtained from Kattis
        """
        self.config = kattis_config
        self.auth_cookies = auth_cookies

    def submit_solution(self, kattis_submission):
        """
        Submits a solution to Kattis. Returns a KattisSubmissionResult on success,
        otherwise throws a KattisClientException.

        @type kattis_submission: KattisSubmission
        @param kattis_submission: The Kattis

        @raise KattisClientException: Raised when the submission is unsucessful
                                      (return code is not 200)

        @rtype: KattisSubmissionResult
        @return: The successful result of the submission
        """
        data = {'submit': 'true',
                'submit_ctr': 2,
                'language': kattis_submission.language,
                'mainclass': kattis_submission.mainclass,
                'problem': kattis_submission.problem,
                'tag': '',
                'script': 'true'}

        sub_files = []
        for f in kattis_submission.files:
            with open(f) as sub_file:
                sub_files.append(('sub_file[]',
                                  (os.path.basename(f),
                                   sub_file.read(),
                                   'application/octet-stream')))

        response = requests.post(
            self.config.submissionurl, data=data, files=sub_files,
            cookies=self.auth_cookies, headers=KattisClient.HEADERS)

        if not response.status_code == 200:
            raise KattisClientException(
                "Could not submit to Kattis. Status code: " + str(res.status_code))

        return KattisSubmissionResult.create_from_response(response, self.config)

class KattisException(Exception):
    pass

class KattisConfigException(KattisException):
    pass

class KattisSubmissionException(KattisException):
    pass

class KattisClientException(KattisException):
    pass


text:
package com.google.android.gms.drive.metadata.internal;

import android.os.Bundle;
import android.os.Parcelable;
import com.google.android.gms.drive.metadata.CollectionMetadataField;
import java.util.ArrayList;
import java.util.Collection;

public class e<T extends Parcelable> extends CollectionMetadataField<T>
{
  public e(String paramString)
  {
    super(paramString);
  }

  protected void a(Bundle paramBundle, Collection<T> paramCollection)
  {
    paramBundle.putParcelableArrayList(getName(), new ArrayList(paramCollection));
  }

  protected Collection<T> i(Bundle paramBundle)
  {
    return paramBundle.getParcelableArrayList(getName());
  }
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     com.google.android.gms.drive.metadata.internal.e
 * JD-Core Version:    0.6.2
 */


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DashboardComponent } from './dashboard.component';
import { MdButtonToggleModule, MdCardModule, MdIconModule } from '@angular/material';
import { LoadAverageComponent } from './load-average/load-average.component';
import {
  DashboardCardComponent, DashboardCardContentComponent,
  DashboardCardActionsComponent, DashboardCardDetailContentComponent, DashboardCardChartComponent
} from './dashboard-card/dashboard-card.component';
import { ChartModule } from 'angular2-highcharts';
import {SystemInfoComponent} from './system-info/system-info.component';
import {MemoryUsageComponent} from './memory-usage/memory-usage.component';
import { CpuLoadComponent } from './cpu-load/cpu-load.component';

@NgModule({
  imports: [
    CommonModule,
    MdCardModule,
    MdButtonToggleModule,
    MdIconModule,
    ChartModule
  ],
  declarations: [
    DashboardComponent,
    LoadAverageComponent,
    DashboardCardComponent,
    DashboardCardContentComponent,
    DashboardCardDetailContentComponent,
    DashboardCardChartComponent,
    DashboardCardActionsComponent,
    MemoryUsageComponent,
    CpuLoadComponent,
    SystemInfoComponent
  ],
  exports: [
    DashboardComponent
  ]
})
export class DashboardModule { }


text:
EarlGrey includes three main groups of APIs:

  * [Interaction APIs](#interaction-apis)
  * [Synchronization APIs](#synchronization-apis)
  * [Other Top Level APIs](#other-top-level-apis)

## Interaction APIs

EarlGrey test cases are made up of interactions with UI elements. Each interaction consists of:

  * Selecting an element to interact with,
  * Performing an action on it, and/or
  * Making an assertion to verify state and behavior.

To reflect this, the Interaction APIs are organized into the following:

  * [Selection API](#selection-api)
  * [Action API](#action-api)
  * [Assertion API](#assertion-api)

Each of these APIs is designed with extensibility in mind, giving the user flexibility for customization,
while preserving the prose-like structure of tests. Consider the following snippet:

```objc
[EarlGrey selectElementWithMatcher:grey_accessibilityID(@"ClickMe")];
```

It shows how to start an interaction by selecting an element with `ClickMe` as the Accessibility
Identifier. After you select an element, you can continue the interaction with an action or an
assertion. EarlGrey works with any element that conforms to the [UIAccessibility protocol](https://developer.apple.com/library/ios/documentation/uikit/reference/UIAccessibility_Protocol/Introduction/Introduction.html),
not just `UIViews`; this allows tests to perform a richer set of interactions.

You can chain a selection and an action in one statement. For example, you can tap on the element
that has `ClickMe` as its Accessibility Identifier as follows:

```objc
[[EarlGrey selectElementWithMatcher:grey_accessibilityID(@"ClickMe")]
    performAction:grey_tap()];
```

Note: `selectElementWithMatcher:` doesn't return an element; it just marks the beginning of an
interaction.

You can also chain a selection and an assertion. The following snippet shows how to select an
element that has `ClickMe` as its accessibility identifier and asserts that it is displayed:

```objc
[[EarlGrey selectElementWithMatcher:grey_accessibilityID(@"ClickMe")]
    assertWithMatcher:grey_sufficientlyVisible()];
```

Finally, you can perform actions and assertions in sequence. The following statement finds an element with
the accessibility identifier `ClickMe`, taps on it, and asserts that it is not displayed.

```objc
[[[EarlGrey selectElementWithMatcher:grey_accessibilityID(@"ClickMe")]
    performAction:grey_tap()]
    assertWithMatcher:grey_notVisible()];
```

The following is an example of a simple interaction:

```objc
[[[EarlGrey selectElementWithMatcher:<element_matcher>]
    performAction:<action>]
    assertWithMatcher:<assertion_matcher>];
```

Where `<element_matcher>` and `<assertion_matcher>` are matchers contained in `GREYMatchers.h` and
`<action>` is one of the actions in `GREYActions.h`. Because each of these has a shorthand
C-function, instead of using `[GREYMatchers matcherForSufficientlyVisible]` you can use
`grey_sufficientlyVisible()`. Shorthand notation is enabled by default. To disable it, add
`#define GREY_DISABLE_SHORTHAND 1` to the project's prefix header.

### Selection API

Use the Selection API to locate a UI element on the screen. This API accepts a matcher and tests it against all
the elements in the UI hierarchy to locate an element to interact with. In
EarlGrey, matchers support an API that is similar to that of [OCHamcrest](https://github.com/hamcrest/OCHamcrest)
matchers. You can combine matchers using AND-OR-NOT logic, allowing you to create matching rules
that can pinpoint any element in the UI hierarchy.

#### EarlGrey Matchers

All EarlGrey matchers are available in the [GREYMatchers](../EarlGrey/Matcher/GREYMatchers.m)
factory class. The best way to find a UI element is to use its accessibility properties. We
strongly recommend using an [accessibility identifier](https://developer.apple.com/library/ios/documentation/uikit/reference/UIAccessibilityIdentification_Protocol/Introduction/Introduction.html)
as it uniquely identifies an element. Use `grey_accessibilityID()` as your matcher to select a UI
element by its accessibility identifier. You can also use other accessibility properties, such as using
`grey_accessibilityTrait()` as the matcher for UI elements with specific accessibility traits, or by using
`grey_accessibilityLabel()` as the matcher for accessibility labels.

A matcher can be ambiguous and match multiple elements: for example, `grey_sufficientlyVisible()`
will match all sufficiently visible UI elements. In such cases, you must narrow down the
selection until it can uniquely identify a single UI element. You can make the matchers more specific
by combining matchers with `grey_allOf()`, `grey_anyOf()`, `grey_not()`  or by supplying a root
matcher with the `inRoot` method to narrow the selection.

Consider these examples for both cases.

First, with collection matchers, the following snippet finds a UI element that has an accessibility
label `Send` **and** is displayed on the screen.

```objc
id<GREYMatcher> visibleSendButtonMatcher =
    grey_allOf(grey_accessibilityLabel(@"Send"), grey_sufficientlyVisible(), nil);

[[EarlGrey selectElementWithMatcher:visibleSendButtonMatcher]
    performAction:grey_tap()];
```

Note that with `grey_allOf` the order matters. If `grey_sufficientlyVisible` is used first, then every element
in the entire application will be checked for visibility. It's important to order matchers from
most selective (such as accessibility label and accessibility id) to least.

Next, with `inRoot`, the following statement finds an element that has the accessibility label set
to `Send` and is contained in a UI element that is an instance of the `SendMessageView` class.

```objc
[[[EarlGrey selectElementWithMatcher:grey_accessibilityLabel(@"Send")]
    inRoot:grey_kindOfClass([SendMessageView class])]
    performAction:grey_tap()];
```

#### Custom Matchers

To create custom matchers, use the block-based [GREYElementMatcherBlock](../EarlGrey/Matcher/GREYElementMatcherBlock.h)
class. For example, the following code matches views that don't have any subviews:

```objc
+ (id<GREYMatcher>)matcherForViewsWithoutSubviews {
  MatchesBlock matches = ^BOOL(UIView *view) {
    return view.subviews.count == 0;
  };
  DescribeToBlock describe = ^void(id<GREYDescription> description) {
    [description appendText:@"Views without subviews"];
  };

  return [[GREYElementMatcherBlock alloc] initWithMatchesBlock:matches
                                              descriptionBlock:describe];
}
```

`MatchesBlock` can also accept type `id` instead of `UIView *`. You should use `id` when the
matcher must also work with accessibility elements. The following matcher example works
universally for all UI element types:

```objc
+ (id<GREYMatcher>)matcherForElementWithoutChildren {
  MatchesBlock matches = ^BOOL(id element) {
    if ([element isKindOfClass:[UIView class]]) {
      return ((UIView *)element).subviews.count == 0;
    }
    // Handle accessibility elements here.
    return ...;
  };
  DescribeToBlock describe = ^void(id<GREYDescription> description) {
    [description appendText:@"UI element without children"];
  };
  return [[GREYElementMatcherBlock alloc] initWithMatchesBlock:matches
                                              descriptionBlock:describe];
}
```

This matcher can be used in a test to select a UI element that doesn't have any children (or
subviews) and double-tap on it (assuming that the method was declared in a class `CustomMatchers`):

```objc
[[EarlGrey selectElementWithMatcher:[CustomMatchers matcherForElementWithoutChildren]]
    performAction:grey_doubleTap()];
```

#### Selecting Off-Screen UI Elements

In certain situations the UI element may be hidden off-screen, and may require certain interactions
to bring it onto the screen. Common examples include scrolling to an element that is not visible in
the scrollview, zooming-in on a map to show UI elements that are shown only in street-view,
navigating through a [UICollectionView](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionView_class/)
that has a custom layout, etc. You can use the `[usingSearchAction:onElementWithMatcher:]` method
to provide a search action for such elements. The API allows you to specify a search action and a
matcher for the element on which the search action will be applied. EarlGrey applies the search
action repeatedly until the element you are looking for is found (or a timeout occurs).

For example, the following statement attempts to find an element matching `aButtonMatcher` by
repeatedly scrolling down (by 50 points at a time) on the element matching `aScrollViewMatcher` and
taps the button when it finally finds it.

```objc
[[[EarlGrey selectElementWithMatcher:aButtonMatcher]
    usingSearchAction:grey_scrollInDirection(kGREYDirectionDown, 50)
 onElementWithMatcher:aScrollViewMatcher]
    performAction:grey_tap()];
```

And in this example, this statement attempts to find a table view cell matching `aCellMatcher` by
repeatedly scrolling up (by 50 points at a time) on a table matching `aTableViewMatcher`.

```objc
[[[EarlGrey selectElementWithMatcher:aCellMatcher]
    usingSearchAction:grey_scrollInDirection(kGREYDirectionUp, 50)
 onElementWithMatcher:aTableViewMatcher]
    performAction:grey_tap()];
```

### Action API

Use the Action API to specify the test actions to perform on a selected UI element.

#### EarlGrey Actions

All EarlGrey actions are available in the [GREYActions](../EarlGrey/Action/GREYActions.h) factory
class. The most common action is tapping (or clicking) on a given element using the `grey_tap()`
method:

```objc
[[EarlGrey selectElementWithMatcher:grey_accessibilityID(@"TapMe")]
    performAction:grey_tap()];
```

If an action triggers changes in the UI hierarchy, EarlGrey synchronizes each action (including
chained actions) with the UI, ensuring that it is in a stable state before the next action is
performed.

Not all actions can be performed on all elements; for example, the tap action cannot be performed
on elements that are not visible. To enforce this, EarlGrey uses **constraints** which are
preconditions in the form of [GREYMatcher](../EarlGrey/Matcher/GREYMatcher.h) that
must be met before an action is actually performed. Failure to meet these constraints results in an
exception being thrown and the test marked as failed. To avoid test failure, you can invoke
`performAction:error:` to get an [NSError](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/)
object containing failure details.

```objc
NSError *error;
[[EarlGrey selectElementWithMatcher:grey_accessibilityID(@"Non-Existent-Ax-Id")]
    performAction:grey_tap()
            error:&error];
```

In the above case, an exception **will not** be thrown for the EarlGrey interaction being performed
on a non-existent element. Instead, the error object passed will save the failure details and not
fail the test immediately. The error details can then be perused for finding the failure details.

#### Custom Actions

Custom actions can be created by conforming to the [GREYAction](../EarlGrey/Action/GREYAction.h)
protocol. For convenience, you can use [GREYActionBlock](../EarlGrey/Action/GREYActionBlock.h),
which already conforms to the GREYAction protocol and allows you to express an action in the form
of a block. The following code creates an action using a block that invokes a custom selector
(`animateWindow`) to animate the selected element's window:

```objc
- (id<GREYAction>)animateWindowAction {
  return [GREYActionBlock actionWithName:@"Animate Window"
                             constraints:nil
                            performBlock:^(id element, NSError *__strong *errorOrNil) {
    // First, make sure the element is attached to a window.
    if ([element window] == nil) {
      // Populate error.
      *errorOrNil = ...
      // Indicates that the action failed.
      return NO;
    }
    // Invoke a custom selector that animates the window of the element.
    [element animateWindow];
    // Indicates that the action was executed successfully.
    return YES;
  }];
}
```

### Assertion API

Use the Assertion API to verify the state and behavior of a UI element.

#### Assertions Using Matchers

Use `assertWithMatcher:` to perform an assertion with [GREYMatcher](../EarlGrey/Matcher/GREYMatcher.h)
matchers. The selected element is run through the matcher for verification. For example,
the following snippet asserts that the element with the accessibility ID `ClickMe` is visible,
and the test fails if the element is not visible on the screen.

```objc
[[EarlGrey selectElementWithMatcher:grey_accessibilityID(@"ClickMe")]
    assertWithMatcher:grey_sufficientlyVisible()];
```

To prevent test failure, you can provide an `NSError` object to the `assertWithMatcher:error:`
method, as in the statement shown below. Instead of failing, the EarlGrey assertion will provide
you with an `NSError` object that contains details about the failure.

```objc
NSError *error;
[[EarlGrey selectElementWithMatcher:grey_accessibilityID(@"ClickMe")]
    assertWithMatcher:grey_sufficientlyVisible()
                error:&error];
```

You can also perform an assertion by using the `assert` method and passing an instance of
[`GREYAssertion`](../EarlGrey/Assertion/GREYAssertion.h). We recommend that you create
assertions from matchers using `assertWithMatcher:`
whenever possible. Matchers are lightweight and ideal for simple assertions. However, a custom
`GREYAssertion` could be a better choice in the case of an assertion that needs to perform complex
logic, like manipulating the UI, to proceed with the assertion.

#### Custom Assertions

You can create custom assertions using the [`GREYAssertion`](../EarlGrey/Assertion/GREYAssertion.h)
protocol or by using [`GREYAssertionBlock`](../EarlGrey/Assertion/GREYAssertionBlock.h) that
accepts the assertion logic in a block. The following example uses `GREYAssertionBlock` to write an
assertion that checks that the view's alpha is equal to the provided value:

```objc
+ (id<GREYAssertion>)hasAlpha:(CGFloat)alpha {
  return [GREYAssertionBlock assertionWithName:@"Has Alpha"
                                assertionBlock:^(UIView *view, NSError *__strong *errorOrNil) {
    if (view.alpha != alpha) {
      NSString *reason =
        [NSString stringWithFormat:@"Alpha value doesn't match for %@", view];
      // Check if errorOrNil was provided, if so populate it with relevant details.
      if (errorOrNil) {
        *errorOrNil = ...
      }
      // Indicates assertion failed.
      return NO;
    }
    // Indicates assertion passed.
    return YES;
  }];
}
```

Note: Do not assume that assertions are run against valid UI elements. You will need to perform
your own check to make sure the UI element is in a valid state before validating the assertion. For
instance, the following snippet checks that the element exists (that it isn't `nil`) before
asserting the rest of the state:

```objc
+ (id<GREYAssertion>)hasAlpha:(CGFloat)alpha {
  return [GREYAssertionBlock assertionWithName:@"Has Alpha"
                                assertionBlock:^(UIView *view, NSError *__strong *errorOrNil) {
    // Assertions can be performed on nil elements. Make sure view isn't nil.
    if (view == nil) {
      // Check if errorOrNil was provided, if so populate it with relevant details.
      if (errorOrNil) {
        *errorOrNil = [NSError errorWithDomain:kGREYInteractionErrorDomain
                                        code:kGREYInteractionElementNotFoundErrorCode
                                    userInfo:nil];
      }
      return NO;
    }
    // Perform rest of the assertion logic.
    ...
    // Indicates assertion passed.
    return YES;
  }];
}
```

Alternatively, you can create a class that conforms to
[GREYAssertion](../EarlGrey/Assertion/GREYAssertion.h).

#### Failure Handlers

By default, EarlGrey uses a failure handler that is invoked when any exception is raised by the
framework. The default handler logs the exception, takes a screenshot, and then prints its path
along with any other useful information. You can choose to provide your own custom failure handler
and install it using the `EarlGrey setFailureHandler:` API which replaces the global default
framework handler. To create a custom failure handler, write a class that conforms to the
[GREYFailureHandler](../EarlGrey/Exception/GREYFailureHandler.h) protocol:

```objc
@interface MyFailureHandler : NSObject <GREYFailureHandler>
@end

@implementation MyFailureHandler

- (void)handleException:(GREYFrameworkException *)exception details:(NSString *)details {
  // Log the failure and state of the app if required.
  // Call thru to XCTFail() with an appropriate error message.
}

- (void)setInvocationFile:(NSString *)fileName
        andInvocationLine:(NSUInteger)lineNumber {
  // Record the file name and line number of the statement which was executing before the
  // failure occurred.
}
@end
```

#### Assertions Macros

EarlGrey provides its own macros that can be used within a testcase for
assertion and verification. These macros are similar to the macros provided by
XCTest and invoke the global failure handler upon assertion failure.

  * `GREYAssert(expression, reason, ...)` — Fails if the expression evaluates to false
  * `GREYAssertTrue(expression, reason, ...)` — Fails if the expression evaluates to
false. Use for BOOL expressions
  * `GREYAssertFalse(expression, reason, ...)` — Fails if the expression evaluates to
true. Use for BOOL expressions
  * `GREYAssertNotNil(expression, reason, ...)` — Fails if the expression evaluates to
nil
  * `GREYAssertNil(expression, reason, ...)` — Fails if the expression evaluates to a
non-nil value
  * `GREYAssertEqual(left, right, reason, ...)` — Fails if left != right for scalar
types
  * `GREYAssertNotEqual(left, right, reason, ...)` — Fails if left == right for scalar
types
  * `GREYAssertEqualObjects(left, right, reason, ...)` — Fails if [left isEqual:right] returns
false
  * `GREYAssertNotEqualObjects(left, right, reason, ...)` — Fails if [left isEqual:right] returns
true
  * `GREYFail(reason, ...)` — Fails immediately with the provided reason
  * `GREYFailWithDetails(reason, details, ...)` — Fails immediately with the provided reason and
  details

#### Layout Testing

EarlGrey provides APIs to verify the layout of UI elements; for example, to verify that element X
is to the left of element Y. Layout assertions are modeled after [NSLayoutConstraint](https://developer.apple.com/library/ios/DOCUMENTATION/AppKit/Reference/NSLayoutConstraint_Class/index.html).
To verify the layout, you need to first create a constraint that specifies the layout,
select an element constrained by it, and then assert that it matches the constraint using
`grey_layout(...)`. Note that `grey_layout(...)` takes an array of constraints, all of which must
be satisfied. This allows for easy specification of complex layout assertions.

For example, the following constraint specifies that the selected element is to the right of any
other arbitrary element used as a reference.

```objc
GREYLayoutConstraint *rightConstraint =
    [GREYLayoutConstraint layoutConstraintWithAttribute:kGREYLayoutAttributeLeft
                                              relatedBy:kGREYLayoutRelationGreaterThanOrEqual
                                   toReferenceAttribute:kGREYLayoutAttributeRight
                                             multiplier:1.0
                                               constant:0.0];
```

You can now select the element with the `RelativeRight` accessibility ID and use
`grey_layout(@[rightConstraint])` to assert if it's on the right of the reference element, which in
our example is the element with `TheReference` accessibility ID.

```objc
[[EarlGrey selectElementWithMatcher:grey_accessibilityID(@"RelativeRight")]
    assertWithMatcher:grey_layout(@[rightConstraint], grey_accessibilityID(@"TheReference"))];
```

You can also create simple directional constraints using `layoutConstraintForDirection:`. The
following code is equivalent to the previous example:

```
GREYLayoutConstraint *rightConstraint =
    [GREYLayoutConstraint layoutConstraintForDirection:kGREYLayoutDirectionRight
                                  andMinimumSeparation:0.0];
```

## Synchronization APIs

These APIs let you control how EarlGrey synchronizes with the app under test.

### GREYCondition

If your test case requires special handling, you can use `GREYCondition` to wait or synchronize
with certain conditions. `GREYCondition` takes a block that returns a `BOOL` to indicate whether
the condition has been met. The framework polls this block until the condition is met before
proceeding with rest of the test case. The following snippet illustrates how to create and use a
`GREYCondition`:

```objc
GREYCondition *myCondition = [GREYCondition conditionWithName:@"my condition"
                                                        block:^BOOL {
  ... do your condition check here ...
  return yesIfMyConditionWasSatisfied;
}];
// Wait for my condition to be satisfied or timeout after 5 seconds.
BOOL success = [myCondition waitWithTimeout:5];
if (!success) {
  // Handle condition timeout.
}
```

### Synchronization

EarlGrey automatically waits for the app to idle by tracking the main dispatch queue, main
operation queue, network, animations and several other signals and performs interactions only when
the app is Idle. However there may be situations where the interactions must be performed in spite
of app being busy. For example in a messaging app, a photo might be uploading and corresponding animation
running but the test might still want to type and send a text message. To address such situations, you can
disable EarlGrey's synchronization using `kGREYConfigKeySynchronizationEnabled`, as shown in the following snippet:

```objc
[[GREYConfiguration sharedInstance] setValue:@(NO)
                                forConfigKey:kGREYConfigKeySynchronizationEnabled];
```

Once disabled all interactions will proceed without waiting for the app to idle until synchronization is
reenabled again. Note that to maximize test effectiveness, synchronization must be reenabled as soon
as possible. Also instead of disabling synchronization completely you can configure the synchronization parameters
to suit the needs of your app. For example:

- `kGREYConfigKeyNSTimerMaxTrackableInterval` can be used to specify the maximum interval of non-repeating
NSTimers that EarlGrey should synchronize with.
- `kGREYConfigKeyDispatchAfterMaxTrackableDelay` can be used to specify the maximum delay
for future executions using `dispatch_after` calls that EarlGrey must synchronize with.
- `kGREYConfigKeyURLBlacklistRegex` can be used to specify a list of URLs for which EarlGrey should
**not** wait.

And several such configurations are available in [GREYConfiguration](../EarlGrey/Common/GREYConfiguration.h).
See below for some specific use cases in detail.

### Network

By default, EarlGrey synchronizes with all network calls, but you can customize this behavior by
providing regular expressions to skip over certain URLs. To blacklist a URL, create a regular
expression that matches the URL, add it to an `NSArray` and pass it to `GREYConfiguration`.
For multiple URLs, repeat the same process by creating one regular expression for each URL.
For example, to tell the framework not to wait for www.google.com and www.youtube.com,
do something like:

```objc
NSArray *blacklist = @[ @".*www\\.google\\.com", @".*www\\.youtube\\.com" ];
[[GREYConfiguration sharedInstance] setValue:blacklist
                                forConfigKey:kGREYConfigKeyURLBlacklistRegex];
```

### Interaction Timeout

By default, a thirty second timeout is used for any interaction. In that time, if the app under
test fails to idle, a timeout exception is thrown and the test is marked as failed. You can use
[GREYConfiguration](../EarlGrey/Common/GREYConfiguration.h) to change this timeout value. For
example, to increase the timeout to 60 seconds (one minute):

```objc
[[GREYConfiguration sharedInstance] setValue:@(60.0)
                                forConfigKey:kGREYConfigKeyInteractionTimeoutDuration];
```

### Animation Timeout

Animations that repeat indefinitely — or that run for a long time — affect synchronization.
Animations that run longer than the test timeout value result in a timeout exception. To avoid such
cases, EarlGrey limits the animation duration to five seconds and disables repeating animations
(continuous animations run once). To instruct EarlGrey to allow animations to run longer, change
the maximum allowable animation duration value. Make sure this doesn't affect your test timeouts.
The following snippet increases the maximum animation duration to 30 seconds.

```objc
[[GREYConfiguration sharedInstance] setValue:@(30.0)
                                forConfigKey:kGREYConfigKeyCALayerMaxAnimationDuration];
```

### Invocation From Non-Main Thread

Due to limitation of dispatch queues and the way EarlGrey synchronizes with them, calling into EarlGrey
statements from a `dispatch_queue` leads to a livelock. To mitigate this, we've introduced new block-based
APIs that wrap EarlGrey statements, and that can be safely called from non-main threads:

  * `grey_execute_sync(void (^block)())` — Synchronous. Blocks until execution is
complete.
  * `grey_execute_async(void (^block)())` — Asynchronous.

## Other Top Level APIs

Outside of UI interaction, you can use EarlGrey to control the device and system in various ways.

### Global Configuration

The `GREYConfiguration` class lets you configure the behavior of the framework. It provides a
means to configure synchronization, interaction timeouts, action constraints checks, logging, etc.
As soon as a configuration is changed, it is applied globally. For instance, the following code
enables verbose logging:

```objc
[[GREYConfiguration sharedInstance] setValue:@(YES)
                                forConfigKey:kGREYConfigKeyVerboseLogging];
```

### Controlling Device Orientation

To rotate a device, use `[EarlGrey rotateDeviceToOrientation:errorOrNil:]` to simulate a device in
a specific orientation. For instance, the following causes the system (and your app) to act as if
the device is in **Landscape** mode with the device held upright and the **Home** button on the
right side:

```objc
[EarlGrey rotateDeviceToOrientation:UIDeviceOrientationLandscapeLeft errorOrNil:nil];
```

You can choose from the following orientation modes (for more information, see [UIDeviceOrientation](https://developer.apple.com/library/ios/documentation/uikit/reference/UIDevice_Class/Reference/UIDevice.html#//apple_ref/doc/c_ref/UIDeviceOrientation)):

  * `UIDeviceOrientationUnknown`
  * `UIDeviceOrientationPortrait`
  * `UIDeviceOrientationPortraitUpsideDown`
  * `UIDeviceOrientationLandscapeLeft`
  * `UIDeviceOrientationLandscapeRight`
  * `UIDeviceOrientationFaceUp`
  * `UIDeviceOrientationFaceDown`


text:
import datetime
import json
import os
import subprocess

import bikeshed

def main():
    updateAndCommit()

def updateAndCommit():
    print(datetime.datetime.utcnow())
    print(subprocess.check_output("git pull", shell=True).decode(encoding="utf-8"))

    scriptPath = os.path.dirname(os.path.realpath(__file__))
    dataPath = os.path.join(scriptPath, "data")

    try:
        with open(os.path.join(dataPath, "manifest.txt"), "r", encoding="utf-8") as fh:
            oldDate, _, oldManifest = fh.read().partition("\n")
    except:
        raise

    updateDataFiles(path=dataPath)

    try:
        with open(os.path.join(dataPath, "manifest.txt"), "r", encoding="utf-8") as fh:
            _, _, newManifest = fh.read().partition("\n")
    except:
        raise
    if oldManifest == newManifest:
        # No change
        print(f"Manifest is unchanged since {oldDate}, nothing to be committed")
        return

    diffFiles = diffManifest(oldManifest, newManifest)

    os.chdir(scriptPath)
    print(subprocess.check_output("git add data", shell=True))
    print(
        subprocess.check_output(
            f"git commit -m 'update {len(diffFiles)} files: {', '.join(diffFiles)}'",
            shell=True,
        )
    )
    print(subprocess.check_output("git push", shell=True))

def updateDataFiles(path):
    bikeshed.constants.quiet = 0
    bikeshed.update.update(path=path, manifestMode="skip")

def diffManifest(old, new):
    oldLines = set(old.split("\n"))
    newLines = set(new.split("\n"))
    diffLines = oldLines ^ newLines
    diffFiles = set(line.partition(" ")[2] for line in diffLines)
    return sorted(diffFiles)

if __name__ == "__main__":
    main()


text:
"""
FILE: file_samples_hello_world_async.py

DESCRIPTION:
    These samples demonstrate common scenarios like instantiating a client,
    creating a file share, and uploading a file to a share.

USAGE:
    python file_samples_hello_world_async.py

    Set the environment variables with your own values before running the sample:
    1) AZURE_STORAGE_CONNECTION_STRING - the connection string to your storage account
"""

import os
import asyncio

SOURCE_FILE = './SampleSource.txt'
DEST_FILE = './SampleDestination.txt'

class HelloWorldSamplesAsync(object):

    connection_string = os.getenv('AZURE_STORAGE_CONNECTION_STRING')

    async def create_client_with_connection_string_async(self):
        # Instantiate the ShareServiceClient from a connection string
        from azure.storage.fileshare.aio import ShareServiceClient
        file_service = ShareServiceClient.from_connection_string(self.connection_string)

    async def create_file_share_async(self):
        # Instantiate the ShareClient from a connection string
        from azure.storage.fileshare.aio import ShareClient
        share = ShareClient.from_connection_string(self.connection_string, share_name="helloworld1")

        # Create the share
        async with share:
            await share.create_share()

            try:
                # [START get_share_properties]
                properties = await share.get_share_properties()
                # [END get_share_properties]

            finally:
                # Delete the share
                await share.delete_share()

    async def upload_a_file_to_share_async(self):
        # Instantiate the ShareClient from a connection string
        from azure.storage.fileshare.aio import ShareClient
        share = ShareClient.from_connection_string(self.connection_string, share_name='helloworld2')

        # Create the share
        async with share:
            await share.create_share()

            try:
                # Instantiate the ShareFileClient from a connection string
                # [START create_file_client]
                from azure.storage.fileshare.aio import ShareFileClient
                file = ShareFileClient.from_connection_string(
                    self.connection_string,
                    share_name='helloworld2',
                    file_path="myfile")
                # [END create_file_client]

                # Upload a file
                async with file:
                    with open(SOURCE_FILE, "rb") as source_file:
                        await file.upload_file(source_file)

            finally:
                # Delete the share
                await share.delete_share()

async def main():
    sample = HelloWorldSamplesAsync()
    await sample.create_client_with_connection_string_async()
    await sample.create_file_share_async()
    await sample.upload_a_file_to_share_async()

if __name__ == '__main__':
    asyncio.run(main())


text:
namespace ui {

TSFInputScope::TSFInputScope(TextInputType text_input_type)
  : text_input_type_(text_input_type),
    ref_count_(0) {
}

TSFInputScope::~TSFInputScope() {
}

ULONG STDMETHODCALLTYPE TSFInputScope::AddRef() {
  return InterlockedIncrement(&ref_count_);
}

ULONG STDMETHODCALLTYPE TSFInputScope::Release() {
  const LONG count = InterlockedDecrement(&ref_count_);
  if (!count) {
    delete this;
    return 0;
  }
  return static_cast<ULONG>(count);
}

STDMETHODIMP TSFInputScope::QueryInterface(REFIID iid, void** result) {
  if (!result)
    return E_INVALIDARG;
  if (iid == IID_IUnknown || iid == IID_ITfInputScope) {
    *result = static_cast<ITfInputScope*>(this);
  } else {
    *result = NULL;
    return E_NOINTERFACE;
  }
  AddRef();
  return S_OK;
}

STDMETHODIMP TSFInputScope::GetInputScopes(InputScope** input_scopes,
                                           UINT* count) {
  DCHECK_NE(text_input_type_, TEXT_INPUT_TYPE_NONE);
  if (!count || !input_scopes)
    return E_INVALIDARG;
  *input_scopes = static_cast<InputScope*>(CoTaskMemAlloc(sizeof(InputScope)));
  if (!input_scopes) {
    *count = 0;
    return E_OUTOFMEMORY;
  }
  (*input_scopes)[0] =
      (text_input_type_ == TEXT_INPUT_TYPE_PASSWORD) ? IS_PASSWORD : IS_DEFAULT;
  *count = 1;
  return S_OK;
}

STDMETHODIMP TSFInputScope::GetPhrase(BSTR** phrases, UINT* count) {
  return E_NOTIMPL;
}

STDMETHODIMP TSFInputScope::GetRegularExpression(BSTR* regexp) {
  return E_NOTIMPL;
}

STDMETHODIMP TSFInputScope::GetSRGS(BSTR* srgs) {
  return E_NOTIMPL;
}

STDMETHODIMP TSFInputScope::GetXML(BSTR* xml) {
  return E_NOTIMPL;
}

}  // namespace ui


text:
using System.Collections.Generic;

namespace Microsoft.Data.Edm.Csdl.Internal.Parsing.Ast
{
    /// <summary>
    /// Common base class for CSDL entity, complex, and row Types.
    /// </summary>
    internal abstract class CsdlStructuredType : CsdlElementWithDocumentation
    {
        protected List<CsdlProperty> properties;

        protected CsdlStructuredType(IEnumerable<CsdlProperty> properties, CsdlDocumentation documentation, CsdlLocation location)
            : base(documentation, location)
        {
            this.properties = new List<CsdlProperty>(properties);
        }

        public IEnumerable<CsdlProperty> Properties
        {
            get { return this.properties; }
        }
    }
}


text:
package com.blt.talk.message.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@Configuration
@EnableAsync
@ComponentScan(basePackages = {"com.blt.talk.common.io", "com.blt.talk.message.server"})
@EnableFeignClients
@EnableDiscoveryClient
public class MessageServerApplication {

    private static final Logger logger = LoggerFactory.getLogger(MessageServerApplication.class);

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MessageServerApplication.class);
        ApplicationContext applicationContext = app.run(args);

        try {
            applicationContext.getBean(MessageServerStarter.class).start(args);
        } catch (Exception e) {
            logger.error("Shutdown with errors ", e);
            SpringApplication.exit(applicationContext);
        } finally {
            logger.info("done");
        }
    }

}


text:
package org.xcolab.view.config.spring.filters;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class CdnUrlEncodingFilter extends GenericFilterBean {

    private final AntPathMatcher pathMatcher = new AntPathMatcher();
    private final Map<String, String> pathPatternToCdnUrlMap;

    public CdnUrlEncodingFilter(Map<String, String> pathPatternToCdnUrlMap) {
        this.pathPatternToCdnUrlMap = pathPatternToCdnUrlMap;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        if (!(response instanceof HttpServletResponse)) {
            throw new ServletException("CdnUrlEncodingFilter just supports HTTP requests");
        }
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        filterChain.doFilter(request, new CdnUrlEncodingResponseWrapper(httpResponse));
    }

    private class CdnUrlEncodingResponseWrapper extends HttpServletResponseWrapper {

        public CdnUrlEncodingResponseWrapper(HttpServletResponse wrapped) {
            super(wrapped);
        }

        @Override
        public String encodeURL(String url) {
            final String localUrl = super.encodeURL(url);
            for (Map.Entry<String, String> entry : pathPatternToCdnUrlMap.entrySet()) {
                final String pattern = entry.getKey();
                final String domain = entry.getValue();

                if (StringUtils.isNotBlank(localUrl) && pathMatcher.match(pattern, localUrl)) {
                    return domain + localUrl;
                }
            }
            return localUrl;
        }
    }
}


text:
require 'srl'

class QueryTests < Minitest::Test
  def test_leaderboard
    assert SRL.leaderboard('alttphacks')
  end
end