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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.15"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Entitas: Entitas.PrimaryEntityIndex< TEntity, TKey > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

Entitas
    1.13.0

Entitas is a super fast Entity Component System (ECS) Framework specifically made for C# and Unity

Public Member Functions |
Protected Member Functions |
List of all members

Entitas.PrimaryEntityIndex< TEntity, TKey > Class Template Reference

Inheritance diagram for Entitas.PrimaryEntityIndex< TEntity, TKey >:

  <map id="Entitas.PrimaryEntityIndex_3C_20TEntity_2C_20TKey_20_3E_map" name="Entitas.PrimaryEntityIndex_3C_20TEntity_2C_20TKey_20_3E_map">
<area href="class_entitas_1_1_abstract_entity_index.html" alt="Entitas.AbstractEntityIndex< TEntity, TKey >" shape="rect" coords="0,56,263,80"/>
<area href="interface_entitas_1_1_i_entity_index.html" alt="Entitas.IEntityIndex" shape="rect" coords="0,0,263,24"/>
  </map>

Public Member Functions

 	PrimaryEntityIndex (string name, IGroup< TEntity > group, Func< TEntity, IComponent, TKey > getKey)

 	PrimaryEntityIndex (string name, IGroup< TEntity > group, Func< TEntity, IComponent, TKey[]> getKeys)

 	PrimaryEntityIndex (string name, IGroup< TEntity > group, Func< TEntity, IComponent, TKey > getKey, IEqualityComparer< TKey > comparer)

 	PrimaryEntityIndex (string name, IGroup< TEntity > group, Func< TEntity, IComponent, TKey[]> getKeys, IEqualityComparer< TKey > comparer)

override void 	Activate ()

TEntity 	GetEntity (TKey key)

override string 	ToString ()

 Public Member Functions inherited from Entitas.AbstractEntityIndex< TEntity, TKey >

virtual void 	Deactivate ()

override string 	ToString ()

Protected Member Functions

override void 	clear ()

override void 	addEntity (TKey key, TEntity entity)

override void 	removeEntity (TKey key, TEntity entity)

 Protected Member Functions inherited from Entitas.AbstractEntityIndex< TEntity, TKey >

 	AbstractEntityIndex (string name, IGroup< TEntity > group, Func< TEntity, IComponent, TKey > getKey)

 	AbstractEntityIndex (string name, IGroup< TEntity > group, Func< TEntity, IComponent, TKey[]> getKeys)

void 	indexEntities (IGroup< TEntity > group)

void 	onEntityAdded (IGroup< TEntity > group, TEntity entity, int index, IComponent component)

void 	onEntityRemoved (IGroup< TEntity > group, TEntity entity, int index, IComponent component)

Additional Inherited Members

 Protected Attributes inherited from Entitas.AbstractEntityIndex< TEntity, TKey >

readonly string 	_name

readonly IGroup< TEntity > 	_group

readonly Func< TEntity, IComponent, TKey > 	_getKey

readonly Func< TEntity, IComponent, TKey[]> 	_getKeys

readonly bool 	_isSingleKey

 Properties inherited from Entitas.AbstractEntityIndex< TEntity, TKey >

string 	name [get]

 Properties inherited from Entitas.IEntityIndex

string 	name [get]

Detailed Description

Type Constraints

TEntity	 :	class

TEntity	 :	IEntity

Definition at line 6 of file PrimaryEntityIndex.cs.

The documentation for this class was generated from the following file:

Entitas/Entitas/EntityIndex/PrimaryEntityIndex.cs

Entitas

PrimaryEntityIndex

Generated by

     1.8.15


text:
package com.cidic.fontdesign.controllers;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cidic.fontdesign.exception.FontDesignException;
import com.cidic.fontdesign.model.ListResultModel;
import com.cidic.fontdesign.model.ResultModel;
import com.cidic.fontdesign.model.SpecialDesign;
import com.cidic.fontdesign.model.SpecialPageModel;
import com.cidic.fontdesign.service.SpecialDesignService;
import com.cidic.fontdesign.util.DateUtil;

@Controller
@RequestMapping("/specialDesign")
public class SpecialDesignController {

	private static final Logger logger = LoggerFactory.getLogger(SpecialDesignController.class);

	@Autowired
	@Qualifier(value="specialDesignServiceImpl")
	private SpecialDesignService specialDesignServiceImpl;

	private ResultModel resultModel = null;

	@ExceptionHandler(FontDesignException.class)
	public @ResponseBody ResultModel handleCustomException(FontDesignException ex) {
		ResultModel resultModel = new ResultModel();
		resultModel.setResultCode(ex.getErrCode());
		resultModel.setMessage(ex.getErrMsg());
		return resultModel;
	}

	@RequestMapping(value = {"/specialDesignCOR"}, method = RequestMethod.GET)
	public ModelAndView getCourseCORView(HttpServletRequest request) {
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/specialDesignCOR");
		return view;
	}

	@RequestMapping(value = {"/specialDesignCOR/{id}"}, method = RequestMethod.GET)
	public ModelAndView getCourseCOR(HttpServletRequest request,@PathVariable int id) {
		SpecialDesign specialDesign = null;
		if (id > 0){
			specialDesign = specialDesignServiceImpl.selectSpecialDesign(id);
		}
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/specialDesignCOR");
		view.addObject("specialDesign", specialDesign);
		return view;
	}

	@RequestMapping(value = "/specialDesignMgr", method = RequestMethod.GET)
	public ModelAndView getCourseMgr(HttpServletRequest request) {
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/specialDesignMgr");
		return view;
	}

	@RequestMapping(value = "/insert", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel insertCourseDesign(@RequestParam String title, @RequestParam String abstract_,
			@RequestParam String teacher,@RequestParam String createTime,@RequestParam int topTag,
			@RequestParam int specialDetailId,@RequestParam String insertTag,@RequestParam String bg,@RequestParam String thumbnail){

		logger.info("/specialdesign/insert/"+title);
		SpecialDesign specialDesign;
		try{
			specialDesign = new SpecialDesign();
			specialDesign.setAbstract_(abstract_);
			specialDesign.setTeacher(teacher);
			specialDesign.setTitle(title);
			if (createTime.equals("")){
				specialDesign.setCreateTime(new Date());
			}
			else{
				specialDesign.setCreateTime(DateUtil.stringToDate(createTime));
			}

			specialDesign.setTopTag(topTag);
			specialDesign.setSpecialDetailId(specialDetailId);
			specialDesign.setBg(bg);
			specialDesign.setThumbnail(thumbnail);
			specialDesignServiceImpl.insertSpecialDesign(specialDesign,insertTag);

			resultModel = new ResultModel();
			resultModel.setResultCode(200);

		}
		catch(Exception e){
			throw new FontDesignException(500, "дÈëÊý¾Ý³ö´í");
		}
		return resultModel;
	}

	@RequestMapping(value = "/select/{id}", method = RequestMethod.GET, produces="application/json")
	@ResponseBody
	public ResultModel selectSpecialDesign(HttpServletRequest request,HttpServletResponse response,@PathVariable int id) throws Exception{
		SpecialDesign specialDesign = null;
		try{
			response.setContentType("text/html;charset=UTF-8");
			response.addHeader("Access-Control-Allow-Origin","*");
		    if("IE".equals(request.getParameter("type"))){
		    	response.addHeader("XDomainRequestAllowed","1");
		    }
		    specialDesign = specialDesignServiceImpl.selectSpecialDesign(id);
			resultModel = new ResultModel();
			resultModel.setResultCode(200);
			resultModel.setObject(specialDesign);
		}
		catch(Exception e){

			throw new FontDesignException(500, "»ñÈ¡Êý¾Ý³ö´í");
		}
		return resultModel;
	}

	@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel updateCourseDesign(@PathVariable int id, @RequestParam String title, @RequestParam String abstract_,
			@RequestParam String teacher,@RequestParam String createTime,@RequestParam int topTag,@RequestParam String bg,
			@RequestParam int specialDetailId,@RequestParam String insertTag,@RequestParam String deleteTag,@RequestParam String thumbnail){

		SpecialDesign specialDesign;
		try{
			specialDesign = new SpecialDesign();
			specialDesign.setId(id);
			specialDesign.setAbstract_(abstract_);
			specialDesign.setTeacher(teacher);
			specialDesign.setTitle(title);
			if (createTime.equals("")){
				specialDesign.setCreateTime(new Date());
			}
			else{
				specialDesign.setCreateTime(DateUtil.stringToDate(createTime));
			}
			specialDesign.setTopTag(topTag);
			specialDesign.setSpecialDetailId(specialDetailId);
			specialDesign.setBg(bg);
			specialDesign.setThumbnail(thumbnail);
			specialDesignServiceImpl.updateSpecialDesign(specialDesign,insertTag,deleteTag);

			resultModel = new ResultModel();
			resultModel.setResultCode(200);

		}
		catch(Exception e){
			throw new FontDesignException(500, "¸üÐÂÊý¾Ý³ö´í");
		}
		return resultModel;
	}

	@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE, produces="application/json")
	@ResponseBody
	public ResultModel deleteCourseDesign(@PathVariable int id){
		SpecialDesign specialDesign = new SpecialDesign();
		specialDesign.setId(id);
		try{
			specialDesignServiceImpl.deleteSpecialDesign(specialDesign);
			resultModel = new ResultModel();
			resultModel.setResultCode(200);
		}
		catch(Exception e){
			throw new FontDesignException(500, "ɾ³ýÊý¾Ý³ö´í");
		}
		return resultModel;
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET, produces="application/json")
	@ResponseBody
	public ListResultModel listCourseDesign(@RequestParam int iDisplayLength, @RequestParam int iDisplayStart,@RequestParam String sEcho){
		ListResultModel listResultModel = new ListResultModel();
		try{
			SpecialPageModel coursePageModel = specialDesignServiceImpl.getDataByPage(iDisplayLength, iDisplayStart, sEcho);
			List<SpecialDesign> list = coursePageModel.getList();
			listResultModel.setAaData(list);
			listResultModel.setsEcho(sEcho);
			listResultModel.setiTotalRecords(coursePageModel.getCount());
			listResultModel.setiTotalDisplayRecords(coursePageModel.getCount());
			listResultModel.setSuccess(true);
		}
		catch(Exception e){
			listResultModel.setSuccess(false);
		}
		return listResultModel;
	}

