text:
<?php

/**
 * @file
 * Contains \Triquanta\IziTravel\Tests\DataType\CountryCityTranslationTest.
 */

namespace Triquanta\IziTravel\Tests\DataType;

use Triquanta\IziTravel\DataType\CountryCityTranslation;
use Triquanta\IziTravel\DataType\MultipleFormInterface;

/**
 * @coversDefaultClass \Triquanta\IziTravel\DataType\CountryCityTranslation
 */
class CountryCityTranslationTest extends \PHPUnit_Framework_TestCase
{

    protected $json = <<<'JSON'
{
  "name": "foo_bar",
  "language":  "UK"
}
JSON;

    /**
     * The class under test.
     *
     * @var \Triquanta\IziTravel\DataType\CountryCityTranslation
     */
    protected $sut;

    public function setUp()
    {
        $this->sut = CountryCityTranslation::createFromJson($this->json,
          MultipleFormInterface::FORM_FULL);
    }

    /**
     * @covers ::createFromJson
     * @covers ::createFromData
     */
    public function testCreateFromJson()
    {
        CountryCityTranslation::createFromJson($this->json,
          MultipleFormInterface::FORM_FULL);
    }

    /**
     * @covers ::createFromJson
     * @covers ::createFromData
     *
     * @expectedException \Triquanta\IziTravel\DataType\InvalidJsonFactoryException
     */
    public function testCreateFromJsonWithInvalidJson()
    {
        $json = 'foo';

        CountryCityTranslation::createFromJson($json,
          MultipleFormInterface::FORM_FULL);
    }

    /**
     * @covers ::getName
     */
    public function testGetName()
    {
        $this->assertSame('foo_bar', $this->sut->getName());
    }

    /**
     * @covers ::getLanguageCode
     */
    public function testGetLanguageCode()
    {
        $this->assertSame('UK', $this->sut->getLanguageCode());
    }

}


text:
namespace fractal
{
	namespace fcore
	{
		MeshDataResource::MeshDataResource (const FString& path) :
			Resource (path, ResourceType::RESOURCE_MESH)
		{
			// TODO: Load mesh from file
		}

		MeshDataResource::MeshDataResource (const FString& name, const MeshData& meshData) :
			MeshDataResource(name, meshData.vertices, meshData.indices)
		{
			// empty
		}

		MeshDataResource::MeshDataResource (const FString& name, const std::vector<VertexPosColorTexture>& vertices,
			const std::vector<WORD>& indices) :
			Resource (name, ResourceType::RESOURCE_MESH)
		{
			ID3D11Device* device = dynamic_cast<fractal::fcore::Graphics*>(fractal::fcore::SystemManager::Instance ()->GetSystem (fractal::SystemType::GRAPHICS_SYSTEM))->GetDevice();
			assert (device);

			// Create and initialize the vertex buffer memory with 0.
			D3D11_BUFFER_DESC vertexBufferDesc;
			ZeroMemory (&vertexBufferDesc, sizeof (D3D11_BUFFER_DESC));
			// TODO: change the next line usage when the thing is static or dynamic
			vertexBufferDesc.Usage					= D3D11_USAGE_DEFAULT; // D3D11_USAGE_DYNAMIC | D3D11_USAGE_IMMUTABLE
			vertexBufferDesc.BindFlags				= D3D11_BIND_VERTEX_BUFFER;
			vertexBufferDesc.ByteWidth				= sizeof (vertices.front()) * vertices.size();
			vertexBufferDesc.CPUAccessFlags			= 0;
			vertexBufferDesc.MiscFlags				= 0;
			vertexBufferDesc.StructureByteStride	= 0;

			D3D11_SUBRESOURCE_DATA resourceData;
			ZeroMemory (&resourceData, sizeof (D3D11_SUBRESOURCE_DATA));
			resourceData.pSysMem = vertices.data();

			// creating the vertex buffer
			HRESULT hr = device->CreateBuffer (&vertexBufferDesc, &resourceData, &m_d3dVertexBuffer);
			assert (!FAILED (hr));

			// Create and initialize the index buffer.
			D3D11_BUFFER_DESC indexBufferDesc;
			ZeroMemory (&indexBufferDesc, sizeof (D3D11_BUFFER_DESC));
			indexBufferDesc.Usage					= D3D11_USAGE_DEFAULT;
			indexBufferDesc.BindFlags				= D3D11_BIND_INDEX_BUFFER;
			indexBufferDesc.ByteWidth				= sizeof (indices.front ()) * indices.size ();
			indexBufferDesc.CPUAccessFlags			= 0;
			indexBufferDesc.MiscFlags				= 0;
			indexBufferDesc.StructureByteStride		= 0;

			resourceData.pSysMem = indices.data ();

			hr = device->CreateBuffer (&indexBufferDesc, &resourceData, &m_d3dIndexBuffer);
			assert (!FAILED (hr));

			m_indicesCount = indices.size ();
		}

		bool MeshDataResource::Init ()
		{
			return Resource::Init () && m_d3dIndexBuffer && m_d3dVertexBuffer;
		}

		bool MeshDataResource::Shutdown ()
		{
			SafeRelease (m_d3dIndexBuffer);
			SafeRelease (m_d3dVertexBuffer);
			return Resource::Shutdown ();
		}

		ID3D11Buffer* MeshDataResource::GetVertexBuffer () const
		{
			return m_d3dVertexBuffer;
		}

		ID3D11Buffer* MeshDataResource::GetIndexBuffer () const
		{
			return m_d3dIndexBuffer;
		}

		unsigned __int32 MeshDataResource::GetIndicesCount () const
		{
			return m_indicesCount;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
/* */
(function(process) {
  var Buffer = require("../../index").Buffer;
  if (process.env.OBJECT_IMPL)
    Buffer.TYPED_ARRAY_SUPPORT = false;
  var common = {};
  var assert = require("assert");
  assert.equal(Buffer('hérité').toString('ascii'), 'hC)ritC)');
  var input = 'C'est, graphiquement, la réunion d'un accent aigu ' + 'et d'un accent grave.';
  var expected = 'Cb\u0000\u0019est, graphiquement, la rC)union ' + 'db\u0000\u0019un accent aigu et db\u0000\u0019un ' + 'accent grave.';
  var buf = Buffer(input);
  for (var i = 0; i < expected.length; ++i) {
    assert.equal(buf.slice(i).toString('ascii'), expected.slice(i));
    if (input.charCodeAt(i) > 65535)
      ++i;
    if (input.charCodeAt(i) > 127)
      ++i;
  }
})(require("process"));


text:
package br.com.chateado;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{

	@Override
	public void configureMessageBroker(MessageBrokerRegistry config){
		config.enableSimpleBroker("/server");
		config.setApplicationDestinationPrefixes("/app");
	}

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		registry.addEndpoint("/chat").setAllowedOrigins("*").withSockJS();
	}

}


text:
#import <UIKit/UIKit.h>
#import "CAUITransportButton.h"

@protocol CAUITransportEngine;

@interface CAUITransportView : UIView ;

/* Object that talks to the host app and handles transport messaging */
@property(assign, nonatomic, setter = setDelegateAddObserver:) id<CAUITransportEngine> engine;

-(IBAction) togglePlayback:(id) sender;
-(IBAction) toggleRecording:(id) sender;
-(IBAction) rewindAction:(id)sender;

@end

/* A protocol for delegates of CAUITransportView, i.e your audio engine */
@protocol CAUITransportEngine <NSObject>

/*Functions/properties  relating to transport state, play/pause, record, rewind, etc*/

@required

@property (nonatomic) bool		playing;
@property (nonatomic) bool		recording;
@property (nonatomic) bool		connected;
@property (nonatomic) Float64	playTime;

-(BOOL) canPlay;
-(BOOL) canRewind;
-(BOOL) canRecord;

-(BOOL) isHostPlaying;
-(BOOL) isHostRecording;
-(BOOL) isHostConnected;

-(void) togglePlay;
-(void) toggleRecord;
-(void)	rewind;

/* Fetch the icon from the host*/
-(UIImage *) getAudioUnitIcon;

/* Fetch the current time from the transport */
-(NSString*) getPlayTimeString;

/* Open a url and goto the host app */

-(void)gotoHost;

@end


text:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class CountTotalDocuments {

	public static void main(String args[])
	{
		TreeMap<String, Integer> map = new TreeMap<String, Integer>();
		HashSet<String> set = new HashSet<String>();
		int count = 0, totalURLs = 0;
		while(count++<99) {
		try {
		String filename = "D:\\crawlstorage\\datafile" + Integer.toString(count+1)  + ".xml";
		String str = null, url = null;;
		BufferedReader br = new BufferedReader(new FileReader(filename));

		while((str=br.readLine())!=null)

		{
			if(str.startsWith("<url>"))
			{
				url = str.substring(5, str.length()-6);
				set.add(url);
			}

		}

	}
	catch(Exception e)
	{ e.printStackTrace(); }

	}

	System.out.println(set.size());
	}

}


text:
package com.outr.arango.api

import com.outr.arango.api.model._
import io.youi.client.HttpClient
import io.youi.http.HttpMethod
import io.youi.net._
import io.circe.Json
import scala.concurrent.{ExecutionContext, Future}

object AdminClusterHealth {

  def get(client: HttpClient)(implicit ec: ExecutionContext): Future[Json] = client
    .method(HttpMethod.Get)
    .path(path"/_admin/cluster/health", append = true)
    .call[Json]
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>YaIBtgWD: daemon.c File Reference</title>

<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />

<link href="search/search.css" rel="stylesheet" type="text/css"/>

YaIBtgWD

Yet another IRC Bot to gain World Domination

Main Page

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

File Members

Functions

daemon.c File Reference

The File includes Functions to daemonize the Program.
More...

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/stat.h>

#include "daemon.h"

Functions

void 	daemonize ()

 	daemonize the Program

Detailed Description

The File includes Functions to daemonize the Program.

Function Documentation

          void daemonize
          (
          	)

daemonize the Program

With this Function, you can daemonize your Program. After the call of this Function, the Program runs in the Background and exists even after your Logout.

 All Files Functions

<address class="footer">
Generated on Wed May 9 2012 16:52:59 for YaIBtgWD by

 1.7.6.1
</address>


text:
title: nameof Expressions
---

# nameof Expressions

Sometimes you need the string name of a variable, type, or member for things such as raising an exception, logging, or firing property changed events. Prior to C# 6.0, you might use a string literal for such purposes.
##
```
public void ProcessStudent(Student student)
{
    if (student == null) throw new ArgumentNullException("student");
}
```
However, if the student parameter were to be renamed, you would have to remember to also modify the string literal. Now with nameof expressions, you don't have to use string literals and the compiler will be able to warn you if you are using an incorrect name.
##
```
public void ProcessStudent(Student student)
{
    if (student == null) throw new ArgumentNullException(nameof(student));
}
```
Some examples of where nameof expressions may be useful include:
* Throwing exceptions during parameter validation
* Passing an action name when setting up MVC action links
* Needing to pass the name of a property when firing a property changed event in a class that implements INotifyPropertyChanged
* Passing the name of a property when registering a XAML dependency property
* Including a variable, type, or member name when logging

It should be noted that if you provide nameof with a qualified name, the compiler will generate a string for the rightmost name.


text:
'use strict';

angular.module('mean.users')
  .controller('QuestionAnswerController', ['$scope', '$rootScope','$http',
    function($scope, $rootScope,$http) {
    	$scope.question="";
    	$scope.answer="";

    	$scope.AddQuestionAnswer = function()
    	{
    		$http.post("/api/sendquestionanswer",{question:$scope.question,answer:$scope.answer}).success(function(res){console.log(res);
            $scope.question="";
            $scope.answer="";
    		});
    	}

    }

    ]);


text:
package nexus.torch

import nexus._
import nexus.math._
import nexus.syntax._
import nexus.torch._
import nexus.torch.jni._

/**
 * @author Tongfei Chen
 */
object TorchTest extends App {

