package com.doublechaintech.retailscm.originalvoucher;

import java.util.*;
import java.math.BigDecimal;
import com.terapico.caf.baseelement.PlainText;
import com.terapico.caf.DateTime;
import com.terapico.caf.Images;
import com.terapico.caf.Password;
import com.terapico.utils.MapUtil;
import com.terapico.utils.ListofUtils;
import com.terapico.utils.TextUtil;
import com.terapico.caf.BlobObject;
import com.terapico.caf.viewpage.SerializeScope;

import com.doublechaintech.retailscm.*;
import com.doublechaintech.retailscm.utils.ModelAssurance;
import com.doublechaintech.retailscm.tree.*;
import com.doublechaintech.retailscm.treenode.*;
import com.doublechaintech.retailscm.RetailscmUserContextImpl;
import com.doublechaintech.retailscm.iamservice.*;
import com.doublechaintech.retailscm.services.IamService;
import com.doublechaintech.retailscm.secuser.SecUser;
import com.doublechaintech.retailscm.userapp.UserApp;
import com.doublechaintech.retailscm.BaseViewPage;
import com.terapico.uccaf.BaseUserContext;

import com.doublechaintech.retailscm.accountingdocument.AccountingDocument;

import com.doublechaintech.retailscm.accountingdocument.CandidateAccountingDocument;

public class OriginalVoucherManagerImpl extends CustomRetailscmCheckerManager implements OriginalVoucherManager, BusinessHandler{

	// Only some of ods have such function

	private static final String SERVICE_TYPE = "OriginalVoucher";
	@Override
	public OriginalVoucherDAO daoOf(RetailscmUserContext userContext) {
		return originalVoucherDaoOf(userContext);
	}

	@Override
	public String serviceFor(){
		return SERVICE_TYPE;
	}

	protected void throwExceptionWithMessage(String value) throws OriginalVoucherManagerException{

		Message message = new Message();
		message.setBody(value);
		throw new OriginalVoucherManagerException(message);

	}

 	protected OriginalVoucher saveOriginalVoucher(RetailscmUserContext userContext, OriginalVoucher originalVoucher, String [] tokensExpr) throws Exception{
 		//return getOriginalVoucherDAO().save(originalVoucher, tokens);

 		Map<String,Object>tokens = parseTokens(tokensExpr);

 		return saveOriginalVoucher(userContext, originalVoucher, tokens);
 	}

 	protected OriginalVoucher saveOriginalVoucherDetail(RetailscmUserContext userContext, OriginalVoucher originalVoucher) throws Exception{

 		return saveOriginalVoucher(userContext, originalVoucher, allTokens());
 	}

 	public OriginalVoucher loadOriginalVoucher(RetailscmUserContext userContext, String originalVoucherId, String [] tokensExpr) throws Exception{

 		checkerOf(userContext).checkIdOfOriginalVoucher(originalVoucherId);
		checkerOf(userContext).throwExceptionIfHasErrors( OriginalVoucherManagerException.class);

 		Map<String,Object>tokens = parseTokens(tokensExpr);

 		OriginalVoucher originalVoucher = loadOriginalVoucher( userContext, originalVoucherId, tokens);
 		//do some calc before sent to customer?
 		return present(userContext,originalVoucher, tokens);
 	}

 	 public OriginalVoucher searchOriginalVoucher(RetailscmUserContext userContext, String originalVoucherId, String textToSearch,String [] tokensExpr) throws Exception{

 		checkerOf(userContext).checkIdOfOriginalVoucher(originalVoucherId);
		checkerOf(userContext).throwExceptionIfHasErrors( OriginalVoucherManagerException.class);

 		Map<String,Object>tokens = tokens().allTokens().searchEntireObjectText(tokens().startsWith(), textToSearch).initWithArray(tokensExpr);

 		OriginalVoucher originalVoucher = loadOriginalVoucher( userContext, originalVoucherId, tokens);
 		//do some calc before sent to customer?
 		return present(userContext,originalVoucher, tokens);
 	}

 	protected OriginalVoucher present(RetailscmUserContext userContext, OriginalVoucher originalVoucher, Map<String, Object> tokens) throws Exception {

		addActions(userContext,originalVoucher,tokens);

		OriginalVoucher  originalVoucherToPresent = originalVoucherDaoOf(userContext).present(originalVoucher, tokens);

		List<BaseEntity> entityListToNaming = originalVoucherToPresent.collectRefercencesFromLists();
		originalVoucherDaoOf(userContext).alias(entityListToNaming);

		renderActionForList(userContext,originalVoucher,tokens);

		return  originalVoucherToPresent;

	}

 	public OriginalVoucher loadOriginalVoucherDetail(RetailscmUserContext userContext, String originalVoucherId) throws Exception{
 		OriginalVoucher originalVoucher = loadOriginalVoucher( userContext, originalVoucherId, allTokens());
 		return present(userContext,originalVoucher, allTokens());

 	}

 	public Object view(RetailscmUserContext userContext, String originalVoucherId) throws Exception{
 		OriginalVoucher originalVoucher = loadOriginalVoucher( userContext, originalVoucherId, viewTokens());
 		return present(userContext,originalVoucher, allTokens());

 	}
 	protected OriginalVoucher saveOriginalVoucher(RetailscmUserContext userContext, OriginalVoucher originalVoucher, Map<String,Object>tokens) throws Exception{
 		return originalVoucherDaoOf(userContext).save(originalVoucher, tokens);
 	}
 	protected OriginalVoucher loadOriginalVoucher(RetailscmUserContext userContext, String originalVoucherId, Map<String,Object>tokens) throws Exception{
		checkerOf(userContext).checkIdOfOriginalVoucher(originalVoucherId);
		checkerOf(userContext).throwExceptionIfHasErrors( OriginalVoucherManagerException.class);

 		return originalVoucherDaoOf(userContext).load(originalVoucherId, tokens);
 	}

 	protected<T extends BaseEntity> void addActions(RetailscmUserContext userContext, OriginalVoucher originalVoucher, Map<String, Object> tokens){
		super.addActions(userContext, originalVoucher, tokens);

		addAction(userContext, originalVoucher, tokens,"@create","createOriginalVoucher","createOriginalVoucher/","main","primary");
		addAction(userContext, originalVoucher, tokens,"@update","updateOriginalVoucher","updateOriginalVoucher/"+originalVoucher.getId()+"/","main","primary");
		addAction(userContext, originalVoucher, tokens,"@copy","cloneOriginalVoucher","cloneOriginalVoucher/"+originalVoucher.getId()+"/","main","primary");

		addAction(userContext, originalVoucher, tokens,"original_voucher.transfer_to_belongs_to","transferToAnotherBelongsTo","transferToAnotherBelongsTo/"+originalVoucher.getId()+"/","main","primary");

	}// end method of protected<T extends BaseEntity> void addActions(RetailscmUserContext userContext, OriginalVoucher originalVoucher, Map<String, Object> tokens){

	public OriginalVoucher createOriginalVoucher(RetailscmUserContext userContext, String title,String madeBy,String receivedBy,String voucherType,String voucherImage,String belongsToId) throws Exception
	//public OriginalVoucher createOriginalVoucher(RetailscmUserContext userContext,String title, String madeBy, String receivedBy, String voucherType, String voucherImage, String belongsToId) throws Exception
	{

		checkerOf(userContext).checkTitleOfOriginalVoucher(title);
		checkerOf(userContext).checkMadeByOfOriginalVoucher(madeBy);
		checkerOf(userContext).checkReceivedByOfOriginalVoucher(receivedBy);
		checkerOf(userContext).checkVoucherTypeOfOriginalVoucher(voucherType);
		checkerOf(userContext).checkVoucherImageOfOriginalVoucher(voucherImage);

		checkerOf(userContext).throwExceptionIfHasErrors(OriginalVoucherManagerException.class);

		OriginalVoucher originalVoucher=createNewOriginalVoucher();

		originalVoucher.setTitle(title);
		originalVoucher.setMadeBy(madeBy);
		originalVoucher.setReceivedBy(receivedBy);
		originalVoucher.setVoucherType(voucherType);
		originalVoucher.setVoucherImage(voucherImage);

		AccountingDocument belongsTo = loadAccountingDocument(userContext, belongsToId,emptyOptions());
		originalVoucher.setBelongsTo(belongsTo);

		originalVoucher = saveOriginalVoucher(userContext, originalVoucher, emptyOptions());

		onNewInstanceCreated(userContext, originalVoucher);
		return originalVoucher;

	}
	protected OriginalVoucher createNewOriginalVoucher()
	{

		return new OriginalVoucher();
	}

	protected void checkParamsForUpdatingOriginalVoucher(RetailscmUserContext userContext,String originalVoucherId, int originalVoucherVersion, String property, String newValueExpr,String [] tokensExpr)throws Exception
	{

		checkerOf(userContext).checkIdOfOriginalVoucher(originalVoucherId);
		checkerOf(userContext).checkVersionOfOriginalVoucher( originalVoucherVersion);

		if(OriginalVoucher.TITLE_PROPERTY.equals(property)){

			checkerOf(userContext).checkTitleOfOriginalVoucher(parseString(newValueExpr));

		}
		if(OriginalVoucher.MADE_BY_PROPERTY.equals(property)){

			checkerOf(userContext).checkMadeByOfOriginalVoucher(parseString(newValueExpr));

		}
		if(OriginalVoucher.RECEIVED_BY_PROPERTY.equals(property)){

			checkerOf(userContext).checkReceivedByOfOriginalVoucher(parseString(newValueExpr));

		}
		if(OriginalVoucher.VOUCHER_TYPE_PROPERTY.equals(property)){

			checkerOf(userContext).checkVoucherTypeOfOriginalVoucher(parseString(newValueExpr));

		}
		if(OriginalVoucher.VOUCHER_IMAGE_PROPERTY.equals(property)){

			checkerOf(userContext).checkVoucherImageOfOriginalVoucher(parseString(newValueExpr));

		}

		checkerOf(userContext).throwExceptionIfHasErrors(OriginalVoucherManagerException.class);

	}