	@RequestMapping(value = "/frontList", method = RequestMethod.GET, produces="application/json")
	@ResponseBody
	public ListResultModel frontListCourseDesign(HttpServletRequest request,HttpServletResponse response,@RequestParam int limit, @RequestParam int offset,@RequestParam int choice){
		ListResultModel listResultModel = new ListResultModel();
		try{
			response.setContentType("text/html;charset=UTF-8");
			response.addHeader("Access-Control-Allow-Origin","*");
		    if("IE".equals(request.getParameter("type"))){
		    	response.addHeader("XDomainRequestAllowed","1");
		    }
			List<SpecialDesign> list = specialDesignServiceImpl.getFrontDataByPage(limit, offset, choice);
			listResultModel.setAaData(list);
			listResultModel.setiTotalRecords(list.size());
			listResultModel.setiTotalDisplayRecords(offset + list.size());
			listResultModel.setSuccess(true);
		}
		catch(Exception e){
			listResultModel.setSuccess(false);
		}
		return listResultModel;
	}

}

redpajama_set_name: RedPajamaGithub


text:
'use strict';
$(document).ready(function(){
	var updateClock = function() {
		var time = new Date();
		$("#time").html(time.toLocaleTimeString('sv'));
		$("#date").html(time.getDate()+'.'+(time.getMonth()+1)+'.'+time.getFullYear());
	};

	setInterval(updateClock, 1000);
});


text:
require 'grape'
require 'sequel'
require 'securerandom'

require_relative 'helpers'
require_relative 'common'

module Banking
  module DB
    # This class contains routes that modify the database,
    # except creating and updating tokens, which remains
    # in the return class.
    class Process < Grape::API
      format :json

      helpers Banking::DB::Helpers

      # Holds the instance of the DB connector for use in this class
      DB = Banking::DB::Common.db_instance

      # Transfer money from one account to another belonging to the
      # same user.
      # Does the usual token-checking stuff and updates the token,
      # then determines if the account the money is coming from
      # belongs to the same user as the token, then checks the
      # account the money is going to belongs to the same account,
      # then checks there's enough money to move, and then goes
      # ahead and does it.
      post :transfer do
        if authenticate?(params[:token])
          id_from = user_id_from_token(params[:token])
          update_token(params[:token])
          case
          when !account_belongs_to?(id_from, params[:acct_no])
            { auth: true, success: false, reason: 'user' }
          when !valid_transfer?(id_from, params[:acct_to])
            { auth: true, success: false, reason: 'account' }
          when !payment_allowed?(params[:acct_no], params[:amount])
            { auth: true, success: false, reason: 'balance' }
          else
            # Get details to use in transactions
            from_acc = DB[:Account].where(AcctNo: params[:acct_no]).first
            to_acc = DB[:Account].where(AcctNo: params[:acct_to]).first
            cur_balance = from_acc[:Balance] * 100
            to_cur_balance = to_acc[:Balance] * 100
            name = formatted_name(DB[:Customer]
                   .where(UserID: from_acc[:UserID]).first)
            sort_code = from_acc[:SortCode]
            # This updates, in order:
            #  -The account the money is leaving
            #  -The transaction with the money leaving the account
            #  -The transaction with the money entering the second account
            #  -The account the money is going into
            DB[:Account].where(AcctNo: params[:acct_no])
              .update(Balance: (cur_balance - params[:amount].to_i).fdiv(100))
            DB[:Transactions].insert(ID: SecureRandom.uuid,
                                     AcctNo: params[:acct_no],
                                     Date: Time.now.to_i,
                                     Change: (params[:amount].to_i * -1)
                                             .fdiv(100),
                                     Balance: (cur_balance - params[:amount]
                                              .to_i).fdiv(100),
                                     Desc: name + ' ' << params[:acct_to] <<
                                           ' ' << sort_code)
            DB[:Transactions].insert(ID: SecureRandom.uuid,
                                     AcctNo: params[:acct_to],
                                     Date: Time.now.to_i,
                                     Change: params[:amount].to_i.fdiv(100),
                                     Balance: (to_cur_balance +
                                               params[:amount]
                                              .to_i).fdiv(100),
                                     Desc: name + ' ' << params[:acct_no] <<
                                           ' ' << sort_code)
            DB[:Account].where(AcctNo: params[:acct_to])
              .update(Balance: (to_cur_balance + params[:amount].to_i)
              .fdiv(100))
            { auth: true, success: true }
          end
        else
          { auth: false }
        end
      end

      # Make a payment from one account to another belonging to a
      # different user.
      # Does the usual token-checking stuff and updates the token,
      # then determines if the account the money is going to is a
      # valid payee for that user, then checks there's enough
      # money to move, and then goes ahead and does it.
      post :payment do
        if authenticate?(params[:token])
          id_from = user_id_from_token(params[:token])
          update_token(params[:token])
          case
          when !account_belongs_to?(id_from, params[:acct_no])
            { auth: true, success: false, reason: 'user' }
          when !valid_payee?(id_from, params[:acct_to])
            { auth: true, success: false, reason: 'payee' }
          when !payment_allowed?(params[:acct_no], params[:amount])
            { auth: true, success: false, reason: 'balance' }
          else
            from_acc = DB[:Account].where(AcctNo: params[:acct_no]).first
            to_acc = DB[:Account].where(AcctNo: params[:acct_to]).first
            cur_balance = DB[:Account].where(AcctNo: params[:acct_no])
                          .first[:Balance] * 100
            to_cur_balance = DB[:Account].where(AcctNo: params[:acct_to])
                             .first[:Balance] * 100

            # This updates, in order:
            #  -The account the money is leaving
            #  -The transaction with the money leaving the account
            #  -The transaction with the money entering the second account
            #  -The account the money is going into
            DB[:Account].where(AcctNo: params[:acct_no])
              .update(Balance: (cur_balance - params[:amount].to_i).fdiv(100))
            DB[:Transactions].insert(ID: SecureRandom.uuid,
                                     AcctNo: params[:acct_no],
                                     Date: Time.now.to_i,
                                     Change: (params[:amount].to_i * -1)
                                             .fdiv(100),
                                     Balance: (cur_balance - params[:amount]
                                              .to_i).fdiv(100),
                                     Desc: params[:reference] + ' ' <<
                                           params[:acct_to] << ' ' <<
                                           to_acc[:SortCode])
            DB[:Transactions].insert(ID: SecureRandom.uuid,
                                     AcctNo: params[:acct_to],
                                     Date: Time.now.to_i,
                                     Change: params[:amount].to_i.fdiv(100),
                                     Balance: (to_cur_balance +
                                              params[:amount]
                                              .to_i).fdiv(100),
                                     Desc: params[:reference] + ' ' <<
                                           params[:acct_no] << ' ' <<
                                           from_acc[:SortCode])
            DB[:Account].where(AcctNo: params[:acct_to])
              .update(Balance: (to_cur_balance + params[:amount].to_i)
              .fdiv(100))
            { auth: true, success: true }
          end
        else
          { auth: false }
        end
      end
    end
  end
end


text:
'use strict';

module.exports = {
  db: 'mongodb://localhost/mean-dev1',
	debug: 'true',
  mongoose: {
    debug: false
  },
  app: {
    name: 'Hattira'
  },
  facebook: {
    clientID: 'DEFAULT_APP_ID',
    clientSecret: 'APP_SECRET',
    callbackURL: 'http://localhost:3000/auth/facebook/callback'
  },
  github: {
    clientID: 'DEFAULT_APP_ID',
    clientSecret: 'APP_SECRET',
    callbackURL: 'http://localhost:3000/auth/github/callback'
  },
  emailFrom: 'Hattira',
  mailer: {
    service: 'Gmail', // Gmail, SMTP
    auth: {
      user: 'edondemand7@gmail.com',
      pass: 'password goes here'
    }
  }
};


text:
namespace three {
namespace gl {

struct GlProperties
{
  optional<GLuint> image_textureCube;
  bool webglInit = false;
  optional<GLuint> texture;
  optional<float> currentAnisotropy;
  optional<GLuint> version;
};

struct MaterialProperties
{
  Program::Ptr program;
  Fog::Ptr fog;
  std::vector<float> clippingState;
  LightsHash lightsHash;
  size_t numClippingPlanes = 0;
  size_t numIntersection = 0;
  ShaderID shaderID = ShaderID::undefined;
  three::Shader shader;
  std::vector<Uniform::Ptr> uniformsList;
};

class Properties
{
  std::unordered_map<sole::uuid, GlProperties> glProperties;

  std::unordered_map<sole::uuid, MaterialProperties> materialProperties;

public:
  GlProperties &getGlProperties(const sole::uuid &uuid)
  {
    return glProperties[uuid];
  }

  MaterialProperties &getMaterialProperties(const sole::uuid &uuid)
  {
    return materialProperties[uuid];
  }

  template<typename T, typename std::enable_if<!std::is_base_of<Material, T>{}, int>::type = 0>
  GlProperties &get(const T &tee)
  {
    return getGlProperties(tee.uuid);
  }

  template<typename T, typename std::enable_if<!std::is_base_of<Material, T>{}, int>::type = 0>
  GlProperties &get(const std::shared_ptr<T> tee)
  {
    return getGlProperties(tee->uuid);
  }

  template<typename T, typename std::enable_if<!std::is_base_of<Material, T>{}, int>::type = 0>
  void remove(const T &tee)
  {
    glProperties.erase(tee.uuid);
  }

  template<typename T, typename std::enable_if<!std::is_base_of<Material, T>{}, int>::type = 0>
  bool has(const T &tee)
  {
    return glProperties.count(tee.uuid) > 0;
  }

  template<typename T, typename std::enable_if<std::is_base_of<Material, T>{}, int>::type = 0>
  MaterialProperties &get(const T &material)
  {
    return getMaterialProperties(material.uuid);
  }

  template<typename T, typename std::enable_if<std::is_base_of<Material, T>{}, int>::type = 0>
  MaterialProperties &get(const std::shared_ptr<T> material)
  {
    return getMaterialProperties(material->uuid);
  }

  template<typename T, typename std::enable_if<std::is_base_of<Material, T>{}, int>::type = 0>
  void remove(const T &material)
  {
    materialProperties.erase(material.uuid);
  }

  template<typename T, typename std::enable_if<std::is_base_of<Material, T>{}, int>::type = 0>
  bool has(const T &material)
  {
    return materialProperties.count(material.uuid) > 0;
  }

  void clear()
  {
    glProperties.clear();
    materialProperties.clear();
  }
};

}
}
#endif //THREEPP_PROPERTIES_H


text:
<?php

namespace DvsaMotTestTest\Factory\Controller;

