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

namespace gov.va.medora.mdo.dao.soap.rdw
{
    public class RdwPatientDao : IPatientDao
    {
        RdwConnection _cxn;

        public RdwPatientDao(AbstractConnection cxn)
        {
            _cxn = (RdwConnection)cxn;
        }

        public Patient select(string pid)
        {
            _cxn.Pid = pid;
            return new Patient() { LocalPid = pid };
        }

        #region Not Implemented Members
        public Patient[] match(string target)
        {
            throw new NotImplementedException();
        }

        public Patient[] getPatientsByWard(string wardId)
        {
            throw new NotImplementedException();
        }

        public Patient[] getPatientsByClinic(string clinicId)
        {
            throw new NotImplementedException();
        }

        public Patient[] getPatientsByClinic(string clinicId, string fromDate, string toDate)
        {
            throw new NotImplementedException();
        }

        public Patient[] getPatientsBySpecialty(string specialtyId)
        {
            throw new NotImplementedException();
        }

        public Patient[] getPatientsByTeam(string teamId)
        {
            throw new NotImplementedException();
        }

        public Patient[] getPatientsByProvider(string providerId)
        {
            throw new NotImplementedException();
        }

        public Patient[] matchByNameCityState(string name, string city, string stateAbbr)
        {
            throw new NotImplementedException();
        }

        public Patient select()
        {
            throw new NotImplementedException();
        }

        public Patient selectBySSN(string ssn)
        {
            throw new NotImplementedException();
        }

        public string getLocalPid(string mpiPID)
        {
            throw new NotImplementedException();
        }

        public bool isTestPatient()
        {
            throw new NotImplementedException();
        }

        public KeyValuePair<int, string> getConfidentiality()
        {
            throw new NotImplementedException();
        }

        public string issueConfidentialityBulletin()
        {
            throw new NotImplementedException();
        }

        public System.Collections.Specialized.StringDictionary getRemoteSiteIds(string pid)
        {
            throw new NotImplementedException();
        }

        public Site[] getRemoteSites(string pid)
        {
            throw new NotImplementedException();
        }

        public OEF_OIF[] getOefOif()
        {
            throw new NotImplementedException();
        }

        public void addHomeData(Patient patient)
        {
            throw new NotImplementedException();
        }

        public PatientAssociate[] getPatientAssociates(string pid)
        {
            throw new NotImplementedException();
        }

        public System.Collections.Specialized.StringDictionary getPatientTypes()
        {
            throw new NotImplementedException();
        }

        public string patientInquiry(string pid)
        {
            throw new NotImplementedException();
        }

        public RatedDisability[] getRatedDisabilities()
        {
            throw new NotImplementedException();
        }

        public RatedDisability[] getRatedDisabilities(string pid)
        {
            throw new NotImplementedException();
        }

        public KeyValuePair<string, string> getPcpForPatient(string dfn)
        {
            throw new NotImplementedException();
        }

        public TextReport getMOSReport(Patient patient)
        {
            throw new NotImplementedException();
        }

        public Dictionary<string, string> getTreatingFacilityIds(string pid)
        {
            throw new NotImplementedException();
        }

        public DemographicSet getDemographics()
        {
            throw new NotImplementedException();
        }
        #endregion

        public bool isIdentityProofed(Patient patient)
        {
            throw new NotImplementedException();
        }
    }
}


text:
package mocks

import io "io"
import mock "github.com/stretchr/testify/mock"

type LaxUploader struct {
	mock.Mock
}

func (_m *LaxUploader) File(string, io.ReadSeeker) (string, error) {
	return "", nil
}

func (_m *LaxUploader) JSON(string, interface{}) error {
	return nil
}

redpajama_set_name: RedPajamaGithub


text:
<?php
// module/Customer/test/CustomerTest/Model/CustomerTest.php:
namespace CustomerTest\Model;

use Customer\Model\Customer;

use PHPUnit_Framework_TestCase;

class CustomerTest extends PHPUnit_Framework_TestCase
{
    public function testCustomerInitialState()
    {
        $customer = new Customer();

        $this->assertNull($customer->email, '"email" should initially be null');
        $this->assertNull($customer->id, '"id" should initially be null');
        $this->assertNull($customer->company, '"company" should initially be null');
    }

    public function testExchangeArraySetsPropertiesCorrectly()
    {
        $customer = new Customer();
        $data  = array('email' => 'some email',
                       'id'     => 123,
                       'company'  => 'some company');

        $customer->exchangeArray($data);

        $this->assertSame($data['email'], $customer->email, '"email" was not set correctly');
        $this->assertSame($data['id'], $customer->id, '"company" was not set correctly');
        $this->assertSame($data['company'], $customer->company, '"company" was not set correctly');
    }

    public function testExchangeArraySetsPropertiesToNullIfKeysAreNotPresent()
    {
        $customer = new Customer();

        $customer->exchangeArray(array('email' => 'some email',
                                    'id'     => 123,
                                    'company'  => 'some company'));
        $customer->exchangeArray(array());

        $this->assertNull($customer->email, '"email" should have defaulted to null');
        $this->assertNull($customer->id, '"company" should have defaulted to null');
        $this->assertNull($customer->company, '"company" should have defaulted to null');
    }
}


text:
package granulej.lang;

import gui.constant.ContextConstant;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.InetAddress;
import java.net.Socket;

public class ContextModify implements Runnable {
	private String con_seq;
	public ContextModify(String con_seq) {
		this.con_seq = con_seq;
	}

	public void run() {
		if("".equals(con_seq))
		return ;
	    Socket socket = null;
    	OutputStream socketPut;
    	PrintWriter socketWriter;
    	  try {
    				socket = new Socket(InetAddress.getLocalHost(), ContextConstant.CONTEXT_CLIENT_PORT);
    				socketPut = socket.getOutputStream();
    				socketWriter = new PrintWriter(socketPut);
    				socketWriter.println(ContextConstant.CONTEXT_UPDATE);
    				socketWriter.println(ContextConstant.CONTEXT_UPDATE_FROM_LOCAL);
    				System.out.println("current context is : "+ con_seq);
    				socketWriter.println(con_seq);
    				socketWriter.flush();
    				//System.out.println("Context value update information is sending ...");
    				socketPut.close();
    				socketWriter.close();
    				socket.close();
    	    } catch (BindException e) {
    			    e.printStackTrace();
    		} catch (IOException e) {
    				e.printStackTrace();
    		}
	}
}


text:
'use strict';

describe('Directive: navbar', function () {

  // load the directive's module
  beforeEach(module('privateTheaterApp'));

  var element,
    scope;

  beforeEach(inject(function ($rootScope) {
    scope = $rootScope.$new();
  }));

  it('should make hidden element visible', inject(function ($compile) {
    element = angular.element('<navbar></navbar>');
    element = $compile(element)(scope);
    //TODO: navbar test
    expect(true).toBe(true);
  }));
});


text:
#ifndef GrSingleOwner_DEFINED
#  define GrSingleOwner_DEFINED
#  include "include/core/SkTypes.h"
#  ifdef SK_DEBUG
#    include "include/private/SkMutex.h"
#    include "include/private/SkThreadID.h"
// This is a debug tool to verify an object is only being used from one thread at a time.
class GrSingleOwner
{
public:
  GrSingleOwner()
    : fOwner(kIllegalThreadID)
    , fReentranceCount(0)
  {
  }
  struct AutoEnforce
  {
    AutoEnforce(GrSingleOwner* so)
      : fSO(so)
    {
      fSO->enter();
    }
    ~AutoEnforce()
    {
      fSO->exit();
    }
    GrSingleOwner* fSO;
  };
private:
  void enter()
  {
    SkAutoMutexExclusive lock(fMutex);
    SkThreadID self = SkGetThreadID();
    SkASSERT(fOwner == self || fOwner == kIllegalThreadID);
    fReentranceCount++;
    fOwner = self;
  }
  void exit()
  {
    SkAutoMutexExclusive lock(fMutex);
    SkASSERT(fOwner == SkGetThreadID());
    fReentranceCount--;
    if (fReentranceCount == 0)
    {
      fOwner = kIllegalThreadID;
    }
  }
  SkMutex fMutex;
  SkThreadID fOwner;
  int fReentranceCount;
};
#  else
class GrSingleOwner
{
};
#  endif
#endif


text:
// Copyright 2004-present Facebook. All Rights Reserved.

#pragma once

#include <folly/Synchronized.h>
#include <chrono>
#include <limits>
#include <numeric>
#include <boost/circular_buffer.hpp>

namespace facebook {
namespace fboss {

/*
 * The purpose of this class is to provide a small footprint
 * structure that can record the max and min values over a
 * timed interval. This class uses a bucketing method, where
 * the structure is a buffer of buckets, where each bucket holds
 * the max and min values for an interval in the bucket. The structure
 * allows for configuration of the length of time to record over,
 * and the granularity of the data recorded. This structure's functions
 * are all thread safe, and are intended to be used for data logging.
 */
template <class ValueType>
class TimeSeriesWithMinMax {
 public:
  /*
   * Unit definitions for readable interface.
   */
  using Time = std::chrono::time_point<std::chrono::system_clock>;
  using Duration = std::chrono::seconds;

  /*
   * Instantiate a time series.
   * interval : Length of time to record max over.
   * bucketInterval : The granularity of the data.
   * The class relies on the buffer's buckets being sorted
   * by time covered.
   */
  explicit TimeSeriesWithMinMax(
      Duration interval = Duration(60),
      Duration bucketInterval = Duration(1))
      : interval_(interval), bucketInterval_(bucketInterval) {
    assert(interval.count() >= bucketInterval.count());
    assert(bucketInterval.count() > 0);
    assert(interval.count() > 0);
    buf_ = boost::circular_buffer<Bucket>(
        interval.count() / bucketInterval_.count());
  }

  /*
   * Add a value into the buffer, at the current time.
   */
  void addValue(const ValueType& value);

