text:
"""
crawler.py
~~~~~~~~~~~~~

主要模块,爬虫的具体实现。
"""
import re
import time
import logging
import threading
import traceback
from hashlib import md5
from bs4 import BeautifulSoup
from datetime import datetime
from collections import deque
from locale import getdefaultlocale
from urlparse import urljoin,urlparse

from database import Database
from webPage import WebPage
from threadPool import ThreadPool

log = logging.getLogger('spider')

class Crawler(threading.Thread):

    def __init__(self, args, queue):
        threading.Thread.__init__(self)
        #指定网页深度
        self.depth = args['depth']
        #标注初始爬虫深度,从1开始
        self.currentDepth = 1
        #指定关键词,使用console的默认编码来解码
        self.keyword = args['keyword'].decode(getdefaultlocale()[1])
        #数据库
        self.database =  Database(db="bt_tornado")
        #线程池,指定线程数
        self.threadPool = ThreadPool(args['threadNum'])
        #已访问的链接
        self.visitedHrefs = set()
        #待访问的链接
        self.unvisitedHrefs = deque()
        #添加待访问的链接
        for url in args['url']:
            self.unvisitedHrefs.append(url)
        #标记爬虫是否开始执行任务
        self.isCrawling = False
        # allow or deny crawl url
        self.entryFilter = args['entryFilter']
        # allow to output back url
        self.yieldFilter = args['yieldFilter']
        #
        self.callbackFilter = args['callbackFilter']
        #
        self.db = args['db']
        self.collection = args['collection']
        # communication queue
        self.queue = queue

    def run(self):
        print '\nStart Crawling\n'
        if not self._isDatabaseAvaliable():
            print 'Error: Unable to open database file.\n'
        else:
            self.isCrawling = True
            self.threadPool.startThreads()
            while self.currentDepth < self.depth+1:
                #分配任务,线程池并发下载当前深度的所有页面(该操作不阻塞)
                self._assignCurrentDepthTasks ()
                #等待当前线程池完成所有任务,当池内的所有任务完成时,即代表爬完了一个网页深度
                #self.threadPool.taskJoin()可代替以下操作,可无法Ctrl-C Interupt
                while self.threadPool.getTaskLeft():
                    time.sleep(8)
                print 'Depth %d Finish. Totally visited %d links. \n' % (
                    self.currentDepth, len(self.visitedHrefs))
                log.info('Depth %d Finish. Total visited Links: %d\n' % (
                    self.currentDepth, len(self.visitedHrefs)))
                self.currentDepth += 1
            self.stop()

    def stop(self):
        self.isCrawling = False
        self.threadPool.stopThreads()
        self.database.close()
        #use queue to communicate between threads
        self.queue.get()
        self.queue.task_done()

    def getAlreadyVisitedNum(self):
        #visitedHrefs保存已经分配给taskQueue的链接,有可能链接还在处理中。
        #因此真实的已访问链接数为visitedHrefs数减去待访问的链接数
        return len(self.visitedHrefs) - self.threadPool.getTaskLeft()

    def _assignCurrentDepthTasks(self):
        while self.unvisitedHrefs:
            url = self.unvisitedHrefs.popleft()
            if not self.__entry_filter(url):
                self.visitedHrefs.add(url)
                continue
            #向任务队列分配任务
            self.threadPool.putTask(self._taskHandler, url)
            #标注该链接已被访问,或即将被访问,防止重复访问相同链接
            self.visitedHrefs.add(url)

    def _callback_filter(self, webPage):
        #parse the web page to do sth
        url , pageSource = webPage.getDatas()
        for tmp  in self.callbackFilter['List']:
            if re.compile(tmp,re.I|re.U).search(url):
                self.callbackFilter['func'](webPage)

    def _taskHandler(self, url):
        #先拿网页源码,再保存,两个都是高阻塞的操作,交给线程处理
        webPage = WebPage(url)
        tmp = webPage.fetch()
        if tmp:
            self._callback_filter(webPage)
            self._saveTaskResults(webPage)
            self._addUnvisitedHrefs(webPage)

    def _saveTaskResults(self, webPage):
        url, pageSource = webPage.getDatas()
        _id = md5(url).hexdigest()
        try:
            if self.__yield_filter(url):
                query = {"id": _id}
                document = {"id": _id, "url":url, "createTime": datetime.now()}
                self.database.saveData(query=query, collection=self.collection, document=document)
        except Exception, e:
            log.error(' URL: %s ' % url + traceback.format_exc())

    def _addUnvisitedHrefs(self, webPage):
        '''添加未访问的链接。将有效的url放进UnvisitedHrefs列表'''
        #对链接进行过滤:1.只获取http或https网页;2.保证每个链接只访问一次
        url, pageSource = webPage.getDatas()
        hrefs = self._getAllHrefsFromPage(url, pageSource)
        for href in hrefs:
            if self._isHttpOrHttpsProtocol(href):
                if not self._isHrefRepeated(href):
                    self.unvisitedHrefs.append(href)

    def _getAllHrefsFromPage(self, url, pageSource):
        '''解析html源码,获取页面所有链接。返回链接列表'''
        hrefs = []
        soup = BeautifulSoup(pageSource)
        results = soup.find_all('a',href=True)
        for a in results:
            #必须将链接encode为utf8, 因为中文文件链接如 http://aa.com/文件.pdf
            #在bs4中不会被自动url编码,从而导致encodeException
            href = a.get('href').encode('utf8')
            if not href.startswith('http'):
                href = urljoin(url, href)#处理相对链接的问题
            hrefs.append(href)
        return hrefs

    def _isHttpOrHttpsProtocol(self, href):
        protocal = urlparse(href).scheme
        if protocal == 'http' or protocal == 'https':
            return True
        return False

    def _isHrefRepeated(self, href):
        if href in self.visitedHrefs or href in self.unvisitedHrefs:
            return True
        return False

    def _isDatabaseAvaliable(self):
        if self.database.isConn():
            return True
        return False

    def __entry_filter(self, checkURL):
        '''
        入口过滤器
        决定了爬虫可以进入哪些url指向的页面进行抓取

        @param checkURL: 交给过滤器检查的url
        @type checkURL: 字符串

        @return: 通过检查则返回True,否则返回False
        @rtype: 布尔值
        '''
        # 如果定义了过滤器则检查过滤器
        if self.entryFilter:
            if self.entryFilter['Type'] == 'allow':        # 允许模式,只要满足一个就允许,否则不允许
                result = False
                for rule in self.entryFilter['List']:
                    pattern = re.compile(rule, re.I | re.U)
                    if pattern.search(checkURL):
                        result = True
                        break
                return result
            elif self.entryFilter['Type'] == 'deny':        # 排除模式,只要满足一个就不允许,否则允许
                result = True
                for rule in self.entryFilter['List']:
                    pattern = re.compile(rule, re.I | re.U)
                    if pattern.search(checkURL):
                        result = False
                        break
                return result

        # 没有过滤器则默认允许
        return True

    def __yield_filter(self, checkURL):
        '''
        生成过滤器
        决定了爬虫可以返回哪些url

        @param checkURL: 交给过滤器检查的url
        @type checkURL: 字符串

        @return: 通过检查则返回True,否则返回False
        @rtype: 布尔值
        '''
        # 如果定义了过滤器则检查过滤器
        if self.yieldFilter:
            if self.yieldFilter['Type'] == 'allow':        # 允许模式,只要满足一个就允许,否则不允许
                result = False
                for rule in self.yieldFilter['List']:
                    pattern = re.compile(rule, re.I | re.U)
                    if pattern.search(checkURL):
                        result = True
                        break
                return result
            elif self.yieldFilter['Type'] == 'deny':        # 排除模式,只要满足一个就不允许,否则允许
                result = True
                for rule in self.yieldFilter['List']:
                    pattern = re.compile(rule, re.I | re.U)
                    if pattern.search(checkURL):
                        result = False
                        break
                return result

        # 没有过滤器则默认允许
        return True


text:
var five = require("johnny-five");
var board = new five.Board();

board.on("ready", function() {
  var accelerometer = new five.Accelerometer({
    controller: "MPU6050"
  });

  accelerometer.on("change", function() {
    console.log("accelerometer");
    console.log("  x            : ", this.x);
    console.log("  y            : ", this.y);
    console.log("  z            : ", this.z);
    console.log("  pitch        : ", this.pitch);
    console.log("  roll         : ", this.roll);
    console.log("  acceleration : ", this.acceleration);
    console.log("  inclination  : ", this.inclination);
    console.log("  orientation  : ", this.orientation);
    console.log("--------------------------------------");
  });
});

redpajama_set_name: RedPajamaGithub


text:
require 'rubygems'
require 'bundler/setup'

require 'rdf'
require 'rdf/ntriples'
require 'csv'
require 'json'

raise "expects args: <nt filename> <default neo4j node label> <options>" if ARGV.count != 3

# first arg
nt_filename = ARGV[0]
m = nt_filename.match(/^(..*)\.nt$/)
basename = m[1]
raise "expects a .nt file!" unless m

# second arg
default_node_label = ARGV[1]

# third arg
begin
  options = JSON.parse ARGV[2]
rescue
  raise "Third arg must be valid json!"
end
label_per_uri_prefix = options['label_per_uri_prefix'] || {}

nodes_csv = CSV.open "#{basename}_neo4j_nodes.csv", 'wb'
edges_csv = CSV.open "#{basename}_neo4j_edges.csv", 'wb'

nodes_csv << ['URI:ID', 'name', ':LABEL']
edges_csv << [':START_ID', 'uri', ':END_ID', ':TYPE']

Neo4jCSVElem = Struct.new :uri, :name
written_node_uris = {}