	public OriginalVoucher clone(RetailscmUserContext userContext, String fromOriginalVoucherId) throws Exception{

		return originalVoucherDaoOf(userContext).clone(fromOriginalVoucherId, this.allTokens());
	}

	public OriginalVoucher internalSaveOriginalVoucher(RetailscmUserContext userContext, OriginalVoucher originalVoucher) throws Exception
	{
		return internalSaveOriginalVoucher(userContext, originalVoucher, allTokens());

	}
	public OriginalVoucher internalSaveOriginalVoucher(RetailscmUserContext userContext, OriginalVoucher originalVoucher, Map<String,Object> options) throws Exception
	{
		//checkParamsForUpdatingOriginalVoucher(userContext, originalVoucherId, originalVoucherVersion, property, newValueExpr, tokensExpr);

		synchronized(originalVoucher){
			//will be good when the originalVoucher loaded from this JVM process cache.
			//also good when there is a ram based DAO implementation
			//make changes to OriginalVoucher.
			if (originalVoucher.isChanged()){

			}
			originalVoucher = saveOriginalVoucher(userContext, originalVoucher, options);
			return originalVoucher;

		}

	}

	public OriginalVoucher updateOriginalVoucher(RetailscmUserContext userContext,String originalVoucherId, int originalVoucherVersion, String property, String newValueExpr,String [] tokensExpr) throws Exception
	{
		checkParamsForUpdatingOriginalVoucher(userContext, originalVoucherId, originalVoucherVersion, property, newValueExpr, tokensExpr);

		OriginalVoucher originalVoucher = loadOriginalVoucher(userContext, originalVoucherId, allTokens());
		if(originalVoucher.getVersion() != originalVoucherVersion){
			String message = "The target version("+originalVoucher.getVersion()+") is not equals to version("+originalVoucherVersion+") provided";
			throwExceptionWithMessage(message);
		}
		synchronized(originalVoucher){
			//will be good when the originalVoucher loaded from this JVM process cache.
			//also good when there is a ram based DAO implementation
			//make changes to OriginalVoucher.

			originalVoucher.changeProperty(property, newValueExpr);
			originalVoucher = saveOriginalVoucher(userContext, originalVoucher, tokens().done());
			return present(userContext,originalVoucher, mergedAllTokens(tokensExpr));
			//return saveOriginalVoucher(userContext, originalVoucher, tokens().done());
		}

	}

	public OriginalVoucher updateOriginalVoucherProperty(RetailscmUserContext userContext,String originalVoucherId, int originalVoucherVersion, String property, String newValueExpr,String [] tokensExpr) throws Exception
	{
		checkParamsForUpdatingOriginalVoucher(userContext, originalVoucherId, originalVoucherVersion, property, newValueExpr, tokensExpr);

		OriginalVoucher originalVoucher = loadOriginalVoucher(userContext, originalVoucherId, allTokens());
		if(originalVoucher.getVersion() != originalVoucherVersion){
			String message = "The target version("+originalVoucher.getVersion()+") is not equals to version("+originalVoucherVersion+") provided";
			throwExceptionWithMessage(message);
		}
		synchronized(originalVoucher){
			//will be good when the originalVoucher loaded from this JVM process cache.
			//also good when there is a ram based DAO implementation
			//make changes to OriginalVoucher.

			originalVoucher.changeProperty(property, newValueExpr);

			originalVoucher = saveOriginalVoucher(userContext, originalVoucher, tokens().done());
			return present(userContext,originalVoucher, mergedAllTokens(tokensExpr));
			//return saveOriginalVoucher(userContext, originalVoucher, tokens().done());
		}

	}
	protected Map<String,Object> emptyOptions(){
		return tokens().done();
	}

	protected OriginalVoucherTokens tokens(){
		return OriginalVoucherTokens.start();
	}
	protected Map<String,Object> parseTokens(String [] tokensExpr){
		return tokens().initWithArray(tokensExpr);
	}
	protected Map<String,Object> allTokens(){
		return OriginalVoucherTokens.all();
	}
	protected Map<String,Object> viewTokens(){
		return tokens().allTokens()
		.analyzeAllLists().done();

	}
	protected Map<String,Object> mergedAllTokens(String []tokens){
		return OriginalVoucherTokens.mergeAll(tokens).done();
	}

	protected void checkParamsForTransferingAnotherBelongsTo(RetailscmUserContext userContext, String originalVoucherId, String anotherBelongsToId) throws Exception
 	{

 		checkerOf(userContext).checkIdOfOriginalVoucher(originalVoucherId);
 		checkerOf(userContext).checkIdOfAccountingDocument(anotherBelongsToId);//check for optional reference
 		checkerOf(userContext).throwExceptionIfHasErrors(OriginalVoucherManagerException.class);

 	}
 	public OriginalVoucher transferToAnotherBelongsTo(RetailscmUserContext userContext, String originalVoucherId, String anotherBelongsToId) throws Exception
 	{
 		checkParamsForTransferingAnotherBelongsTo(userContext, originalVoucherId,anotherBelongsToId);

		OriginalVoucher originalVoucher = loadOriginalVoucher(userContext, originalVoucherId, allTokens());
		synchronized(originalVoucher){
			//will be good when the originalVoucher loaded from this JVM process cache.
			//also good when there is a ram based DAO implementation
			AccountingDocument belongsTo = loadAccountingDocument(userContext, anotherBelongsToId, emptyOptions());
			originalVoucher.updateBelongsTo(belongsTo);
			originalVoucher = saveOriginalVoucher(userContext, originalVoucher, emptyOptions());

			return present(userContext,originalVoucher, allTokens());

		}

 	}

	public CandidateAccountingDocument requestCandidateBelongsTo(RetailscmUserContext userContext, String ownerClass, String id, String filterKey, int pageNo) throws Exception {

		CandidateAccountingDocument result = new CandidateAccountingDocument();
		result.setOwnerClass(ownerClass);
		result.setOwnerId(id);
		result.setFilterKey(filterKey==null?"":filterKey.trim());
		result.setPageNo(pageNo);
		result.setValueFieldName("id");
		result.setDisplayFieldName("name");

		pageNo = Math.max(1, pageNo);
		int pageSize = 20;
		//requestCandidateProductForSkuAsOwner
		SmartList<AccountingDocument> candidateList = accountingDocumentDaoOf(userContext).requestCandidateAccountingDocumentForOriginalVoucher(userContext,ownerClass, id, filterKey, pageNo, pageSize);
		result.setCandidates(candidateList);
		int totalCount = candidateList.getTotalCount();
		result.setTotalPage(Math.max(1, (totalCount + pageSize -1)/pageSize ));
		return result;
	}

 //--------------------------------------------------------------

 	protected AccountingDocument loadAccountingDocument(RetailscmUserContext userContext, String newBelongsToId, Map<String,Object> options) throws Exception
 	{

 		return accountingDocumentDaoOf(userContext).load(newBelongsToId, options);
 	}

	//--------------------------------------------------------------

	public void delete(RetailscmUserContext userContext, String originalVoucherId, int originalVoucherVersion) throws Exception {
		//deleteInternal(userContext, originalVoucherId, originalVoucherVersion);
	}
	protected void deleteInternal(RetailscmUserContext userContext,
			String originalVoucherId, int originalVoucherVersion) throws Exception{

		originalVoucherDaoOf(userContext).delete(originalVoucherId, originalVoucherVersion);
	}

	public OriginalVoucher forgetByAll(RetailscmUserContext userContext, String originalVoucherId, int originalVoucherVersion) throws Exception {
		return forgetByAllInternal(userContext, originalVoucherId, originalVoucherVersion);
	}
	protected OriginalVoucher forgetByAllInternal(RetailscmUserContext userContext,
			String originalVoucherId, int originalVoucherVersion) throws Exception{

		return originalVoucherDaoOf(userContext).disconnectFromAll(originalVoucherId, originalVoucherVersion);
	}

	public int deleteAll(RetailscmUserContext userContext, String secureCode) throws Exception
	{
		/*
		if(!("dElEtEaLl".equals(secureCode))){
			throw new OriginalVoucherManagerException("Your secure code is not right, please guess again");
		}
		return deleteAllInternal(userContext);
		*/
		return 0;
	}

	protected int deleteAllInternal(RetailscmUserContext userContext) throws Exception{
		return originalVoucherDaoOf(userContext).deleteAll();
	}

	public void onNewInstanceCreated(RetailscmUserContext userContext, OriginalVoucher newCreated) throws Exception{
		ensureRelationInGraph(userContext, newCreated);
		sendCreationEvent(userContext, newCreated);

	}

  public void sendAllItems(RetailscmUserContext ctx) throws Exception{
    originalVoucherDaoOf(ctx).loadAllAsStream().forEach(
          event -> sendInitEvent(ctx, event)
    );
  }

