text:
/* eslint global-require:0 */
import { createStore as _createStore, applyMiddleware, compose } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import reduxThunk from 'redux-thunk';
import reduxCatch from 'redux-catch';
import reducer from 'App/reducer';
import actionLogger from './middleware/actionLogger';

function middlewareHandler(error) {
    console.log(error);
}

export default function createStore(history, data) {
    // Sync dispatched route actions to the history
    const reduxRouterMiddleware = routerMiddleware(history);

    const middleware = [
        reduxCatch(middlewareHandler),
        reduxThunk,
        reduxRouterMiddleware,
        actionLogger
    ];

    let finalCreateStore;
    if (__CLIENT__ && window.devToolsExtension) {
        finalCreateStore = compose(
            applyMiddleware(...middleware),
            // The devtools extension is injecting this function into the document
            // so we can call it. It returns a middleware definition that allows
            // it to hook into events right before they enter the root reducer
            window.devToolsExtension()
        )(_createStore);
    } else {
        finalCreateStore = applyMiddleware(...middleware)(_createStore);
    }

    const store = finalCreateStore(reducer, data);

    if (__DEVELOPMENT__ && module.hot) {
        module.hot.accept('App/reducer', () => {
            store.replaceReducer(require('App/reducer').default);
        });
    }

    return store;
}


text:
package com.compositesw.services.system.admin.resource;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for wsdlDocumentSet complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="wsdlDocumentSet">
 *   <complexContent>
 *     <extension base="{http://www.compositesw.com/services/system/admin/resource}xmlDocumentSet">
 *       <sequence>
 *         <element name="importedDocuments" minOccurs="0">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence>
 *                   <element name="importedDocument" type="{http://www.compositesw.com/services/system/admin/resource}wsdlDocumentSet" maxOccurs="unbounded" minOccurs="0"/>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "wsdlDocumentSet", propOrder = {
    "importedDocuments"
})
public class WsdlDocumentSet
    extends XmlDocumentSet
{

    protected WsdlDocumentSet.ImportedDocuments importedDocuments;

    /**
     * Gets the value of the importedDocuments property.
     *
     * @return
     *     possible object is
     *     {@link WsdlDocumentSet.ImportedDocuments }
     *
     */
    public WsdlDocumentSet.ImportedDocuments getImportedDocuments() {
        return importedDocuments;
    }

    /**
     * Sets the value of the importedDocuments property.
     *
     * @param value
     *     allowed object is
     *     {@link WsdlDocumentSet.ImportedDocuments }
     *
     */
    public void setImportedDocuments(WsdlDocumentSet.ImportedDocuments value) {
        this.importedDocuments = value;
    }

    /**
     *
Java class for anonymous complex type.
     *
     *
The following schema fragment specifies the expected content contained within this class.
     *
     *

     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <sequence>
     *         <element name="importedDocument" type="{http://www.compositesw.com/services/system/admin/resource}wsdlDocumentSet" maxOccurs="unbounded" minOccurs="0"/>
     *       </sequence>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     *

     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "importedDocument"
    })
    public static class ImportedDocuments {

        protected List<WsdlDocumentSet> importedDocument;

        /**
         * Gets the value of the importedDocument property.
         *
         *

         * This accessor method returns a reference to the live list,
         * not a snapshot. Therefore any modification you make to the
         * returned list will be present inside the JAXB object.
         * This is why there is not a set method for the importedDocument property.
         *
         *

         * For example, to add a new item, do as follows:
         *

         *    getImportedDocument().add(newItem);
         *

         *
         *
         *

         * Objects of the following type(s) are allowed in the list
         * {@link WsdlDocumentSet }
         *
         *
         */
        public List<WsdlDocumentSet> getImportedDocument() {
            if (importedDocument == null) {
                importedDocument = new ArrayList<WsdlDocumentSet>();
            }
            return this.importedDocument;
        }

    }

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">

	<!-- SECURITY -->
	<security:global-method-security
		secured-annotations="enabled" />

	<security:http auto-config="true" >
		<!-- Restrict URLs based on role -->
		<security:intercept-url pattern="/secured.do" access="ROLE_ADMIN"/>
		<security:intercept-url pattern="/**"
			access="IS_AUTHENTICATED_ANONYMOUSLY"/>

		<security:anonymous granted-authority="IS_AUTHENTICATED_ANONYMOUSLY"/>

		<!-- Override default login and logout pages -->
		<security:form-login login-page="/home.do"
			default-target-url="/home.do" authentication-failure-url="/loginFailure.do" />
		<security:logout logout-success-url="/logout.do" />

		<security:remember-me key="rememberMeKey" />

	</security:http>

	<bean id="rememberMeFilter" class=
	 "org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
	  <property name="rememberMeServices" ref="rememberMeServices"/>
	  <property name="authenticationManager" ref="authManager" />
	</bean>

	<bean id="rememberMeServices" class=
	 "org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
	  <property name="userDetailsService" ref="userDetailsService"/>
	  <property name="key" value="rememberMeKey"/>
	</bean>

	<security:authentication-manager alias="authManager">
		<security:authentication-provider user-service-ref="userDetailsService"/>
	</security:authentication-manager>

	<bean id="userDetailsService"
		class="com.amazon.aws.samplecode.travellog.web.SpringAuthenticator">
	</bean>

	<!-- END SECURITY -->

</beans>


text:
program phelloworld

  implicit none

include 'mpif.h'

  !! eigenvalue system
  integer,parameter :: N=2,LDA=2
  character(len=1),parameter :: UPLO='F' ! 'L' or 'U' also fine
  double precision,dimension(N*N) :: A=(/2.0d0,-1.0d0,-1.0d0,2.0d0/)
  double precision :: Emin=-5.0d0, Emax=5.0d0
  integer :: M0=2 ! (Initial) subspace dimension
  !! input parameters for FEAST
  integer,dimension(64) :: feastparam
  !! output variables for FEAST
  double precision,dimension(:),allocatable :: E, res
  double precision,dimension(:,:),allocatable :: X
  double precision :: epsout
  integer :: i,loop,info,M

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! MPI!!!!!!!!!!!!!!!!!!!!
integer :: code,rank,nb_procs
  call MPI_INIT(code)
  call MPI_COMM_SIZE(MPI_COMM_WORLD,nb_procs,code)
  call MPI_COMM_RANK(MPI_COMM_WORLD,rank,code)
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

!!! Allocate memory for eigenvalues.eigenvectors/residual
  allocate(E(M0))
  allocate(res(M0))
  allocate(X(N,M0))

!!!!!!!!!! FEAST
  call feastinit(feastparam)
  feastparam(1)=1 !! change from default value
  call dfeast_syev(UPLO,N,A,LDA,feastparam,epsout,loop,Emin,Emax,M0,E,X,M,res,info)

!!!!!!!!!! REPORT
if (rank==0) then
  print *,'FEAST OUTPUT INFO',info
  if (info==0) then
     print *,'*************************************************'
     print *,'************** REPORT ***************************'
     print *,'*************************************************'
     print *,'# processors',nb_procs
     print *,'# Search interval [Emin,Emax]',Emin,Emax
     print *,'# mode found/subspace',M,M0
     print *,'# iterations',loop
     print *,'TRACE',sum(E(1:M))
     print *,'Relative error on the Trace',epsout
     print *,'Eigenvalues/Residuals'
     do i=1,M
        print *,i,E(i),res(i)
     enddo
     print *,'Eigenvectors'
     do i=1,M
        print *,i,"(",X(1,i),X(2,i),")"
     enddo
  endif
endif

call MPI_FINALIZE(code)

end program phelloworld


text:
Compiled example
----------------
![Example](countable-sets.png)


text:
CommandLine parser