use Core\Catalog\CountryOfRegistration\CountryOfRegistrationCatalog;
use Core\Service\MotFrontendIdentityProviderInterface;
use Dvsa\Mot\ApiClient\Service\VehicleService;
use DvsaCommon\Obfuscate\ParamObfuscator;
use DvsaCommonTest\TestUtils\ServiceFactoryTestHelper;
use DvsaFeature\FeatureToggles;
use DvsaMotTest\Controller\StartTestConfirmationController;
use DvsaMotTest\Factory\Controller\StartTestConfirmationControllerFactory;
use DvsaMotTest\Service\AuthorisedClassesService;
use DvsaMotTest\Service\MotTestCookieService;
use DvsaMotTest\Service\StartTestChangeService;
use DvsaMotTest\Specification\OfficialWeightSourceForVehicle;

class StartTestConfirmationControllerFactoryTest extends \Dvsa\Mot\Frontend\Test\TestCase
{
    public function testFactory()
    {
        ServiceFactoryTestHelper::testCreateServiceForCM(
            StartTestConfirmationControllerFactory::class,
            StartTestConfirmationController::class,
            [
                ParamObfuscator::class,
                CountryOfRegistrationCatalog::class,
                VehicleService::class,
                StartTestChangeService::class,
                AuthorisedClassesService::class,
                MotTestCookieService::class,
                MotFrontendIdentityProviderInterface::class,
                OfficialWeightSourceForVehicle::class,
                FeatureToggles::class
            ]
        );
    }

}


text:
#ifndef pam_krb5_initopts_h
#define pam_krb5_initopts_h

#include "options.h"

void _pam_krb5_set_init_opts(krb5_context ctx,
			     krb5_get_init_creds_opt *k5_options,
			     struct _pam_krb5_options *options);
void _pam_krb5_set_init_opts_for_pwchange(krb5_context ctx,
					  krb5_get_init_creds_opt *k5_options,
					  struct _pam_krb5_options *options);

#endif


text:
namespace Territorium.Tests.Kademlia
{
    public class FindMoreNodes : IMessage
    {
        public Address Customer { get; }
        public Address NodeToFind { get; }
        public int Alpha { get; private set; }

        public FindMoreNodes(Address customer, Address nodeToFind, byte alpha)
        {
            Customer = customer;
            NodeToFind = nodeToFind;
            Alpha = alpha;
        }
    }
}