RDF::Reader.open(nt_filename) do |reader|
  reader.each_statement do |statement|
    subject, predicate, object = statement.to_a.map do |uri|
      name = uri.to_s.gsub(/.*[\/#]([^\/#]*)$/, '\1')
      name = uri if name.empty?
      Neo4jCSVElem.new uri.to_s, name
    end

    [subject, object].each do |node|
      next if written_node_uris.include? node.uri
      labels = label_per_uri_prefix.map do |uri_prefix, label|
        label if node.uri.start_with? uri_prefix
      end.compact
      labels << default_node_label if labels.empty?
      nodes_csv << [node.uri, node.name, labels.join(';')]
      written_node_uris[node.uri] = true
    end

    edges_csv << [subject.uri, predicate.uri, object.uri, predicate.name.upcase]
  end
end

nodes_csv.close
edges_csv.close

puts "Output: #{nodes_csv.path}"
puts "Output: #{edges_csv.path}"


text:
using System;

namespace GameUtils
{
    public class BasicGraphCost : IGraphCostCalculator
    {
        public double CalculateGraphCost(GridNode from, GridNode to) {
            return IsDiagonal(from, to) ? 1.414213562 : 1;
        }

        private bool IsDiagonal(GridNode nodeA, GridNode nodeB) {
            return nodeA.X != nodeB.X && nodeA.Y != nodeB.Y;
        }
    }
}


text:
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace TCP_Client
{
    internal class Program
    {
        private static readonly byte[] Buffer = new byte[1024];

        private static void Main()
        {
            try
            {
                Uri uri = new Uri("http://127.0.0.1:9876");

                //①创建一个Socket
                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //②连接到指定服务器的指定端口
                socket.Connect("127.0.0.1", 4433);
                WriteLine("Client: Connect to server success!", ConsoleColor.White);

                //③实现异步接受消息的方法 客户端不断监听消息
                socket.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);

                //④接受用户输入,将消息发送给服务器端
                while (true)
                {
                    var message = "zheis11111" + socket.RemoteEndPoint; //System.IO.File.ReadAllText("d:\\text.txt"); //Console.ReadLine();
                    if (message != null)
                    {
                        var outputBuffer = new Byte[1] ;//Encoding.UTF8.GetBytes(message);
                        socket.BeginSend(outputBuffer, 0, outputBuffer.Length, SocketFlags.None, null, null);
                    }
                    Thread.Sleep(20);
                }
            }
            catch (Exception ex)
            {
                WriteLine("Client: Error " + ex.Message, ConsoleColor.Red);
            }
            finally
            {
                Console.Read();
            }
        }

        // 接收信息
        public static void ReceiveMessage(IAsyncResult ar)
        {
            try
            {
                var socket = ar.AsyncState as Socket;

                //方法参考:http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.endreceive.aspx
                if (socket != null)
                {
                    var length = socket.EndReceive(ar);
                    var message = Encoding.ASCII.GetString(Buffer, 0, length);
                    WriteLine(message, ConsoleColor.White);
                }

                //接收下一个消息
                if (socket != null)
                {
                    socket.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
                }
            }
            catch (Exception ex)
            {
                WriteLine(ex.Message, ConsoleColor.Red);
            }
        }

        public static void WriteLine(string str, ConsoleColor color)
        {
            Console.ForegroundColor = color;
            Console.WriteLine("[{0:MM-dd HH:mm:ss}] {1}", DateTime.Now, str);
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Apisearch\Tests\Query;

use Apisearch\Query\Filter;
use Apisearch\Query\ScoreStrategies;
use Apisearch\Query\ScoreStrategy;
use PHPUnit\Framework\TestCase;

/**
 * Class ScoreStrategiesTest.
 */
class ScoreStrategiesTest extends TestCase
{
    /**
     * Test empty.
     */
    public function testEmpty()
    {
        $scoreStrategies = ScoreStrategies::createEmpty();
        $this->assertEquals(
            ScoreStrategies::SUM,
            $scoreStrategies->getScoreMode()
        );
        $this->assertEquals(
            [],
            $scoreStrategies->getScoreStrategies()
        );
    }

    /**
     * Test empty.
     */
    public function testMultiple()
    {
        $scoreStrategies = ScoreStrategies::createEmpty(ScoreStrategies::AVG);
        $scoreStrategies
            ->addScoreStrategy(ScoreStrategy::createDefault())
            ->addScoreStrategy(ScoreStrategy::createDefault())
            ->addScoreStrategy(ScoreStrategy::createDefault());

        $this->assertEquals(
            ScoreStrategies::AVG,
            $scoreStrategies->getScoreMode()
        );
        $this->assertCount(
            3,
            $scoreStrategies->getScoreStrategies()
        );
    }

    /**
     * Test to array and from array.
     */
    public function testArrayTransformation()
    {
        $scoreStrategies = ScoreStrategies::createEmpty(ScoreStrategies::AVG);
        $scoreStrategies
            ->addScoreStrategy(ScoreStrategy::createDefault())
            ->addScoreStrategy(ScoreStrategy::createDefault())
            ->addScoreStrategy(ScoreStrategy::createWeightFunction(1.1, Filter::create('a', ['b'], Filter::MUST_ALL, Filter::TYPE_FIELD)))
            ->addScoreStrategy(ScoreStrategy::createFieldBoosting('field1', 1.1, 2.2, 'avg', 4.4, Filter::create('a2', ['b2'], Filter::MUST_ALL, Filter::TYPE_FIELD), 'none'))
            ->addScoreStrategy(ScoreStrategy::createDecayFunction('gauss', 'a1', 'a2', 'a3', 'a4', 1.1, 2.2, Filter::create('a3', ['b3'], Filter::MUST_ALL, Filter::TYPE_FIELD), 'kk'));
        $scoreStrategiesAsArray = $scoreStrategies->toArray();
        $this->assertCount(5, $scoreStrategies->getScoreStrategies());
        $covertedScoreStrategies = ScoreStrategies::createFromArray($scoreStrategiesAsArray);

        $this->assertEquals(
            $scoreStrategiesAsArray,
            $covertedScoreStrategies->toArray()
        );

        $this->assertCount(5, $covertedScoreStrategies->getScoreStrategies());
    }
}


text:
package com.iniesta.ardillo.services;

public class CreationDatabaseService {

}


text:
package markdown

import "regexp"

// MarkdownRe matches front matter and content see https://regex101.com/r/pOZOTG/1
var MarkdownRe = regexp.MustCompile(`(?m)^(?s:(^---\n)(.*?)(^---(?:\n|$))(.*))$`)

// FrontMatterRe matches front matter, see https://regex101.com/r/bXta8n/1
var FrontMatterRe = regexp.MustCompile(`([^:.]*)\s*:\s*(.*)\n?`)

// ImageRe matches markdown images, see https://regex101.com/r/Xen6Cp/3
var ImageRe = regexp.MustCompile(`!\[(.*)\]\(({{.+}})?([^)\s]*\/)*([^)]*\.(png|jpg|jpeg|gif|svg))\)(\{:\s?(.*)\})?(\{:\s?(.*)\})?(\n[\*_](Figure[^\*\n]+)[\*_])?`)

// HtmlImageRe matches html images, see https://regex101.com/r/Vepscq/1
var HtmlImageRe = regexp.MustCompile(`<img([^>]+)/>`)

// FigureRe matches a figure caption that is preceded by a blank line https://regex101.com/r/fWZxR0/2
var FigureRe = regexp.MustCompile(`\n{2,}(\*Figure([^\*]+)\*)`)

// SourceRe matches the src attribute of images, see https://regex101.com/r/UfNttw/1
var SourceRe = regexp.MustCompile(`(src)="({{.+}})?([^"\s]*\/)*([^"]*\.(png|jpg|jpeg|gif|svg))"`)

// AttributesRe matches html attributes, see https://regex101.com/r/FgkHDJ/1
var AttributesRe = regexp.MustCompile(`(\w+)="([^\"]+)"`)

// CalloutRe matches callouts https://regex101.com/r/8CnxPG/1
var CalloutRe = regexp.MustCompile(`(?ms)<div class="presidium-([\w\-]+)">\s*(<span>(.*?)</span>)?(.*?)</div>`)

// TooltipRe matches tooltips, see https://regex101.com/r/McE770/1
var TooltipRe = regexp.MustCompile(`(?m)\[([^(.]*)]\(({{.+}})?([^)\s]*?)\s*'presidium-tooltip'\)`)

// TableBodyRe matches tables, see https://regex101.com/r/K9xbsc/1
var TableBodyRe = regexp.MustCompile(`(?:\|[^\n]+\|?\r?\n?\s*){2,}`)

// TableHeaderRe matches the header section of a table, see https://regex101.com/r/zeaXvT/1
var TableHeaderRe = regexp.MustCompile(`(\|[^\n]+\|?\r?\n)?(\s*(?:\|:?\s*[-]+:?\s*)+\|?)`)

// IfVariablesRe matches jekyll conditional logic https://regex101.com/r/n1vbLY/1
var IfVariablesRe = regexp.MustCompile(`(?msU){% if ([^}]*?) %}(.+)({% elsif ([^}]*?) %}(.+))?({% else %}(.+))?{% endif %}`)

// IfConditionRe matches the entire if condition, see https://regex101.com/r/BHIU0V/1
var IfConditionRe = regexp.MustCompile(`(?ms)(and|or)?\s??site.(\w+) ([!=]=) "(\w+)"`)

// IfConditionShortcodeRe matches individual conditions, see https://regex101.com/r/BvAtyC/1
var IfConditionShortcodeRe = regexp.MustCompile(`(?ms)site.(\w+) == "(\w+)"`)

// ContainsShortcodeRe matches shortcodes, see https://regex101.com/r/aKgUVk/1
var ContainsShortcodeRe = regexp.MustCompile(`(?ms){{[%<].*?[%>]}}`)

// CommentRe matches comments, see https://regex101.com/r/31XAPX/1
var CommentRe = regexp.MustCompile(`(?ms){% comment %}(.*?){% endcomment %}`)

// EmptyLineRe matches empty lines, see https://regex101.com/r/rNxkKo/3
var EmptyLineRe = regexp.MustCompile(`(?m)^(?:[\t ]*(?:\r?\n|\r))+`)

// WeightAndSlugRe matches the weight and slug in a filename, see https://regex101.com/r/DZmKgp/2
var WeightAndSlugRe = regexp.MustCompile(`((([\d.]+)([a-z]?))[-_])?(.+?)(\.[^.\s]+)?$`)

// WeightRe matches the weight in a filename, see https://regex101.com/r/90itMQ/1
var WeightRe = regexp.MustCompile(`^([\d.]+)([a-z]?)[-_]`)

// SpaceRe matches one or more spaces, see https://regex101.com/r/rRXM3s/1
var SpaceRe = regexp.MustCompile(`\s+`)


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:ns1="urn:oasis:names:tc:xliff:document:1.2">
    <!-- From: file:/tmp/tmp-deduplicated7925291612035517390/blaze-out/gcc-4.X.Y-crosstool-v18-hybrid-grtev4-k8-opt/genfiles/java/com/google/android/gmscore/integ/client/common/res/values-gl/strings.xml -->
    <eat-comment/>
    <string msgid="9089562800660647919" name="common_google_play_services_unknown_issue">"<ns1:g id="APP_NAME">%1$s</ns1:g> ten problemas cos servizos de Google Play. Se o problema continúa, ponte en contacto co programador para obter axuda."</string>
</resources>


text:
"""
A set of functions required to pre-process DAYSIM simulation input files
"""

# Common imports
import os
import re

# Custom imports
from pybps import util

# Handle Python 2/3 compatibility
from six.moves import configparser
import six

if six.PY2:
  ConfigParser = configparser.SafeConfigParser
else:
  ConfigParser = configparser.ConfigParser

def rotate_scene(model_abspath):
    """Rotate Radiance geometry in Daysim project"""

	# Get information from config file
    conf = SafeConfigParser()
    conf_file = os.path.join(os.path.abspath(os.path.dirname(__file__)),
        '..\config.ini')
    conf.read(conf_file)
    bin_dir = os.path.abspath(conf.get('DAYSIM', 'Bin_Dir'))
    rotatescene_path = os.path.join(bin_dir, 'rotate_scene.exe')

    # Call rotate_scene program
    cmd = [rotatescene_path, model_abspath]
    util.run_cmd(cmd)

    # Rename rotated .rad and .pts files
    work_dir = os.path.dirname(model_abspath)
    for root, dirs, files in os.walk(work_dir):
        for fname in files:
            if fname.endswith('rotated.rad') or fname.endswith('rotated.pts'):
                old = os.path.join(root, fname)
                new = os.path.join(root, fname[:-12])
                # Try to rename filename
                # Remove new_fname if already exists because os.rename can't
                # overwrite existing files on Windows
                try:
                    os.rename(old, new)
                except WindowsError:
                    os.remove(new)
                    os.rename(old, new)

def radfiles2daysim(model_abspath):
    """Call radfiles2daysim program to convert source rad file to
    daysim material and geometry rad files"""

	# Get information from config file
    conf = SafeConfigParser()
    conf_file = os.path.join(os.path.abspath(os.path.dirname(__file__)),
        '..\config.ini')
    conf.read(conf_file)
    bin_dir = os.path.abspath(conf.get('DAYSIM', 'Bin_Dir'))
    radfiles2daysim_path = os.path.join(bin_dir, 'radfiles2daysim.exe')

    # Call radfiles2daysim program
    cmd = [radfiles2daysim_path, model_abspath, '-g', '-m', '-d']
    util.run_cmd(cmd)


text:
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import AbstractUser

class Info():
	''' This class is used to pass info to the pages'''
	def __init__(self, key, value, edit):
		self.key = key
		self.value = value
		self.edit = edit

class User(AbstractUser):
	''' This is the user class'''
	User._meta.get_field('email')._unique = True
	street = models.TextField(blank=True, null=True)
	city =  models.TextField(blank=True, null=True)
	state =  models.TextField(blank=True, null=True)
	zipcode =  models.TextField(blank=True, null=True)
	country =  models.TextField(blank=True, null=True)
	phone =  models.TextField(blank=True, null=True)
	salary = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	hourlypay = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	commissionRate = models.DecimalField(blank=True, null=True, decimal_places=3, max_digits=4)
	resetlink = models.TextField(blank=True, null=True)
	resetdate = models.DateTimeField(blank=True, null=True)
	confirmed =  models.NullBooleanField()
	confirmedlink = models.TextField(blank=True, null=True)
	confirmeddate = models.DateTimeField(blank=True, null=True)

	def __str__(self):
		return self.username + " | " + self.first_name + " " + self.last_name

	def info(self):
		''' This function displays most user info for use in the manager app '''
		info = []
		info.append(Info("Username", self.username, False))
		info.append(Info("Email", self.email, False))
		info.append(Info("First Name", self.first_name, True))
		info.append(Info("Last Name", self.last_name, True))
		info.append(Info("Street", self.street, True))
		info.append(Info("City", self.city, True))
		info.append(Info("State", self.state, True))
		info.append(Info("Zipcode", self.zipcode, True))
		info.append(Info("Phone", self.phone, True))
		info.append(Info("Staff", self.is_staff, True))
		info.append(Info("Admin", self.is_superuser, True))
		return info

	def customer(self):
		''' This function displays user info meant for customers in the shop app '''
		info = []
		info.append(Info("Username", self.username, False))
		info.append(Info("Email", self.email, False))
		info.append(Info("First Name", self.first_name, True))
		info.append(Info("Last Name", self.last_name, True))
		info.append(Info("Street", self.street, True))
		info.append(Info("City", self.city, True))
		info.append(Info("State", self.state, True))
		info.append(Info("Zipcode", self.zipcode, True))
		info.append(Info("Phone", self.phone, True))
		return info

class UserShipping(models.Model):
	''' This class holds shipping information for a customer '''
	user = models.ForeignKey(User)
	name = models.TextField(blank=True, null=True)
	street = models.TextField(blank=True, null=True)
	city =  models.TextField(blank=True, null=True)
	state =  models.TextField(blank=True, null=True)
	zipcode =  models.TextField(blank=True, null=True)

	def __str__(self):
		return self.user.username + ": " + self.name

	def customer(self):
		info = []
		info.append(Info("Name", self.name, False))
		info.append(Info("Street", self.street, True))
		info.append(Info("City", self.city, True))
		info.append(Info("State", self.state, True))
		info.append(Info("Zipcode", self.zipcode, True))
		return info

class CardType(models.Model):
	''' This class determines which types of cards the company accepts - Not editable through manager app should be added by admin '''
	name = models.TextField(blank=True, null=True)

	def __str__(self):
		return self.name

class UserBilling(models.Model):
	''' This class holds billing information for a customer '''
	user = models.ForeignKey(User)
	name = models.TextField(blank=True, null=True)
	cardtype = models.ForeignKey(CardType)
	number = models.TextField(blank=True, null=True)
	security = models.TextField(blank=True, null=True)
	street = models.TextField(blank=True, null=True)
	city =  models.TextField(blank=True, null=True)
	state =  models.TextField(blank=True, null=True)
	zipcode =  models.TextField(blank=True, null=True)
	expmonth = models.PositiveIntegerField()
	expyear = models.PositiveIntegerField()

class ShippingOption(models.Model):
	''' This class holds shipping options for the customer '''
	daystoarrive = models.PositiveIntegerField()
	price = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)

class TransactionType(models.Model):
	''' This holds the different transaction types availabe - Not editable in manager app because some code depends on certain naming conventions '''
	transactiontype = models.TextField(blank=True, null=True)

class Transaction(models.Model):
	''' This class holds a transaction '''
	buyer = models.ForeignKey(User)
	seller = models.ForeignKey(User, limit_choices_to={'is_staff': True}, related_name="trans_seller")
	transactiontype = models.ForeignKey(TransactionType)
	shipping = models.ForeignKey(UserShipping, blank=True, null=True)
	billing = models.ForeignKey(UserBilling)
	shippingoption = models.ForeignKey(ShippingOption, blank=True, null=True)
	subtotal = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	taxAmount = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	date = models.DateTimeField(blank=True, null=True)
	commissionNeeded = models.NullBooleanField()
	packed = models.NullBooleanField()

	def __str__(self):
		return self.buyer.username + " | " + self.seller.username + " | "

class Commission(models.Model):
	''' This class holds commission from a transaction '''
	transaction = models.ForeignKey(Transaction)
	seller = models.ForeignKey(User, limit_choices_to={'is_staff': True}, related_name="trans_seller_commission")
	amount = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	paid = models.NullBooleanField()

class TaxRates(models.Model):
	''' This holds tax rates - Should be managed by admin '''
	state =  models.TextField(blank=True, null=True)
	taxRate = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=3)

class JournalEntry(models.Model):
	'''This class records a journal entry '''
	transaction = models.ForeignKey(Transaction)
	note =  models.CharField(max_length=1000, blank=True, null=True)

class Subledger(models.Model):
	''' This class holds the different types of subledgers - Should be managed by admin because of dependencies '''
	type =  models.CharField(max_length=1000, blank=True, null=True)

	def __str__(self):
		return self.type

class DebitCredit(models.Model):
	''' This class models a debit or a credit to a particular subledger '''
	journalentry = models.ForeignKey(JournalEntry)
	subledger = models.ForeignKey(Subledger)
	isDebit = models.NullBooleanField()
	amount = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)

	def __str__(self):
		return self.subledger.type + ": " + str(self.amount)

class GeneralLedger(models.Model):
	date = models.DateTimeField(auto_now_add=True, blank=True)
	subledger = models.ForeignKey(Subledger)
	isDebit = models.NullBooleanField()
	amount = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)