  class A extends Dim; val A = new A
  class B extends Dim; val B = new B
  class C extends Dim; val C = new C

  val x = FloatTensor.fromNestedArray(A, B)(
    Array(
      Array(1f, 2f),
      Array(3f, 4f)
    )
  )

  println(x)

  val y = FloatTensor.fromNestedArray(B)(Array(-1f, -1f))
  val z = mvMul(x, y)

  val u = matMul(x, transpose(x))

  val bp = 0
}


text:
set -x -e

# build the db with BuildDatabase
BuildDatabase -engine ncbi -name db test.fa 2> /dev/null

# run repeat modeler
RepeatModeler -engine ncbi -database db 2> /dev/null

# check the result
test -s RM_*/consensi.fa


text:
package org.apache.hadoop.yarn.server.nodemanager;

import java.util.Map;
import java.util.concurrent.ConcurrentMap;

import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.yarn.api.ContainerManagementProtocol;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.server.api.records.NodeHealthStatus;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
import org.apache.hadoop.yarn.server.nodemanager.security.NMContainerTokenSecretManager;
import org.apache.hadoop.yarn.server.nodemanager.security.NMTokenSecretManagerInNM;
import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;

/**
 * Context interface for sharing information across components in the
 * NodeManager.
 */
public interface Context {

  /**
   * Return the nodeId. Usable only when the ContainerManager is started.
   *
   * @return the NodeId
   */
  NodeId getNodeId();

  /**
   * Return the node http-address. Usable only after the Webserver is started.
   *
   * @return the http-port
   */
  int getHttpPort();

  ConcurrentMap<ApplicationId, Application> getApplications();

  Map<ApplicationId, Credentials> getSystemCredentialsForApps();

  ConcurrentMap<ContainerId, Container> getContainers();

  NMContainerTokenSecretManager getContainerTokenSecretManager();

  NMTokenSecretManagerInNM getNMTokenSecretManager();

  NodeHealthStatus getNodeHealthStatus();

  ContainerManagementProtocol getContainerManager();

  LocalDirsHandlerService getLocalDirsHandler();

  ApplicationACLsManager getApplicationACLsManager();

  NMStateStoreService getNMStateStore();

  boolean getDecommissioned();

  void setDecommissioned(boolean isDecommissioned);

  NodeStatusUpdater getNodeStatusUpdater();
}


text:
require File.join(File.dirname(__FILE__), 'services')
module Noah
  class Host < Model
    # Host model
    # @return {Host} a {Host} object
    include Taggable
    include Linkable
    attribute :name
    attribute :status
    collection :services, Service

    index :name
    index :status
    index :services

    def validate
      super
      assert_present :name
      assert_present :status
      assert_unique :name
      assert_member :status, ["up","down","pending"]
    end

    # @return [Hash] A hash representation of a {Host}
    def to_hash
      services_hash = Hash.new
      services.sort.each do |svc|
        services_hash["#{svc.name}"] = svc.status
      end
      h = {:name => name, :status => status, :created_at => created_at, :updated_at => updated_at, :services => services_hash}
      super.merge(h)
    end

    class << self
    def find_or_create(opts = {})
      begin
        h = find(:name => opts[:name]).first
        #h = find(opts.reject{|key,value| key == :status}).first
        h.nil? ? host=new(opts) : host=h
        host.status = opts[:status]
        if host.valid?
          host.save
        end
        host
      rescue Exception => e
        e.message
      end
    end
    end

  end

  class Hosts
    # @param [Hash] optional filters for results
    # @return [Array] Array of {Host} objects
    def self.all(options = {})
      host_hash = Hash.new
      options.empty? ? hosts=Noah::Host.all.sort : hosts=Noah::Host.find(options).sort
      hosts.each {|x| host_hash["#{x.name}"] = x.to_hash.reject {|k,v| k == :name } }
      host_hash
    end
  end
end


text:
namespace {

// Converts ui::EventType to state for X*Events.
unsigned int XEventState(int flags) {
  return
      ((flags & ui::EF_SHIFT_DOWN) ? ShiftMask : 0) |
      ((flags & ui::EF_CONTROL_DOWN) ? ControlMask : 0) |
      ((flags & ui::EF_ALT_DOWN) ? Mod1Mask : 0) |
      ((flags & ui::EF_CAPS_LOCK_DOWN) ? LockMask : 0) |
      ((flags & ui::EF_ALTGR_DOWN) ? Mod5Mask : 0) |
      ((flags & ui::EF_COMMAND_DOWN) ? Mod4Mask : 0) |
      ((flags & ui::EF_MOD3_DOWN) ? Mod3Mask : 0) |
      ((flags & ui::EF_NUMPAD_KEY) ? Mod2Mask : 0) |
      ((flags & ui::EF_LEFT_MOUSE_BUTTON) ? Button1Mask: 0) |
      ((flags & ui::EF_MIDDLE_MOUSE_BUTTON) ? Button2Mask: 0) |
      ((flags & ui::EF_RIGHT_MOUSE_BUTTON) ? Button3Mask: 0);
}

// Converts EventType to XKeyEvent type.
int XKeyEventType(ui::EventType type) {
  switch (type) {
    case ui::ET_KEY_PRESSED:
      return KeyPress;
    case ui::ET_KEY_RELEASED:
      return KeyRelease;
    default:
      return 0;
  }
}

int XIButtonEventType(ui::EventType type) {
  switch (type) {
    case ui::ET_MOUSEWHEEL:
    case ui::ET_MOUSE_PRESSED:
      // The button release X events for mouse wheels are dropped by Aura.
      return XI_ButtonPress;
    case ui::ET_MOUSE_RELEASED:
      return XI_ButtonRelease;
    default:
      NOTREACHED();
      return 0;
  }
}

// Converts KeyboardCode to XKeyEvent keycode.
unsigned int XKeyEventKeyCode(ui::KeyboardCode key_code,
                              int flags,
                              XDisplay* display) {
  // XKeyEvent keycode is hardware keycode which doesn't consider SHIFT state.
  // There are bugs in XKeysymToKeycode that it returns wrong keycode for keysym
  // with SHIFT state. e.g. XK_less should return 59 but returns 94;
  // XK_parenright should return 19 but returns 188; etc.
  return XKeysymToKeycode(display, XKeysymForWindowsKeyCode(key_code, false));
}

// Converts Aura event type and flag to X button event.
unsigned int XButtonEventButton(ui::EventType type,
                                int flags) {
  // Aura events don't keep track of mouse wheel button, so just return
  // the first mouse wheel button.
  if (type == ui::ET_MOUSEWHEEL)
    return Button4;

  if (flags & ui::EF_LEFT_MOUSE_BUTTON)
    return Button1;
  if (flags & ui::EF_MIDDLE_MOUSE_BUTTON)
    return Button2;
  if (flags & ui::EF_RIGHT_MOUSE_BUTTON)
    return Button3;

  return 0;
}

void InitValuatorsForXIDeviceEvent(XIDeviceEvent* xiev) {
  int valuator_count = ui::DeviceDataManager::DT_LAST_ENTRY;
  xiev->valuators.mask_len = (valuator_count / 8) + 1;
  xiev->valuators.mask = new unsigned char[xiev->valuators.mask_len];
  memset(xiev->valuators.mask, 0, xiev->valuators.mask_len);
  xiev->valuators.values = new double[valuator_count];
}

XEvent* CreateXInput2Event(int deviceid,
                           int evtype,
                           int tracking_id,
                           const gfx::Point& location) {
  XEvent* event = new XEvent;
  memset(event, 0, sizeof(*event));
  event->type = GenericEvent;
  event->xcookie.data = new XIDeviceEvent;
  XIDeviceEvent* xiev =
      static_cast<XIDeviceEvent*>(event->xcookie.data);
  memset(xiev, 0, sizeof(XIDeviceEvent));
  xiev->deviceid = deviceid;
  xiev->sourceid = deviceid;
  xiev->evtype = evtype;
  xiev->detail = tracking_id;
  xiev->event_x = location.x();
  xiev->event_y = location.y();
  xiev->event = DefaultRootWindow(gfx::GetXDisplay());
  if (evtype == XI_ButtonPress || evtype == XI_ButtonRelease) {
    xiev->buttons.mask_len = 8;
    xiev->buttons.mask = new unsigned char[xiev->buttons.mask_len];
    memset(xiev->buttons.mask, 0, xiev->buttons.mask_len);
  }
  return event;
}

}  // namespace

namespace ui {

// XInput2 events contain additional data that need to be explicitly freed (see
// |CreateXInput2Event()|.
void XEventDeleter::operator()(XEvent* event) {
  if (event->type == GenericEvent) {
    XIDeviceEvent* xiev =
        static_cast<XIDeviceEvent*>(event->xcookie.data);
    if (xiev) {
      delete[] xiev->valuators.mask;
      delete[] xiev->valuators.values;
      delete[] xiev->buttons.mask;
      delete xiev;
    }
  }
  delete event;
}

ScopedXI2Event::ScopedXI2Event() {}
ScopedXI2Event::~ScopedXI2Event() {}

void ScopedXI2Event::InitKeyEvent(EventType type,
                                  KeyboardCode key_code,
                                  int flags) {
  XDisplay* display = gfx::GetXDisplay();
  event_.reset(new XEvent);
  memset(event_.get(), 0, sizeof(XEvent));
  event_->type = XKeyEventType(type);
  CHECK_NE(0, event_->type);
  event_->xkey.serial = 0;
  event_->xkey.send_event = 0;
  event_->xkey.display = display;
  event_->xkey.time = 0;
  event_->xkey.window = 0;
  event_->xkey.root = 0;
  event_->xkey.subwindow = 0;
  event_->xkey.x = 0;
  event_->xkey.y = 0;
  event_->xkey.x_root = 0;
  event_->xkey.y_root = 0;
  event_->xkey.state = XEventState(flags);
  event_->xkey.keycode = XKeyEventKeyCode(key_code, flags, display);
  event_->xkey.same_screen = 1;
}

void ScopedXI2Event::InitGenericButtonEvent(int deviceid,
                                            EventType type,
                                            const gfx::Point& location,
                                            int flags) {
  event_.reset(CreateXInput2Event(deviceid,
                                  XIButtonEventType(type), 0, gfx::Point()));
  XIDeviceEvent* xievent = static_cast<XIDeviceEvent*>(event_->xcookie.data);
  xievent->mods.effective = XEventState(flags);
  xievent->detail = XButtonEventButton(type, flags);
  xievent->event_x = location.x();
  xievent->event_y = location.y();
  XISetMask(xievent->buttons.mask, xievent->detail);
  // Setup an empty valuator list for generic button events.
  SetUpValuators(std::vector<Valuator>());
}

void ScopedXI2Event::InitGenericMouseWheelEvent(int deviceid,
                                                int wheel_delta,
                                                int flags) {
  InitGenericButtonEvent(deviceid, ui::ET_MOUSEWHEEL, gfx::Point(), flags);
  XIDeviceEvent* xievent = static_cast<XIDeviceEvent*>(event_->xcookie.data);
  xievent->detail = wheel_delta > 0 ? Button4 : Button5;
}

void ScopedXI2Event::InitScrollEvent(int deviceid,
                                     int x_offset,
                                     int y_offset,
                                     int x_offset_ordinal,
                                     int y_offset_ordinal,
                                     int finger_count) {
  event_.reset(CreateXInput2Event(deviceid, XI_Motion, 0, gfx::Point()));

  Valuator valuators[] = {
    Valuator(DeviceDataManager::DT_CMT_SCROLL_X, x_offset),
    Valuator(DeviceDataManager::DT_CMT_SCROLL_Y, y_offset),
    Valuator(DeviceDataManager::DT_CMT_ORDINAL_X, x_offset_ordinal),
    Valuator(DeviceDataManager::DT_CMT_ORDINAL_Y, y_offset_ordinal),
    Valuator(DeviceDataManager::DT_CMT_FINGER_COUNT, finger_count)
  };
  SetUpValuators(
      std::vector<Valuator>(valuators, valuators + arraysize(valuators)));
}

void ScopedXI2Event::InitFlingScrollEvent(int deviceid,
                                          int x_velocity,
                                          int y_velocity,
                                          int x_velocity_ordinal,
                                          int y_velocity_ordinal,
                                          bool is_cancel) {
  event_.reset(CreateXInput2Event(deviceid, XI_Motion, deviceid, gfx::Point()));

  Valuator valuators[] = {
    Valuator(DeviceDataManager::DT_CMT_FLING_STATE, is_cancel ? 1 : 0),
    Valuator(DeviceDataManager::DT_CMT_FLING_Y, y_velocity),
    Valuator(DeviceDataManager::DT_CMT_ORDINAL_Y, y_velocity_ordinal),
    Valuator(DeviceDataManager::DT_CMT_FLING_X, x_velocity),
    Valuator(DeviceDataManager::DT_CMT_ORDINAL_X, x_velocity_ordinal)
  };

  SetUpValuators(
      std::vector<Valuator>(valuators, valuators + arraysize(valuators)));
}

void ScopedXI2Event::InitTouchEvent(int deviceid,
                                    int evtype,
                                    int tracking_id,
                                    const gfx::Point& location,
                                    const std::vector<Valuator>& valuators) {
  event_.reset(CreateXInput2Event(deviceid, evtype, tracking_id, location));

  // If a timestamp was specified, setup the event.
  for (size_t i = 0; i < valuators.size(); ++i) {
    if (valuators[i].data_type == DeviceDataManager::DT_TOUCH_RAW_TIMESTAMP) {
      SetUpValuators(valuators);
      return;
    }
  }

  // No timestamp was specified. Use |ui::EventTimeForNow()|.
  std::vector<Valuator> valuators_with_time = valuators;
  valuators_with_time.push_back(
      Valuator(DeviceDataManager::DT_TOUCH_RAW_TIMESTAMP,
               (ui::EventTimeForNow()).InMicroseconds()));
  SetUpValuators(valuators_with_time);
}

void ScopedXI2Event::SetUpValuators(const std::vector<Valuator>& valuators) {
  CHECK(event_.get());
  CHECK_EQ(GenericEvent, event_->type);
  XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(event_->xcookie.data);
  InitValuatorsForXIDeviceEvent(xiev);
  ui::DeviceDataManager* manager = ui::DeviceDataManager::GetInstance();
  for (size_t i = 0; i < valuators.size(); ++i) {
    manager->SetValuatorDataForTest(xiev, valuators[i].data_type,
                                    valuators[i].value);
  }
}

void SetUpTouchPadForTest(unsigned int deviceid) {
  std::vector<unsigned int> device_list;
  device_list.push_back(deviceid);

  TouchFactory::GetInstance()->SetPointerDeviceForTest(device_list);
  ui::DeviceDataManager* manager = ui::DeviceDataManager::GetInstance();
  manager->SetDeviceListForTest(std::vector<unsigned int>(), device_list);
}

void SetUpTouchDevicesForTest(const std::vector<unsigned int>& devices) {
  TouchFactory::GetInstance()->SetTouchDeviceForTest(devices);
  ui::DeviceDataManager* manager = ui::DeviceDataManager::GetInstance();
  manager->SetDeviceListForTest(devices, std::vector<unsigned int>());
}

}  // namespace ui


text:
"""Simple memory-based accessor for tests and development."""
from __future__ import absolute_import
from __future__ import print_function

import collections
import uuid
import logging

import sortedcontainers

from biggraphite import accessor as bg_accessor
from biggraphite import glob_utils as bg_glob
from biggraphite.drivers import _downsampling
from biggraphite.drivers import _delayed_writer

log = logging.getLogger(__name__)

OPTIONS = {}

class Error(bg_accessor.Error):
    """Base class for all exceptions from this module."""

class InvalidArgumentError(Error, bg_accessor.InvalidArgumentError):
    """Callee did not follow requirements on the arguments."""

class _MemoryAccessor(bg_accessor.Accessor):
    """A memory acessor that doubles as a memory MetadataCache."""