text:
couchbase-interop
=================
## Overview ##
This project wraps [Official Couchbase .NET SDK](https://github.com/couchbase/couchbase-net-client) with classes providing [COM](https://msdn.microsoft.com/en-us/library/ms680573.aspx) interface. The main goal is to make Couchbase available for [Classic ASP](https://msdn.microsoft.com/en-us/library/aa286483.aspx) applications. However any legacy application capable of consuming COM objects can benefit from this SDK.

Due to missing support for JSON format in legacy applications, the COM API does not offer full range of methods like typical Couchbase 2.0 SDK. Instead it's focusing on the basic Memcached operations which can be easily used by all legacy applications.

## Versioning ##
The first 3 digits (Major, Minior, Build) of Couchbase.ComClient.dll will always reflect the version of Couchbase.NetClient.dll it is based upon. The last digit (Revision) may be used if patch for COM SDK is required without update of the underlying .NET SDK.

## Dependencies ##
This project requires several [NuGet](https://www.nuget.org/) packages as dependencies. For a complete list please refer to [packages.config](Src/Couchbase.ComClient/packages.config). Because of the fundaments of COM - .NET Interoperability, there is no app.config file available to handle .NET assembly redirection. For this reason all shared dependencies must all sync on one exact version to be used through out the project.

For example if Couchbase.NetClient.dll references Common.Logging version 3.0.0, the Couchbase.ComClient can not reference Common.Logging version 3.1.0.

## Deployment ##
The easiest deployment model is to register Couchbase.ComClient and all its dependencies into [GAC](https://msdn.microsoft.com/en-us/library/yf1d93sz.aspx) through [Gacutil](https://msdn.microsoft.com/en-us/library/ex0ss12c.aspx) tool. After that you can register the COM interfaces with [Regasm](https://msdn.microsoft.com/en-us/library/tzat5yw6.aspx). This deployment model will ensure that the COM object assembly and its dependencies are always available and can be easily updated at any time.

Alternatively you can avoid usage of GAC if you use **/codebase** argument in Regasm. In this case make sure that the path you used to register COM components contains all required dependencies in their correct versions and that it's accessible by consuming applications.

Example script with GAC deployment: [com-register.cmd](Src/scripts/com-register.cmd)

## Usage Example ##
```vbs
dim logConfig, factory, bucket, result

set logConfig = CreateObject("Couchbase.ComClient.LogConfig")
logConfig.FileName = "example.log"
call logConfig.SetupLogging()
set logConfig = nothing

set factory = CreateObject("Couchbase.ComClient.BucketFactory")
call factory.ConfigureCluster("example.config", "local")
set bucket = factory.GetBucket("default")

set result = bucket.Upsert("testkey", "Hello World!", 60)
call WScript.StdOut.WriteLine("Upsert call success: " & result.Success)
set result = nothing

call factory.CloseBucket("default")
set bucket = nothing
factory.CloseCluster("local")
set factory = nothing
```
## COM API ##
* [LogConfig](Docs/LogConfig.md) - Configuration of underlying .NET SDK logging
* [BucketFactory](Docs/BucketFactory.md) - Management of Couchbase clusters and buckets
* [BucketWrapper](Docs/BucketWrapper.md) - Executing operations on Couchbase buckets
* [OperationResultWrapper](Docs/OperationResultWrapper.md) - Reading operation results


text:
package br.uff.ic.infraestrutura.seguranca;

import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertThat;

/**
 * Created by guilherme on 15/04/17.
 */
public class AutorizacaoTest{

    private Autorizacao autorizacaoA;

    @Before
    public void setUp() throws Exception {
        autorizacaoA = new Autorizacao(TipoAutorizacao.ROLE_USUARIO);
    }

    @After
    public void tearDown() throws Exception {
        autorizacaoA = null;
    }

    @Test
    public void getAuthority() throws Exception {
        assertThat(autorizacaoA.getAuthority(), Matchers.is("ROLE_USUARIO"));
    }

    @Test
    public void testToString() throws Exception {
        assertThat(autorizacaoA.toString(), Matchers.is("ROLE_USUARIO"));
    }
}


text:
(function(undefined) {

    var path = require('path'),
        fs = require('fs'),
        decree = require('decree'),
        defs = require('./defs'),
        util = require('./util'),
        decoder = require('../build/Release/lwip_decoder'),
        Image = require('./Image');

    var openers = [{
        exts: ['jpg', 'jpeg'],
        opener: decoder.jpeg
    }, {
        exts: ['png'],
        opener: decoder.png
    }];

    function open() {
        decree(defs.args.open)(arguments, function(source, type, callback) {
            if (typeof source === 'string') {
                type = type || path.extname(source).slice(1);
                var opener = getOpener(type);
                fs.readFile(source, function(err, imbuff) {
                    if (err) return callback(err);
                    opener(imbuff, function(err, pixelsBuf, width, height, channels, trans) {
                        callback(err, err ? null : new Image(pixelsBuf, width, height, trans));
                    });
                });
            } else if (source instanceof Buffer) {
                var opener = getOpener(type);
                opener(source, function(err, pixelsBuf, width, height, channels, trans) {
                    callback(err, err ? null : new Image(pixelsBuf, width, height, trans));
                });
            } else throw Error("Invalid source");
        });
    }

    function getOpener(ext) {
        ext = ext.toLowerCase();
        for (var i = 0; i < openers.length; i++) {
            var opener = openers[i].opener,
                exts = openers[i].exts;
            if (exts.indexOf(ext) !== -1) return opener;
        }
        throw Error('Unknown type \'' + ext + '\'');
    }

    function create() {
        decree(defs.args.create)(arguments, function(width, height, color, callback) {
            color = util.normalizeColor(color);
            var trans = color.a < 100,
                c_len = width * height,
                pixelsBuf = new Buffer(c_len * 4);
            for (var i = 0; i < width * height; i++) {
                pixelsBuf[i] = color.r;
                pixelsBuf[c_len + i] = color.g;
                pixelsBuf[2 * c_len + i] = color.b;
                pixelsBuf[3 * c_len + i] = color.a;
            }
            setImmediate(function() {
                callback(null, new Image(pixelsBuf, width, height, trans));
            });
        });
    }

    // EXPORTS
    // -------
    module.exports = {
        open: open,
        create: create
    };
})(void 0);


text:
import os

from wa import ApkUiautoWorkload, Parameter
from wa.utils.types import list_of_strs
from wa.framework.exception import ValidationError

class AdobeReader(ApkUiautoWorkload):

    name = 'adobereader'
    package_names = ['com.adobe.reader']
    description = '''
    The Adobe Reader workflow carries out the following typical productivity tasks.

    Test description:

    1. Open a local file on the device
    2. Gestures test:
        2.1. Swipe down across the central 50% of the screen in 200 x 5ms steps
        2.2. Swipe up across the central 50% of the screen in 200 x 5ms steps
        2.3. Swipe right from the edge of the screen in 50 x 5ms steps
        2.4. Swipe left from the edge of the screen  in 50 x 5ms steps
        2.5. Pinch out 50% in 100 x 5ms steps
        2.6. Pinch In 50% in 100 x 5ms steps
    3. Search test:
        Search ``document_name`` for each string in the ``search_string_list``
    4. Close the document

    Known working APK version: 16.1
    '''

    default_search_strings = [
        'The quick brown fox jumps over the lazy dog',
        'TEST_SEARCH_STRING',
    ]

    parameters = [
        Parameter('document_name', kind=str, default='uxperf_test_doc.pdf',
                  description='''
                  The document name to use for the Gesture and Search test.
                  '''),
        Parameter('search_string_list', kind=list_of_strs, default=default_search_strings,
                  constraint=lambda x: len(x) > 0,
                  description='''
                  For each string in the list, a document search is performed
                  using the string as the search term. At least one must be
                  provided.
                  '''),
    ]

    def __init__(self, target, **kwargs):
        super(AdobeReader, self).__init__(target, **kwargs)
        self.deployable_assets = [self.document_name]
        self.asset_directory = self.target.path.join(self.target.external_storage,
                                                     'Android', 'data',
                                                     'com.adobe.reader', 'files')

    def init_resources(self, context):
        super(AdobeReader, self).init_resources(context)
        # Only accept certain file formats
        if os.path.splitext(self.document_name.lower())[1] not in ['.pdf']:
            raise ValidationError('{} must be a PDF file'.format(self.document_name))
        self.gui.uiauto_params['filename'] = self.document_name
        self.gui.uiauto_params['search_string_list'] = self.search_string_list

    def setup(self, context):
        super(AdobeReader, self).setup(context)
        # Need to re-deploy each time to adobe folder as it is wiped upon clearing app
        self.deploy_assets(context)


text:
var creep_looter = {

    /** @param {Creep} creep **/
    run: function(creep) {
        if (creep.carryCapacity == 0) {
            //YER DED TO ME
            creep.suicide();
        }
        if (creep.room.name != creep.memory.destination && creep.store.getFreeCapacity() >= 100) {
            if (Game.rooms[creep.memory.destination] && Game.rooms[creep.memory.destination].storage) {
                creep.travelTo(Game.rooms[creep.memory.destination].storage);
            } else {
                creep.travelTo(new RoomPosition(25, 25, creep.memory.destination));
            }
        } else if (creep.room.name != creep.memory.homeRoom && creep.store.getFreeCapacity() < 100) {
            if (Game.rooms[creep.memory.homeRoom] && Game.rooms[creep.memory.homeRoom].storage) {
                creep.travelTo(Game.rooms[creep.memory.homeRoom].storage);
            } else {
                creep.travelTo(new RoomPosition(25, 25, creep.memory.homeRoom));
            }
        } else {
            if (creep.store.getFreeCapacity() >= 100) {
                //In far room, loot container
                //Check for ruins first
                let ruins = creep.pos.findClosestByRange(FIND_RUINS, {
                    filter: (thisRuin) => (thisRuin.store.getUsedCapacity() > 0)
                });
                if (ruins) {
                    if (creep.withdraw(ruins, Object.keys(ruins.store)[0]) == ERR_NOT_IN_RANGE) {
                        creep.travelTo(ruins, {
                            maxRooms: 1
                        });
                    }
                } else if (creep.room.storage && creep.room.storage.owner.username != "Montblanc") {
                    if (creep.room.storage.store.getUsedCapacity() == 0) {
                        if (creep.room.terminal && creep.room.terminal.store.getUsedCapacity() > 0) {
                            if (Object.keys(creep.room.terminal.store).length > 1) {
                                if (creep.withdraw(creep.room.terminal, Object.keys(creep.room.terminal.store)[1]) == ERR_NOT_IN_RANGE) {
                                    creep.travelTo(creep.room.terminal);
                                }
                            } else {
                                if (creep.withdraw(creep.room.terminal, Object.keys(creep.room.terminal.store)[0]) == ERR_NOT_IN_RANGE) {
                                    creep.travelTo(creep.room.terminal);
                                }
                            }
                        } else {
                            //Nothing left to loot
                            if (Game.flags[creep.memory.homeRoom + "Loot"]) {
                                Game.flags[creep.memory.homeRoom + "Loot"].remove();
                            }
                            if (Memory.lootSpawn) {
                                Memory.lootSpawn = undefined;
                            }
                            creep.suicide();
                        }
                    } else {
                    	let withdrawResult = undefined;
                    	if (Object.keys(creep.room.storage.store).length > 1) {
                    		withdrawResult = creep.withdraw(creep.room.storage, Object.keys(creep.room.storage.store)[1])
                    	} else {
                    		withdrawResult = creep.withdraw(creep.room.storage, Object.keys(creep.room.storage.store)[0])
                    	}
                        if (withdrawResult == ERR_NOT_IN_RANGE) {
                            creep.travelTo(creep.room.storage);
                        } else if (withdrawResult == OK) {
                            if (Game.rooms[creep.memory.homeRoom] && Game.rooms[creep.memory.homeRoom].storage) {
                                creep.travelTo(Game.rooms[creep.memory.homeRoom].storage);
                            } else {
                                creep.travelTo(new RoomPosition(25, 25, creep.memory.homeRoom));
                            }
                        }
                    }
                } else if (creep.room.terminal && creep.room.terminal.owner.username != "Montblanc" && creep.room.terminal.store.getUsedCapacity() > 0) {
                    if (Object.keys(creep.room.terminal.store).length > 1) {
                        if (creep.withdraw(creep.room.terminal, Object.keys(creep.room.terminal.store)[1]) == ERR_NOT_IN_RANGE) {
                            creep.travelTo(creep.room.terminal);
                        }
                    } else {
                        if (creep.withdraw(creep.room.terminal, Object.keys(creep.room.terminal.store)[0]) == ERR_NOT_IN_RANGE) {
                            creep.travelTo(creep.room.terminal);
                        }
                    }
                } else {
                    //Nothing left to loot
                    if (Game.flags[creep.memory.homeRoom + "Loot"]) {
                        Game.flags[creep.memory.homeRoom + "Loot"].remove();
                    }
                    if (Memory.lootSpawn) {
                        Memory.lootSpawn = undefined;
                    }
                    creep.suicide();
                }
            } else {
                //In home room, drop off energy
                if (creep.room.storage) {
                    let transferResult = undefined;
                    if (Object.keys(creep.store).length > 1) {
                        transferResult = creep.transfer(creep.room.storage, Object.keys(creep.store)[1])
                    } else {
                        transferResult = creep.transfer(creep.room.storage, Object.keys(creep.store)[0])
                    }
                    if (transferResult == ERR_NOT_IN_RANGE) {
                        creep.travelTo(creep.room.storage);
                    }
                }
            }
        }
    }
};

module.exports = creep_looter;


text:
layout: model
title: German ElectraForQuestionAnswering Distilled model (from deepset)
author: John Snow Labs
name: electra_qa_g_base_germanquad_distilled
date: 2022-06-22
tags: [de, open_source, electra, question_answering]
task: Question Answering
language: de
edition: Spark NLP 4.0.0
spark_version: 3.0
supported: true
annotator: BertForQuestionAnswering
article_header:
type: cover
use_language_switcher: "Python-Scala-Java"
---

## Description

Pretrained Question Answering model, adapted from Hugging Face and curated to provide scalability and production-readiness using Spark NLP. `gelectra-base-germanquad-distilled` is a German model originally trained by `deepset`.

{:.btn-box}
<button class="button button-orange" disabled>Live Demo</button>
<button class="button button-orange" disabled>Open in Colab</button>
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/electra_qa_g_base_germanquad_distilled_de_4.0.0_3.0_1655921806755.zip){:.button.button-orange.button-orange-trans.arr.button-icon}

## How to use

<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}
```python
documentAssembler = MultiDocumentAssembler() \
.setInputCols(["question", "context"]) \
.setOutputCols(["document_question", "document_context"])

spanClassifier = BertForQuestionAnswering.pretrained("electra_qa_g_base_germanquad_distilled","de") \
.setInputCols(["document_question", "document_context"]) \
.setOutputCol("answer")\
.setCaseSensitive(True)

pipeline = Pipeline(stages=[documentAssembler, spanClassifier])

data = spark.createDataFrame([["Was ist mein Name?", "Mein Name ist Clara und ich lebe in Berkeley."]]).toDF("question", "context")

result = pipeline.fit(data).transform(data)
```
```scala
val documentAssembler = new MultiDocumentAssembler()
.setInputCols(Array("question", "context"))
.setOutputCols(Array("document_question", "document_context"))

val spanClassifer = BertForQuestionAnswering.pretrained("electra_qa_g_base_germanquad_distilled","de")
.setInputCols(Array("document", "token"))
.setOutputCol("answer")
.setCaseSensitive(true)

val pipeline = new Pipeline().setStages(Array(documentAssembler, spanClassifier))

val data = Seq("Was ist mein Name?", "Mein Name ist Clara und ich lebe in Berkeley.").toDF("question", "context")

val result = pipeline.fit(data).transform(data)
```

{:.nlu-block}
```python
import nlu
nlu.load("de.answer_question.electra.distilled_base").predict("""Was ist mein Name?|||"Mein Name ist Clara und ich lebe in Berkeley.""")
```

</div>

{:.model-param}
## Model Information

{:.table-model}
|---|---|
|Model Name:|electra_qa_g_base_germanquad_distilled|
|Compatibility:|Spark NLP 4.0.0+|
|License:|Open Source|
|Edition:|Official|
|Input Labels:|[document_question, document_context]|
|Output Labels:|[answer]|
|Language:|de|
|Size:|410.8 MB|
|Case sensitive:|true|
|Max sentence length:|512|

## References

- https://huggingface.co/deepset/gelectra-base-germanquad-distilled
- https://deepset.ai/germanquad
- https://deepset.ai/german-bert
- https://github.com/deepset-ai/FARM
- https://github.com/deepset-ai/haystack/
- https://haystack.deepset.ai/community/join


text:
using System.Diagnostics.CodeAnalysis;
using Business.Contracts.Product;
using Core.Common.Exceptions;
using Core.Common.Model;
using Domain.MasterData.ProductAggregate;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TennisStoreTests.Products
{
    [TestClass]
    [ExcludeFromCodeCoverage]
    public class ProductSelectorProductTests : ProductTestBase
    {
        [TestMethod]
        public void FindAllTest()
        {
            IProductSelector selector = MefBase.Resolve<IProductSelector>();
            Assert.IsTrue(selector.FindAll(true).Count == 15, $"Actual {selector.FindAll(true).Count}");
        }

        [TestMethod]
        [ExpectedException(typeof(NotValidException))]
        public void GetBadIdTest()
        {
            MefBase.Resolve<IProductSelector>().Get("");
        }

        [TestMethod]
        [ExpectedException(typeof(ResourceNotFoundException))]
        public void GetNonExistentTest()
        {
            MefBase.Resolve<IProductSelector>().Get("adwda");
        }

        [TestMethod]
        public void GetTest()
        {
            Product product = MefBase.Resolve<IProductSelector>().Get("1");
            Assert.IsTrue(product.Name == "Babolat Pure Control Tour");
            Assert.IsTrue(product.StandardCost == 159.00M);
            Assert.IsTrue(product.ProductCategoryId == 1);
        }
    }
}


text:
  class GalleryUploader < CarrierWave::Uploader::Base
    include CarrierWave::MiniMagick

    def store_dir
       "uploads/galleries/#{model.id}"
    end

    process resize_to_limit: [2000, 2000]

    version :large do

      process resize_to_fit: [960, 960]

    end

    version :medium do
      process resize_to_fit: [600, 600]
    end

    version :small do
      process resize_to_fill: [223, 149]
    end

    version :thumb do
      process resize_to_fill: [107, 71]
    end

    version :card do
      process resize_to_fill: [550, 250]
    end

    def extension_white_list
      %w(jpg jpeg gif png)
    end

  end


text:
class Fluentd
  module Setting
    class OutForward < Output
      class Server
        include Common
        KEYS = [
          :name, :host, :port, :weight, :standby
        ].freeze

        attr_accessor(*KEYS)

        flags :standby

        validates :host, presence: true
        validates :port, presence: true
      end

      class Secondary
        include Common
        KEYS = [
          :type, :path
        ].freeze

        attr_accessor(*KEYS)

        hidden :type
        validates :path, presence: true
      end

      include Common
      relate_to_details

      KEYS = [
        :match,
        :send_timeout, :recover_wait, :heartbeat_type, :heartbeat_interval,
        :phi_threshold, :hard_timeout,
        :server, :secondary
      ].freeze

      attr_accessor(*KEYS)
      choice :heartbeat_type, %w(udp tcp)
      nested :server, Server, multiple: true
      nested :secondary, Secondary

      validates :match, presence: true
      validate :validate_has_at_least_one_server
      validate :validate_nested_values

      def validate_has_at_least_one_server
        if children_of(:server).reject{|s| s.empty_value? }.blank?
          errors.add(:base, :out_forward_blank_server)
        end
      end

      def validate_nested_values
        self.class.children.inject(true) do |result, (key, _)|
          children_of(key).each do |child|
            if !child.empty_value? && !child.valid?
              child.errors.full_messages.each do |message|
                errors.add(:base, "(#{key})#{message}")
              end
              result = false
            end
            result
          end
          result
        end
      end

      def self.initial_params
        {
          secondary: {
            "0" => {
              type: "file",
            }
          }
        }
      end

      def common_options
        [
          :match, :server, :secondary,
        ]
      end

      def advanced_options
        [
          :send_timeout, :recover_wait, :heartbeat_type, :heartbeat_interval,
          :phi_threshold, :hard_timeout,
        ]
      end

      def self.stream_field_name
        'server'
      end
    end
  end
end


text:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Options;
using System.Security.Cryptography;

namespace Serenity.Web
{
    public class ContentHashCache : IContentHashCache
    {
        private readonly ConcurrentDictionary<string, string> hashByContentPath;
        private readonly bool cdnEnabled;
        private readonly string cdnHttp;
        private readonly string cdnHttps;
        private readonly IO.GlobFilter cdnFilter;
        private readonly IWebHostEnvironment hostEnvironment;
        private readonly IHttpContextAccessor httpContextAccessor;

        public class CDNSettings
        {
            public bool? Enabled { get; set; }
            public string Url { get; set; }
            public string HttpsUrl { get; set; }
            public List<string> Include { get; set; }
            public List<string> Exclude { get; set; }
        }

        public ContentHashCache(IOptions<CDNSettings> cdnSettings,
            IWebHostEnvironment hostEnvironment, IHttpContextAccessor httpContextAccessor = null)
        {
            this.hostEnvironment = hostEnvironment ?? throw new ArgumentNullException(nameof(hostEnvironment));
            this.httpContextAccessor = httpContextAccessor;

            var cdn = cdnSettings.Value;
            hashByContentPath = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            cdnEnabled = cdn.Enabled == true && !string.IsNullOrEmpty(cdn.Url);
            cdnHttp = cdn.Url;
            if (string.IsNullOrEmpty(cdn.HttpsUrl))
                cdnHttps = (cdnHttp ?? "").Replace("http://", "https://", StringComparison.Ordinal);
            else
                cdnHttps = cdn.HttpsUrl;

            cdnFilter = new IO.GlobFilter(cdn.Include, cdn.Exclude);
        }

        public void ScriptsChanged()
        {
            hashByContentPath.Clear();
        }

        private static string GetFileSHA1(IFileInfo file)
        {
            byte[] hash;
            var md5 = MD5.Create();
            var physicalPath = file.PhysicalPath;
            if (physicalPath != null)
            {
                using System.IO.FileStream fs = new(physicalPath,
                    System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, 120000);
                hash = md5.ComputeHash(fs);
            }
            else
            {
                using var stream = file.CreateReadStream();
                hash = md5.ComputeHash(stream);
            }
            return WebEncoders.Base64UrlEncode(hash);
        }

        public string ResolvePath(PathString pathBase, string contentPath)
        {
            if (contentPath.IsNullOrEmpty())
                throw new ArgumentNullException(nameof(contentPath));

            if (contentPath[0] != '/' &&
                (contentPath[0] != '~' || contentPath.Length < 2 || contentPath[1] != '/'))
                return contentPath;

            contentPath = VirtualPathUtility.ToAbsolute(pathBase, contentPath);
            if (!cdnEnabled)
                return contentPath;

            bool isSecureConnection = httpContextAccessor?.HttpContext?.Request?.IsHttps == true;

            string cdnRoot = isSecureConnection ? cdnHttps : cdnHttp;
            return UriHelper.Combine(cdnRoot, contentPath);
        }

        public string ResolveWithHash(PathString pathBase, string contentUrl)
        {
            if (contentUrl.IsNullOrEmpty())
                throw new ArgumentNullException(nameof(contentUrl));

            if (contentUrl[0] == '~')
            {
                if (contentUrl.Length < 2 || contentUrl[1] != '/')
                    return VirtualPathUtility.ToAbsolute(pathBase, contentUrl);
            }
            else if (contentUrl[0] == '/')
            {
                if (contentUrl.Length < 2)
                    return contentUrl;

                var v = pathBase.Value ?? "";
                if (v.Length == 0 || v[^1] != '/')
                    v += '/';
                if (!contentUrl.StartsWith(v, StringComparison.OrdinalIgnoreCase))
                    return contentUrl;
                contentUrl = "~/" + contentUrl[v.Length..];
            }

            string cdnMatch = contentUrl;

            if (contentUrl.Contains(".axd/", StringComparison.OrdinalIgnoreCase))
            {
                if (!cdnEnabled)
                    return VirtualPathUtility.ToAbsolute(pathBase, contentUrl);

                cdnMatch = contentUrl.Split('?')[0];
            }
            else
            {
                var path = PathHelper.ToPath(contentUrl[2..]);

                var hash = hashByContentPath.GetOrAdd(path, (filePath) =>
                {
                    var fileInfo = hostEnvironment.WebRootFileProvider.GetFileInfo(filePath);
                    if (fileInfo.Exists)
                        return GetFileSHA1(fileInfo);
                    else
                        return DateTime.Now.ToString("yyyyMMddhh", CultureInfo.InvariantCulture);
                });

                contentUrl = VirtualPathUtility.ToAbsolute(pathBase, contentUrl) + "?v=" + hash;
                if (!cdnEnabled)
                    return contentUrl;
            }

            if (cdnMatch[0] == '/')
            {
                var root = VirtualPathUtility.ToAbsolute(pathBase, "~/");
                if (cdnMatch.StartsWith(root, StringComparison.OrdinalIgnoreCase))
                    cdnMatch = cdnMatch[root.Length..];
            }
            else
                cdnMatch = cdnMatch[2..];

            if (!cdnFilter.IsMatch(cdnMatch.Replace('/', System.IO.Path.DirectorySeparatorChar)))
                return contentUrl;

            bool isSecureConnection = httpContextAccessor?.HttpContext?.Request?.IsHttps == true;

            string cdnRoot = isSecureConnection ? cdnHttps : cdnHttp;
            contentUrl = VirtualPathUtility.ToAbsolute(pathBase, contentUrl);
            return UriHelper.Combine(cdnRoot, contentUrl);
        }
    }
}


text:
#ifndef GEOS_OP_POLYGONIZE_EDGERING_H
#define GEOS_OP_POLYGONIZE_EDGERING_H

#include <geos/export.h>

#include <vector>

#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4251) // warning C4251: needs to have dll-interface to be used by clients of class
#endif

// Forward declarations
namespace geos {
	namespace geom {
		class LineString;
		class LinearRing;
		class Polygon;
		class CoordinateSequence;
		class Geometry;
		class GeometryFactory;
		class Coordinate;
	}
	namespace planargraph {
		class DirectedEdge;
	}
}

namespace geos {
namespace operation { // geos::operation
namespace polygonize { // geos::operation::polygonize

/**\brief
 * Represents a ring of PolygonizeDirectedEdge which form
 * a ring of a polygon.  The ring may be either an outer shell or a hole.
 */
class GEOS_DLL EdgeRing {
private:
	const geom::GeometryFactory *factory;

	typedef std::vector<const planargraph::DirectedEdge*> DeList;
	DeList deList;

	// cache the following data for efficiency
	geom::LinearRing *ring;
	geom::CoordinateSequence *ringPts;

	typedef std::vector<geom::Geometry*> GeomVect;
	GeomVect *holes;

	/** \brief
	 * Computes the list of coordinates which are contained in this ring.
	 * The coordinatea are computed once only and cached.
	 *
	 * @return an array of the Coordinate in this ring
	 */
	geom::CoordinateSequence* getCoordinates();

	static void addEdge(const geom::CoordinateSequence *coords,
			bool isForward,
			geom::CoordinateSequence *coordList);

public:
	/**
	 * \brief
	 * Find the innermost enclosing shell EdgeRing
	 * containing the argument EdgeRing, if any.
	 *
	 * The innermost enclosing ring is the smallest enclosing ring.
	 * The algorithm used depends on the fact that:
	 *
	 * ring A contains ring B iff envelope(ring A) contains envelope(ring B)
	 *
	 * This routine is only safe to use if the chosen point of the hole
	 * is known to be properly contained in a shell
	 * (which is guaranteed to be the case if the hole does not touch
	 * its shell)
	 *
	 * @return containing EdgeRing, if there is one
	 * @return null if no containing EdgeRing is found
	 */
	static EdgeRing* findEdgeRingContaining(
			EdgeRing *testEr,
			std::vector<EdgeRing*> *shellList);

	/**
	 * \brief
	 * Finds a point in a list of points which is not contained in
	 * another list of points.
	 *
	 * @param testPts the CoordinateSequence to test
	 * @param pts the CoordinateSequence to test the input points against
	 * @return a Coordinate reference from testPts which is
	 * not in pts, or Coordinate::nullCoord
	 */
	static const geom::Coordinate& ptNotInList(
			const geom::CoordinateSequence *testPts,
			const geom::CoordinateSequence *pts);

	/** \brief
	 * Tests whether a given point is in an array of points.
	 * Uses a value-based test.
	 *
	 * @param pt a Coordinate for the test point
	 * @param pts an array of Coordinate to test
	 * @return true if the point is in the array
	 */
	static bool isInList(const geom::Coordinate &pt,
			const geom::CoordinateSequence *pts);

	EdgeRing(const geom::GeometryFactory *newFactory);

	~EdgeRing();

	/** \brief
	 * Adds a DirectedEdge which is known to form part of this ring.
	 *
	 * @param de the DirectedEdge to add. Ownership to the caller.
	 */
	void add(const planargraph::DirectedEdge *de);

	/** \brief
	 * Tests whether this ring is a hole.
	 *
	 * Due to the way the edges in the polyongization graph are linked,
	 * a ring is a hole if it is oriented counter-clockwise.
	 * @return true if this ring is a hole
	 */
	bool isHole();

	/** \brief
	 * Adds a hole to the polygon formed by this ring.
	 *
	 * @param hole the LinearRing forming the hole.
	 */
	void addHole(geom::LinearRing *hole);

	/** \brief
	 * Computes the Polygon formed by this ring and any contained holes.
	 *
	 * LinearRings ownership is transferred to returned polygon.
	 * Subsequent calls to the function will return NULL.
	 *
	 * @return the Polygon formed by this ring and its holes.
	 */
	geom::Polygon* getPolygon();

	/** \brief
	 * Tests if the LinearRing ring formed by this edge ring
	 * is topologically valid.
	 */
	bool isValid();

	/** \brief
	 * Gets the coordinates for this ring as a LineString.
	 *
	 * Used to return the coordinates in this ring
	 * as a valid geometry, when it has been detected that the ring
	 * is topologically invalid.
	 * @return a LineString containing the coordinates in this ring
	 */
	geom::LineString* getLineString();

	/** \brief
	 * Returns this ring as a LinearRing, or null if an Exception
	 * occurs while creating it (such as a topology problem).
	 *
	 * Ownership of ring is retained by the object.
	 * Details of problems are written to standard output.
	 */
	geom::LinearRing* getRingInternal();

	/** \brief
	 * Returns this ring as a LinearRing, or null if an Exception
	 * occurs while creating it (such as a topology problem).
	 *
	 * Details of problems are written to standard output.
	 * Caller gets ownership of ring.
	 */
	geom::LinearRing* getRingOwnership();
};

} // namespace geos::operation::polygonize
} // namespace geos::operation
} // namespace geos

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#endif // GEOS_OP_POLYGONIZE_EDGERING_H

/**********************************************************************
 * $Log$
 * Revision 1.2  2006/05/02 14:32:49  strk
 * Added port info for polygonize/EdgeRing class, polygonize/EdgeRing.h header
 * not installed.
 *
 * Revision 1.1  2006/03/22 11:19:06  strk
 * opPolygonize.h headers split.
 *
 **********************************************************************/


text:
        <?php
        $encrypted = $this->general->encryptParaID($course['courseid'],'course');
        $encrypted_assignid = $this->general->encryptParaID($course['assignid'],'courseassigned');
        ?>

<a href="<?php echo base_url() ?>index.php/student/courseView/<?php echo $encrypted ?>"><?php echo $course['coursename']?>

            <?php if ($this->nativesession->get('error')): ?>

                    <?php echo $this->nativesession->get('error');$this->nativesession->delete('error'); ?>

            <?php endif; ?>
            <?php if (validation_errors()): ?>

                    <?php echo validation_errors(); ?>

            <?php endif; ?>
            <?php if ($this->nativesession->get('success')): ?>

                    <?php echo $this->nativesession->get('success'); $this->nativesession->delete('success');?>

            <?php endif; ?>

            <?php if (!empty($top2navigation)): ?>
                <?php $this->load->view($top2navigation); ?>
            <?php else: ?>
                Navigation not found !
            <?php endif; ?>

Submit Assignment or Quizzes

                        <?php
                        $encrypted = $this->general->encryptParaID($anqID,'anq');
                        ?>
                        <?php echo form_open_multipart('student/courseAssignmentQuizSubmission/'.$encrypted); ?>
                        <input type="hidden" class="form-control set-margin-bottom" name="studentid" value="<?php echo $student['studentid']; ?>"/>
                        <input type="hidden" class="form-control set-margin-bottom" name="teacherid" value="<?php echo $teacherid; ?>"/>
                        <input type="hidden" class="form-control set-margin-bottom" name="anqid" value="<?php echo $anqID; ?>"/>

                            Topic

                                <input type="text" class="form-control col-md-7 col-xs-12" name="topic" value="<?php echo $anqData['topic']?>" readonly/>

                            Type

                                <input type="text" class="form-control col-md-7 col-xs-12" name="type" value="<?php echo $anqData['type']?>" readonly/>

                            Due Date

                                <input name="duedate" id="duedate" class="date-picker form-control col-md-7 col-xs-12" type="text" readonly/>

                            Choose File

                                <input class="btn btn-yellow" type="file" name="userfile" />

                        <button type="submit" class="btn btn-success set-margin-top"> Upload</button>
                        <?php echo form_close(); ?>


text:
<?php

namespace Yansongda\Pay\Tests\Stubs\Traits;

use Yansongda\Pay\Traits\GetUnipayCerts;

class GetUnipayCertsStub
{
    use GetUnipayCerts;
}


text:
#pragma once

#if ENABLE(ASYNC_SCROLLING) || USE(COORDINATED_GRAPHICS)

#include "ScrollingConstraints.h"
#include "ScrollingStateNode.h"

#include <wtf/Forward.h>

namespace WebCore {

class FixedPositionViewportConstraints;

class ScrollingStateFixedNode final : public ScrollingStateNode {
public:
    static Ref<ScrollingStateFixedNode> create(ScrollingStateTree&, ScrollingNodeID);

    Ref<ScrollingStateNode> clone(ScrollingStateTree&) override;

    virtual ~ScrollingStateFixedNode();

    enum {
        ViewportConstraints = NumStateNodeBits
    };

    WEBCORE_EXPORT void updateConstraints(const FixedPositionViewportConstraints&);
    const FixedPositionViewportConstraints& viewportConstraints() const { return m_constraints; }

private:
    ScrollingStateFixedNode(ScrollingStateTree&, ScrollingNodeID);
    ScrollingStateFixedNode(const ScrollingStateFixedNode&, ScrollingStateTree&);

    void reconcileLayerPositionForViewportRect(const LayoutRect& viewportRect, ScrollingLayerPositionAction) override;

    void dumpProperties(WTF::TextStream&, ScrollingStateTreeAsTextBehavior) const override;

    FixedPositionViewportConstraints m_constraints;
};

} // namespace WebCore

SPECIALIZE_TYPE_TRAITS_SCROLLING_STATE_NODE(ScrollingStateFixedNode, isFixedNode())

#endif // ENABLE(ASYNC_SCROLLING) || USE(COORDINATED_GRAPHICS)


text:
/*
 * Do not modify this file. This file is generated from the elasticfilesystem-2015-02-01.normal.json service model.
 */

using System;

using Amazon.Runtime;

namespace Amazon.ElasticFileSystem
{

    /// <summary>
    /// Constants used for properties of type LifeCycleState.
    /// </summary>
    public class LifeCycleState : ConstantClass
    {

        /// <summary>
        /// Constant Available for LifeCycleState
        /// </summary>
        public static readonly LifeCycleState Available = new LifeCycleState("available");
        /// <summary>
        /// Constant Creating for LifeCycleState
        /// </summary>
        public static readonly LifeCycleState Creating = new LifeCycleState("creating");
        /// <summary>
        /// Constant Deleted for LifeCycleState
        /// </summary>
        public static readonly LifeCycleState Deleted = new LifeCycleState("deleted");
        /// <summary>
        /// Constant Deleting for LifeCycleState
        /// </summary>
        public static readonly LifeCycleState Deleting = new LifeCycleState("deleting");

        /// <summary>
        /// Default Constructor
        /// </summary>
        public LifeCycleState(string value)
            : base(value)
        {
        }

        /// <summary>
        /// Finds the constant for the unique value.
        /// </summary>
        /// <param name="value">The unique value for the constant</param>
        /// <returns>The constant for the unique value</returns>
        public static LifeCycleState FindValue(string value)
        {
            return FindValue<LifeCycleState>(value);
        }

        /// <summary>
        /// Utility method to convert strings to the constant class.
        /// </summary>
        /// <param name="value">The string value to convert to the constant class.</param>
        /// <returns></returns>
        public static implicit operator LifeCycleState(string value)
        {
            return FindValue(value);
        }
    }

}


text:
package aux;

import java.awt.*;

public class ImageCanvas extends Canvas {
    private Image image;

    public ImageCanvas(Image image) {
	this.image = image;
    }

    public void paint(Graphics graphics) {
	graphics.drawImage(image, 0, 0, this);
    }

    public void update(Graphics graphics) {
	paint(graphics);
    }

    public Dimension minimumSize() {
	int w = image.getWidth(null);
	int h = image.getHeight(null);
	if (w == -1 || h == -1)
	    return new Dimension(0,0);
	return new Dimension(w, h);
    }

    public Dimension preferredSize() {
	return minimumSize();
    }
}


text:
import { History } from './routerHistory';
declare const hashHistory: History;
export default hashHistory;


text:
library for profiling code

## Compilation

    sbt package publishLocal

## Basic usage

	  Profiler.profile {
	  	println("hello")
	  	Thread.sleep(500L )
	  }

## With identification

    Profiler.profileWithIdentifier("hello", {
  	  println("hello")
  	  Thread.sleep(500L)
    })


text:
from odin.fuel.nlp_data._base import NLPDataset
from odin.fuel.nlp_data.newsgroup import Newsgroup5, Newsgroup20
from odin.fuel.nlp_data.newsgroup20_clean import Newsgroup20_clean


text:
app.factory('notificationService', ['$mdToast', function ($mdToast) {

    var notificationTypes = {
        error: 'error',
        success: 'success'
    };

    function showNotification(message, hideDelay, type) {
        hideDelay = hideDelay || 3000;
        $mdToast.show(
            $mdToast.simple()
                .textContent(message)
                .position('left')
                .theme(type + '-toast')
                .hideDelay(hideDelay));
    }

    function showError(message, hideDelay) {
        showNotification(message, hideDelay, notificationTypes.error);
    }

    function showSuccess(message, hideDelay) {
        showNotification(message, hideDelay, notificationTypes.success);
    }

    return {
        showError: showError,
        showSuccess: showSuccess
    };
}]);


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

namespace Winning_Ticket
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] tickets = Console.ReadLine().Split(',').Select(x => x.Trim()).ToArray();
            char[] winningSymbols = new char[] { '@', '#', '$', '^' };
            foreach (var ticket in tickets)
            {
                if (ticket.Length != 20)
                {
                    Console.WriteLine("invalid ticket");
                    continue;
                }
                int repeatsLeft = 1;
                int repeatsRight = 1;
                List<KeyValuePair<char, int>> leftWins = new List<KeyValuePair<char, int>>();
                List<KeyValuePair<char, int>> leftJackpot = new List<KeyValuePair<char, int>>();
                for (int i = 0; i < ticket.Length/2-1; i++)
                {
                    if (winningSymbols.Contains(ticket[i]) && ticket[i] == ticket[i+1])
                    {
                        repeatsLeft++;
                        if (repeatsLeft >= 6 && repeatsLeft <= 9)
                        {
                            leftWins.Add(new KeyValuePair<char, int>(ticket[i], repeatsLeft));
                        }
                        else if (repeatsLeft == 10)
                        {
                            leftJackpot.Add(new KeyValuePair<char, int>(ticket[i], repeatsLeft));
                        }

                    }
                    else
                    {
                        repeatsLeft = 1;
                    }
                }
                int matchLength = 0;
                char matchSymbol = char.MinValue;
                bool match = false;
                bool jackpot = false;
                for (int i = ticket.Length-1; i > ticket.Length/2; i--)
                {
                    if (winningSymbols.Contains(ticket[i]) && ticket[i] == ticket[i - 1])
                    {
                        repeatsRight++;
                        if (repeatsRight >= 6 && repeatsRight <= 9)
                        {
                            if (leftWins.Contains(new KeyValuePair<char, int>(ticket[i], repeatsRight)) && repeatsRight > matchLength)
                            {
                                match = true;
                                matchSymbol = ticket[i];
                                matchLength = repeatsRight;
                            }
                        }
                        else if (repeatsLeft == 10 && leftJackpot.Contains(new KeyValuePair<char, int>(ticket[i], repeatsRight)))
                        {
                            Console.WriteLine("ticket \"{0}\" - 10{1} Jackpot!", ticket, ticket[0]);
                            match = false;
                            jackpot = true;
                            break;
                        }
                    }
                    else
                    {
                        repeatsRight = 1;
                    }
                }
                if (match)
                {
                    Console.WriteLine("ticket \"{0}\" - {1}{2}", ticket, matchLength, matchSymbol);
                }
                else
                {
                    if (!jackpot)
                    {
                        Console.WriteLine("ticket \"{0}\" - no match", ticket);
                    }
                }
            }
        }
    }
}