class Store(models.Model):
	'''A store object'''
	locationName = models.TextField(blank=True, null=True)
	manager = models.ForeignKey(User, limit_choices_to={'is_staff': True}, related_name="store_manager", blank=True, null=True)
	street = models.TextField(blank=True, null=True)
	city  = models.TextField(blank=True, null=True)
	state  = models.TextField(blank=True, null=True)
	zipcode  = models.TextField(blank=True, null=True)
	phone  = models.TextField(blank=True, null=True)
	active = models.NullBooleanField()

	def __str__(self):
		return self.locationName

	def info(self):
		info = []
		info.append(Info("Location Name", self.locationName, False))
		info.append(Info("Street", self.street, True))
		info.append(Info("City", self.city, True))
		info.append(Info("State", self.state, True))
		info.append(Info("Zipcode", self.zipcode, True))
		info.append(Info("Phone", self.phone, True))
		return info

class Category(models.Model):
	''' This class defines the different categories - Should be managed by the admin because of dependencies '''
	name = models.TextField(blank=True, null=True)
	description = models.TextField(blank=True, null=True)
	imagePath = models.CharField(max_length=100, blank=True, null=True)
	url = models.CharField(max_length=50, blank=True, null=True)
	#url contains where
	is_active = models.NullBooleanField()
	queryURL = models.CharField(max_length=50, blank=True, null=True)

	def __str__(self):
		return self.name

	def info(self):
		info = []
		info.append(Info("Name", self.name, False))
		info.append(Info("Description", self.description, False))
		return info

class InventoryType(models.Model):
	''' This class defines whether the CatalogProduct is Stocked or Serialized - Should be managed by Admin '''
	name = models.TextField(blank=True, null=True)

	def __str__(self):
		return self.name

class CatalogProduct(models.Model):
	''' This class holds a catalog product. CatalogProducts are the different types of products the company can stock '''
	catalogID = models.TextField(blank=True, null=True)
	inventorytype = models.ForeignKey(InventoryType)
	name = models.TextField(blank=True, null=True)
	lname = models.TextField(blank=True, null=True)
	description = models.TextField(blank=True, null=True)
	ldescription = models.TextField(blank=True, null=True)
	brand = models.TextField(blank=True, null=True)
	lbrand = models.TextField(blank=True, null=True)
	category = models.ForeignKey(Category)
	imagePath = models.CharField(max_length=100, blank=True, null=True)
	#imagePath stores the path to the image. Pictures can not be uploaded through the manager app. This is because of the need to properly format pictures before uploading and displaying them on the server
	price = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	rentalPrice = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	replacementPrice = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	is_active = models.NullBooleanField()

	def info(self):
		info = []
		info.append(Info("CatalogID", self.catalogID, False))
		info.append(Info("Name", self.name, False))
		info.append(Info("Description", self.description, False))
		info.append(Info("Brand", self.brand, False))
		info.append(Info("Price", self.price, False))
		info.append(Info("Rental Price", self.rentalPrice, False))
		info.append(Info("Replacement Price", self.replacementPrice, False))
		return info

	def __str__(self):
		return self.catalogID + ": " + self.name

class TransactionToPack(models.Model):
	''' This class holds what is needed to pack for a transaction ordered from the online store. '''
	transaction = models.ForeignKey(Transaction)
	catalog_product = models.ForeignKey(CatalogProduct)
	quantity = models.PositiveIntegerField()
	packed = models.NullBooleanField()