  /*
   * Add a value into the bucket at a specified time
   */
  void addValue(const ValueType& value, Time t);

  /*
   * Get the current maximum value of the buffer.
   */
  ValueType getMax();

  /*
   * Get the maximum value over an interval
   */
  ValueType getMax(Time start, Time end);

  /*
   * Get the current minimum value of the buffer.
   */
  ValueType getMin();

  /*
   * Get the minimum value over an interval
   */
  ValueType getMin(Time start, Time end);

 private:
  /*
   * Internal bucket class to keep granularity of data.
   */
  class Bucket {
   public:
    /*
     * Construct a Bucket object.
     */
    Bucket(Time now, Duration width);

    /*
     * Add a value into a bucket.
     */
    void addValue(const ValueType& value);

    /*
     * Field querying methods.
     */
    bool isTimeInBucket(Time time);

    Time getInstantiatedTime() const;

    ValueType getMax() const {
      return max_;
    }

    ValueType getMin() const {
      return min_;
    }

   private:
    ValueType max_ = std::numeric_limits<ValueType>::lowest();
    ValueType min_ = std::numeric_limits<ValueType>::max();
    Time startTime_;
    Duration width_;
  };

  /*
   * Internal method to restrict buffer length, and remove buckets
   * from outside of the time window.
   */
  void maintainBuffer(Time now);

  /*
   * Local copies of constructor arguments.
   */
  Duration interval_;
  Duration bucketInterval_;

  /*
   * Vector structure to hold buckets of data. Using folly
   * Synchronized provides the thread-safety needed.
   */
  folly::Synchronized<boost::circular_buffer<Bucket>> buf_;
};
}
}
#include "TimeSeriesWithMinMax-inl.h"


text:
source $HOME/.bash_profile
source $HOME/.bashrc
export HUB=$HOME/git/scoophealth/hquery/query-composer
export HB_PIDFILE=$HUB/tmp/pids/server.pid
export DL_PIDFILE=$HUB/tmp/pids/delayed_job.pid
cd $HUB
if [ -f $DL_PIDFILE ];
then
  bundle exec $HUB/script/delayed_job stop
  # pid file should be gone but recheck
  if [ -f $DL_PIDFILE ];
  then
    rm $DL_PIDFILE
  fi
fi
#
# If gateway is running, stop it.
if [ -f $HB_PIDFILE ];
then
  kill `cat $HB_PIDFILE`
  if [ -f $HB_PIDFILE ];
  then
    kill -9 `cat $HB_PIDFILE`
  fi
  rm $HB_PIDFILE
fi


text:
import { FunctionComponent } from 'react';

import { translate } from '@waldur/i18n';
import { CopyToClipboard } from '@waldur/marketplace/offerings/service-providers/shared/CopyToClipboard';
import './GoogleCalendarLink.scss';

interface GoogleCalendarLinkProps {
  link: string;
}

export const GoogleCalendarLink: FunctionComponent<GoogleCalendarLinkProps> = ({
  link,
}) => (

      {translate('Calendar')}:

        {translate('Click to see Google Calendar')}

    <CopyToClipboard value={link} />

);


text:
package com.frostwire.jlibtorrent.alerts;

import com.frostwire.jlibtorrent.swig.tracker_warning_alert;

/**
 * This alert is triggered if the tracker reply contains a warning field. Usually this
 * means that the tracker announce was successful, but the tracker has a message to
 * the client.
 *
 * @author gubatron
 * @author aldenml
 */
public final class TrackerWarningAlert extends TrackerAlert<tracker_warning_alert> {

    public TrackerWarningAlert(tracker_warning_alert alert) {
        super(alert);
    }

    /**
     * The message associated with this warning.
     *
     * @return
     */
    public String warningMessage() {
        return alert.getMsg();
    }
}


text:
pkg_filepath = "#{Chef::Config['file_cache_path'] || '/tmp'}/#{File.basename(node['mysql-zrm']['package']['all'])}"

# Download and build MySQL ZRM
remote_file pkg_filepath do
  source node['mysql-zrm']['package']['all']
  action :create_if_missing
  not_if 'which mysql-zrm'
end

# Install package dependencies for mysql-zrm
package 'libxml-parser-perl' do
  action :install
end

dpkg_package pkg_filepath do
  action :install
  not_if 'which mysql-zrm'
end


text:
@title[List Content Templates]

## @color[black](List Content
Slide Templates)

@fa[arrow-down text-black]

@snap[south docslink span-50]
[The Template Docs](https://gitpitch.com/docs/the-template)
@snapend

+++?image=template/img/spotlight.png&position=top right&size=20% auto
@title[Title + Concise List]

@snap[north-west]
The Agenda
@snapend

@snap[south-west list-content-concise span-100]
@ol[list-bullets-black](false)
- Lorem ipsum dolor sit amet
- Consectetur adipiscing elit
- Sed do eiusmod tempor
- Ut enim ad minim veniam
- Duis aute irure dolor in
- Excepteur sint occaecat
- Cupidatat non proident
- Sunt in culpa qui officia
@olend

@snapend

@snap[south-west template-note text-gray]
Concise ordered list-items template.
@snapend

+++?image=template/img/spotlight.png&position=top right&size=20% auto
@title[Title + List Fragments]

@snap[north-west]
The Agenda [ Step-by-Step ]
@snapend

@snap[south-west list-content-concise span-100]
@ol
- Lorem ipsum dolor sit amet
- Consectetur adipiscing elit
- Sed do eiusmod tempor
- Ut enim ad minim veniam
- Duis aute irure dolor in
- Excepteur sint occaecat
- Cupidatat non proident
- Sunt in culpa qui officia
@olend

@snapend

@snap[south-west template-note text-gray]
Concise list-item fragments template.
@snapend

+++?image=template/img/spotlight.png&position=top right&size=20% auto
@title[Title + Verbose List]

@snap[north-west]
The Key Concepts
@snapend

@snap[west list-content-verbose span-100]

@ul[](false)
- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
- Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
- Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
- Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
@ulend
@snapend

@snap[south-west template-note text-gray]
Verbose unordered list-items template.
@snapend

+++?image=template/img/spotlight.png&position=top right&size=20% auto
@title[Title + List Fragments]

@snap[north-west]
The Key Concepts [ Step-by-Step ]
@snapend

@snap[west list-content-verbose span-100]

@ul[list-bullets-circles]
- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
- Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
- Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
- Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
@ulend
@snapend

@snap[south-west template-note text-gray]
Verbose list-item fragments template.
@snapend


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

using CommandLine;
using CommandLine.Text;
using Grpc.Core;
using Grpc.Core.Utils;
using Grpc.Testing;
using NUnit.Framework;

namespace Grpc.IntegrationTesting
{
    public class QpsWorker
    {
        private class ServerOptions
        {
            [Option("driver_port", Default = 0)]
            public int DriverPort { get; set; }
        }

        ServerOptions options;

        private QpsWorker(ServerOptions options)
        {
            this.options = options;
        }

        public static void Run(string[] args)
        {
            var parserResult = Parser.Default.ParseArguments<ServerOptions>(args)
                .WithNotParsed((x) => Environment.Exit(1))
                .WithParsed(options =>
                {
                    var workerServer = new QpsWorker(options);
                    workerServer.RunAsync().Wait();
                });
        }

        private async Task RunAsync()
        {
            // (ThreadPoolSize == ProcessorCount) gives best throughput in benchmarks
            // and doesn't seem to harm performance even when server and client
            // are running on the same machine.
            GrpcEnvironment.SetThreadPoolSize(Environment.ProcessorCount);

            string host = "0.0.0.0";
            int port = options.DriverPort;

            var tcs = new TaskCompletionSource<object>();
            var workerServiceImpl = new WorkerServiceImpl(() => { Task.Run(() => tcs.SetResult(null)); });

            var server = new Server
            {
                Services = { WorkerService.BindService(workerServiceImpl) },
                Ports = { new ServerPort(host, options.DriverPort, ServerCredentials.Insecure )}
            };
            int boundPort = server.Ports.Single().BoundPort;
            Console.WriteLine("Running qps worker server on " + string.Format("{0}:{1}", host, boundPort));
            server.Start();
            await tcs.Task;
            await server.ShutdownAsync();
        }
    }
}


text:
@implementation CustomPin

@end


text:
package org.apache.drill.exec.rpc.control;

import org.apache.drill.exec.proto.BitControl;
import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
import org.apache.drill.exec.rpc.BasicClient;

public class RemoteControlConnectionManager extends ControlConnectionManager {
  private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(RemoteControlConnectionManager.class);

  private final ControlConnectionConfig config;
  private final DrillbitEndpoint remoteEndpoint;

  public RemoteControlConnectionManager(ControlConnectionConfig config, DrillbitEndpoint
    localEndpoint, DrillbitEndpoint remoteEndpoint) {
    super(localEndpoint, remoteEndpoint);
    this.config = config;
    this.remoteEndpoint = remoteEndpoint;
  }

  @Override
  protected BasicClient<?, ControlConnection, BitControl.BitControlHandshake, ?> getNewClient() {
    return new ControlClient(config, remoteEndpoint, new CloseHandlerCreator());
  }
}


text:
package org.colorcoding.ibas.initialfantasy.routing;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import org.colorcoding.ibas.initialfantasy.MyConfiguration;

/**
 * 服务信息
 *
 * @author Niuren.Zhu
 *
 */
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "ServiceInformation", namespace = MyConfiguration.NAMESPACE_SERVICE)
@XmlRootElement(name = "ServiceInformation", namespace = MyConfiguration.NAMESPACE_SERVICE)
public class ServiceInformation {
	private String id;

	/**
	 * 获取-服务标记
	 *
	 * @return
	 */
	@XmlElement(name = "Id")
	public String getId() {
		return id;
	}

	/**
	 * 设置-服务标记
	 *
	 */
	public void setId(String id) {
		this.id = id;
	}

	private String name;

	/**
	 * 获取-服务名称
	 *
	 * @return
	 */
	@XmlElement(name = "Name")
	public String getName() {
		return name;
	}