text:
"use strict";

var fs = require("fs");
var path = require("path");
var postcss = require("postcss");

var csswring = require("../index");

exports["Public API"] = function (test) {
  var expected;
  var input = ".foo{color:black}";
  expected = postcss().process(input).css;

  test.expect(2);

  test.strictEqual(
    csswring.wring(input).css,
    expected
  );

  test.strictEqual(
    postcss([
      csswring()
    ]).process(input).css,
    expected
  );

  test.done();
};

exports["Option: PostCSS options"] = function (test) {
  var expected;
  var input = ".foo{color:black}";
  var opts = {
    from: "from.css",
    map: {
      inline: false
    }
  };
  var processed = csswring.wring(input, opts);
  expected = postcss().process(input, opts);

  test.expect(2);

  test.strictEqual(
    processed.css,
    expected.css
  );

  test.deepEqual(
    processed.map,
    expected.map
  );

  test.done();
};

exports["Option: preserveHacks"] = function (test) {
  var expected = ".hacks{_color:red}";
  var input = expected;
  var opts = {
    preserveHacks: true
  };

  test.expect(3);

  test.strictEqual(
    csswring.wring(input, opts).css,
    expected
  );

  expected = postcss([csswring()]).process(input).css;
  test.notStrictEqual(
    postcss([csswring(opts)]).process(input).css,
    expected
  );

  expected = "";
  test.strictEqual(
    csswring.wring(input).css,
    expected
  );

  test.done();
};