	// -----------------------------------//  登录部分处理 \\-----------------------------------
	// 手机号+短信验证码 登录
	public Object loginByMobile(RetailscmUserContextImpl userContext, String mobile, String verifyCode) throws Exception {
		LoginChannel loginChannel = LoginChannel.of(RetailscmBaseUtils.getRequestAppType(userContext), this.getBeanName(),
				"loginByMobile");
		LoginData loginData = new LoginData();
		loginData.setMobile(mobile);
		loginData.setVerifyCode(verifyCode);

		LoginContext loginContext = LoginContext.of(LoginMethod.MOBILE, loginChannel, loginData);
		return processLoginRequest(userContext, loginContext);
	}
	// 账号+密码登录
	public Object loginByPassword(RetailscmUserContextImpl userContext, String loginId, Password password) throws Exception {
		LoginChannel loginChannel = LoginChannel.of(RetailscmBaseUtils.getRequestAppType(userContext), this.getBeanName(), "loginByPassword");
		LoginData loginData = new LoginData();
		loginData.setLoginId(loginId);
		loginData.setPassword(password.getClearTextPassword());

		LoginContext loginContext = LoginContext.of(LoginMethod.PASSWORD, loginChannel, loginData);
		return processLoginRequest(userContext, loginContext);
	}
	// 微信小程序登录
	public Object loginByWechatMiniProgram(RetailscmUserContextImpl userContext, String code) throws Exception {
		LoginChannel loginChannel = LoginChannel.of(RetailscmBaseUtils.getRequestAppType(userContext), this.getBeanName(),
				"loginByWechatMiniProgram");
		LoginData loginData = new LoginData();
		loginData.setCode(code);

		LoginContext loginContext = LoginContext.of(LoginMethod.WECHAT_MINIPROGRAM, loginChannel, loginData);
		return processLoginRequest(userContext, loginContext);
	}
	// 企业微信小程序登录
	public Object loginByWechatWorkMiniProgram(RetailscmUserContextImpl userContext, String code) throws Exception {
		LoginChannel loginChannel = LoginChannel.of(RetailscmBaseUtils.getRequestAppType(userContext), this.getBeanName(),
				"loginByWechatWorkMiniProgram");
		LoginData loginData = new LoginData();
		loginData.setCode(code);

		LoginContext loginContext = LoginContext.of(LoginMethod.WECHAT_WORK_MINIPROGRAM, loginChannel, loginData);
		return processLoginRequest(userContext, loginContext);
	}
	// 调用登录处理
	protected Object processLoginRequest(RetailscmUserContextImpl userContext, LoginContext loginContext) throws Exception {
		IamService iamService = (IamService) userContext.getBean("iamService");
		LoginResult loginResult = iamService.doLogin(userContext, loginContext, this);
		// 根据登录结果
		if (!loginResult.isAuthenticated()) {
			throw new Exception(loginResult.getMessage());
		}
		if (loginResult.isSuccess()) {
			return onLoginSuccess(userContext, loginResult);
		}
		if (loginResult.isNewUser()) {
			throw new Exception("请联系你的上级,先为你创建账号,然后再来登录.");
		}
		return new LoginForm();
	}

	@Override
	public Object checkAccess(BaseUserContext baseUserContext, String methodName, Object[] parameters)
			throws IllegalAccessException {
		RetailscmUserContextImpl userContext = (RetailscmUserContextImpl)baseUserContext;
		IamService iamService = (IamService) userContext.getBean("iamService");
		Map<String, Object> loginInfo = iamService.getCachedLoginInfo(userContext);

		SecUser secUser = iamService.tryToLoadSecUser(userContext, loginInfo);
		UserApp userApp = iamService.tryToLoadUserApp(userContext, loginInfo);
		if (userApp != null) {
			userApp.setSecUser(secUser);
		}
		if (secUser == null) {
			iamService.onCheckAccessWhenAnonymousFound(userContext, loginInfo);
		}
		afterSecUserAppLoadedWhenCheckAccess(userContext, loginInfo, secUser, userApp);
		if (!isMethodNeedLogin(userContext, methodName, parameters)) {
			return accessOK();
		}

		return super.checkAccess(baseUserContext, methodName, parameters);
	}

	// 判断哪些接口需要登录后才能执行. 默认除了loginBy开头的,其他都要登录
	protected boolean isMethodNeedLogin(RetailscmUserContextImpl userContext, String methodName, Object[] parameters) {
		if (methodName.startsWith("loginBy")) {
			return false;
		}
		if (methodName.startsWith("logout")) {
			return false;
		}

		return true;
	}

	// 在checkAccess中加载了secUser和userApp后会调用此方法,用于定制化的用户数据加载. 默认什么也不做
	protected void afterSecUserAppLoadedWhenCheckAccess(RetailscmUserContextImpl userContext, Map<String, Object> loginInfo,
			SecUser secUser, UserApp userApp) throws IllegalAccessException{
	}

	protected Object onLoginSuccess(RetailscmUserContext userContext, LoginResult loginResult) throws Exception {
		// by default, return the view of this object
		UserApp userApp = loginResult.getLoginContext().getLoginTarget().getUserApp();
		return this.view(userContext, userApp.getObjectId());
	}

	public void onAuthenticationFailed(RetailscmUserContext userContext, LoginContext loginContext,
			LoginResult loginResult, IdentificationHandler idHandler, BusinessHandler bizHandler)
			throws Exception {
		// by default, failed is failed, nothing can do
	}
	// when user authenticated success, but no sec_user related, this maybe a new user login from 3-rd party service.
	public void onAuthenticateNewUserLogged(RetailscmUserContext userContext, LoginContext loginContext,
			LoginResult loginResult, IdentificationHandler idHandler, BusinessHandler bizHandler)
			throws Exception {
		// Generally speaking, when authenticated user logined, we will create a new account for him/her.
		// you need do it like :
		// First, you should create new data such as:
		//   OriginalVoucher newOriginalVoucher = this.createOriginalVoucher(userContext, ...
		// Next, create a sec-user in your business way:
		//   SecUser secUser = secUserManagerOf(userContext).createSecUser(userContext, login, mobile ...
		// And set it into loginContext:
		//   loginContext.getLoginTarget().setSecUser(secUser);
		// Next, create an user-app to connect secUser and newOriginalVoucher
		//   UserApp uerApp = userAppManagerOf(userContext).createUserApp(userContext, secUser.getId(), ...
		// Also, set it into loginContext:
		//   loginContext.getLoginTarget().setUserApp(userApp);
		// Since many of detailed info were depending business requirement, So,
		throw new Exception("请重载函数onAuthenticateNewUserLogged()以处理新用户登录");
	}
	public void onAuthenticateUserLogged(RetailscmUserContext userContext, LoginContext loginContext,
			LoginResult loginResult, IdentificationHandler idHandler, BusinessHandler bizHandler)
			throws Exception {
		// by default, find the correct user-app
		SecUser secUser = loginResult.getLoginContext().getLoginTarget().getSecUser();
		MultipleAccessKey key = new MultipleAccessKey();
		key.put(UserApp.SEC_USER_PROPERTY, secUser.getId());
		key.put(UserApp.OBJECT_TYPE_PROPERTY, OriginalVoucher.INTERNAL_TYPE);
		SmartList<UserApp> userApps = userContext.getDAOGroup().getUserAppDAO().findUserAppWithKey(key, EO);
		if (userApps == null || userApps.isEmpty()) {
			throw new Exception("您的账号未关联销售人员,请联系客服处理账号异常.");
		}
		UserApp userApp = userApps.first();
		userApp.setSecUser(secUser);
		loginResult.getLoginContext().getLoginTarget().setUserApp(userApp);
		BaseEntity app = userContext.getDAOGroup().loadBasicData(userApp.getObjectType(), userApp.getObjectId());
		((RetailscmBizUserContextImpl)userContext).setCurrentUserInfo(app);
	}
	// -----------------------------------\\  登录部分处理 //-----------------------------------

	// -----------------------------------// list-of-view 处理 \\-----------------------------------
    protected void enhanceForListOfView(RetailscmUserContext userContext,SmartList<OriginalVoucher> list) throws Exception {
    	if (list == null || list.isEmpty()){
    		return;
    	}
		List<AccountingDocument> belongsToList = RetailscmBaseUtils.collectReferencedObjectWithType(userContext, list, AccountingDocument.class);
		userContext.getDAOGroup().enhanceList(belongsToList, AccountingDocument.class);

    }