    Row = collections.namedtuple(
        'Row', ['time_start_ms', 'offset', 'shard', 'value', 'count'])

    Row0 = collections.namedtuple(
        'Row', ['time_start_ms', 'offset', 'value'])

    _UUID_NAMESPACE = uuid.UUID('{00000000-1111-2222-3333-444444444444}')

    def __init__(self):
        """Create a new MemoryAccessor."""
        super(_MemoryAccessor, self).__init__("memory")
        self._metric_to_points = collections.defaultdict(
            sortedcontainers.SortedDict)
        self._name_to_metric = {}
        self._directory_names = sortedcontainers.SortedSet()
        self.__downsampler = _downsampling.Downsampler()
        self.__delayed_writer = _delayed_writer.DelayedWriter(self)

    @staticmethod
    def _components_from_name(metric_name):
        res = metric_name.split(".")
        return filter(None, res)

    @property
    def _metric_names(self):
        return self._name_to_metric.keys()

    def connect(self, *args, **kwargs):
        """See the real Accessor for a description."""
        super(_MemoryAccessor, self).connect(*args, **kwargs)
        self.is_connected = True

    def shutdown(self, *args, **kwargs):
        """See the real Accessor for a description."""
        super(_MemoryAccessor, self).shutdown(*args, **kwargs)
        self.is_connected = False

    def background(self):
        """Perform periodic background operations."""
        if self.__downsampler:
            self.__downsampler.purge()
        if self.__delayed_writer:
            self.__delayed_writer.write_some()

    def flush(self):
        """Flush any internal buffers."""
        if self.__delayed_writer:
            self.__delayed_writer.flush()

    def insert_points_async(self, metric, datapoints, on_done=None):
        """See the real Accessor for a description."""
        super(_MemoryAccessor, self).insert_points_async(
            metric, datapoints, on_done)
        if metric.name not in self._name_to_metric:
            self.create_metric(metric)

        datapoints = self.__downsampler.feed(metric, datapoints)
        if self.__delayed_writer:
            datapoints = self.__delayed_writer.feed(metric, datapoints)
        return self.insert_downsampled_points_async(metric, datapoints, on_done)

    def insert_downsampled_points_async(self, metric, datapoints, on_done=None):
        """See the real Accessor for a description."""
        super(_MemoryAccessor, self).insert_downsampled_points_async(
            metric, datapoints, on_done)
        if metric.name not in self._name_to_metric:
            self.create_metric(metric)

        for datapoint in datapoints:
            timestamp, value, count, stage = datapoint
            points = self._metric_to_points[(metric.name, stage)]
            points[timestamp] = (value, count)
        if on_done:
            on_done(None)

    def drop_all_metrics(self, *args, **kwargs):
        """See the real Accessor for a description."""
        super(_MemoryAccessor, self).drop_all_metrics(*args, **kwargs)
        self._metric_to_points.clear()
        self._name_to_metric.clear()
        self._directory_names.clear()

    def make_metric(self, name, metadata):
        """See bg_accessor.Accessor."""
        # Cleanup name (avoid double dots)
        name = ".".join(self._components_from_name(name))
        uid = uuid.uuid5(self._UUID_NAMESPACE, name)
        return bg_accessor.Metric(name, uid, metadata)

    def create_metric(self, metric):
        """See the real Accessor for a description."""
        super(_MemoryAccessor, self).create_metric(metric)
        self._name_to_metric[metric.name] = metric
        components = self._components_from_name(metric.name)
        path = []
        for part in components[:-1]:
            path.append(part)
            self._directory_names.add(".".join(path))

    def update_metric(self, name, updated_metadata):
        """See bg_accessor.Accessor."""
        super(_MemoryAccessor, self).update_metric(name, updated_metadata)
        # Cleanup name (avoid double dots)
        name = ".".join(self._components_from_name(name))
        metric = self._name_to_metric[name]
        if not metric:
            raise InvalidArgumentError(
                "Unknown metric '%s'" % name)
        metric.metadata = updated_metadata
        self._name_to_metric[name] = metric

    @staticmethod
    def __glob_names(names, glob):
        results = bg_glob.glob(names, glob)
        results.sort()
        return results

    def glob_metric_names(self, glob):
        """See the real Accessor for a description."""
        super(_MemoryAccessor, self).glob_metric_names(glob)
        return iter(self.__glob_names(self._metric_names, glob))

    def glob_directory_names(self, glob):
        """See the real Accessor for a description."""
        super(_MemoryAccessor, self).glob_directory_names(glob)
        return iter(self.__glob_names(self._directory_names, glob))

    def has_metric(self, metric_name):
        """See bg_accessor.Accessor."""
        super(_MemoryAccessor, self).has_metric(metric_name)
        return self.get_metric(metric_name) is not None

    def get_metric(self, metric_name, touch=False):
        """See the real Accessor for a description."""
        super(_MemoryAccessor, self).get_metric(metric_name, touch=touch)
        metric_name = ".".join(self._components_from_name(metric_name))
        return self._name_to_metric.get(metric_name)

    def fetch_points(self, metric, time_start, time_end, stage, aggregated=True):
        """See the real Accessor for a description."""
        super(_MemoryAccessor, self).fetch_points(
            metric, time_start, time_end, stage)
        points = self._metric_to_points[(metric.name, stage)]
        rows = []
        for ts in points.irange(time_start, time_end):
            # A row is time_base_ms, time_offset_ms, value, count
            if stage.aggregated():
                row = self.Row(
                    ts * 1000.0, 0, 0,
                    float(points[ts][0]), points[ts][1])
            else:
                row = self.Row0(ts * 1000.0, 0, float(points[ts][0]))
            rows.append(row)

        query_results = [(True, rows)]
        time_start_ms = int(time_start) * 1000
        time_end_ms = int(time_end) * 1000
        return bg_accessor.PointGrouper(
            metric, time_start_ms, time_end_ms, stage, query_results, aggregated=aggregated)

    def touch_metric(self, metric_name):
        """See the real Accessor for a description."""
        super(_MemoryAccessor, self).touch_metric(metric_name)

        # TODO Implements the function
        log.warn("%s is not implemented" % self.touch_metric.__name__)
        pass

    def repair(self, *args, **kwargs):
        """See the real Accessor for a description."""
        super(_MemoryAccessor, self).repair(*args, **kwargs)
        callback_on_progress = kwargs.pop('callback_on_progress')

        def _callback(m, i, t):
            callback_on_progress(i, t)
            # TODO Implements the function
            log.warn("%s is not implemented" % self.repair.__name__)

        self.map(_callback, *args, **kwargs)

    def clean(self, *args, **kwargs):
        """See bg_accessor.Accessor."""
        super(_MemoryAccessor, self).clean(*args, **kwargs)
        callback_on_progress = kwargs.pop('callback_on_progress')
        kwargs.pop('max_age', None)

        def _callback(m, i, t):
            callback_on_progress(i, t)
            # TODO Implements the function
            log.warn("%s is not implemented" % self.clean.__name__)

        self.map(_callback, *args, **kwargs)

    def map(self, callback, start_key=None, end_key=None, shard=1, nshards=0):
        """See bg_accessor.Accessor."""
        super(_MemoryAccessor, self).map(callback, start_key, end_key, shard, nshards)

        metrics = self._name_to_metric
        total = len(metrics)
        for i, metric in enumerate(metrics.values()):
            callback(metric, i, total)

def build(*args, **kwargs):
    """Return a bg_accessor.Accessor using memory."""
    return _MemoryAccessor(*args, **kwargs)


text:
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.PropertyEditors;

namespace Umbraco.Web.PropertyEditors.ParameterEditors
{
    /// <summary>
    /// Represents a multiple media picker macro parameter editor.
    /// </summary>
    [DataEditor(
        Constants.PropertyEditors.Aliases.MultipleMediaPicker,
        EditorType.MacroParameter,
        "Multiple Media Picker",
        "mediapicker",
        ValueType = ValueTypes.Text)]
    public class MultipleMediaPickerParameterEditor : DataEditor
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MultipleMediaPickerParameterEditor"/> class.
        /// </summary>
        public MultipleMediaPickerParameterEditor(ILogger logger)
            : base(logger)
        {
            DefaultConfiguration.Add("multiPicker", "1");
        }
    }
}


text:
<?php

class Controller {