exports["Option: removeAllComments"] = function (test) {
  var expected = ".foo{display:block}\n/*# sourceMappingURL=to.css.map */";
  var input = "/*!comment*/.foo{display:block}\n/*# sourceMappingURL=to.css.map */";
  var opts = {
    map: {
      inline: false
    },
    removeAllComments: true
  };

  test.expect(3);

  test.strictEqual(
    csswring.wring(input, opts).css,
    expected
  );

  expected = postcss([csswring(opts)]).process(input).css;
  test.notStrictEqual(
    postcss([csswring()]).process(input).css,
    expected
  );

  opts.removeAllComments = false;
  expected = input;
  test.strictEqual(
    csswring.wring(input, opts).css,
    expected
  );

  test.done();
};

exports["Real CSS"] = function (test) {
  var testCases = fs.readdirSync(path.join(__dirname, "fixtures"));

  var loadExpected = function (file) {
    file = path.join(__dirname, "expected", file);

    return fs.readFileSync(file, "utf8").trim();
  };

  var loadInput = function (file) {
    file = path.join(__dirname, "fixtures", file);

    return fs.readFileSync(file, "utf8");
  };

  test.expect(testCases.length);

  testCases.forEach(function (testCase) {
    var opts = {};

    if (testCase.indexOf("hacks_") === 0) {
      opts.preserveHacks = true;
    }

    test.strictEqual(
      csswring.wring(loadInput(testCase), opts).css,
      loadExpected(testCase),
      testCase
    );
  });

  test.done();
};