	/**
	 * 设置-服务名称
	 *
	 */
	public void setName(String name) {
		this.name = name;
	}

	private String description;

	/**
	 * 获取-服务描述
	 *
	 * @return
	 */
	@XmlElement(name = "Description")
	public String getDescription() {
		return description;
	}

	/**
	 * 设置-服务描述
	 *
	 */
	public void setDescription(String description) {
		this.description = description;
	}

	@XmlElementWrapper(name = "Providers")
	@XmlElement(name = "Provider", type = ServiceProvider.class)
	private ServiceProvider[] providers;

	/**
	 * 获取-服务提供者
	 *
	 * @return
	 */
	public ServiceProvider[] getProviders() {
		if (providers == null) {
			this.providers = new ServiceProvider[] {};
		}
		return providers;
	}

	/**
	 * 添加-服务提供者
	 *
	 * public void setProviders(ServiceProvider[] providers) { this.providers =
	 * providers; }
	 *
	 */

	public void addProvider(ServiceProvider provider) {
		int index = 0;
		if (this.providers == null || this.providers.length == 0) {
			this.providers = new ServiceProvider[1];
			index = 0;
		} else {
			ServiceProvider[] newProviders = new ServiceProvider[this.providers.length + 1];
			for (int i = 0; i < providers.length - 1; i++) {
				newProviders[i] = this.providers[i];
			}
			this.providers = newProviders;
		}
		this.providers[index] = provider;
	}
}


text:
+-------------+-------------------+
| Computers   | R Documentation   |
+-------------+-------------------+

Prices of Personal Computers
----------------------------

Description
~~~~~~~~~~~

a cross-section from 1993 to 1995

*number of observations* : 6259

*observation* : goods

*country* : United States

Usage
~~~~~

::

    data(Computers)

Format
~~~~~~

A dataframe containing :

price
    price in US dollars of 486 PCs

speed
    clock speed in MHz

hd
    size of hard drive in MB

ram
    size of Ram in in MB

screen
    size of screen in inches

cd
    is a CD-ROM present ?

multi
    is a multimedia kit (speakers, sound card) included ?

premium
    is the manufacturer was a "premium" firm (IBM, COMPAQ) ?

ads
    number of 486 price listings for each month

trend
    time trend indicating month starting from January of 1993 to
    November of 1995.

Source
~~~~~~

Stengos, T. and E. Zacharias (2005) "Intertemporal pricing and price
discrimination : a semiparametric hedonic analysis of the personal
computer market", *Journal of Applied Econometrics*, **forthcoming**.

References
~~~~~~~~~~

Journal of Applied Econometrics data archive :
`http://jae.wiley.com/jae/ <http://jae.wiley.com/jae/>`__.

See Also
~~~~~~~~

``Index.Source``, ``Index.Economics``, ``Index.Econometrics``,
``Index.Observations``


text:
package com.framework.resourcemanager;