class StockedProduct(models.Model):
	''' This class represents an actual product of the CatalogProduct '''
	catalogID = models.ForeignKey(CatalogProduct)
	amount = models.PositiveIntegerField()
	cost = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	store = models.ForeignKey(Store)
	is_active = models.NullBooleanField()

	def __str__(self):
		return self.catalogID.catalogID + ": " + self.catalogID.name + " - "  + self.store.locationName	+ " | " + str(self.amount)

	def info(self):
		info = []
		info.append(Info("Amount", self.amount, False))
		info.append(Info("Cost", self.cost, False))
		return info

class SerializedProduct(models.Model):
	''' This class represents a single actual serialized product off the CatalogProduct '''
	catalogID = models.ForeignKey(CatalogProduct)
	serialNumber = models.TextField(blank=True, null=True)
	datePurchased = models.DateTimeField(blank=True, null=True)
	cost = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	store = models.ForeignKey(Store)
	is_rental = models.NullBooleanField()
	is_available = models.NullBooleanField()
	is_new = models.NullBooleanField()
	is_active = models.NullBooleanField()

	def info(self):
		info = []
		info.append(Info("Serial Number", self.serialNumber, False))
		info.append(Info("Cost", self.cost, False))
		info.append(Info("Rental", self.is_rental, False))
		info.append(Info("Available", self.is_available, False))
		info.append(Info("New", self.is_new, False))
		info.append(Info("Date Purchased", self.datePurchased, False))
		return info

	def __str__(self):
		return self.catalogID.catalogID + ": " + self.catalogID.name + " - " + self.store.locationName + " | " + self.serialNumber 	+ " | " + str(self.datePurchased)

class Rental(models.Model):
	''' This class represents a rental '''
	user = models.ForeignKey(User)
	serialized = models.ForeignKey(SerializedProduct)
	daily_rate = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	checkout_date = models.DateTimeField(blank=True, null=True)
	checkout_condition = models.CharField(max_length=100, blank=True, null=True)
	days_to_rent = models.PositiveIntegerField()
	expected_date = models.DateTimeField(blank=True, null=True)
	return_date = models.DateTimeField(blank=True, null=True)
	return_condition = models.CharField(max_length=100, blank=True, null=True)
	before_fees = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	late_fees = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	damage_fees = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	damage_note = models.CharField(max_length=100, blank=True, null=True)
	paid = models.NullBooleanField()

	def __str__(self):
		return self.user.username + " | " + self.serialized.catalogID.name

class RepairStatus(models.Model):
	''' This class holds the statuses of In Progress and Completed so users can check the status of their repair'''
	status = models.CharField(max_length=100, blank=True, null=True)

	def __str__(self):
		return self.status

class Repair(models.Model):
	''' This class represents a repair '''
	user = models.ForeignKey(User)
	serial_number = models.CharField(max_length=100, blank=True, null=True)
	description = models.CharField(max_length=100, blank=True, null=True)
	date_received = models.DateTimeField(blank=True, null=True)
	problem = models.CharField(max_length=100, blank=True, null=True)
	status = models.ForeignKey(RepairStatus)
	estimate = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	additional_cost = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	# additional_cost represents how much more should be added to the estimate for the customer
	cost = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	#cost represents the actual cost of the repair. Field is used for accounting purposes.
	costs_note = models.CharField(max_length=1000, blank=True, null=True)
	total_charged = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
	date_returned = models.DateTimeField(blank=True, null=True)
	paid = models.NullBooleanField()

	def __str__(self):
		return self.user.username + " | " + self.description

class StockedTransaction(models.Model):
	''' This class connects a stocked item to a transaction '''
	transaction = models.ForeignKey(Transaction)
	stocked = models.ForeignKey(StockedProduct)
	amount = models.PositiveIntegerField()

class SerializedTransaction(models.Model):
	''' This class connects a serialized item to a transaction '''
	transaction = models.ForeignKey(Transaction)
	serialized = models.ForeignKey(SerializedProduct)

class RepairTransaction(models.Model):
	''' This class connects a repair to a transaction '''
	transaction = models.ForeignKey(Transaction)
	repair = models.ForeignKey(Repair)

class RentalTransaction(models.Model):
	''' This class connects a rental to a transaction '''
	transaction = models.ForeignKey(Transaction)
	rental = models.ForeignKey(Rental)


text:
<bill session="115" type="hr" number="216" updated="2017-05-16T18:46:30Z">
  <state datetime="2017-03-21">REFERRED</state>
  <status>
    <introduced datetime="2017-03-21"/>
  </status>
  <introduced datetime="2017-03-21"/>
  <titles>
    <title type="official" as="introduced">Congratulating the Plastics Industry Association on its 80th anniversary.</title>
    <title type="display">Congratulating the Plastics Industry Association on its 80th anniversary.</title>
  </titles>
  <sponsor bioguide_id="B001275"/>
  <cosponsors/>
  <actions>
    <action datetime="2017-03-21">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-03-21" state="REFERRED">
      <text>Referred to the Committee on Energy and Commerce, and in addition to the Committees on Science, Space, and Technology, and Education and the Workforce, for a period to be subsequently determined by the Speaker, in each case for consideration of such provisions as fall within the jurisdiction of the committee concerned.</text>
    </action>
    <action datetime="2017-03-21">
      <text>Referred to House Energy and Commerce</text>
    </action>
    <action datetime="2017-03-21">
      <text>Referred to House Science, Space, and Technology</text>
    </action>
    <action datetime="2017-03-21">
      <text>Referred to House Education and the Workforce</text>
    </action>
    <action datetime="2017-03-24">
      <text>Referred to the Subcommittee on Digital Commerce and Consumer Protection.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="HSIF" name="House Energy and Commerce" activity="Referral"/>
    <committee subcommittee="Commerce, Manufacturing, and Trade" code="HSIF17" name="House Energy and Commerce" activity="Referral"/>
    <committee subcommittee="" code="HSED" name="House Education and the Workforce" activity="Referral"/>
    <committee subcommittee="" code="HSSY" name="House Science, Space, and Technology" activity="Referral"/>
  </committees>
  <relatedbills>
    <bill type="sr" session="115" relation="identical" number="64"/>
  </relatedbills>
  <subjects>
    <term name="Commerce"/>
    <term name="Commemorative events and holidays"/>
    <term name="Congressional tributes"/>
    <term name="Manufacturing"/>
    <term name="Science and engineering education"/>
  </subjects>
  <amendments/>
  <summary date="2017-03-21T04:00:00Z" status="Introduced in House">Congratulates the Plastics Industry Association on its 80th anniversary. Reaffirms the crucial role of plastics in strengthening the U.S. economy and improving people's lives.

Recognizes the importance of continued investment in plastics, manufacturing, research, and education in the fields of science, technology, engineering, and mathematics.</summary>
  <committee-reports/>
</bill>


text:
<?php
namespace app\ext\Notification\Dispatch\Transport\Email;

use app\models\User;

class EmailAddressee
{
    public $email;
    public $name;

    public function __construct($email, $name)
    {
        $this->email = $email;
        $this->name = $name;
    }

    /**
     * @param User $user
     * @return EmailAddressee
     */
    public static function getAddresseeByUser(User $user)
    {
        return new static($user->email, $user->username);
    }
}


text:
namespace amf
{

bool AmfBool::operator==(const AmfItem& other) const {
	const AmfBool* p = dynamic_cast<const AmfBool*>(&other);
	return p != nullptr && value == p->value;
}

AmfBool AmfBool::deserialize(v8::const_iterator& it, v8::const_iterator end, DeserializationContext&) {
	if (it == end)
		throw std::invalid_argument("AmfBool: End of iterator");

	u8 marker = *it++;
	if (marker != AMF_TRUE && marker != AMF_FALSE)
		throw std::invalid_argument("AmfBool: Invalid type marker");

	return AmfBool(marker == AMF_TRUE);
}

} // namespace amf


text:
<!--
  ~ Copyright 2015 Open Networking Laboratory
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->
<scenario name="net-smoke" description="Basic network functionality smoke test">
    <group name="Net-Smoke">
        <import file="${ONOS_SCENARIOS}/net-setup.xml"/>

        <import file="${ONOS_SCENARIOS}/net-pingall.xml" namespace="Reactive-Forwarding"/>
        <dependency name="Reactive-Forwarding.Net-Pingall" requires="Net-Setup"/>

        <import file="${ONOS_SCENARIOS}/net-link-down-up.xml" namespace="Reactive-Forwarding"/>
        <dependency name="Reactive-Forwarding.Net-Link-Down-Up" requires="Net-Setup,~Reactive-Forwarding.Net-Pingall"/>

        <import file="${ONOS_SCENARIOS}/net-host-intent.xml"/>
        <dependency name="Host-Intent-Connectivity" requires="Net-Setup,~Reactive-Forwarding.Net-Link-Down-Up"/>

        <import file="${ONOS_SCENARIOS}/net-point-intent.xml"/>
        <dependency name="P2P-Intent-Connectivity" requires="Net-Setup,~Reactive-Forwarding.Net-Link-Down-Up,Host-Intent-Connectivity"/>

        <import file="${ONOS_SCENARIOS}/net-rest.xml"/>
        <dependency name="Net-REST" requires="Net-Setup,P2P-Intent-Connectivity"/>

        <import file="${ONOS_SCENARIOS}/net-create-flows.xml"/>
        <dependency name="Net-Create-Flows" requires="Net-Setup,P2P-Intent-Connectivity,Net-REST"/>

        <import file="${ONOS_SCENARIOS}/net-topo.xml"/>
        <dependency name="Net-Topo" requires="Net-Setup,Net-Create-Flows"/>

        <import file="${ONOS_SCENARIOS}/net-teardown.xml"/>
        <dependency name="Net-Teardown" requires="~Host-Intent-Connectivity,
                                                  ~P2P-Intent-Connectivity,
                                                  ~Net-REST,
                                                  ~Net-Create-Flows,
                                                  ~Net-Topo"/>
    </group>
</scenario>


text:
package org.jboss.arquillian.container.weld.embedded;

import jakarta.inject.Inject;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 * WeldEmbeddedIntegrationTestCase
 *
 * @author Aslak Knutsen
 * @version $Revision: $
 */