text:
<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\User;
use AppBundle\Entity\Group;
use AppBundle\Entity\Address;
use AppBundle\Entity\Image;
use AppBundle\Entity\Country;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Validator\Constraints\Url;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class UserController extends Controller
{

    /**
     * @Route("/users", name="test")
     * @Method({"GET"})
     */
    public function indexAction(Request $request)
    {
        $response = array();
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('AppBundle:User');
        $allUser = $user->findAll();
        $serializer = $this->get('jms_serializer');

        $response['body'] = $allUser;
        $response['status'] = true;
        $response['error'] = [];

        $res = new Response($serializer->serialize($response,'json'));
        $res->headers->set('Content-Type', 'application/json');
        return $res;
    }

    /**
     * @Route("/users", name="save_user")
     * @Method({"POST"})
     */
    public function addUserAction(Request $request)
    {

        //get file from request
        $file = $request->files->get('file');
        $serializer = $this->get('jms_serializer');

        //validate file
        $image = new Image();
        $image->setFile($file);
        $validator = $this->get('validator');
        $errors = $validator->validate($image);
        //validate upload image
        if (count($errors) > 0) {
            /*
             * Uses a __toString method on the $errors variable which is a
             * ConstraintViolationList object. This gives us a nice string
             * for debugging.
             */
            $errorMessage = [];
            foreach ($errors as $error) {
                $errorMessage[$error->getPropertyPath()] =  $error->getMessage();
            }

            $response['body'] = [];
            $response['status'] = false;
            $response['error'] = $errorMessage;

            return new Response($serializer->serialize($response,'json'));
            die();
        }

        $fileName = $this->get('app.file_uploader')->upload($file);

        $formData = $request->request->all();

        //save form data
        //$request->query->get('id'); retrive post get data example
        $user = new User();
        $address = new Address();
        $user_permission = new Group();
        $image = new Image();

        //response to API
        $response = array();
        //$serializer = $this->get('jms_serializer');

        //NEED VALIDATE FORM DATA IN FUTURE

        $repository = $this->getDoctrine()->getRepository('AppBundle:User');

        $check_duplicat_name = $repository->findOneByUsername($formData['name']);

        //check duplicat
        if($check_duplicat_name){

            $response['error'] = 'Username already exist!';
            $array = $serializer->toArray($response);
            return new JsonResponse($array);

        }

        $check_duplicat_email = $repository->findOneByEmail($formData['email']);
        //check duplicat
        if($check_duplicat_email){

            $response['error'] = 'Email already exist!';
            $array = $serializer->toArray($response);
            return new JsonResponse($array);
        }

        $em = $this->getDoctrine()->getManager();
        $user_role = $em->getRepository('AppBundle:Role')
            ->loadRoleByRolename('ROLE_USER'); //my custom repository

        $user_country = $em->getRepository('AppBundle:Country')
            ->loadCountryByName($formData['country']);
        //*/
        //save form data to database
        // $image->setPath($form_data['file_path']);
        $image->setPath($request->getScheme() . '://' . $request->getHttpHost().'/upload/'.$fileName);
        $address->setAddress($formData['address']);
        $pwd= 111111; //$user->getPassword()
        $encoder=$this->container->get('security.password_encoder');
        $pwd=$encoder->encodePassword($user, $pwd);
        $user->setPassword($pwd);
        $user->setUsername($formData['name']);
        $user->setEmail($formData['email']);
        $user->setOnline();

        //set user relation
        $user->setAddress($address);
        $user->setCountry($user_country);
        $user->setImage($image);
        //add user permission
        $user_permission->setName($formData['name']);
        $user_permission->setUserRole($user_role);

        $user->addGroup($user_permission);
        $em = $this->getDoctrine()->getManager();

        $em->persist($address);
        $em->persist($user);
        $em->persist($user_permission);
        $em->persist($image);
        $em->flush();

        //return last save object
        $last_object = $repository->find($user->getId());

        // $serializer = $serializer::create()->build();
        $array = $serializer->toArray($last_object);
        $response['body'] = $array;
        $response['status'] = true;
        $response['error'] = [];

        return new Response($serializer->serialize($response,'json'));
        die();
    }

    /**
     * @Route("/users/{id}", name="delete_user")
     * @Method({"DELETE"})
     */
    public function deleteUserAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('AppBundle:User')->find($id);
        $em->remove($user);
        $em->flush();
        $res = new Response(json_encode(true));
        return $res;
    }

    //public route to display image
    /**
     * @Route("/test", name="test_image")
     * @Method({"GET"})
     */
    public function test(request $request)
    {
        $file = $this->getParameter('upload_path').'/'.'1a2e824562e22ec6956a9fdb4a0328ee.jpeg';
        $response = new BinaryFileResponse($file);
        // you can modify headers here, before returning
        return $response;
    }

    /**
     * @Route("/login", name="login_user")
     * @Method({"POST"})
     */
    public function loginAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $serializer = $this->get('jms_serializer');
        $formData = $request->request->all();

        $user = new User();
        $encoder=$this->container->get('security.password_encoder');
        $pwd=$encoder->encodePassword($user, $formData['password']);
        $repository = $this->getDoctrine()->getRepository('AppBundle:User');
        $user = $repository->findOneBy(
            ['email' => $formData['email'], 'password' => $pwd]
        );
        if($user) {
            //update login user online time
            $user->setOnline();
            $em->flush();

            $response['body'] = $serializer->toArray($user);
            $response['status'] = true;
            $response['error'] = [];
        } else {
            $response['body'] = '';
            $response['status'] = false;
            $response['error'] = ['User do not exist'];
        }
        $res = new Response($serializer->serialize($response,'json'));
        return $res;
    }

    /**
     * @Route("/online/update", name="userOnline")
     * @Method({"POST"})
     */
    public function updateOnlineStatus(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $serializer = $this->get('jms_serializer');
        $params = array();
        $content =$request->getContent();
        if (!empty($content))
        {
            $params = json_decode($content, true); // 2nd param to get as array
        }
        $repository = $this->getDoctrine()->getRepository('AppBundle:User');
        $user = $repository->find($params['currentUser']);
        if($user) {
            //update login user online time
            $user->setOnline();
            $em->flush();
            $response['message'] = ['User online status update successfully'];
            $response['status'] = 200;
            $response['error'] = [];
        } else {
            $response['message'] = [];
            $response['status'] = 404;
            $response['error'] = ['User do not exist'];
        }
        $res = new Response($serializer->serialize($response,'json'), $response['status']);
        return $res;
    }

    /**
     * @Route("/online/user", name="getUserOnline")
     * @Method({"GET"})
     */
    public function getOnlineUser(Request $request)
    {
        $currentId = $request->query->get('currentUser');
        $currentTime = date("Y-m-d H:i:s", (time() - 60)); //current time - 1 minute
        $serializer = $this->get('jms_serializer');
        $em = $this->getDoctrine()->getManager();

        $qb = $em->createQueryBuilder();
        $user = $em
            ->getRepository('AppBundle:User')
            ->createQueryBuilder('e')
           //\ ->where($qb->expr()->notIn('e.id', [(int)$currentId]))
            ->andWhere('e.online > :currentDate')
            ->setParameter('currentDate', $currentTime)
            ->getQuery()
            ->getResult();
        if($user) {
            //update login user online time
            $response['body'] = $user;
            $response['status'] = 200;
            $response['error'] = [];
        } else {
            $response['body'] = [];
            $response['status'] = 404;
            $response['error'] = ['User do not exist'];
        }
        $res = new Response($serializer->serialize($response,'json'), $response['status']);
        return $res;
    }

    //check authentication
    /**
     * @Route("login/confirm", name="login_confirm")
     * @Method({"POST"})
     */
    public function loginConfirmAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $serializer = $this->get('jms_serializer');
        $formData = $request->request->all();

        $em = $this->getDoctrine()->getManager();

        $qb = $em->createQueryBuilder();
        $user = $em
            ->getRepository('AppBundle:User')
            ->createQueryBuilder('e')
            ->where('e.isActive = :active')
            ->setParameter('active',1)
            ->andWhere('e.email = :emaill')
            ->setParameter('emaill', $formData['email'])
            ->getQuery()
            ->getResult();

        if($user) {

            $response['status'] = true;
            $response['error'] = [];
        } else {
            $response['status'] = false;
            $response['error'] = ['User do not exist'];
        }
        $res = new Response($serializer->serialize($response,'json'));
        return $res;
    }
}