    public function model ($model) {
        require_once '../app/models/' .$model . '.php';
        return new $model();
    }

    public function view ($view, $data = []) {
        require_once '../app/views/' . $view .'.php';
    }

}


text:
<?php

class Google_Service_CloudTalentSolution_CompanyDerivedInfo extends Google_Model
{
  protected $headquartersLocationType = 'Google_Service_CloudTalentSolution_Location';
  protected $headquartersLocationDataType = '';

  /**
   * @param Google_Service_CloudTalentSolution_Location
   */
  public function setHeadquartersLocation(Google_Service_CloudTalentSolution_Location $headquartersLocation)
  {
    $this->headquartersLocation = $headquartersLocation;
  }
  /**
   * @return Google_Service_CloudTalentSolution_Location
   */
  public function getHeadquartersLocation()
  {
    return $this->headquartersLocation;
  }
}


text:
package opennlp.morfologik.tagdict;

import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;

import morfologik.stemming.Dictionary;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import opennlp.morfologik.builder.POSDictionayBuilderTest;
import opennlp.tools.postag.TagDictionary;

public class MorfologikTagDictionaryTest {

  @Test
  public void testNoLemma() throws Exception {
    MorfologikTagDictionary dict = createDictionary(false);

    List<String> tags = Arrays.asList(dict.getTags("carro"));
    Assertions.assertEquals(1, tags.size());
    Assertions.assertTrue(tags.contains("NOUN"));
  }

  @Test
  public void testPOSDictionaryInsensitive() throws Exception {
    TagDictionary dict = createDictionary(false);

    List<String> tags = Arrays.asList(dict.getTags("casa"));
    Assertions.assertEquals(2, tags.size());
    Assertions.assertTrue(tags.contains("NOUN"));
    Assertions.assertTrue(tags.contains("V"));

    // this is the behavior of case insensitive dictionary
    // if we search it using case insensitive, Casa as a proper noun
    // should be lower case in the dictionary
    tags = Arrays.asList(dict.getTags("Casa"));
    Assertions.assertEquals(2, tags.size());
    Assertions.assertTrue(tags.contains("NOUN"));
    Assertions.assertTrue(tags.contains("V"));
  }

  @Test
  public void testPOSDictionarySensitive() throws Exception {
    TagDictionary dict = createDictionary(true);

    List<String> tags = Arrays.asList(dict.getTags("casa"));
    Assertions.assertEquals(2, tags.size());
    Assertions.assertTrue(tags.contains("NOUN"));
    Assertions.assertTrue(tags.contains("V"));

    // this is the behavior of case insensitive dictionary
    // if we search it using case insensitive, Casa as a proper noun
    // should be lower case in the dictionary
    tags = Arrays.asList(dict.getTags("Casa"));
    Assertions.assertEquals(1, tags.size());
    Assertions.assertTrue(tags.contains("PROP"));

  }

  private MorfologikTagDictionary createDictionary(boolean caseSensitive)
      throws Exception {
    return this.createDictionary(caseSensitive, null);
  }

  private MorfologikTagDictionary createDictionary(boolean caseSensitive,
      List<String> constant) throws Exception {
    Path output = POSDictionayBuilderTest.createMorfologikDictionary();
    output.toFile().deleteOnExit();
    Dictionary dic = Dictionary.read(output);
    return new MorfologikTagDictionary(dic, caseSensitive);
  }

}


text:
from actorbot.bots import Conversation
from actorbot.api import messaging

class EchoConversation(Conversation):
    """
        Simple echo bot
    """
    async def message_handler(self, message):
        """ """
        out_msg = messaging.SendMessage(self._get_id(),
                                        peer=self._peer,
                                        message=message)
        await self.send(out_msg)

    async def response_handler(self, message):
        """ """
        await super().response_handler(message)


text:
package ca.barelabs.bareservice.internal;

import ca.barelabs.bareservice.internal.ParameterFactory.Parameter;

public class BooleanParameter implements Parameter {

    @Override
    public Object toObject(String value) {
        if(value != null && value.length() == 1 && value.equals("1"))
            return true;

        return Boolean.valueOf(value);
    }
}


text:
"""Time-series forecasting with encoding-decoding architecture."""

from models import architectures
from models import base

import tensorflow as tf

class ForecastModel(base.ForecastModel):
  """Baseline forecasting model based on LSTM seq2seq."""

  def __init__(self, loss_object, hparams):
    super().__init__(hparams)

    self.loss_object = loss_object
    self.optimizer = tf.keras.optimizers.Adam(
        learning_rate=hparams["learning_rate"])

    # Model layers
    self.encoder_architecture = architectures.LSTMEncoder(
        hparams, return_state=True)
    self.forecast_architecture = architectures.LSTMDecoder(hparams)

  @tf.function
  def train_step(self, input_sequence, input_static, target):

    with tf.GradientTape() as tape:
      encoded_representation, encoder_states = self.encoder_architecture.forward(
          input_sequence, input_static)
      predictions = self.forecast_architecture.forward(
          encoded_representation, input_static, self.future_features_train,
          encoder_states)
      loss = self.loss_object(target, predictions)
    all_trainable_weights = (
        self.encoder_architecture.trainable_weights +
        self.forecast_architecture.trainable_weights)
    gradients = tape.gradient(loss, all_trainable_weights)
    self.optimizer.apply_gradients(zip(gradients, all_trainable_weights))
    return loss

  @tf.function
  def test_step(self, input_sequence, input_static):

    encoded_representation, encoder_states = self.encoder_architecture.forward(
        input_sequence, input_static)
    predictions = self.forecast_architecture.forward(encoded_representation,
                                                     input_static,
                                                     self.future_features_eval,
                                                     encoder_states)
    return predictions


text:
package net.techreadiness.service.common;

public interface SelectableItemProvider<T> extends DataGridItemProvider<T> {

	T getObjectForKey(String rowKey);
}


text:
Пакет для Laravel 5, позволяющий связать Ваше Laravel приложение с CMS DLE, на основе laravel auth driver. Ваше laravel приложение будет использовать общую авторизацию с CMS DLE.

## Install

Via Composer

``` bash
$ composer require maxic/laravel-dle-auth
```

## Usage

``` php
Добавьте сервис-провайдер пакет в Ваш config/app.php
'Maxic\DleAuth\DleAuthServiceProvider',
В config/auth.php измение поле 'driver' на
'driver' => 'dleauth',
```

``` php
Добавьте в App/Http/Kernel в $middleware
'Maxic\DleAuth\Middleware\Authenticate'
```


text:
local cassandra = require("cassandra")
--local utils = require "kong.tools.utils"

local fmt = string.format
local table_concat = table.concat

local _M = {}
_M.__index = _M

function _M.new(connector)
  if type(connector) ~= "table" then
    error("connector must be a table", 2)
  end

  return setmetatable({
    connector = connector,
  }, _M)
end

-- Iterator to update plugin configurations.
-- It works indepedent of the underlying datastore.
-- @param dao the dao to use
-- @param plugin_name the name of the plugin whos configurations
-- to iterate over
-- @return `ok+config+update` where `ok` is a boolean, `config` is the plugin configuration
-- table (or the error if not ok), and `update` is an update function to call with
-- the updated configuration table
-- @usage
--    up = function(_, _, dao)
--      for ok, config, update in plugin_config_iterator(dao, "jwt") do
--        if not ok then
--          return config
--        end
--        if config.run_on_preflight == nil then
--          config.run_on_preflight = true
--          local _, err = update(config)
--          if err then
--            return err
--          end
--        end
--      end
--    end
--[==[
function _M.plugin_config_iterator(dao, plugin_name)
  local db = dao.db.new_db

  -- iterates over rows
  local run_rows = function(t)
    for _, row in ipairs(t) do
      if type(row.config) == "string" then
        -- de-serialize in case of Cassandra
        local json, err = json_decode(row.config)
        if not json then
          return nil, ("json decoding error '%s' while decoding '%s'"):format(
                      tostring(err), tostring(row.config))
        end
        row.config = json
      end
      coroutine.yield(row.config, function(updated_config)
        if type(updated_config) ~= "table" then
          return nil, "expected table, got " .. type(updated_config)
        end
        row.created_at = nil
        row.config = updated_config
        return db.plugins:update({id = row.id}, row)
      end)
    end
    return true
  end

  local coro
  if db.strategy == "cassandra" then
    coro = coroutine.create(function()
      local coordinator = dao.db:get_coordinator()
      for rows, err in coordinator:iterate([[
                SELECT * FROM plugins WHERE name = ']] .. plugin_name .. [[';
              ]]) do
        if err then
          return nil, nil, err
        end

        assert(run_rows(rows))
      end
    end)

  elseif db.strategy == "postgres" then
    coro = coroutine.create(function()
      local rows, err = dao.db:query([[
        SELECT * FROM plugins WHERE name = ']] .. plugin_name .. [[';
      ]])
      if err then
        return nil, nil, err
      end

      assert(run_rows(rows))
    end)

  else
    coro = coroutine.create(function()
      return nil, nil, "unknown database type: " .. tostring(db.strategy)
    end)
  end

  return function()
    local coro_ok, config, update, err = coroutine.resume(coro)
    if not coro_ok then return false, config end  -- coroutine errored out
    if err         then return false, err    end  -- dao soft error
    if not config  then return nil           end  -- iterator done
    return true, config, update
  end
end
--]==]

local CASSANDRA_EXECUTE_OPTS = {
  consistency = cassandra.consistencies.all,
}

--[[
Insert records from the table defined by source_table_def into
destination_table_def. Both table_defs have the following structure
  { name    = "ssl_certificates",
    columns = {
      id         = "uuid",
      cert       = "text",
      key        = "text",
      created_at = "timestamp",
    },
    partition_keys = { "id" },
  }

columns_to_copy is a hash-like table.
* Each key must be a string D representing a column in the destination table.
* If the value is a string S, then the value of the S column in the source
  table will be assigned to the D column in destination.
* If the value is a function, then the result of executing it will be assigned
  to the D column.
Example:
  {
    partition  = function() return cassandra.text("certificates") end,
    id         = "id",
    cert       = "cert",
    key        = "key",
    created_at = "created_at",
  }

The function takes the "source row" as parameter, so it could be used to do things
like merging two fields together into one, or putting a string in uppercase.

Note: In Cassandra, INSERT does "insert if not exists or update using pks if exists"
      So this function is re-entrant
--]]
function _M:copy_cassandra_records(source_table_def,
                                   destination_table_def,
                                   columns_to_copy)
  local coordinator, err = self.connector:connect_migrations()
  if not coordinator then
    return nil, err
  end

  local cql = fmt("SELECT * FROM %s", source_table_def.name)
  for rows, err in coordinator:iterate(cql) do
    if err then
      return nil, err
    end

    for _, source_row in ipairs(rows) do
      local column_names = {}
      local values = {}
      local len = 0

      for dest_column_name, source_value in pairs(columns_to_copy) do
        if type(source_value) == "string" then
          source_value = source_row[source_value]

          local dest_type = destination_table_def.columns[dest_column_name]
          local type_converter = cassandra[dest_type]
          if not type_converter then
            return nil, fmt("Could not find the cassandra type converter for column %s (type %s)",
                            dest_column_name, source_table_def[dest_column_name])
          end

          if source_value == nil then
            source_value = cassandra.unset
          else
            source_value = type_converter(source_value)
          end

        elseif type(source_value) == "function" then
          source_value = source_value(source_row)

        else
          return nil, fmt("Expected a string or function, found %s (a %s)",
                          tostring(source_value), type(source_value))
        end

        if source_value ~= nil then
          len = len + 1
          values[len] = source_value
          column_names[len] = dest_column_name
        end
      end