import java.io.IOException;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class ResourceManagerTest extends TestCase {

    public ResourceManagerTest() {
        super("ResourceManagerTest");
    }

    public static Test suite() {
        return new TestSuite(ResourceManagerTest.class);
    }

    public void testApp() throws IOException {
        try {

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


text:
package org.opensingular.ws.wkhtmltopdf.controller;

import org.junit.Assert;
import org.junit.Test;

public class WkHtmlToPdfRestControllerTest {

//    @Test
//    public void testConvertHtmlToPdf(){
//        Assert.assertNotNull(new WkHtmlToPdfRestController().convertHtmlToPdf(getHtmlToPdfDTO()));
//    }

//    private HtmlToPdfDTO getHtmlToPdfDTO(){
//        HtmlToPdfDTO dto = new HtmlToPdfDTO();
//        dto.setHeader("" +
//                "<title>Mock html</title>" +
//                "");
//        dto.setBody("
Qualquer coisa com um valor
");
//        dto.setFooter("");
//
//        return dto;
//    }

    @Test
    public void testConvertHtmlToPdfWithNullValue(){
        Assert.assertNull(new WkHtmlToPdfRestController().convertHtmlToPdf(null));
    }

}


text:
namespace demo.device {
	'use strict';

	interface IDeviceViewModel {
		available:boolean;
        cordova:string;
        model:string;
        platform:string;
        uuid:string;
        version:string;
	}

	export class DeviceController {

		public vm:IDeviceViewModel;

		static $inject:Array<string> = ["$ionicPlatform", "$cordovaDevice"];
		constructor($ionicPlatform:ionic.platform.IonicPlatformService, $cordovaDevice:ngCordova.IDeviceService) {

			$ionicPlatform.ready(() => {
				this.vm = {
					available : $cordovaDevice.getDevice().available,
					cordova : $cordovaDevice.getCordova(),
					model : $cordovaDevice.getModel(),
					platform : $cordovaDevice.getPlatform(),
					uuid : $cordovaDevice.getUUID(),
					version : $cordovaDevice.getVersion()
				};
			});
		}

	}

	angular.module("demo.device").controller("DeviceController", DeviceController);
}


text:
<?php

namespace   PDOExtended;
use         PDOException;

/**
 * StmtException class allowing query debugging
 * @author Beno!t POLASZEK - 2013
 */
Class StmtException Extends PDOException {

    protected    $Stmt;

    public function __construct($Message, $Code, PDOException $Exception, PDOStatementExtended $Stmt) {
        // PB avec le code HY093, alors que $Code est censé être de type long
        parent::__construct($Message, (int) $Code);
        $this->Stmt    =    $Stmt;
    }

    public function GetStmt() {
        return $this->Stmt;
    }

}


text:
<?php

namespace Sabre\VObject\Component;
use Sabre\VObject;

class VAlarm extends VObject\Component {

    /**
     * Returns a DateTime object when this alarm is going to trigger.
     *
     * This ignores repeated alarm, only the first trigger is returned.
     *
     * @return DateTime
     */
    public function getEffectiveTriggerTime() {

        $trigger = $this->TRIGGER;
        if(!isset($trigger['VALUE']) || strtoupper($trigger['VALUE']) === 'DURATION') {
            $triggerDuration = VObject\DateTimeParser::parseDuration($this->TRIGGER);
            $related = (isset($trigger['RELATED']) && strtoupper($trigger['RELATED']) == 'END') ? 'END' : 'START';

            $parentComponent = $this->parent;
            if ($related === 'START') {

                if ($parentComponent->name === 'VTODO') {
                    $propName = 'DUE';
                } else {
                    $propName = 'DTSTART';
                }

                $effectiveTrigger = clone $parentComponent->$propName->getDateTime();
                $effectiveTrigger->add($triggerDuration);
            } else {
                if ($parentComponent->name === 'VTODO') {
                    $endProp = 'DUE';
                } elseif ($parentComponent->name === 'VEVENT') {
                    $endProp = 'DTEND';
                } else {
                    throw new \LogicException('time-range filters on VALARM components are only supported when they are a child of VTODO or VEVENT');
                }

                if (isset($parentComponent->$endProp)) {
                    $effectiveTrigger = clone $parentComponent->$endProp->getDateTime();
                    $effectiveTrigger->add($triggerDuration);
                } elseif (isset($parentComponent->DURATION)) {
                    $effectiveTrigger = clone $parentComponent->DTSTART->getDateTime();
                    $duration = VObject\DateTimeParser::parseDuration($parentComponent->DURATION);
                    $effectiveTrigger->add($duration);
                    $effectiveTrigger->add($triggerDuration);
                } else {
                    $effectiveTrigger = clone $parentComponent->DTSTART->getDateTime();
                    $effectiveTrigger->add($triggerDuration);
                }
            }
        } else {
            $effectiveTrigger = $trigger->getDateTime();
        }
        return $effectiveTrigger;

    }

    /**
     * Returns true or false depending on if the event falls in the specified
     * time-range. This is used for filtering purposes.
     *
     * The rules used to determine if an event falls within the specified
     * time-range is based on the CalDAV specification.
     *
     * @param \DateTime $start
     * @param \DateTime $end
     * @return bool
     */
    public function isInTimeRange(\DateTime $start, \DateTime $end) {

        $effectiveTrigger = $this->getEffectiveTriggerTime();

        if (isset($this->DURATION)) {
            $duration = VObject\DateTimeParser::parseDuration($this->DURATION);
            $repeat = (string)$this->repeat;
            if (!$repeat) {
                $repeat = 1;
            }

            $period = new \DatePeriod($effectiveTrigger, $duration, (int)$repeat);

            foreach($period as $occurrence) {

                if ($start <= $occurrence && $end > $occurrence) {
                    return true;
                }
            }
            return false;
        } else {
            return ($start <= $effectiveTrigger && $end > $effectiveTrigger);
        }

    }

}


text:
import server from '../api/server';

export const LOGIN_REQUESTED = 'login';
export const LOGOUT_REQUESTED = 'logout';
export const USER_IN = 'user_in';
export const USER_OUT = 'user_out';

//
// ActionCreators
//

export function initialize() {
	return (dispatch) => {
		let database = new server();
		return database
			.activateAuth()
			.then((authData) => {
				if (authData) {
					dispatch(userIn(authData));
				} else {
					dispatch(userOut());
				}
			})
			.catch((a) => console.error('initialize', a));
	};
}

export function login() {
	return (dispatch) => {
		dispatch(loginRequested());
		let database = new server();
		return database
			.login()
			.then((authData) => {
				if (authData) {
					dispatch(userIn(authData));
				} else {
					dispatch(userOut());
				}
			})
			.catch((a) => console.error('login', a));

	};
	// TODO: notify error
}

export function logout() {
	return (dispatch) => {
		dispatch(logoutRequested());
		let database = new server();
		return database
			.logout()
			.then(() => dispatch(userOut()))
			.catch(a => console.error('logout', a));
	}
}

//
// simple Actions
//

function loginRequested() {
	return {
		type: LOGIN_REQUESTED
	};
}

function userIn(authData) {
	return {
		type: USER_IN,
		payload: {authData}
	};
}

function logoutRequested() {
	return {
		type: LOGOUT_REQUESTED
	};
}

function userOut() {
	return {
		type: USER_OUT
	};
}


text:
package org.diorite.inventory;

import org.diorite.entity.ArmoredEntity;
import org.diorite.inventory.item.ItemStack;
import org.diorite.material.ArmorType;

public interface EntityEquipment
{
    /**
     * @return An array of ItemStacks from the eq.
     */
    ItemStack[] getContents();

    /**
     * @return The ItemStack in the helmet slot
     */
    ItemStack getHelmet();

    /**
     * @return The ItemStack in the chestplate slot
     */
    ItemStack getChestplate();

    /**
     * @return The ItemStack in the leg slot
     */
    ItemStack getLeggings();

    /**
     * @return The ItemStack in the boots slot
     */
    ItemStack getBoots();

    /**
     * Put the given ItemStack into the given armor slot. This does not check if
     * the ItemStack is a valid type for this slot.
     *
     * @param type  type of armor to find slot.
     * @param armor The ItemStack to use as armor.
     *
     * @return true if item was set.
     */
    default boolean setArmor(final ArmorType type, final ItemStack armor)
    {
        return type.setItem(this, armor);
    }

    /**
     * Put the given ItemStack into the helmet slot. This does not check if
     * the ItemStack is a helmet
     *
     * @param helmet The ItemStack to use as helmet
     *
     * @return previous itemstack used as helmet.
     */
    ItemStack setHelmet(final ItemStack helmet);

    /**
     * Put the given ItemStack into the chestplate slot. This does not check
     * if the ItemStack is a chestplate
     *
     * @param chestplate The ItemStack to use as chestplate
     *
     * @return previous itemstack used as chestplate.
     */
    ItemStack setChestplate(final ItemStack chestplate);

    /**
     * Put the given ItemStack into the leg slot. This does not check if the
     * ItemStack is a pair of leggings
     *
     * @param leggings The ItemStack to use as leggings
     *
     * @return previous itemstack used as leggings.
     */
    ItemStack setLeggings(final ItemStack leggings);

    /**
     * Put the given ItemStack into the boots slot. This does not check if the
     * ItemStack is a boots
     *
     * @param boots The ItemStack to use as boots
     *
     * @return previous itemstack used as boots.
     */
    ItemStack setBoots(final ItemStack boots);

    /**
     * Put the given ItemStack into the helmet slot if it matches a excepted one.
     * NOTE: this is atomic operation.
     *
     * @param excepted excepted item to replace.
     * @param helmet   The ItemStack to use as helmet
     *
     * @return true if item was replaced.
     *
     * @throws IllegalArgumentException if excepted item isn't impl version of ItemStack, so it can't be == to any item from inventory.
     */
    boolean replaceHelmet(final ItemStack excepted, final ItemStack helmet) throws IllegalArgumentException;

    /**
     * Put the given ItemStack into the chestplate slot if it matches a excepted one.
     * NOTE: this is atomic operation.
     *
     * @param excepted   excepted item to replace.
     * @param chestplate The ItemStack to use as chestplate
     *
     * @return true if item was replaced.
     *
     * @throws IllegalArgumentException if excepted item isn't impl version of ItemStack, so it can't be == to any item from inventory.
     */
    boolean replaceChestplate(final ItemStack excepted, final ItemStack chestplate) throws IllegalArgumentException;

    /**
     * Put the given ItemStack into the leggings slot if it matches a excepted one.
     * NOTE: this is atomic operation.
     *
     * @param excepted excepted item to replace.
     * @param leggings The ItemStack to use as leggings
     *
     * @return true if item was replaced.
     *
     * @throws IllegalArgumentException if excepted item isn't impl version of ItemStack, so it can't be == to any item from inventory.
     */
    boolean replaceLeggings(final ItemStack excepted, final ItemStack leggings) throws IllegalArgumentException;

    /**
     * Put the given ItemStack into the boots slot if it matches a excepted one.
     * NOTE: this is atomic operation.
     *
     * @param excepted excepted item to replace.
     * @param boots    The ItemStack to use as boots
     *
     * @return true if item was replaced.
     *
     * @throws IllegalArgumentException if excepted item isn't impl version of ItemStack, so it can't be == to any item from inventory.
     */
    boolean replaceBoots(final ItemStack excepted, final ItemStack boots) throws IllegalArgumentException;

    /**
     * Completely replaces the inventory's contents. Removes all existing
     * contents and replaces it with the ItemStacks given in the array.
     *
     * @param items A complete replacement for the contents; the length must
     *              be less than or equal to {@link #size()}.
     *
     * @throws IllegalArgumentException If the array has more items than the
     *                                  inventory.
     */
    void setContent(final ItemStack[] items);

    /**
     * Gets the entity belonging to this equipment.
     *
     * @return The holder of the inventory; null if it has no holder.
     */
    ArmoredEntity getEquipmentHolder();

    /**
     * @return The size of the inventory
     */
    int size();

}


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:animateLayoutChanges="true"
    android:background="@color/bgBlue">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        style="@style/Toolbar"
        android:layout_width="match_parent"
        android:elevation="20dp"
        app:contentInsetStart="8dp"
        app:layout_constraintTop_toTopOf="parent">

        <FrameLayout
            android:id="@+id/flBack"
            android:layout_width="36dp"
            android:layout_height="36dp">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:background="@drawable/ic_arrow_back" />
        </FrameLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/toolbarTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:textColor="@android:color/white"
                android:textSize="17sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/tvSubTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:alpha="0.6"
                android:textColor="@android:color/white"
                android:textStyle="normal"
                tools:text="subtitle" />
        </LinearLayout>

        <ImageView
            android:id="@+id/ivMore"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:layout_marginEnd="16dp"
            android:paddingHorizontal="16dp"
            android:paddingVertical="4dp"
            android:src="@drawable/ic_more"
            tools:ignore="ContentDescription" />
    </androidx.appcompat.widget.Toolbar>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvMessages"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:clipToPadding="false"
        android:paddingTop="8dp"
        app:layout_constraintBottom_toTopOf="@+id/rlChatSend"
        app:layout_constraintTop_toBottomOf="@+id/toolbar"
        tools:listitem="@layout/item_text_right_message" />

    <LinearLayout
        android:id="@+id/llAttachment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        android:orientation="vertical"
        android:visibility="gone"
        app:layout_constraintBottom_toTopOf="@+id/rlChatSend"
        tools:visibility="visible">

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/colorDivider"
            app:layout_constraintBottom_toTopOf="@+id/rvPreview" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rvPreview"
            android:layout_width="match_parent"
            android:layout_height="96dp"
            android:orientation="horizontal"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            tools:listitem="@layout/item_attachment_preview" />
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/rlChatSend"
        android:layout_width="match_parent"
        android:layout_height="44dp"
        android:background="@android:color/white"
        app:layout_constraintBottom_toBottomOf="parent">

        <ImageView
            android:id="@+id/ivAttachment"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentStart="true"
            android:background="?attr/selectableItemBackground"
            android:paddingLeft="9dp"
            android:paddingTop="7dp"
            android:paddingRight="9dp"
            android:paddingBottom="7dp"
            android:src="@drawable/ic_add_attachment" />

        <EditText
            android:id="@+id/etMessage"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_toStartOf="@+id/ivSend"
            android:layout_toEndOf="@+id/ivAttachment"
            android:background="@android:color/transparent"
            android:hint="@string/chat_edit_text_hint"
            android:importantForAutofill="no"
            android:inputType="textShortMessage"
            android:maxLength="1000"
            android:textColor="@color/grayText"
            android:textColorHint="@color/gray"
            android:textSize="15sp" />

        <ImageView
            android:id="@+id/ivSend"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentEnd="true"
            android:background="?attr/selectableItemBackground"
            android:paddingStart="2.5dp"
            android:paddingTop="8dp"
            android:paddingEnd="10.5dp"
            android:paddingBottom="8dp"
            android:src="@drawable/ic_send_message" />
    </RelativeLayout>

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


text:
<?php

namespace Sylius\Component\Shipping\Resolver;

use Doctrine\Common\Persistence\ObjectRepository;
use Sylius\Component\Shipping\Checker\ShippingMethodEligibilityCheckerInterface;
use Sylius\Component\Shipping\Model\ShippingMethodInterface;
use Sylius\Component\Shipping\Model\ShippingSubjectInterface;

/**
 * Default available methods resolver.
 *
 * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
 */
class MethodsResolver implements MethodsResolverInterface
{
    /**
     * Shipping methods repository.
     *
     * @var ObjectRepository
     */
    protected $repository;

    /**
     * Shipping method eligibility checker.
     *
     * @var ShippingMethodEligibilityCheckerInterface
     */
    protected $eligibilityChecker;

    /**
     * Constructor.
     *
     * @param ObjectRepository                          $repository
     * @param ShippingMethodEligibilityCheckerInterface $eligibilityChecker
     */
    public function __construct(ObjectRepository $repository, ShippingMethodEligibilityCheckerInterface $eligibilityChecker)
    {
        $this->repository = $repository;
        $this->eligibilityChecker = $eligibilityChecker;
    }

    /**
     * {@inheritdoc}
     */
    public function getSupportedMethods(ShippingSubjectInterface $subject, array $criteria = array())
    {
        $methods = array();

        foreach ($this->getMethods($criteria) as $method) {
            if ($this->eligibilityChecker->isEligible($subject, $method)) {
                $methods[] = $method;
            }
        }

        return $methods;
    }

    /**
     * Return all methods matching given criteria.
     *
     * @param array $criteria
     *
     * @return ShippingMethodInterface[]
     */
    protected function getMethods(array $criteria = array())
    {
        return $this->repository->findBy($criteria);
    }
}


text:
package com.cinchapi.concourse.example.mocktwitter;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.cinchapi.concourse.time.Time;

/**
 *
 *
 * @author Jeff Nelson
 */
public class MysqlTwitter implements Twitter {

    private static Comparator<Long> REVERSE_CHRONOLOGICAL_SORTER = new Comparator<Long>() {

        @Override
        public int compare(Long o1, Long o2) {
            return -1 * o1.compareTo(o2);
        }

    };

    /**
     * Return a string that represents the hash for {@code string}.
     *
     * @param string
     * @return the hash
     */
    private static String hash(String string) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(string.getBytes());
            // props to http://stackoverflow.com/a/5470268/1336833
            StringBuilder hex = new StringBuilder();
            for (int i = 0; i < hash.length; i++) {
                if((0xff & hash[i]) < 0x10) {
                    hex.append("0" + Integer.toHexString((0xFF & hash[i])));
                }
                else {
                    hex.append(Integer.toHexString(0xFF & hash[i]));
                }
            }
            return hex.toString();
        }
        catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e); // this should never happen
        }
    }

    /**
     * Generates secure random salt values. This is overkill for the demo, but
     * good to use for real applications.
     */
    private final SecureRandom srand = new SecureRandom();

    /**
     * The id of the user that is currenty logged in.
     */
    private long userid = 0;

    private Connection mysql;
    {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String user = "root";
            String password = "root";
            String url = "jdbc:mysql://localhost:8889/twitter";
            mysql = DriverManager.getConnection(url, user, password);
        }
        catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            mysql = null;
        }
    }

    @Override
    public boolean follow(String username) {
        try {
            long id = getUserId(username);
            if(id != userid) {
                PreparedStatement stmt = mysql
                        .prepareStatement("INSERT INTO followers (follower, followed) VALUES (?,?)");
                stmt.setLong(1, userid);
                stmt.setLong(2, id);
                return stmt.executeUpdate() > 0;
            }
            else {
                return false;
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean login(String username, String password) {
        try {
            if(exists(username)) {
                long userid = getUserId(username);
                PreparedStatement stmt = mysql
                        .prepareStatement("SELECT salt, password FROM users WHERE uid = ?");
                stmt.setLong(1, userid);
                stmt.execute();
                ResultSet result = stmt.getResultSet();
                result.next();
                long salt = result.getLong(1);
                String pword = result.getString(2);
                password = hash(password + salt);
                if(password.equals(pword)) {
                    this.userid = userid;
                    return true;
                }
            }
            return false;
        }
        catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Map<Long, String> mentions() {
        try {
            PreparedStatement stmt = mysql
                    .prepareStatement("SELECT tid FROM mentions WHERE uid = ?");
            stmt.setLong(1, userid);
            stmt.execute();
            ResultSet result = stmt.getResultSet();
            Set<Long> tids = new HashSet<Long>();
            while (result.next()) {
                tids.add(result.getLong(1));
            }
            return getTweetInfo(tids);
        }
        catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean register(String username, String password) {
        try {
            if(!exists(username)) {
                long id = Time.now();
                long salt = srand.nextLong();
                PreparedStatement stmt = mysql
                        .prepareStatement("INSERT INTO users (uid, username, password, salt) VALUES (?,?,?,?)");
                stmt.setLong(1, id);
                stmt.setString(2, username);
                stmt.setString(3, hash(password + salt));
                stmt.setLong(4, salt);
                return stmt.executeUpdate() > 0;
            }
            else {
                throw new IllegalArgumentException("Username is already taken!");
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Map<Long, String> timeline() {
        try {
            Map<Long, String> timeline = new TreeMap<Long, String>(
                    REVERSE_CHRONOLOGICAL_SORTER);

            // Get all of my tweets
            PreparedStatement stmt = mysql
                    .prepareStatement("SELECT tid FROM tweets where author = ?");
            stmt.setLong(1, userid);
            stmt.execute();
            ResultSet result = stmt.getResultSet();
            Set<Long> tids = new HashSet<Long>();
            while (result.next()) {
                tids.add(result.getLong(1));
            }
            timeline.putAll(getTweetInfo(tids));

            // Get all of the tweets for users i am following
            stmt = mysql
                    .prepareStatement("SELECT followed FROM followers WHERE follower = ?");
            stmt.setLong(1, userid);
            stmt.execute();
            result = stmt.getResultSet();
            while (result.next()) {
                long followed = result.getLong(1);
                PreparedStatement stmt2 = mysql
                        .prepareStatement("SELECT tid FROM tweets where author = ?");
                stmt2.setLong(1, followed);
                stmt2.execute();
                ResultSet result2 = stmt.getResultSet();
                Set<Long> tids2 = new HashSet<Long>();
                while (result2.next()) {
                    tids2.add(result2.getLong(1));
                }
                timeline.putAll(getTweetInfo(tids2));
            }

            // Get all the tweets where I am mentioned
            timeline.putAll(mentions());

            return timeline;
        }
        catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void tweet(String message) {
        try {
            if(message.length() <= 140) {
                long tweetId = Time.now();

                PreparedStatement stmt = mysql
                        .prepareStatement("INSERT INTO tweets (tid, author, message, timestamp) VALUES (?,?,?,?)");
                stmt.setLong(1, tweetId);
                stmt.setLong(2, userid);
                stmt.setString(3, message);
                stmt.setLong(4, Time.now());
                stmt.executeUpdate();

                // Parse out mentioned users and link them to the tweet
                Pattern pattern = Pattern.compile("[@][\\w]+");
                Matcher matcher = pattern.matcher(message);
                PreparedStatement stmt2 = mysql
                        .prepareStatement("INSERT INTO mentions (tid, uid) VALUES (?,?)");
                while (matcher.find()) {
                    String uname = matcher.group().replace("@", "");
                    long mentioned = getUserId(uname);
                    stmt2.clearParameters();
                    stmt2.setLong(1, tweetId);
                    stmt2.setLong(2, mentioned);
                    stmt2.execute();
                }
            }
            else {
                throw new IllegalArgumentException("Tweet is too long!");
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    public boolean unfollow(String username) {
        try {
            long id = getUserId(username);
            if(id != userid) {
                PreparedStatement stmt = mysql
                        .prepareStatement("DELETE FROM folowers WHERE follower = ? AND followerd = ?");
                stmt.setLong(1, userid);
                stmt.setLong(2, id);
                return stmt.executeUpdate() > 0;
            }
            else {
                return false;
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Return {@code true} if a user with {@code username} exists.
     *
     * @param username
     * @return {@code true} if {@code username} exists
     * @throws SQLException
     */
    private boolean exists(String username) throws SQLException {
        PreparedStatement stmt = mysql
                .prepareStatement("SELECT uid FROM users WHERE username = ?");
        stmt.setString(1, username);
        stmt.execute();
        ResultSet result = stmt.getResultSet();
        return result.next();
    }

    /**
     * Return a map from timestamp to tweet that contains information for the
     * set of tweet ids specified in {@code tweets}.
     *
     * @param tweets
     * @return the tweet info
     */
    private Map<Long, String> getTweetInfo(Set<Long> tweets) {
        try {
            Map<Long, String> collection = new TreeMap<Long, String>(
                    REVERSE_CHRONOLOGICAL_SORTER);
            PreparedStatement stmt = mysql
                    .prepareStatement("SELECT username, message, timestamp FROM tweets JOIN users on author = uid WHERE tid = ?");
            for (Long tweetId : tweets) {
                stmt.clearParameters();
                stmt.setLong(1, tweetId);
                stmt.execute();
                ResultSet result = stmt.getResultSet();
                result.next();
                String author = result.getString(1);
                String message = result.getString(2);
                long timestamp = result.getLong(3);
                collection.put(timestamp, author + ": " + message);
            }
            return collection;
        }
        catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Return the user id (primary key) for the user with {@code username}.
     *
     * @param username
     * @return the user id for {@code username}
     * @throws SQLException
     * @throws IllegalArgumentException
     */
    private long getUserId(String username) throws SQLException {
        if(exists(username)) {
            PreparedStatement stmt = mysql
                    .prepareStatement("SELECT uid FROM users WHERE username = ?");
            stmt.setString(1, username);
            stmt.execute();
            ResultSet result = stmt.getResultSet();
            result.next();
            return result.getLong(1);
        }
        else {
            throw new IllegalArgumentException("Invalid user");
        }

    }
}


text:
package com.julienvey.trello.impl.http;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.julienvey.trello.exception.TrelloHttpException;

public class ApacheHttpClient extends AbstractHttpClient {

	private DefaultHttpClient httpClient;
	private ObjectMapper mapper;

	public ApacheHttpClient() {
		this(new DefaultHttpClient());
	}

	public ApacheHttpClient(DefaultHttpClient httpClient) {
		this.httpClient = httpClient;
		this.mapper = new ObjectMapper();
	}

	@Override
	public <T> T get(String url, Class<T> objectClass, String... params) {
		HttpGet httpGet = new HttpGet(expandUrl(url, params));
		return getEntityAndReleaseConnection(objectClass, httpGet);
	}

	@Override
	public <T> T postForObject(String url, T object, Class<T> objectClass, String... params) {
		HttpPost httpPost = new HttpPost(expandUrl(url, params));

		try {
			HttpEntity entity = new ByteArrayEntity(this.mapper.writeValueAsBytes(object),
					ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);

			return getEntityAndReleaseConnection(objectClass, httpPost);
		} catch (JsonProcessingException e) {
			// TODO : custom exception
			throw new RuntimeException(e);
		}
	}

	public <T> T postFileForObject(String url, File file, Class<T> objectClass, String... params) {
		HttpPost httpPost = new HttpPost(expandUrl(url, params));

		MultipartEntity entity = new MultipartEntity();
		entity.addPart("file", new FileBody(file));
		try {
			entity.addPart("filename", new StringBody(file.getName()));
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}

		httpPost.setEntity(entity);

		return getEntityAndReleaseConnection(objectClass, httpPost);
	}

	@Override
	public <T> T putForObject(String url, T object, Class<T> objectClass, String... params) {
		HttpPut put = new HttpPut(expandUrl(url, params));
		try {
			HttpEntity entity = new ByteArrayEntity(this.mapper.writeValueAsBytes(object),
					ContentType.APPLICATION_JSON);
			put.setEntity(entity);

			return getEntityAndReleaseConnection(objectClass, put);
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public URI postForLocation(String url, Object object, String... params) {
		HttpPost httpPost = new HttpPost(expandUrl(url, params));

		try {
			HttpEntity entity = new ByteArrayEntity(this.mapper.writeValueAsBytes(object),
					ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			HttpResponse httpResponse = this.httpClient.execute(httpPost);

			Header location = httpResponse.getFirstHeader("Location");
			if (location != null) {
				return URI.create(location.getValue());
			} else {
				// TODO : error
				throw new NullPointerException();
			}
		} catch (JsonProcessingException e) {
			// TODO : custom exception
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new TrelloHttpException(e);
		} finally {
			httpPost.releaseConnection();
		}
	}

	private <T> T getEntityAndReleaseConnection(Class<T> objectClass, HttpRequestBase httpRequest) {
		try {
			HttpResponse httpResponse = this.httpClient.execute(httpRequest);

			HttpEntity httpEntity = httpResponse.getEntity();
			if (httpEntity != null) {
				return this.mapper.readValue(httpEntity.getContent(), objectClass);
			} else {
				// TODO : error
				throw new NullPointerException();
			}
		} catch (IOException e) {
			throw new TrelloHttpException(e);
		} finally {
			httpRequest.releaseConnection();
		}
	}
}


text:
<?php

namespace Nosto\Test\Support;

use Nosto\Model\Cart\LineItem;

class MockPseudoItem extends LineItem
{
    public function __construct()
    {
        parent::__construct();
        $this->loadSpecialItemData("Discount", 123.45, "EUR");
    }
}


text:
<?php

declare(strict_types=1);

namespace Nelmio\Alice;

use Nelmio\Alice\Definition\Object\CompleteObject;
use Nelmio\Alice\Definition\Object\SimpleObject;
use Nelmio\Alice\Throwable\Exception\InvalidArgumentExceptionFactory;
use Nelmio\Alice\Throwable\Exception\ObjectNotFoundException;
use Nelmio\Alice\Throwable\Exception\ObjectNotFoundExceptionFactory;

/**
 * Value object containing a list of objects.
 */
final class ObjectBag implements \IteratorAggregate, \Countable
{
    /**
     * @var ObjectInterface[]
     */
    private $objects = [];

    private $array = [];

    public function __construct(array $objects = [])
    {
        foreach ($objects as $id => $object) {
            if ($object instanceof ObjectInterface) {
                if ($id !== $object->getId()) {
                    throw InvalidArgumentExceptionFactory::createForReferenceKeyMismatch($id, $object->getId());
                }
                $this->objects[$id] = $object;
                $this->array[$id] = $object->getInstance();

                continue;
            }

            $this->objects[$id] = new CompleteObject(
                new SimpleObject($id, $object)
            );
            $this->array[$id] = $object;
        }
    }

    /**
     * Creates a new instance which will contain the given object. If an object with the same reference already exists,
     * it will be overridden by the new object.
     *
     * @param ObjectInterface $object
     *
     * @return self
     */
    public function with(ObjectInterface $object): self
    {
        $clone = clone $this;
        $clone->objects[$object->getId()] = $object;
        $clone->array[$object->getId()] = $object->getInstance();

        return $clone;
    }

    /**
     * Creates a new instance which will no longer contain the given object.
     *
     * @param FixtureInterface|ObjectInterface $objectOrFixture
     *
     * @return self
     */
    public function without($objectOrFixture): self
    {
        $clone = clone $this;
        unset($clone->objects[$objectOrFixture->getId()]);
        unset($clone->array[$objectOrFixture->getId()]);

        return $clone;
    }

    /**
     * Creates a new instance with the new objects. If objects with the same reference already exists, they will be
     * overridden by the new ones.
     *
     * @param ObjectBag $objects
     *
     * @return self
     */
    public function mergeWith(self $objects): self
    {
        $clone = clone $this;
        foreach ($objects->objects as $reference => $object) {
            $clone->objects[$reference] = $object;
            $clone->array[$reference] = $object->getInstance();
        }

        return $clone;
    }

    public function has(FixtureIdInterface $fixture): bool
    {
        return isset($this->objects[$fixture->getId()]);
    }

    /**
     * @param FixtureIdInterface $fixture
     *
     * @throws ObjectNotFoundException
     *
     * @return ObjectInterface
     */
    public function get(FixtureIdInterface $fixture): ObjectInterface
    {
        if ($this->has($fixture)) {
            return $this->objects[$fixture->getId()];
        }

        throw ObjectNotFoundExceptionFactory::create(
            $fixture->getId(),
            $fixture instanceof FixtureInterface ? $fixture->getClassName() : 'no class given'
        );
    }

    /**
     * @inheritdoc
     */
    public function count()
    {
        return count($this->objects);
    }

    /**
     * @inheritdoc
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->objects);
    }

    public function toArray(): array
    {
        return $this->array;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>javax.jws.soap Class Hierarchy (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package javax.jws.soap

Package Hierarchies:

All Packages

Annotation Type Hierarchy

javax.jws.soap.SOAPBinding (implements java.lang.annotation.Annotation)

javax.jws.soap.InitParam (implements java.lang.annotation.Annotation)

javax.jws.soap.SOAPMessageHandler (implements java.lang.annotation.Annotation)

javax.jws.soap.SOAPMessageHandlers (implements java.lang.annotation.Annotation)

Enum Hierarchy

java.lang.Object

java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)

javax.jws.soap.SOAPBinding.Style

javax.jws.soap.SOAPBinding.Use

javax.jws.soap.SOAPBinding.ParameterStyle

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev

Next

Frames

No Frames

All Classes

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
package v2alpha

import (
	"bytes"
	"errors"
	"fmt"
	"net"
	"net/mail"
	"net/url"
	"regexp"
	"sort"
	"strings"
	"time"
	"unicode/utf8"

	"google.golang.org/protobuf/types/known/anypb"
)

// ensure the imports are used
var (
	_ = bytes.MinRead
	_ = errors.New("")
	_ = fmt.Print
	_ = utf8.UTFMax
	_ = (*regexp.Regexp)(nil)
	_ = (*strings.Reader)(nil)
	_ = net.IPv4len
	_ = time.Duration(0)
	_ = (*url.URL)(nil)
	_ = (*mail.Address)(nil)
	_ = anypb.Any{}
	_ = sort.Sort
)

// Validate checks the field values on Body with the rules defined in the proto
// definition for this message. If any rules are violated, the first error
// encountered is returned, or nil if there are no violations.
func (m *Body) Validate() error {
	return m.validate(false)
}

// ValidateAll checks the field values on Body with the rules defined in the
// proto definition for this message. If any rules are violated, the result is
// a list of violation errors wrapped in BodyMultiError, or nil if none found.
func (m *Body) ValidateAll() error {
	return m.validate(true)
}

func (m *Body) validate(all bool) error {
	if m == nil {
		return nil
	}

	var errors []error

	// no validation rules for Truncated

	switch m.BodyType.(type) {

	case *Body_AsBytes:
		// no validation rules for AsBytes

	case *Body_AsString:
		// no validation rules for AsString

	}

	if len(errors) > 0 {
		return BodyMultiError(errors)
	}

	return nil
}

// BodyMultiError is an error wrapping multiple validation errors returned by
// Body.ValidateAll() if the designated constraints aren't met.
type BodyMultiError []error

// Error returns a concatenation of all the error messages it wraps.
func (m BodyMultiError) Error() string {
	var msgs []string
	for _, err := range m {
		msgs = append(msgs, err.Error())
	}
	return strings.Join(msgs, "; ")
}

// AllErrors returns a list of validation violation errors.
func (m BodyMultiError) AllErrors() []error { return m }

// BodyValidationError is the validation error returned by Body.Validate if the
// designated constraints aren't met.
type BodyValidationError struct {
	field  string
	reason string
	cause  error
	key    bool
}

// Field function returns field value.
func (e BodyValidationError) Field() string { return e.field }

// Reason function returns reason value.
func (e BodyValidationError) Reason() string { return e.reason }

// Cause function returns cause value.
func (e BodyValidationError) Cause() error { return e.cause }

// Key function returns key value.
func (e BodyValidationError) Key() bool { return e.key }

// ErrorName returns error name.
func (e BodyValidationError) ErrorName() string { return "BodyValidationError" }

// Error satisfies the builtin error interface
func (e BodyValidationError) Error() string {
	cause := ""
	if e.cause != nil {
		cause = fmt.Sprintf(" | caused by: %v", e.cause)
	}

	key := ""
	if e.key {
		key = "key for "
	}

	return fmt.Sprintf(
		"invalid %sBody.%s: %s%s",
		key,
		e.field,
		e.reason,
		cause)
}

var _ error = BodyValidationError{}

var _ interface {
	Field() string
	Reason() string
	Key() bool
	Cause() error
	ErrorName() string
} = BodyValidationError{}


text:
<?php
/**
 * Created by PhpStorm.
 * User: sergey
 * Date: 26.01.17
 * Time: 21:33
 */

namespace app\controllers;
use app\models\Product;
use app\models\Category;
use Yii;

class ProductController extends AppController
{
    public function actionView($id)
    {
        $product = Product::findOne($id);
        if(empty($product))
            throw new \yii\web\HttpException(404, 'Такго товара нет.');
        $hits = Product::find()->where(['hit' => '1'])->limit(6)->all();
        $this->setMeta("E-SHOPPER | " . $product->name, $product->keywords, $product->description);

        return $this->render('view', compact('product', 'hits'));
    }
}


text:
package com.dotosoft.dot4command.chain;

/**
 * A Processing encapsulates states that can be returned by
 * commands.
 *

 * {@link Command}s should either return FINISHED if the
 * processing of the given context has been completed, or return
 * CONTINUE if the processing of the given {@link Context} should
 * be delegated to a subsequent command in an enclosing {@link Chain}.
 *
 * @version $Id $
 */
public enum Processing {

	/**
     * Commands should return break if the processing of the given
     * context should be broken from loop command in an enclosing chain.
     *
     * @since Chain 2.0
     */
    BREAK,

    /**
     * Commands should return continue if the processing of the given
     * context should be delegated to a subsequent command in an enclosing chain.
     *
     * @since Chain 2.0
     */
    CONTINUE,

    /**
     * Commands should return finished if the processing of the given context
     * has been completed.
     *
     * @since Chain 2.0
     */
    FINISHED,

    /**
     * Commands should return terminate if the processing of the given
     * context should be ended.
     *
     * @since Chain 2.0
     */
    TERMINATE,

}


text:
<?php
namespace Google\Service;

/**
 * Service definition for Freebase (v1).
 *
 *

 * Find Freebase entities using textual queries and other constraints.
 *

 *
 *

 * For more information about this service, see the API
 * Documentation
 *

 *
 * @author Google, Inc.
 */
class Freebase extends \Google\Service
{

  private $base_methods;

  /**
   * Constructs the internal representation of the Freebase service.
   *
   * @param \Google\Client $client
   */
  public function __construct(\Google\Client $client)
  {
    parent::__construct($client);
    $this->servicePath = 'freebase/v1/';
    $this->version = 'v1';
    $this->serviceName = 'freebase';

    $this->base_methods = new \Google\Service\Resource(
        $this,
        $this->serviceName,
        '',
        array(
          'methods' => array(
            'reconcile' => array(
              'path' => 'reconcile',
              'httpMethod' => 'GET',
              'parameters' => array(
                'lang' => array(
                  'location' => 'query',
                  'type' => 'string',
                  'repeated' => true,
                ),
                'confidence' => array(
                  'location' => 'query',
                  'type' => 'number',
                ),
                'name' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'kind' => array(
                  'location' => 'query',
                  'type' => 'string',
                  'repeated' => true,
                ),
                'prop' => array(
                  'location' => 'query',
                  'type' => 'string',
                  'repeated' => true,
                ),
                'limit' => array(
                  'location' => 'query',
                  'type' => 'integer',
                ),
              ),
            ),'search' => array(
              'path' => 'search',
              'httpMethod' => 'GET',
              'parameters' => array(
                'domain' => array(
                  'location' => 'query',
                  'type' => 'string',
                  'repeated' => true,
                ),
                'help' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'query' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'scoring' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'cursor' => array(
                  'location' => 'query',
                  'type' => 'integer',
                ),
                'prefixed' => array(
                  'location' => 'query',
                  'type' => 'boolean',
                ),
                'exact' => array(
                  'location' => 'query',
                  'type' => 'boolean',
                ),
                'mid' => array(
                  'location' => 'query',
                  'type' => 'string',
                  'repeated' => true,
                ),
                'encode' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'type' => array(
                  'location' => 'query',
                  'type' => 'string',
                  'repeated' => true,
                ),
                'as_of_time' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'stemmed' => array(
                  'location' => 'query',
                  'type' => 'boolean',
                ),
                'format' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'spell' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'with' => array(
                  'location' => 'query',
                  'type' => 'string',
                  'repeated' => true,
                ),
                'lang' => array(
                  'location' => 'query',
                  'type' => 'string',
                  'repeated' => true,
                ),
                'indent' => array(
                  'location' => 'query',
                  'type' => 'boolean',
                ),
                'filter' => array(
                  'location' => 'query',
                  'type' => 'string',
                  'repeated' => true,
                ),
                'callback' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'without' => array(
                  'location' => 'query',
                  'type' => 'string',
                  'repeated' => true,
                ),
                'limit' => array(
                  'location' => 'query',
                  'type' => 'integer',
                ),
                'output' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'mql_output' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
              ),
            ),
          )
        )
    );
  }
  /**
   * Reconcile entities to Freebase open data. (reconcile)
   *
   * @param array $optParams Optional parameters.
   *
   * @opt_param string lang
   * Languages for names and values. First language is used for display. Default is 'en'.
   * @opt_param float confidence
   * Required confidence for a candidate to match. Must be between .5 and 1.0
   * @opt_param string name
   * Name of entity.
   * @opt_param string kind
   * Classifications of entity e.g. type, category, title.
   * @opt_param string prop
   * Property values for entity formatted as
  :
   * @opt_param int limit
   * Maximum number of candidates to return.
   * @return \Google\Service\Freebase\ReconcileGet
   */
  public function reconcile($optParams = array())
  {
    $params = array();
    $params = array_merge($params, $optParams);
    return $this->base_methods->call('reconcile', array($params), "\Google\Service\Freebase\ReconcileGet");
  }
  /**
   * Search Freebase open data. (search)
   *
   * @param array $optParams Optional parameters.
   *
   * @opt_param string domain
   * Restrict to topics with this Freebase domain id.
   * @opt_param string help
   * The keyword to request help on.
   * @opt_param string query
   * Query term to search for.
   * @opt_param string scoring
   * Relevance scoring algorithm to use.
   * @opt_param int cursor
   * The cursor value to use for the next page of results.
   * @opt_param bool prefixed
   * Prefix match against names and aliases.
   * @opt_param bool exact
   * Query on exact name and keys only.
   * @opt_param string mid
   * A mid to use instead of a query.
   * @opt_param string encode
   * The encoding of the response. You can use this parameter to enable html encoding.
   * @opt_param string type
   * Restrict to topics with this Freebase type id.
   * @opt_param string asOfTime
   * A mql as_of_time value to use with mql_output queries.
   * @opt_param bool stemmed
   * Query on stemmed names and aliases. May not be used with prefixed.
   * @opt_param string format
   * Structural format of the json response.
   * @opt_param string spell
   * Request 'did you mean' suggestions
   * @opt_param string with
   * A rule to match against.
   * @opt_param string lang
   * The code of the language to run the query with. Default is 'en'.
   * @opt_param bool indent
   * Whether to indent the json results or not.
   * @opt_param string filter
   * A filter to apply to the query.
   * @opt_param string callback
   * JS method name for JSONP callbacks.
   * @opt_param string without
   * A rule to not match against.
   * @opt_param int limit
   * Maximum number of results to return.
   * @opt_param string output
   * An output expression to request data from matches.
   * @opt_param string mqlOutput
   * The MQL query to run againist the results to extract more data.
   */
  public function search($optParams = array())
  {
    $params = array();
    $params = array_merge($params, $optParams);
    return $this->call('search', array($params));
  }
}


text:
(function( angular ) {
    'use strict';

    /**
     * @ngdoc function
     * @name test.controller
     * @description
     * # testCtrl
     * Controller of the test
     */
    class testController {
        constructor() {}
    }

    testController.$inject = [];

    angular
    .module('acx.test.controllers')
        .controller('testController', testController );

})( this.angular );


text:
package net.mindengine.jeremy.client;

import java.util.Map;

public class HttpResponse {

    private String url;
    private int status;
    private String language;
    private Map<String, String> headers;

    private byte[] bytes;

    public void setStatus(int status) {
        this.status = status;
    }
    public int getStatus() {
        return status;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getUrl() {
        return url;
    }
    public byte[] getBytes() {
        return bytes;
    }
    public void setBytes(byte[] bytes) {
        this.bytes = bytes;
    }
    public String getLanguage() {
        return language;
    }
    public void setLanguage(String language) {
        this.language = language;
    }
    public Map<String, String> getHeaders() {
        return headers;
    }
    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }
}


text:
#include "libs/base/random.h"

#include <cstddef>
#include <cstdio>
#include <functional>

#include "libs/base/queue_task.h"
#include "libs/base/tasks.h"
#include "third_party/freertos_kernel/include/semphr.h"
#include "third_party/nxp/rt1176-sdk/devices/MIMXRT1176/drivers/cm7/fsl_cache.h"
#include "third_party/nxp/rt1176-sdk/devices/MIMXRT1176/drivers/fsl_caam.h"

namespace coralmicro {
namespace {
struct Response {
  bool success;
};

struct Request {
  void* out;
  size_t len;
  std::function<void(Response)> callback;
};

constexpr char kRandomTaskName[] = "random_task";

class Random : public QueueTask<Request, Response, kRandomTaskName,
                                configMINIMAL_STACK_SIZE * 10,
                                kRandomTaskPriority, /*QueueLength=*/4> {
 public:
  static Random* GetSingleton() {
    static Random random;
    return &random;
  }

  bool Generate(void* out, size_t len) {
    Request req;
    req.out = out;
    req.len = len;
    Response resp = SendRequest(req);
    return resp.success;
  }

 private:
  void RequestHandler(Request* req) override {
    Response resp;
    caam_handle_t handle;
    handle.jobRing = kCAAM_JobRing0;
    status_t status =
        CAAM_RNG_GetRandomData(CAAM, &handle, kCAAM_RngStateHandle0, req->out,
                               req->len, kCAAM_RngDataAny, nullptr);
    DCACHE_InvalidateByRange(reinterpret_cast<uint32_t>(req->out), req->len);
    resp.success = (status == kStatus_Success);
    req->callback(resp);
  }
};

}  // namespace

void RandomInit() { Random::GetSingleton()->Init(); }

bool RandomGenerate(void* buf, size_t size) {
  return Random::GetSingleton()->Generate(buf, size);
}

}  // namespace coralmicro


text:
package info.puzz.a10000sentences.utils;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.LabeledIntent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.Toast;

import org.apache.commons.lang3.*;

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

import info.puzz.a10000sentences.R;

public final class TranslateUtils {

    private static final String TAG = TranslateUtils.class.getSimpleName();

    private TranslateUtils() throws Exception {
        throw new Exception();
    }

    public static void translate(Activity activity, String text) {

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PROCESS_TEXT);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_PROCESS_TEXT, text);

        String packageName = getTranslatePackageName(activity, intent);
        if (org.apache.commons.lang3.StringUtils.isEmpty(packageName)) {
            fallback(activity, text);
            return;
        }
        intent.setPackage(packageName);

        try {
            activity.startActivity(intent);
        } catch (Throwable e) {
            Log.e(TAG, e.getMessage(), e);
            fallback(activity, text);
        }
    }

    private static void fallback(Activity activity, String text) {
        Toast.makeText(activity, R.string.not_translate_app_found, Toast.LENGTH_SHORT).show();
        // If the user has "Tap to translate enabled", at least that will work:
        ShareUtils.copyToClipboard(activity, text);
    }

    private static String getTranslatePackageName(Activity activity, Intent intent) {
        return "com.google.android.apps.translate";
/*        PackageManager pm = activity.getPackageManager();
        List<ResolveInfo> resInfo = pm.queryIntentActivities(intent, 0);
        List<LabeledIntent> intentList = new ArrayList<>();
        for (ResolveInfo ri : resInfo) {
            if(ri.activityInfo.packageName.contains("com.google.android") && ri.activityInfo.packageName.endsWith(".translate")) {
                return ri.activityInfo.packageName;
            }
        }
        return null;*/
    }
}


text:
package org.apache.calcite.rel.rules;

import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptRule;
import org.apache.calcite.plan.RelOptRuleCall;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.Aggregate;
import org.apache.calcite.rel.core.Join;
import org.apache.calcite.rel.core.JoinInfo;
import org.apache.calcite.rel.core.Project;
import org.apache.calcite.rel.core.RelFactories;
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.tools.RelBuilder;
import org.apache.calcite.tools.RelBuilderFactory;
import org.apache.calcite.util.ImmutableBitSet;
import org.apache.calcite.util.ImmutableIntList;

import com.google.common.base.Predicate;
import com.google.common.collect.Lists;

import java.util.List;

/**
 * Planner rule that creates a {@code SemiJoinRule} from a
 * {@link org.apache.calcite.rel.core.Join} on top of a
 * {@link org.apache.calcite.rel.logical.LogicalAggregate}.
 */
public class SemiJoinRule extends RelOptRule {
  private static final Predicate<Join> IS_LEFT_OR_INNER =
      new Predicate<Join>() {
        public boolean apply(Join input) {
          switch (input.getJoinType()) {
          case LEFT:
          case INNER:
            return true;
          default:
            return false;
          }
        }
      };

  public static final SemiJoinRule INSTANCE =
      new SemiJoinRule(Project.class, Join.class, Aggregate.class,
          RelFactories.LOGICAL_BUILDER, "SemiJoinRule");

  /** Creates a SemiJoinRule. */
  public SemiJoinRule(Class<Project> projectClass, Class<Join> joinClass,
      Class<Aggregate> aggregateClass, RelBuilderFactory relBuilderFactory,
      String description) {
    super(
        operand(projectClass,
            some(
                operand(joinClass, null, IS_LEFT_OR_INNER,
                    some(operand(RelNode.class, any()),
                        operand(aggregateClass, any()))))),
        relBuilderFactory, description);
  }

  @Override public void onMatch(RelOptRuleCall call) {
    final Project project = call.rel(0);
    final Join join = call.rel(1);
    final RelNode left = call.rel(2);
    final Aggregate aggregate = call.rel(3);
    final RelOptCluster cluster = join.getCluster();
    final RexBuilder rexBuilder = cluster.getRexBuilder();
    final ImmutableBitSet bits =
        RelOptUtil.InputFinder.bits(project.getProjects(), null);
    final ImmutableBitSet rightBits =
        ImmutableBitSet.range(left.getRowType().getFieldCount(),
            join.getRowType().getFieldCount());
    if (bits.intersects(rightBits)) {
      return;
    }
    final JoinInfo joinInfo = join.analyzeCondition();
    if (!joinInfo.rightSet().equals(
        ImmutableBitSet.range(aggregate.getGroupCount()))) {
      // Rule requires that aggregate key to be the same as the join key.
      // By the way, neither a super-set nor a sub-set would work.
      return;
    }
    if (!joinInfo.isEqui()) {
      return;
    }
    final RelBuilder relBuilder = call.builder();
    relBuilder.push(left);
    switch (join.getJoinType()) {
    case INNER:
      final List<Integer> newRightKeyBuilder = Lists.newArrayList();
      final List<Integer> aggregateKeys = aggregate.getGroupSet().asList();
      for (int key : joinInfo.rightKeys) {
        newRightKeyBuilder.add(aggregateKeys.get(key));
      }
      final ImmutableIntList newRightKeys = ImmutableIntList.copyOf(newRightKeyBuilder);
      relBuilder.push(aggregate.getInput());
      final RexNode newCondition =
          RelOptUtil.createEquiJoinCondition(relBuilder.peek(2, 0),
              joinInfo.leftKeys, relBuilder.peek(2, 1), newRightKeys,
              rexBuilder);
      relBuilder.semiJoin(newCondition);
      break;

    case LEFT:
      // The right-hand side produces no more than 1 row (because of the
      // Aggregate) and no fewer than 1 row (because of LEFT), and therefore
      // we can eliminate the semi-join.
      break;

    default:
      throw new AssertionError(join.getJoinType());
    }
    relBuilder.project(project.getProjects(), project.getRowType().getFieldNames());
    call.transformTo(relBuilder.build());
  }
}

// End SemiJoinRule.java


text:
package org.jetbrains.jps.builders;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.module.JpsModule;

import java.util.Collection;
import java.util.List;

/**
 * Allows to enumerate all build targets existing in a project.
 *
 * @author Eugene Zhuravlev
 * @since 10/27/12
 */
public interface BuildTargetRegistry {
  /**
   * Returns all build targets of a specified type.
   */
  @NotNull
  <T extends BuildTarget<?>>
  List<T> getAllTargets(@NotNull BuildTargetType<T> type);

  /**
   * Returns all build targets existing in the project.
   */
  @NotNull
  List<BuildTarget<?>> getAllTargets();

  enum ModuleTargetSelector {
    PRODUCTION, TEST, ALL
  }

  /**
   * Returns the module-based targets of the specified module that have the specified type.
   */
  @NotNull
  Collection<ModuleBasedTarget<?>> getModuleBasedTargets(@NotNull JpsModule module, @NotNull ModuleTargetSelector selector);
}


text:
var gulp       = require('gulp'),
    plumber    = require('gulp-plumber'),
    watch      = require('gulp-watch'),
    jade       = require('gulp-jade'),
    minifyHTML = require('gulp-minify-html'),
    react      = require('gulp-react'),
    uglify     = require('gulp-uglify'),
    sass       = require('gulp-sass'),
    minifyCSS  = require('gulp-minify-css'),
    nodemon    = require('nodemon');

//////////
// Code //

////
// Deploying

// Deploying Jade.
gulp.task('deploy-jade', function () {
  gulp.src('src/templates/jade/**')
    .pipe(plumber())
    .pipe(jade({}))
    .pipe(minifyHTML())
    .pipe(gulp.dest('src/static/html/'));
});

// Deploying JSX.a
gulp.task('deploy-jsx', function () {
  gulp.src('src/templates/jsx/**')
    .pipe(plumber())
    .pipe(react({}))
    .pipe(uglify())
    .pipe(gulp.dest('src/static/js/'));
});

// Deploying SCSS.
gulp.task('deploy-scss', function () {
  gulp.src('src/templates/scss/**')
    .pipe(plumber())
    .pipe(sass())
    .pipe(minifyCSS())
    .pipe(gulp.dest('src/static/css'));
});

// Deploying the templates.
gulp.task('deploy-templates', ['deploy-jade', 'deploy-jsx', 'deploy-scss'], function () { });

// Deploying the front-end dependencies.
gulp.task('deploy-dependencies', function () {
  // Deploying React.
  gulp.src('bower_components/react/react.min.js')
    .pipe(gulp.dest('src/static/js/'));

  // Deploying Bootstrap.
  gulp.src('bower_components/bootstrap/dist/css/bootstrap.min.css')
    .pipe(gulp.dest('src/static/css/'));

  gulp.src('bower_components/bootstrap/dist/fonts/*')
    .pipe(gulp.dest('src/static/fonts/'));

  // Deploying cookie.js
  gulp.src('bower_components/cookies-js/dist/cookies.min.js')
    .pipe(gulp.dest('src/static/js'));
});

// Deploying everything.
gulp.task('deploy', ['deploy-dependencies', 'deploy-templates'], function () { });

////
// Watching

// Watching the project.
gulp.task('watch-project', function () {
  nodemon({
    script: 'src/app.js',
    ext   : 'js',
    ignore: ['src/static/', 'src/templates/jsx/', 'gulpfile.js']
  }).on('restart', function () {
    console.log('Server restarted...');
  }).on('crash', function () {
    console.log('Server crashed. It will restart upon the next change!');
  });
});

// Watching the templates.
gulp.task('watch-templates', function () {
  gulp.watch('src/templates/jade/**', ['deploy-jade']);
  gulp.watch('src/templates/scss/**', ['deploy-scss']);
  gulp.watch('src/templates/jsx/**', ['deploy-jsx']);
});

// Watching the whole project for updates.
gulp.task('watch', ['watch-project', 'watch-templates'], function () { });

////
// Default

// Defaults to first deploying the dependencies and then watching the project
// for updates.
gulp.task('default', ['deploy', 'watch']);


text:
package pl.mmorpg.prototype.clientservercommon.packets.quest.event;

import lombok.Data;
import pl.mmorpg.prototype.clientservercommon.packets.quest.QuestStateInfoPacket;
import pl.mmorpg.prototype.clientservercommon.registering.Registerable;

@Registerable
@Data
public class QuestAcceptedEventPacket extends EventPacket
{
	private QuestStateInfoPacket questStatePacket;
}