text:
local Object = require "object"

local Bag = {}

-- creates a new `Bag` filled with `parameters`.
local function new(parameters)
    local self = {}
    local parameters = parameters or {}

    -- gets the Bag's parameters.
    function self:all()
        return parameters
    end

    -- gets the Bag's keys.
    function self:keys()
        local keys = {}
        local i = 0

        for k in pairs(parameters) do
            i = i + 1
            keys[i] = k
        end

        return keys
    end

    -- replaces the Bag's parameters
    function self:replace(parameters)
        parameters = parameters
    end

    -- adds multiple parameters to the Bag
    function self:add(parameters)
        for k, v in pairs(parameters) do
            parameters[k] = v
        end
    end

    -- gets the value of `key`
    function self:get(key, default)
        return parameters[key] or default
    end

    -- sets the value of `key`
    function self:set(key, value)
        parameters[key] = value
    end

    -- determines whether `key` exists in the Bag
    function self:has(key)
        return parameters[key] ~= nil
    end

    -- removes `key` from the Bag
    function self:remove(key)
        parameters[key] = nil
    end

    return self
end

local Bag = Object{"Bag", new}

return Bag


text:
/*
 * Handler.h
 *
 *  Created on: 2015年12月2日
 *      Author: lijing
 */

#ifndef POLA_HANDLER_H_
#define POLA_HANDLER_H_

#include "pola/utils/thread/AbsMessageHandler.h"
#include "pola/utils/thread/Looper.h"
#include "pola/utils/Times.h"

namespace pola {
namespace utils {

class Handler : public AbsMessageHandler {

public:

	Handler(sp<Looper> looper);

	virtual ~Handler() {};

	bool post(Task* task) {
		return postDelayed(task, 0);
	}
	bool postDelayed(Task* task, p_nsecs_t delayMillis);

	bool postAndWait(Task* task);

	bool sendMessage(int what, int arg1 = 0, int arg2 = 0, void* obj = NULL) {
		return sendMessageDelayed(what, arg1, arg2, NULL, 0);
	}
	bool sendMessageDelayed(int what, int arg1 = 0, int arg2 = 0, void* obj = NULL, p_nsecs_t delayMillis = 0);

	void removeTask(Task* task);
	void removeMessages(int what);
	void removeTasksAndMessages();

	void dispatchMessage(Message* msg);

	virtual void handleMessage(Message* msg);
	virtual void handleRecycleMessage(Message* msg);

private:
	sp<Looper> mLooper;

	pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
	pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

};
}
}

#endif /* POLA_HANDLER_H_ */

redpajama_set_name: RedPajamaGithub


text:
"""
Spider task queue backend powered by redis
"""
import queue
import random
import logging
import pickle

from redis import StrictRedis
from fastrq.priorityqueue import PriorityQueue  # pytype: disable=import-error

from grab.spider.queue_backend.base import QueueInterface
from grab.spider.error import SpiderMisuseError

class CustomPriorityQueue(PriorityQueue):
    def __init__(self, key, **kwargs):
        # sets `key` to `self._key`
        super().__init__(key)
        self._conn_kwargs = kwargs

    # https://github.com/limen/fastrq/blob/master/fastrq/base.py
    def connect(self):
        if self._redis is None:
            self._redis = StrictRedis(decode_responses=False, **self._conn_kwargs)
        return self._redis

    def clear(self):
        if self._redis:
            self._redis.delete(self._key)

class QueueBackend(QueueInterface):
    def __init__(self, spider_name, queue_name=None, **kwargs):
        super(QueueBackend, self).__init__(spider_name, **kwargs)
        self.spider_name = spider_name
        if queue_name is None:
            queue_name = "task_queue_%s" % spider_name
        self.queue_name = queue_name
        self.queue_object = CustomPriorityQueue(queue_name, **kwargs)
        logging.debug("Redis queue key: %s", self.queue_name)

    def put(self, task, priority, schedule_time=None):
        if schedule_time is not None:
            raise SpiderMisuseError("Redis task queue does not support " "delayed task")
        # Add attribute with random value
        # This is required because qr library
        # does not allow to store multiple values with same hash
        # in the PriorityQueue

        task.redis_qr_rnd = random.random()
        self.queue_object.push({pickle.dumps(task): priority})

    def get(self):
        task = self.queue_object.pop()
        if task is None:
            raise queue.Empty()
        else:
            return pickle.loads(task[0])  # pylint: disable=unsubscriptable-object

    def size(self):
        return len(self.queue_object)

    def clear(self):
        self.queue_object.clear()

    def close(self):
        # get conneciton opened by qr and close it
        pass


text:
<?php

namespace INHack20\ConsultorioBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use INHack20\ConsultorioBundle\Entity\TipoConsulta;
use INHack20\ConsultorioBundle\Form\TipoConsultaType;

/**
 * TipoConsulta controller.
 *
 * @Route("/tipoconsulta")
 */