      local question_marks = string.sub(string.rep("?, ", len), 1, -3)

      local insert_cql = fmt("INSERT INTO %s (%s) VALUES (%s)",
                             destination_table_def.name,
                             table_concat(column_names, ", "),
                             question_marks)

      local _, err = coordinator:execute(insert_cql, values, CASSANDRA_EXECUTE_OPTS)
      if err then
        return nil, err
      end
    end
  end

  return true
end

--[==[
do
  local function create_table_if_not_exists(coordinator, table_def)
    local partition_keys = table_def.partition_keys
    local primary_key_cql = ""
    if #partition_keys > 0 then
      primary_key_cql = fmt(", PRIMARY KEY (%s)", table_concat(partition_keys, ", "))
    end

    local column_declarations = {}
    local len = 0
    for name, typ in pairs(table_def.columns) do
      len = len + 1
      column_declarations[len] = fmt("%s %s", name, typ)
    end

    local column_declarations_cql = table_concat(column_declarations, ", ")

    local cql = fmt("CREATE TABLE IF NOT EXISTS %s(%s%s);",
                    table_def.name,
                    column_declarations_cql,
                    primary_key_cql)
    return coordinator:execute(cql, {}, CASSANDRA_EXECUTE_OPTS)
  end

  local function drop_table_if_exists(coordinator, table_name)
    local cql = fmt("DROP TABLE IF EXISTS %s;", table_name)

    return coordinator:execute(cql, {}, CASSANDRA_EXECUTE_OPTS)
  end

  local function get_columns_to_copy(table_structure)
    local res = {}

    for k, _ in pairs(table_structure.columns) do
      res[k] = k
    end

    return res
  end

  local function create_aux_table_def(table_def)
    local aux_table_def = utils.deep_copy(table_def)
    aux_table_def.name = "copy_of_" .. table_def.name
    aux_table_def.columns.partition = "text"

    table.insert(aux_table_def.partition_keys, 1, "partition")

    return aux_table_def
  end

  --[[
    Add a new partition key called "partition" to the table specified by table_def.

    table_def has the following structure:
    { name    = "ssl_certificates",
      columns = {
        id         = "uuid",
        cert       = "text",
        key        = "text",
        created_at = "timestamp",
      },
      partition_keys = { "id" },
    }
  --]]
  function _M.cassandra.add_partition(dao, table_def)
    local copy_records = _M.cassandra.copy_records
    local coordinator, err = dao.db:get_coordinator()
    if not coordinator then
      return nil, err
    end

    table_def = utils.deep_copy(table_def)

    local aux_table_def = create_aux_table_def(table_def)
    local columns_to_copy = get_columns_to_copy(table_def)
    columns_to_copy.partition = function()
      return cassandra.text(table_def.name)
    end

    local _, err = create_table_if_not_exists(coordinator, aux_table_def)
    if err then
      return nil, err
    end

    local _, err = copy_records(dao, table_def, aux_table_def, columns_to_copy)
    if err then
      return nil, err
    end

    local _, err = drop_table_if_exists(coordinator, table_def.name)
    if err then
      return nil, err
    end

    table_def.columns.partition = "text"
    table.insert(table_def.partition_keys, 1, "partition")

    local _, err = create_table_if_not_exists(coordinator, table_def)
    if err then
      return nil, err
    end

    local _, err = copy_records(dao, aux_table_def, table_def, columns_to_copy)
    if err then
      return nil, err
    end

    local _, err = drop_table_if_exists(coordinator, aux_table_def.name)
    if err then
      return nil, err
    end
  end
end
--]==]

return _M


text:
package com.cebedo.pmsys.domain;

import java.util.UUID;

import org.apache.commons.lang.StringUtils;

import com.cebedo.pmsys.base.IObjectDomain;
import com.cebedo.pmsys.constants.ConstantsRedis;
import com.cebedo.pmsys.constants.RegistryRedisKeys;
import com.cebedo.pmsys.enums.CategoryMaterial;
import com.cebedo.pmsys.enums.UnitLength;
import com.cebedo.pmsys.enums.UnitMass;
import com.cebedo.pmsys.enums.UnitVolume;
import com.cebedo.pmsys.model.Company;
import com.cebedo.pmsys.model.Project;
import com.cebedo.pmsys.utils.NumberFormatUtils;

public class Material implements IObjectDomain {

    private static final long serialVersionUID = 2300406369596684113L;
    /**
     * Keys: company:%s:project:%s:delivery:%s:material:%s
     */
    private Company company;
    private Project project;
    private Delivery delivery;
    private UUID uuid;

    /**
     * Detail fields.
     */
    private String name;
    private String remarks;

    /**
     * Specifications.
     */
    private double quantity;
    private double used;
    private double available;

    /**
     * Bean-backed form.
     *
     */
    private CategoryMaterial materialCategory;
    private String unitOfMeasure;

    /**
     * Cost per unit.
     */
    private double costPerUnitMaterial;
    private double costPerUnitLabor;
    private double costPerUnitEquipment;
    private double costPerUnitTotal;

    /**
     * Total cost per unit (costPerUnit * quantity).
     */
    private double totalCostPerUnitMaterial;
    private double totalCostPerUnitLabor;
    private double totalCostPerUnitEquipment;
    private double totalCost;

    public Material() {
	;
    }

    public Material(Delivery delivery2) {
	setCompany(delivery2.getCompany());
	setProject(delivery2.getProject());
	setDelivery(delivery2);
    }

    @Override
    public String getKey() {
	// company:%s:project:%s:delivery:%s:material:%s
	return String.format(RegistryRedisKeys.KEY_MATERIAL, this.company.getId(), this.project.getId(),
		this.delivery.getUuid(), this.uuid);
    }

    public String getUnitName() {
	String unitStr = getUnitOfMeasure();
	// If Length.
	try {
	    UnitLength unitOfMeasure = UnitLength.valueOf(unitStr);
	    return unitOfMeasure.getLabel();
	} catch (IllegalArgumentException e) {

	    // If Mass.
	    try {
		UnitMass unitOfMeasure = UnitMass.valueOf(unitStr);
		return unitOfMeasure.getLabel();
	    } catch (IllegalArgumentException e2) {

		// If Volume.
		try {
		    UnitVolume unitOfMeasure = UnitVolume.valueOf(unitStr);
		    return unitOfMeasure.getLabel();
		}
		// Others.
		catch (IllegalArgumentException e3) {
		    return unitStr;
		}
	    }
	}
    }

    public String getUnitSymbol() {
	String unitStr = getUnitOfMeasure();
	// If Length.
	try {
	    UnitLength unitOfMeasure = UnitLength.valueOf(unitStr);
	    return unitOfMeasure.getSymbol();
	} catch (IllegalArgumentException e) {

	    // If Mass.
	    try {
		UnitMass unitOfMeasure = UnitMass.valueOf(unitStr);
		return unitOfMeasure.getSymbol();
	    } catch (IllegalArgumentException e2) {
		// If Volume.
		try {
		    UnitVolume unitOfMeasure = UnitVolume.valueOf(unitStr);
		    return unitOfMeasure.getSymbol();
		}
		// Others.
		catch (IllegalArgumentException e3) {
		    return org.springframework.util.StringUtils.uncapitalize(unitStr);
		}
	    }
	}
    }

    public Company getCompany() {
	return company;
    }

    public void setCompany(Company company) {
	this.company = company;
    }

    public Project getProject() {
	return project;
    }

    public void setProject(Project project) {
	this.project = project;
    }

    public Delivery getDelivery() {
	return delivery;
    }

    public void setDelivery(Delivery delivery) {
	this.delivery = delivery;
    }

    public String getName() {
	return name;
    }

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

    public String getRemarks() {
	return remarks;
    }

    public void setRemarks(String remarks) {
	this.remarks = StringUtils.trim(remarks);
    }

    public double getQuantity() {
	return quantity;
    }

    public void setQuantity(double quantity) {
	this.quantity = quantity;
    }

    public String getCostPerUnitMaterialAsString() {
	return NumberFormatUtils.getCurrencyFormatter().format(costPerUnitMaterial);
    }

    public double getCostPerUnitMaterial() {
	return costPerUnitMaterial;
    }

    public void setCostPerUnitMaterial(double costPerUnitMaterial) {
	this.costPerUnitMaterial = costPerUnitMaterial;
    }

    @Deprecated
    public double getCostPerUnitLabor() {
	return costPerUnitLabor;
    }

    public void setCostPerUnitLabor(double costPerUnitLabor) {
	this.costPerUnitLabor = costPerUnitLabor;
    }

    @Deprecated
    public double getCostPerUnitEquipment() {
	return costPerUnitEquipment;
    }

    public void setCostPerUnitEquipment(double costPerUnitEquipment) {
	this.costPerUnitEquipment = costPerUnitEquipment;
    }

    @Deprecated
    public double getCostPerUnitTotal() {
	return costPerUnitTotal;
    }

    public void setCostPerUnitTotal(double costPerUnitTotal) {
	this.costPerUnitTotal = costPerUnitTotal;
    }

    public String getTotalCostPerUnitMaterialAsString() {
	return NumberFormatUtils.getCurrencyFormatter().format(totalCostPerUnitMaterial);
    }

    public double getTotalCostPerUnitMaterial() {
	return totalCostPerUnitMaterial;
    }

    public void setTotalCostPerUnitMaterial(double totalCostPerUnitMaterial) {
	this.totalCostPerUnitMaterial = totalCostPerUnitMaterial;
    }

    public double getTotalCostPerUnitLabor() {
	return totalCostPerUnitLabor;
    }

    public void setTotalCostPerUnitLabor(double totalCostPerUnitLabor) {
	this.totalCostPerUnitLabor = totalCostPerUnitLabor;
    }

    public double getTotalCostPerUnitEquipment() {
	return totalCostPerUnitEquipment;
    }

    public void setTotalCostPerUnitEquipment(double totalCostPerUnitEquipment) {
	this.totalCostPerUnitEquipment = totalCostPerUnitEquipment;
    }

    @Deprecated
    public double getTotalCost() {
	return totalCost;
    }

    public void setTotalCost(double totalCost) {
	this.totalCost = totalCost;
    }

    public UUID getUuid() {
	return uuid;
    }

    public void setUuid(UUID uuid) {
	this.uuid = uuid;
    }

    public double getUsed() {
	return used;
    }

    public void setUsed(double used) {
	this.used = used;
    }

    public double getAvailable() {
	return available;
    }

    public String getAvailableCSS() {
	int avail = getAvailableAsInt();

	if (avail >= 75 && avail <= 100) {
	    return "success";
	}

	else if (avail >= 50 && avail < 75) {
	    return "info";
	}

	else if (avail >= 25 && avail < 50) {
	    return "warning";
	}

	return "danger";
    }

    private int getAvailableAsInt() {
	return (int) ((available / quantity) * 100);
    }

    public String getAvailableAsPercentageForDisplay() {
	int percentDisplay = getAvailableAsInt();
	return percentDisplay + "%";
    }

    public String getAvailableAsPercentage() {
	int percentDisplay = getAvailableAsInt();
	if (percentDisplay <= 0) {
	    return "100%";
	}
	return percentDisplay + "%";
    }

    public void setAvailable(double available) {
	this.available = available;
    }

    public static String constructPattern(Delivery delivery2) {
	Company company = delivery2.getCompany();
	Project project = delivery2.getProject();
	return String.format(RegistryRedisKeys.KEY_MATERIAL, company.getId(), project.getId(),
		delivery2.getUuid(), "*");
    }

    public static String constructPattern(Project project) {
	Company company = project.getCompany();
	return String.format(RegistryRedisKeys.KEY_MATERIAL, company.getId(), project.getId(), "*", "*");
    }

    @Override
    public boolean equals(Object obj) {
	return obj instanceof Material ? ((Material) obj).getKey().equals(getKey()) : false;
    }

    @Override
    public int hashCode() {
	return getKey().hashCode();
    }