@RunWith(Arquillian.class)
public class WeldEmbeddedIntegrationEARTestCase
{
   @Deployment
   public static EnterpriseArchive createdeployment()
   {
      return ShrinkWrap.create(EnterpriseArchive.class)
                  .addAsModule(
                        ShrinkWrap.create(WebArchive.class)
                           .addClasses(
                              WeldEmbeddedIntegrationEARTestCase.class,
                              MyBean.class)
                           .addAsWebResource(
                              EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"))
                  );
   }

   @Inject
   private MyBean instanceVariable;

   @Test
   public void shouldBeAbleToInjectBeanAsInstanceVariable() throws Exception
   {
      Assert.assertNotNull(
            "Verify that the Bean has been injected",
            instanceVariable);

      Assert.assertEquals("aslak", instanceVariable.getName());
   }

   @Test
   public void shouldBeAbleToInjectBeanAsArgumentVariable(MyBean argumentVariable) throws Exception
   {
      Assert.assertNotNull(
            "Verify that the Bean has been injected",
            argumentVariable);

      Assert.assertEquals("aslak", argumentVariable.getName());
   }
}


text:
<?php

namespace Plancke\HypixelPHP\util\games;

use Exception;
use Plancke\HypixelPHP\util\games\bedwars\BedWarsUtils;
use Plancke\HypixelPHP\util\games\skywars\SkyWarsUtils;

/**
 * Class GameUtils
 * @package Plancke\HypixelPHP\util\games
 */
class GameUtils {

    protected static $BEDWARS_UTILS;
    protected static $MEGA_WALLS_UTILS;
    protected static $SKYWARS_UTILS;
    protected static $BLITZ_UTILS;

    /**
     * @throws Exception
     */
    public function __construct() {
        throw new Exception();
    }

    /**
     * @return BedWarsUtils
     */
    public static function getBedWars() {
        if (GameUtils::$BEDWARS_UTILS == null) {
            GameUtils::$BEDWARS_UTILS = new BedWarsUtils();
        }
        return GameUtils::$BEDWARS_UTILS;
    }

    /**
     * @return MegaWallsUtils
     */
    public static function getMegaWalls() {
        if (GameUtils::$MEGA_WALLS_UTILS == null) {
            GameUtils::$MEGA_WALLS_UTILS = new MegaWallsUtils();
        }
        return GameUtils::$MEGA_WALLS_UTILS;
    }

    /**
     * @return SkyWarsUtils
     */
    public static function getSkyWars() {
        if (GameUtils::$SKYWARS_UTILS == null) {
            GameUtils::$SKYWARS_UTILS = new SkyWarsUtils();
        }
        return GameUtils::$SKYWARS_UTILS;
    }

    /**
     * @return BlitzUtils
     */
    public static function getBlitz() {
        if (GameUtils::$BLITZ_UTILS == null) {
            GameUtils::$BLITZ_UTILS = new BlitzUtils();
        }
        return GameUtils::$BLITZ_UTILS;
    }
}


text:
var fs = require('fs');

var solve = require('./modules/solve.js');
var none = require('./input/input-none.json');
var any = require('./input/input-any.json');
var one = require('./input/input-1.json');
var two = require('./input/input-2.json');

console.log(solve.quadratic(one["a"], one["b"], one["c"]));
console.log(solve.quadratic(two["a"], two["b"], two["c"]));
console.log(solve.quadratic(none["a"], none["b"], none["c"]));
console.log(solve.quadratic(any["a"], any["b"], any["c"]));


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Merchant
 *
 * @ORM\Table(name="merchant")
 * @ORM\Entity
 */
class Merchant
{
    public function __construct()
    {
        $this->invoices = new ArrayCollection();
    }

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=45, nullable=true)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="street", type="string", length=45, nullable=true)
     */
    private $street;

    /**
     * @var string
     *
     * @ORM\Column(name="houseNumber", type="string", length=45, nullable=true)
     */
    private $housenumber;

    /**
     * @var string
     *
     * @ORM\Column(name="apartmentNumber", type="string", length=45, nullable=true)
     */
    private $apartmentnumber;

    /**
     * @var string
     *
     * @ORM\Column(name="postalCode", type="string", length=45, nullable=true)
     */
    private $postalcode;

    /**
     * @var string
     *
     * @ORM\Column(name="city", type="string", length=45, nullable=true)
     */
    private $city;

    /**
     * @var string
     *
     * @ORM\Column(name="nip", type="string", length=45, nullable=true)
     */
    private $nip;

    /**
     * @var string
     *
     * @ORM\Column(name="phoneNumber", type="string", length=45, nullable=true)
     */
    private $phonenumber;

    /**
     * @var integer
     *
     * @ORM\Column(name="idMerchant", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $idmerchant;

    /**
     * @ORM\OneToMany(targetEntity="Invoice", mappedBy="idmerchant")
     */
    protected $invoices;

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

        return $this;
    }

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

    /**
     * Set street
     *
     * @param string $street
     * @return Merchant
     */
    public function setStreet($street)
    {
        $this->street = $street;

        return $this;
    }

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

    /**
     * Set housenumber
     *
     * @param string $housenumber
     * @return Merchant
     */
    public function setHousenumber($housenumber)
    {
        $this->housenumber = $housenumber;

        return $this;
    }

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

    /**
     * Set apartmentnumber
     *
     * @param string $apartmentnumber
     * @return Merchant
     */
    public function setApartmentNumber($apartmentnumber)
    {
        $this->apartmentnumber = $apartmentnumber;

        return $this;
    }

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

    /**
     * Set postalcode
     *
     * @param string $postalcode
     * @return Merchant
     */
    public function setPostalcode($postalcode)
    {
        $this->postalcode = $postalcode;

        return $this;
    }

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

    /**
     * Set city
     *
     * @param string $city
     * @return Merchant
     */
    public function setCity($city)
    {
        $this->city = $city;

        return $this;
    }

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

    /**
     * Set nip
     *
     * @param string $nip
     * @return Merchant
     */
    public function setNip($nip)
    {
        $this->nip = $nip;

        return $this;
    }

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

    /**
     * Set phonenumber
     *
     * @param string $phonenumber
     * @return Merchant
     */
    public function setPhonenumber($phonenumber)
    {
        $this->phonenumber = $phonenumber;

        return $this;
    }

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

    /**
     * Get idmerchant
     *
     * @return int
     */
    public function getidMerchant()
    {
        return $this->idmerchant;
    }

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

    /**
     * Add invoices
     *
     * @param \AppBundle\Entity\Invoice $invoices
     * @return Merchant
     */
    public function addInvoices(\AppBundle\Entity\Invoice $invoices)
    {
        $this->invoices[] = $invoices;

        return $this;
    }

    /**
     * Remove invoices
     *
     * @param \AppBundle\Entity\Invoice $invoices
     */
    public function removeInvoices(\AppBundle\Entity\Invoice $invoices)
    {
        $this->invoices->removeElement($invoices);
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.firestore.v1.model;

/**
 * A request for Firestore.Listen
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Firestore API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class ListenRequest extends com.google.api.client.json.GenericJson {

  /**
   * A target to add to this stream.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private Target addTarget;

  /**
   * Labels associated with this target change.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.Map<String, java.lang.String> labels;

  /**
   * The ID of a target to remove from this stream.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Integer removeTarget;

  /**
   * A target to add to this stream.
   * @return value or {@code null} for none
   */
  public Target getAddTarget() {
    return addTarget;
  }

  /**
   * A target to add to this stream.
   * @param addTarget addTarget or {@code null} for none
   */
  public ListenRequest setAddTarget(Target addTarget) {
    this.addTarget = addTarget;
    return this;
  }

  /**
   * Labels associated with this target change.
   * @return value or {@code null} for none
   */
  public java.util.Map<String, java.lang.String> getLabels() {
    return labels;
  }

  /**
   * Labels associated with this target change.
   * @param labels labels or {@code null} for none
   */
  public ListenRequest setLabels(java.util.Map<String, java.lang.String> labels) {
    this.labels = labels;
    return this;
  }

  /**
   * The ID of a target to remove from this stream.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getRemoveTarget() {
    return removeTarget;
  }

  /**
   * The ID of a target to remove from this stream.
   * @param removeTarget removeTarget or {@code null} for none
   */
  public ListenRequest setRemoveTarget(java.lang.Integer removeTarget) {
    this.removeTarget = removeTarget;
    return this;
  }

  @Override
  public ListenRequest set(String fieldName, Object value) {
    return (ListenRequest) super.set(fieldName, value);
  }

  @Override
  public ListenRequest clone() {
    return (ListenRequest) super.clone();
  }

}


text:
package org.onosproject.novibng.config;

import org.onlab.packet.Ip4Address;
import org.onlab.packet.Ip4Prefix;
import org.onlab.packet.MacAddress;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by nick on 8/22/16.
 */
public class BngDeviceConfig {

    private Logger log = LoggerFactory.getLogger(getClass());

    private DeviceId deviceId;
    private Ip4Address loopbackIP;
    private Ip4Address primaryLinkIp;
    private int primaryLinkSubnetLength;
    private Ip4Address secondaryLinkIp;
    private int secondaryLinkSubnetLength;
    private MacAddress primaryLinkMac;
    private MacAddress secondaryLinkMac;
    private PortNumber primaryLinkPort;
    private PortNumber secondaryLinkPort;
    private Ip4Address primaryNextHopIp;
    private Ip4Address secondaryNextHopIp;

    public BngDeviceConfig(DeviceId deviceId, Ip4Address loopbackIP, Ip4Address primaryLinkIp,
                           int primaryLinkSubnetLength, Ip4Address secondaryLinkIp, int secondaryLinkSubnetLength,
                           MacAddress primaryLinkMac, MacAddress secondaryLinkMac, PortNumber primaryLinkPort,
                           PortNumber secondaryLinkPort, Ip4Address primaryNextHopIp, Ip4Address secondaryNextHopIp) {

        this.deviceId = deviceId;
        this.loopbackIP = loopbackIP;
        this.primaryLinkIp = primaryLinkIp;
        this.primaryLinkSubnetLength = primaryLinkSubnetLength;
        this.secondaryLinkIp = secondaryLinkIp;
        this.secondaryLinkSubnetLength = secondaryLinkSubnetLength;
        this.primaryLinkMac = primaryLinkMac;
        this.secondaryLinkMac = secondaryLinkMac;
        this.primaryLinkPort = primaryLinkPort;
        this.secondaryLinkPort = secondaryLinkPort;
        this.primaryNextHopIp = primaryNextHopIp;
        this.secondaryNextHopIp = secondaryNextHopIp;

    }

    public DeviceId getDeviceId() {
        return deviceId;
    }

    public Ip4Address getLoopbackIP() {
        return loopbackIP;
    }

    public Ip4Prefix getPrimaryLinkSubnet() {
        return Ip4Prefix.valueOf(primaryLinkIp, primaryLinkSubnetLength);
    }

    public Ip4Prefix getSecondaryLinkSubnet() {
        return Ip4Prefix.valueOf(secondaryLinkIp, secondaryLinkSubnetLength);
    }

    public Ip4Address getPrimaryLinkIp() {
        return primaryLinkIp;
    }

    public Ip4Address getSecondaryLinkIp() {
        return secondaryLinkIp;
    }

    public MacAddress getPrimaryLinkMac() {
        return primaryLinkMac;
    }

    public MacAddress getSecondaryLinkMac() {
        return secondaryLinkMac;
    }