	public Object listByBelongsTo(RetailscmUserContext userContext,String belongsToId) throws Exception {
		return listPageByBelongsTo(userContext, belongsToId, 0, 20);
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Object listPageByBelongsTo(RetailscmUserContext userContext,String belongsToId, int start, int count) throws Exception {
		SmartList<OriginalVoucher> list = originalVoucherDaoOf(userContext).findOriginalVoucherByBelongsTo(belongsToId, start, count, new HashMap<>());
		enhanceForListOfView(userContext, list);
		RetailscmCommonListOfViewPage page = new RetailscmCommonListOfViewPage();
		page.setClassOfList(OriginalVoucher.class);
		page.setContainerObject(AccountingDocument.withId(belongsToId));
		page.setRequestBeanName(this.getBeanName());
		page.setDataList((SmartList)list);
		page.setPageTitle("原始凭证列表");
		page.setRequestName("listByBelongsTo");
		page.setRequestOffset(start);
		page.setRequestLimit(count);
		page.setDisplayMode("auto");
		page.setLinkToUrl(TextUtil.encodeUrl(String.format("%s/listByBelongsTo/%s/",  getBeanName(), belongsToId)));

		page.assemblerContent(userContext, "listByBelongsTo");
		return page.doRender(userContext);
	}

  // -----------------------------------\\ list-of-view 处理 //-----------------------------------v

 	/**
	 * miniprogram调用返回固定的detail class
	 *
	 * @return
	 * @throws Exception
	 */
 	public Object wxappview(RetailscmUserContext userContext, String originalVoucherId) throws Exception{
	  SerializeScope vscope = RetailscmViewScope.getInstance().getOriginalVoucherDetailScope().clone();
		OriginalVoucher merchantObj = (OriginalVoucher) this.view(userContext, originalVoucherId);
    String merchantObjId = originalVoucherId;
    String linkToUrl =	"originalVoucherManager/wxappview/" + merchantObjId + "/";
    String pageTitle = "原始凭证"+"详情";
		Map result = new HashMap();
		List propList = new ArrayList();
		List sections = new ArrayList();

		propList.add(
				MapUtil.put("id", "1-id")
				    .put("fieldName", "id")
				    .put("label", "ID")
				    .put("type", "text")
				    .put("linkToUrl", "")
				    .put("displayMode", "{}")
				    .into_map()
		);
		result.put("id", merchantObj.getId());

		propList.add(
				MapUtil.put("id", "2-title")
				    .put("fieldName", "title")
				    .put("label", "头衔")
				    .put("type", "text")
				    .put("linkToUrl", "")
				    .put("displayMode", "{}")
				    .into_map()
		);
		result.put("title", merchantObj.getTitle());

		propList.add(
				MapUtil.put("id", "3-madeBy")
				    .put("fieldName", "madeBy")
				    .put("label", "由")
				    .put("type", "text")
				    .put("linkToUrl", "")
				    .put("displayMode", "{}")
				    .into_map()
		);
		result.put("madeBy", merchantObj.getMadeBy());

		propList.add(
				MapUtil.put("id", "4-receivedBy")
				    .put("fieldName", "receivedBy")
				    .put("label", "受")
				    .put("type", "text")
				    .put("linkToUrl", "")
				    .put("displayMode", "{}")
				    .into_map()
		);
		result.put("receivedBy", merchantObj.getReceivedBy());

		propList.add(
				MapUtil.put("id", "5-voucherType")
				    .put("fieldName", "voucherType")
				    .put("label", "凭证类型")
				    .put("type", "text")
				    .put("linkToUrl", "")
				    .put("displayMode", "{}")
				    .into_map()
		);
		result.put("voucherType", merchantObj.getVoucherType());

		propList.add(
				MapUtil.put("id", "6-voucherImage")
				    .put("fieldName", "voucherImage")
				    .put("label", "凭证图像")
				    .put("type", "image")
				    .put("linkToUrl", "")
				    .put("displayMode", "{}")
				    .into_map()
		);
		result.put("voucherImage", merchantObj.getVoucherImage());

		propList.add(
				MapUtil.put("id", "7-belongsTo")
				    .put("fieldName", "belongsTo")
				    .put("label", "属于")
				    .put("type", "auto")
				    .put("linkToUrl", "accountingDocumentManager/wxappview/:id/")
				    .put("displayMode", "{\"brief\":\"accounting_document_date\",\"imageUrl\":\"\",\"name\":\"auto\",\"title\":\"name\",\"imageList\":\"\"}")
				    .into_map()
		);
		result.put("belongsTo", merchantObj.getBelongsTo());

		//处理 sectionList

		result.put("propList", propList);
		result.put("sectionList", sections);
		result.put("pageTitle", pageTitle);
		result.put("linkToUrl", linkToUrl);

		vscope.field("propList", SerializeScope.EXCLUDE())
				.field("sectionList", SerializeScope.EXCLUDE())
				.field("pageTitle", SerializeScope.EXCLUDE())
				.field("linkToUrl", SerializeScope.EXCLUDE());
		userContext.forceResponseXClassHeader("com.terapico.appview.DetailPage");
		return BaseViewPage.serialize(result, vscope);
	}

}

{'repo_name': 'doublechaintech/scm-biz-suite', 'stars': '1003', 'repo_language': 'Java', 'file_name': 'README.md', 'mime_type': 'text/plain', 'hash': -3969718060034666093, 'source_dataset': 'data'}


package cmd

import (
	"fmt"
	"strings"

	"github.com/aws-cloudformation/rain/cfn/parse"
	"github.com/aws-cloudformation/rain/cfn/value"
	"github.com/aws-cloudformation/rain/console/text"
	"github.com/spf13/cobra"
)

func formatMessages(m value.Interface) string {
	out := strings.Builder{}

	var path []interface{}

	if m.Comment() != "" {
		out.WriteString(fmt.Sprintf(" %s", text.Red(m.Comment())))
	}

	for _, node := range m.Nodes() {
		if node.Content.Comment() != "" {
			for i, part := range node.Path {
				if i >= len(path) || part != path[i] {
					out.WriteString("\n")

					out.WriteString(fmt.Sprintf("%s%s:",
						strings.Repeat("  ", i+1),
						text.Orange(fmt.Sprint(part)),
					))

					if i == len(node.Path)-1 {
						out.WriteString(fmt.Sprintf(" %s", text.Red(node.Content.Comment())))
					}
				}
			}
			path = node.Path
		}
	}

	return out.String()
}

var checkCmd = &cobra.Command{
	Use:                   "check <template file>",
	Short:                 "Validate a CloudFormation template against the spec",
	Long:                  "Reads the specified CloudFormation template and validates it against the current CloudFormation specification.",
	Args:                  cobra.ExactArgs(1),
	Annotations:           templateAnnotation,
	DisableFlagsInUseLine: true,
	Run: func(cmd *cobra.Command, args []string) {
		fn := args[0]

		t, err := parse.File(fn)
		if err != nil {
			panic(fmt.Errorf("Unable to parse template '%s': %s", fn, err))
		}

		out, ok := t.Check()

		messages := formatMessages(out)

		if ok {
			if len(messages) == 0 {
				fmt.Printf("%s: ok\n", fn)
			} else {
				fmt.Printf("%s: ok but with warnings%s", fn, messages)
			}
		} else {
			panic(fmt.Sprintf("%s: not ok%s", fn, messages))
		}
	},
}

func init() {
	Rain.AddCommand(checkCmd)
}

{'repo_name': 'aws-cloudformation/rain', 'stars': '158', 'repo_language': 'Go', 'file_name': 'main.go', 'mime_type': 'text/x-c', 'hash': -2575910983753207497, 'source_dataset': 'data'}


import {Boolean} from './Boolean'
import {Formats} from './_Internal'

/**
Change the format of a [[Boolean]]
@param B to transform
@returns `string | number | boolean`
@example
```ts
import {B} from 'ts-toolbelt'

type test0 = B.Format<B.True, 's'> // 'true'
type test1 = B.Format<B.True, 'b'> //  true
```
*/
export type Format<B extends Boolean, fmt extends Formats> = {
    'b': [ false,   true ][B] // 0:  false , 1:  true
    'n': B
    's': ['false', 'true'][B] // 0: 'false', 1: 'true'
}[fmt]

{'repo_name': 'millsp/ts-toolbelt', 'stars': '1489', 'repo_language': 'TypeScript', 'file_name': 'Class.ts', 'mime_type': 'text/x-c++', 'hash': -2770686783923735059, 'source_dataset': 'data'}


package models

import (
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
	"time"
)

type Post struct {
	ID        bson.ObjectId `bson:"_id,omitempty"`
	ShortID   int
	Title     string
	Subtitle  string
	Image     string
	Slug      string
	Body      string
	Category  string
	Tags      []string
	Published bool
	Timestamp time.Time
}

// sequential Id counter for posts
type Counter struct {
	ID   bson.ObjectId `bson:"_id,omitempty"`
	Name string
	Seq  int
}

func assertSequenceExists(collection *mgo.Collection) {
	c, _ := collection.Find(nil).Count()
	if c == 0 {
		collection.Insert(&Counter{
			Seq: 0})
	}
}

func GetNextSequence(database *mgo.Database) (count int) {
	collection := database.C("postCounter")
	assertSequenceExists(collection)
	change := mgo.Change{
		Update:    bson.M{"$inc": bson.M{"seq": 1}},
		ReturnNew: true,
	}
	result := Counter{}
	collection.Find(nil).Apply(change, &result)
	return result.Seq
}

{'repo_name': 'hermanschaaf/ironzebra', 'stars': '204', 'repo_language': 'CSS', 'file_name': 'jquery.expandable.js', 'mime_type': 'text/plain', 'hash': 581045015567412552, 'source_dataset': 'data'}


package magic.model.event;

import magic.model.MagicGame;
import magic.model.MagicLocationType;
import magic.model.MagicPermanent;
import magic.model.MagicPlayer;
import magic.model.MagicSource;
import magic.model.action.RemoveFromPlayAction;
import magic.model.choice.MagicTargetChoice;
import magic.model.target.MagicBounceTargetPicker;

public class MagicBounceChosenPermanentEvent extends MagicEvent {

    public MagicBounceChosenPermanentEvent(final MagicSource source, final MagicTargetChoice targetChoice) {
        this(source, source.getController(), targetChoice);
    }

    public MagicBounceChosenPermanentEvent(final MagicSource source, final MagicPlayer player, final MagicTargetChoice targetChoice) {
        super(
            source,
            player,
            targetChoice,
            MagicBounceTargetPicker.create(),
            EVENT_ACTION,
            "Return "+targetChoice.getTargetDescription()+"$ to its owner's hand."
        );
    }