text:
Small Donor Democracy

The public matching funds program amplifies the impact of low-dollar contributions, giving more New Yorkers a real voice in the democratic process.


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

<title>SerializationTester</title>
<meta name="date" content="2016-09-19">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.deeplearning4j.spark.util

Class SerializationTester

java.lang.Object

org.deeplearning4j.spark.util.SerializationTester

public class SerializationTester
extends java.lang.Object

Test serialization

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static void
testSerialization(ActorSystem system,
                 java.lang.Object test)

Testing akka serialization

static void
testSerialization(java.lang.Object test)

Test serialization

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

testSerialization

public static void testSerialization(ActorSystem system,
                                     java.lang.Object test)
                              throws java.lang.Exception

Testing akka serialization

Parameters:

system - the system to test on

test - the object to test

Throws:

java.lang.Exception

testSerialization

public static void testSerialization(java.lang.Object test)

Test serialization

Parameters:

test - the object to test

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php

declare(strict_types=1);

namespace Eloquent\Phony\Hamcrest;

use Hamcrest\Matcher;
use Hamcrest\Util;
use PHPUnit\Framework\TestCase;
use ReflectionClass;

class HamcrestMatcherDriverTest extends TestCase
{
    protected function setUp(): void
    {
        Util::registerGlobalFunctions();

        $this->subject = new HamcrestMatcherDriver();

        $this->matcher = equalTo('x');
    }

    public function testIsAvailable()
    {
        $this->assertTrue($this->subject->isAvailable());
    }

    public function testMatcherClassNames()
    {
        $this->assertSame([Matcher::class], $this->subject->matcherClassNames());
    }

    public function testWrapMatcher()
    {
        $this->assertEquals(new HamcrestMatcher($this->matcher), $this->subject->wrapMatcher($this->matcher));
    }

    public function testInstance()
    {
        $class = get_class($this->subject);
        $reflector = new ReflectionClass($class);
        $property = $reflector->getProperty('instance');
        $property->setAccessible(true);
        $property->setValue(null, null);
        $instance = $class::instance();

        $this->assertInstanceOf($class, $instance);
        $this->assertSame($instance, $class::instance());
    }
}


text:
use strict;
use warnings;

use Getopt::Long;
use JSON qw(decode_json);

use Bio::EnsEMBL::Compara::DBSQL::DBAdaptor;
use Bio::EnsEMBL::Utils::IO qw(slurp);

# Parameters:
# URL to the Compara database
my ($compara_url, $species_json);
# Group ranks in taxonomy table?
# E.g.:
#   CLASS     SUPERORDER        ORDER     SUBORDER     FAMILY   SUBFAMILY       SPECIES             GENOMEDB NAME
#   Mammalia  Euarchontoglires  Primates  Haplorrhini  Cebidae  Callitrichinae  Callithrix jacchus  callithrix_jacchus
#   Mammalia  Euarchontoglires  Primates  Haplorrhini  Cebidae  Cebinae         Cebus capucinus     cebus_capucinus
# will be printed like
#   CLASS     SUPERORDER        ORDER     SUBORDER     FAMILY   SUBFAMILY       SPECIES             GENOMEDB NAME
#   Mammalia  Euarchontoglires  Primates  Haplorrhini  Cebidae  Callitrichinae  Callithrix jacchus  callithrix_jacchus
#   ''        ''                ''        ''           ''       Cebinae         Cebus capucinus     cebus_capucinus
my $group_ranks = 0;
# Handle input arguments
GetOptions("compara_url=s"  => \$compara_url,
           "group"          => \$group_ranks,
           "species_json=s" => \$species_json,
          ) or die("Error in command line arguments\n");
die "Error in command line arguments: -compara_url mysql://user:pass\@host:port/db_name"
    if (!$compara_url);

# Create new Compara database adaptor and get the GenomeDB adaptor
my $compara_dba = Bio::EnsEMBL::Compara::DBSQL::DBAdaptor->new(-url => $compara_url);
# Declare the taxonomic ranks of interest (sorted)
my @target_ranks = qw(class superorder order suborder family subfamily species);
# Number of ranks (plus the default addition of "GenomeDB name" as last rank)
my $num_ranks = $#target_ranks + 1;
# Create the taxonomy template: if a rank is missing, assign "N/A"
my $null_value = 'N/A';
my %rank_template = map {$_ => $null_value} @target_ranks;
# Get the taxon node for each species either in the species JSON file or in the genome_db table
my %taxon_hash;
if ($species_json) {
    my $species_list = decode_json(slurp($species_json));
    my $taxon_adaptor = $compara_dba->get_NCBITaxonAdaptor();
    foreach my $species (@$species_list) {
        my $species_name = ($species =~ s/_/ /gr);
        $taxon_hash{$species} = $taxon_adaptor->fetch_node_by_name($species_name);
    }
} else {
    my $genome_db_adaptor = $compara_dba->get_GenomeDBAdaptor();
    # Get all the Genome DBs
    my $list_of_gdbs = $genome_db_adaptor->fetch_all();
    foreach my $gdb (@{$list_of_gdbs}) {
        # There are some $gdb that may not have 'taxon_id', so we need to handle the
        # exception, report the troubling $gdb and move to the next one
        if (!$gdb->taxon_id() || !defined($gdb->taxon())) {
            warn "Undefined taxon_id for '", $gdb->name(), "'.\n";
            next;
        }
        $taxon_hash{$gdb->name()} = $gdb->taxon();
    }
}
# @taxonomy_table will have one string per species' taxonomy in tab-separated
# values (TSV) format
my @taxonomy_table;
foreach my $species (keys %taxon_hash) {
    my $node = $taxon_hash{$species};
    # Copy taxonomy template and fill it in
    my %taxonomy = %rank_template;
    while ($node->name() ne 'root') {
        my $rank = $node->rank();
        if (exists($taxonomy{$rank})) {
            $taxonomy{$rank} = $node->name();
        }
        $node = $node->parent();
    }
    # Get the taxonomy in a TSV-like string, add GenomeDB name as the last
    # level/rank and append it to the taxonomy table
    my $taxonomy_str = join("\t", (map {$taxonomy{$_}} @target_ranks), $species);
    push(@taxonomy_table, $taxonomy_str);
}
# Sort the rows in alphabetical order
@taxonomy_table = sort(@taxonomy_table);
if ($group_ranks) {
    # Group ranks in taxonomy table, replacing duplicates by "''"
    # Get the first row as reference to see how many ranks are the same
    my @prev_taxonomy = split(/\t/, $taxonomy_table[0]);
    foreach my $i (1 .. $#taxonomy_table) {
        my @taxonomy = split(/\t/, $taxonomy_table[$i]);
        # Grouped version of the taxonomy (string)
        my $grouped_taxonomy = "";
        # Flag when two consecutive species have a not-null matching rank
        my $not_null_match_found = 0;
        # Loop over each rank to compare it with the value in the previous row
        foreach my $j (0 .. $num_ranks) {
            if ($prev_taxonomy[$j] eq $taxonomy[$j]) {
                # Get the flag to True if the ranks are not null and equal
                if ($taxonomy[$j] ne $null_value) {
                    $not_null_match_found = 1;
                }
            } else {
                # If there is a not-null match, all the ranks matched can be
                # replaced by "''". If not, it means all the ranks were missing
                # until this point, so leave the null value.
                my @values;
                if ($not_null_match_found) {
                    @values = ("''") x $j;
                } else {
                    @values = ($null_value) x $j;
                }
                # As soon as one rank is different, the remaining will be too
                $grouped_taxonomy .= join("\t", @values, @taxonomy[$j .. $num_ranks]);
                last;
            }
        }
        # Replace the string by its grouped version
        $taxonomy_table[$i] = $grouped_taxonomy;
        # Get the current taxonomy as reference for the next step
        @prev_taxonomy = @taxonomy;
    }
}
# Write the array into STDOUT with @target_ranks as headers
print join("\t", map(ucfirst, @target_ranks), 'Requested name'), "\n",
      join("\n", @taxonomy_table), "\n";