    public PortNumber getPrimaryLinkPort() {
        return primaryLinkPort;
    }

    public PortNumber getSecondaryLinkPort() {
        return secondaryLinkPort;
    }

    public Ip4Address getPrimaryNextHopIp() {
        return primaryNextHopIp;
    }

    public Ip4Address getSecondaryNextHopIp() {
        return secondaryNextHopIp;
    }

    public boolean equals(Object otherObject) {

        if (otherObject instanceof BngDeviceConfig) {

            BngDeviceConfig other = (BngDeviceConfig) otherObject;
            return deviceId.equals(other.deviceId) && loopbackIP.equals(other.loopbackIP)
                    && primaryLinkIp.equals(other.primaryLinkIp) && secondaryLinkIp.equals(other.secondaryLinkIp)
                    && primaryLinkSubnetLength == other.primaryLinkSubnetLength
                    && secondaryLinkSubnetLength == other.secondaryLinkSubnetLength
                    && primaryLinkPort.equals(other.primaryLinkPort)
                    && secondaryLinkPort.equals(other.secondaryLinkPort) &&
                    primaryLinkMac.equals(other.primaryLinkMac) && secondaryLinkMac.equals(other.secondaryLinkMac);

        }

        return false;

    }

    public int hashCode() {

        int hash = deviceId.hashCode() + 2 * loopbackIP.hashCode() + 3 * primaryLinkIp.hashCode() +
                5 * secondaryLinkIp.hashCode() + 7 * primaryLinkSubnetLength + 11 * secondaryLinkSubnetLength +
                13 * primaryLinkPort.hashCode() + 17 * secondaryLinkPort.hashCode() + 19 * primaryLinkMac.hashCode() +
                23 * secondaryLinkMac.hashCode();

        return hash;

    }
}


text:
#include <linux/kvm_host.h>
#include <linux/fs.h>
#include <linux/seq_file.h>
#include <linux/debugfs.h>
#include <linux/uaccess.h>

#include <asm/time.h>
#include <asm-generic/div64.h>

#include "timing.h"

void kvmppc_init_timing_stats(struct kvm_vcpu *vcpu)
{
	int i;

	/* pause guest execution to avoid concurrent updates */
	local_irq_disable();
	mutex_lock(&vcpu->mutex);

	vcpu->arch.last_exit_type = 0xDEAD;
	for (i = 0; i < __NUMBER_OF_KVM_EXIT_TYPES; i++) {
		vcpu->arch.timing_count_type[i] = 0;
		vcpu->arch.timing_max_duration[i] = 0;
		vcpu->arch.timing_min_duration[i] = 0xFFFFFFFF;
		vcpu->arch.timing_sum_duration[i] = 0;
		vcpu->arch.timing_sum_quad_duration[i] = 0;
	}
	vcpu->arch.timing_last_exit = 0;
	vcpu->arch.timing_exit.tv64 = 0;
	vcpu->arch.timing_last_enter.tv64 = 0;

	mutex_unlock(&vcpu->mutex);
	local_irq_enable();
}

static void add_exit_timing(struct kvm_vcpu *vcpu, u64 duration, int type)
{
	u64 old;

	do_div(duration, tb_ticks_per_usec);
	if (unlikely(duration > 0xFFFFFFFF)) {
		printk(KERN_ERR"%s - duration too big -> overflow"
			" duration %lld type %d exit #%d\n",
			__func__, duration, type,
			vcpu->arch.timing_count_type[type]);
		return;
	}

	vcpu->arch.timing_count_type[type]++;

	/* sum */
	old = vcpu->arch.timing_sum_duration[type];
	vcpu->arch.timing_sum_duration[type] += duration;
	if (unlikely(old > vcpu->arch.timing_sum_duration[type])) {
		printk(KERN_ERR"%s - wrap adding sum of durations"
			" old %lld new %lld type %d exit # of type %d\n",
			__func__, old, vcpu->arch.timing_sum_duration[type],
			type, vcpu->arch.timing_count_type[type]);
	}

	/* square sum */
	old = vcpu->arch.timing_sum_quad_duration[type];
	vcpu->arch.timing_sum_quad_duration[type] += (duration*duration);
	if (unlikely(old > vcpu->arch.timing_sum_quad_duration[type])) {
		printk(KERN_ERR"%s - wrap adding sum of squared durations"
			" old %lld new %lld type %d exit # of type %d\n",
			__func__, old,
			vcpu->arch.timing_sum_quad_duration[type],
			type, vcpu->arch.timing_count_type[type]);
	}

	/* set min/max */
	if (unlikely(duration < vcpu->arch.timing_min_duration[type]))
		vcpu->arch.timing_min_duration[type] = duration;
	if (unlikely(duration > vcpu->arch.timing_max_duration[type]))
		vcpu->arch.timing_max_duration[type] = duration;
}

void kvmppc_update_timing_stats(struct kvm_vcpu *vcpu)
{
	u64 exit = vcpu->arch.timing_last_exit;
	u64 enter = vcpu->arch.timing_last_enter.tv64;

	/* save exit time, used next exit when the reenter time is known */
	vcpu->arch.timing_last_exit = vcpu->arch.timing_exit.tv64;

	if (unlikely(vcpu->arch.last_exit_type == 0xDEAD || exit == 0))
		return; /* skip incomplete cycle (e.g. after reset) */

	/* update statistics for average and standard deviation */
	add_exit_timing(vcpu, (enter - exit), vcpu->arch.last_exit_type);
	/* enter -> timing_last_exit is time spent in guest - log this too */
	add_exit_timing(vcpu, (vcpu->arch.timing_last_exit - enter),
			TIMEINGUEST);
}

static const char *kvm_exit_names[__NUMBER_OF_KVM_EXIT_TYPES] = {
	[MMIO_EXITS] =              "MMIO",
	[DCR_EXITS] =               "DCR",
	[SIGNAL_EXITS] =            "SIGNAL",
	[ITLB_REAL_MISS_EXITS] =    "ITLBREAL",
	[ITLB_VIRT_MISS_EXITS] =    "ITLBVIRT",
	[DTLB_REAL_MISS_EXITS] =    "DTLBREAL",
	[DTLB_VIRT_MISS_EXITS] =    "DTLBVIRT",
	[SYSCALL_EXITS] =           "SYSCALL",
	[ISI_EXITS] =               "ISI",
	[DSI_EXITS] =               "DSI",
	[EMULATED_INST_EXITS] =     "EMULINST",
	[EMULATED_MTMSRWE_EXITS] =  "EMUL_WAIT",
	[EMULATED_WRTEE_EXITS] =    "EMUL_WRTEE",
	[EMULATED_MTSPR_EXITS] =    "EMUL_MTSPR",
	[EMULATED_MFSPR_EXITS] =    "EMUL_MFSPR",
	[EMULATED_MTMSR_EXITS] =    "EMUL_MTMSR",
	[EMULATED_MFMSR_EXITS] =    "EMUL_MFMSR",
	[EMULATED_TLBSX_EXITS] =    "EMUL_TLBSX",
	[EMULATED_TLBWE_EXITS] =    "EMUL_TLBWE",
	[EMULATED_RFI_EXITS] =      "EMUL_RFI",
	[DEC_EXITS] =               "DEC",
	[EXT_INTR_EXITS] =          "EXTINT",
	[HALT_WAKEUP] =             "HALT",
	[USR_PR_INST] =             "USR_PR_INST",
	[FP_UNAVAIL] =              "FP_UNAVAIL",
	[DEBUG_EXITS] =             "DEBUG",
	[TIMEINGUEST] =             "TIMEINGUEST"
};

static int kvmppc_exit_timing_show(struct seq_file *m, void *private)
{
	struct kvm_vcpu *vcpu = m->private;
	int i;

	seq_printf(m, "%s", "type	count	min	max	sum	sum_squared\n");

	for (i = 0; i < __NUMBER_OF_KVM_EXIT_TYPES; i++) {
		seq_printf(m, "%12s	%10d	%10lld	%10lld	%20lld	%20lld\n",
			kvm_exit_names[i],
			vcpu->arch.timing_count_type[i],
			vcpu->arch.timing_min_duration[i],
			vcpu->arch.timing_max_duration[i],
			vcpu->arch.timing_sum_duration[i],
			vcpu->arch.timing_sum_quad_duration[i]);
	}
	return 0;
}

/* Write 'c' to clear the timing statistics. */
static ssize_t kvmppc_exit_timing_write(struct file *file,
				       const char __user *user_buf,
				       size_t count, loff_t *ppos)
{
	int err = -EINVAL;
	char c;

	if (count > 1) {
		goto done;
	}

	if (get_user(c, user_buf)) {
		err = -EFAULT;
		goto done;
	}

	if (c == 'c') {
		struct seq_file *seqf = (struct seq_file *)file->private_data;
		struct kvm_vcpu *vcpu = seqf->private;
		/* Write does not affect our buffers previously generated with
		 * show. seq_file is locked here to prevent races of init with
		 * a show call */
		mutex_lock(&seqf->lock);
		kvmppc_init_timing_stats(vcpu);
		mutex_unlock(&seqf->lock);
		err = count;
	}

done:
	return err;
}

static int kvmppc_exit_timing_open(struct inode *inode, struct file *file)
{
	return single_open(file, kvmppc_exit_timing_show, inode->i_private);
}

static const struct file_operations kvmppc_exit_timing_fops = {
	.owner   = THIS_MODULE,
	.open    = kvmppc_exit_timing_open,
	.read    = seq_read,
	.write   = kvmppc_exit_timing_write,
	.llseek  = seq_lseek,
	.release = single_release,
};

void kvmppc_create_vcpu_debugfs(struct kvm_vcpu *vcpu, unsigned int id)
{
	static char dbg_fname[50];
	struct dentry *debugfs_file;

	snprintf(dbg_fname, sizeof(dbg_fname), "vm%u_vcpu%u_timing",
		 current->pid, id);
	debugfs_file = debugfs_create_file(dbg_fname, 0666,
					kvm_debugfs_dir, vcpu,
					&kvmppc_exit_timing_fops);

	if (!debugfs_file) {
		printk(KERN_ERR"%s: error creating debugfs file %s\n",
			__func__, dbg_fname);
		return;
	}

	vcpu->arch.debugfs_exit_timing = debugfs_file;
}

void kvmppc_remove_vcpu_debugfs(struct kvm_vcpu *vcpu)
{
	if (vcpu->arch.debugfs_exit_timing) {
		debugfs_remove(vcpu->arch.debugfs_exit_timing);
		vcpu->arch.debugfs_exit_timing = NULL;
	}
}


text:
package net.sourceforge.plantuml.creole.legacy;

import net.sourceforge.plantuml.command.PSystemBasicFactory;
import net.sourceforge.plantuml.core.DiagramType;
import net.sourceforge.plantuml.core.UmlSource;

public class PSystemCreoleFactory extends PSystemBasicFactory<PSystemCreole> {