class TipoConsultaController extends Controller
{
    /**
     * Lists all TipoConsulta entities.
     *
     * @Route("/", name="tipoconsulta")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('INHack20ConsultorioBundle:TipoConsulta')->findAll();

        return array(
            'entities' => $entities,
        );
    }

    /**
     * Finds and displays a TipoConsulta entity.
     *
     * @Route("/{id}/show", name="tipoconsulta_show")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('INHack20ConsultorioBundle:TipoConsulta')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find TipoConsulta entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to create a new TipoConsulta entity.
     *
     * @Route("/new", name="tipoconsulta_new")
     * @Template()
     */
    public function newAction()
    {
        $entity = new TipoConsulta();
        $form   = $this->createForm(new TipoConsultaType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a new TipoConsulta entity.
     *
     * @Route("/create", name="tipoconsulta_create")
     * @Method("POST")
     * @Template("INHack20ConsultorioBundle:TipoConsulta:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity  = new TipoConsulta();
        $form = $this->createForm(new TipoConsultaType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('tipoconsulta_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Displays a form to edit an existing TipoConsulta entity.
     *
     * @Route("/{id}/edit", name="tipoconsulta_edit")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('INHack20ConsultorioBundle:TipoConsulta')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find TipoConsulta entity.');
        }

        $editForm = $this->createForm(new TipoConsultaType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing TipoConsulta entity.
     *
     * @Route("/{id}/update", name="tipoconsulta_update")
     * @Method("POST")
     * @Template("INHack20ConsultorioBundle:TipoConsulta:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('INHack20ConsultorioBundle:TipoConsulta')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find TipoConsulta entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new TipoConsultaType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('tipoconsulta_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a TipoConsulta entity.
     *
     * @Route("/{id}/delete", name="tipoconsulta_delete")
     * @Method("POST")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('INHack20ConsultorioBundle:TipoConsulta')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find TipoConsulta entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

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

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}


text:
package com.percolate.foam;

import android.content.Context;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * {@inheritDoc}
 */
class Graphite extends ServiceImpl implements EventTrackingService {

    String host;
    int port;
    String apiKey;

    Graphite(Context context) {
        super(context);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void enable(String url) {
        if(utils.isNotBlank(url) && url.contains(":") && url.split(":").length == 2) {
            String first = url.split(":")[0];
            String second = url.split(":")[1];

            if (first.contains("@")) {
                this.apiKey = first.split("@")[0];
                this.host = first.split("@")[1];
            } else {
                this.host = url.split(":")[0];
            }

            try {
                this.port = Integer.parseInt(second);
            } catch (NumberFormatException ex) {
                utils.logIssue("Invalid port in Graphite URL [" + second + "]", ex);
            }
        } else {
            utils.logIssue("Invalid Graphite URL.  Expecting \"[key@]host:port\" format.", null);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isEnabled() {
        return host != null && port != 0;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ServiceType getServiceType() {
        return ServiceType.GRAPHITE;
    }

    /**
     * Send data to graphite in the format "metric_path value timestamp\n".
     * Example: "com.myapp.activities.MainActivity 1 1429801333\n"
     * ApiKey will be appended to the metric_path as expected by hosted providers.
     *
     * {@inheritDoc}
     */
    @Override
    public void logEvent(Context context, String event) {
        StringBuilder eventData = new StringBuilder();
        if(utils.isNotBlank(apiKey)){
            eventData.append(apiKey);
            eventData.append(".");
        }
        eventData.append(utils.getApplicationPackageName(context));
        eventData.append(".");
        eventData.append(event);
        eventData.append(" 1 ");
        eventData.append(getTimeStamp());
        eventData.append("\n");

        sendData(eventData.toString());
    }

    /**
     * Return unix epoch for the current time
     * @return Epoch in for the current time.
     */
    long getTimeStamp() {
        return System.currentTimeMillis() / 1000L;
    }

    /**
     * Start new background thread to send data with.
     *
     * @param graphiteEvent Event data to send to graphite.
     */
    void sendData(final String graphiteEvent) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                sendUdpData(graphiteEvent);
            }
        }).start();
    }

    /**
     * Send data to Graphite server.
     *
     * @param graphiteEvent Event data to send to graphite.
     */
    void sendUdpData(String graphiteEvent) {
        Socket socket = null;
        try {
            socket = sendDataOverSocket(graphiteEvent);
        } catch (IOException ex) {
            utils.logIssue("Error sending graphite event [" + graphiteEvent + "] to [" + host + ":" + port + "].", ex);
        } finally {
            closeSocket(socket);
        }
    }

    /**
     * Create new {@link DataOutputStream} to send data over.
     *
     * @param graphiteEvent Event data to send to graphite.
     * @return created {@link Socket} object.  Should be closed after calling this method.
     * @throws IOException propagates if there was a network issue.
     */
    Socket sendDataOverSocket(String graphiteEvent) throws IOException {
        Socket socket = new Socket(host, port);
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        dos.writeBytes(graphiteEvent);
        dos.flush();
        return socket;
    }

    /**
     * Close the given {@link} Socket object, checking for null
     * @param socket socket to close.
     */
    void closeSocket(Socket socket) {
        if(socket != null) {
            try {
                socket.close();
            } catch (Exception ex) {
                utils.logIssue("Could not close graphite socket [" + host + ":" + port + "].", ex);
            }
        }
    }

}


text:
var managerData = {
  totalAgents: 305,
  totalConversations: 40175,
  totalSeats: 25,
  currentDraftConfidence: 73,
  currentAutosendConfidence: 84
}

var billingData = {
  paid: true,
}

// THESE VARIABLES ESTABLISH THE STATE OF THE DASHBOARD APPLICATION
var currentLocation;

var managerState = {
  selectAll: false,
  availableSeats: 0,
  assignments: []
}

var roleState = {
  currentCard: 'admin',
  cardName: 'admin',
  cardPermissions: ['create-user', 'edit-user', 'delete-user', 'assign-user-roles', 'set-global-permissions', 'change-role-permissions', 'assign-models', 'create-models', 'merge-models', 'add-integrations', 'adjust-confidence-thresholds']
}

var userState = {
  selectedUsers: [],
}

$(document).ready(function() {
  currentLocation = $('#dash-view').data('location');

  // MANAGER DASHBOARD FUNCTIONALITY
  if (currentLocation === 'dashboard-manager') {
    loadManagerData();
    $('#agent-search-toggle').click(handleAgentSearchToggle);
    $('#agent-search').on('keyup keypress', handleAgentSearch);
    $('.assignment-row').on('click', 'input', handleAssignment);
    $('#select-all input').click(handleSelectAllAssignments);
    $('#draft-confidence').on('change', captureSliderChange);
    $('#autosend-confidence').on('change', captureSliderChange);
  }

  // SETTINGS ROLES FUNCTIONALITY
  if (currentLocation === 'settings-roles') {
    $('#controller-cards').on('click', '.controller-card', handleCardSelection);
    $('.delete-card').click(handleDeleteCard);
    $('.save-btn').click(saveRoleChanges);
    $('.modal').modal();

    $('#add-role-form').validate({
      errorClass: 'error failedValidation',
      validClass: 'success',
      highlight: function(element, errorClass, validClass) {
        $(element).closest('.validate').addClass(errorClass).removeClass(validClass);
      },
      unhighlight: function(element, errorClass, validClass) {
        $(element).closest('.validate').addClass(validClass).removeClass(errorClass);
      },
      submitHandler: function() {
        $('#add-role-modal').modal('close');
        handleAddNewRole();
      }
    });

  }

  // SETTINGS USERS FUNCTIONALITY
  if (currentLocation === 'settings-users') {
    $('#controller-cards').on('click', '.user-card input', handleSelectedUser);
    $('.delete-user-card').click(handleRemoveUser);
    $('.modal').modal();

    $('#add-users-form').validate({
      errorClass: 'error failedValidation',
      validClass: 'success',
      highlight: function(element, errorClass, validClass) {
        $(element).closest('.validate').addClass(errorClass).removeClass(validClass);
      },
      unhighlight: function(element, errorClass, validClass) {
        $(element).closest('.validate').addClass(validClass).removeClass(errorClass);
      },
      submitHandler: function() {
        $('#add-users-modal').modal('close');
        handleAddUser();
      }
    });

    $('#edit-users-form').validate({
      errorClass: 'error failedValidation',
      validClass: 'success',
      highlight: function(element, errorClass, validClass) {
        $(element).closest('.validate').addClass(errorClass).removeClass(validClass);
      },
      unhighlight: function(element, errorClass, validClass) {
        $(element).closest('.validate').addClass(validClass).removeClass(errorClass);
      },
      submitHandler: function() {
        $('#edit-users-modal').modal('close');
        handleEditUser();
      }
    });
  }

  // SETTINGS SECURITY FUNCTIONALITY
  if (currentLocation === 'settings-security') {
    $('#confidential-topics-form').submit(handleTopicsUpdate);

    $('#email-form').validate({
      errorClass: 'error failedValidation',
      validClass: 'success',
      highlight: function(element, errorClass, validClass) {
        $(element).closest('.validate').addClass(errorClass).removeClass(validClass);
      },
      unhighlight: function(element, errorClass, validClass) {
        $(element).closest('.validate').addClass(validClass).removeClass(errorClass);
      },
      submitHandler: function() {
        handleEmailUpdate();
      }
    });

    $('#password-form').validate({
      errorClass: 'error failedValidation',
      validClass: 'success',
      highlight: function(element, errorClass, validClass) {
        $(element).closest('.validate').addClass(errorClass).removeClass(validClass);
      },
      unhighlight: function(element, errorClass, validClass) {
        $(element).closest('.validate').addClass(validClass).removeClass(errorClass);
      },
      submitHandler: function() {
        handlePasswordUpdate();
      }
    });

    $('.tooltipped').tooltip({delay: 50});
  }

  // SETTINGS BILLING FUNCTIONALITY
  if (currentLocation === 'settings-billing') {
    loadBillingData();
  }

});

function loadManagerData() {
  managerState.availableSeats = managerData.totalSeats;
  $('#available-seats').text(managerState.availableSeats);
  $('#total-seats').text(managerData.totalSeats);

  $('#agents-stat').text(Number(managerData.totalAgents).toLocaleString());
  $('#conversations-stat').text(Number(managerData.totalConversations).toLocaleString());
  $('#draft-confidence').val(Number(managerData.currentDraftConfidence));
  $('#autosend-confidence').val(Number(managerData.currentAutosendConfidence));
}

function loadBillingData() {
  if (billingData.paid) {
    $('#billing-paid').addClass('active-block');
  } else {
    $('#billing-overdue').addClass('active-block');
  }
}

// MANAGER DASHBOARD FUNCTIONALITY

function handleAgentSearchToggle() {
  $(this).siblings('.input-field').fadeToggle().toggleClass('hide');
  $('#select-all p').fadeToggle().toggleClass('hide');
  $('.assignment-row').removeClass('hide');
}

function handleAgentSearch() {
  var value = $(this).val().toLowerCase();
  $('.assignment-row').removeClass('hide');

  $('.assignment-row p').each(function(index) {
    var agent = $(this).text().toLowerCase();
    if (agent.search(value) === -1) {
      $(this).parent().addClass('hide');
    }
  })
}

function handleAssignment() {
  var name = $(this).val();

  if (currentlyAssigned(name)) {
    removeAssigned(name);
  } else if ((!currentlyAssigned(name)) && (managerState.availableSeats > 0)) {
    addAssigned(name);
  } else {
    $(this).prop({checked: false});
    $('#select-all p').addClass('failedValidation');
    setTimeout(function() {
      $('#select-all p').removeClass('failedValidation');
    }, 1000)
  };

  managerState.availableSeats = managerData.totalSeats - managerState.assignments.length;
  $('#available-seats').text(managerState.availableSeats);
}

function currentlyAssigned(name) {
  if (managerState.assignments.length <= 0) {
    return false;
  }
  for(var k in managerState.assignments) {
    if (managerState.assignments[k].name === name) {
      return true;
    }
  }
  return false
}

function removeAssigned(name) {
  for(var k in managerState.assignments) {
    if (managerState.assignments[k].name === name) {
      managerState.assignments.splice(k, 1);
    }
  }
}

function addAssigned(name) {
  managerState.assignments.push({
    name: name
  })
}

function handleSelectAllAssignments() {
  managerState.selectAll = !managerState.selectAll;
  var $inputs = $('#assignment-form #assignment-switch-container :input');

  if (managerState.selectAll) {
    var k = 0;
    var tracker = 0;
    while ((tracker < managerState.availableSeats) && (k < $('.assignment-row').length)) {
      if ($($inputs[k]).prop('checked') === false) {
        addAssigned($inputs[k].value)
        switchToggle($inputs[k], managerState.selectAll);
        tracker++;
      }
      k++;
    }
  } else {
    managerState.assignments = [];
    switchToggle($inputs, managerState.selectAll);
  }

  managerState.availableSeats = managerData.totalSeats - managerState.assignments.length;
  $('#available-seats').text(managerState.availableSeats);
}

function switchToggle(input, status) {
  $(input).prop({checked: status});
}

function captureSliderChange() {
  var $this = $(this);
  var value = $this.val();
  var type = $this.attr('id');

  if (type === "draft-confidence") {

  } else if (type === "autosend-confidence") {

  }
}

// SETTINGS ROLES FUNCTIONALITY

function handleCardSelection() {
  var newCard = $(this).data('role');

  if (newCard === roleState.currentCard) {
    return
  } else {
    var newId = '#' + newCard.toLowerCase() + '-card';
    var currentId = '#' + roleState.currentCard + '-card';
    var newPermissions = $(this).data('permissions');

    $(newId).toggleClass('active-card');
    $(currentId).toggleClass('active-card');

    $('#editor-input').val(newCard);

    if (newCard === 'Admin') {
      $('#editor-input').prop('disabled', true);
      $('#editor-options input').prop('checked', true);
      $('#editor-options input').prop('disabled', true);
    } else {
      $('#editor-input').prop('disabled', false);
      $('#editor-options input').prop('checked', false);
      $('#editor-options input').prop('disabled', false);
    }

    roleState.currentCard = newCard.toLowerCase();
    roleState.cardName = newCard.toLowerCase();
    roleState.cardPermissions = [];

    if (newPermissions.length > 0) {
      newPermissions.split(",").forEach(function(permission) {
        if (permission !== "") {
          $('#' + permission).prop('checked', true);
          roleState.cardPermissions.push(permission);
        }
      })
    }
  }
}

function handleDeleteCard() {
  if (roleState.currentCard === 'admin') {
    return
  } else {
    var currentId = '#' + roleState.currentCard.toLowerCase() + '-card';
    var newId = '#admin-card';

    $(currentId).remove();
    $(newId).toggleClass('active-card');
    $('#editor-input').val('Admin');
    $('#editor-input').prop('disabled', true);
    $('#editor-options input').prop('checked', true);
    $('#editor-options input').prop('disabled', true);
    roleState.currentCard = 'admin';
    roleState.cardName = 'admin';
  }
}

function handleAddNewRole() {
  var newRole = $('#add-role-form').serializeArray();
  createNewRole(newRole)
  $('#add-role-form').trigger('reset');
}

function createNewRole(data) {
  var roleName = findDataPoint(data, 'role-name');
  var roleDescription = findDataPoint(data, 'role-description');

  var $newRoleCard = $("

" + roleName + "

A " + roleName + " can " + roleDescription + "

")
  $('#controller-cards').append($newRoleCard);
}

function saveRoleChanges() {
  var value = $('#editor-input').val();
  var $this = '#' + roleState.currentCard + '-card';

  $($this).data('role', value);
  $($this + ' .controller-title').text(value);
  $($this + ' .description-title').text(value);
  $($this).attr('id', value.toLowerCase() + '-card');

  roleState.cardName = value;
  roleState.currentCard = value;
  roleState.cardPermissions = [];

  var permissions = "";
  $('#editor-options :input').each(function() {
    if (this.checked === true) {
      roleState.cardPermissions.push(this.name);
      permissions = permissions + this.name + ",";
    }
  })

  $($this).data('permissions', permissions);

  // submitRequest(roleState, url);

  handleSaveAction();
}

// SETTINGS USERS FUNCTIONALITY
function handleSelectedUser() {
  var value = $(this).val();

  if (currentlySelected(value)) {
    removeSelected(value);
  } else {
    addSelected(value);
  }
}

function currentlySelected(name) {
  if (userState.selectedUsers.length <= 0) {
    return false;
  }
  for(var k in userState.selectedUsers) {
    if (userState.selectedUsers[k].name === name) {
      return true;
    }
  }
  return false
}

function removeSelected(name) {
  for(var k in userState.selectedUsers) {
    if (userState.selectedUsers[k].name === name) {
      userState.selectedUsers.splice(k, 1);
    }
  }
}

function addSelected(name) {
  userState.selectedUsers.push({
    name: name
  })
}

function handleAddUser(e) {
  var newUser = $('#add-users-form').serializeArray();
  createNewUser(newUser)
  $('#add-users-form').trigger('reset');
}

function createNewUser(data) {
  var userName = findDataPoint(data, 'user-name'),
      userRole = findDataPoint(data, 'user-role'),
      $newUserCard = $('
<input type="checkbox" id="' + userName + '" value="' + userName + '"  class="validate"/>' + userName + ' (' + userRole + ')
');

  $('#users-container #controller-cards').append($newUserCard);
  // submitRequest(userState.selectedUsers, url);
}

function handleEditUser(e) {
  var value = $('#edit-users-modal form input').val();
  userState.selectedUsers.forEach(function(user) {
    document.getElementById(user.name + ' role').innerHTML = '(' + value + ')';
  })
  // submitRequest(userState.selectedUsers, url);
  $('#edit-users-form').trigger('reset');
}

function handleRemoveUser(e) {
  userState.selectedUsers.forEach(function(user) {
    document.getElementById(user.name + ' card').remove();
  })
  // submitRequest(userState.selectedUsers, url);
}

// SETTINGS SECURITY FUNCTIONALITY

function handleTopicsUpdate(e) {
  e.preventDefault();
  var $inputs = $('#confidential-topics-form :input');
  var values = captureFormData($inputs);
  // submitRequest(values, url);
}

function handleEmailUpdate(e) {
  e.preventDefault();
  var $inputs = $('#email-form :input');
  var values = captureFormData($inputs);
  // submitRequest(values, url);
}

function handlePasswordUpdate(e) {
  e.preventDefault();
  var $inputs = $('#password-form :input');
  var values = captureFormData($inputs);
  // submitRequest(values, url);
}

function handleSaveAction() {
  $('#saved-notification').addClass('active-flex')

  setTimeout(function(){
    $('#saved-notification').removeClass('active-flex')
  },2000)
}

function findDataPoint(data, point) {
  var locatedPoint;
  data.forEach(function(datapoint) {
    if (datapoint.name === point) {
      locatedPoint = datapoint.value;
    }
  });

  return locatedPoint;
}

function captureFormData(inputs) {
  var values = {};
  inputs.each(function() {
      values[this.name] = $(this).val();
  });
  return values;
}

function submitRequest(data, url) {
  var payload = new FormData();
  payload.append( "json", JSON.stringify( data ) );

  fetch(url,
  {
      method: "POST",
      body: payload
  })
  .then(function(res){
    handleSaveAction();
    return res.json();
  })
  .catch(function (error){ console.log('Request failed', error)});
}


text:
// Copyright (c) 2004, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "utilities.h"

#include <cstdio>
#include <cstdlib>
#include "config.h"
#include "base/commandlineflags.h"
#include <glog/logging.h>
#include "stacktrace.h"

#ifdef HAVE_EXECINFO_H
# include <execinfo.h>
#endif

using namespace GOOGLE_NAMESPACE;

#ifdef HAVE_STACKTRACE

// Obtain a backtrace, verify that the expected callers are present in the
// backtrace, and maybe print the backtrace to stdout.

// The sequence of functions whose return addresses we expect to see in the
// backtrace.
const int BACKTRACE_STEPS = 6;

struct AddressRange {
  const void *start, *end;
};

// Expected function [start,end] range.
AddressRange expected_range[BACKTRACE_STEPS];

#if __GNUC__
// Using GCC extension: address of a label can be taken with '&&label'.
// Start should be a label somewhere before recursive call, end somewhere
// after it.
#define INIT_ADDRESS_RANGE(fn, start_label, end_label, prange)           \
  do {                                                                   \
    (prange)->start = &&start_label;                                     \
    (prange)->end = &&end_label;                                         \
    CHECK_LT((prange)->start, (prange)->end);                            \
  } while (0)
// This macro expands into "unmovable" code (opaque to GCC), and that
// prevents GCC from moving a_label up or down in the code.
// Without it, there is no code following the 'end' label, and GCC
// (4.3.1, 4.4.0) thinks it safe to assign &&end an address that is before
// the recursive call.
#define DECLARE_ADDRESS_LABEL(a_label)                                   \
  a_label: do { __asm__ __volatile__(""); } while (0)
// Gcc 4.4.0 may split function into multiple chunks, and the chunk
// performing recursive call may end up later in the code then the return
// instruction (this actually happens with FDO).
// Adjust function range from __builtin_return_address.
#define ADJUST_ADDRESS_RANGE_FROM_RA(prange)                             \
  do {                                                                   \
    void *ra = __builtin_return_address(0);                              \
    CHECK_LT((prange)->start, ra);                                       \
    if (ra > (prange)->end) {                                            \
      printf("Adjusting range from %p..%p to %p..%p\n",                  \
             (prange)->start, (prange)->end,                             \
             (prange)->start, ra);                                       \
      (prange)->end = ra;                                                \
    }                                                                    \
  } while (0)
#else
// Assume the Check* functions below are not longer than 256 bytes.
#define INIT_ADDRESS_RANGE(fn, start_label, end_label, prange)           \
  do {                                                                   \
    (prange)->start = reinterpret_cast<const void *>(&fn);               \
    (prange)->end = reinterpret_cast<const char *>(&fn) + 256;           \
  } while (0)
#define DECLARE_ADDRESS_LABEL(a_label) do { } while (0)
#define ADJUST_ADDRESS_RANGE_FROM_RA(prange) do { } while (0)
#endif  // __GNUC__

//-----------------------------------------------------------------------//

static void CheckRetAddrIsInFunction(void *ret_addr, const AddressRange &range)
{
  CHECK_GE(ret_addr, range.start);
  CHECK_LE(ret_addr, range.end);
}

//-----------------------------------------------------------------------//

#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu-label-as-value"
#endif

void ATTRIBUTE_NOINLINE CheckStackTrace(int);
static void ATTRIBUTE_NOINLINE CheckStackTraceLeaf(void) {
  const int STACK_LEN = 10;
  void *stack[STACK_LEN];
  int size;

  ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[1]);
  INIT_ADDRESS_RANGE(CheckStackTraceLeaf, start, end, &expected_range[0]);
  DECLARE_ADDRESS_LABEL(start);
  size = GetStackTrace(stack, STACK_LEN, 0);
  printf("Obtained %d stack frames.\n", size);
  CHECK_GE(size, 1);
  CHECK_LE(size, STACK_LEN);

  if (1) {
#ifdef HAVE_EXECINFO_H
    char **strings = backtrace_symbols(stack, size);
    printf("Obtained %d stack frames.\n", size);
    for (int i = 0; i < size; i++) {
      printf("%s %p\n", strings[i], stack[i]);
    }

    union {
      void (*p1)(int);
      void* p2;
    } p = {&CheckStackTrace};

    printf("CheckStackTrace() addr: %p\n", p.p2);
    free(strings);
#endif
  }
  for (int i = 0; i < BACKTRACE_STEPS; i++) {
    printf("Backtrace %d: expected: %p..%p  actual: %p ... ",
           i, expected_range[i].start, expected_range[i].end, stack[i]);
    fflush(stdout);
    CheckRetAddrIsInFunction(stack[i], expected_range[i]);
    printf("OK\n");
  }
  DECLARE_ADDRESS_LABEL(end);
}

//-----------------------------------------------------------------------//

/* Dummy functions to make the backtrace more interesting. */
static void ATTRIBUTE_NOINLINE CheckStackTrace4(int i) {
  ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[2]);
  INIT_ADDRESS_RANGE(CheckStackTrace4, start, end, &expected_range[1]);
  DECLARE_ADDRESS_LABEL(start);
  for (int j = i; j >= 0; j--) {
    CheckStackTraceLeaf();
  }
  DECLARE_ADDRESS_LABEL(end);
}
static void ATTRIBUTE_NOINLINE CheckStackTrace3(int i) {
  ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[3]);
  INIT_ADDRESS_RANGE(CheckStackTrace3, start, end, &expected_range[2]);
  DECLARE_ADDRESS_LABEL(start);
  for (int j = i; j >= 0; j--) {
    CheckStackTrace4(j);
  }
  DECLARE_ADDRESS_LABEL(end);
}
static void ATTRIBUTE_NOINLINE CheckStackTrace2(int i) {
  ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[4]);
  INIT_ADDRESS_RANGE(CheckStackTrace2, start, end, &expected_range[3]);
  DECLARE_ADDRESS_LABEL(start);
  for (int j = i; j >= 0; j--) {
    CheckStackTrace3(j);
  }
  DECLARE_ADDRESS_LABEL(end);
}
static void ATTRIBUTE_NOINLINE CheckStackTrace1(int i) {
  ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[5]);
  INIT_ADDRESS_RANGE(CheckStackTrace1, start, end, &expected_range[4]);
  DECLARE_ADDRESS_LABEL(start);
  for (int j = i; j >= 0; j--) {
    CheckStackTrace2(j);
  }
  DECLARE_ADDRESS_LABEL(end);
}

#ifndef __GNUC__
// On non-GNU environment, we use the address of `CheckStackTrace` to
// guess the address range of this function. This guess is wrong for
// non-static function on Windows. This is probably because
// `&CheckStackTrace` returns the address of a trampoline like PLT,
// not the actual address of `CheckStackTrace`.
// See https://github.com/google/glog/issues/421 for the detail.
static
#endif
void ATTRIBUTE_NOINLINE CheckStackTrace(int i) {
  INIT_ADDRESS_RANGE(CheckStackTrace, start, end, &expected_range[5]);
  DECLARE_ADDRESS_LABEL(start);
  for (int j = i; j >= 0; j--) {
    CheckStackTrace1(j);
  }
  DECLARE_ADDRESS_LABEL(end);
}

#if defined(__clang__)
#pragma clang diagnostic pop
#endif

//-----------------------------------------------------------------------//

int main(int, char ** argv) {
  FLAGS_logtostderr = true;
  InitGoogleLogging(argv[0]);

  CheckStackTrace(0);

  printf("PASS\n");
  return 0;
}

#else
int main() {
  printf("PASS (no stacktrace support)\n");
  return 0;
}
#endif  // HAVE_STACKTRACE


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

namespace RCore.ClangMacroParser.Expressions
{
    public static class OperationTypeExtensions
    {
        // http://en.cppreference.com/w/c/language/operator_precedence
        private static readonly Dictionary<OperationType, int> OperationPrecedence = new Dictionary<OperationType, int>
        {
            {OperationType.Add, 4},
            {OperationType.Divide, 3},
            {OperationType.Modulo, 3},
            {OperationType.Multiply, 3},
            {OperationType.Power, 9},
            {OperationType.Subtract, 4},
            {OperationType.And, 11},
            {OperationType.Or, 10},
            {OperationType.ExclusiveOr, 9},
            {OperationType.LeftShift, 5},
            {OperationType.RightShift, 5},
            {OperationType.AndAlso, 11},
            {OperationType.OrElse, 12},
            {OperationType.Equal, 7},
            {OperationType.NotEqual, 7},
            {OperationType.GreaterThanOrEqual, 6},
            {OperationType.GreaterThan, 6},
            {OperationType.LessThan, 6},
            {OperationType.LessThanOrEqual, 6}
        };

        public static int GetPrecedence(this OperationType operationType) => OperationPrecedence[operationType];

        public static OperationType ToOperationType(this string value)
        {
            switch (value)
            {
                case "+": return OperationType.Add;
                case "/": return OperationType.Divide;
                case "%": return OperationType.Modulo;
                case "*": return OperationType.Multiply;
                case "^": return OperationType.Power;
                case "-": return OperationType.Subtract;
                case "&": return OperationType.And;
                case "|": return OperationType.Or;
                case "~": return OperationType.ExclusiveOr;
                case "<<": return OperationType.LeftShift;
                case ">>": return OperationType.RightShift;
                case "&&": return OperationType.AndAlso;
                case "||": return OperationType.OrElse;
                case "==": return OperationType.Equal;
                case "!=": return OperationType.NotEqual;
                case ">=": return OperationType.GreaterThanOrEqual;
                case ">": return OperationType.GreaterThan;
                case "<": return OperationType.LessThan;
                case "<=": return OperationType.LessThanOrEqual;
                default:
                    throw new ArgumentOutOfRangeException(nameof(value));
            }
        }

        public static string ToOperationTypeString(this OperationType operationType)
        {
            switch (operationType)
            {
                case OperationType.Add: return "+";
                case OperationType.Divide: return "/";
                case OperationType.Modulo: return "%";
                case OperationType.Multiply: return "*";
                case OperationType.Power: return "^";
                case OperationType.Subtract: return "-";
                case OperationType.And: return "&";
                case OperationType.Or: return "|";
                case OperationType.ExclusiveOr: return "~";
                case OperationType.LeftShift: return "<<";
                case OperationType.RightShift: return ">>";
                case OperationType.AndAlso: return "&&";
                case OperationType.OrElse: return "||";
                case OperationType.Equal: return "==";
                case OperationType.NotEqual: return "!=";
                case OperationType.GreaterThanOrEqual: return ">=";
                case OperationType.GreaterThan: return ">";
                case OperationType.LessThan: return "<";
                case OperationType.LessThanOrEqual: return "<=";

                default:
                    throw new ArgumentOutOfRangeException(nameof(operationType));
            }
        }

        public static bool IsArithmetic(this OperationType operationType)
            => operationType == OperationType.Add ||
               operationType == OperationType.Divide ||
               operationType == OperationType.Modulo ||
               operationType == OperationType.Multiply ||
               operationType == OperationType.Power ||
               operationType == OperationType.Subtract;

        public static bool IsBitwise(this OperationType operationType)
            => operationType == OperationType.And ||
               operationType == OperationType.Or ||
               operationType == OperationType.ExclusiveOr;

        public static bool IsShift(this OperationType operationType)
            => operationType == OperationType.LeftShift ||
               operationType == OperationType.RightShift;

        public static bool IsConditional(this OperationType operationType)
            => operationType == OperationType.AndAlso ||
               operationType == OperationType.OrElse;

        public static bool IsComparison(this OperationType operationType)
            => operationType == OperationType.Equal ||
               operationType == OperationType.NotEqual ||
               operationType == OperationType.GreaterThan ||
               operationType == OperationType.GreaterThanOrEqual ||
               operationType == OperationType.LessThan ||
               operationType == OperationType.LessThanOrEqual;
    }
}


text:
#include "gm.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkPath.h"

namespace skiagm {

static void makebm(SkBitmap* bm, int w, int h) {
    bm->allocN32Pixels(w, h);
    bm->eraseColor(SK_ColorTRANSPARENT);

    SkCanvas    canvas(*bm);
    SkScalar    s = SkIntToScalar(SkMin32(w, h));
    SkPoint     pts[] = { { 0, 0 }, { s, s } };
    SkColor     colors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE };
    SkScalar    pos[] = { 0, SK_Scalar1/2, SK_Scalar1 };
    SkPaint     paint;

    paint.setDither(true);
    paint.setShader(SkGradientShader::MakeLinear(pts, colors, pos, SK_ARRAY_COUNT(colors),
                                                 SkShader::kClamp_TileMode));
    canvas.drawPaint(paint);
}

///////////////////////////////////////////////////////////////////////////////

struct GradData {
    int             fCount;
    const SkColor*  fColors;
    const SkScalar* fPos;
};

static const SkColor gColors[] = {
    SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK
};

static const GradData gGradData[] = {
    { 2, gColors, nullptr },
    { 5, gColors, nullptr },
};

static sk_sp<SkShader> MakeLinear(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm) {
    return SkGradientShader::MakeLinear(pts, data.fColors, data.fPos, data.fCount, tm);
}

static sk_sp<SkShader> MakeRadial(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm) {
    SkPoint center;
    center.set(SkScalarAve(pts[0].fX, pts[1].fX),
               SkScalarAve(pts[0].fY, pts[1].fY));
    return SkGradientShader::MakeRadial(center, center.fX, data.fColors, data.fPos, data.fCount,
                                        tm);
}

static sk_sp<SkShader> MakeSweep(const SkPoint pts[2], const GradData& data, SkShader::TileMode) {
    SkPoint center;
    center.set(SkScalarAve(pts[0].fX, pts[1].fX),
               SkScalarAve(pts[0].fY, pts[1].fY));
    return SkGradientShader::MakeSweep(center.fX, center.fY, data.fColors, data.fPos, data.fCount);
}

static sk_sp<SkShader> Make2Conical(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm) {
    SkPoint center0, center1;
    center0.set(SkScalarAve(pts[0].fX, pts[1].fX),
                SkScalarAve(pts[0].fY, pts[1].fY));
    center1.set(SkScalarInterp(pts[0].fX, pts[1].fX, SkIntToScalar(3)/5),
                SkScalarInterp(pts[0].fY, pts[1].fY, SkIntToScalar(1)/4));
    return SkGradientShader::MakeTwoPointConical(
                            center1, (pts[1].fX - pts[0].fX) / 7,
                            center0, (pts[1].fX - pts[0].fX) / 2,
                            data.fColors, data.fPos, data.fCount, tm);
}

typedef sk_sp<SkShader> (*GradMaker)(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm);

static const GradMaker gGradMakers[] = {
    MakeLinear, MakeRadial, MakeSweep, Make2Conical
};

///////////////////////////////////////////////////////////////////////////////

class ShaderTextGM : public GM {
public:
    ShaderTextGM() {
        this->setBGColor(sk_tool_utils::color_to_565(0xFFDDDDDD));
    }

protected:

    SkString onShortName() override {
        return SkString("shadertext");
    }

    SkISize onISize() override { return SkISize::Make(1450, 500); }

    void onDraw(SkCanvas* canvas) override {
        const char text[] = "Shaded Text";
        const int textLen = SK_ARRAY_COUNT(text) - 1;
        const int pointSize = 36;

        const int w = pointSize * textLen;
        const int h = pointSize;

        SkPoint pts[2] = {
            { 0, 0 },
            { SkIntToScalar(w), SkIntToScalar(h) }
        };
        SkScalar textBase = SkIntToScalar(h/2);

        SkShader::TileMode tileModes[] = {
            SkShader::kClamp_TileMode,
            SkShader::kRepeat_TileMode,
            SkShader::kMirror_TileMode
        };

        static const int gradCount = SK_ARRAY_COUNT(gGradData) *
                                     SK_ARRAY_COUNT(gGradMakers);
        static const int bmpCount = SK_ARRAY_COUNT(tileModes) *
                                    SK_ARRAY_COUNT(tileModes);
        sk_sp<SkShader> shaders[gradCount + bmpCount];

        int shdIdx = 0;
        for (size_t d = 0; d < SK_ARRAY_COUNT(gGradData); ++d) {
            for (size_t m = 0; m < SK_ARRAY_COUNT(gGradMakers); ++m) {
                shaders[shdIdx++] = gGradMakers[m](pts,
                                                   gGradData[d],
                                                   SkShader::kClamp_TileMode);
            }
        }

        SkBitmap bm;
        makebm(&bm, w/16, h/4);
        for (size_t tx = 0; tx < SK_ARRAY_COUNT(tileModes); ++tx) {
            for (size_t ty = 0; ty < SK_ARRAY_COUNT(tileModes); ++ty) {
                shaders[shdIdx++] = SkShader::MakeBitmapShader(bm, tileModes[tx], tileModes[ty]);
            }
        }

        SkPaint paint;
        paint.setDither(true);
        paint.setAntiAlias(true);
        sk_tool_utils::set_portable_typeface(&paint);
        paint.setTextSize(SkIntToScalar(pointSize));

        canvas->save();
        canvas->translate(SkIntToScalar(20), SkIntToScalar(10));

        SkPath path;
        path.arcTo(SkRect::MakeXYWH(SkIntToScalar(-40), SkIntToScalar(15),
                                    SkIntToScalar(300), SkIntToScalar(90)),
                                    SkIntToScalar(225), SkIntToScalar(90),
                                    false);
        path.close();

        static const int testsPerCol = 8;
        static const int rowHeight = 60;
        static const int colWidth = 300;
        canvas->save();
        for (int s = 0; s < static_cast<int>(SK_ARRAY_COUNT(shaders)); s++) {
            canvas->save();
            int i = 2*s;
            canvas->translate(SkIntToScalar((i / testsPerCol) * colWidth),
                              SkIntToScalar((i % testsPerCol) * rowHeight));
            paint.setShader(shaders[s]);
            canvas->drawText(text, textLen, 0, textBase, paint);
            canvas->restore();
            canvas->save();
            ++i;
            canvas->translate(SkIntToScalar((i / testsPerCol) * colWidth),
                              SkIntToScalar((i % testsPerCol) * rowHeight));
            canvas->drawTextOnPath(text, textLen, path, nullptr, paint);
            canvas->restore();
        }
        canvas->restore();

    }

private:
    typedef GM INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

static GM* MyFactory(void*) { return new ShaderTextGM; }
static GMRegistry reg(MyFactory);
}


text:
import numpy
from scipy import ndimage

pi2 = numpy.pi * 2

numpy.random.seed(1)

numcases = 100000
patchsize = 13

baseims1 = numpy.random.randn(numcases, patchsize, patchsize)
baseims2 = numpy.random.randn(numcases, patchsize, patchsize)
analogies = numpy.zeros((numcases, 4, patchsize**2), dtype='float')

for i in range(numcases):
    print i
    _angle = 0.0
    angle_delta = (numpy.random.vonmises(0.0, 1.0)/numpy.pi) * 180
    for j in range(2):
        _angle += angle_delta
        analogies[i, j, :] = ndimage.rotate(baseims1[i], _angle, reshape=False, mode='wrap').flatten()
        analogies[i, j+2, :] = ndimage.rotate(baseims2[i], _angle, reshape=False, mode='wrap').flatten()

numpy.save('rotation_analogies'+str(patchsize)+'x'+str(patchsize)+'_numcases'+str(numcases)+'.npy', analogies)


text:
package main

import (
	"flag"
	"fmt"
	"os"
	"sort"
	"strconv"
	"text/tabwriter"
)

var (
	changedOnly = flag.Bool("changed", false, "show only benchmarks that have changed")
	magSort     = flag.Bool("mag", false, "sort benchmarks by magnitude of change")
	best        = flag.Bool("best", false, "compare best times from old and new")
)

const usageFooter = `
Each input file should be from:
	go test -test.run=NONE -test.bench=. > [old,new].txt

Benchcmp compares old and new for each benchmark.

If -test.benchmem=true is added to the "go test" command
benchcmp will also compare memory allocations.
`

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: %s old.txt new.txt\n\n", os.Args[0])
		flag.PrintDefaults()
		fmt.Fprint(os.Stderr, usageFooter)
		os.Exit(2)
	}
	flag.Parse()
	if flag.NArg() != 2 {
		flag.Usage()
	}

	before := parseFile(flag.Arg(0))
	after := parseFile(flag.Arg(1))

	cmps, warnings := Correlate(before, after)

	for _, warn := range warnings {
		fmt.Fprintln(os.Stderr, warn)
	}

	if len(cmps) == 0 {
		fatal("benchcmp: no repeated benchmarks")
	}

	w := new(tabwriter.Writer)
	w.Init(os.Stdout, 0, 0, 5, ' ', 0)
	defer w.Flush()

	var header bool // Has the header has been displayed yet for a given block?

	if *magSort {
		sort.Sort(ByDeltaNsOp(cmps))
	} else {
		sort.Sort(ByParseOrder(cmps))
	}
	for _, cmp := range cmps {
		if !cmp.Measured(NsOp) {
			continue
		}
		if delta := cmp.DeltaNsOp(); !*changedOnly || delta.Changed() {
			if !header {
				fmt.Fprintf(w, "benchmark\told ns/op\tnew ns/op\tdelta\t\n")
				header = true
			}
			fmt.Fprintf(w, "%s\t%s\t%s\t%s\t\n", cmp.Name(), formatNs(cmp.Before.NsOp), formatNs(cmp.After.NsOp), delta.Percent())
		}
	}

	header = false
	if *magSort {
		sort.Sort(ByDeltaMbS(cmps))
	}
	for _, cmp := range cmps {
		if !cmp.Measured(MbS) {
			continue
		}
		if delta := cmp.DeltaMbS(); !*changedOnly || delta.Changed() {
			if !header {
				fmt.Fprintf(w, "\nbenchmark\told MB/s\tnew MB/s\tspeedup\t\n")
				header = true
			}
			fmt.Fprintf(w, "%s\t%.2f\t%.2f\t%s\t\n", cmp.Name(), cmp.Before.MbS, cmp.After.MbS, delta.Multiple())
		}
	}

	header = false
	if *magSort {
		sort.Sort(ByDeltaAllocsOp(cmps))
	}
	for _, cmp := range cmps {
		if !cmp.Measured(AllocsOp) {
			continue
		}
		if delta := cmp.DeltaAllocsOp(); !*changedOnly || delta.Changed() {
			if !header {
				fmt.Fprintf(w, "\nbenchmark\told allocs\tnew allocs\tdelta\t\n")
				header = true
			}
			fmt.Fprintf(w, "%s\t%d\t%d\t%s\t\n", cmp.Name(), cmp.Before.AllocsOp, cmp.After.AllocsOp, delta.Percent())
		}
	}

	header = false
	if *magSort {
		sort.Sort(ByDeltaBOp(cmps))
	}
	for _, cmp := range cmps {
		if !cmp.Measured(BOp) {
			continue
		}
		if delta := cmp.DeltaBOp(); !*changedOnly || delta.Changed() {
			if !header {
				fmt.Fprintf(w, "\nbenchmark\told bytes\tnew bytes\tdelta\t\n")
				header = true
			}
			fmt.Fprintf(w, "%s\t%d\t%d\t%s\t\n", cmp.Name(), cmp.Before.BOp, cmp.After.BOp, cmp.DeltaBOp().Percent())
		}
	}
}

func fatal(msg interface{}) {
	fmt.Fprintln(os.Stderr, msg)
	os.Exit(1)
}

func parseFile(path string) BenchSet {
	f, err := os.Open(path)
	if err != nil {
		fatal(err)
	}
	bb, err := ParseBenchSet(f)
	if err != nil {
		fatal(err)
	}
	return bb
}

// formatNs formats ns measurements to expose a useful amount of
// precision. It mirrors the ns precision logic of testing.B.
func formatNs(ns float64) string {
	prec := 0
	switch {
	case ns < 10:
		prec = 2
	case ns < 100:
		prec = 1
	}
	return strconv.FormatFloat(ns, 'f', prec, 64)
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.0
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace T4Toolbox.VisualStudio {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("T4Toolbox.VisualStudio.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to T4 Toolbox.
        /// </summary>
        internal static string _100 {
            get {
                return ResourceManager.GetString("100", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to General.
        /// </summary>
        internal static string _101 {
            get {
                return ResourceManager.GetString("101", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Path must be absolute..
        /// </summary>
        internal static string InputFilePathMustBeAbsoluteMessage {
            get {
                return ResourceManager.GetString("InputFilePathMustBeAbsoluteMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to One of the output files is a null reference.
        /// </summary>
        internal static string OutputFileIsNullMessage {
            get {
                return ResourceManager.GetString("OutputFileIsNullMessage", resourceCulture);
            }
        }
    }
}


text:
/**
* Node fs module that returns promises
*/

var fs = require("fs"),
  convertNodeAsyncFunction = require("./promise").convertNodeAsyncFunction;

// convert all the non-sync functions
for (var i in fs) {
  if (!(i.match(/Sync$/))) {
    exports[i] = convertNodeAsyncFunction(fs[i]);
  }
}

// convert the functions that don't have a declared callback
exports.writeFile = convertNodeAsyncFunction(fs.writeFile, true);
exports.readFile = convertNodeAsyncFunction(fs.readFile, true);


text:
let mirror = require('keymirror')

module.exports = mirror({
	CANDIDATE_CREATE: null,
	CANDIDATE_DESTROY: null,
	ISSUE_CREATE: null,
	ISSUE_DESTROY: null,
	VIDEOS_SYNC: null
})


text:
namespace Demo.InProcSessions {
  using System;
  using Nancy;

  public static class FormatterExtensions {
    public static Response AsNonCachedText(this IResponseFormatter responseFormatter, string responseText) {
      if (responseFormatter == null) throw new ArgumentNullException("responseFormatter");

      return responseFormatter.AsText(responseText)
        .WithHeader("Cache-Control", "no-cache, no-store, must-revalidate")
        .WithHeader("Pragma", "no-cache")
        .WithHeader("Expires", "0");
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="@color/bg_search_map" />

    <stroke
        android:width="0dp"
        android:color="@color/bg_search_map" />

    <corners
        android:bottomLeftRadius="5dip"
        android:bottomRightRadius="5dip"
        android:topLeftRadius="5dip"
        android:topRightRadius="5dip" />

</shape>


text:
package test

import (
	"crypto/rand"
	"testing"

	"github.com/digitalocean/doctl/Godeps/_workspace/src/golang.org/x/crypto/ssh"
)

func TestCertLogin(t *testing.T) {
	s := newServer(t)
	defer s.Shutdown()

	// Use a key different from the default.
	clientKey := testSigners["dsa"]
	caAuthKey := testSigners["ecdsa"]
	cert := &ssh.Certificate{
		Key:             clientKey.PublicKey(),
		ValidPrincipals: []string{username()},
		CertType:        ssh.UserCert,
		ValidBefore:     ssh.CertTimeInfinity,
	}
	if err := cert.SignCert(rand.Reader, caAuthKey); err != nil {
		t.Fatalf("SetSignature: %v", err)
	}

	certSigner, err := ssh.NewCertSigner(cert, clientKey)
	if err != nil {
		t.Fatalf("NewCertSigner: %v", err)
	}

	conf := &ssh.ClientConfig{
		User: username(),
	}
	conf.Auth = append(conf.Auth, ssh.PublicKeys(certSigner))
	client, err := s.TryDial(conf)
	if err != nil {
		t.Fatalf("TryDial: %v", err)
	}
	client.Close()
}


text:
package com.fionapet.business.service;

import com.fionapet.business.entity.WarehouseMoverecord;
import org.dubbo.x.repository.DaoBase;
import org.dubbo.x.service.CURDServiceBase;
import com.fionapet.business.repository.WarehouseMoverecordDao;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *  移库记录
* Created by tom on 2016-07-18 11:56:08.
 */
public class WarehouseMoverecordServiceImpl extends CURDServiceBase<WarehouseMoverecord> implements WarehouseMoverecordService {
    @Autowired
    private WarehouseMoverecordDao warehouseMoverecordDao;

    @Override
    public DaoBase<WarehouseMoverecord> getDao() {
        return warehouseMoverecordDao;
    }
}


text:
#include "application.hpp"
#include "command_buffer.hpp"
#include "device.hpp"
#include "os_filesystem.hpp"
#include "math.hpp"
#include "thread_group.hpp"

using namespace Granite;
using namespace Vulkan;
using namespace Util;

struct AsyncSpecConstantApplication : Granite::Application, Granite::EventHandler
{
	std::unordered_set<Hash> pending_pipelines;

	void render_frame(double, double)
	{
		auto &wsi = get_wsi();
		auto &device = wsi.get_device();

		auto cmd = device.request_command_buffer();
		cmd->begin_render_pass(device.get_swapchain_render_pass(SwapchainRenderPass::ColorOnly));

		CommandBufferUtil::setup_fullscreen_quad(*cmd, "builtin://shaders/quad.vert", "assets://shaders/fill_color_spec_constant.frag");

		uint32_t value = frame_count >> 8;
		cmd->set_specialization_constant_mask(3 << 1);
		cmd->set_specialization_constant(1, 1);
		cmd->set_specialization_constant(2, value);
		cmd->push_constants(&value, 0, sizeof(value));

		// If we have the specialized shader already, go ahead, otherwise, queue up a compile to specialize the pipeline.
		if (!cmd->flush_pipeline_state_without_blocking())
		{
			DeferredPipelineCompile compile;
			cmd->extract_pipeline_state(compile);

			if (pending_pipelines.count(compile.hash) == 0)
			{
				LOGI("Enqueueing pipeline compile for spec constant %u.\n", value);
				GRANITE_THREAD_GROUP()->create_task([&device, c = std::make_unique<DeferredPipelineCompile>(compile)]() {
					CommandBuffer::build_graphics_pipeline(&device, *c, CommandBuffer::CompileMode::AsyncThread);
				});
				pending_pipelines.insert(compile.hash);
			}

			cmd->set_specialization_constant_mask(0);
			LOGI("Pipeline is currently not compiled, so falling back to ubershader for spec constant %u.\n", value);
		}
		CommandBufferUtil::draw_fullscreen_quad(*cmd);

		cmd->end_render_pass();
		device.submit(cmd);
		frame_count++;
	}

	ImageHandle render_target;
	unsigned frame_count = 0;
};

namespace Granite
{
Application *application_create(int, char **)
{
	GRANITE_APPLICATION_SETUP_FILESYSTEM();

	try
	{
		auto *app = new AsyncSpecConstantApplication();
		return app;
	}
	catch (const std::exception &e)
	{
		LOGE("application_create() threw exception: %s\n", e.what());
		return nullptr;
	}
}
}


text:
FROM yangqi/docker-debian
MAINTAINER Qi Yang <i@yangqi.me>

ENV DEBIAN_FRONTEND noninteractive
ENV MYSQL_ROOT_PASSWORD '123456'

WORKDIR /root

RUN \
  apt-get update && \
  apt-get install -y wget procps psmisc debconf debconf-utils perl && \
  wget -q http://dev.mysql.com/get/mysql-apt-config_0.3.6-1debian8_all.deb && \
  echo mysql-apt-config	mysql-apt-config/select-server	select	mysql-5.6 | debconf-set-selections && \
  echo mysql-apt-config	mysql-apt-config/select-product	select	Apply | debconf-set-selections && \
  dpkg -i mysql-apt-config_0.3.6-1debian8_all.deb && \
  apt-get update && \
  echo mysql-community-server	mysql-community-server/root-pass password $MYSQL_ROOT_PASSWORD | debconf-set-selections && \
  echo mysql-community-server	mysql-community-server/re-root-pass	password $MYSQL_ROOT_PASSWORD | debconf-set-selections && \
  apt-get install -y mysql-community-server

ADD my.cnf /etc/mysql/my.cnf
ADD startup.sh startup.sh

VOLUME ["/etc/mysql", "/var/lib/mysql", "/var/log/mysql"]

CMD ["/bin/bash", "startup.sh"]

EXPOSE 3306


text:
First off, thank you for considering contributing to MetPy. MetPy is community-driven
project, so it's people like you that make MetPy useful and successful.

Following these guidelines helps to communicate that you respect the time of the
developers managing and developing this open source project. In return, they
should reciprocate that respect in addressing your issue, assessing changes, and
helping you finalize your pull requests.

We love contributions from community members, just like you! There are many ways
to contribute, from writing tutorial or example Jupyter notebooks, improvements
to the documentation, submitting bug report and feature requests, or even writing
code which can be incorporated into MetPy for everyone to use. If you get stuck at
any point you can create an [issue on GitHub](https://github.com/Unidata/MetPy/issues)
or contact us at one of the other channels mentioned below.

For more information on contributing to open source projects,
[GitHub's own guide](https://guides.github.com/activities/contributing-to-open-source/)
is a great starting point.

## Getting Started

Interested in helping build MetPy? Have code from your research that you believe others will
find useful? Have a few minutes to tackle an issue? In this guide we will get you setup and
integrated into contributing to MetPy!

## What Can I Do?
* Tackle any [issues](https://github.com/Unidata/MetPy/issues) you wish! We have a special
  label for issues that beginners might want to try. Have a look at our
  [current beginner issues.](https://github.com/unidata/metpy/issues?q=is%3Aopen+is%3Aissue+label%3A%22Difficulty%3A+Beginner%22)

* Contribute code you already have. It doesn't need to be perfect! We will help you clean
  things up, test it, etc.

* Make a tutorial or example of how to do something.

## How Can I Talk to You?
Discussion of MetPy development often happens in the issue tracker and in pull requests.
In addition, the developers monitor the
[gitter chat room](https://gitter.im/Unidata/MetPy?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
for the project as well.

## Ground Rules
The goal is to maintain a diverse community that's pleasant for everyone. Please
be considerate and respectful of others. Other items:

* Each pull request should consist of a logical collection of changes. You can
  include multiple bug fixes in a single pull request, but they should be related.
  For unrelated changes, please submit multiple pull requests.
* Do not commit changes to files that are irrelevant to your feature or bugfix
  (eg: .gitignore).
* Be willing to accept criticism and work on improving your code; we don't want
  to break other users' code, so care must be taken not to introduce bugs.
* Be aware that the pull request review process is not immediate, and is
  generally proportional to the size of the pull request.

## Reporting a bug
When creating a new issue, please be as specific as possible. Include the version
of the code you were using, as well as what operating system you are running.
If possible, include complete, minimal example code that reproduces the problem.

## Pull Requests
**Working on your first Pull Request?** You can learn how from this *free* series [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github)

We love pull requests from everyone. Fork, then clone the repo:

    git clone git@github.com:your-username/metpy.git

Install metpy:

    pip install .

Install py.test (at least version 2.4) and make sure the tests pass:

    pip install pytest
    py.test

Make your change. Add tests for your change. Make the tests pass:

    py.test

Commit the changes you made. Chris Beams has written a [guide](http://chris.beams.io/posts/git-commit/) on how to write good commit messages.

Push to your fork and [submit a pull request][pr].

[pr]: https://github.com/Unidata/metpy/compare/

For the Pull Request to be accepted, you need to agree to the
[MetPy Contributor License Agreement (CLA)](https://www.clahub.com/agreements/Unidata/MetPy).
See [here](https://github.com/Unidata/MetPy/blob/master/CLA.md) for more
explanation and rationale behind MetPy's CLA.

As part of the Pull Request, be sure to add yourself to the
[list of contributors](https://github.com/Unidata/MetPy/blob/master/CONTRIBUTORS.md).
We want to make sure we acknowledge the hard work you've generously contributed
here.

## Code Review
Once you've submitted a Pull Request, at this point you're waiting on us. You
should expect to hear at least a comment within a couple of days.
We may suggest some changes or improvements or alternatives.

Some things that will increase the chance that your pull request is accepted:

* Write tests.
* Follow [PEP8][pep8] for style. (The `flake8` utility can help with this.)
* Write a [good commit message][commit].

Pull requests will automatically have tests run by Travis. This includes
running both the unit tests as well as the `flake8` code linter.

[pep8]: https://www.python.org/dev/peps/pep-0008/
[commit]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html

## Other Channels
If you're interested in contacting us or being a part of the community in
other ways, feel free to contact us in
[MetPy's Gitter Channel](https://gitter.im/Unidata/MetPy) or through Unidata's
[python-users](https://www.unidata.ucar.edu/support/#mailinglists) mailing list.


text:
cask 'downie' do
  version '3.6.1,1950'
  sha256 '7a29fb6aa42684e9218c2daef5bcc38beedb9cfc0c66a7674310dc8257a41cc0'

  url "https://trial.charliemonroe.net/downie/v#{version.major}/Downie_#{version.major}_#{version.after_comma}.zip"
  appcast "https://trial.charliemonroe.net/downie/updates_#{version.major}.xml"
  name 'Downie'
  homepage 'https://software.charliemonroe.net/downie.php'

  auto_updates true
  depends_on macos: '>= :el_capitan'

  app "Downie #{version.major}.app"
end


text:
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Contacts.Controllers;

namespace Contacts.Tests.Controllers
{
	[TestClass]
	public class HomeControllerTest
	{
		[TestMethod]
		public void Index()
		{
			// Arrange
			HomeController controller = new HomeController();

			// Act
			ViewResult result = controller.Index() as ViewResult;

			// Assert
			Assert.AreEqual("Contacts ASP.NET MVC application", result.ViewBag.Message);
		}

		[TestMethod]
		public void About()
		{
			// Arrange
			HomeController controller = new HomeController();

			// Act
			ViewResult result = controller.About() as ViewResult;

			// Assert
			Assert.IsNotNull(result);
		}
	}
}


text:
<?php
namespace App\Repositories;

use App\Category;
use App\Http\Controllers\PrepareResponse;
use App\Task;
use App\Transformers\TaskTransformer;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;

class TaskRepository extends AbstractRepository
{
	private $transformer;
	const RULES_VALIDATIONS = array(
		'category_id' => 'required|integer',
		'description' => 'required|string'
	);

    public function __construct(Task $model, TaskTransformer $transformer)
    {
        parent::__construct(new PrepareResponse);
	    $this->transformer = new TaskTransformer();
    }

    /**
     * @param $category_id
     * @return array
     */
    public function getAllByCategoryAndUser($category_id)
    {
	    $user = Auth::user();
	    if ( ! $user instanceof User) {
		    return $this->prepare_response->errorUnauthorized();
	    }

	    $limit = Input::get('limit')? : self::DEFAULT_LIMIT;
	    if ( $limit > self::MAXIMUM_LIMIT ) {
		    $limit = self::MAXIMUM_LIMIT;
	    }

        $category = ( new Category )
            ->where('id', $category_id)
            ->where('user_id', $user->id)
            ->first();

        if ( $category instanceof Category) {
            return $this->prepare_response->respondWithCollection($category->tasks()->paginate($limit), new TaskTransformer);
        }
	    return $this->prepare_response->errorNotFound();
    }

	/**
	 * @param array $params
	 * @param $category_id
	 *
	 * @return array
	 */
    public function createByCategoryAndUser(array $params, $category_id)
    {
	    $user = Auth::user();
	    if ( ! $user instanceof User) {
		    return $this->prepare_response->errorUnauthorized();
	    }

        $category = ( new Category )
            ->where('id', $category_id)
            ->where('user_id', $user->id)
            ->first();

        if ( ! $category instanceof Category) {
	        return $this->prepare_response->errorNotFound();
        }
	    $params["category_id"] = $category->id;

	    if ( ! $this->setValidationRules(self::RULES_VALIDATIONS)->validateParameters($params) ) {
		    return $this->prepare_response->errorWrongArgs();
	    }

	    return $this->prepare_response->responseCreated(
		    $category->tasks()->create($params),
		    new TaskTransformer
	    );

    }

	/**
	 * Index Path
	 *
	 * @param $category_id
	 * @param $task_id
	 *
	 * @return array
	 */
	public function showByUserTaskIDAndCategoryID($category_id, $task_id)
	{
		$user = Auth::user();
		if ( ! $user instanceof User) {
			return $this->prepare_response->errorUnauthorized();
		}

		$category = $user->categories()
		             ->where('id',$category_id)
		             ->first();

		if ( $category instanceof Category) {
			$task = $category
				->tasks()
				->where('id',$task_id)
				->first();

			if ( $task instanceof Task) {
				return $this->prepare_response->respondWithItem(
					$task,
					new TaskTransformer
				);
			}

			return $this->prepare_response->errorNotFound();
		}

		return $this->prepare_response->errorNotFound();
	}

	/**
	 * Index Path
	 *
	 * @param array $params
	 * @param $category_id
	 * @param $task_id
	 *
	 * @return array
	 */
    public function updateByUserTaskIDandCategoryID(array $params, $category_id, $task_id)
    {
	    $user = Auth::user();
	    if ( ! $user instanceof User) {
		    return $this->prepare_response->errorUnauthorized();
	    }

        $category = ( new Category )
            ->where('user_id', $user->id)
            ->where('id', $category_id)
            ->first();

        if ( ! $category instanceof Category) {
            return $this->prepare_response->errorNotFound();
        }
	    $params["category_id"] = $category->id;

	    $task = $category
		    ->tasks()
		    ->where('id',$task_id)
		    ->first();

	    if ( ! $task instanceof Task) {
		    return $this->prepare_response->errorNotFound();
	    }

	    if ( ! $this->setValidationRules(self::RULES_VALIDATIONS)->validateParameters($params) ) {
		    return $this->prepare_response->errorWrongArgs();
	    }

	    $task->fill($params)->save();
	    return $this->prepare_response->respondWithItem(
		    $task,
		    new TaskTransformer
	    );
    }

	/**
	 * Index Path
	 *
	 * @param $category_id
	 * @param $task_id
	 *
	 * @return array
	 */
    public function deleteByUserTaskIDandCategoryID($category_id, $task_id)
    {
	    $user = Auth::user();
	    if ( ! $user instanceof User) {
		    return $this->prepare_response->errorUnauthorized();
	    }

        $category = ( new Category )
            ->where('user_id', $user->id)
            ->where('id', $category_id)
            ->first();

        if ( $category instanceof Category) {
            $task = $category
                ->tasks()
                ->where('id',$task_id)
                ->first();

            if ( $task instanceof Task) {
                $task->delete();
                return $this->prepare_response->respondWithoutItem("Task");
            }

            return $this->prepare_response->errorNotFound();
        }

	    return $this->prepare_response->errorNotFound();
    }
}


text:
import { ProjectShape, TestShape } from '@seleniumhq/side-model'
import {
  getCustomCommands,
  correctPluginPaths,
  loadPlugins,
  Playback,
  Variables,
  WebDriverExecutor,
} from '@seleniumhq/side-runtime'
import fs from 'fs'
import { render } from 'ink'
import path from 'path'
import React from 'react'
import PlaybackComponent from './components/playback'

const main = async () => {
  let projectPath = process.argv[2]
  if (projectPath.startsWith('.')) {
    projectPath = path.join(process.cwd(), projectPath)
  }

  const project: ProjectShape = JSON.parse(
    fs.readFileSync(projectPath).toString()
  )

  const plugins = await loadPlugins(
    correctPluginPaths(projectPath, project.plugins)
  )
  const customCommands = getCustomCommands(plugins)
  const executor = new WebDriverExecutor({
    customCommands,
  })

  const playback = new Playback({
    baseUrl: project.url,
    getTestByName: (name: string) =>
      project.tests.find((t) => t.name === name) as TestShape,
    logger: console,
    executor,
    variables: new Variables(),
  })

  render(<PlaybackComponent project={project} playback={playback} />)
}

main()


text:
package com.example.commontasker;

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

/**
 * Created by Αρης on 6/10/2016.
 */
public class DataProvider {
    public  static HashMap<String,List<String>> getInfo(){

        HashMap<String,List<String>> catogories_details=new HashMap<String, List<String>>();

         List<String> house=new ArrayList<String>();
        house.add("Καθάρισμα Σπιτιού");
        house.add("Καθάρισμα Μπάνιου");
        house.add("Καθάρισμα Κουζίνας");
        house.add("Καθάρισμα Γκαράζ");

         List<String>  ergasies=new ArrayList<String>();
        ergasies.add("Συγγομηδή Ελίας");
        ergasies.add("Αμπέλια");
        ergasies.add("Αγορά απο Κρεοπώλη");
        ergasies.add("Καλλιέργεια Καλαμποκιού");

         List<String>  teaching=new ArrayList<String>();
        teaching.add("Mαθαίνοντας Αγγλικά");
        teaching.add("Mαθαίνοντας Ισπανικά για ένα Σεμιναριο");

         List<String>  Helping=new ArrayList<String>();
        Helping.add("Βοηθώντας Αδέσποτα ζώα");
        Helping.add("Βοηθώντας ένα Μεσήλικα να κάνει τα βασικά σε ένα Ηλεκτρονικό Υπολογιστή");
        Helping.add("Μετακόμιση");
        Helping.add("Προσοχή Ηλικιωμένου Ανθρώπου");

        catogories_details.put("Δουλειές Σπιτιού",house);
        catogories_details.put("Εξωτερικές Εργασίες",ergasies);
        catogories_details.put("Εκπαιδευτικές Εργασίες",teaching);
        catogories_details.put("Προσφέροντας Βοήθεια",Helping);

        return catogories_details;
    }

}


text:
class Ums::User < ActiveRecord::Base
  belongs_to :role

  validates_presence_of :account,:role
  validates_uniqueness_of :account,:name

  validate :password_non_blank

  belongs_to :created_by, class_name: "Ums::User"
  belongs_to :updated_by, class_name: "Ums::User"

  before_validation :record_operator

    #记录操作人员
    def record_operator
      if self.respond_to?(:session) && session[:user_id]
        self.created_by_id = session[:user_id] if new_record?
        self.updated_by_id = session[:user_id]
      end
    end

    def self.authenticate(account,password)
    	user = self.find_by_account(account)
    	if user
      	expected_password = encrypted_password(password,user.salt)
        #logger.debug("user.hashed_password:" + user.hashed_password + ",expected_password:" + expected_password)
      	if user.hashed_password != expected_password || !user.is_enabled
      		user = nil
      	end
      end
      user
    end

    def verify_password(password)
      expected_password = Ums::User.encrypted_password(password,self.salt)
      logger.debug("expected_password:"+expected_password+",hashed_password:"+self.hashed_password)
      if self.hashed_password == expected_password
        true
      else
        false
      end
    end

    def password
    	@password
    end

	def password=(pwd)
		@password = pwd
		return if pwd.blank?
		create_salt
		self.hashed_password = Ums::User.encrypted_password(pwd,self.salt)
	end

  def as_json options=nil
    options ||= {}
    options[:except] = [:hashed_password,:salt]
    super options
  end

	private
	def password_non_blank
		errors.add(:password,"missing password") if hashed_password.blank?
	end
	def self.encrypted_password(password,slat)
    Digest::SHA2.hexdigest(password.to_s + slat.to_s)
	end
	def create_salt
	    self.salt =  rand.to_s
	end
end


text:
using System;
using System.Data.Entity;
using Bmz.Framework.MultiTenancy;

namespace Bmz.Framework.EntityFramework
{
    /// <summary>
    ///
    /// </summary>
    /// <typeparam name="TDbContext"></typeparam>
    public interface IDbContextProvider<out TDbContext>
        where TDbContext : DbContext
    {
        [Obsolete("Use GetDbContext() method instead")]
        TDbContext DbContext { get; }

        TDbContext GetDbContext();

        TDbContext GetDbContext(MultiTenancySides? multiTenancySide );
    }
}


text:
Todo:

*Polylines:
-fix line styling,
-make dots better
-animate!!!

*Front-page
-instruction boxes

*Markers
-add alert when trying to add more than 10 markers

*Navbar
-make responsive

*Routes
-draw all only includes so many routes - add alert?

*Green bar
-styling


text:
<?php

namespace Pwc\SirBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="likelihood")
 */
class Likelihood
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $name;

    /**
     * @ORM\Column(type="integer", length=1)
     */
    protected $rank;

    /**
     * @ORM\OneToMany(targetEntity="Vulnerability", mappedBy="likelihood")
     */
    protected $vulnerabilities;

    public function __toString()
    {
        return $this->getName();
    }

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->vulnerabilities = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Likelihood
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set rank
     *
     * @param integer $rank
     * @return Likelihood
     */
    public function setRank($rank)
    {
        $this->rank = $rank;

        return $this;
    }

    /**
     * Get rank
     *
     * @return integer
     */
    public function getRank()
    {
        return $this->rank;
    }

    /**
     * Add vulnerability
     *
     * @param \Pwc\SirBundle\Entity\Vulnerability $vulnerability
     * @return Likelihood
     */
    public function addVulnerability(\Pwc\SirBundle\Entity\Vulnerability $vulnerability)
    {
        $this->vulnerabilities[] = $vulnerability;

        return $this;
    }

    /**
     * Remove vulnerability
     *
     * @param \Pwc\SirBundle\Entity\Vulnerability $vulnerability
     */
    public function removeVulnerability(\Pwc\SirBundle\Entity\Vulnerability $vulnerability)
    {
        $this->vulnerabilities->removeElement($vulnerability);
    }

    /**
     * Get vulnerabilities
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getVulnerabilities()
    {
        return $this->vulnerabilities;
    }
}