    private static final MagicEventAction EVENT_ACTION = (final MagicGame game, final MagicEvent event) ->
        event.processTargetPermanent(game, (final MagicPermanent permanent) ->
            game.doAction(new RemoveFromPlayAction(
                permanent,
                MagicLocationType.OwnersHand
            ))
        );
}

{'repo_name': 'magarena/magarena', 'stars': '290', 'repo_language': 'Java', 'file_name': 'result.txt', 'mime_type': 'text/plain', 'hash': -1100638994209005307, 'source_dataset': 'data'}


// RUN: %clang_cc1 -fno-rtti -emit-llvm-only -triple i686-pc-win32 -fms-extensions -fdump-record-layouts -fsyntax-only %s 2>/dev/null \
// RUN:            | FileCheck %s
// RUN: %clang_cc1 -fno-rtti -emit-llvm-only -triple x86_64-pc-win32 -fms-extensions -fdump-record-layouts -fsyntax-only %s 2>/dev/null \
// RUN:            | FileCheck %s

struct EmptyIntMemb {
  int FlexArrayMemb[0];
};
// CHECK:       *** Dumping AST Record Layout
// CHECK-NEXT:  0 | struct EmptyIntMemb
// CHECK-NEXT:  0 | int [0] FlexArrayMemb
// CHECK-NEXT:    | [sizeof=4, align=4

struct EmptyLongLongMemb {
  long long FlexArrayMemb[0];
};
// CHECK: *** Dumping AST Record Layout
// CHECK-NEXT:  0 | struct EmptyLongLongMemb
// CHECK-NEXT:  0 | long long [0] FlexArrayMemb
// CHECK-NEXT:    | [sizeof=4, align=8

struct EmptyAligned2LongLongMemb {
  long long __declspec(align(2)) FlexArrayMemb[0];
};

// CHECK: *** Dumping AST Record Layout
// CHECK-NEXT:  0 | struct EmptyAligned2LongLongMemb
// CHECK-NEXT:  0 | long long [0] FlexArrayMemb
// CHECK-NEXT:    | [sizeof=4, align=8

struct EmptyAligned8LongLongMemb {
  long long __declspec(align(8)) FlexArrayMemb[0];
};

// CHECK: *** Dumping AST Record Layout
// CHECK-NEXT:  0 | struct EmptyAligned8LongLongMemb
// CHECK-NEXT:  0 | long long [0] FlexArrayMemb
// CHECK-NEXT:    | [sizeof=8, align=8

#pragma pack(1)
struct __declspec(align(4)) EmptyPackedAligned4LongLongMemb {
  long long FlexArrayMemb[0];
};
#pragma pack()

// CHECK: *** Dumping AST Record Layout
// CHECK-NEXT:  0 | struct EmptyPackedAligned4LongLongMemb
// CHECK-NEXT:  0 | long long [0] FlexArrayMemb
// CHECK-NEXT:    | [sizeof=4, align=4

#pragma pack(1)
struct EmptyPackedAligned8LongLongMemb {
  long long __declspec(align(8)) FlexArrayMemb[0];
};
#pragma pack()

// CHECK: *** Dumping AST Record Layout
// CHECK-NEXT:  0 | struct EmptyPackedAligned8LongLongMemb
// CHECK-NEXT:  0 | long long [0] FlexArrayMemb
// CHECK-NEXT:    | [sizeof=8, align=8

int a[
sizeof(struct EmptyIntMemb)+
sizeof(struct EmptyLongLongMemb)+
sizeof(struct EmptyAligned2LongLongMemb)+
sizeof(struct EmptyAligned8LongLongMemb)+
sizeof(struct EmptyPackedAligned4LongLongMemb)+
sizeof(struct EmptyPackedAligned8LongLongMemb)+
0];

{'repo_name': 'llvm-mirror/clang', 'stars': '2759', 'repo_language': 'C++', 'file_name': '__init__.py', 'mime_type': 'text/plain', 'hash': 4027664419443274249, 'source_dataset': 'data'}


import { VocabularyFilterType } from '@ulangi/ulangi-common/enums';

import { categoryDetailScreen } from '../screen-objects/CategoryDetailScreen';
import { createFirstSetScreen } from '../screen-objects/CreateFirstSetScreen';
import { lightBoxDialog } from '../screen-objects/LightBoxDialog';
import { manageScreen } from '../screen-objects/ManageScreen';
import { welcomeScreen } from '../screen-objects/WelcomeScreen';
import { addVocabularyScreen } from '../screen-objects/addVocabularyScreen';

describe('Delete vocabulary', (): void => {
  describe(`Test starts at ManageScreen after adding one vocabulary`, (): void => {
    beforeEach(
      async (): Promise<void> => {
        await welcomeScreen.tapYes();
        await createFirstSetScreen.selectLanguagesAndSubmit(
          'Japanese',
          'English'
        );
        await manageScreen.navigateToAddVocabularyScreen();
        await addVocabularyScreen.fillAndSaveTerm({
          vocabularyText: 'vocabulary 1',
          definitions: ['meaning 1'],
        });
        await lightBoxDialog.close();
      }
    );

    it('delete active vocabulary in manage screen', async (): Promise<void> => {
      await manageScreen.showVocabularyList();
      await manageScreen.deleteVocabulary('vocabulary 1');
      await manageScreen.expectVocabularyToNotExist('vocabulary 1');

      await manageScreen.openMenuAndSelectFilter(VocabularyFilterType.DELETED);
      await manageScreen.expectVocabularyToExist('vocabulary 1');
    });

    it('delete archived vocabulary in manage screen', async (): Promise<
      void
    > => {
      await manageScreen.showVocabularyList();
      await manageScreen.archiveVocabulary('vocabulary 1');
      await manageScreen.expectVocabularyToNotExist('vocabulary 1');

      await manageScreen.openMenuAndSelectFilter(VocabularyFilterType.ARCHIVED);
      await manageScreen.deleteVocabulary('vocabulary 1');
      await manageScreen.expectVocabularyToNotExist('vocabulary 1');

      await manageScreen.openMenuAndSelectFilter(VocabularyFilterType.DELETED);
      await manageScreen.expectVocabularyToExist('vocabulary 1');
    });

    it('delete active vocabulary in category detail screen', async (): Promise<
      void
    > => {
      await manageScreen.viewCategoryDetail('Uncategorized');
      await categoryDetailScreen.deleteVocabulary('vocabulary 1');
      await categoryDetailScreen.expectVocabularyToNotExist('vocabulary 1');
      await categoryDetailScreen.openMenuAndSelectFilter(
        VocabularyFilterType.DELETED
      );
      await categoryDetailScreen.expectVocabularyToExist('vocabulary 1');
    });

    it('delete archived vocabulary in category detail screen', async (): Promise<
      void
    > => {
      await manageScreen.showVocabularyList();
      await manageScreen.archiveVocabulary('vocabulary 1');
      await manageScreen.expectVocabularyToNotExist('vocabulary 1');

      await manageScreen.showCategoryList();
      await manageScreen.openMenuAndSelectFilter(VocabularyFilterType.ARCHIVED);
      await manageScreen.viewCategoryDetail('Uncategorized');

      await categoryDetailScreen.deleteVocabulary('vocabulary 1');
      await categoryDetailScreen.expectVocabularyToNotExist('vocabulary 1');
      await categoryDetailScreen.openMenuAndSelectFilter(
        VocabularyFilterType.DELETED
      );
      await categoryDetailScreen.expectVocabularyToExist('vocabulary 1');
    });
  });
});

{'repo_name': 'ulangi/ulangi', 'stars': '129', 'repo_language': 'TypeScript', 'file_name': 'set_up_dev_env.sh', 'mime_type': 'text/x-shellscript', 'hash': 6765375302560849338, 'source_dataset': 'data'}


package com.fincatto.documentofiscal.nfe310.classes;

public enum NFNotaInfoItemModalidadeBCICMS {

    MVA("0", "Margem de valor agregado"),
    PAUTA("1", "Pauta"),
    PRECO_TABELADO_MAXIMO("2", "Pre\u00e7o tabelado m\u00e1ximo"),
    VALOR_OPERACAO("3", "Valor da opera\u00e7\u00e3o");

    private final String codigo;
    private final String descricao;

    NFNotaInfoItemModalidadeBCICMS(final String codigo, final String descricao) {
        this.codigo = codigo;
        this.descricao = descricao;
    }

    public String getCodigo() {
        return this.codigo;
    }

    public String getDescricao() {
        return this.descricao;
    }