	public PSystemCreoleFactory() {
		super(DiagramType.CREOLE);
	}

	@Override
	public PSystemCreole initDiagram(UmlSource source, String startLine) {
		if (getDiagramType() == DiagramType.CREOLE)
			return new PSystemCreole(source);

		return null;
	}

	@Override
	public PSystemCreole executeLine(UmlSource source, PSystemCreole system, String line) {
		system.doCommandLine(line);
		return system;
	}

}


text:
package com.polydes.paint.app.editors.bitmapfont;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

import com.polydes.paint.app.editors.bitmapfont.tools.GlyphBounds;
import com.polydes.paint.app.editors.bitmapfont.tools.GlyphSpacing;
import com.polydes.paint.app.editors.bitmapfont.tools.LineSpacing;
import com.polydes.paint.app.editors.image.DrawTools;
import com.polydes.paint.data.BitmapFont;
import com.polydes.paint.res.Resources;

import stencyl.sw.SW;

@SuppressWarnings("serial")
public class FontTools extends DrawTools
{
	private ToolButton glyphBoundsButton;
	private ToolButton glyphSpacingButton;
	private ToolButton lineSpacingButton;
	private JButton packGlyphsButton;

	public FontTools()
	{
		super();

		glyphBoundsButton = createToolButton(Resources.loadIcon("draw/glyph_bounds.png"), new GlyphBounds());
		glyphSpacingButton = createToolButton(Resources.loadIcon("draw/glyph_spacing.png"), new GlyphSpacing());
		lineSpacingButton = createToolButton(Resources.loadIcon("draw/line_spacing.png"), new LineSpacing());
		packGlyphsButton = createButton(Resources.loadIcon("draw/pack_glyphs.png"));
		packGlyphsButton.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				FontDrawArea area = (FontDrawArea) getDrawArea();
				BitmapFont font = area.font;
				PackGlyphsDialog.showPackGlyphsDialog(font, area, SW.get());
			}
		});

		add(createButtonPair(glyphBoundsButton, glyphSpacingButton));
		add(createButtonPair(lineSpacingButton, null));

		createButtonPair(null, null);

		add(packGlyphsButton);
	}
}


text:
namespace Nice {

template<typename T>
class GpuSvdSolver {
 private:
  Matrix<T> u_;
  Matrix<T> v_;
  Vector<T> s_;

 public:
  GpuSvdSolver() {}

  void Compute(const Matrix<T> &A) {
    int M = A.rows();
    int N = A.cols();
    const T *h_A = &A(0);
    // --- Setting the device matrix and moving the host matrix to the device
    T *d_A;   gpuErrchk(cudaMalloc(&d_A,      M * N * sizeof(T)));
    gpuErrchk(cudaMemcpy(d_A, h_A, M * N * sizeof(T), cudaMemcpyHostToDevice));

    //--- host side SVD results space
    s_.resize(M, 1);
    u_.resize(M, M);
    v_.resize(N, N);

    // --- device side SVD workspace and matrices
    int work_size = 0;
    int devInfo_h = 0;
    int *devInfo;   gpuErrchk(cudaMalloc(&devInfo,          sizeof(int)));
    T *d_U;         gpuErrchk(cudaMalloc(&d_U,      M * M * sizeof(T)));
    T *d_V;         gpuErrchk(cudaMalloc(&d_V,      N * N * sizeof(T)));
    T *d_S;         gpuErrchk(cudaMalloc(&d_S,      N *     sizeof(T)));
    cusolverStatus_t stat;

    // --- CUDA solver initialization
    cusolverDnHandle_t solver_handle;
    cusolverDnCreate(&solver_handle);
    stat = cusolverDnSgesvd_bufferSize(solver_handle, M, N, &work_size);
    if (stat != CUSOLVER_STATUS_SUCCESS) {
      std::cout << "Initialization of cuSolver failed." << std::endl;
      cudaFree(d_S); cudaFree(d_U); cudaFree(d_V);
      cusolverDnDestroy(solver_handle);
      exit(1);
    }
    T *work;    gpuErrchk(cudaMalloc(&work, work_size * sizeof(T)));

    // --- CUDA SVD execution
    stat = GpuSvd(solver_handle, M, N,
                 d_A, d_S, d_U, d_V,
                 work, work_size, devInfo);

    // Error Check
    gpuErrchk(cudaMemcpy(&devInfo_h, devInfo,
              sizeof(int), cudaMemcpyDeviceToHost));
    if (stat != CUSOLVER_STATUS_SUCCESS || devInfo_h != 0) {
      std::cerr << "GPU SVD Solver Internal Failure" << std::endl;
      cudaFree(d_S); cudaFree(d_U); cudaFree(d_V); cudaFree(work);
      cusolverDnDestroy(solver_handle);
      exit(1);
    }
    cudaDeviceSynchronize();

        // --- Moving the results from device to host
    gpuErrchk(cudaMemcpy(&s_(0, 0), d_S, N*sizeof(T),
              cudaMemcpyDeviceToHost));
    gpuErrchk(cudaMemcpy(&u_(0, 0), d_U, M*M*sizeof(T),
              cudaMemcpyDeviceToHost));
    gpuErrchk(cudaMemcpy(&v_(0, 0), d_V, N*N*sizeof(T),
              cudaMemcpyDeviceToHost));

    cudaFree(d_S); cudaFree(d_U); cudaFree(d_V); cudaFree(work);
    cusolverDnDestroy(solver_handle);
  }

  Matrix<T> MatrixU() const              { return u_; }

  Matrix<T> MatrixV() const              { return v_; }

  Vector<T> SingularValues() const       { return s_; }
};
}  // namespace Nice

#endif  // NEED_CUDA

#endif  // CPP_INCLUDE_GPU_SVD_SOLVER_H_


text:
/* eslint-disable func-names, space-before-function-paren, no-var, prefer-rest-params, wrap-iife, no-use-before-define, no-useless-escape, no-new, quotes, object-shorthand, no-unused-vars, comma-dangle, no-alert, consistent-return, no-else-return, prefer-template, one-var, one-var-declaration-per-line, curly, max-len */
/* global GitLab */
/* global UsersSelect */
/* global ZenMode */
/* global Autosave */
/* global dateFormat */
/* global Pikaday */

(function() {
  var bind = function(fn, me) { return function() { return fn.apply(me, arguments); }; };

  this.IssuableForm = (function() {
    IssuableForm.prototype.issueMoveConfirmMsg = 'Are you sure you want to move this issue to another project?';

    IssuableForm.prototype.wipRegex = /^\s*(\[WIP\]\s*|WIP:\s*|WIP\s+)+\s*/i;

    function IssuableForm(form) {
      var $issuableDueDate, calendar;
      this.form = form;
      this.toggleWip = bind(this.toggleWip, this);
      this.renderWipExplanation = bind(this.renderWipExplanation, this);
      this.resetAutosave = bind(this.resetAutosave, this);
      this.handleSubmit = bind(this.handleSubmit, this);
      gl.GfmAutoComplete.setup();
      new UsersSelect();
      new ZenMode();
      this.titleField = this.form.find("input[name*='[title]']");
      this.descriptionField = this.form.find("textarea[name*='[description]']");
      this.issueMoveField = this.form.find("#move_to_project_id");
      if (!(this.titleField.length && this.descriptionField.length)) {
        return;
      }
      this.initAutosave();
      this.form.on("submit", this.handleSubmit);
      this.form.on("click", ".btn-cancel", this.resetAutosave);
      this.initWip();
      this.initMoveDropdown();
      $issuableDueDate = $('#issuable-due-date');
      if ($issuableDueDate.length) {
        calendar = new Pikaday({
          field: $issuableDueDate.get(0),
          theme: 'gitlab-theme animate-picker',
          format: 'yyyy-mm-dd',
          container: $issuableDueDate.parent().get(0),
          onSelect: function(dateText) {
            $issuableDueDate.val(dateFormat(new Date(dateText), 'yyyy-mm-dd'));
          }
        });
        calendar.setDate(new Date($issuableDueDate.val()));
      }
    }

    IssuableForm.prototype.initAutosave = function() {
      new Autosave(this.titleField, [document.location.pathname, document.location.search, "title"]);
      return new Autosave(this.descriptionField, [document.location.pathname, document.location.search, "description"]);
    };

    IssuableForm.prototype.handleSubmit = function() {
      var fieldId = (this.issueMoveField != null) ? this.issueMoveField.val() : null;
      if ((parseInt(fieldId, 10) || 0) > 0) {
        if (!confirm(this.issueMoveConfirmMsg)) {
          return false;
        }
      }
      return this.resetAutosave();
    };

    IssuableForm.prototype.resetAutosave = function() {
      this.titleField.data("autosave").reset();
      return this.descriptionField.data("autosave").reset();
    };

    IssuableForm.prototype.initWip = function() {
      this.$wipExplanation = this.form.find(".js-wip-explanation");
      this.$noWipExplanation = this.form.find(".js-no-wip-explanation");
      if (!(this.$wipExplanation.length && this.$noWipExplanation.length)) {
        return;
      }
      this.form.on("click", ".js-toggle-wip", this.toggleWip);
      this.titleField.on("keyup blur", this.renderWipExplanation);
      return this.renderWipExplanation();
    };

    IssuableForm.prototype.workInProgress = function() {
      return this.wipRegex.test(this.titleField.val());
    };

    IssuableForm.prototype.renderWipExplanation = function() {
      if (this.workInProgress()) {
        this.$wipExplanation.show();
        return this.$noWipExplanation.hide();
      } else {
        this.$wipExplanation.hide();
        return this.$noWipExplanation.show();
      }
    };

    IssuableForm.prototype.toggleWip = function(event) {
      event.preventDefault();
      if (this.workInProgress()) {
        this.removeWip();
      } else {
        this.addWip();
      }
      return this.renderWipExplanation();
    };

    IssuableForm.prototype.removeWip = function() {
      return this.titleField.val(this.titleField.val().replace(this.wipRegex, ""));
    };

    IssuableForm.prototype.addWip = function() {
      return this.titleField.val("WIP: " + (this.titleField.val()));
    };

    IssuableForm.prototype.initMoveDropdown = function() {
      var $moveDropdown, pageSize;
      $moveDropdown = $('.js-move-dropdown');
      if ($moveDropdown.length) {
        pageSize = $moveDropdown.data('page-size');
        return $('.js-move-dropdown').select2({
          ajax: {
            url: $moveDropdown.data('projects-url'),
            quietMillis: 125,
            data: function(term, page, context) {
              return {
                search: term,
                offset_id: context
              };
            },
            results: function(data) {
              var context,
                more;

              if (data.length >= pageSize)
                more = true;

              if (data[data.length - 1])
                context = data[data.length - 1].id;

              return {
                results: data,
                more: more,
                context: context
              };
            }
          },
          formatResult: function(project) {
            return project.name_with_namespace;
          },
          formatSelection: function(project) {
            return project.name_with_namespace;
          }
        });
      }
    };

    return IssuableForm;
  })();
}).call(window);