    public CategoryMaterial getMaterialCategory() {
	return materialCategory;
    }

    public void setMaterialCategory(CategoryMaterial materialCategory) {
	this.materialCategory = materialCategory;
    }

    public String getUnitOfMeasure() {
	return unitOfMeasure;
    }

    public void setUnitOfMeasure(String unitOfMeasure) {
	this.unitOfMeasure = unitOfMeasure;
    }

    @Override
    public String getObjectName() {
	return ConstantsRedis.OBJECT_MATERIAL;
    }

    public Material clone() {
	try {
	    return (Material) super.clone();
	} catch (Exception e) {
	    return null;
	}
    }

}


text:
'use strict'

const config = require('./config.json')
const sinon = require('sinon')
const targets = require('../src/targets')
const test = require('ava')
const util = require('./_util')

function createMultiTargetOptions (extraOpts) {
  return {
    name: 'targetTest',
    dir: util.fixtureSubdir('basic'),
    electronVersion: config.version,
    ...extraOpts
  }
}

function testMultiTarget (extraOpts, expectedPackageCount, packageExistenceMessage) {
  return t => {
    const opts = createMultiTargetOptions(extraOpts)
    const platforms = targets.validateListFromOptions(opts, 'platform')
    const archs = targets.validateListFromOptions(opts, 'arch')
    const combinations = targets.createPlatformArchPairs(opts, platforms, archs)

    t.is(combinations.length, expectedPackageCount, packageExistenceMessage)
  }
}

function testCombinations (testcaseDescription, arch, platform) {
  testMultiTarget(testcaseDescription, { arch: arch, platform: platform }, 4,
                  'Packages should be generated for all combinations of specified archs and platforms')
}

test('allOfficialArchsForPlatformAndVersion is undefined for unknown platforms', t => {
  t.is(targets.allOfficialArchsForPlatformAndVersion('unknown', '1.0.0'), undefined)
})

test('allOfficialArchsForPlatformAndVersion returns the correct arches for a known platform', t => {
  t.deepEqual(targets.allOfficialArchsForPlatformAndVersion('darwin', '1.0.0'), ['x64'])
})

test('allOfficialArchsForPlatformAndVersion returns linux/arm64 when the correct version is specified', t => {
  t.true(targets.allOfficialArchsForPlatformAndVersion('linux', '1.8.0').includes('arm64'),
         'should be found when version is >= 1.8.0')
  t.false(targets.allOfficialArchsForPlatformAndVersion('linux', '1.7.0').includes('arm64'),
          'should not be found when version is < 1.8.0')
})

test('allOfficialArchsForPlatformAndVersion returns linux/mips64el when the correct version is specified', t => {
  t.true(targets.allOfficialArchsForPlatformAndVersion('linux', '1.8.2').includes('mips64el'),
         'should be found when version is >= 1.8.2-beta.5')
  t.false(targets.allOfficialArchsForPlatformAndVersion('linux', '1.8.0').includes('mips64el'),
          'should not be found when version is < 1.8.2-beta.5')
})

test('allOfficialArchsForPlatformAndVersion returns win32/arm64 when the correct version is specified', t => {
  t.true(targets.allOfficialArchsForPlatformAndVersion('win32', '6.0.8').includes('arm64'),
         'should be found when version is >= 6.0.8')
  t.false(targets.allOfficialArchsForPlatformAndVersion('win32', '5.0.0').includes('arm64'),
          'should not be found when version is < 6.0.8')
})

test('validateListFromOptions does not take non-Array/String values', t => {
  targets.supported.digits = new Set(['64', '65'])
  t.false(targets.validateListFromOptions({ digits: 64 }, 'digits') instanceof Array,
          'should not be an Array')
  delete targets.supported.digits
})

test('validateListFromOptions works for armv7l host and target arch', t => {
  sinon.stub(process, 'arch').value('arm')
  sinon.stub(process, 'config').value({ variables: { arm_version: '7' } })

  t.deepEqual(targets.validateListFromOptions({}, 'arch'), ['armv7l'])

  sinon.restore()
})

test('build for all available official targets',
     testMultiTarget({ all: true, electronVersion: '1.8.2' }, util.allPlatformArchCombosCount - 3,
                     'Packages should be generated for all possible platforms (except win32/arm64)'))
test('build for all available official targets for a version without arm64 or mips64el support',
     testMultiTarget({ all: true }, util.allPlatformArchCombosCount - 5,
                     'Packages should be generated for all possible platforms (except linux/arm64, linux/mips64el, or win32/arm64)'))
test('platform=all (one arch)',
     testMultiTarget({ arch: 'ia32', platform: 'all' }, 2, 'Packages should be generated for both 32-bit platforms'))
test('arch=all (one platform)',
     testMultiTarget({ arch: 'all', platform: 'linux' }, 3, 'Packages should be generated for all expected architectures'))

testCombinations('multi-platform / multi-arch test, from arrays', ['ia32', 'x64'], ['linux', 'win32'])
testCombinations('multi-platform / multi-arch test, from strings', 'ia32,x64', 'linux,win32')
testCombinations('multi-platform / multi-arch test, from strings with spaces', 'ia32, x64', 'linux, win32')

test('fails with invalid arch', util.invalidOptionTest({
  arch: 'z80',
  platform: 'linux'
}))
test('fails with invalid platform', util.invalidOptionTest({
  arch: 'ia32',
  platform: 'dos'
}))

test('invalid official combination', testMultiTarget({ arch: 'ia32', platform: 'darwin' }, 0, 'Package should not be generated for invalid official combination'))

test('platform=linux and arch=arm64 with a supported official Electron version', testMultiTarget({ arch: 'arm64', platform: 'linux', electronVersion: '1.8.0' }, 1, 'Package should be generated for linux/arm64'))
test('platform=linux and arch=arm64 with a supported official Electron version (11.0.0-beta.22)', testMultiTarget({ arch: 'arm64', platform: 'linux', electronVersion: '11.0.0-beta.22' }, 1, 'Package should be generated for linux/arm64'))
test('platform=linux and arch=arm64 with an unsupported official Electron version', testMultiTarget({ arch: 'arm64', platform: 'linux' }, 0, 'Package should not be generated for linux/arm64'))

test('platform=linux and arch=mips64el with a supported official Electron version', testMultiTarget({ arch: 'mips64el', platform: 'linux', electronVersion: '1.8.2-beta.5' }, 1, 'Package should be generated for mips64el'))
test('platform=linux and arch=mips64el with an unsupported official Electron version', testMultiTarget({ arch: 'mips64el', platform: 'linux' }, 0, 'Package should not be generated for linux/mips64el'))
test('platform=linux and arch=mips64el with an unsupported official Electron version (2.0.0)', testMultiTarget({ arch: 'mips64el', platform: 'linux', electronVersion: '2.0.0' }, 0, 'Package should not be generated for linux/mips64el'))

test('platform=win32 and arch=arm64 with a supported official Electron version', testMultiTarget({ arch: 'arm64', platform: 'win32', electronVersion: '6.0.8' }, 1, 'Package should be generated for win32/arm64'))
test('platform=win32 and arch=arm64 with an unsupported official Electron version', testMultiTarget({ arch: 'arm64', platform: 'win32' }, 0, 'Package should not be generated for win32/arm64'))

test('platform=darwin and arch=arm64 with a supported official Electron version', testMultiTarget({ arch: 'arm64', platform: 'darwin', electronVersion: '11.0.0-beta.5' }, 1, 'Package should be generated for darwin/arm64'))
test('platform=darwin and arch=arm64 with an unsupported official Electron version', testMultiTarget({ arch: 'arm64', platform: 'darwin' }, 0, 'Package should not be generated for darwin/arm64'))

test('platform=mas and arch=arm64 with a supported official Electron version', testMultiTarget({ arch: 'arm64', platform: 'mas', electronVersion: '11.0.0-beta.5' }, 1, 'Package should be generated for mas/arm64'))
test('platform=mas and arch=arm64 with an unsupported official Electron version', testMultiTarget({ arch: 'arm64', platform: 'mas' }, 0, 'Package should not be generated for mas/arm64'))

test('unofficial arch', testMultiTarget({ arch: 'z80', platform: 'linux', download: { mirrorOptions: { mirror: 'mirror' } } }, 1,
                                        'Package should be generated for non-standard arch from non-official mirror'))
test('unofficial platform', testMultiTarget({ arch: 'ia32', platform: 'minix', download: { mirrorOptions: { mirror: 'mirror' } } }, 1,
                                            'Package should be generated for non-standard platform from non-official mirror'))


text:
zip -r ../LambdaBilling ./* -x bin/\* .env .gitignore LICENSE package.json README.md

aws lambda create-function \
--function-name LambdaBilling \
--runtime nodejs \
--role $LAMBDA_ROLE_ARN \
--handler index.handler \
--zip-file fileb://../LambdaBilling.zip \
--profile $AWS_PROFILE


text:
---
uid: SolidEdgeAssembly.WireRuns.Item(System.Object)
summary:
remarks:
syntax:
    parameters:
    - id: Index
      description: Variant (input) index.
---


text:
<?xml version="1.0" encoding="UTF-8"?>
<sbml xmlns="http://www.sbml.org/sbml/level1" level="1" version="2">
  <model name="case00143">
    <listOfCompartments>
      <compartment name="compartment" volume="5" units="volume"/>
    </listOfCompartments>
    <listOfSpecies>
      <species name="S1" compartment="compartment" initialAmount="1e-005" units="substance"/>
      <species name="S2" compartment="compartment" initialAmount="1.5e-005" units="substance"/>
      <species name="S3" compartment="compartment" initialAmount="1e-005" units="substance"/>
    </listOfSpecies>
    <listOfParameters>
      <parameter name="k1" value="150000"/>
      <parameter name="k2" value="50"/>
    </listOfParameters>
    <listOfRules>
      <compartmentVolumeRule formula="1" compartment="compartment"/>
    </listOfRules>
    <listOfReactions>
      <reaction name="reaction1" reversible="false">
        <listOfReactants>
          <speciesReference species="S1"/>
          <speciesReference species="S2"/>
        </listOfReactants>
        <listOfProducts>
          <speciesReference species="S3"/>
        </listOfProducts>
        <kineticLaw formula="compartment * k1 * S1 * S2"/>
      </reaction>
      <reaction name="reaction2" reversible="false">
        <listOfReactants>
          <speciesReference species="S3"/>
        </listOfReactants>
        <listOfProducts>
          <speciesReference species="S1"/>
          <speciesReference species="S2"/>
        </listOfProducts>
        <kineticLaw formula="compartment * k2 * S3"/>
      </reaction>
    </listOfReactions>
  </model>
</sbml>


text:
require 'httpclient'
require 'cgi'
require 'multi_json'

# not sure why we need to require the entire 'helpers'
# when all we want is sanitize_helper, but I think we do:
require 'action_view/helpers'
#require 'action_view/helpers/sanitize_helper'

require 'http_client_patch/include_client'

module BentoSearch
  #
  # https://developers.google.com/books/docs/v1/using
  # https://developers.google.com/books/docs/v1/reference/volumes#resource
  #
  # Configuration :api_key STRONGLY recommended, or google will severely
  # rate-limit you.
  #
  # == Custom Data
  # GBS API's "viewability" value is stored at item.custom_data[:viewability]
  # PARTIAL, ALL_PAGES, NO_PAGES or UNKNOWN.
  # https://developers.google.com/books/docs/v1/reference/volumes#resource
  #
  # #link_is_fulltext? is also set appropriately.
  #
  # You may want to use a custom decorator to display the viewability
  # status somehow (in display_format? In an other_link?). See wiki
  # for info on decorators.
  class GoogleBooksEngine
    include BentoSearch::SearchEngine
    include ActionView::Helpers::SanitizeHelper

    extend HTTPClientPatch::IncludeClient
    include_http_client # gives us a #http_client with persistent class-level

    class_attribute :base_url
    self.base_url = "https://www.googleapis.com/books/v1/"

    def search_implementation(arguments)
      query_url = args_to_search_url(arguments)

      results = Results.new

      begin
        response = http_client.get(query_url )
        json = MultiJson.load( response.body )
        # Can't rescue everything, or we catch VCR errors, making
        # things confusing.
      rescue TimeoutError, HTTPClient::TimeoutError,
            HTTPClient::ConfigurationError, HTTPClient::BadResponseError  => e
        results.error ||= {}
        results.error[:exception] = e
      end

      # Trap json parse error, but also check for bad http
      # status, or error reported in the json. In any of those cases
      # return results obj with error status.
      #
      if ( response.nil? || json.nil? ||
          (! HTTP::Status.successful? response.status) ||
          (json && json["error"]))

       results.error ||= {}
       results.error[:status] = response.status if response
       if json && json["error"] && json["error"]["errors"] && json["error"]["errors"].kind_of?(Array)
         results.error[:message] = json["error"]["errors"].first.values.join(", ")
       end
       results.error[:error_info] = json["error"] if json && json.respond_to?("[]")

       # escape early!
       return results
      end

      results.total_items = json["totalItems"]

      (json["items"] || []).each do |item_response|
        results <<  hash_to_item(item_response)
      end

      return results
    end

    # Look up a single item by #unique_id. Returns a single item, or
    # raises BentoSearch::NotFound, BentoSearch::TooManyFound, or other.
    def get(id)
      # Have to use different API endpoint, can't do a fielded search.
      url = base_url + "volumes/#{CGI.escape id}"

      if configuration.api_key
        url += "?key=#{configuration.api_key}"
      end

      response = http_client.get( url )

      if response.status == 404
        raise BentoSearch::NotFound.new("ID: #{id}")
      end

      # GBS has switched to returning a 503 for bad id's???
      # Prob a bug on Google's end, but we have to deal with it.
      if response.status == 503
        raise BentoSearch::NotFound.new("ID: #{id} (503 error from Google, tests show indicates not found ID however)")
      end

      json = MultiJson.load( response.body )

      if json["error"]
        raise Exception.new("Error in get(#{id}): #{json['error'].inspect}")
      end

      return hash_to_item(json)
    end

    # take a hash from Google json response, representing a single
    # item, return a ResultItem obj. Used internally.
    def hash_to_item(item_response)
      v_info = item_response["volumeInfo"] || {}

      item = ResultItem.new

      item.unique_id             = item_response["id"]

      item.title          = format_title(v_info)
      item.publisher      = v_info["publisher"]
      # previewLink gives you your search results highlighted, preferable
      # if it exists.
      item.link           = v_info["previewLink"] || v_info["canonicalVolumeLink"]
      item.abstract       = sanitize v_info["description"]
      item.year           = get_year v_info["publishedDate"]
      # sometimes we have yyyy-mm, but we need a date to make a ruby Date,
      # we'll just say the 1st.
      item.publication_date = case v_info["publishedDate"]
        when /(\d\d\d\d)-(\d\d)/ then Date.parse "#{$1}-#{$2}-01"
        when /(\d\d\d\d)-(\d\d)-(\d\d)/ then Date.parse v_info["published_date"]
        else nil
      end

      item.format         = if v_info["printType"] == "MAGAZINE"
                            :serial
                          else
                            "Book"
                          end

      item.language_code  = v_info["language"]

      (v_info["authors"] || []).each do |author_name|
        item.authors << Author.new(:display => author_name)
      end

      # Find ISBN's, prefer ISBN-13
      item.isbn           = (v_info["industryIdentifiers"] || []).find {|node| node["type"] == "ISBN_13"}.try {|node| node["identifier"]}
      unless item.isbn
        # Look for ISBN-10 okay
        item.isbn         = (v_info["industryIdentifiers"] || []).find {|node| node["type"] == "ISBN_10"}.try {|node| node["identifier"]}
      end

      # only VERY occasionally does a GBS hit have an OCLC number, but let's look
      # just in case.
      item.oclcnum        = (v_info["industryIdentifiers"] || []).
        find {|node| node["type"] == "OTHER" && node["identifier"].starts_with?("OCLC:") }.
        try do |node|
          node =~ /OCLC:(.*)/ ? $1 : nil
        end

      # save viewability status in custom_data. PARTIAL, ALL_PAGES, NO_PAGES or UNKNOWN.
      # https://developers.google.com/books/docs/v1/reference/volumes#resource
      item.custom_data[:viewability] = item_response["accessInfo"].try {|h| h["viewability"]}
      item.link_is_fulltext = (item.custom_data[:viewability] == "ALL_PAGES") if item.custom_data[:viewability]

      return item
    end

    ###########
    # BentoBox::SearchEngine API
    ###########

    def max_per_page
      100
    end

    def search_field_definitions
      { nil           => {:semantic => :general},
        "intitle"     => {:semantic => :title},
        "inauthor"    => {:semantic => :author},
        "inpublisher" => {:semantic => :publisher},
        "subject"     => {:semantic => :subject},
        "isbn"        => {:semantic => :isbn}
      }
    end

    def sort_definitions
      {
        "relevance" => {:implementation => nil}, # default
        "date_desc" => {:implementation => "newest"}
      }
    end

    def multi_field_search?
      true
    end

    protected

    #############
    # Our own implementation code
    ##############

    # takes a normalized #search arguments hash from SearchEngine
    # turns it into a URL for Google API. Factored out to make testing
    # possible.
    def args_to_search_url(arguments)
      query = if arguments[:query].kind_of? Hash
        #multi-field
        arguments[:query].collect {|field, query| fielded_query(query, field)}.join(" ")
      elsif arguments[:search_field]
        fielded_query(arguments[:query], arguments[:search_field])
      else
        arguments[:query]
      end

      query_url = base_url + "volumes?q=#{CGI.escape  query}"
      if configuration.api_key
        query_url += "&key=#{configuration.api_key}"
      end

      if arguments[:per_page]
        query_url += "&maxResults=#{arguments[:per_page]}"
      end
      if arguments[:start]
        query_url += "&startIndex=#{arguments[:start]}"
      end

      if arguments[:sort] &&
          (defn = sort_definitions[arguments[:sort]]) &&
          (value = defn[:implementation])
        query_url += "&orderBy=#{CGI.escape(value)}"
      end

      return query_url
    end

    # If they ask for a <one two> :intitle, we're
    # actually gonna do like google's own form does,
    # and change it to <intitle:one intitle:two>. Internal
    # phrases will be respected.
    def fielded_query(query, field)
      tokens = query.split(%r{\s|("[^"]+")}).delete_if {|a| a.blank?}
      return tokens.collect {|token| "#{field}:#{token}"}.join(" ")
    end

    def get_year(iso8601)
      return nil if iso8601.blank?

      if iso8601 =~ /^(\d{4})/
        return $1.to_i
      end
      return nil
    end

    def format_title(v_info)
      title = v_info["title"]
      if v_info["subtitle"]
        title = "#{title}: #{v_info["subtitle"]}"
      end
      return title
    end

  end
end


text:
<?php
/**
 * Created by PhpStorm.
 * User: fahim
 * Date: 7/30/17
 * Time: 9:30 PM
 */
include "patient_drawer.php";
session_start();
date_default_timezone_set('Asia/Dhaka');
$title="Patient Portal";
$doctorId = $_GET['docId'];
$fetchedDoctor = findDoctorByDoctorId($doctorId);
$doctorTimeTable = getDoctorAppointmentTable($doctorId);
$patientID = findPatientIdByUserId($_SESSION['user_id']);
?>

Appointment