[![NuGet version](https://img.shields.io/nuget/v/commandline.net.svg?style=flat)](https://www.nuget.org/packages/CommandLine.Net/)
[![Nuget downloads](https://img.shields.io/nuget/dt/commandline.net.svg?style=flat)](https://www.nuget.org/packages/CommandLine.Net/)
![Build And Test](https://github.com/AlexGhiondea/CommandLine/workflows/Build%20And%20Test/badge.svg)
[![codecov](https://codecov.io/gh/AlexGhiondea/CommandLine/branch/master/graph/badge.svg)](https://codecov.io/gh/AlexGhiondea/CommandLine)
[![MIT License](https://img.shields.io/github/license/AlexGhiondea/CommandLine.svg)](https://github.com/AlexGhiondea/CommandLine/blob/master/LICENSE)
[![Code Factor](https://www.codefactor.io/repository/github/alexghiondea/commandline/badge)](https://www.codefactor.io/repository/github/alexghiondea/commandline)
========

## Getting started

First install the package:

```powershell
Install-Package CommandLine.Net
```

Then you can define a class that can be used with the parser:

```csharp
class Options
{
    [RequiredArgument(0,"dir","Directory")]
    public string Directory { get; set; }

    [OptionalArgument("*.*","pattern", "Search pattern")]
    public string SearchPattern { get; set; }
}
```

This is the code that you need to parse the command line arguments into an object:

```csharp
if (!Parser.TryParse(args, out Options options))
{
    return;
}
```

The parser understands common requests for help as you can see below.

## Display the available commands

The parser understand the following help commands:
 - `-?` which is the short form help

 ```
Usage:
 <exename> dir [-pattern value]

For detailed information run '<exename> --help'.
 ```

 - `--help` which is the long form help

 ```
Usage:
 <exename> dir [-pattern value]
  - dir     : Directory (string, required)
  - pattern : Search pattern (string, default=*.*)
 ```
### Display the help using code

If you want to display the help manually, you can use the `Parser.DisplayHelp()` API to do it:
```csharp
Parser.DisplayHelp<Options>();
```

By default, the API assumes you are using the `HelpFormat.Short` specifier which maps to `/?` or `-?`.

You can ask for the long version of the help by using the `HelpFormat.Full` specifier:

```csharp
Parser.DisplayHelp<Options>(HelpFormat.Full);
```

### Specifying multiple enum values

If you have an enum defined as a flags enum, you need to pass this value as an argument in order for it to be correctly parsed: `"A, B"` or `A,B`.
```csharp
[Flags]
enum MyFlags
{
  A = 1,
  B = 2
}
```
Note:
- The enum values need to be starting at 1, otherwise when the OR operation happens, the value that is 0 will be lost
- The string needs to either be inside a double quote (if it contains a space) or have no space inside

## Types of arguments

To use you need to provide a class that is going to hold the options parsed from the command line and use attributes to define the behavior of the parser.

There are 2 kinds of arguments:
 - Required
   - These must be specified
   - They have a specific location where they must be specified
 - Optional
   - They don't have to be specified
   - They have a name that you need to provide on the command line before you provide the value
   - If they are not specified, the object parsed will have the default value specified.'

## Advanced scenarios

### Argument grouping
There are cases when you want to have different sets of arguments depending on one of the arguments.

The argument that will be used as the differentiator will be marked with the `ActionArgument` attribute. That argument must be specified.

You can then define multiple groups of arguments.
You will specify the argument group for a property using the `ArgumentGroup` attribute.
A single property in a class can take part in many argument groups.

If a property will be common to all groups, you can use the `CommonArgument' attribute

```csharp
internal class CommandLineOptions
{
    [ActionArgument]
    public CommandLineActionGroup Action { get; set; }

    [CommonArgument]
    [RequiredArgumentAttribute(0, "host", "The name of the host")]
    public string Host { get; set; }

    #region Add-host Action
    [RequiredArgument(1, "mac", "The MAC address of the host")]
    [ArgumentGroup(nameof(CommandLineActionGroup.add))]
    public string MAC { get; set; }

    #endregion
}
```

If you have a required argument that is shared between multiple argument groups but use different positions, you can tweak the expected position depending on the group

```csharp
internal class CommandLineOptions
{
    [ActionArgument]
    public CommandLineActionGroup Action { get; set; }

    // Here the argument 'name' is expected at position 1 in the add group and position 0 in the list group
    [ArgumentGroup(nameof(CommandLineActionGroup.list), 0)]
    [ArgumentGroup(nameof(CommandLineActionGroup.add))]
    [RequiredArgumentAttribute(1, "name", "The name of the host")]
    public string Host { get; set; }

    [ArgumentGroup(nameof(CommandLineActionGroup.add))]
    [RequiredArgumentAttribute(0, "host", "The name of the host")]
    public string Host { get; set; }

}
```

### Argument position override

Sometimes you want to have a common parameter shared across multiple commands, but you want the position of it to be different in those two groups.

To do that, you use the constructor for the `ArgumentGroup` attribute that takes as the second argument the override position for that argument group.

In the example below, the common parameter `repos` is defined as required in position `1`.
For the group `Create` where no override position is specified, the parameter will be required at position `1`.
For the group `List` where the override position is specified, the parameter will be required at position `0`.

```csharp
class OverridePositionGroup
{
    [ActionArgument]
    public Action Action { get; set; }

    [ArgumentGroup(nameof(Action.Create))]
    [RequiredArgument(0, "milestoneInputFile", "The file containing the list of milestones to create.")]
    public string MilestoneFile { get; set; }

    [ArgumentGroup(nameof(Action.List), 0)]
    [ArgumentGroup(nameof(Action.Create))]
    [RequiredArgument(1, "repos", "The list of repositories where to add the milestones to. The format is: owner\\repoName.", true)]
    public List<string> Repositories { get; set; }
}
```

### Background color

The parser will automatically detect the color to use when displaying help in a command prompt. There are a set of colors that are predefined depending on the console color.

You can specify different colors to be used by implementing the `IColor` interface and configuring the parser:

```csharp
public class CustomColors : IColors
{
    public ConsoleColor ErrorColor => ConsoleColor.Red;
    public ConsoleColor AssemblyNameColor => ConsoleColor.DarkGray;
    public ConsoleColor ArgumentGroupColor => ConsoleColor.DarkGreen;
    public ConsoleColor RequiredArgumentColor => ConsoleColor.Magenta;
    public ConsoleColor ArgumentValueColor => ConsoleColor.DarkGreen;
    public ConsoleColor OptionalArgumentColor => ConsoleColor.DarkBlue;
}

// Configure the parser to use the new colors
Parser.Configuration.DisplayColors.Set(new CustomColors());
```

### Environment variable parsing

By default, the parser will try and infer optional parameters from the environment variables if they are not specified in the command line.

The order of precedence is going to be (from most specific to least specific):
1. Values passed in via the command line
2. Values specified in the environment
3. Default value specified in the argument type

By default, the Parser will look for environment variables with this name:

```
CommandLine_<name>
```

The `<name>` represents the optional parameter name as defined in the type declaration.

You can change the prefix for the Parser:
```csharp
ParserOptions parserOptions = new ParserOptions() { VariableNamePrefix = "myPrefix" };

if (!Parser.TryParse(args, out Options options, parserOptions))
{
    return;
}
```

You can also disable the feature completely:
```csharp
ParserOptions parserOptions = new ParserOptions() { ReadFromEnvironment = false };

if (!Parser.TryParse(args, out Options options, parserOptions))
{
    return;
}
```


text:
using Microsoft.Owin.Security;
using System.IdentityModel.Selectors;

namespace Thinktecture.IdentityModel.Owin
{
    public class ClientCertificateAuthenticationOptions : AuthenticationOptions
    {
        public X509CertificateValidator Validator { get; set; }
        public bool CreateExtendedClaimSet { get; set; }

        public ClientCertificateAuthenticationOptions() : base("X.509")
        {
            Validator = X509CertificateValidator.ChainTrust;
            CreateExtendedClaimSet = false;
        }
    }
}


text:
<?php echo $this->lang->line('module_dashboard');?>

<?php echo $this->lang->line('label_change_password');?>

<?php echo $this->lang->line('label_profile');?>

<?php echo $this->lang->line('label_preferences');?>

<?php echo $this->lang->line('label_admin_menu_settings');?>

<?php echo $this->lang->line('label_extra_fields');?>

<?php foreach($users->result() as $id):?>

	<?php echo form_open("auth/edit_profile");?>
	<fieldset>
	<legend><?php echo $this->lang->line('module_dashboard');?></legend>

		<?php echo $this->lang->line('label_email_address');?>
			<input type="text" class="form-control" name="email" value="<?php echo $id->email?>" />

		<?php echo $this->lang->line('label_first_name');?>
			<input type="text" class="form-control" name="first_name" value="<?php echo $id->first_name?>" />

		<?php echo $this->lang->line('label_last_name');?>
			<input type="text" class="form-control" name="last_name" value="<?php echo $id->last_name?>" />

		<?php if($this->config->item('company_enabled') == 'Y'):?>

		<?php echo $this->lang->line('label_company_name');?>
			<input type="text" class="form-control" name="company" value="<?php echo $id->company?>" />

		<?php endif;?>

		<?php if($this->config->item('phone_enabled') == 'Y'):?>

		<?php echo $this->lang->line('label_phone');?>
			<input type="text" class="form-control" name="phone" value="<?php echo $id->phone?>" />

		<?php endif;?>

		<?php echo form_submit('submit', 'Submit', 'class="btn btn-primary"');?>

	<?php echo form_close();?>
	</fieldset>

<?php endforeach;?>

<?php echo modules::run('users/auth/change_password');?>

<?php echo modules::run('profile/edit_profile');?>

<?php echo modules::run('profile/edit_preferences');?>

<?php echo modules::run('profile/edit_settings');?>

<?php echo modules::run('profile/custom_fields');?>


text:
package chipmunk

import (
	"github.com/CossackPyra/chipmunk/vect"
)

// Wrapper around []vect.Vect.
type Vertices []vect.Vect

// Checks if verts forms a valid polygon.
// The vertices must be convex and winded clockwise.
func (verts Vertices) ValidatePolygon() bool {
	numVerts := len(verts)
	for i := 0; i < numVerts; i++ {
		a := verts[i]
		b := verts[(i+1)%numVerts]
		c := verts[(i+2)%numVerts]

		if vect.Cross(vect.Sub(b, a), vect.Sub(c, b)) > 0.0 {
			return false
		}
	}

	return true
}


text:
[![Build Status](https://github.com/lindenbaum/hinterface/workflows/Test/badge.svg)](https://github.com/lindenbaum/hinterface/actions)

[![Hackage](https://img.shields.io/hackage/v/hinterface)](http://hackage.haskell.org/package/hinterface)

# hinterface - Haskell / Erlang interoperability library

Inspired by Jinterface (Java), a set of tools for communication with Erlang processes.


text:
import Directive from '@grid/view/directives/directive';
import cellBuilder from '../cell/cell.build';
import {VIEW_CORE_NAME, TF_CORE_NAME, TABLE_CORE_NAME, GRID_NAME} from '@grid/view/definition';
import {TdCtrl} from '@grid/core/cell/td.ctrl';

const classify = TdCtrl.classify;

class TfCore extends Directive(TF_CORE_NAME, {
	view: `^^${VIEW_CORE_NAME}`,
	table: `^^${TABLE_CORE_NAME}`,
	root: `^^${GRID_NAME}`
}) {
	constructor($scope, $element) {
		super();

		this.$element = $element;
		this.$scope = $scope;
	}

	onInit() {
		const column = this.column;
		this.root.bag.foot.addCell(this);

		classify(this.element, column);

		const model = this.view.model;
		const cache = model.foot().cache;
		const rowIndex = this.rowIndex;
		const key = rowIndex > 0 ? column.key + rowIndex : column.key;
		let link = cache.find(key);
		if (!link) {
			const build = cellBuilder(this.root.template);
			link = build('foot', this.view.model, this.column);
			cache.set(key, link);
		}

		link(this.$element, this.$scope);
	}

	get value() {
		const column = this.column;
		return this.view.foot.value(column);
	}

	get rowIndex() {
		return this.$scope.$parent.$index;
	}

	get column() {
		return this.$scope.$column.model;
	}

	get columnIndex() {
		return this.$scope.column.index;
	}

	get element() {
		return this.$element[0];
	}

	onDestroy() {
		this.root.bag.foot.deleteCell(this);
	}
}

TfCore.$inject = [
	'$scope',
	'$element'
];

export default {
	restrict: 'A',
	bindToController: true,
	controllerAs: '$cell',
	controller: TfCore,
	require: TfCore.require,
	link: TfCore.link,
	scope: false
};


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Skift: A/B test basic example</title>

Skift: A/B test basic example

This is an A/B split test

Below there's a div. It will be blue originally, and orange if you're in the A/B test.

<button id="test-button">This is the original div</button>
<button onclick="skift.reset();">Reset</button>


text:
var Scrape, config, scrape;
Scrape = require('./scrape.js');
config = require('./config.js');

console.log('Initializing scrape...');
scrape = new Scrape.scrape({});


text:
package mongo

import (
	"github.com/globalsign/mgo"
)

// define global handler
var (
	GH *Handler
)

// LoadHandler load global handler
func LoadHandler(url, dbName string) {
	h, err := InitHandlerWithDB(url, dbName)
	if err != nil {
		panic(err)
	}
	GH = h
}

// Session get current session
func Session() *mgo.Session {
	return GH.Session()
}

// CloneSession clone session
func CloneSession() *mgo.Session {
	return GH.CloneSession()
}

// DB get database
func DB() *mgo.Database {
	return GH.DB()
}

// DBWithName get database with name
func DBWithName(dbName string) *mgo.Database {
	return GH.DBWithName(dbName)
}

// CHandle use the default DB processing with a set of callback functions,
// the session will be closed down after processing is completed
func CHandle(cName string, handle func(c *mgo.Collection)) {
	GH.CHandle(cName, handle)
}

// CHandleWithDB use the new DB processing with a set of callback functions,
// the session will be closed down after processing is completed
func CHandleWithDB(dbName, cName string, handle func(c *mgo.Collection)) {
	GH.CHandleWithDB(dbName, cName, handle)
}

// C use the default db get collection
func C(cName string) *mgo.Collection {
	return GH.C(cName)
}

// CWithDB use the new db get collection
func CWithDB(dbName, cName string) *mgo.Collection {
	return GH.CWithDB(dbName, cName)
}

// IncrID get increase id
func IncrID(cName string, storeCName ...string) (id int64, err error) {
	id, err = GH.IncrID(cName, storeCName...)
	return
}


text:
#ifndef ORM_FK_HPP
#define ORM_FK_HPP

#include <ORM/fields/private/FKBase.hpp>

namespace orm
{
    /**
     * \brief exactly like FKBase, but make nullable as template param
     **/
    template<typename T,bool NULLABLE=true>
    class FK : public FKBase<T>
    {
        public:
            /**
             * \brief Construct a FK
             *
             * \param column colum where the fk is stored
             **/
            FK(const std::string& column);

            FK(const FK&) = delete;

            using FKBase<T>::operator->;
            using FKBase<T>::operator*;
            using FKBase<T>::operator bool;
            using FKBase<T>::operator typename T::pointer;
            using FKBase<T>::operator=;
    };
}

#include <ORM/fields/FK.tpl>

#endif


text:
using InBloomClient.Enum;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace InBloomClient.Entities
{
    public class ElectronicMail
    {
        [DataType(DataType.EmailAddress)]
        public string emailAddress { get; set; }

        [JsonConverter(typeof(StringEnumConverter))]
        public ElectronicMailAddressType emailAddressType { get; set; }
    }
}


text:
package org.jrebirth.af.showcase.demo.ui;

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

import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;

import org.jrebirth.af.api.exception.CoreException;
import org.jrebirth.af.api.ui.ModuleModel;
import org.jrebirth.af.core.ui.DefaultView;

/**
 *
 * The class MainView.
 *
 * The main view of the JRebirth Analyzer application.
 *
 * @author Sébastien Bordes
 */
public final class MainView extends DefaultView<MainModel, BorderPane, MainController> {

    private final List<Button> buttonList = new ArrayList<>();

    /**
     * Default Constructor.
     *
     * @param model the view model
     *
     * @throws CoreException if build fails
     */
    public MainView(final MainModel model) throws CoreException {
        super(model);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initView() {

        node().setPrefSize(800, 600);

        node().setLeft(createMenu());

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void start() {
        this.buttonList.stream().findFirst().ifPresent(Button::fire);
    }

    private Node createMenu() {
        final VBox box = new VBox();

        model().getModules().stream()
               .map(this::createModuleButton)
               .forEach(box.getChildren()::add);

        return box;
    }

    private Button createModuleButton(final ModuleModel mm) {
        final Button b = new Button(mm.moduleName());

        b.getStyleClass().add("menuButton");
        b.setPrefSize(100, 50);
        b.setOnAction(controller()::onButtonFired);
        b.setUserData(mm.key());

        VBox.setMargin(b, new Insets(4, 4, 4, 4));
        this.buttonList.add(b);

        return b;
    }

}


text:
<?php

return [

    'full_name'                   => 'Nome completo',
    'email'                       => 'Email',
    'password'                    => 'Password',
    'retype_password'             => 'Ripeti password',
    'remember_me'                 => 'Ricordami',
    'register'                    => 'Registrazione',
    'register_a_new_membership'   => 'Registra un nuovo abbonamento',
    'i_forgot_my_password'        => 'Ho dimenticato la password',
    'i_already_have_a_membership' => 'Ho già un abbonamento',
    'sign_in'                     => 'Accedi',
    'log_out'                     => 'Logout',
    'toggle_navigation'           => 'Attiva la navigazione',
    'login_message'               => 'Accedi per iniziare la tua sessione',
    'register_message'            => 'Registra un nuovo abbonamento',
    'password_reset_message'      => 'Resetta la password',
    'reset_password'              => 'Resetta la password',
    'send_password_reset_link'    => 'Invia link di reset della password',
];


text:
require 'spec_helper'

describe PagesController do
  render_views

  before(:each) do
    @base_title = "Ruby on Rails Tutorial Sample App"
  end

  describe "GET 'home'" do
    it "should be successful" do
      get 'home'
      response.should be_success
    end

    it "should have the right title" do
      get 'home'
      response.should have_selector("title",
        :content => @base_title + " | Home")
    end
  end

  describe "GET 'contact'" do
    it "should be successful" do
      get 'contact'
      response.should be_success
    end

    it "should have the right title" do
      get 'contact'
      response.should have_selector("title",
        :content => @base_title + " | Contact")
    end
  end

  describe "GET 'about'" do
    it "should be successful" do
      get 'about'
      response.should be_success
    end

    it "should have the right title" do
      get 'about'
      response.should have_selector("title",
        :content => @base_title + " | About")
    end

  end

  describe "GET 'help'" do
    it "should be successful" do
      get 'help'
      response.should be_success
    end

    it "should have the right title" do
      get 'help'
      response.should have_selector("title",
        :content => @base_title + " | Help")
    end

  end

end


text:
<?php

namespace Thruster\Bundle\DoctrineActionsBundle\Tests;

use Thruster\Bundle\DoctrineActionsBundle\DoctrinePersistActionExecutor;

class DoctrinePersistActionExecutorTest extends \PHPUnit_Framework_TestCase
{
    public function testExecuteRegistryDefault()
    {
        $object = new \stdClass();

        $em = $this->getMockBuilder('\Doctrine\ORM\EntityManager')
            ->disableOriginalConstructor()
            ->getMock();

        $em->expects($this->once())
            ->method('persist')
            ->with($object);

        $em->expects($this->once())
            ->method('flush');

        $registry = $this->getMockBuilder('\Doctrine\Bundle\DoctrineBundle\Registry')
            ->disableOriginalConstructor()
            ->getMock();

        $registry->expects($this->once())
            ->method('getManager')
            ->with('default')
            ->willReturn($em);

        $executor = new DoctrinePersistActionExecutor($registry);
        $executor->execute([$object]);
    }

    public function testExecuteRegistryCustomManager()
    {
        $object = new \stdClass();

        $em = $this->getMockBuilder('\Doctrine\ORM\EntityManager')
            ->disableOriginalConstructor()
            ->getMock();

        $em->expects($this->once())
            ->method('persist')
            ->with($object);

        $em->expects($this->once())
            ->method('flush');

        $registry = $this->getMockBuilder('\Doctrine\Bundle\DoctrineBundle\Registry')
            ->disableOriginalConstructor()
            ->getMock();

        $registry->expects($this->once())
            ->method('getManager')
            ->with('custom')
            ->willReturn($em);

        $executor = new DoctrinePersistActionExecutor($registry);
        $executor->execute(['custom', $object]);
    }
}


text:
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// 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.
package com.google.devtools.build.lib.packages;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.eventbus.EventBus;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
import com.google.devtools.build.lib.events.Location;
import com.google.devtools.build.lib.events.Reporter;
import com.google.devtools.build.lib.packages.RuleFactory.BuildLangTypedAttributeValuesMap;
import com.google.devtools.build.lib.packages.util.PackageLoadingTestCase;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.testutil.TestRuleClassProvider;
import com.google.devtools.build.lib.vfs.Path;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class RuleFactoryTest extends PackageLoadingTestCase {

  private ConfiguredRuleClassProvider provider = TestRuleClassProvider.getRuleClassProvider();
  private RuleFactory ruleFactory =
      new RuleFactory(provider, AttributeContainer.ATTRIBUTE_CONTAINER_FACTORY);

  public static final Location LOCATION_42 = Location.fromFileAndOffsets(null, 42, 42);

  @Test
  public void testCreateRule() throws Exception {
    Path myPkgPath = scratch.resolve("/foo/workspace/mypkg/BUILD");
    Package.Builder pkgBuilder =
        packageFactory.newPackageBuilder(PackageIdentifier.createInMainRepo("mypkg"), "TESTING")
            .setFilename(myPkgPath)
            .setMakeEnv(new MakeEnvironment.Builder());

    Map<String, Object> attributeValues = new HashMap<>();
    attributeValues.put("name", "foo");
    attributeValues.put("alwayslink", true);

    RuleClass ruleClass = provider.getRuleClassMap().get("cc_library");
    Rule rule =
        RuleFactory.createAndAddRule(
            pkgBuilder,
            ruleClass,
            new BuildLangTypedAttributeValuesMap(attributeValues),
            new Reporter(new EventBus()),
            /*ast=*/ null,
            LOCATION_42,
            /*env=*/ null,
            new AttributeContainer(ruleClass));

    assertSame(rule, rule.getAssociatedRule());

    // pkg.getRules() = [rule]
    Package pkg = pkgBuilder.build();
    assertThat(Sets.newHashSet(pkg.getTargets(Rule.class))).hasSize(1);
    assertEquals(rule, pkg.getTargets(Rule.class).iterator().next());

    assertSame(rule, pkg.getTarget("foo"));

    assertEquals(Label.parseAbsolute("//mypkg:foo"), rule.getLabel());
    assertEquals("foo", rule.getName());

    assertEquals("cc_library", rule.getRuleClass());
    assertEquals("cc_library rule", rule.getTargetKind());
    assertEquals(42, rule.getLocation().getStartOffset());
    assertFalse(rule.containsErrors());

    // Attr with explicitly-supplied value:
    AttributeMap attributes = RawAttributeMapper.of(rule);
    assertTrue(attributes.get("alwayslink", Type.BOOLEAN));
    try {
      attributes.get("alwayslink", Type.STRING); // type error: boolean, not string!
      fail();
    } catch (Exception e) {
      /* Class of exception and error message are not specified by API. */
    }
    try {
      attributes.get("nosuchattr", Type.STRING); // no such attribute
      fail();
    } catch (Exception e) {
      /* Class of exception and error message are not specified by API. */
    }

    // Attrs with default values:
    // cc_library linkstatic default=0 according to build encyc.
    assertFalse(attributes.get("linkstatic", Type.BOOLEAN));
    assertFalse(attributes.get("testonly", Type.BOOLEAN));
    assertThat(attributes.get("srcs", BuildType.LABEL_LIST)).isEmpty();
  }

  @Test
  public void testCreateWorkspaceRule() throws Exception {
    Path myPkgPath = scratch.resolve("/foo/workspace/WORKSPACE");
    Package.Builder pkgBuilder = packageFactory.newExternalPackageBuilder(myPkgPath, "TESTING");

    Map<String, Object> attributeValues = new HashMap<>();
    attributeValues.put("name", "foo");
    attributeValues.put("actual", "//foo:bar");

    RuleClass ruleClass = provider.getRuleClassMap().get("bind");
    Rule rule =
        RuleFactory.createAndAddRule(
            pkgBuilder,
            ruleClass,
            new BuildLangTypedAttributeValuesMap(attributeValues),
            new Reporter(new EventBus()),
            /*ast=*/ null,
            Location.fromFileAndOffsets(myPkgPath.asFragment(), 42, 42),
            /*env=*/ null,
            new AttributeContainer(ruleClass));
    assertFalse(rule.containsErrors());
  }

  @Test
  public void testWorkspaceRuleFailsInBuildFile() throws Exception {
    Path myPkgPath = scratch.resolve("/foo/workspace/mypkg/BUILD");
    Package.Builder pkgBuilder =
        packageFactory.newPackageBuilder(PackageIdentifier.createInMainRepo("mypkg"), "TESTING")
            .setFilename(myPkgPath)
            .setMakeEnv(new MakeEnvironment.Builder());

    Map<String, Object> attributeValues = new HashMap<>();
    attributeValues.put("name", "foo");
    attributeValues.put("actual", "//bar:baz");

    RuleClass ruleClass = provider.getRuleClassMap().get("bind");
    try {
      RuleFactory.createAndAddRule(
          pkgBuilder,
          ruleClass,
          new BuildLangTypedAttributeValuesMap(attributeValues),
          new Reporter(new EventBus()),
          /*ast=*/ null,
          LOCATION_42,
          /*env=*/ null,
          new AttributeContainer(ruleClass));
      fail();
    } catch (RuleFactory.InvalidRuleException e) {
      assertThat(e.getMessage()).contains("must be in the WORKSPACE file");
    }
  }

  @Test
  public void testBuildRuleFailsInWorkspaceFile() throws Exception {
    Path myPkgPath = scratch.resolve("/foo/workspace/WORKSPACE");
    Package.Builder pkgBuilder =
        packageFactory.newPackageBuilder(Label.EXTERNAL_PACKAGE_IDENTIFIER, "TESTING")
            .setFilename(myPkgPath)
            .setMakeEnv(new MakeEnvironment.Builder());

    Map<String, Object> attributeValues = new HashMap<>();
    attributeValues.put("name", "foo");
    attributeValues.put("alwayslink", true);

    RuleClass ruleClass = provider.getRuleClassMap().get("cc_library");
    try {
      RuleFactory.createAndAddRule(
          pkgBuilder,
          ruleClass,
          new BuildLangTypedAttributeValuesMap(attributeValues),
          new Reporter(new EventBus()),
          /*ast=*/ null,
          Location.fromFileAndOffsets(myPkgPath.asFragment(), 42, 42),
          /*env=*/ null,
          new AttributeContainer(ruleClass));
      fail();
    } catch (RuleFactory.InvalidRuleException e) {
      assertThat(e.getMessage()).contains("cannot be in the WORKSPACE file");
    }
  }

  private void assertAttr(RuleClass ruleClass, String attrName, Type<?> type) throws Exception {
    assertTrue(
        "Rule class '"
            + ruleClass.getName()
            + "' should have attribute '"
            + attrName
            + "' of type '"
            + type
            + "'",
        ruleClass.hasAttr(attrName, type));
  }

  @Test
  public void testOutputFileNotEqualDot() throws Exception {
    Path myPkgPath = scratch.resolve("/foo");
    Package.Builder pkgBuilder =
        packageFactory.newPackageBuilder(PackageIdentifier.createInMainRepo("mypkg"), "TESTING")
            .setFilename(myPkgPath)
            .setMakeEnv(new MakeEnvironment.Builder());

    Map<String, Object> attributeValues = new HashMap<>();
    attributeValues.put("outs", Lists.newArrayList("."));
    attributeValues.put("name", "some");
    RuleClass ruleClass = provider.getRuleClassMap().get("genrule");
    try {
      RuleFactory.createAndAddRule(
          pkgBuilder,
          ruleClass,
          new BuildLangTypedAttributeValuesMap(attributeValues),
          new Reporter(new EventBus()),
          /*ast=*/ null,
          Location.fromFileAndOffsets(myPkgPath.asFragment(), 42, 42),
          /*env=*/ null,
          new AttributeContainer(ruleClass));
      fail();
    } catch (RuleFactory.InvalidRuleException e) {
      assertTrue(e.getMessage(), e.getMessage().contains("output file name can't be equal '.'"));
    }
  }

  /**
   * Tests mandatory attribute definitions for test rules.
   */
  // TODO(ulfjack): Remove this check when we switch over to the builder
  // pattern, which will always guarantee that these attributes are present.
  @Test
  public void testTestRules() throws Exception {
    Path myPkgPath = scratch.resolve("/foo/workspace/mypkg/BUILD");
    Package pkg =
        packageFactory.newPackageBuilder(PackageIdentifier.createInMainRepo("mypkg"), "TESTING")
            .setFilename(myPkgPath)
            .setMakeEnv(new MakeEnvironment.Builder())
            .build();

    for (String name : ruleFactory.getRuleClassNames()) {
      // Create rule instance directly so we'll avoid mandatory attribute check yet will be able
      // to use TargetUtils.isTestRule() method to identify test rules.
      RuleClass ruleClass = ruleFactory.getRuleClass(name);
      Rule rule =
          new Rule(
              pkg,
              pkg.createLabel("myrule"),
              ruleClass,
              Location.fromFile(myPkgPath),
              new AttributeContainer(ruleClass));
      if (TargetUtils.isTestRule(rule)) {
        assertAttr(ruleClass, "tags", Type.STRING_LIST);
        assertAttr(ruleClass, "size", Type.STRING);
        assertAttr(ruleClass, "flaky", Type.BOOLEAN);
        assertAttr(ruleClass, "shard_count", Type.INTEGER);
        assertAttr(ruleClass, "local", Type.BOOLEAN);
      }
    }
  }
}


text:
package org.apache.syncope.client.console.wicket.markup.html.form;

import java.util.Collection;
import java.util.List;
import org.apache.syncope.client.console.commons.SelectChoiceRenderer;
import org.apache.wicket.extensions.markup.html.form.palette.Palette;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.util.ListModel;

public class AjaxPalettePanel<T> extends AbstractFieldPanel<List<T>> {

    private static final long serialVersionUID = 7738499668258805567L;

    protected final Palette<T> palette;

    public AjaxPalettePanel(final String id, final IModel<List<T>> model, final ListModel<T> choices) {
        this(id, model, choices, false);
    }

    public AjaxPalettePanel(final String id, final IModel<List<T>> model, final ListModel<T> choices,
            final boolean allowOrder) {

        this(id, model, choices, new SelectChoiceRenderer<T>(), allowOrder, false);
    }

    public AjaxPalettePanel(final String id, final IModel<List<T>> model, final ListModel<T> choices,
            final IChoiceRenderer<T> renderer, final boolean allowOrder, final boolean allowMoveAll) {

        super(id, model);

        this.palette = createPalette(model, choices, renderer, allowOrder, allowMoveAll);
        add(palette.setOutputMarkupId(true));
        setOutputMarkupId(true);
    }

    protected Palette<T> createPalette(final IModel<List<T>> model, final ListModel<T> choices,
            final IChoiceRenderer<T> renderer, final boolean allowOrder, final boolean allowMoveAll) {

        return new NonI18nPalette<T>("paletteField", model, choices, renderer, 8, allowOrder, allowMoveAll);
    }

    @Override
    public AjaxPalettePanel<T> setModelObject(final List<T> object) {
        palette.setDefaultModelObject(object);
        return this;
    }

    public Collection<T> getModelCollection() {
        return palette.getModelCollection();
    }
}


text:
require_relative '../test_helper'

class ProductTest < ActiveSupport::TestCase

  should have_one(:supplier_product)
  should have_one(:supplier)

end


text: Graphics are taken from http://www.lostgarden.com/2007/05/dancs-miraculously-flexible-game.html


text:
#ifndef QUICKSTEP_UTILITY_TEMPLATE_UTIL_HPP_
#define QUICKSTEP_UTILITY_TEMPLATE_UTIL_HPP_

#include <cstddef>
#include <tuple>
#include <utility>

namespace quickstep {

/** \addtogroup Utility
 *  @{
 */

/**
 * @brief Represents a compile-time sequence of integers.
 *
 * Sequence is defined here for C++11 compatibility. For C++14 and above,
 * std::integer_sequence can be used to achieve the same functionality.
 *
 * TODO(jianqiao): directly use std::integer_sequence if having C++14 support.
 */
template<std::size_t ...>
struct Sequence {};

/**
 * @brief The helper class for creating Sequence. MakeSequence<N>::type is
 *        equivalent to Sequence<1,2,...,N>.
 *
 * MakeSequence is defined here for C++11 compatibility. For C++14 and above,
 * std::make_index_sequence can be used to achieve the same functionality.
 *
 * TODO(jianqiao): directly use std::make_index_sequence if having C++14 support.
 */
template<std::size_t N, std::size_t ...S>
struct MakeSequence : MakeSequence<N-1, N-1, S...> {};

template<std::size_t ...S>
struct MakeSequence<0, S...> {
  typedef Sequence<S...> type;
};

/**
 * @brief Final step of CreateBoolInstantiatedInstance. Now all bool_values are
 *        ready. Instantiate the template and create (i.e. new) an instance.
 */
template <template <bool ...> class T, class ReturnT,
          bool ...bool_values, std::size_t ...i,
          typename Tuple>
inline ReturnT* CreateBoolInstantiatedInstanceInner(Tuple &&args,
                                                    Sequence<i...> &&indices) {
  return new T<bool_values...>(std::get<i>(std::forward<Tuple>(args))...);
}

/**
 * @brief Edge case of the recursive CreateBoolInstantiatedInstance function
 *        when all bool variables have been branched and replaced with compile-time
 *        bool constants.
 */
template <template <bool ...> class T, class ReturnT,
          bool ...bool_values,
          typename Tuple>
inline ReturnT* CreateBoolInstantiatedInstance(Tuple &&args) {
  // Note that the constructor arguments have been forwarded as a tuple (args).
  // Here we generate a compile-time index sequence (i.e. typename MakeSequence<n_args>::type())
  // for the tuple, so that the tuple can be unpacked as a sequence of constructor
  // parameters in CreateBoolInstantiatedInstanceInner.
  constexpr std::size_t n_args = std::tuple_size<Tuple>::value;
  return CreateBoolInstantiatedInstanceInner<T, ReturnT, bool_values...>(
      std::forward<Tuple>(args), typename MakeSequence<n_args>::type());
}

/**
 * @brief A helper function for creating bool branched templates.
 *
 * The scenario for using this helper function is that, suppose we have a class
 * where all template parameters are bools:
 * --
 * template <bool c1, bool c2, bool c3>
 * class SomeClass : public BaseClass {
 *   // This simple function will be invoked in computationally-intensive loops.
 *   inline SomeType someSimpleFunction(...) {
 *     if (c1) {
 *       doSomeThing1();
 *     }
 *     if (c2) {
 *       doSomeThing2();
 *     }
 *     if (c3) {
 *       doSomeThing3();
 *     }
 *   }
 * };
 * --
 * Typically, this bool-paramterized template is for performance consideration.
 * That is, we would like to make a copy of code for each configuration of bool
 * values, so that there will be no branchings in someSimpleFunction().
 *
 * The problem is that, to conditionally instantiate the template, given bool
 * variables c1, c2, c3, we have to do something like this:
 * --
 * if (c1) {
 *   if (c2) {
 *     if (c3) {
 *       return new SomeClass<true, true, true>(some_args...);
 *     } else {
 *       return new SomeClass<true, true, false>(some_args...);
 *     }
 *   } else {
 *     if (c3) {
 *       return new SomeClass<true, false, true>(some_args...);
 *     } else {
 *       return new SomeClass<true, false, false>(some_args...);
 *     }
 * } else {
 *   ...
 * }
 * --
 * Then there will be power(2,N) branches if the template has N bool parameters,
 * making it tedious to do the instantiating.
 *
 * Now, this helper function can achieve the branched instantiation in one
 * statement as:
 * --
 * return CreateBoolInstantiatedInstance<SomeClass,BaseClass>(
 *     std::forward_as_tuple(some_args...), c1, c2, c3);
 * --
 */
template <template <bool ...> class T, class ReturnT,
          bool ...bool_values, typename ...Bools,
          typename Tuple>
inline ReturnT* CreateBoolInstantiatedInstance(Tuple &&args,
                                               const bool tparam,
                                               const Bools ...rest_tparams) {
  if (tparam) {
    return CreateBoolInstantiatedInstance<T, ReturnT, bool_values..., true>(
        std::forward<Tuple>(args), rest_tparams...);
  } else {
    return CreateBoolInstantiatedInstance<T, ReturnT, bool_values..., false>(
        std::forward<Tuple>(args), rest_tparams...);
  }
}

/** @} */

}  // namespace quickstep

#endif  // QUICKSTEP_UTILITY_TEMPLATE_UTIL_HPP_


text:
- Final year student & Security Enthusiast
- Interested in Cloud Security and Artificial Intelligence
- Twitter: [@pingsns](https://twitter.com/@pingsns)

### Madhu Akula

- Automation Ninja @Appsecco
- Interested in Security, DevOps and Cloud
- Speaker & Trainer at Defcon, DevSecCon, AllDayDevOps, etc.
- Found bugs in Google, Microsoft, Yahoo, etc
- Never ending learner!
- Follow me (or) Tweet to me [@madhuakula](https://twitter.com/@madhuakula)


text:
#include "math/mat3.h"
#include "math/vec3.h"
#include "render/material.h"
#include "entity/primitive.h"
#include "math/maths.h"
#include "render/proceduraltexture.h"

#include <algorithm>

//const Material Material::defaultMaterial(Color color(1, 1, 1, 1)) {_diffuse = color}; //= { Color::white, Color::black };

Material::Material()

{
	_kt = vec3(1, 1, 1);
	_kd = vec3(1,1,1);
	_ks = vec3(0.5f, 0.5f, 0.5f);
	_ka = 1.0f;
	_ns = 100.f;
	_d = 1.0;

	_ni = 0;//0.12;
	_texture = nullptr;
	_normalMap = nullptr;
	_transparentMap = nullptr;
	_pattern = nullptr;
	_unlit = false;
}

Material::Material(const vec3 & diffuse, const vec3 & specular, float shininess, float refraction)
	:
	_kd(diffuse),
	_ks(specular),
	_ns(shininess),
	_ni(refraction)
{

	_kd = 1.0f;
	_ks = 0.2f;
	_ka = 1.0f;
	_ns = 100.f;
	_d = 1.0;
	_kt = vec3(1, 1, 1);
	_ni = 0;
	_texture = nullptr;
	_normalMap = nullptr;
	_transparentMap = nullptr;
	_pattern = nullptr;
	_unlit = false;
}

Material::~Material()
{
	//_texture = nullptr;
	//_bumpTexture = nullptr;
}

void Material::shade(const Ray & ray, const RaycastHit & hit, const vec3 & lightColor, const vec3 & lightDir, vec3 & diffuseContrib, vec3 & specularContrib)
{
	//vec3 color;
	vec3 albedo;
	vec3 normal = hit.normal;
	vec3 ldir = -lightDir;
	// check texture

	if (_texture != nullptr && _texture->loaded())
		albedo = _texture->getTexel(hit.texCoord);
	else if (_pattern != nullptr) {
		if (_pattern->kind == 1)
			albedo = ProceduralTexture::stripe(hit.texCoord, _pattern->angle, _pattern->scale);
		else
			albedo = ProceduralTexture::checkboard(hit.texCoord, _pattern->a, _pattern->b, _pattern->scale);
	}
	else
		albedo = _kd;

	if (!_unlit) {

		if (_normalMap != nullptr && _normalMap->loaded())
		{
			const mat4 & m = hit.object->getInversedMatrix();
			vec3 wt = vec3(m * vec4(hit.tangent, 1));
			normal = calcBumpedNormal(wt, normal, hit.texCoord);
		}

		if (albedo.maxComponent() > Epsilon)
			diffuseContrib += albedo * lightColor * std::max(0.f, vec3::dot(normal, ldir));

		if (this->_ks.maxComponent() > Epsilon && lightColor > Epsilon) {
			//(lightDir.normalized() + -1 * ray.direction.normalized()).normalized();
			vec3 r = vec3::reflect(lightDir, hit.normal);//(-lightDir + (-1 * ray.direction)).normalized();
			specularContrib += this->_ks *  lightColor * pow(std::max(0.f, vec3::dot(r, -ray.direction)), _ns); //std::max(0.f, ); //
		}

		// transparent map
		if (_transparentMap != nullptr && _transparentMap->loaded())
			diffuseContrib += _transparentMap->getTexel(hit.texCoord) * lightColor * std::max(0.f, vec3::dot(hit.normal, ldir)) * _transparentMapIntensity;

	}
	else {
		diffuseContrib = albedo;
	}

	//return color;

	/*if (_normalMap != nullptr && _normalMap->loaded())
	{
		vec3 bumpNormal;
		// calculate bi-tangent // tangent space normal mapping
		vec3 bitanget = vec3::cross(hit.tangent, normal).normalized();

		mat4 a = hit.object->getMatrix();

		// TBN matrix
		//mat3 TBN((a * hit.tangent), (a * bitanget), normal);

		mat3 TBN(hit.tangent, bitanget, normal);
		TBN = mat3::transpose(TBN);

		// Perturbed Normal - RGB
		bumpNormal = _normalMap->getTexel(hit.texCoord);
		bumpNormal = 2.0f * (bumpNormal - 0.5f);
		//bumpNormal.normalized();
		normal = (TBN * bumpNormal).normalized();
		ldir = (TBN * -lightDir).normalized();
		//ldir *= -1;
	}*/

/*	bool isBack = (vec3::dot(hit.normal, ray.direction) > 0);
	if (isBack)
	{
		// std::cout << "Back face: " << Vector3f::dot(normal, rayDir) << endl;
		normal *= -1; // Flip normal
	}*/

	// is not unlit, then compute difusse and specular
/*	if (!_unlit) {

		//color = pointWiseDot(lightColor, kd) * clampedDot(hit.normal, -lightDir);

		//std::cout << vec3::dot(normal, ldir) << std::endl;

		// lambert
		if (albedo.max() > fEpsilon)
			diffuseContrib += albedo * lightColor * std::max(0.f, vec3::dot(normal, ldir));

		// specular - phong

		if (this->_specularColor.max() > fEpsilon && lightColor > fEpsilon) {
			//(lightDir.normalized() + -1 * ray.direction.normalized()).normalized();
			vec3 r = vec3::reflect(lightDir, hit.normal);//(-lightDir + (-1 * ray.direction)).normalized();
			specularContrib +=   lightColor * pow(std::max(0.f, vec3::dot(r, -ray.direction)), _ns); //std::max(0.f, ); //
		}
		//color += specularColor;

	}
	else
		diffuseContrib = albedo;*/

	//return color;

}

vec3 Material::shade2(const Ray & ray, const RaycastHit & hit, const vec3 & lightColor, const vec3 & lightDir) {

	vec3 normal = hit.normal;
	vec3 albedo;
	vec3 color;
	vec3 ldir = -lightDir;

	// check texture
	if (_texture != nullptr && _texture->loaded())
		albedo = _texture->getTexel(hit.texCoord);
	else if (_pattern != nullptr) {
		if (_pattern->kind == 1)
			albedo = ProceduralTexture::stripe(hit.texCoord, _pattern->angle, _pattern->scale);
		else
			albedo = ProceduralTexture::checkboard(hit.texCoord,_pattern->a, _pattern->b, _pattern->scale);
	}
	else
		albedo = _kd;

	/*bool isBack = (vec3::dot(hit.normal, ray.direction) > 0);
	if (isBack)
	{
		// std::cout << "Back face: " << Vector3f::dot(normal, rayDir) << endl;
		normal *= -1; // Flip normal
	}*/

	// is not unlit, then compute difusse and specular
	if (!_unlit) {
		if (_normalMap != nullptr && _normalMap->loaded())
		{
			const mat4 & m = hit.object->getInversedMatrix();
			vec3 wt = vec3(m * vec4(hit.tangent, 1));
			normal = calcBumpedNormal(wt, normal, hit.texCoord);
		}

			// lambert
		if (albedo.maxComponent() > Epsilon)
				color = albedo * lightColor * std::max(0.f, vec3::dot(normal, ldir));

		// specular - phong

		if (this->_ks.maxComponent() > Epsilon && lightColor > Epsilon) {
			//(lightDir.normalized() + -1 * ray.direction.normalized()).normalized();
			vec3 r = vec3::reflect(-lightDir, normal);//(-lightDir + (-1 * ray.direction)).normalized();
			color += this->_ks * lightColor * pow(std::max(0.f, -vec3::dot(r, ray.direction)), _ns); //std::max(0.f, ); //
		}

		// transparent map
		if (_transparentMap != nullptr && _transparentMap->loaded())
			color += _transparentMap->getTexel(hit.texCoord) * lightColor * std::max(0.f, vec3::dot(hit.normal, ldir)) * _transparentMapIntensity;

	} else {

		if (_transparentMap != nullptr && _transparentMap->loaded())
			color += _transparentMap->getTexel(hit.texCoord);
	}

	return color;

}

vec3 Material::shadeCelShading(const Ray & ray, const RaycastHit & hit, const vec3 & lightColor, const vec3 & lightDir, const float & levels, const float & factor, const bool & outline)
{
	vec3 normal = hit.normal;
	vec3 albedo;
	vec3 color;
	vec3 ldir = -lightDir;

	// check texture
	if (_texture != nullptr && _texture->loaded())
		albedo = _texture->getTexel(hit.texCoord);
	else if (_pattern != nullptr) {
		if (_pattern->kind == 1)
			albedo = ProceduralTexture::stripe(hit.texCoord, _pattern->angle, _pattern->scale);
		else
			albedo = ProceduralTexture::checkboard(hit.texCoord, _pattern->a, _pattern->b, _pattern->scale);
	}
	else
		albedo = _kd;

	/*bool isBack = (vec3::dot(hit.normal, ray.direction) > 0);
	if (isBack)
	{
	// std::cout << "Back face: " << Vector3f::dot(normal, rayDir) << endl;
	normal *= -1; // Flip normal
	}*/

	// is not unlit, then compute difusse and specular
	if (!_unlit) {
		if (_normalMap != nullptr && _normalMap->loaded())
		{
			const mat4 & m = hit.object->getInversedMatrix();
			vec3 wt = vec3(m * vec4(hit.tangent, 1));
			normal = calcBumpedNormal(wt, normal, hit.texCoord);
		}

		// lambert
		vec3 lambert;
		vec3 difus;

		// difusa
		// albedo é a cor da difusa
		// lambert é dividido em numero de niveis do cell shading
		if (albedo.maxComponent() > Epsilon) {
			lambert = floorf(std::max(0.f, vec3::dot(normal, ldir)) * levels) * factor;
			difus = albedo * lightColor * lambert;//floorf(std::max(0.f, vec3::dot(normal, ldir)) * levels) * factor;
		}

		// specular - phong
		// calcula specular
		vec3 specular;
		vec3 r = vec3::reflect(-lightDir, normal);
		if (this->_ks.maxComponent() > Epsilon && lightColor > Epsilon) {
			specular = this->_ks * lightColor * std::max(0.f, -vec3::dot(r, ray.direction));// pow(, _ns);
			// can use clamp to create a border
			// pow(Math::clamp(-vec3::dot(r, ray.direction), 0.f, 1.0f), _ns);
		}

		// limit specular
		vec3 h = (ldir + ray.direction).normalized();
		float specMask = (std::powf(vec3::dot(h, normal), _ns) > 0.5) ? 1 : 0;
		//float specMask = (std::powf(vec3::dot(h, ray.direction), _ns) > 0.4) ? 1 : 0;

		//edege
		float edgeDetection = 1;

		if (outline)
			edgeDetection = (vec3::dot(normal, ray.direction) > 0.35) ? 1 : 0;

		color = edgeDetection * (difus + specular * specMask);

		// transparent map
		if (_transparentMap != nullptr && _transparentMap->loaded())
			color += _transparentMap->getTexel(hit.texCoord) * lambert * _transparentMapIntensity;

	}
	else {

		if (_transparentMap != nullptr && _transparentMap->loaded())
			color += _transparentMap->getTexel(hit.texCoord);
	}

	return color;
}

vec3 Material::shadeGooch(const Ray & ray, const RaycastHit & hit, const vec3 & lightColor, const vec3 & lightDir,
	const vec3 & warmColor, const vec3 & coolColor, const float & alpha, const float & beta,
	const bool & outline, bool superCut)
{
	vec3 albedo;
	vec3 color;
	vec3 normal = hit.normal;
	vec3 ldir = -lightDir;

	// check texture
	if (_texture != nullptr && _texture->loaded())
		albedo = _texture->getTexel(hit.texCoord);
	else if (_pattern != nullptr) {
		if (_pattern->kind == 1)
			albedo = ProceduralTexture::stripe(hit.texCoord, _pattern->angle, _pattern->scale);
		else
			albedo = ProceduralTexture::checkboard(hit.texCoord, _pattern->a, _pattern->b, _pattern->scale);
	}
	else
		albedo = _kd;

	if (!_unlit) {
		if (_normalMap != nullptr && _normalMap->loaded())
		{
			const mat4 & m = hit.object->getInversedMatrix();
			vec3 wt = vec3(m * vec4(hit.tangent, 1));
			normal = calcBumpedNormal(wt, normal, hit.texCoord);
		}

		// intensity of diffuse lighting [-1, 1]
		float diffuseLighting = vec3::dot(normal, ldir);

		// lambert
		vec3 difus;

		if (albedo.maxComponent() > Epsilon)
		{
			if (!superCut)
			{
				// cool color mixed with color of the object
				vec3 coolColorMod = coolColor + albedo * alpha;// u_alpha;
				// warm color mixed with color of the object
				vec3 warmColorMod = warmColor + albedo * beta; // u_beta;

				// map intensity of lighting from range [-1; 1] to [0, 1]
				float intensityMap = (1.0 + diffuseLighting) / 2;

				// interpolation of cool and warm colors according
				// to lighting intensity. The lower the light intensity,
				// the larger part of the cool color is used
				//
				difus = lightColor * vec3::lerp(coolColorMod, warmColorMod, intensityMap);
			}
			else
			{
				// cool color mixed with color of the object
				vec3 coolColorMod = albedo * alpha;// u_alpha;
				// warm color mixed with color of the object
				vec3 warmColorMod = albedo * beta; // u_beta;

				// hi mask
				float hiMask = (diffuseLighting > 0.4) ? 1 : 0;
				//((1 + normal dot light) / 2) * color.cool + (1 - ((1 + normal dot light) / 2)) * color.warm
				//vec3 t = (intensityMap * coolColorMod) + ((1-intensityMap) * warmColorMod);
				difus = lightColor * vec3::lerp(coolColorMod, warmColorMod, hiMask);
			}

		}// * std::max(0.f, vec3::dot(normal, ldir));

		// specular - phong
		vec3 r = vec3::reflect(-lightDir, normal);
		vec3 spec;
		if (this->_ks.maxComponent() > Epsilon && lightColor > Epsilon) {
			if (!superCut)
			{
				//pow(std::max(0.f, -vec3::dot(r, ray.direction)), _ns);
				vec3 h = (ldir + ray.direction).normalized();
				spec = this->_ks * lightColor * std::powf(std::max(0.f, -vec3::dot(r, ray.direction)), _ns); // -vec3::dot(r, ray.direction) // vec3::dot(h, normal)
			}
			else
			{
				spec = this->_ks * lightColor * std::max(0.f, -vec3::dot(r, ray.direction)); // pow(), _ns);
				vec3 h = (ldir + ray.direction).normalized();

				// limit specular
				float specMask = (std::powf(vec3::dot(h, normal), _ns) > 0.5) ? 1 : 0;
				spec *= specMask;

			}
		}

		// edege mask
		float edgeMask = 1;

		if (outline)
			edgeMask = (vec3::dot(normal, ray.direction) > 0.3) ? 1 : 0;

		 //(std::powf(vec3::dot(r, ray.direction), _ns) > 0.5) ? 1 : 0;

		color = edgeMask * (difus + spec);

		// transparent map
		if (_transparentMap != nullptr && _transparentMap->loaded())
			color += _transparentMap->getTexel(hit.texCoord) * lightColor * std::max(0.f, vec3::dot(hit.normal, ldir)) * _transparentMapIntensity;
	}

	return color;

}

vec3 Material::calcPhong(const vec3 & diffuseContrib, const vec3 & specularContrib, const vec3 & shadowContrib)
{
	return shadowContrib *_kd + specularContrib * _ks;
}

vec3 Material::calcBumpedNormal(const vec3 & tangent, const vec3 & normal, const vec2 & texCoord)
{

	// compute tan
	vec3 tan = tangent.normalized();

	//  Gram-Schmidt process
	tan = (tan - vec3::dot(tan, normal) * normal);
	tan.normalize();

	// calculate bi-tangent // tangent space normal mapping
	vec3 bitanget = vec3::cross(tan, normal);

		// Perturbed Normal - RGB
		vec3 bumpNormal = _normalMap->getTexel(texCoord);
		bumpNormal = 2.0f * bumpNormal - 1.0f; //( - 0.5f);
		//bumpNormal.normalize();

			//mat4 a = hit.object->getMatrix();

		//mat4 a = object->getMatrix();
		//mat3 TBN((a * hit.tangent), (a * bitanget), normal);

		// TBN matrix
		mat3 TBN(tan, bitanget, normal);
		//TBN = mat3::transpose(TBN);

		vec3 newNormal = TBN * bumpNormal;

		newNormal.normalize();

		return newNormal;

}

void Material::setPattern(Pattern * pattern)
{
	this->_pattern = pattern;
}

void Material::setProperty(const int materialPropertyIndex, const vec3 & value)
{
	switch (materialPropertyIndex)
	{
	default:
		break;
	case MAT_AMBIENT: {
		_ka = value;
		break;
	}
	case MAT_DIFFUSE: {
		_kd  = value;
		break;
	}
	case MAT_SPECULAR: {
		_ks = value;
		break;
	}
	case MAT_TRANSMITTANCE: {
		_kt = value;
		break;
	}
	case MAT_EMISSION: {
		_ke = value;
		break;
	}
	/*case MAT_TRANSPARENT: {
		_reflective = value;
		break;
	}*/
	}
}

void Material::setProperty(const int materialPropertyIndex, const Color & value)
{
	setProperty(materialPropertyIndex, vec3(value));
}

void Material::setProperty(const int materialPropertyIndex, float value)
{
	switch (materialPropertyIndex)
	{
	default:
		break;
	case MAT_TRANSPARENCY: {
		_d = value;
		break;
	}
	case MAT_REFRACTION: {
		_ni = value;
		break;
	}
	case MAT_SHININESS: {
		_ns = value;
		break;
	}
	case MAT_ILLUM: {
		_illum = (int)value;
		break;
	}
	}
}

/*void Material::setProperty(const int materialPropertyIndex, int value)
{
	if (materialPropertyIndex == MAT_TEXTURE)
		_textureID = value;
}*/

void Material::setTexture( Texture * texture)
{
	_texture = texture;
}

void Material::setNormalMap(Texture * texture)
{
	_normalMap = texture;
}

void Material::setTransparentMap(Texture * texture)
{

	_transparentMap = texture;

}

void Material::setUnlit(bool flag) {

	_unlit = flag;

}

Color Material::getColor(const int materialPropertyIndex) const {

	return getVec3(materialPropertyIndex).toColor();

}

vec3 Material::getVec3(const int materialPropertyIndex) const
{
	switch (materialPropertyIndex)
	{
	default:
		return vec3::zero;
		break;
	case MAT_AMBIENT: {
		return _ka;
		break;
	}
	case MAT_DIFFUSE: {
		return _kd;
		break;
	}
	case MAT_SPECULAR: {
		return _ks;
		break;
	}
	case MAT_TRANSMITTANCE: {
		return _kt;
		break;
	}
	case MAT_EMISSION: {
		return _ke;
		break;
	}
	}
}

float Material::getFloat(const int materialPropertyIndex) const
{
	switch (materialPropertyIndex)
	{
	default:
		return 0;
		break;
	case MAT_TRANSPARENCY: {
		return _d;
		break;
	}
	case MAT_REFRACTION: {
		return _ni;
		break;
	}
	case MAT_SHININESS: {
		return _ns;
		break;
	}
	}
}

bool Material::getUnlit() const
{
	return _unlit;
}

Color Material::getAlbedo(const vec2 & texCoord) const
{
	if (_texture != nullptr && _texture->loaded()) {
		return _texture->getTexel(texCoord);

	}
	else if (_pattern != nullptr) {
		if (_pattern->kind == 1)
			return ProceduralTexture::stripe(texCoord, _pattern->angle, _pattern->scale);
		else
			return ProceduralTexture::checkboard(texCoord, _pattern->a, _pattern->b, _pattern->scale,_pattern->angle);
	}
	else
		return _kd;

	/*float scale = 5;
	float pattern = (fmodf(texCoord.x * scale, 1) > 0.5) ^ (fmodf(texCoord.y * scale, 1) > 0.5);
	return vec3::lerp(vec3(0.815, 0.235, 0.031), vec3(0.937, 0.937, 0.231), pattern);*/
}

/*int Material::getInteger(const int materialPropertyIndex) const
{
	if (materialPropertyIndex == MAT_TEXTURE)
		return _textureID;

	return 0;

}*/

Texture * Material::getTexture() const
{
	return _texture;
}

Texture * Material::getNormalMap() const
{
	return _normalMap;
}
/*
vec3 Material::clampedDot(const vec3 & v1, const vec3 & v2)
{
	float d = vec3::dot(v1, v2);
	return (d>0) ? d : 0;
}

vec3 Material::pointWiseDot(const vec3 & v1, const vec3 & v2)
{
	return vec3(v1[0] * v2[0], v1[1] * v2[1], v1[2] * v2[2]);

}*/


text:
<?php defined('COREPATH') or exit('No direct script access allowed'); ?>

INFO - 2015-12-23 12:19:11 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "sabcadmin"
INFO - 2015-12-23 12:19:11 --> Fuel\Core\Request::execute - Called
INFO - 2015-12-23 12:19:11 --> Fuel\Core\Request::execute - Setting main Request
INFO - 2015-12-23 12:19:22 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "sabcadmin"
INFO - 2015-12-23 12:19:22 --> Fuel\Core\Request::execute - Called
INFO - 2015-12-23 12:19:22 --> Fuel\Core\Request::execute - Setting main Request


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

    <ProgressBar
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_margin="10dp" />

    <TextView
        android:id="@+id/messageTextViewFromLoading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textSize="20sp"
        android:textStyle="bold" />

</LinearLayout>


text:
package org.apache.spark.examples.ml;

// $example on$
import org.apache.spark.ml.classification.NaiveBayes;
import org.apache.spark.ml.classification.NaiveBayesModel;
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
// $example off$

/**
 * An example for Naive Bayes Classification.
 */
public class JavaNaiveBayesExample {

  public static void main(String[] args) {
    SparkSession spark = SparkSession
      .builder()
      .appName("JavaNaiveBayesExample")
      .getOrCreate();

    // $example on$
    // Load training data
    Dataset<Row> dataFrame =
      spark.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");
    // Split the data into train and test
    Dataset<Row>[] splits = dataFrame.randomSplit(new double[]{0.6, 0.4}, 1234L);
    Dataset<Row> train = splits[0];
    Dataset<Row> test = splits[1];

    // create the trainer and set its parameters
    NaiveBayes nb = new NaiveBayes();
    // train the model
    NaiveBayesModel model = nb.fit(train);
    // compute accuracy on the test set
    Dataset<Row> result = model.transform(test);
    Dataset<Row> predictionAndLabels = result.select("prediction", "label");
    MulticlassClassificationEvaluator evaluator = new MulticlassClassificationEvaluator()
      .setMetricName("accuracy");
    System.out.println("Accuracy = " + evaluator.evaluate(predictionAndLabels));
    // $example off$

    spark.stop();
  }
}


text:
package org.txazo.wx.app.remind.execute;

import org.springframework.stereotype.Component;

/**
 * IndexController
 *
 * @author txazo
 * @email txazo1218@163.com
 * @since 03.06.2015
 */
@Component
public class RemindExecute {

    public RemindExecute() {
        Thread thread = new Thread(new RemindExecuteThread());
        thread.setDaemon(true);
        thread.start();
    }

    private class RemindExecuteThread implements Runnable {

        @Override
        public void run() {
        }

    }

}


text:
namespace SourceControlSystem.Api.Tests.IntegrationTests
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Controllers;
    using System;
    using System.Net;
    using System.Net.Http;
    using System.Threading;
    using System.Web.Http;

    [TestClass]
    public class CommitsIntegrationTests
    {
        [TestMethod]
        public void ByProjectShouldReturnCorrectResponse()
        {
            // Required by the HttpServer to find controller in another assembly
            var controller = typeof(CommitsController);

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
            );

            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            var httpServer = new HttpServer(config);
            var httpInvoker = new HttpMessageInvoker(httpServer);

            using (httpInvoker)
            {
                var request = new HttpRequestMessage
                {
                    RequestUri = new Uri("http://test.com/api/Commits/ByProject/1"),
                    Method = HttpMethod.Get
                };

                var result = httpInvoker.SendAsync(request, CancellationToken.None).Result;

                Assert.IsNotNull(result);
                Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            }
        }
    }
}


text:
module DPH.Pass.Summon
        (passSummon)
where
import DPH.Core.Pretty
import HscTypes
import CoreSyn
import CoreMonad
import Avail
import Data.Maybe
import Data.Set                 (Set)
import qualified UniqFM         as UFM
import qualified Data.Set       as Set
import Control.Monad
import Debug.Trace

-- Pass -----------------------------------------------------------------------
passSummon :: ModGuts -> CoreM ModGuts
passSummon guts
 = do   let tops        = mg_binds guts

        -- Get the names of the vectorised versions of all exported bindings.
        let nsExported  = [ n | Avail n <- mg_exports guts]
        let nsExported_vect
                = catMaybes
                $ map (UFM.lookupUFM (vectInfoVar $ mg_vect_info guts))
                $ nsExported

        -- Summon all of the vectorised things.
        let summonMe
                = Set.fromList
                $ map snd
                $ nsExported_vect

        tops'   <- mapM (summonTop summonMe tops) tops
        return  $ guts { mg_binds = tops'}

-- Top ------------------------------------------------------------------------
-- | If some `CoreBind` is in the set, then summon all its parts.
summonTop
        :: Set CoreBndr -- ^ Summon into bindings with these binders.
        -> [CoreBind]   -- ^ All the top-level bindings for this module.
        -> CoreBind     -- ^ Binding to inspect
        -> CoreM CoreBind

summonTop bsSet tops bind
 = case bind of
        NonRec b x
         -> do  (b', x')        <- goSummon (b, x)
                return $ NonRec b' x'

        Rec bxs
         -> do  bxs'            <- mapM goSummon bxs
                return $ Rec bxs'
 where
        goSummon (b, x)
         | Set.member b bsSet   = summon tops (b, x)
         | otherwise            = return (b, x)

-- Summon ---------------------------------------------------------------------
-- | Inline everything we can find into this binding.
summon  :: [CoreBind]            -- ^ All the top-level bindings for this module.
        -> (CoreBndr, Expr CoreBndr)   -- ^ The binding to work on.
        -> CoreM (CoreBndr, Expr CoreBndr)
summon tops (b, xx)
 = trace (renderIndent $ text "summoning " <> ppr b)
 $ do   xx'     <- summonX tops xx
        return  (b, xx')

-- | Summon into an expression.
summonX :: [CoreBind]
        -> Expr CoreBndr
        -> CoreM (Expr CoreBndr)
summonX tops xx
 = let down     = summonX tops
   in case xx of
        Var n
         -> trace (renderIndent $ text "look at " <> ppr n)
         $  case lookupBind tops n of
                Nothing -> return xx
                Just x' -> summonX tops x'

        Lit{}           -> return xx
        App x arg       -> liftM2 App (down x)  (down arg)
        Lam b   x       -> liftM2 Lam (return b)         (down x)
        Let bnd x       -> liftM2 Let (summonB tops bnd) (down x)

        Case x b t alts -> liftM4 Case  (down x)
                                (return b) (return t)
                                (mapM (summonA tops) alts)

        Cast x co       -> liftM2 Cast  (down x)   (return co)
        Tick t x        -> liftM2 Tick  (return t) (down x)
        Type t          -> return xx
        Coercion co     -> return xx

-- | Summon into an alternative.
summonA :: [CoreBind]
        -> (AltCon, [CoreBndr], Expr CoreBndr)
        -> CoreM (AltCon, [CoreBndr], Expr CoreBndr)

summonA tops (con, bs, x)
 = do   x'      <- summonX tops x
        return  $ (con, bs, x')

-- | Summon into a let-binding.
summonB :: [CoreBind]
        -> Bind CoreBndr
        -> CoreM (Bind CoreBndr)

summonB tops bb
 = case bb of
        NonRec b x
         -> liftM2 NonRec (return b) (summonX tops x)

        Rec bxs
         -> do  let (bs, xs)    = unzip bxs
                xs'             <- mapM (summonX tops) xs
                return          $ Rec $ zip bs xs

lookupBind
        :: [CoreBind]
        -> CoreBndr
        -> Maybe (Expr CoreBndr)
lookupBind tops b
 = case tops of
        []      -> Nothing

        (NonRec b' x : _)
         | b == b'      -> Just x

        _ : ts          -> lookupBind ts b


text:
shipwire-api
============
These library will help you with the usage of Shipwire API.

[![Latest Stable Version](https://poser.pugx.org/flydreamers/shipwire-api/v/stable.svg)](https://packagist.org/packages/flydreamers/shipwire-api)
[![Total Downloads](https://poser.pugx.org/flydreamers/shipwire-api/downloads.svg)](https://packagist.org/packages/flydreamers/shipwire-api)
[![Latest Unstable Version](https://poser.pugx.org/flydreamers/shipwire-api/v/unstable.svg)](https://packagist.org/packages/flydreamers/shipwire-api)
[![License](https://poser.pugx.org/flydreamers/shipwire-api/license.svg)](https://packagist.org/packages/flydreamers/shipwire-api)

## Installing via Composer

The recommended way to install Shipwire-API is through
[Composer](http://getcomposer.org).

```bash
# Install Composer
curl -sS https://getcomposer.org/installer | php
```

Next, run the Composer command to install the latest stable version of Shipwire-API:

```bash
composer require flydreamers/shipwire-api
```

After installing, you need to require Composer's autoloader:

```php
require 'vendor/autoload.php';
```

## Documentation

### Initial configuration

To configure the library just call ShipwireConnector::init() function to and start using it.

To use it you only have to configure your username and password in The clientyour config-local file like this:

```php
ShipwireConnector::init($config['username'], $config['password'], 'sandbox');
```

### Stock

To check for Stock of a product:

```php
$response = $stock->getStockBySKUs(['CAPTRACKERBLUE']);
```

If you have more than one SKU, just add them to the array like:

```php
$response = $stock->getStockBySKUs(['CAPTRACKERBLUE', 'CAPTRACKERRED', 'ETCETERA']);
```
Extra parameters can be used. See \flydreamers\shipwire\Stock for more information.

### Rates

You can ask Shipwire API for a shipping rate using Rate class.

```php
$rate = new Rate;
$options = [
    "currency" => "USD",
    "groupBy" => "all",
    "canSplit" => 1,
    "warehouseArea" => "US"
];

$address = Address::createFromArray([
    "address1" => "6501 Railroad Avenue SE",
    "address2" => "Room 315",
    "address3" => "",
    "city" => "Snoqualmie",
    "postalCode" => "85283",
    "region" => "WA",
    "country" => "US",
    "isCommercial" => 0,
    "isPoBox" => 0
]);

$items = [
    ['sku' => 'CAPTRACKERBLUE', 'quantity' => 3]
];

$shippingInfo = $rate->quote($address, $items, $options);
```

### Orders

```php
$order = new \flydreamers\shipwire\Order();

```

**TBD**

##Issues and Feature Requests

If you have issues to report, or issues to request, use the issue tracker in Github.

##Contributing

Currently, the library isn't very feature rich or mature. If you'd like to offer improvements:

1. Fork it
2. Create your feature branch `git checkout -b feature-name`
3. Commit your changes `git commit -am 'Add feature'` \*
4. Push the branch `git push origin feature-name`
5. Create a pull request

##Contact

Have a question? I'm on twitter: [@sebathi](https://twitter.com/sebathi)

##License

[MIT](License)


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>JavaScript SDK for AT&T Enhanced WebRTC API Namespace: Phone</title>

	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.cerulean.css">

			JavaScript SDK for AT&T Enhanced WebRTC API

					Namespaces

							ATT.browser

							ATT.logManager

							ATT.rtc

							ATT.rtc.dhs

							ATT.rtc.Phone

							ATT.utils.ErrorStore.APIErrors

					Classes

							Phone

					Events

							Phone#call:canceled

							Phone#call:connected

							Phone#call:connecting

							Phone#call:disconnected

							Phone#call:disconnecting

							Phone#call:held

							Phone#call:incoming

							Phone#call:moved

							Phone#call:muted

							Phone#call:rejected

							Phone#call:resumed

							Phone#call:ringback-provided

							Phone#call:unmuted

							Phone#conference:canceled

							Phone#conference:connected

							Phone#conference:connecting

							Phone#conference:disconnecting

							Phone#conference:ended

							Phone#conference:held

							Phone#conference:invitation-accepted

							Phone#conference:invitation-received

							Phone#conference:invitation-rejected

							Phone#conference:invitation-sending

							Phone#conference:invitation-sent

							Phone#conference:joining

							Phone#conference:participant-removed

							Phone#conference:resumed

							Phone#event:address-updated

							Phone#event:answering

							Phone#event:dialing

							Phone#event:error

							Phone#event:notification

							Phone#event:warning

							Phone#media:established

							Phone#session:call-switched

							Phone#session:disconnected

							Phone#session:expired

							Phone#session:ready

Namespace: Phone

        .rtc.

    Phone

The ATT.rtc.Phone namespace provides the main method to get an instance of the Phone Object.
A Phone object allows users to utilize the functionality provided by AT&T's Enhanced WebRTC SDK
with operations like make a conference or call, answer an incoming call and hold or resume
an existing call.
Adding and removing participants to or from a conference can also be performed using the
Phone object.

Methods

<static> getPhone() → {Phone}

Get the current instance of Phone.

The public method is used for getting an instance of the Phone object.
A Phone instance is required before any operation related to AT&T's
Enhanced WebRTC can be performed.
At any given time, there can one be one Phone object and any calls to
this function return the same object.

Returns:

A Phone object.

		Type

Phone

		AT&T

		Documentation generated by JSDoc 3.2.2
		on 2015-02-20T21:19:34-08:00 using the DocStrap template.


text:
package ast

import (
	"testing"

	"github.com/pingcap/tidb/parser/charset"
	"github.com/stretchr/testify/require"
)

func TestNodeSetText(t *testing.T) {
	n := &node{}
	tests := []struct {
		text           string
		enc            charset.Encoding
		expectUTF8Text string
		expectText     string
	}{
		{"你好", nil, "你好", "你好"},
		{"\xd2\xbb", charset.EncodingGBKImpl, "一", "\xd2\xbb"},
		{"\xc1\xd0", charset.EncodingGBKImpl, "列", "\xc1\xd0"},
	}
	for _, tt := range tests {
		n.SetText(tt.enc, tt.text)
		require.Equal(t, tt.expectUTF8Text, n.Text())
		require.Equal(t, tt.expectText, n.OriginalText())
	}
}


text:
module Senders
  class STDOUT
    def initialize(destination)
    end

    def publish(message)
      puts(message)
    end

    def to_s
      'stdout'
    end
  end
end


text:
slug: graceful
name: graceful
---


text:
  * If the `inst` directory itself doesn't exist, it will be created.
  * Refactoring the file checking and creation logic.

# Version 0.2.1.1

  * Fixes location of the pkgdown file written by Rocco.
  * Doesn't move the same directory multiple times.

# Version 0.2.1

  * Rocco now will call Roxygen documentation prior to compiling pkgdown.

# Version 0.2

  * Now Rocco also generates [pkgdown](https://github.com/hadley/pkgdown).  It creates all the necessary pre-files for pkgdown so you don't have to build them yourself.
  * This repo now has pkgdown.
  * Removed pending files.

# Version 0.1.1

  * Added the ability to push the generated documentation to the
    [gh-pages](https://robertzk.github.io/rocco) branch of your repo.
    When calling `rocco::rocco`, set `gh_pages = TRUE`.

# Version 0.1.0

  * The initial creation of the package.


text:
layout: doc
title: "AcceptAction.metadata"
position: 0
---

Метаданные типа [`AcceptAction`](../).

# Properties

Нет

# Examples

```json
{
	"AcceptAction": {
	}
}
```


text:
class UnitDeathSwitch : public BaseSwitch {
public:
	UnitDeathSwitch();
	UnitDeathSwitch(Object* object_);
	virtual ~UnitDeathSwitch();

	static inline ComponentIdType GetTypeId() { return BaseSwitch::GetTypeId(); }

	//[[PROPERTY]]//
	virtual void SetSwitchType(std::string typeStr);
	//[[PROPERTY]]//
	virtual void SetResetTime(float t);
	//[[PROPERTY]]//
	inline void SetRequiredDeaths(unsigned int numDeaths);
	//[[PROPERTY]]//
	void SetRequiredUnitType(std::string typeStr);    // Only allows the specified unit type
	void SetRequiredUnitType(UnitType uType);
	//[[PROPERTY]]//
	void AddAllowedUnitType(std::string typeStr);     // Also allow the specified unit type
	void AddAllowedUnitType(UnitType uType);
	//[[PROPERTY]]//
	void AllowAllUnitTypesUpTo(std::string typeStr);  // Set all units up to the specified type as allowed
	void AllowAllUnitTypesUpTo(UnitType uType);

	// @Override
	virtual void HandleMessage(MessageChunk messageChunk);

protected:
	// @Override
	//virtual bool isConditionMet();

	void onUnitWasKilled(ObjectIdType id);
	bool doesUnitDeathCount(ObjectIdType id);

private:
	void init();
	void destroy();

	unsigned int requiredDeaths;
	unsigned long long unitTypeBitMask;
};

void UnitDeathSwitch::SetRequiredDeaths(unsigned int numDeaths)  { this->requiredDeaths = numDeaths; }

#endif // UNITDEATHSWITCH_H


text:
UniqueHashMap
=============

`UniqueHashMap` is to provide all the features and behavior of `java.util.HashMap`, with only one difference:

- `UniqueHashMap` is to enforce the constraint that each value in the map be unique. In other words, each value is mapped to by at most one key. If `UniqueHashMap.put()` is called with a value that already exists in the map, the old key should be replaced. For example, if the map contains:

	"blog" => "glob"

then calling `put("blag", "glob")` would cause the mapping above to be replaced by:

	"blag" => "glob"


text:
package filter

import (
	"testing"

	. "github.com/zimmski/tavor/test/assert"

	"github.com/zimmski/tavor/token/lists"
	"github.com/zimmski/tavor/token/primitives"
)

func TestNewNegativeBoundaryValueAnalysisFilterToBeFilter(t *testing.T) {
	var filt *Filter

	Implements(t, filt, &NegativeBoundaryValueAnalysisFilter{})
}

func TestNewNegativeBoundaryValueAnalysisFilter(t *testing.T) {
	f := NewNegativeBoundaryValueAnalysisFilter()

	// single value range
	{
		root := primitives.NewRangeInt(10, 10)
		replacements, err := f.Apply(root)
		Nil(t, err)
		Equal(t, replacements, lists.NewOne(
			primitives.NewConstantInt(9),
			primitives.NewConstantInt(11),
		))
	}
	// two value range
	{
		root := primitives.NewRangeInt(10, 11)
		replacements, err := f.Apply(root)
		Nil(t, err)
		Equal(t, replacements, lists.NewOne(
			primitives.NewConstantInt(9),
			primitives.NewConstantInt(12),
		))
	}
	// three value range
	{
		root := primitives.NewRangeInt(10, 12)
		replacements, err := f.Apply(root)
		Nil(t, err)
		Equal(t, replacements, lists.NewOne(
			primitives.NewConstantInt(9),
			primitives.NewConstantInt(13),
		))
	}
	// four value range
	{
		root := primitives.NewRangeInt(10, 13)
		replacements, err := f.Apply(root)
		Nil(t, err)
		Equal(t, replacements, lists.NewOne(
			primitives.NewConstantInt(9),
			primitives.NewConstantInt(14),
		))
	}
	// five value range
	{
		root := primitives.NewRangeInt(10, 14)
		replacements, err := f.Apply(root)
		Nil(t, err)
		Equal(t, replacements, lists.NewOne(
			primitives.NewConstantInt(9),
			primitives.NewConstantInt(15),
		))
	}
}


text:
find_package(PkgConfig)
pkg_check_modules(PC_ARGTABLE QUIET argtable2)
set(ARGTABLE_DEFINITIONS ${PC_ARGTABLE_CFLAGS_OTHER})

find_path(ARGTABLE_INCLUDE_DIR argtable2.h
          HINTS ${PC_ARGTABLE_INCLUDEDIR} ${PC_ARGTABLE_INCLUDE_DIRS}
          PATHS ENV ARGTABLE_INC
          PATH_SUFFIXES argtable )

find_library(ARGTABLE_LIBRARY NAMES argtable2 libargtable2
             HINTS ${PC_ARGTABLE_LIBDIR} ${PC_ARGTABLE_LIBRARY_DIRS}
             PATHS ENV ARGTABLE_BINARY )

set(ARGTABLE_LIBRARIES ${ARGTABLE_LIBRARY} )
set(ARGTABLE_INCLUDE_DIRS ${ARGTABLE_INCLUDE_DIR} )

include(FindPackageHandleStandardArgs)
# handle the QUIETLY and REQUIRED arguments and set ARGTABLE_FOUND to TRUE
# if all listed variables are TRUE
find_package_handle_standard_args(ArgTable  DEFAULT_MSG
                                  ARGTABLE_LIBRARY ARGTABLE_INCLUDE_DIR)

mark_as_advanced(ARGTABLE_INCLUDE_DIR ARGTABLE_LIBRARY )