text:
using Newtonsoft.Json.Linq;
using Sporty.Business;
using Sporty.Business.Interfaces;
using Sporty.Common;
using Sporty.Helper;
using Sporty.Infrastructure;
using Sporty.ViewModel;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace Sporty.Controllers
{
    //[HandleErrorWithElmah]
    [Authorize]
    public abstract class BaseCalendarController : ApiController
    {
        protected Guid? UserId;
        protected IUserRepository UserRepository;

        protected ICalendarService calendarService;
        protected ISportTypeRepository sportTypeRepository;
        protected ITrainingTypeRepository trainingTypeRepository;
        protected IWeekPlanRepository weekPlanRepository;
        protected IZoneRepository zoneRepository;
        protected IMaterialRepository materialRepository;

        public CalendarContentType CalendarMode;

        protected Guid? GetUserId()
        {
            if (!UserId.HasValue)
            {
                UserId = UserRepository.FindUserId(User.Identity.Name);
            }
            return UserId;
        }

        protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext)
        {
            UserRepository = ServiceFactory.Current.Resolve<IUserRepository>();
            UserId = GetUserId();

            sportTypeRepository = ServiceFactory.Current.Resolve<ISportTypeRepository>();
            //}
            zoneRepository = ServiceFactory.Current.Resolve<IZoneRepository>();
            trainingTypeRepository = ServiceFactory.Current.Resolve<ITrainingTypeRepository>();
            weekPlanRepository = ServiceFactory.Current.Resolve<IWeekPlanRepository>();
            calendarService = ServiceFactory.Current.Resolve<ICalendarService>();
            materialRepository = ServiceFactory.Current.Resolve<IMaterialRepository>();

            base.Initialize(controllerContext);
        }
        public CalendarViewModel GetCalendar()
        {
            return GetCalendar(null, null);
        }

        // GET api/calendar
        public virtual CalendarViewModel GetCalendar(int? month, int? year)
        {
            DateTime currentDate = GetDateFromSessionOrToday();

            int monthValue = month.HasValue ? month.Value : currentDate.Month;

            int yearValue = year.HasValue ? year.Value : currentDate.Year;

            if (month.HasValue && year.HasValue)
            {
                //Http["startDate"] = new DateTime(year.Value, month.Value, 1);
            }

            CalendarViewModel model = calendarService.GetViewModel(monthValue, yearValue, UserId.Value, CalendarMode );

            model.PublicICalUrl = UserRepository.GetSsoToken(UserId);
            return model;
        }

        // PUT api/calendar/5
        public HttpResponseMessage Put(int id, [FromBody]string value)
        {
            return Request.CreateResponse(HttpStatusCode.OK);
        }

        public void DeleteFile(string filename)
        {
            string filePathAndName = GetAttachmentFilePathAndName(filename, GetUserId().Value);

            if (System.IO.File.Exists(filePathAndName))
            {
                try
                {
                    System.IO.File.Delete(filePathAndName);
                }
                catch (Exception)
                {
                    //TODO log
                }
            }
        }

        public string GetAttachmentFilePathAndName(string filename, Guid userId)
        {
            string rootFolder = AppConfigHelper.GetWebConfigValue(Constants.RootUploadFolder);

            string fileName = Path.GetFileName(filename).ToLower();
            string filePathAndName = Path.Combine(rootFolder, userId.ToString(), fileName);
            return filePathAndName;
        }

        protected DateTime GetDateFromSessionOrToday()
        {
            DateTime currentDate = DateTime.Today;
            //var dateInSession = Session["startDate"] as DateTime?;
            //if (dateInSession.HasValue)
            //{
            //    currentDate = dateInSession.Value;
            //}
            return currentDate;
        }
    }
}


text:
class ChangeColumnLedger < ActiveRecord::Migration
  def change
    remove_column :ledgers, :calendar_id
    add_column :ledgers, :statement_id, :integer
    add_foreign_key :ledgers, :statements
  end
end


text:
import { TestBed, async, inject } from '@angular/core/testing';

import { LoggedInGuard } from './logged-in.guard';

describe('LoggedInGuard', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [LoggedInGuard]
    });
  });

  it('should ...', inject([LoggedInGuard], (guard: LoggedInGuard) => {
    expect(guard).toBeTruthy();
  }));
});


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

  	<EditText android:id="@+id/rename"
	  android:singleLine="true"
	  android:layout_width="match_parent"
	  android:layout_height="wrap_content"
	  android:layout_marginLeft="10dp"
	  android:layout_marginRight="10dp"/>

</LinearLayout>


text:
package in.droun.hammernet;

import static org.apache.commons.lang3.StringUtils.isNotBlank;

import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 *
 * @author Pedro F. Hernandez <digitalrounin@gmail.com>
 */
public class NetworkInterfaceInfo {

    /**
     * Internal instance of {@link InterfaceQuery}.
     */
    private final transient InterfaceQuery mInterfaceQuery;

    public static final int MAX_INTERFACE_NAME_LENGTH = 128;

    /**
     * Simple NetworkInterfaceInfo constructor.
     */
    public NetworkInterfaceInfo() {
        this(new InterfaceQuery());
    }

    /**
     * This constructor is only intended to aid with unit testing. This constructor allows for an
     * instance of {@link InterfaceQuery} to be injected, making it easier to perform testing.
     *
     * @param interfaceQuery instance of {@link  InterfaceQuery}.
     */
    protected NetworkInterfaceInfo(final InterfaceQuery interfaceQuery) {
        mInterfaceQuery = interfaceQuery;
    }

    /**
     * Converts a MAC address string to byte array.
     *
     * @param macString Any MAC address in string form, bytes delimited by either ':', '-', or ' '.
     *
     * @return BigInteger of given MAC address.
     */
    public static BigInteger macAddressToBigInteger(final String macString) {

        // Validate
        final int maxMacStringLength = 17;
        String cleanMacString = null;
        if (isNotBlank(macString) && macString.length() <= maxMacStringLength) {

            // Cleanup and revalidate
            cleanMacString = macString.replaceAll("[:\\.\\s-]", "").toLowerCase();
            if (!cleanMacString.matches("[0-9a-f]{12}")) {
                cleanMacString = null;
            }
        }

        // Convert
        BigInteger result = null;
        if (isNotBlank(cleanMacString)) {
            final char[] macNibbles = cleanMacString.toCharArray();

            final int macByteSize = 6;
            final byte[] macAddress = new byte[macByteSize];
            for (int i = 0; i < macByteSize; i++) {
                final int pos = i * 2;
                macAddress[i] = Integer.decode("0x" + macNibbles[pos] + macNibbles[pos + 1])
                        .byteValue();
            }

            result = new BigInteger(macAddress);
        }

        return result;
    }

    /**
     * Returns the Wi-Fi interface name on an Android device.
     *
     * @param macAddress MAC address of interface name to find.
     *
     * @return The interface name of the Wi-Fi adapter. If there is no Wi-Fi adapter, null is
     *         returned. This is typical the case for Android Virtual Machines.
     *
     * @throws SocketException
     *
     * <!-- CHECKSTYLE.OFF: LineLength - URLs, cannot shorten -->
     * @see <a
     * href="http://stackoverflow.com/questions/4677684/wifi-network-interface-name/18657669#18657669">
     * Stackoverflow: wifi network interface name</a> - for more information.
     * <!-- CHECKSTYLE.ON: LineLength -->
     */
    public String getNameByMacAddress(final BigInteger macAddress) throws SocketException {

        // Fetch list of interfaces on the device and iterate
        final Enumeration<NetworkInterface> interfaces = mInterfaceQuery.getNetworkInterfaces();
        String result = null;
        if (macAddress != null && interfaces != null) {
            while (interfaces.hasMoreElements()) {
                final NetworkInterface current = interfaces.nextElement();

                final byte[] hardwareAddress;
                try {
                    hardwareAddress = current.getHardwareAddress();
                } catch (SocketException socketException) {
                    // getHardwareAddress() throws "java.net.SocketException: No such device" on
                    // the Jenkins, just skip these interfaces.
                    continue;
                }

                if (hardwareAddress == null) {
                    continue;
                }

                // Next NOPMD is for AvoidInstantiatingObjectsInLoops, no choice in the matter
                final BigInteger currentMac = new BigInteger(hardwareAddress); // NOPMD
                if (currentMac.equals(macAddress)) {
                    // If the current interface's and WiFi MAC match, we have a winner
                    result = current.getName();
                    break;
                }
            }
        }

        return result;
    }

    /**
     * Returns the numeric representation of this IPv4 address (such as
     * "2001:0db8:85a3:0000:0000:8a2e:0370:7334").
     *
     * @param interfaceName name of interface.
     *
     * @return Interface's IP address
     *
     * @throws SocketException if a network error occurs.
     */
    public String getIp4HostAddressByName(final String interfaceName) throws SocketException {
        return getHostAddressByName(interfaceName, Inet4Address.class);
    }

    /**
     * Returns the numeric representation of this IP address (such as "127.0.0.1"). Can return
     * either IPv4 or IPv6, depending on value of clazz.
     *
     * @param interfaceName name of interface.
     * @param clazz         type of address to return. Either Inet4Address or Inet4Address. Returns
     *                      null if not found.
     *
     * @return Interface's IP address
     *
     * @throws SocketException if a network error occurs.
     */
    protected String getHostAddressByName(final String interfaceName, final Class clazz)
            throws SocketException {

        final NetworkInterface adaptor
                = isNotBlank(interfaceName) && interfaceName.length() <= MAX_INTERFACE_NAME_LENGTH
                ? mInterfaceQuery.getByName(interfaceName) : null;

        // Query for information requested
        String result = null;
        if (adaptor != null && clazz != null) {
            final Enumeration<InetAddress> addresses = adaptor.getInetAddresses();
            while (addresses.hasMoreElements()) {
                final InetAddress currentAddress = addresses.nextElement();
                if (currentAddress != null && clazz.isInstance(currentAddress)) {
                    result = currentAddress.getHostAddress();
                    break;
                }
            }
        }
        return result;
    }

    /**
     * This internal class is only intended to be used in unit testing. It wraps around
     * {@link java.net.NetworkInterface}. It basically allows for easier mocking.
     */
    protected static class InterfaceQuery {

        /**
         * A wrapper around {@link java.net.NetworkInterface#getByName(java.lang.String)}.
         *
         * @param name
         *
         * @return
         *
         * @throws SocketException
         */
        protected NetworkInterface getByName(final String name) throws SocketException {
            return NetworkInterface.getByName(name);
        }

        /**
         * A wrapper around {@link java.net.NetworkInterface#getNetworkInterfaces()}.
         *
         * @return
         *
         * @throws SocketException
         */
        protected Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException {
            return NetworkInterface.getNetworkInterfaces();
        }
    }
}