        <form method="post" action="appointment.php" id="register_form">

<?php echo $fetchedDoctor['Name']; ?>

<?php echo $fetchedDoctor['Degree']; ?>

<?php echo $fetchedDoctor['Department']; ?>

            <input name="doctor_id" hidden value="<?php echo $doctorId; ?>"/>
            <input name="patient_id" hidden value="<?php echo $patientID; ?>"/>

                Registration Date
                <input class="mdui-textfield-input mdui-text-capitalize" type="text" name="register_date" value="<?php echo date("d-m-y"); ?>" />

                Appointment Date
                <select class="mdui-textfield-input" name="appointment_date" id="date_selection">
                    <option>--Select--</option>
                    <?php
                        foreach ($doctorTimeTable as $item) {
                            $start_date=strtotime($item['VisitingDay']);
                            echo date("d-m-yy", $start_date)."
";
                            echo "<option value=\"".date("d-m-y", $start_date)."\">". $item['VisitingDay'].", ".date("d-m-y", $start_date)."</option>";
                        }
                    ?>
                </select>

                Time Slot
                <select class="mdui-textfield-input" name="appointment_time" id="time_selection">

                </select>

            <button class="mdui-btn mdui-ripple mdui-color-green mdui-float-right login-register-button" style="margin: 10px;" type="submit" id="register_submit" name="submit">Register</button>
        </form>

<?php include("../includes/portal_components/footer.php");?>


text:
import Promise from 'promise-polyfill';

import { IFuncWrapper } from './func_wrapper';
import { jsonifyNotice } from './jsonify_notice';
import { INotice } from './notice';
import { Scope } from './scope';

import { espProcessor } from './processor/esp';
import { Processor } from './processor/processor';

import { angularMessageFilter } from './filter/angular_message';
import { makeDebounceFilter } from './filter/debounce';
import { Filter } from './filter/filter';
import { ignoreNoiseFilter } from './filter/ignore_noise';
import { uncaughtMessageFilter } from './filter/uncaught_message';

import { makeRequester, Requester } from './http_req';

import { IOptions } from './options';
import { QueriesStats } from './queries';
import { QueueMetric, QueuesStats } from './queues';
import { RouteMetric, RoutesBreakdowns, RoutesStats } from './routes';
import { NOTIFIER_NAME, NOTIFIER_VERSION, NOTIFIER_URL } from './version';
import { PerformanceFilter } from './filter/performance_filter';
import { RemoteSettings } from './remote_settings';

export class BaseNotifier {
  routes: Routes;
  queues: Queues;
  queries: QueriesStats;

  _opt: IOptions;
  _url: string;

  _processor: Processor;
  _requester: Requester;
  _filters: Filter[] = [];
  _performanceFilters: PerformanceFilter[] = [];
  _scope = new Scope();

  _onClose: (() => void)[] = [];

  constructor(opt: IOptions) {
    if (!opt.projectId || !opt.projectKey) {
      throw new Error('airbrake: projectId and projectKey are required');
    }

    this._opt = opt;
    this._opt.host = this._opt.host || 'https://api.airbrake.io';
    this._opt.remoteConfigHost =
      this._opt.remoteConfigHost || 'https://notifier-configs.airbrake.io';
    this._opt.apmHost = this._opt.apmHost || 'https://api.airbrake.io';
    this._opt.timeout = this._opt.timeout || 10000;
    this._opt.keysBlocklist = this._opt.keysBlocklist || [/password/, /secret/];
    this._url = `${this._opt.host}/api/v3/projects/${this._opt.projectId}/notices?key=${this._opt.projectKey}`;

    this._opt.errorNotifications = this._opt.errorNotifications !== false;
    this._opt.performanceStats = this._opt.performanceStats !== false;

    this._opt.queryStats = this._opt.queryStats !== false;
    this._opt.queueStats = this._opt.queueStats !== false;

    this._opt.remoteConfig = this._opt.remoteConfig !== false;

    this._processor = this._opt.processor || espProcessor;
    this._requester = makeRequester(this._opt);

    this.addFilter(ignoreNoiseFilter);
    this.addFilter(makeDebounceFilter());
    this.addFilter(uncaughtMessageFilter);
    this.addFilter(angularMessageFilter);

    this.addFilter((notice: INotice): INotice | null => {
      notice.context.notifier = {
        name: NOTIFIER_NAME,
        version: NOTIFIER_VERSION,
        url: NOTIFIER_URL,
      };
      if (this._opt.environment) {
        notice.context.environment = this._opt.environment;
      }
      return notice;
    });

    this.routes = new Routes(this);
    this.queues = new Queues(this);
    this.queries = new QueriesStats(this._opt);

    if (this._opt.remoteConfig) {
      const pollerId = new RemoteSettings(this._opt).poll();
      this._onClose.push(() => clearInterval(pollerId));
    }
  }

