text:
class stratus {
        private:
                std::list<element> elements;
        public:
                std::list<element>::iterator add (element elem);
                void remove (std::list<element>::iterator elem);
                void modify (std::list<element>::iterator elem, element state);
                float evaluate (float base = 0);
};

redpajama_set_name: RedPajamaGithub


text:
package com.latitude.seventimer.ui.location;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.latitude.seventimer.R;
import com.latitude.seventimer.model.database.WeatherLocation;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * Created by cloud on 2019/7/6.
 */
public class LocationAdapter extends RecyclerView.Adapter<LocationAdapter.LocationViewHolder> {

    private List<WeatherLocation> mDatas;

    public LocationAdapter() {
    }

    public LocationAdapter(List<WeatherLocation> datas) {
        mDatas = datas;
    }

    @NonNull
    @Override
    public LocationViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout_location, viewGroup, false);
        return new LocationViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull LocationViewHolder locationViewHolder, int i) {
        WeatherLocation location = mDatas.get(i);
        locationViewHolder.temp.setText("30 ℃");
        locationViewHolder.title.setText(location.getAddress());

    }

    @Override
    public int getItemCount() {
        if (mDatas != null) {
            return mDatas.size();
        } else {
            return 0;
        }
    }

    public WeatherLocation getItem(int position) {
        if (mDatas != null && mDatas.size() > position) {
            return mDatas.get(position);
        }
        return null;
    }

    public void setData(List<WeatherLocation> datas) {
        if (mDatas == null) {
            mDatas = datas;
        } else {
            mDatas.clear();
            mDatas.addAll(datas);
        }
    }

    public void removeItem(int position) {
        if (mDatas != null && mDatas.size() > position && position > -1) {
            mDatas.remove(position);
        }
    }

    public static class LocationViewHolder extends RecyclerView.ViewHolder {
        TextView temp;
        TextView title;
        TextView subtitle;
        ImageView weather;

        public LocationViewHolder(@NonNull View itemView) {
            super(itemView);
            temp = itemView.findViewById(R.id.tv_temperature);
            title = itemView.findViewById(R.id.tv_title);
            subtitle = itemView.findViewById(R.id.tv_subtitle);
            weather = itemView.findViewById(R.id.iv_weather);
        }
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PathStringConverterTest.cs">
//     Copyright (c) 2017. All rights reserved. Licensed under the MIT license. See LICENSE file in
//     the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Spritely.Foundations.WebApi.Test
{
    using Microsoft.Owin;
    using Newtonsoft.Json;
    using NUnit.Framework;

    [TestFixture]
    public class PathStringConverterTest
    {
        [Test]
        public void JsonConvert_can_serialize_PathString_value()
        {
            var serialized = JsonConvert.SerializeObject(new PathString("/test"), new PathStringJsonConverter());

            Assert.That(serialized, Is.EqualTo(@"""/test"""));
        }

        [Test]
        public void JsonConvert_can_deserialize_PathString_value()
        {
            var deserialized = JsonConvert.DeserializeObject<PathString>(@"""/test""", new PathStringJsonConverter());

            Assert.That(deserialized, Is.EqualTo(new PathString("/test")));
        }
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.faetec.backingbeans;

import br.faetec.model.dao.CargoDAO;
import br.faetec.model.dto.CargoDTO;
import java.io.Serializable;
import java.util.Collection;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *Métodos para ações relativas ao cargo, get/set e strings para navegação.
@author Antonio Cassiano
 **/
public class CargoAction implements Serializable {

    private static final long serialVersionUID = 1L;
    private FacesContext context = FacesContext.getCurrentInstance();
    private HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
    private HttpSession session = request.getSession();

    /** Creates a new instance of UsuarioAction */
    public CargoAction() {
    }
    private CargoDTO cargoDTO;
    private Collection<CargoDTO> lista;

    public Collection<CargoDTO> getLista() {
        CargoDAO cargoDAO = new CargoDAO();
        lista = cargoDAO.listar();
        return lista;
    }

    public CargoDTO getCargoDTO() {
        if (cargoDTO == null) {
            cargoDTO = new CargoDTO();
        }
        return cargoDTO;
    }

    public void setCargoDTO(CargoDTO cargoDTO) {
        this.cargoDTO = cargoDTO;
    }

    /**
     *Instancia um cargoDAO e invoca o método listar().
    @author Antonio Cassiano
    @return String listar, para navegação.
     **/
    public String listar() {
        CargoDAO cargoDAO = new CargoDAO();
        lista = cargoDAO.listar();
        return "listar";
    }

    /**
     *Instancia um cargoDAO, obtem o idCargo  e invoca o método excluir
    @author Antonio Cassiano
    @return String listar, para navegação.
     **/
    public String excluir() {
        CargoDAO cargoDAO = new CargoDAO();
        getCargoDTO().setIdCargo(new Integer(request.getParameter("idCargo")));
        cargoDAO.excluir(getCargoDTO());
        return "listar";
    }

    /**
     *Set IdCargo com zero e permiti inserir novo registro na tabela cargo
    @author Antonio Cassiano
    @return String inserir, para navegação.
     **/
    public String inserir() {
        getCargoDTO().setIdCargo(0);
        return "inserir";
    }

    /**
     *Instancia um cargoDAO, invoca o método gravar, passando  o objeto CargoDTO
    @author Antonio Cassiano
    @return String listar, para navegação.
     **/
    public String gravar() {
        CargoDAO cargoDAO = new CargoDAO();
        cargoDAO.gravar(getCargoDTO());
        return "listar";
    }

    /**
     *Instancia um cargoDAO, obtem o idCargo e invoca o método selecionar, passando  o objeto CargoDTO
    @author Antonio Cassiano
    @return String inserir, para navegação.
     **/
    public String alterar() {
        CargoDAO cargoDAO = new CargoDAO();
        getCargoDTO().setIdCargo(new Integer(request.getParameter("idCargo")));
        setCargoDTO(cargoDAO.selecionar(getCargoDTO()));
        return "inserir";
    }

    /**
     *Controle de navegação para o menu
    @author Antonio Cassiano
    @return String menu, para navegação.
     **/
    public String menu() {
        return "menu";
    }
}


text:
<?php

namespace humhub\modules\tasks\components;

use Yii;
use humhub\modules\content\components\actions\ContentContainerStream;
use humhub\modules\tasks\models\Task;

class StreamAction extends ContentContainerStream
{

    /**
     * Setup additional filters
     */
    public function setupFilters()
    {
        $this->activeQuery->andWhere(['content.object_model' => Task::className()]);

        if (in_array('tasks_meAssigned', $this->filters) || in_array('tasks_open', $this->filters) || in_array('tasks_finished', $this->filters) || in_array('tasks_notassigned', $this->filters) || in_array('tasks_byme', $this->filters)) {

            $this->activeQuery->leftJoin('task', 'content.object_id=task.id AND content.object_model=:taskModel', [':taskModel' => Task::className()]);

            if (in_array('tasks_meAssigned', $this->filters)) {
                $this->activeQuery->leftJoin('task_user', 'task.id=task_user.task_id AND task_user.user_id=:userId', [':userId' => Yii::$app->user->id]);
                $this->activeQuery->andWhere('task_user.id IS NOT null');
            }

            if (in_array('tasks_notassigned', $this->filters)) {
                $this->activeQuery->andWhere("(SELECT COUNT(*) FROM task_user WHERE task_id=task.id) = 0");
            }

            if (in_array('tasks_byme', $this->filters)) {
                $this->activeQuery->andWhere(['task.created_by' => Yii::$app->user->id]);
            }

            if (in_array('tasks_open', $this->filters)) {
                $this->activeQuery->andWhere(['task.status' => Task::STATUS_OPEN]);
            }

            if (in_array('tasks_finished', $this->filters)) {
                $this->activeQuery->andWhere(['task.status' => Task::STATUS_FINISHED]);
            }
        }
    }

}

?>


text:
package org.apache.struts2.config_browser;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.validator.ActionValidatorManager;
import com.opensymphony.xwork2.validator.Validator;
import org.apache.struts2.util.ClassLoaderUtils;

import java.util.Collections;
import java.util.List;

/**
 * ListValidatorsAction loads the validations for a given class and context
 *
 */
public class ListValidatorsAction extends ActionSupport {

    private static final long serialVersionUID = 1L;

    private String clazz;
    private String context;
    List<Validator> validators = Collections.EMPTY_LIST;
    private ActionValidatorManager actionValidatorManager;

    @Inject
    public void setActionValidatorManager(ActionValidatorManager mgr) {
        this.actionValidatorManager = mgr;
    }

    public String getClazz() {
        return clazz;
    }

    public void setClazz(String clazz) {
        this.clazz = clazz;
    }

    public String stripPackage(Class clazz) {
        return clazz.getName().substring(clazz.getName().lastIndexOf('.') + 1);
    }

    public String stripPackage(String clazz) {
        return clazz.substring(clazz.lastIndexOf('.') + 1);
    }

    public String getContext() {
        return context;
    }

    public void setContext(String context) {
        this.context = context;
    }

    public List getValidators() {
        return validators;
    }

    public String execute() throws Exception {
        loadValidators();
        return super.execute();
    }

    protected void loadValidators() {
        Class value = getClassInstance();
        if ( value != null ) {
            validators = actionValidatorManager.getValidators(value, context);
        }
    }

    private Class getClassInstance() {
        try {
            return ClassLoaderUtils.loadClass(clazz, ActionContext.getContext().getClass());
        } catch (Exception e) {
            LOG.error("Class '" + clazz + "' not found...",e);
        }
        return null;
    }
}


text:
<?xml version="1.0"?>
<openerp>
    <data noupdate="1">

        <record model="mail.message" id="module_install_notification">
            <field name="model">mail.channel</field>
            <field name="res_id" ref="mail.channel_all_employees"/>
            <field name="message_type">notification</field>
            <field name="subtype_id" ref="mail.mt_comment"/>
            <field name="subject">Leave Management application installed!</field>
            <field name="body"><![CDATA[
Manage employee leaves from the top menu "Human Resources". Employees can create leave requests that are validated by their manager and/or HR officers.

Once validated, they are visible in the employee's calendar. HR officers can define leave types and allocate leaves to employees and employee categories.
]]></field>
        </record>

        <record model="hr.holidays.status" id="holiday_status_cl">
            <field name="name" eval="'Legal Leaves '+time.strftime('%Y')"/>
            <field name="limit" eval="False"/>
            <field name="color_name">black</field>
        </record>

        <record model="hr.holidays.status" id="holiday_status_sl">
            <field name="name">Sick Leaves</field>
            <field name="limit" eval="True"/>
            <field name="color_name">red</field>
        </record>

        <record model="hr.holidays.status" id="holiday_status_comp">
            <field name="name">Compensatory Days</field>
            <field name="limit" eval="False"/>
            <field name="color_name">lavender</field>
        </record>

        <record model="hr.holidays.status" id="holiday_status_unpaid">
            <field name="name">Unpaid</field>
            <field name="limit" eval="True"/>
            <field name="color_name">brown</field>
        </record>

        <record id="mt_holidays_confirmed" model="mail.message.subtype">
            <field name="name">Confirmed</field>
            <field name="res_model">hr.holidays</field>
            <field name="description">Request created and waiting confirmation</field>
        </record>
        <record id="mt_holidays_first_validated" model="mail.message.subtype">
            <field name="name">Waiting Second Validation</field>
            <field name="res_model">hr.holidays</field>
            <field name="default" eval="False"/>
            <field name="description">Request validated, waiting second validation</field>
        </record>
        <record id="mt_holidays_approved" model="mail.message.subtype">
            <field name="name">Approved</field>
            <field name="res_model">hr.holidays</field>
            <field name="description">Request approved</field>
        </record>
        <record id="mt_holidays_refused" model="mail.message.subtype">
            <field name="name">Refused</field>
            <field name="res_model">hr.holidays</field>
            <field name="default" eval="False"/>
            <field name="description">Request refused</field>
        </record>

        <record id="mt_department_holidays_confirmed" model="mail.message.subtype">
            <field name="name">Leaves/Allocations Confirmed</field>
            <field name="res_model">hr.department</field>
            <field name="default" eval="True"/>
            <field name="parent_id" eval="ref('mt_holidays_confirmed')"/>
            <field name="relation_field">department_id</field>
            <field name="sequence" eval="6"/>
        </record>
        <record id="mt_department_holidays_first_validated" model="mail.message.subtype">
            <field name="name">Leaves/Allocations First Approval</field>
            <field name="res_model">hr.department</field>
            <field name="default" eval="False"/>
            <field name="parent_id" eval="ref('mt_holidays_first_validated')"/>
            <field name="relation_field">department_id</field>
            <field name="sequence" eval="7"/>
        </record>
        <record id="mt_department_holidays_approved" model="mail.message.subtype">
            <field name="name">Leaves/Allocation Approved</field>
            <field name="res_model">hr.department</field>
            <field name="default" eval="False"/>
            <field name="parent_id" eval="ref('mt_holidays_approved')"/>
            <field name="relation_field">department_id</field>
            <field name="sequence" eval="8"/>
        </record>
        <record id="mt_department_holidays_refused" model="mail.message.subtype">
            <field name="name">Leaves/Allocation Refused</field>
            <field name="res_model">hr.department</field>
            <field name="default" eval="False"/>
            <field name="parent_id" eval="ref('mt_holidays_refused')"/>
            <field name="relation_field">department_id</field>
            <field name="sequence" eval="9"/>
        </record>

    </data>
</openerp>


text:
package com.juanco.chat.comm;

/**
 * @author Juan C. Orozco <juanco89@gmail.com>
 */
public interface ObservadorCom {

    public void conexionExitosa();

    public void nuevoMensajeRecibido(String msn);

    public void conexionTerminada();
}


text:
import { assert } from 'chai';
import mockPetition from '../mocks/petition';
import mockPetitionOwned from '../mocks/petitionOwned';
import mockUser from '../mocks/trustedUser';
import getTrustForm from 'selectors/trustForm';

describe('trustForm selector', () => {
  it('returns `petition` correctly', () => {
    const result = getTrustForm(mockPetition.data);
    const actual = result.petition;
    const expected = mockPetition.data;

    assert.deepEqual(actual, expected);
  });

  it('assigns me param to `me` key', () => {
    const result = getTrustForm(
      mockPetition.data,
      mockUser,
      {}
    );
    const actual = result.me;
    const expected = mockUser;

    assert.deepEqual(actual, expected);
  });

  context('with petition', () => {
    it('assigns me param as `user` to `initialValues` key', () => {
      const result = getTrustForm(
        mockPetition.data,
        mockUser,
        {}
      );
      const actual = result.initialValues.user;
      const expected = mockUser;

      assert.deepEqual(actual, expected);
    });

    it('assigns me param as `owner` to `initialValues` key', () => {
      const result = getTrustForm(
        mockPetition.data,
        mockUser,
        {}
      );
      const actual = result.initialValues.owner;
      const expected = mockUser;

      assert.deepEqual(actual, expected);
    });
  });

  context('with owned petition', () => {
    it('assigns me param as `user` to `initialValues` key', () => {
      const result = getTrustForm(
        mockPetitionOwned.data,
        mockUser,
        {}
      );
      const actual = result.initialValues.user;
      const expected = mockUser;

      assert.deepEqual(actual, expected);
    });

    it('assigns petition owner as `owner` to `initialValues` key', () => {
      const result = getTrustForm(
        mockPetitionOwned.data,
        mockUser,
        {}
      );
      const actual = result.initialValues.owner;
      const expected = mockPetitionOwned.data.owner;

      assert.deepEqual(actual, expected);
    });
  });

  context('`trustedFields` object', () => {
    const result = getTrustForm(
      mockPetition.data,
      mockUser,
      {}
    );

    it('exists', () => {
      const actual = typeof result.trustedFields;
      const expected = 'object';

      assert.deepEqual(actual, expected);
    });

    it('has `user.email` property', () => {
      const actual = result.trustedFields.hasOwnProperty('user.email');
      assert.isTrue(actual);
    });

    it('has `user.mobile` property', () => {
      const actual = result.trustedFields.hasOwnProperty('user.mobile');
      assert.isTrue(actual);
    });

    it('has `owner.email` property', () => {
      const actual = result.trustedFields.hasOwnProperty('owner.email');
      assert.isTrue(actual);
    });

    it('has `owner.mobile` property', () => {
      const actual = result.trustedFields.hasOwnProperty('owner.mobile');
      assert.isTrue(actual);
    });
  });
});


text:
from .constraint_foreign import ConstraintForeign
from .index_key import IndexKey
from .index_primary import IndexPrimary
from .index_unique import IndexUnique
from .type_character import TypeCharacter
from .type_datetime import TypeDateTime
from .type_decimal import TypeDecimal
from .type_enum import TypeEnum
from .type_numeric import TypeNumeric
from .type_plain import TypePlain
from .type_text import TypeText
from .table_option import TableOption
from .insert_values import InsertValues

__all__ = [
    "ConstraintForeign", "IndexKey", "IndexPrimary", "IndexUnique", "TypeCharacter", "TypeDecimal", "TypeDateTime",
    "TypeEnum", "TypeNumeric", "TypePlain", "TypeText", "TableOption", "InsertValues"
]


text:
package edu.usc.irds.sparkler.pipeline

import edu.usc.irds.sparkler.SparklerConfiguration

import java.util.concurrent.atomic.AtomicLong
import edu.usc.irds.sparkler.base.Loggable
import edu.usc.irds.sparkler.model._
import edu.usc.irds.sparkler.util.HealthChecks
import org.apache.commons.io.FilenameUtils
import org.apache.solr.common.SolrInputDocument
import org.apache.tika.mime.{MimeType, MimeTypes}

import java.io.{File, FileOutputStream}
import java.net.URI
import java.nio.file.Paths

/**
  * Created by thammegr on 6/7/16.
  */
class FairFetcher(val job: SparklerJob, val resources: Iterator[Resource], val delay: Long,
                  val fetchFunc: ((SparklerJob, Iterator[Resource]) => Iterator[FetchedData]),
                  val parseFunc: ((CrawlData) => (ParsedData)),
                  val outLinkFilterFunc: ((SparklerJob, CrawlData)  => (Set[String])),
                  val updateFunction: (CrawlData => Map[String, Object] ))
  extends Iterator[CrawlData] {

  import FairFetcher.LOG

  val hitCounter = new AtomicLong()
  var lastHit: String = ""
  val fetchedData: Iterator[FetchedData] = fetchFunc(job, resources)

  override def hasNext: Boolean = {
    if(!HealthChecks.checkFailureRate(job)) {
      fetchedData.hasNext
    } else{
      false
    }
  }

  def discoverMime(data: CrawlData): String ={
    val allTypes = MimeTypes.getDefaultMimeTypes
    var ctype : MimeType = null
    if(data.fetchedData.getContentType != null && data.fetchedData.getContentType != "") {
      ctype = allTypes.forName(data.fetchedData.getContentType)
    }
    if(ctype != null) {
      val ext = ctype.getExtension
      if (ext == null || ext == "") {
        var ext = FilenameUtils.getExtension(data.fetchedData.getResource.getUrl)
        if (ext.contains("#") || ext.contains("?")) {
          val splits = ext.split("[#?]")
          ext = splits(0)
        }
        ext = "." + ext
      }
      ext
    } else{
      ""
    }
  }

  def persistDocument(data: CrawlData, jobContext: SparklerConfiguration): Unit = {
    LOG.info("Persisting Document")
    try {
      if (jobContext.containsKey("fetcher.persist.content.location")) {

        val uri = new URI(data.fetchedData.getResource.getUrl)
        val domain = uri.getHost
        var outputFile: File = null
        if (jobContext.get("fetcher.persist.content.filename").toString == "hash") {
          val ext = discoverMime(data)
          if (data.fetchedData.getContenthash == null) {
            outputFile = Paths.get(jobContext.get("fetcher.persist.content.location").toString,
              data.fetchedData.getResource.getCrawlId, domain, data.fetchedData.getResource.getDedupeId + ext).toFile
          } else {
            outputFile = Paths.get(jobContext.get("fetcher.persist.content.location").toString,
              data.fetchedData.getResource.getCrawlId, domain, data.fetchedData.getContenthash + ext).toFile
          }
        }
        else {
          outputFile = Paths.get(jobContext.get("fetcher.persist.content.location").toString,
            data.fetchedData.getResource.getCrawlId, domain, FilenameUtils.getName(data.fetchedData.getResource.getUrl)).toFile
        }
        LOG.info("Creating directory: " + outputFile.toPath.getParent.toString)
        outputFile.toPath.getParent.toFile.mkdirs()
        try {
          LOG.info("Writing to: " + outputFile.toString)
          val outputStream = new FileOutputStream(outputFile)
          try outputStream.write(data.fetchedData.getContent)
          finally if (outputStream != null) outputStream.close()
        }
      }
    } catch {
      case e : Throwable => {
        println("Could not persist data to file system." + e.getMessage)
        println(e.getCause)
        println(e.printStackTrace())
      }
    }
  }

  override def next(): CrawlData = {
    val data = new CrawlData()

      val nextFetch = hitCounter.get() + delay
      val waitTime = nextFetch - System.currentTimeMillis()
      if (waitTime > 0) {
        LOG.debug("    Waiting for {} ms", waitTime)
        Thread.sleep(waitTime)
      }
      //STEP: Fetch
      val startTime = System.currentTimeMillis()
      data.fetchedData = fetchedData.next
      if(data.fetchedData != null) {
        val endTime = System.currentTimeMillis()
        data.fetchedData.getResource.setFetchTimestamp(data.fetchedData.getFetchedAt)
        data.fetchedData.setSegment(job.currentTask)
        lastHit = data.fetchedData.getResource.getUrl
        if (data.fetchedData.getResponseTime < 0) {
          data.fetchedData.setResponseTime(endTime - startTime)
        }
        hitCounter.set(System.currentTimeMillis())

        //STEP: Parse
        data.parsedData = parseFunc(data)

        if(data.parsedData != null){
          //STEP: URL Filter
          data.parsedData.outlinks = outLinkFilterFunc(job, data);
        } else{
          LOG.info("Empty parsed data for: " + data.fetchedData.getResource.getUrl)
        }

      } else{
        LOG.info("Empty fetched data")
      }
      persistDocument(data, job.getConfiguration)
      val doc = updateFunction(data)
      LOG.info("Adding doc to SOLR")
      job.getStorageFactory.getProxy.addResource(doc)
      data

  }
}

object FairFetcher extends Loggable {}
//=======
///*
// * Licensed to the Apache Software Foundation (ASF) under one or more
// * contributor license agreements.  See the NOTICE file distributed with
// * this work for additional information regarding copyright ownership.
// * The ASF 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 edu.usc.irds.sparkler.pipeline
//
//import java.util.concurrent.atomic.AtomicLong
//
//import edu.usc.irds.sparkler.base.Loggable
//import edu.usc.irds.sparkler.model._
//
///**
//  * Created by thammegr on 6/7/16.
//  */
//class FairFetcher(val job: SparklerJob, val resources: Iterator[Resource], val delay: Long,
//                  val fetchFunc: ((SparklerJob, Iterator[Resource]) => Iterator[FetchedData]),
//                  val parseFunc: ((CrawlData) => (ParsedData)),
//                  val outLinkFilterFunc: ((SparklerJob, CrawlData)  => (Set[String])),
//                  val updateFunction: (CrawlData => Map[String, Object] ))
//  extends Iterator[CrawlData] {
//
//  import FairFetcher.LOG
//
//  val hitCounter = new AtomicLong()
//  var lastHit: String = ""
//  val fetchedData: Iterator[FetchedData] = fetchFunc(job, resources)
//
//  override def hasNext: Boolean = fetchedData.hasNext
//
//  override def next(): CrawlData = {
//
//    val data = new CrawlData()
//    val nextFetch = hitCounter.get() + delay
//    val waitTime = nextFetch - System.currentTimeMillis()
//    if (waitTime > 0) {
//      LOG.debug("    Waiting for {} ms", waitTime)
//      Thread.sleep(waitTime)
//    }
//    //STEP: Fetch
//    val startTime = System.currentTimeMillis()
//    data.fetchedData = fetchedData.next
//    val endTime = System.currentTimeMillis()
//    data.fetchedData.getResource.setFetchTimestamp(data.fetchedData.getFetchedAt)
//    data.fetchedData.setSegment(job.currentTask)
//    lastHit = data.fetchedData.getResource.getUrl
//    if (data.fetchedData.getResponseTime < 0) {
//      data.fetchedData.setResponseTime(endTime - startTime)
//    }
//    hitCounter.set(System.currentTimeMillis())
//
//    //STEP: Parse
//    data.parsedData = parseFunc(data)
//
//    //STEP: URL Filter
//    data.parsedData.outlinks = outLinkFilterFunc(job, data)
//    val doc = updateFunction(data)
//    LOG.info("Adding doc to storage engine")
//    job.getStorageFactory().getProxy().addResource(doc)
//    data
//  }
//}
//
//object FairFetcher extends Loggable {}
//>>>>>>> master


text:
<?php

use \Mockery as m;
use LucaDegasperi\OAuth2Server\Proxies\AuthorizationServerProxy;

class AuthorizationServerProxyTest extends TestCase {

    public function getProxy($mock)
    {
        return new AuthorizationServerProxy($mock);
    }

    public function getServer()
    {
        return m::mock('League\OAuth2\Server\Authorization');
    }

    public function getStub()
    {
        return array(
            'client_id' => 1,
            'client_details' => 'foo',
            'redirect_uri' => 'http://www.example.com/',
            'response_type' => 'code',
            'scopes' => 'scope',
            'state' => '123456789',
        );
    }

    public function test_make_redirect()
    {
        $proxy = $this->getProxy($this->getServer());

        $result = $proxy->makeRedirect('example');

        $this->assertEquals('example?', $result);
    }

    public function test_make_redirect_with_code()
    {
        $proxy = $this->getProxy($this->getServer());

        $result = $proxy->makeRedirectWithCode('1234567890', array('redirect_uri' => 'example'));

        $this->assertEquals('example?code=1234567890&state=', $result);

        $result = $proxy->makeRedirectWithCode('1234567890', array('redirect_uri' => 'example', 'state' => 'random'));

        $this->assertEquals('example?code=1234567890&state=random', $result);
    }

    public function test_make_redirect_with_error()
    {
        $mock = $this->getServer();
        $mock->shouldReceive('getExceptionMessage')->twice()->andReturn('error_message');

        $proxy = $this->getProxy($mock);

        $result = $proxy->makeRedirectWithError(array('redirect_uri' => 'example'));

        $this->assertEquals('example?error=access_denied&error_message=error_message&state=', $result);

        $result = $proxy->makeRedirectWithError(array('redirect_uri' => 'example', 'state' => 'random'));

        $this->assertEquals('example?error=access_denied&error_message=error_message&state=random', $result);
    }

    public function test_check_authorize_params()
    {
        $mock = $this->getServer();
        $mock->shouldReceive('getGrantType->checkAuthoriseParams')->andReturn($this->getStub());

        $response = $this->getProxy($mock)->checkAuthorizeParams();

        $this->assertEquals($this->getStub(), $response);
    }

    public function test_new_authorize_request()
    {
        $mock = $this->getServer();
        $mock->shouldReceive('getGrantType->newAuthoriseRequest')->andReturn('example_code');

        $response = $this->getProxy($mock)->newAuthorizeRequest('user', 1, $this->getStub());

        $this->assertEquals('example_code', $response);
    }

    public function test_access_token_correctly_issued()
    {
        $mock = $this->getServer();
        $mock->shouldReceive('issueAccessToken')->once()->andReturn(array('foo' => 'bar'));

        $response = $this->getProxy($mock)->performAccessTokenFlow();

        $this->assertEquals('{"foo":"bar"}', $response->getContent());
        $this->assertTrue($response instanceof Illuminate\Http\JsonResponse);
        $this->assertTrue($response->isOk());
    }

    public function test_access_token_with_client_error()
    {
        $mock = $this->getServer();
        $mock->shouldReceive('issueAccessToken')->once()->andThrow(new League\OAuth2\Server\Exception\ClientException('client exception'));
        $mock->shouldReceive('getExceptionType')->twice()->andReturn('invalid_request');
        $mock->shouldReceive('getExceptionHttpHeaders')->once()->andReturn(array());

        $response = $this->getProxy($mock)->performAccessTokenFlow();

        $this->assertTrue($response instanceof Illuminate\Http\JsonResponse);
        $this->assertFalse($response->isOk());

    }

    public function test_access_token_with_generic_error()
    {
        $mock = $this->getServer();
        $mock->shouldReceive('issueAccessToken')->once()->andThrow(new Exception('internal server error'));

        $response = $this->getProxy($mock)->performAccessTokenFlow();

        $this->assertTrue($response instanceof Illuminate\Http\JsonResponse);
        $this->assertTrue($response->isServerError());

    }

    public function test_calls_to_underlying_object()
    {
        $mock = $this->getServer();
        $mock->shouldReceive('unexistingMethod')->times(6)->andReturn('baz');

        $proxy = $this->getProxy($mock);
        $responses = array();
        $responses[] = $proxy->unexistingMethod();
        $responses[] = $proxy->unexistingMethod('foo');
        $responses[] = $proxy->unexistingMethod('foo', 'bar');
        $responses[] = $proxy->unexistingMethod('foo', 'bar', 'foo');
        $responses[] = $proxy->unexistingMethod('foo', 'bar', 'foo', 'bar');
        $responses[] = $proxy->unexistingMethod('foo', 'bar', 'foo', 'bar', 'foo');

        for($i = 0; $i < count($responses); $i++)
        {
            $this->assertEquals('baz', $responses[$i]);
        }
    }

    public function tearDown() {
        m::close();
    }

}


text:
---
author: smspillaz
comments: true
date: 2016-05-27 02:03:46+00:00
layout: post
link: https://smspillaz.wordpress.com/2016/05/27/bringing-back-the-old-animations/
slug: bringing-back-the-old-animations
title: Bringing back the old animations
wordpress_id: 3438
---

One of the other casualties when we switched to using Modern OpenGL in Compiz was the loss of the older animation plugins, such as animationaddon, simple-animations, animationjc and animationsplus.

I took some time last weekend to make the necessary changes to bring them back to life and get them merged back into mainline.

One of the more interesting parts of all this was the polygon-based animations. You might remember this as the "glass shatter" or "explode" animations. Unlike most of the other code in Compiz plugins that did transformations on windows, the "polygon animation" mode actually completely took over window drawing. This meant that there was a lot more work to do in terms of getting them to work again.

## glDrawElements

Compiz has had (for a few years now) a class called GLVertexBuffer which encapsulates the entire process of setting up geometry and drawing it. If you want to draw something, the process is usually one of getting a handle for something called the "streaming buffer", resetting its state, adding whatever vertices, texture co-ordinates, attribute and uniform values you needed then calling its render method.

Under the hood, that would populate vertex buffer objects with all the data just before rendering and then call glDrawArrays to render it on screen using the defined vertex and pixel processing pipeline.

glDrawArrays can be cumbersome to work with though, especially with primitive types where you might end up having a lot of repeated vertex data. You have to repeat the components of each vertex for every single triangle that you want to specify.

glDrawElements on the other hand allows you to set up an array of vertices once, adding that array to the vertex buffer, then specifying a little bit later the order in which those vertices will be drawn. That means that if you were drawing some object in which triangles always had a point of (0, 0, 0), then you could just refer to that vertex as "1", so long as it was the second vertex in the vertex buffer. This is very handy when you have complex 3D geometry.

Quite understandably, animationaddon's polygon animation mode didn't use glDrawArrays but glDrawElements.

In order to support both OpenGL and GLES it was necessary add some sort of support for this in GLVertexBuffer, since the old code was using client side vertex and attribute arrays. The quickest way to do this was to just add some overloads to GLVertexBuffer's render method, so now as a user you can specify an array of indices to render. Its a little more OpenGL traffic, but it makes things a lot easier as a user.

## Re-tessellation

All the geometry for those 3D animations was rendered using the GL_POLYGON primitive type. Polygons are essentially untesselated concave shapes. GLES only supports triangles, triangle fans and triangle strips which threw a spanner in the words.

The polygon animation mode supported splitting windows into rectangles, hexagons and glass shards.

At first I was wondering how to convert between the two geometries, but it turns out that for concave shapes there's an easy way to split it up into triangles. Just take a reference point, then make a line from that reference point to each of its neighbours, bar its neighbours.

![path4156.png](https://smspillaz.files.wordpress.com/2016/05/path4156.png?w=364)

That can be represented with this simple function:

    namespace
    {
        enum class Winding : int
        {
        Clockwise = 0,
        Counterclockwise = 1
        };

        /* This function assumes that indices is large enough to
         * hold a polygon of nSides sides */
        unsigned int determineIndicesForPolygon (GLushort *indices,
                             GLushort nSides,
                             Winding direction)
        {
        unsigned int index = 0;
        bool front = direction == Winding::Counterclockwise;

        for (GLushort i = 2; i < nSides; ++i)
        {
            indices[index] = 0;
            indices[index + 1] = (front ? (i - 1) : i);
            indices[index + 2] = (front ? i : (i - 1));

            index += 3;
        }

        return index;
        }
    }

## Depth Buffer

We never really used the depth (or stencil buffers) particularly extensively in Compiz, even though the depth buffer is a common feature in most OpenGL applications.

The depth buffer is a straightforward solution to a hard problem - given a bunch of geometry, how do you draw it so that geometry which is closer to the camera is drawn on top of geometry that is further away?

For simple geometry, the answer is usually just to sort it by Z order and draw it back to front. For the vast majority of cases, compiz does just that. But this solution tends to break down once you have a lot of intersecting geometry. And those animations have a lot of intersecting geometry.

![Incorrect Depth Buffer.png](https://smspillaz.files.wordpress.com/2016/05/incorrect-depth-buffer.png)

Note in this image how the white borders around each piece are drawn on top of everything else?

The better alternative is to use the depth buffer. It isn't perfect and doesn't allow for transparency as between objects whilst the depth buffer is enabled, but it does handle the intersecting geometry case very well.

The way it works is to create an entirely separate framebuffer where each "pixel" is a single 24 bit floating point number. Compiz uses an implementation [where the other 8 bits are masked out and used for the stencil buffer](https://www.opengl.org/registry/specs/EXT/packed_depth_stencil.txt). Every time OpenGL is about to write a pixel to the framebuffer, it keeps track of how far away that pixel is in the scene. It does that during something called the "rasterisation stage". This is where a determination is made as to _where_ to draw pixels. That's done by interpolating between each vertex to reach a position and its relatively trivial to keep track of depth too by similar methods. Then, OpenGL compares the depth to the existing value at that position in the depth buffer. The usual depth test is GL_LESS - so the value in the depth buffer is updated and the framebuffer write is allowed.

The result is that parts of geometry which were already occluded are simply not drawn, where as geometry which occludes other previously-drawn geometry overwrites that geometry.

![Correct Depth Buffer.png](https://smspillaz.files.wordpress.com/2016/05/correct-depth-buffer.png)

I this image, you'll notice that each piece correctly overlaps each other piece, even if they are intersecting.

## Trying it out

The newly returned plugins should be back in the next Compiz release to hit Yakkety. They won't be installed or enabled by default, but you can install the  compiz-plugins package and compizconfig-settings-manager to get access to them.

If you're ever curious about how some of those effects work, taking the time to re-write them to work with the Modern OpenGL API is a great way to learn. In some cases it can take a lot of head-scratching and debugging, but the end result is always very pleasant and rewarding. There's still a few more to do, like _group, stackswitch_ and _bicubic_.


text:
export const description = `API Operation Tests for RenderPass StoreOp.
Tests a render pass with a resolveTarget resolves correctly for many combinations of:
  - number of color attachments, some with and some without a resolveTarget
  - renderPass storeOp set to {'store', 'discard'}
  - resolveTarget mip level {0, >0} (TODO?: different mip level from colorAttachment)
  - resolveTarget {2d array layer, TODO: 3d slice} {0, >0} with {2d, TODO: 3d} resolveTarget
    (TODO?: different z from colorAttachment)
  - TODO: test all renderable color formats
  - TODO: test that any not-resolved attachments are rendered to correctly.
  - TODO: test different loadOps
  - TODO?: resolveTarget mip level {0, >0} (TODO?: different mip level from colorAttachment)
  - TODO?: resolveTarget {2d array layer, TODO: 3d slice} {0, >0} with {2d, TODO: 3d} resolveTarget
    (different z from colorAttachment)
`;

import { makeTestGroup } from '../../../../common/framework/test_group.js';
import { GPUTest } from '../../../gpu_test.js';

const kSlotsToResolve = [
  [0, 2],
  [1, 3],
  [0, 1, 2, 3],
];

const kSize = 4;
const kFormat: GPUTextureFormat = 'rgba8unorm';

export const g = makeTestGroup(GPUTest);

g.test('render_pass_resolve')
  .params(u =>
    u
      .combine('storeOperation', ['discard', 'store'] as const)
      .beginSubcases()
      .combine('numColorAttachments', [2, 4] as const)
      .combine('slotsToResolve', kSlotsToResolve)
      .combine('resolveTargetBaseMipLevel', [0, 1] as const)
      .combine('resolveTargetBaseArrayLayer', [0, 1] as const)
  )
  .fn(t => {
    const targets: GPUColorTargetState[] = [];
    for (let i = 0; i < t.params.numColorAttachments; i++) {
      targets.push({ format: kFormat });
    }

    // These shaders will draw a white triangle into a texture. After draw, the top left
    // half of the texture will be white, and the bottom right half will be unchanged. When this
    // texture is resolved, there will be two distinct colors in each portion of the texture, as
    // well as a line between the portions that contain the midpoint color due to the multisample
    // resolve.
    const pipeline = t.device.createRenderPipeline({
      layout: 'auto',
      vertex: {
        module: t.device.createShaderModule({
          code: `
            @vertex fn main(
              @builtin(vertex_index) VertexIndex : u32
              ) -> @builtin(position) vec4<f32> {
              var pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>(
                  vec2<f32>(-1.0, -1.0),
                  vec2<f32>(-1.0,  1.0),
                  vec2<f32>( 1.0,  1.0));
              return vec4<f32>(pos[VertexIndex], 0.0, 1.0);
            }`,
        }),
        entryPoint: 'main',
      },
      fragment: {
        module: t.device.createShaderModule({
          code: `
            struct Output {
              @location(0) fragColor0 : vec4<f32>,
              @location(1) fragColor1 : vec4<f32>,
              @location(2) fragColor2 : vec4<f32>,
              @location(3) fragColor3 : vec4<f32>,
            };

            @fragment fn main() -> Output {
              return Output(
                vec4<f32>(1.0, 1.0, 1.0, 1.0),
                vec4<f32>(1.0, 1.0, 1.0, 1.0),
                vec4<f32>(1.0, 1.0, 1.0, 1.0),
                vec4<f32>(1.0, 1.0, 1.0, 1.0)
              );
            }`,
        }),
        entryPoint: 'main',
        targets,
      },
      primitive: { topology: 'triangle-list' },
      multisample: { count: 4 },
    });

    const resolveTargets: GPUTexture[] = [];
    const renderPassColorAttachments: GPURenderPassColorAttachment[] = [];

    // The resolve target must be the same size as the color attachment. If we're resolving to mip
    // level 1, the resolve target base mip level should be 2x the color attachment size.
    const kResolveTargetSize = kSize << t.params.resolveTargetBaseMipLevel;

    for (let i = 0; i < t.params.numColorAttachments; i++) {
      const colorAttachment = t.device.createTexture({
        format: kFormat,
        size: { width: kSize, height: kSize, depthOrArrayLayers: 1 },
        sampleCount: 4,
        mipLevelCount: 1,
        usage:
          GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC | GPUTextureUsage.RENDER_ATTACHMENT,
      });

      if (t.params.slotsToResolve.includes(i)) {
        const colorAttachment = t.device.createTexture({
          format: kFormat,
          size: { width: kSize, height: kSize, depthOrArrayLayers: 1 },
          sampleCount: 4,
          mipLevelCount: 1,
          usage:
            GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC | GPUTextureUsage.RENDER_ATTACHMENT,
        });

        const resolveTarget = t.device.createTexture({
          format: kFormat,
          size: {
            width: kResolveTargetSize,
            height: kResolveTargetSize,
            depthOrArrayLayers: t.params.resolveTargetBaseArrayLayer + 1,
          },
          sampleCount: 1,
          mipLevelCount: t.params.resolveTargetBaseMipLevel + 1,
          usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.RENDER_ATTACHMENT,
        });

        // Clear to black for the load operation. After the draw, the top left half of the attachment
        // will be white and the bottom right half will be black.
        renderPassColorAttachments.push({
          view: colorAttachment.createView(),
          clearValue: { r: 0.0, g: 0.0, b: 0.0, a: 0.0 },
          loadOp: 'clear',
          storeOp: t.params.storeOperation,
          resolveTarget: resolveTarget.createView({
            baseMipLevel: t.params.resolveTargetBaseMipLevel,
            baseArrayLayer: t.params.resolveTargetBaseArrayLayer,
          }),
        });

        resolveTargets.push(resolveTarget);
      } else {
        renderPassColorAttachments.push({
          view: colorAttachment.createView(),
          clearValue: { r: 0.0, g: 0.0, b: 0.0, a: 0.0 },
          loadOp: 'clear',
          storeOp: t.params.storeOperation,
        });
      }
    }

    const encoder = t.device.createCommandEncoder();

    const pass = encoder.beginRenderPass({
      colorAttachments: renderPassColorAttachments,
    });
    pass.setPipeline(pipeline);
    pass.draw(3);
    pass.end();
    t.device.queue.submit([encoder.finish()]);

    // Verify the resolve targets contain the correct values.
    for (const resolveTarget of resolveTargets) {
      // Test top left pixel, which should be {255, 255, 255, 255}.
      t.expectSinglePixelIn2DTexture(
        resolveTarget,
        kFormat,
        { x: 0, y: 0 },
        {
          exp: new Uint8Array([0xff, 0xff, 0xff, 0xff]),
          slice: t.params.resolveTargetBaseArrayLayer,
          layout: { mipLevel: t.params.resolveTargetBaseMipLevel },
        }
      );

      // Test bottom right pixel, which should be {0, 0, 0, 0}.
      t.expectSinglePixelIn2DTexture(
        resolveTarget,
        kFormat,
        { x: kSize - 1, y: kSize - 1 },
        {
          exp: new Uint8Array([0x00, 0x00, 0x00, 0x00]),
          slice: t.params.resolveTargetBaseArrayLayer,
          layout: { mipLevel: t.params.resolveTargetBaseMipLevel },
        }
      );

      // Test top right pixel, which should be {127, 127, 127, 127} due to the multisampled resolve.
      t.expectSinglePixelBetweenTwoValuesIn2DTexture(
        resolveTarget,
        kFormat,
        { x: kSize - 1, y: 0 },
        {
          exp: [new Uint8Array([0x7f, 0x7f, 0x7f, 0x7f]), new Uint8Array([0x80, 0x80, 0x80, 0x80])],
          slice: t.params.resolveTargetBaseArrayLayer,
          layout: { mipLevel: t.params.resolveTargetBaseMipLevel },
        }
      );
    }
  });


text:
package com.all.shared.model;

import javax.persistence.Entity;
import javax.persistence.Id;

import com.all.shared.AllConstants;

@Entity
public class UltrapeerNode implements Comparable<UltrapeerNode> {

	@Id
	private String address;
	private int succesfulConnections;
	private int unsuccesfulConnections;

	public UltrapeerNode() {
	}

	public UltrapeerNode(String address) {
		this.address = address;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public void incrementSuccesfulConnections() {
		succesfulConnections++;
	}

	public void incrementUnsuccesfulConnections() {
		unsuccesfulConnections++;
	}

	public int getPort() {
		return AllConstants.ULTRAPEER_PORT;
	}

	@Override
	public int compareTo(UltrapeerNode o) {
		return Integer.valueOf(getConnectionBalance()).compareTo(Integer.valueOf(o.getConnectionBalance()));
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		}
		if (obj instanceof UltrapeerNode) {
			UltrapeerNode other = (UltrapeerNode) obj;
			if (address != null) {
				return address.equals(other.address);
			}
		}
		return false;
	}

	@Override
	public int hashCode() {
		if (address != null) {
			return 13 * address.hashCode();
		}
		return super.hashCode();
	}

	private int getConnectionBalance() {
		return succesfulConnections - unsuccesfulConnections;
	}

	@Override
	public String toString() {
		return "Ultrapeer=" + address + ":" + getPort();
	}

	public int getSc() {
		return succesfulConnections;
	}

	public void setSc(int succesfulConnections) {
		this.succesfulConnections = succesfulConnections;
	}

	public int getUc() {
		return unsuccesfulConnections;
	}

	public void setUc(int unsuccesfulConnections) {
		this.unsuccesfulConnections = unsuccesfulConnections;
	}

}


text: angular-templaminator


text:
Lorem Ipsum is simply dummy text of the printing and typesetting industry

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.

								1 month ago

							1

							1

@brendname

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.

								2 months ago

							1

							1

@brendname

Reader will be distracted by the readable content of a page when looking at its layout.

								2 months ago

							1

							1

Contrary to popular belief

There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form.

								3 months ago

							1


text:
import pytest
import numpy as np
import nnabla.functions as F
from nbla_test_utils import list_context

ctxs = list_context('ATanh')

@pytest.mark.parametrize("ctx, func_name", ctxs)
@pytest.mark.parametrize("seed", [313])
def test_atanh_forward_backward(seed, ctx, func_name):
    from nbla_test_utils import function_tester
    rng = np.random.RandomState(seed)
    inputs = [np.clip(rng.randn(2, 3, 4).astype(np.float32) * 0.3, -0.9, 0.9)]
    function_tester(rng, F.atanh, np.arctanh, inputs, ctx=ctx, func_name=func_name,
                    atol_f=1e-3, atol_b=1e-2)

@pytest.mark.parametrize("ctx, func_name", ctxs)
@pytest.mark.parametrize("seed", [313])
def test_atanh_double_backward(seed, ctx, func_name):
    from nbla_test_utils import cap_ignore_region, backward_function_tester
    rng = np.random.RandomState(seed)
    inputs = [np.clip(rng.randn(2, 3, 4).astype(np.float32) * 0.3, -0.9, 0.9)]
    backward_function_tester(rng, F.atanh,
                             inputs=inputs,
                             func_args=[], func_kwargs={},
                             atol_accum=3e-1,
                             dstep=1e-3,
                             ctx=ctx)


text:
package cn.net.normcore.iorder.api.app;

import cn.net.normcore.iorder.common.SimpleResult;
import cn.net.normcore.iorder.filter.ValidateToken;
import cn.net.normcore.iorder.service.promotion.PromotionService;
import cn.net.normcore.iorder.vo.promotion.PromotionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Map;

/**
 * 推广信息相关接口
 * Created by 81062 on 2017/3/19.
 */
@Controller
@Path("/app/promotion")
@Produces(MediaType.APPLICATION_JSON)
@ValidateToken
public class PromotionApi {
    @Autowired
    private PromotionService promotionService;

    /**
     * 获取所有推广信息
     *
     * @return
     */
    @GET
    public Map<String, Object> promotion() {
        Map<String, Object> result = SimpleResult.optimistic();
        result.put("promotions", PromotionVo.listFromPromotions(promotionService.findAll()));
        return result;
    }
}


text:
import Ember from 'ember';
import UploadQueue from '../system/upload-queue';
import flatten from '../system/flatten';

var get = Ember.get;
var set = Ember.set;
var computed = Ember.computed;

export default Ember.Service.extend({

  /**
    @private
    Setup a map of uploaders so they may be
    accessed by name via the `find` method.
   */
  init() {
    set(this, 'queues', Ember.Map.create());
    set(this, 'all', Ember.A());
  },

  files: computed('all.@each.length', {
    get() {
      return flatten(get(this, 'all').invoke('toArray'));
    }
  }),

  size: computed('all.@each.size', {
    get() {
      return Ember.A(get(this, 'all').getEach('size')).reduce(function (E, x) {
        return E + x;
      }, 0);
    }
  }),

  loaded: computed('all.@each.loaded', {
    get() {
      return Ember.A(get(this, 'all').getEach('loaded')).reduce(function (E, x) {
        return E + x;
      }, 0);
    }
  }),

  progress: Ember.computed('size', 'loaded', function () {
    let percent = get(this, 'loaded') / get(this, 'size') || 0;
    return Math.floor(percent * 100);
  }),

  /**
    Return or instantiate a new plupload instance
    for an upload queue.

    @method find
    @param {String} name The name of the queue to find
    @param {Object} [config] The configuration to use for the uploader
   */
  findOrCreate(name, component, config) {
    var queue;

    if (get(this, 'queues').has(name)) {
      queue = get(this, 'queues').get(name);
      if (config != null) {
        set(queue, 'target', component);
        queue.configure(config);
      }
    } else {
      queue = UploadQueue.create({
        name: name,
        target: component
      });
      get(this, 'all').push(queue);
      get(this, 'queues').set(name, queue);
      queue.configure(config);
    }
    return queue;
  }
});


text:
package net.genesishub.gFeatures.Feature.GenesisAccess;

import net.genesishub.gFeatures.Configuration.Config;

public class ConfigHub {
	Config config = new Config();
	public void setupConfig(){
		config.createDirectory("plugins/gFeatures/GenesisAccess", "GenesisAccess plugin directory set!");
	}
}


text:
This theme is forked from [Bootstrap2](https://github.com/getpelican/pelican-themes/tree/master/bootstrap2) theme.

It makes use of [Font-Awesome](http://fortawesome.github.com/Font-Awesome/) icons, supports tag_cloud, translation,
and try to keep other features from Pelican's default theme `notmyidea`.

Here's preview

![bootstrap2 dark theme](screenshot.png)

Feel free to use it.


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m150622_192202_create_status_table extends Migration
{
    public function up()
    {
        $this->createTable('status', [
                'id' => 'pk',
                'message' => 'string NOT NULL',
                'permissions' => 'int NOT NULL DEFAULT 0',
                'created_at' => 'int NOT NULL',
                'updated_at' => 'int NOT NULL'
            ]
        );

    }

    public function down()
    {
        $this->dropTable('status');

        return false;
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}


text:
extern void g(int);
void f(int i, void (*fptr)(int)) {
  if(!fptr)
    fptr = g;

  fptr(i);
}
// FIXME: Also need a test for non-fptr vals
// Test function pointers via phi nodes in a loop


text:
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "config.h"
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <inttypes.h>

#ifndef NDEBUG
#include <signal.h>
#endif

#include "cache.h"

#ifndef NDEBUG
const uint64_t redzone_pattern = 0xdeadbeefcafebabe;
int cache_error = 0;
#endif

const int initial_pool_size = 64;

static bool inFreeList(cache_t *cache, void *object) {
    bool rv = false;
    size_t i;
    for (i = 0; i < cache->freecurr; i++) {
        rv |= cache->ptr[i] == object;
    }
    return rv;
}

cache_t* cache_create(const char *name, size_t bufsize, size_t align,
                      cache_constructor_t* constructor,
                      cache_destructor_t* destructor) {
    cache_t* ret = calloc(1, sizeof(cache_t));
    char* nm = strdup(name);
    void** ptr = calloc(initial_pool_size, sizeof(void*));
    if (ret == NULL || nm == NULL || ptr == NULL) {
        free(ret);
        free(nm);
        free(ptr);
        return NULL;
    }

    cb_mutex_initialize(&ret->mutex);
    ret->name = nm;
    ret->ptr = ptr;
    ret->freetotal = initial_pool_size;
    ret->constructor = constructor;
    ret->destructor = destructor;

#ifndef NDEBUG
    ret->bufsize = bufsize + 2 * sizeof(redzone_pattern);
#else
    ret->bufsize = bufsize;
#endif

    return ret;
}

static void* get_object(void *ptr) {
#ifndef NDEBUG
    uint64_t *pre = ptr;
    return pre + 1;
#else
    return ptr;
#endif
}

void cache_destroy(cache_t *cache) {
    while (cache->freecurr > 0) {
        void *ptr = cache->ptr[--cache->freecurr];
        if (cache->destructor) {
            cache->destructor(get_object(ptr), NULL);
        }
        free(ptr);
    }
    free(cache->name);
    free(cache->ptr);
    cb_mutex_destroy(&cache->mutex);
    free(cache);
}

void* cache_alloc(cache_t *cache) {
    void *ret;
    void *object;
    cb_mutex_enter(&cache->mutex);
    if (cache->freecurr > 0) {
        ret = cache->ptr[--cache->freecurr];
        object = get_object(ret);
        cb_assert(!inFreeList(cache, ret));
    } else {
        object = ret = malloc(cache->bufsize);
        if (ret != NULL) {
            object = get_object(ret);

            if (cache->constructor != NULL &&
                cache->constructor(object, NULL, 0) != 0) {
                free(ret);
                object = NULL;
            }
        }
    }
    cb_mutex_exit(&cache->mutex);

#ifndef NDEBUG
    if (object != NULL) {
        /* add a simple form of buffer-check */
        uint64_t *pre = ret;
        *pre = redzone_pattern;
        ret = pre+1;
        memcpy(((char*)ret) + cache->bufsize - (2 * sizeof(redzone_pattern)),
               &redzone_pattern, sizeof(redzone_pattern));
    }
#endif

    return object;
}

void cache_free(cache_t *cache, void *object) {
    void *ptr = object;
#ifndef NDEBUG
    uint64_t *pre = ptr;
#endif

    cb_mutex_enter(&cache->mutex);

#ifndef NDEBUG
    /* validate redzone... */
    if (memcmp(((char*)ptr) + cache->bufsize - (2 * sizeof(redzone_pattern)),
               &redzone_pattern, sizeof(redzone_pattern)) != 0) {
        raise(SIGABRT);
        cache_error = 1;
        cb_mutex_exit(&cache->mutex);
        return;
    }
    --pre;
    if (*pre != redzone_pattern) {
        raise(SIGABRT);
        cache_error = -1;
        cb_mutex_exit(&cache->mutex);
        return;
    }
    ptr = pre;
#endif
    cb_assert(!inFreeList(cache, ptr));
    if (cache->freecurr < cache->freetotal) {
        cache->ptr[cache->freecurr++] = ptr;
        cb_assert(inFreeList(cache, ptr));
    } else {
        /* try to enlarge free connections array */
        size_t newtotal = cache->freetotal * 2;
        void **new_free;
        cb_assert(newtotal > 0);
        new_free = realloc(cache->ptr, sizeof(void *) * newtotal);
        if (new_free) {
            cache->freetotal = newtotal;
            cache->ptr = new_free;
            cache->ptr[cache->freecurr++] = ptr;
            cb_assert(inFreeList(cache, ptr));
        } else {
            if (cache->destructor) {
                cache->destructor(ptr, NULL);
            }
            free(ptr);
            cb_assert(!inFreeList(cache, ptr));
        }
    }
    cb_mutex_exit(&cache->mutex);
}


text:
<?php
namespace CodeIgniter\Language;

use Config\Services;
use Tests\Support\Language\MockLanguage;
use Tests\Support\Language\SecondMockLanguage;

class LanguageTest extends \CIUnitTestCase
{

	public function testReturnsStringWithNoFileInMessage()
	{
		$lang = new MockLanguage('en');

		$this->assertEquals('something', $lang->getLine('something'));
	}

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

	public function testGetLineReturnsLine()
	{
		$lang = new MockLanguage('en');

		$lang->setData('books', [
			'bookSaved'  => 'We kept the book free from the boogeyman',
			'booksSaved' => 'We saved some more',
		]);

		$this->assertEquals('We saved some more', $lang->getLine('books.booksSaved'));
	}

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

	public function testGetLineReturnsFallbackLine()
	{
		$lang = new MockLanguage('en-US');
		$lang->setData('equivalent', [
			'touchWood'   => 'touch wood',
			'lieOfLand'   => 'lie of the land',
			'leaseOfLife' => 'a new lease of life',
			'slowcoach'   => 'slowcoach',
		], 'en');
		$lang->setData('equivalent', [
			'lieOfLand' => 'lay of the land',
			'slowcoach' => 'slowpoke',
		], 'en-US');

		$this->assertEquals(
				'lay of the land', $lang->getLine('equivalent.lieOfLand')
		);
		$this->assertEquals(
				'slowpoke', $lang->getLine('equivalent.slowcoach')
		);
		$this->assertEquals(
				'a new lease of life', $lang->getLine('equivalent.leaseOfLife')
		);
		$this->assertEquals(
				'touch wood', $lang->getLine('equivalent.touchWood')
		);
		$this->assertEquals(
				'equivalent.unknown', $lang->getLine('equivalent.unknown')
		);
	}

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

	public function testGetLineArrayReturnsLineArray()
	{
		$lang = new MockLanguage('en');

		$lang->setData('books', [
			'booksList' => [
				'The Boogeyman',
				'We Saved',
			],
		]);

		$this->assertEquals([
			'The Boogeyman',
			'We Saved',
		], $lang->getLine('books.booksList'));
	}

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

	public function testGetLineFormatsMessage()
	{
		// No intl extension? then we can't test this - go away....
		if (! class_exists('\MessageFormatter'))
		{
			return;
		}

		$lang = new MockLanguage('en');

		$lang->setData('books', [
			'bookCount' => '{0, number, integer} books have been saved.',
		]);

		$this->assertEquals('45 books have been saved.', $lang->getLine('books.bookCount', [91 / 2]));
	}

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

	public function testGetLineArrayFormatsMessages()
	{
		// No intl extension? Then we can't test this - go away...
		if (! class_exists('\MessageFormatter'))
		{
			return;
		}

		$lang = new MockLanguage('en');

		$lang->setData('books', [
			'bookList' => [
				'{0, number, integer} related books.'
			],
		]);

		$this->assertEquals(['45 related books.'], $lang->getLine('books.bookList', [91 / 2]));
	}

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

	/**
	 * @see https://github.com/codeigniter4/CodeIgniter4/issues/891
	 */
	public function testLangAllowsOtherLocales()
	{
		$str1 = lang('Language.languageGetLineInvalidArgumentException', [], 'en');
		$str2 = lang('Language.languageGetLineInvalidArgumentException', [], 'ru');

		$this->assertEquals('Get line must be a string or array of strings.', $str1);
		$this->assertEquals('Whatever this would be, translated', $str2);
	}

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

	public function testLangDoesntFormat()
	{
		$lang = new MockLanguage('en');
		$lang->disableIntlSupport();

		$lang->setData('books', [
			'bookList' => [
				'{0, number, integer} related books.'
			],
		]);

		$this->assertEquals(['{0, number, integer} related books.'], $lang->getLine('books.bookList', [15]));
	}

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

	public function testLanguageDuplicateKey()
	{
		$lang = new Language('en', false);
		$this->assertEquals('These are not the droids you are looking for', $lang->getLine('More.strongForce', []));
		$this->assertEquals('I have a very bad feeling about this', $lang->getLine('More.cannotMove', []));
		$this->assertEquals('Could not move file {0} to {1} ({2})', $lang->getLine('Files.cannotMove', []));
		$this->assertEquals('I have a very bad feeling about this', $lang->getLine('More.cannotMove', []));
	}

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

	public function testLanguageFileLoading()
	{
		$lang = new SecondMockLanguage('en');

		$result = $lang->loadem('More', 'en');
		$this->assertTrue(in_array('More', $lang->loaded()));
		$result = $lang->loadem('More', 'en');
		$this->assertEquals(1, count($lang->loaded())); // should only be there once
	}

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

	public function testLanguageFileLoadingReturns()
	{
		$lang = new SecondMockLanguage('en');

		$result = $lang->loadem('More', 'en', true);
		$this->assertFalse(in_array('More', $lang->loaded()));
		$this->assertEquals(3, count($result));
		$result = $lang->loadem('More', 'en');
		$this->assertTrue(in_array('More', $lang->loaded()));
		$this->assertEquals(1, count($lang->loaded()));
	}

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

	public function testLanguageSameKeyAndFileName()
	{
		$lang = new MockLanguage('en');

		// first file data | example.message
		$lang->setData('example', ['message' => 'This is an example message']);

		// force loading data into file Example
		$this->assertEquals('This is an example message', $lang->getLine('example.message'));

		// second file data | another.example
		$lang->setData('another', ['example' => 'Another example']);

		$this->assertEquals('Another example', $lang->getLine('another.example'));
	}

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

	public function testGetLocale()
	{
		$language = Services::language('en', false);
		$this->assertEquals('en', $language->getLocale());
	}

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

	public function testPrioritizedLocator()
	{
		$language = Services::language('en', false);
		// this should load the replacement bundle of messages
		$message = lang('Core.missingExtension', [], 'en');
		$this->assertEquals('{0} extension could not be found.', $message);
		// and we should have our new message too
		$this->assertEquals('billions and billions', lang('Core.bazillion', [], 'en'));
	}

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

	public function MessageBundles()
	{
		return [
			['CLI'],
			['Cache'],
			['Cast'],
			['Core'],
			['Database'],
			['Files'],
			['Filters'],
			['Format'],
			['HTTP'],
			['Images'],
			['Language'],
			['Log'],
			['Migrations'],
			['Number'],
			['Pager'],
			['Router'],
			['Session'],
			['Time'],
			['Validation'],
			['View'],
		];
	}

	/**
	 * There's not a whole lot that can be done with message bundles,
	 * but we can at least try loading them ... more accurate code coverage?
	 *
	 * @dataProvider MessageBundles
	 */
	public function testBundleUniqueKeys($bundle)
	{
		$language = Services::language('en', false);
		$messages = require SYSTEMPATH . 'Language/en/' . $bundle . '.php';
		$this->assertGreaterThan(0, count($messages));
	}

	//--------------------------------------------------------------------
	// Testing base locale vs variants

	public function testBaseFallbacks()
	{
		$language = Services::language('en-ZZ', false);
		// key is in both base and variant; should pick variant
		$this->assertEquals("It's made of cheese", $language->getLine('More.notaMoon'));

		// key is in base but not variant; should pick base
		$this->assertEquals('I have a very bad feeling about this', $language->getLine('More.cannotMove'));

		// key is in variant but not base; should pick variant
		$this->assertEquals('There is no try', $language->getLine('More.wisdom'));

		// key isn't in either base or variant; should return bad key
		$this->assertEquals('More.shootMe', $language->getLine('More.shootMe'));
	}

	//--------------------------------------------------------------------
	/**
	 * Testing base locale vs variants, with fallback to English.
	 *
	 * Key	en	ab	ac-CD
	 * none	N	N	N
	 * one	N	N	Y
	 * two	N	Y	N
	 * tre	N	Y	Y
	 * for	Y	N	N
	 * fiv	Y	N	Y
	 * six	Y	Y	N
	 * sev	Y	Y	Y
	 */
	public function testAllTheWayFallbacks()
	{
		$language = Services::language('ab-CD', false);
		$this->assertEquals('Allin.none', $language->getLine('Allin.none'));
		$this->assertEquals('Pyramid of Giza', $language->getLine('Allin.one'));
		$this->assertEquals('gluttony', $language->getLine('Allin.two'));
		$this->assertEquals('Colossus of Rhodes', $language->getLine('Allin.tre'));
		$this->assertEquals('four calling birds', $language->getLine('Allin.for'));
		$this->assertEquals('Temple of Artemis', $language->getLine('Allin.fiv'));
		$this->assertEquals('envy', $language->getLine('Allin.six'));
		$this->assertEquals('Hanging Gardens of Babylon', $language->getLine('Allin.sev'));
	}

}


text:
namespace ArachNGIN.Files.FileFormats
{
    /// <summary>
    ///     PAK File Allocation Table
    /// </summary>
    internal struct PakFat
    {
        /// <summary>
        ///     The file length
        /// </summary>
        public int FileLength;

        /// <summary>
        ///     The file name
        /// </summary>
        public string FileName;

        /// <summary>
        ///     The starting offset of a file
        /// </summary>
        public int FileStart;
    }
}


text:
Choose on table you want to use and add conditions:

**PHP code:**

```
// Chooses rows where id=5
$entity = $db["table"]->id(5);
```

After specifiing all conditions call `set($array)` to send data to database

```
// Print number of changed rows
echo($db["article"]->id(5)->set(["title" => "New title"]));
```


text:
@implementation User

@dynamic timestamp;
@dynamic primary;
@dynamic events;

+ (User *)primaryUserInContext:(NSManagedObjectContext *)context {
	User *user = nil;
	NSManagedObjectModel *model = [AppDelegate appDelegate].managedObjectModel;

	NSFetchRequest *fetchRequest = [[model fetchRequestTemplateForName:@"primaryUser"] copy];

	NSError *error;
	NSArray *results = [context executeFetchRequest:fetchRequest error:&error];
	if (results && [results count] > 0) {
		user = [results objectAtIndex:0];
	}
	return user;
}

+ (User *)insertedNewUserInManagedObjectContext:(NSManagedObjectContext *)context {
	return [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([User class]) inManagedObjectContext:context];
}

- (User *)userInContext:(NSManagedObjectContext *)context {
	if (context == self.managedObjectContext) {
		return self;
	}
	else {
		return (User *)[context objectWithID:[self objectID]];
	}
}

@end


text:
"use strict"

const fs   = require("fs")
const path = require("path")

const tempfile         = require("tempfile")
const BrowserWindow    = require("browser-window")
const throttleDebounce = require("throttle-debounce")

const pkg      = require("../package.json")
const menus    = require("./menus")
const utils    = require("./utils")
const markdown = require("./markdown")

//------------------------------------------------------------------------------
exports.createViewer               = createViewer
exports.hasViewers                 = hasViewers
exports.getViewers                 = getViewers
exports.getFocusedViewer           = getFocusedViewer
exports.getViewerFromBrowserWindow = getViewerFromBrowserWindow

//------------------------------------------------------------------------------
const ViewersOpen = new Map()

//------------------------------------------------------------------------------
function createViewer(fileName, options) {
  const fullFileName = getFullFileName(fileName)

  if (ViewersOpen.has(fullFileName)) {
    return ViewersOpen.get(fullFileName)
  }

  return new Viewer(fileName, options)
}

//------------------------------------------------------------------------------
function hasViewers() {
  return ViewersOpen.size != 0
}

//------------------------------------------------------------------------------
function getViewers() {
  return utils.ita(ViewersOpen.values())
}

//------------------------------------------------------------------------------
function getFocusedViewer() {
  const browserWindow = BrowserWindow.getFocusedWindow()
  if (!browserWindow) return null

  return getViewerFromBrowserWindow(browserWindow)
}

//------------------------------------------------------------------------------
function getViewerFromBrowserWindow(browserWindow) {
  return browserWindow.mdViewer
}

//------------------------------------------------------------------------------
class Viewer {

  //----------------------------------------------------------------------------
  constructor(fileName, options) {
    this.fileName     = fileName
    this.prefs        = options.prefs
    this.title        = options.title

    this.fullFileName = getFullFileName(fileName)
    this.relFileName  = getRelFileName(fileName)
    this.htmlFileName = getHtmlFileName(fileName)
    this.zoomFactor    = this.prefs.data.window_zoomFactor

    this.openFile()
  }

  //------------------------------------------------------------------------------
  openFile() {
    // app.addRecentDocument(this.fullFileName)

    markdown.render(this.fullFileName, this.htmlFileName)

    const opts = {
      width:              this.prefs.data.window_width,
      height:             this.prefs.data.window_height,
      preload:            path.join(__dirname, "../renderer/modules/renderer.js"),
      "node-integration": false,
      "zoom-factor":      this.zoomFactor
    }

    if (this.title)            { opts.title = this.title }
    else if (this.relFileName) { opts.title = this.relFileName }
    else                       { opts.title = pkg.productName }

    const browserWindow = this.browserWindow = new BrowserWindow(opts)
    browserWindow.mdViewer = this

    ViewersOpen.set(this.fullFileName, this)

    const windowMenu = menus.loadWindowMenu(this)
    browserWindow.setMenu(windowMenu)

    browserWindow.loadUrl("file://" + this.htmlFileName)

    if (this.fullFileName) {
      browserWindow.setRepresentedFilename(this.fullFileName)
    }

    const viewer = this

    const onResizeDebounced = debounce(1000, function() { viewer.onResize() })

    browserWindow.on("close",  function() { viewer.onClose() })
    browserWindow.on("closed", function() { viewer.onClosed() })
    browserWindow.on("resize", function() { onResizeDebounced() })

    browserWindow.webContents.on("did-finish-load", function() {
      viewer.didFinishLoad()
    })

    const self = this

    fs.watchFile(this.fullFileName, {interval: 1000}, function(curr, prev) {
      self.fileModified(curr, prev)
    })
  }

  //------------------------------------------------------------------------------
  reload() {
    markdown.render(this.fullFileName, this.htmlFileName)

    const hContent = fs.readFileSync(this.htmlFileName, "utf8")

    // this.browserWindow.reload()
    this.runScript("window.mdViewer.reload(" + JSON.stringify(hContent) + ")")
  }

  //------------------------------------------------------------------------------
  fileModified(curr, prev) {
    if (curr.mtime == prev.mtime) return

    this.reload()
  }

  //----------------------------------------------------------------------------
  didFinishLoad() {
  }

  //----------------------------------------------------------------------------
  runScript(script) {
    this.browserWindow.webContents.executeJavaScript(script)
  }

  //----------------------------------------------------------------------------
  show() {
    this.browserWindow.show()
  }

  //----------------------------------------------------------------------------
  onClose() {
  }

  //----------------------------------------------------------------------------
  onClosed() {
    ViewersOpen.delete(this.fileName)
    fs.unlinkSync(this.htmlFileName)
  }

  //----------------------------------------------------------------------------
  onResize() {
    const size = this.browserWindow.getSize()

    this.prefs.data.window_width  = size[0]
    this.prefs.data.window_height = size[1]
    this.prefs.store()
  }

}

//------------------------------------------------------------------------------
function debounce(ms, fn) {
  return throttleDebounce.debounce(ms, fn)
}

//------------------------------------------------------------------------------
function getHtmlFileName(fileName) {
  if (!fileName) return null

  const htmlTemp = tempfile(".md-viewer.html")

  return htmlTemp
}

//------------------------------------------------------------------------------
function getFullFileName(fileName) {
  if (!fileName) return null

  return path.resolve(fileName)
}

//------------------------------------------------------------------------------
function getRelFileName(fileName) {
  if (!fileName) return null

  const home = process.env.HOME
  if (!home) return fileName

  fileName = path.resolve(fileName)

  const relFileName = path.relative(home, fileName)
  if (relFileName[0] == ".") return fileName

  return path.join("~", relFileName)
}

//------------------------------------------------------------------------------
// 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.
//------------------------------------------------------------------------------


text:
.. _installation:

Requirements
============

The models and management commands should work without any additional requirements,
but if you want to use the templates, especially the templates involving forms that
ship with this app, then you will need ``django-forms-bootstrap`` and ``eldarion-ajax``.

Add ``django-forms-bootstrap`` to your project::

    pip install django-forms-bootstrap

You will also want to add ``django_forms_bootstrap`` to your `INSTALLED_APPS``::

    INSTALLED_APPS = [
        "django_forms_bootstrap",
    ]

Add ``eldarion-ajax.js`` to your base template. eldarion-ajax_
is a library used by the included templates to interact with the ajax views. You
can certainly write your own javascript, but it is likely easier for you to just
include the library.

Get it here: eldarion-ajax_

Installation
============

* To install ::

    pip install django-stripe-payments

* Add ``'payments'`` to your ``INSTALLED_APPS`` setting::

    INSTALLED_APPS = [
        "payments",
    ]

* Add ``'payments'`` to your ``urls.py`` ::

    urlpatterns = patterns("",
        ...
        url(r"^payments/", include("payments.urls")),
        ...
    )

Configuration (Modifications to `settings.py`)
=======================
* Add entries to for your publishable and secret keys. The recommended method is
  to setup your production keys using environment variables.  This helps to keep them
  more secure.  Your test keys can be displayed in your code directly.

  The following entries look for your STRIPE_PUBLIC_KEY and
  STRIPE_SECRET_KEY in your environment and, if it can't find them,
  uses your test keys values instead::

    STRIPE_PUBLIC_KEY = os.environ.get("STRIPE_PUBLIC_KEY", "<your publishable test key>")
    STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY", "<your secret test key>")

* Setup your payment plans by defining the setting ``PAYMENTS_PLANS``::

    PAYMENTS_PLANS = {
        "monthly": {
            "stripe_plan_id": "pro-monthly",
            "name": "Web App Pro ($25/month)",
            "description": "The monthly subscription plan to WebApp",
            "price": 25,
            "currency": "usd",
            "interval": "month"
        },
        "yearly": {
            "stripe_plan_id": "pro-yearly",
            "name": "Web App Pro ($199/year)",
            "description": "The annual subscription plan to WebApp",
            "price": 199,
            "currency": "usd",
            "interval": "year"
        },
        "monthly-trial": {
            "stripe_plan_id": "pro-monthly-trial",
            "name": "Web App Pro ($25/month with 30 days free)",
            "description": "The monthly subscription plan to WebApp",
            "price": 25,
            "currency": "usd",
            "interval": "month",
            "trial_period_days": 30
        },
    }

Static Media
============

The included templates have been tested to work with Checkout_.

An example of integrating Checkout_ is to put this in your base template::

    <script src="//checkout.stripe.com/v2/checkout.js"></script>
    <script>
        $(function() {
            $('body').on("click", '.change-card, .subscribe-form button[type=submit]', function(e) {
              e.preventDefault();
              var $form = $(this).closest("form"),
                  token = function(res) {
                    $form.find("input[name=stripe_token]").val(res.id);
                    $form.trigger("submit");
                  };

              StripeCheckout.open({
                key:         $form.data("stripe-key"),
                name:        'Payment Method',
                panelLabel:  'Add Payment Method',
                token:       token
              });

              return false;
            });
        });
    </script>

.. _eldarion-ajax: https://github.com/eldarion/eldarion-ajax
.. _Checkout: https://stripe.com/docs/checkout


text:
namespace LogePT
{
    partial class MainMenu
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.BtnNorth = new System.Windows.Forms.Button();
            this.BtnEast = new System.Windows.Forms.Button();
            this.BtnSouth = new System.Windows.Forms.Button();
            this.BtnWest = new System.Windows.Forms.Button();
            this.CurrentPosition = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // BtnNorth
            //
            this.BtnNorth.Location = new System.Drawing.Point(285, 167);
            this.BtnNorth.Name = "BtnNorth";
            this.BtnNorth.RightToLeft = System.Windows.Forms.RightToLeft.No;
            this.BtnNorth.Size = new System.Drawing.Size(101, 53);
            this.BtnNorth.TabIndex = 0;
            this.BtnNorth.Text = "BtnNorth";
            this.BtnNorth.UseVisualStyleBackColor = true;
            this.BtnNorth.Click += new System.EventHandler(this.btnNorth_Click);
            //
            // BtnEast
            //
            this.BtnEast.Location = new System.Drawing.Point(404, 243);
            this.BtnEast.Name = "BtnEast";
            this.BtnEast.Size = new System.Drawing.Size(101, 53);
            this.BtnEast.TabIndex = 1;
            this.BtnEast.Text = "BtnEast";
            this.BtnEast.UseVisualStyleBackColor = true;
            this.BtnEast.Click += new System.EventHandler(this.btnEast_Click);
            //
            // BtnSouth
            //
            this.BtnSouth.Location = new System.Drawing.Point(285, 330);
            this.BtnSouth.Name = "BtnSouth";
            this.BtnSouth.Size = new System.Drawing.Size(101, 53);
            this.BtnSouth.TabIndex = 2;
            this.BtnSouth.Text = "BtnSouth";
            this.BtnSouth.UseVisualStyleBackColor = true;
            this.BtnSouth.Click += new System.EventHandler(this.btnSouth_Click);
            //
            // BtnWest
            //
            this.BtnWest.Location = new System.Drawing.Point(166, 243);
            this.BtnWest.Name = "BtnWest";
            this.BtnWest.Size = new System.Drawing.Size(101, 53);
            this.BtnWest.TabIndex = 3;
            this.BtnWest.Text = "BtnWest";
            this.BtnWest.UseVisualStyleBackColor = true;
            this.BtnWest.Click += new System.EventHandler(this.btnWest_Click);
            //
            // CurrentPosition
            //
            this.CurrentPosition.AutoSize = true;
            this.CurrentPosition.Location = new System.Drawing.Point(282, 57);
            this.CurrentPosition.Name = "CurrentPosition";
            this.CurrentPosition.Size = new System.Drawing.Size(105, 17);
            this.CurrentPosition.TabIndex = 4;
            this.CurrentPosition.Text = "CurrentPosition";
            //
            // MainMenu
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(741, 496);
            this.Controls.Add(this.CurrentPosition);
            this.Controls.Add(this.BtnWest);
            this.Controls.Add(this.BtnSouth);
            this.Controls.Add(this.BtnEast);
            this.Controls.Add(this.BtnNorth);
            this.Name = "MainMenu";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.MainMenu_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button BtnNorth;
        private System.Windows.Forms.Button BtnEast;
        private System.Windows.Forms.Button BtnSouth;
        private System.Windows.Forms.Button BtnWest;
        private System.Windows.Forms.Label CurrentPosition;
    }
}


text:
package com.mkl.websuites.internal.command.impl.select;

import java.util.Map;

import org.openqa.selenium.support.ui.Select;

import com.mkl.websuites.command.CommandDescriptor;

@CommandDescriptor(name = "deselectByValue", argumentTypes = {String.class, String.class})
public class DeselctByValueCommand extends SelectByValueCommand {

    public DeselctByValueCommand(Map<String, String> parameterMap) {
        super(parameterMap);
    }

    public DeselctByValueCommand(String selector, String value) {
        super(selector, value);
    }

    @Override
    protected void doSelect(String value, Select select) {
        select.deselectByValue(value);
    }
}


text:
module.exports = {
  name: 'Timeout (asynchronous)',
  maxTime: 0.1,
  defer: true,
  onComplete: function() {
    console.log('Hooray!');
  },
  fn: function(deferred) {
    setTimeout(function() {
      deferred.resolve();
    }, 1);
  }
};


text:
TEST(Extended, GetInputs) {
  auto api = IOTA::API::Extended{ get_proxy_host(), get_proxy_port() };
  auto res = api.getInputs(ACCOUNT_2_SEED, 0, 0, 0);

  EXPECT_EQ(res.getTotalBalance(), ACCOUNT_2_FUND);
  ASSERT_EQ(res.getInputs().size(), 4UL);

  //! Note that the first address is skipped because it has no fund

  auto input1 = res.getInputs()[0];
  EXPECT_EQ(input1.toTrytes(), ACCOUNT_2_ADDRESS_2_HASH_WITHOUT_CHECKSUM);
  EXPECT_EQ(input1.getBalance(), ACCOUNT_2_ADDRESS_2_FUND);
  EXPECT_EQ(input1.getKeyIndex(), 1);
  EXPECT_EQ(input1.getSecurity(), 2);

  auto input2 = res.getInputs()[1];
  EXPECT_EQ(input2.toTrytes(), ACCOUNT_2_ADDRESS_3_HASH_WITHOUT_CHECKSUM);
  EXPECT_EQ(input2.getBalance(), ACCOUNT_2_ADDRESS_3_FUND);
  EXPECT_EQ(input2.getKeyIndex(), 2);
  EXPECT_EQ(input2.getSecurity(), 2);

  auto input3 = res.getInputs()[2];
  EXPECT_EQ(input3.toTrytes(), ACCOUNT_2_ADDRESS_4_HASH_WITHOUT_CHECKSUM);
  EXPECT_EQ(input3.getBalance(), ACCOUNT_2_ADDRESS_4_FUND);
  EXPECT_EQ(input3.getKeyIndex(), 3);
  EXPECT_EQ(input3.getSecurity(), 2);

  auto input4 = res.getInputs()[3];
  EXPECT_EQ(input4.toTrytes(), ACCOUNT_2_ADDRESS_5_HASH_WITHOUT_CHECKSUM);
  EXPECT_EQ(input4.getBalance(), ACCOUNT_2_ADDRESS_5_FUND);
  EXPECT_EQ(input4.getKeyIndex(), 4);
  EXPECT_EQ(input4.getSecurity(), 2);
}

TEST(Extended, GetInputsStartEnd) {
  auto api = IOTA::API::Extended{ get_proxy_host(), get_proxy_port() };
  auto res = api.getInputs(ACCOUNT_2_SEED, 2, 4, 0);

  EXPECT_EQ(res.getTotalBalance(), ACCOUNT_2_ADDRESS_3_FUND + ACCOUNT_2_ADDRESS_4_FUND);
  ASSERT_EQ(res.getInputs().size(), 2UL);

  //! Note that the first address is skipped because it has no fund

  auto input1 = res.getInputs()[0];
  EXPECT_EQ(input1.toTrytes(), ACCOUNT_2_ADDRESS_3_HASH_WITHOUT_CHECKSUM);
  EXPECT_EQ(input1.getBalance(), ACCOUNT_2_ADDRESS_3_FUND);
  EXPECT_EQ(input1.getKeyIndex(), 2);
  EXPECT_EQ(input1.getSecurity(), 2);

  auto input2 = res.getInputs()[1];
  EXPECT_EQ(input2.toTrytes(), ACCOUNT_2_ADDRESS_4_HASH_WITHOUT_CHECKSUM);
  EXPECT_EQ(input2.getBalance(), ACCOUNT_2_ADDRESS_4_FUND);
  EXPECT_EQ(input2.getKeyIndex(), 3);
  EXPECT_EQ(input2.getSecurity(), 2);
}

TEST(Extended, GetInputsInvalidStart) {
  auto api = IOTA::API::Extended{ get_proxy_host(), get_proxy_port() };
  EXPECT_EXCEPTION(auto res = api.getInputs(ACCOUNT_2_SEED, 5, 4, 0), IOTA::Errors::IllegalState,
                   "Invalid inputs provided");
}

TEST(Extended, GetInputMin) {
  auto api = IOTA::API::Extended{ get_proxy_host(), get_proxy_port() };

  EXPECT_THROW(api.getInputs(ACCOUNT_2_SEED, 0, 0, 1000000), IOTA::Errors::IllegalState);
}


text:
package com.studio.jc.modules.mySys.controller;

import java.util.Map;

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

import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.common.collect.Maps;
import com.studio.jc.common.config.Global;
import com.studio.jc.common.servlet.ValidateCodeServlet;
import com.studio.jc.common.utils.CacheUtils;
import com.studio.jc.common.utils.CookieUtils;
import com.studio.jc.common.utils.IdGen;
import com.studio.jc.common.utils.JedisUtils;
import com.studio.jc.common.utils.StringUtils;
import com.studio.jc.common.web.BaseController;
import com.studio.jc.modules.mySys.security.MyFormAuthenticationFilter;
import com.studio.jc.modules.mySys.security.MyPrincipal;
import com.studio.jc.modules.mySys.utils.MyUserUtils;
import com.studio.jc.modules.sys.security.FormAuthenticationFilter;
import com.studio.jc.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.studio.jc.modules.sys.utils.UserUtils;

import redis.clients.jedis.Jedis;

@Controller
public class MyLoginController extends BaseController{

	@RequestMapping(value = "${adminPath}/login2", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response, Model model){

//		MyPrincipal principal = MyUserUtils.getMyPrincipal();
//
//		if(principal != null){
//			return "redirect:" + adminPath;
//		}
		return "modules/sys/sysLogin";
	}

	/**
	 * 登录url,如果正确登录,不会调到这个url,如果登录失败才会跳到这个Url
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "${adminPath}/login2", method = RequestMethod.POST)
	public String loginFail(HttpServletRequest request, HttpServletResponse response, Model model) {
		MyPrincipal principal = MyUserUtils.getMyPrincipal();
		//如果已经登录,就跳到管理页面,为什么呢,这里不是登陆失败才回执行这里吗?
		if(null != principal){
			return "redirect:" + adminPath;
		}

		String username = WebUtils.getCleanParam(request, MyFormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
		boolean rememberMe = WebUtils.isTrue(request, MyFormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM);
		String exception = (String) request.getAttribute(MyFormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		String message = (String) request.getAttribute(MyFormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);

		//什么情况下才会出现这个情况?
		if (StringUtils.isBlank(message) || StringUtils.equals(message, "null")){
			message = "用户或密码错误, 请重试.";
		}

		model.addAttribute(MyFormAuthenticationFilter.DEFAULT_USERNAME_PARAM, username);
		model.addAttribute(MyFormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM, rememberMe);
		model.addAttribute(MyFormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, exception);
		model.addAttribute(MyFormAuthenticationFilter.DEFAULT_MESSAGE_PARAM, message);

		//输出
		logger.debug("login fail, message: {}, exception: {}", message, exception);

		if(!UnauthorizedException.class.getName().equals(exception)){
			//当isFail为true的时候,就是将登陆失败次数加一,并且返回是否需要验证码登录
			boolean result = isValidateCodeLogin(username, true, false);
			model.addAttribute("isValidateCodeLogin", result);
		}
		// 验证失败清空验证码
		request.getSession().setAttribute(ValidateCodeServlet.VALIDATE_CODE, IdGen.uuid());
		return "modules/sys/sysLogin";
	}

	/**
	 * 判断是否验证码登录
	 * @return
	 */
	public static boolean isValidateCodeLogin(String username, boolean isFial, boolean clean){
		//获取错误信息,,存在jedis中,所以如果登录失败,需要保存这个键值对,键名叫myLoginFailMap
		Map<String, Integer> loginFailMap = (Map<String, Integer>) JedisUtils.getObject("myLoginFailMap");

		if(null == loginFailMap){
			loginFailMap = Maps.newHashMap();
			JedisUtils.setObject("myLoginFailMap", loginFailMap, 0);
		}

		Integer loginFailNum = loginFailMap.get(username);
		if(null == loginFailNum){
			loginFailNum = 0;
		}

		if(isFial){
			loginFailNum++;
			loginFailMap.put(username, loginFailNum);
		}

		if(clean){
			loginFailMap.remove(username);
		}

		return loginFailNum>=3;

	}
}


text:
package com.github.lstephen.ootp.ai.site;

import com.github.lstephen.ootp.ai.data.Id;
import com.github.lstephen.ootp.ai.player.ratings.RatingsDefinition;
import com.github.lstephen.ootp.ai.rating.Scale;
import com.github.lstephen.ootp.ai.roster.Team;

/** @author lstephen */
public interface SiteDefinition extends RatingsDefinition {

  String getName();

  Id<Team> getTeam();

  String getSiteRoot();

  Version getType();

  String getLeague();

  Integer getNumberOfTeams();

  Site getSite();

  Scale<?> getAbilityRatingScale();

  Scale<?> getPotentialRatingsScale();

  Scale<?> getBuntScale();

  Scale<?> getRunningScale();
}