    public static NFNotaInfoItemModalidadeBCICMS valueOfCodigo(final String codigo) {
        for (final NFNotaInfoItemModalidadeBCICMS modalidade : NFNotaInfoItemModalidadeBCICMS.values()) {
            if (modalidade.getCodigo().equals(codigo)) {
                return modalidade;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        return codigo + " - " + descricao;
    }
}

{'repo_name': 'wmixvideo/nfe', 'stars': '472', 'repo_language': 'Java', 'file_name': 'stubs_webservice.txt', 'mime_type': 'text/plain', 'hash': 4956971104368263636, 'source_dataset': 'data'}


<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2015 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
-->

<resources>

    <style name="Theme.DesignDemo" parent="Base.Theme.DesignDemo">
    </style>

    <style name="Base.Theme.DesignDemo" parent="Theme.AppCompat.DayNight.NoActionBar">
        <item name="colorPrimary">#673AB7</item>
        <item name="colorPrimaryDark">#512DA8</item>
        <item name="colorAccent">#FF4081</item>
    </style>

    <style name="Widget.CardContent" parent="android:Widget">
        <item name="android:paddingLeft">16dp</item>
        <item name="android:paddingRight">16dp</item>
        <item name="android:paddingTop">24dp</item>
        <item name="android:paddingBottom">24dp</item>
        <item name="android:orientation">vertical</item>
    </style>

</resources>

{'repo_name': 'chrisbanes/cheesesquare', 'stars': '7785', 'repo_language': 'Java', 'file_name': 'CheeseListFragment.java', 'mime_type': 'text/x-java', 'hash': 8220720677999463665, 'source_dataset': 'data'}


<?php

namespace Victoire\Bundle\MediaBundle\Helper;

use Victoire\Bundle\MediaBundle\Entity\Media;
use Victoire\Bundle\MediaBundle\Helper\File\FileHandler;
use Victoire\Bundle\MediaBundle\Helper\Media\AbstractMediaHandler;

/**
 * MediaManager.
 */
class MediaManager
{
    /**
     * @var AbstractMediaHandler[]
     */
    protected $handlers = [];

    /**
     * @param AbstractMediaHandler $handler Media handler
     *
     * @return void
     */
    public function addHandler(AbstractMediaHandler $handler)
    {
        $this->handlers[$handler->getName()] = $handler;
    }

    /**
     * Returns handler to handle the Media item which can handle the item. If no handler is found, it returns FileHandler.
     *
     * @param Media $media
     *
     * @return AbstractMediaHandler
     */
    public function getHandler($media)
    {
        foreach ($this->handlers as $handler) {
            if ($handler->canHandle($media)) {
                return $handler;
            }
        }

        return new FileHandler();
    }

    /**
     * Returns handler to handle the Media item based on the Type. If no handler is found, it returns FileHandler.
     *
     * @param string $type
     *
     * @return AbstractMediaHandler
     */
    public function getHandlerForType($type)
    {
        foreach ($this->handlers as $handler) {
            if ($handler->getType() == $type) {
                return $handler;
            }
        }

        return new FileHandler();
    }

    /**
     * @return AbstractMediaHandler[]
     */
    public function getHandlers()
    {
        return $this->handlers;
    }

    /**
     * @param \Victoire\Bundle\MediaBundle\Entity\Media $media
     */
    public function prepareMedia(Media $media)
    {
        $handler = $this->getHandler($media);
        $handler->prepareMedia($media);
    }

    /**
     * @param Media $media The media
     * @param bool  $new   Is new
     */
    public function saveMedia(Media $media, $new = false)
    {
        $handler = $this->getHandler($media);

        if ($new) {
            $handler->saveMedia($media);
        } else {
            $handler->updateMedia($media);
        }
    }

    /**
     * @param \Victoire\Bundle\MediaBundle\Entity\Media $media
     */
    public function removeMedia(Media $media)
    {
        $handler = $this->getHandler($media);
        $handler->removeMedia($media);
    }

    /**
     * @param mixed $data
     *
     * @return Media
     */
    public function createNew($data)
    {
        foreach ($this->handlers as $handler) {
            $result = $handler->createNew($data);
            if ($result) {
                return $result;
            }
        }
    }

    /**
     * @return array
     */
    public function getFolderAddActions()
    {
        $result = [];
        foreach ($this->handlers as $handler) {
            $actions = $handler->getAddFolderActions();
            if ($actions) {
                $result = array_merge($actions, $result);
            }
        }

        return $result;
    }
}

{'repo_name': 'Victoire/victoire', 'stars': '226', 'repo_language': 'JavaScript', 'file_name': '_menu.html.twig', 'mime_type': 'text/plain', 'hash': 7536253041043381168, 'source_dataset': 'data'}


A new profiler for Ruby. With a GUI

{'repo_name': 'porter-io/tag-github', 'stars': '159', 'repo_language': 'None', 'file_name': '__meta__.json', 'mime_type': 'text/plain', 'hash': -2480265172147944077, 'source_dataset': 'data'}


[android-components](../../../index.md) / [mozilla.components.concept.engine](../../index.md) / [EngineSession](../index.md) / [SafeBrowsingPolicy](index.md) / [MALWARE](./-m-a-l-w-a-r-e.md)

# MALWARE

`MALWARE` [(source)](https://github.com/mozilla-mobile/android-components/blob/master/components/concept/engine/src/main/java/mozilla/components/concept/engine/EngineSession.kt#L156)

Blocks malware sites.

### Inherited Properties

| Name | Summary |
|---|---|
| [id](id.md) | `val id: `[`Int`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html) |

{'repo_name': 'mozilla-mobile/android-components', 'stars': '1393', 'repo_language': 'Kotlin', 'file_name': 'gradle-wrapper.properties', 'mime_type': 'text/plain', 'hash': -1158800693891874296, 'source_dataset': 'data'}


package t::lib::TestPod;
use Dancer2;

=head1 NAME

TestPod

=head2 ROUTES

=over

=cut

=item get "/in_testpod"

testpod

=cut

get '/in_testpod' => sub {

    # code;
};

=item get "/hello"

testpod

=cut

get '/hello' => sub {

    # code;
};

=item post '/in_testpod/*'

post in_testpod

=cut

post '/in_testpod/*' => sub {
    return 'post in_testpod';
};

=back

=head2 SPECIALS

=head3 PUBLIC

=over

=item get "/me:id"

=cut

get "/me:id" => sub {

    # code;
};

=back

=head3 PRIVAT

=over

=item post "/me:id"

post /me:id

=cut

post "/me:id" => sub {

    # code;
};

=back

=cut

1;

{'repo_name': 'PerlDancer/Dancer2', 'stars': '470', 'repo_language': 'Perl', 'file_name': 'dancer2', 'mime_type': 'text/x-perl', 'hash': -264564334725998966, 'source_dataset': 'data'}


/*
 *  The driver for the Cirrus Logic's Sound Fusion CS46XX based soundcards
 *  Copyright (c) by Jaroslav Kysela <perex@perex.cz>
 *
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 *
 */

#ifndef __CS46XX_LIB_H__
#define __CS46XX_LIB_H__

/*
 *  constants
 */

#define CS46XX_BA0_SIZE		  0x1000
#define CS46XX_BA1_DATA0_SIZE 0x3000
#define CS46XX_BA1_DATA1_SIZE 0x3800
#define CS46XX_BA1_PRG_SIZE	  0x7000
#define CS46XX_BA1_REG_SIZE	  0x0100

#ifdef CONFIG_SND_CS46XX_NEW_DSP
#define CS46XX_MIN_PERIOD_SIZE 64
#define CS46XX_MAX_PERIOD_SIZE 1024*1024
#else
#define CS46XX_MIN_PERIOD_SIZE 2048
#define CS46XX_MAX_PERIOD_SIZE 2048
#endif

#define CS46XX_FRAGS 2
/* #define CS46XX_BUFFER_SIZE CS46XX_MAX_PERIOD_SIZE * CS46XX_FRAGS */

#define SCB_NO_PARENT             0
#define SCB_ON_PARENT_NEXT_SCB    1
#define SCB_ON_PARENT_SUBLIST_SCB 2

/* 3*1024 parameter, 3.5*1024 sample, 2*3.5*1024 code */
#define BA1_DWORD_SIZE		(13 * 1024 + 512)
#define BA1_MEMORY_COUNT	3

/*
 *  common I/O routines
 */

static inline void snd_cs46xx_poke(struct snd_cs46xx *chip, unsigned long reg, unsigned int val)
{
	unsigned int bank = reg >> 16;
	unsigned int offset = reg & 0xffff;

	/*
	if (bank == 0)
		printk(KERN_DEBUG "snd_cs46xx_poke: %04X - %08X\n",
		       reg >> 2,val);
	*/
	writel(val, chip->region.idx[bank+1].remap_addr + offset);
}

static inline unsigned int snd_cs46xx_peek(struct snd_cs46xx *chip, unsigned long reg)
{
	unsigned int bank = reg >> 16;
	unsigned int offset = reg & 0xffff;
	return readl(chip->region.idx[bank+1].remap_addr + offset);
}

static inline void snd_cs46xx_pokeBA0(struct snd_cs46xx *chip, unsigned long offset, unsigned int val)
{
	writel(val, chip->region.name.ba0.remap_addr + offset);
}

static inline unsigned int snd_cs46xx_peekBA0(struct snd_cs46xx *chip, unsigned long offset)
{
	return readl(chip->region.name.ba0.remap_addr + offset);
}

struct dsp_spos_instance *cs46xx_dsp_spos_create (struct snd_cs46xx * chip);
void cs46xx_dsp_spos_destroy (struct snd_cs46xx * chip);
int cs46xx_dsp_load_module (struct snd_cs46xx * chip, struct dsp_module_desc * module);
#ifdef CONFIG_PM
int cs46xx_dsp_resume(struct snd_cs46xx * chip);
#endif
struct dsp_symbol_entry *cs46xx_dsp_lookup_symbol (struct snd_cs46xx * chip, char * symbol_name,
						   int symbol_type);
#ifdef CONFIG_PROC_FS
int cs46xx_dsp_proc_init (struct snd_card *card, struct snd_cs46xx *chip);
int cs46xx_dsp_proc_done (struct snd_cs46xx *chip);
#else
#define cs46xx_dsp_proc_init(card, chip)
#define cs46xx_dsp_proc_done(chip)
#endif
int cs46xx_dsp_scb_and_task_init (struct snd_cs46xx *chip);
int snd_cs46xx_download (struct snd_cs46xx *chip, u32 *src, unsigned long offset,
			 unsigned long len);
int snd_cs46xx_clear_BA1(struct snd_cs46xx *chip, unsigned long offset, unsigned long len);
int cs46xx_dsp_enable_spdif_out (struct snd_cs46xx *chip);
int cs46xx_dsp_enable_spdif_hw (struct snd_cs46xx *chip);
int cs46xx_dsp_disable_spdif_out (struct snd_cs46xx *chip);
int cs46xx_dsp_enable_spdif_in (struct snd_cs46xx *chip);
int cs46xx_dsp_disable_spdif_in (struct snd_cs46xx *chip);
int cs46xx_dsp_enable_pcm_capture (struct snd_cs46xx *chip);
int cs46xx_dsp_disable_pcm_capture (struct snd_cs46xx *chip);
int cs46xx_dsp_enable_adc_capture (struct snd_cs46xx *chip);
int cs46xx_dsp_disable_adc_capture (struct snd_cs46xx *chip);
int cs46xx_poke_via_dsp (struct snd_cs46xx *chip, u32 address, u32 data);
struct dsp_scb_descriptor * cs46xx_dsp_create_scb (struct snd_cs46xx *chip, char * name,
						   u32 * scb_data, u32 dest);
#ifdef CONFIG_PROC_FS
void cs46xx_dsp_proc_free_scb_desc (struct dsp_scb_descriptor * scb);
void cs46xx_dsp_proc_register_scb_desc (struct snd_cs46xx *chip,
					struct dsp_scb_descriptor * scb);
#else
#define cs46xx_dsp_proc_free_scb_desc(scb)
#define cs46xx_dsp_proc_register_scb_desc(chip, scb)
#endif
struct dsp_scb_descriptor * cs46xx_dsp_create_timing_master_scb (struct snd_cs46xx *chip);
struct dsp_scb_descriptor *
cs46xx_dsp_create_codec_out_scb(struct snd_cs46xx * chip,
				char * codec_name, u16 channel_disp, u16 fifo_addr,
				u16 child_scb_addr, u32 dest,
				struct dsp_scb_descriptor * parent_scb,
				int scb_child_type);
struct dsp_scb_descriptor *
cs46xx_dsp_create_codec_in_scb(struct snd_cs46xx * chip, char * codec_name,
			       u16 channel_disp, u16 fifo_addr,
			       u16 sample_buffer_addr, u32 dest,
			       struct dsp_scb_descriptor * parent_scb,
			       int scb_child_type);
void cs46xx_dsp_remove_scb (struct snd_cs46xx *chip,
			    struct dsp_scb_descriptor * scb);
struct dsp_scb_descriptor *
cs46xx_dsp_create_codec_in_scb(struct snd_cs46xx * chip, char * codec_name,
			       u16 channel_disp, u16 fifo_addr,
			       u16 sample_buffer_addr, u32 dest,
			       struct dsp_scb_descriptor * parent_scb,
			       int scb_child_type);
struct dsp_scb_descriptor *
cs46xx_dsp_create_src_task_scb(struct snd_cs46xx * chip, char * scb_name,
			       int sample_rate, u16 src_buffer_addr,
			       u16 src_delay_buffer_addr, u32 dest,
			       struct dsp_scb_descriptor * parent_scb,
			       int scb_child_type, int pass_through);
struct dsp_scb_descriptor *
cs46xx_dsp_create_mix_only_scb(struct snd_cs46xx * chip, char * scb_name,
			       u16 mix_buffer_addr, u32 dest,
			       struct dsp_scb_descriptor * parent_scb,
			       int scb_child_type);

struct dsp_scb_descriptor *
cs46xx_dsp_create_vari_decimate_scb(struct snd_cs46xx * chip, char * scb_name,
				    u16 vari_buffer_addr0, u16 vari_buffer_addr1, u32 dest,
				    struct dsp_scb_descriptor * parent_scb,
				    int scb_child_type);
struct dsp_scb_descriptor *
cs46xx_dsp_create_asynch_fg_rx_scb(struct snd_cs46xx * chip, char * scb_name,
				   u32 dest, u16 hfg_scb_address, u16 asynch_buffer_address,
				   struct dsp_scb_descriptor * parent_scb,
				   int scb_child_type);
struct dsp_scb_descriptor *
cs46xx_dsp_create_spio_write_scb(struct snd_cs46xx * chip, char * scb_name, u32 dest,
				 struct dsp_scb_descriptor * parent_scb,
				 int scb_child_type);
struct dsp_scb_descriptor *
cs46xx_dsp_create_mix_to_ostream_scb(struct snd_cs46xx * chip, char * scb_name,
				     u16 mix_buffer_addr, u16 writeback_spb, u32 dest,
				     struct dsp_scb_descriptor * parent_scb,
				     int scb_child_type);
struct dsp_scb_descriptor *
cs46xx_dsp_create_magic_snoop_scb(struct snd_cs46xx * chip, char * scb_name,
				  u32 dest, u16 snoop_buffer_address,
				  struct dsp_scb_descriptor * snoop_scb,
				  struct dsp_scb_descriptor * parent_scb,
				  int scb_child_type);
struct dsp_pcm_channel_descriptor *
cs46xx_dsp_create_pcm_channel (struct snd_cs46xx * chip, u32 sample_rate,
			       void * private_data, u32 hw_dma_addr,
			       int pcm_channel_id);
void cs46xx_dsp_destroy_pcm_channel (struct snd_cs46xx * chip,
				     struct dsp_pcm_channel_descriptor * pcm_channel);
int cs46xx_dsp_pcm_unlink (struct snd_cs46xx * chip,
			   struct dsp_pcm_channel_descriptor * pcm_channel);
int cs46xx_dsp_pcm_link (struct snd_cs46xx * chip,
			 struct dsp_pcm_channel_descriptor * pcm_channel);
struct dsp_scb_descriptor *
cs46xx_add_record_source (struct snd_cs46xx *chip, struct dsp_scb_descriptor * source,
			  u16 addr, char * scb_name);
int cs46xx_src_unlink(struct snd_cs46xx *chip, struct dsp_scb_descriptor * src);
int cs46xx_src_link(struct snd_cs46xx *chip, struct dsp_scb_descriptor * src);
int cs46xx_iec958_pre_open (struct snd_cs46xx *chip);
int cs46xx_iec958_post_close (struct snd_cs46xx *chip);
int cs46xx_dsp_pcm_channel_set_period (struct snd_cs46xx * chip,
				       struct dsp_pcm_channel_descriptor * pcm_channel,
				       int period_size);
int cs46xx_dsp_pcm_ostream_set_period (struct snd_cs46xx * chip, int period_size);
int cs46xx_dsp_set_dac_volume (struct snd_cs46xx * chip, u16 left, u16 right);
int cs46xx_dsp_set_iec958_volume (struct snd_cs46xx * chip, u16 left, u16 right);
#endif /* __CS46XX_LIB_H__ */

{'repo_name': 'comcat/miwifi', 'stars': '275', 'repo_language': 'C', 'file_name': 'keyring-type.h', 'mime_type': 'text/x-c', 'hash': 5454127928350120749, 'source_dataset': 'data'}


(set-logic QF_BV)
(set-option :produce-models true)
(declare-fun val1()  (_ BitVec 16))
(declare-fun val2()  (_ BitVec 16))
(declare-fun gen_mul()  (_ BitVec 16))
(assert (= val1 #xb621))
(assert (= val2 #xd620))
(assert (= gen_mul (bvmul val1 val2)))
(check-sat)
(get-value (val1))
(get-value (val2))
(get-value (gen_mul))
(exit)

{'repo_name': 'Boolector/boolector', 'stars': '136', 'repo_language': 'SMT', 'file_name': 'FindCryptoMiniSat.cmake', 'mime_type': 'text/plain', 'hash': -4668077260139646593, 'source_dataset': 'data'}


// @ts-check
import commonjs from '.';

/** @type {import("rollup").RollupOptions} */
const config = {
	input: 'main.js',
	output: {
		file: 'bundle.js',
		format: 'iife'
	},
	plugins: [
		commonjs({
			include: 'node_modules/**',
			exclude: [ 'node_modules/foo/**', 'node_modules/bar/**', /node_modules/ ],
			extensions: [ '.js', '.coffee' ],
			ignoreGlobal: false,
			sourceMap: false,
			namedExports: { './module.js': ['foo', 'bar' ] },
			ignore: [ 'conditional-runtime-dependency' ]
		})
	]
};

export default config;

{'repo_name': 'rollup/rollup-plugin-commonjs', 'stars': '474', 'repo_language': 'JavaScript', 'file_name': 'input.js', 'mime_type': 'text/plain', 'hash': -2646616510844925464, 'source_dataset': 'data'}


/*
*  Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*  WSO2 Inc. licenses this file to you under the Apache License,
*  Version 2.0 (the "License"); you may not use this file except
*  in compliance with the License.
*  You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.wso2.mb.integration.common.clients.operations.clients.utils;

import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.client.Stub;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.utils.CarbonUtils;

/**
 * This class is used to authenticate a web services so that it's stubs can be used.
 * @see AuthenticateStubUtil
 * for more other mehtods.
 */
public class AuthenticateStubUtil {

    /**
     * Info logger.
     */
    private static final Log log = LogFactory.getLog(AuthenticateStubUtil.class);

    /**
     * Stub authentication method
     *
     * @param stub          valid stub
     * @param sessionCookie session cookie
     */
    public static void authenticateStub(String sessionCookie, Stub stub) {
        long soTimeout = 5 * 60 * 1000; // Three minutes

        ServiceClient client = stub._getServiceClient();
        Options option = client.getOptions();
        option.setManageSession(true);
        option.setTimeOutInMilliSeconds(soTimeout);
        option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, sessionCookie);
        if (log.isDebugEnabled()) {
            log.debug("AuthenticateStub : Stub created with session " + sessionCookie);
        }
    }

    /**
     * Authenticate the given web service stub against the Product user manager. This
     * will make it possible to use the stub for invoking Product admin services.
     *
     * @param stub Axis2 service stub which needs to be authenticated
     */
    public static void authenticateStub(String userName, String password, Stub stub) {
        CarbonUtils.setBasicAccessSecurityHeaders(userName, password, stub._getServiceClient());
    }
}

{'repo_name': 'wso2/product-ei', 'stars': '252', 'repo_language': 'Java', 'file_name': 'ESBJAVA4569RabbiMQSSLStoreWithoutClientCertValidationTest.java', 'mime_type': 'text/x-java', 'hash': -5190738559507324828, 'source_dataset': 'data'}


(ns rssminer.test-common
  (:use [rssminer.routes :only [app]]
        [clojure.test :only [join-fixtures]]
        [clojure.java.shell :only [sh]]
        [clojure.data.json :only [json-str]]
        [clojure.java.jdbc :only [print-sql-exception-chain]]
        [rssminer.handlers.subscriptions :only [subscribe]]
        (rssminer [search :only [use-index-writer! searcher
                                 close-global-index-writer!]]
                  [util :only [user-id-from-session now-seconds]]
                  [parser :only [parse-feed]]
                  [redis :only [fetcher-enqueue set-redis-pool!
                                redis-pool fetcher-dequeue]]
                  [config :only [rssminer-conf]])
        (rssminer.db [user :only [create-user]]
                     [feed :only [save-feeds]])

        rssminer.classify)
  (:require [clojure.string :as str]
            [clojure.java.jdbc :as jdbc]
            [rssminer.database :as db])
  (:import java.io.File
           rssminer.Utils
           java.sql.SQLException
           [redis.clients.jedis JedisPool Jedis]))

(def user1 nil)
(def user2 nil)

(def test-user {:name "feng"
                :password "123456"
                :like_score 1.0
                :neutral_score 0
                :email "shenedu@gmail.com"})

(def test-user2 {:name "feng"
                 :password "123456"
                 :like_score 1.0
                 :neutral_score 0
                 :email "feng@gmail.com"})

(defn user-fixture [test-fn]
  (def user1 (create-user test-user))
  (def user2 (create-user test-user2))
  ;; (create-user {:name "test" :password "123456" :email "demo@rssminer.net"})
  (swap! rssminer-conf assoc
         :demo-user (first (db/mysql-query ["SELECT id, email, conf,
                 like_score, neutral_score FROM users WHERE email = 'demo@rssminer.net'"])))
  (test-fn))

(defn json-body [body]
  (java.io.ByteArrayInputStream. (.getBytes ^String (json-str body))))

(def auth-app
  (fn [& args]
    (binding [user-id-from-session (fn [req] (:id user1))]
      (apply (app) args))))

(def auth-app2
  (fn [& args]
    (binding [user-id-from-session (fn [req] (:id user2))]
      (apply (app) args))))

(defn mk-feeds-fixtrue [resource]
  (fn [test-fn]
    (let [sub (subscribe "http://link-to-scottgu.rss" (:id user1) nil nil)
          feeds (parse-feed (slurp resource))]
      (save-feeds feeds (:rss_link_id sub)))
    (.decRef (.openReader @searcher)) ; just refresh reader
    (test-fn)))

(defn lucene-fixture [test-fn]
  (use-index-writer! :path "RAM")
  (test-fn))

(defn- run-admin [cmd params]
  (apply sh (concat ["./scripts/admin"] params [cmd])))

(defn mysql-fixture [test-fn]
  (let [test-db-name "rssminer_test"
        test-user "feng_test"]
    (try
      (run-admin "init-db" ["-d" test-db-name "-u" test-user])
      (db/use-mysql-database! :url (str "jdbc:mysql://localhost/" test-db-name
                                        "?noAccessToProcedureBodies=true")
                              :user test-user
                              :password "")
      (test-fn)
      (catch SQLException e
        (print-sql-exception-chain e)
        (throw e))
      ;; (finally (run-admin "drop-db" ["-d" test-db-name]))
      )))

(defn redis-fixture [test-fn]
  (sh "redis-cli" "-n" 2  "flushdb")            ; just clean all
  (set-redis-pool! :database 2)
  (swap! rssminer-conf assoc :events-threshold (int 3))
  (test-fn))

(defn- wait-redis-key-present [key]
  (let [^JedisPool client @redis-pool
        ^Jedis j (.getResource client)]
    (try
      (loop [i 20]
        (when-not (.exists j key)
          (Thread/sleep i)
          (recur i)))
      (finally (.returnResource client j)))))

(defn feeds-score-fixture [test-fn]
  (start-classify-daemon!)
  (let [subid (:rss_link_id (subscribe "http://test-rss-ink"
                                       (:id user1) nil nil))
        feeds (update-in (parse-feed (slurp "test/atom.xml"))
                         [:entries]
                         (fn [entries]
                           (map (fn [f] (assoc f :published_ts (now-seconds)))
                                entries)))]
    ;; will add to lucene index
    (save-feeds feeds subid)
    (let [ids (map :id (db/mysql-query ["select id from feeds"]))]
      (doseq [id (take 8 ids)]
        (auth-app {:request-method :post
                   :uri (str "/api/feeds/" id "/vote")
                   :body (json-body {:vote (if (even? id) 1 -1)})})))
    (wait-redis-key-present (Utils/genKey (:id user1) subid)))
  (test-fn)
  (stop-classify-daemon!))

(defmacro mocking [var new-f & forms]
  `(let [old# (atom nil)]
     (try
       (alter-var-root ~var (fn [f#]
                              (reset! old# f#)
                              ~new-f))
       ~@forms
       (finally
         (alter-var-root ~var (fn [n#] @old#))))))

(defn redis-queue-fixture [test-fn]
  (mocking #'fetcher-enqueue (fn [& args])
           (mocking #'fetcher-dequeue (fn [& args])
                    (test-fn))))

(def app-fixture (join-fixtures [mysql-fixture
                                 user-fixture
                                 redis-fixture
                                 lucene-fixture
                                 redis-queue-fixture
                                 feeds-score-fixture]))

(def test-app (app))

{'repo_name': 'shenfeng/rssminer', 'stars': '150', 'repo_language': 'JavaScript', 'file_name': 'keyboard.js', 'mime_type': 'text/plain', 'hash': 5085323128729251475, 'source_dataset': 'data'}


<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../libc/enum.fpos64_t.html">

Redirecting to ../../../libc/enum.fpos64_t.html...

{'repo_name': 'rust-lang-ja/the-rust-programming-language-ja', 'stars': '349', 'repo_language': 'HTML', 'file_name': 'main.css', 'mime_type': 'text/plain', 'hash': 9130738980125800781, 'source_dataset': 'data'}


namespace Nancy.ViewEngines.SuperSimpleViewEngine
{
    /// <summary>
    /// Provides the view engine with utility functions for
    /// encoding, locating partial view templates etc.
    /// </summary>
    public interface IViewEngineHost
    {
        /// <summary>
        /// Context object of the host application.
        /// </summary>
        /// <value>An instance of the context object from the host.</value>
        object Context { get; }

        /// <summary>
        /// Html "safe" encode a string
        /// </summary>
        /// <param name="input">Input string</param>
        /// <returns>Encoded string</returns>
        string HtmlEncode(string input);

        /// <summary>
        /// Get the contents of a template
        /// </summary>
        /// <param name="templateName">Name/location of the template</param>
        /// <param name="model">Model to use to locate the template via conventions</param>
        /// <returns>Contents of the template, or null if not found</returns>
        string GetTemplate(string templateName, object model);

        /// <summary>
        /// Gets a uri string for a named route
        /// </summary>
        /// <param name="name">Named route name</param>
        /// <param name="parameters">Parameters to use to expand the uri string</param>
        /// <returns>Expanded uri string, or null if not found</returns>
        string GetUriString(string name, params string[] parameters);

        /// <summary>
        /// Expands a path to include any base paths
        /// </summary>
        /// <param name="path">Path to expand</param>
        /// <returns>Expanded path</returns>
        string ExpandPath(string path);

        /// <summary>
        /// Get the anti forgery token form element
        /// </summary>
        /// <returns>String containing the form element</returns>
        string AntiForgeryToken();
    }
}

{'repo_name': 'SonarSource/sonar-dotnet', 'stars': '411', 'repo_language': 'C#', 'file_name': 'Akka.TestKit.Xunit.csproj', 'mime_type': 'text/xml', 'hash': 6273419652298353310, 'source_dataset': 'data'}


using System.Threading.Tasks;
using Android.App;
using Android.Content.PM;
using Android.OS;
using MvvmCross.Forms.Platforms.Android.Views;

namespace StarWarsSample.Forms.Droid
{
    [Activity(
        Label = "StarWarsSample.Forms",
        MainLauncher = true,
        Icon = "@mipmap/icon",
        Theme = "@style/MainTheme.Splash",
        NoHistory = true,
        ScreenOrientation = ScreenOrientation.Portrait,
        ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class SplashScreen : MvxFormsSplashScreenActivity<Setup, Core.App, App>
    {
        public SplashScreen()
            : base(Resource.Layout.SplashScreen)
        {
        }

        protected override Task RunAppStartAsync(Bundle bundle)
        {
            StartActivity(typeof(RootActivity));
            return Task.CompletedTask;
        }
    }
}

{'repo_name': 'MvvmCross/MvvmCross-Samples', 'stars': '249', 'repo_language': 'C#', 'file_name': 'AssemblyInfo.cs', 'mime_type': 'text/plain', 'hash': -2608765481350840884, 'source_dataset': 'data'}