  close(): void {
    for (let fn of this._onClose) {
      fn();
    }
  }

  scope(): Scope {
    return this._scope;
  }

  setActiveScope(scope: Scope) {
    this._scope = scope;
  }

  addFilter(filter: Filter): void {
    this._filters.push(filter);
  }

  addPerformanceFilter(performanceFilter: PerformanceFilter) {
    this._performanceFilters.push(performanceFilter);
  }

  notify(err: any): Promise<INotice> {
    let notice: INotice = {
      errors: [],
      context: {
        severity: 'error',
        ...this.scope().context(),
        ...err.context,
      },
      params: err.params || {},
      environment: err.environment || {},
      session: err.session || {},
    };

    if (typeof err !== 'object' || err.error === undefined) {
      err = { error: err };
    }

    if (!this._opt.errorNotifications) {
      notice.error = new Error(
        `airbrake: not sending this error, errorNotifications is disabled err=${JSON.stringify(
          err.error
        )}`
      );
      return Promise.resolve(notice);
    }

    if (!err.error) {
      notice.error = new Error(
        `airbrake: got err=${JSON.stringify(err.error)}, wanted an Error`
      );
      return Promise.resolve(notice);
    }

    let error = this._processor(err.error);
    notice.errors.push(error);

    for (let filter of this._filters) {
      let r = filter(notice);
      if (r === null) {
        notice.error = new Error('airbrake: error is filtered');
        return Promise.resolve(notice);
      }
      notice = r;
    }

    if (!notice.context) {
      notice.context = {};
    }
    notice.context.language = 'JavaScript';
    return this._sendNotice(notice);
  }

  _sendNotice(notice: INotice): Promise<INotice> {
    let body = jsonifyNotice(notice, {
      keysBlocklist: this._opt.keysBlocklist,
    });
    if (this._opt.reporter) {
      if (typeof this._opt.reporter === 'function') {
        return this._opt.reporter(notice);
      } else {
        console.warn('airbrake: options.reporter must be a function');
      }
    }

    let req = {
      method: 'POST',
      url: this._url,
      body,
    };
    return this._requester(req)
      .then((resp) => {
        notice.id = resp.json.id;
        notice.url = resp.json.url;
        return notice;
      })
      .catch((err) => {
        notice.error = err;
        return notice;
      });
  }

  wrap(fn, props: string[] = []): IFuncWrapper {
    if (fn._airbrake) {
      return fn;
    }

    // tslint:disable-next-line:no-this-assignment
    let client = this;
    let airbrakeWrapper = function () {
      let fnArgs = Array.prototype.slice.call(arguments);
      let wrappedArgs = client._wrapArguments(fnArgs);
      try {
        return fn.apply(this, wrappedArgs);
      } catch (err) {
        client.notify({ error: err, params: { arguments: fnArgs } });
        client._ignoreNextWindowError();
        throw err;
      }
    } as IFuncWrapper;

    for (let prop in fn) {
      if (fn.hasOwnProperty(prop)) {
        airbrakeWrapper[prop] = fn[prop];
      }
    }
    for (let prop of props) {
      if (fn.hasOwnProperty(prop)) {
        airbrakeWrapper[prop] = fn[prop];
      }
    }

    airbrakeWrapper._airbrake = true;
    airbrakeWrapper.inner = fn;

    return airbrakeWrapper;
  }

  _wrapArguments(args: any[]): any[] {
    for (let i = 0; i < args.length; i++) {
      let arg = args[i];
      if (typeof arg === 'function') {
        args[i] = this.wrap(arg);
      }
    }
    return args;
  }

  _ignoreNextWindowError() {}

  call(fn, ..._args: any[]): any {
    let wrapper = this.wrap(fn);
    return wrapper.apply(this, Array.prototype.slice.call(arguments, 1));
  }
}

class Routes {
  _notifier: BaseNotifier;
  _routes: RoutesStats;
  _breakdowns: RoutesBreakdowns;
  _opt: IOptions;

  constructor(notifier: BaseNotifier) {
    this._notifier = notifier;
    this._routes = new RoutesStats(notifier._opt);
    this._breakdowns = new RoutesBreakdowns(notifier._opt);
    this._opt = notifier._opt;
  }

  start(
    method = '',
    route = '',
    statusCode = 0,
    contentType = ''
  ): RouteMetric {
    const metric = new RouteMetric(method, route, statusCode, contentType);

    if (!this._opt.performanceStats) {
      return metric;
    }

    const scope = this._notifier.scope().clone();
    scope.setContext({ httpMethod: method, route });
    scope.setRouteMetric(metric);
    this._notifier.setActiveScope(scope);

    return metric;
  }

  notify(req: RouteMetric): void {
    if (!this._opt.performanceStats) {
      return;
    }

    req.end();

    for (const performanceFilter of this._notifier._performanceFilters) {
      if (performanceFilter(req) === null) {
        return;
      }
    }
    this._routes.notify(req);
    this._breakdowns.notify(req);
  }
}

class Queues {
  _notifier: BaseNotifier;
  _queues: QueuesStats;
  _opt: IOptions;

  constructor(notifier: BaseNotifier) {
    this._notifier = notifier;
    this._queues = new QueuesStats(notifier._opt);
    this._opt = notifier._opt;
  }

  start(queue: string): QueueMetric {
    const metric = new QueueMetric(queue);

    if (!this._opt.performanceStats) {
      return metric;
    }

    const scope = this._notifier.scope().clone();
    scope.setContext({ queue });
    scope.setQueueMetric(metric);
    this._notifier.setActiveScope(scope);

    return metric;
  }

  notify(q: QueueMetric): void {
    if (!this._opt.performanceStats) {
      return;
    }

    q.end();
    this._queues.notify(q);
  }
}


text:
(function() {
    function ModalInstanceCtrl($uibModalInstance) {
        this.cancel = function() {
            $uibModalInstance.dismiss('dismiss')
        }
    }

    angular
        .module('angularModals')
        .controller('ModalInstanceCtrl', ['$uibModalInstance', ModalInstanceCtrl])
})()


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/city_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="City Name"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/country_code"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:text="Country code"
            android:textAppearance="?android:attr/textAppearanceMedium" />

    </LinearLayout>

    <TextView
        android:id="@+id/coords"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="GPS coordinates"
        android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>


text:
#include "FastLED.h"

#define NUM_LEDS 52
#define V_GAUGE_NUM_LEDS 14
#define H_GAUGE_NUM_LEDS 8

#ifndef BRIGHTNESS_MIN
#define BRIGHTNESS_MIN  60
#endif
#ifndef BRIGHTNESS_MAX
#define BRIGHTNESS_MAX  250
#endif
#ifndef BRIGHTNESS_INC
#define BRIGHTNESS_INC 7
#endif

#ifndef LED_PIN
#define LED_PIN 10
#endif

class Gauge;

/**
 * The Led Controller controls all the leds of the Beacon
 */
class LedController {
public:
  LedController();
  void begin();
  void update();
  void stop();
  /**
   * See enum declaration for details
   */
  byte getHorizontalLEDsStrategy();
  void setHorizontalLEDsStrategy(byte str);
  Gauge* getVGauge1();
  Gauge* getVGauge2();
  Gauge* getHGauge1();
  Gauge* getHGauge2();
  Gauge* getHGauge3();
private:
  Gauge* vGauge1;
  Gauge* vGauge2;
  Gauge* hGauge1;
  Gauge* hGauge2;
  Gauge* hGauge3;
  byte ledStrategy;
  CRGB leds[NUM_LEDS];
  byte bri;
  boolean dir;
  /**
   * Used internally to update the current gauge color
   */
  void updateGauge(byte offset, Gauge* gauge);
  /**
   * Used internally to determine the next gauge brightness
   */
  void nextBrightness();
};


text:
var googleapi = {
	config: geosharecfg.auth,
	authorize: function() {
		var deferred = $.Deferred();
		var options = googleapi.config;

		//Build the OAuth consent page URL
		var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
			client_id: options.client_id,
			redirect_uri: options.redirect_uri,
			response_type: 'code',
			scope: options.scope,
			access_type: 'offline'
		});

		//Open the OAuth consent page in the InAppBrowser
		var authWindow = window.open(authUrl, '_blank', 'location=no,toolbar=no');

		//The recommendation is to use the redirect_uri "urn:ietf:wg:oauth:2.0:oob"
		//which sets the authorization code in the browser's title. However, we can't
		//access the title of the InAppBrowser.
		//
		//Instead, we pass a bogus redirect_uri of "http://localhost", which means the
		//authorization code will get set in the url. We can access the url in the
		//loadstart and loadstop events. So if we bind the loadstart event, we can
		//find the authorization code and close the InAppBrowser after the user
		//has granted us access to their data.
		$(authWindow).on('loadstart', function(e) {
			var url = e.originalEvent.url;
			var code = /\?code=(.+)$/.exec(url);
			var error = /\?error=(.+)$/.exec(url);

			if (code || error) {
				//Always close the browser when match is found
				authWindow.close();
			}

			if (code) {
				//Exchange the authorization code for an access token
				$.post('https://accounts.google.com/o/oauth2/token', {
					code: code[1],
					client_id: options.client_id,
					client_secret: options.client_secret,
					redirect_uri: options.redirect_uri,
					grant_type: 'authorization_code'
				}).done(function(data) {
					googleapi.setToken(data);
					deferred.resolve(data);
				}).fail(function(response) {
					deferred.reject({
						type: 'exchange_code',
						error: response.responseJSON
					});
				});
			} else if (error) {
				//The user denied access to the app
				deferred.reject({
					type: 'user_denied_access',
					error: error[1]
				});
			}
		});

		return deferred.promise();
	},
	setToken: function(data) {
		console.log('New access token ' + JSON.stringify(data,null,2));

		localStorage.access_token = data.access_token;

		// The refresh_token only is sent once, after the user authorizes the application
		localStorage.refresh_token = data.refresh_token || localStorage.refresh_token;

		//Calculate exactly when the token will expire, then subtract
		//one minute to give ourselves a small buffer.
		var now = new Date().getTime();
		var expiresAt = now + parseInt(data.expires_in, 10) * 1000 - 60000;
		localStorage.expires_at = expiresAt;
	},
	getToken: function() {
		var options = googleapi.config;
		var deferred = $.Deferred();
		var now = new Date().getTime();

		if ( !localStorage.access_token ) {
			return googleapi.authorize();
		}

		if ( geoshare.isBrowser || now < localStorage.expires_at ) {
			console.log('Found a valid access token[' + localStorage.access_token + ']');

			//The token is still valid, so immediately return it from the cache
			deferred.resolve({
				access_token: localStorage.access_token
			});
		} else if ( localStorage.refresh_token ) {
			console.log('Found a expired access token, trying to refresh... refresh_token=' + localStorage.refresh_token);

			//The token is expired, but we can get a new one with a refresh token
			$.post('https://accounts.google.com/o/oauth2/token', {
				refresh_token: localStorage.refresh_token,
				client_id: options.client_id,
				client_secret: options.client_secret,
				grant_type: 'refresh_token'
			}).done(function(data) {
				console.log('Refresh token done.', data);
				googleapi.setToken(data);
				deferred.resolve(data);
			}).fail(function(response) {
				console.log('Refresh token fail.', response);
				googleapi.reset();
				deferred.reject({type: 'invalid_refresh_token', error: response.responseJSON});
			});
		} else {
			//We do not have any cached token information yet
			googleapi.reset();
			deferred.reject({type: 'no_refresh_token_saved'});
		}

		return deferred.promise();
	},
	reset : function () {
		// Only remove tokens from localStorage
		localStorage.removeItem('expires_at');
		localStorage.removeItem('access_token');
		localStorage.removeItem('refresh_token');
	}
};