text:
const request = require('request-promise');
const cheerio = require('cheerio');
const logger = require('log4js').getLogger();
const fs = require('fs');
const fsExtra = require('fs-extra');
const moment = require('moment');
const path = require('path');
const Promise = require('bluebird');

const Post = require('../models/post');
const dir_prefix = 'postpic/';
const uuid = require('uuid/v4');

class Spider {
    constructor($, from) {
        this.$ = $;
        this.from = from;
    }

    static async fetch(url) {
        let options = {
            url: url,
            transform: (body) => {
                return cheerio.load(body, {decodeEntities: false});
            }
        };
        return await request(options);
    }

    static download(uri, filename, callback) {
        request.head(uri, (err, res, body) => {
            request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
        });
    }

    static async downloadImage(url, postTime, fileName) {
        if (!url) {
            logger.error('Unknown url:', postTime);
            return null;
        }
        let arr = url.split('/');
        if (!fileName) {
            let extension = '.jpg';
            fileName = arr[arr.length - 2] + '-' + arr[arr.length - 1] + extension;
        }
        let dir = dir_prefix + moment(postTime).format('YYYY/MM/DD/');
        let savePath = path.join(__dirname, '../public', dir + fileName);
        let saveDir = path.join(__dirname, '../public', dir);
        fsExtra.ensureDirSync(saveDir);
        let relPath = dir + fileName;
        if (fs.existsSync(savePath)) {
            logger.debug('Skip download:', fileName, savePath);
            return relPath;
        }
        logger.debug('downloading image from ', url);
        const downloadPromise = Promise.promisify(this.download);
        await downloadPromise(url, savePath);
        return relPath;
    }
}

class TecentSpider extends Spider {
    constructor($) {
        super($, 't.qq.com');
    }

    extractAll() {
        let $ = this.$;
        let self = this;
        $('#talkList').children('li').each((i, element) => {
            self.extract($(element)).then(post => {
                if (!post) return;
                self.savePost(post)
                    .then(result => {
                        logger.debug('saved:', result._id);
                    })
                    .catch(err => {
                        logger.error(err);
                    });
            });
        });
    }

    async extract(li) {
        const self = this;
        let id = li.attr('id');
        let exists = await this.checkPost(id);
        if (exists) {
            logger.debug('skip existing post:', id);
            return null;
        }
        logger.debug('fetching post:', id);
        let msgBox = li.find('.msgBox');
        let user = msgBox.find('.userName').attr('rel');

        let msgCnt = msgBox.find('.msgCnt');
        let contentIcons = msgCnt.find('img');
        for (let i = 0; i < contentIcons.length; i++) {
            let icon = contentIcons.get(i);
            let $ = this.$;
            $(icon).attr('src', $(icon).attr('crs'));
        }
        let content = msgCnt.html();
        let mediaWrap = msgBox.find('.multiMedia').find('.mediaWrap');
        let pubInfo = msgBox.find('.pubInfo').find('span');
        let timestamp = pubInfo.find('.time').attr('rel');
        let postTime = new Date(timestamp * 1000);
        let client = pubInfo.find('.f').text();
        let images = this.findImages(mediaWrap);
        let localImages = [];
        for (let i = 0; i < images.length; i++) {
            let img = images[i];
            let localImage = await self.extractImage(img, postTime);
            localImages.push(localImage);
        }
        let video = this.findVideo(mediaWrap);
        let post = {
            content: content,
            when: timestamp,
            source: {
                client: client,
                user: user,
                id: id,
                url: 'http://t.qq.com/p/t/' + id,
                from: this.from,
            },
            images: localImages,
            video: video,
        };
        return post;
    }

    async extractImage(a, postTime) {
        let src = a.attr('href');
        let img = a.find('img').attr('crs');
        let localSrc = await Spider.downloadImage(src, postTime);
        let localThumb = await Spider.downloadImage(img, postTime);
        return {
            thumb: localThumb,
            src: localSrc,
        };
    }

    findImages(mediaWrap) {
        if (mediaWrap.length <= 0) return [];
        let pictures = [];
        let $ = this.$;
        let pictureGroup = mediaWrap.find('.tl_imgGroup');
        if (pictureGroup.length > 0) {
            logger.debug('find picture group.');
            pictureGroup.find('.tl_imgGroup_item').each((i, element) => {
                let a = $(element).find('a');
                pictures.push(a);
            });
        }
        else {
            let a = mediaWrap.find('.picBox').find('a');
            if (a.length > 0) {
                pictures.push(a);
                logger.debug('find picture.');
            }
        }
        return pictures;
    }

    findVideo(mediaWrap) {
        if (mediaWrap.length <= 0) return [];
        let a = mediaWrap.find('.videoBox').find('.vWrap').find('a');
        if (a.length <= 0)
            return null;
        logger.debug('=>find video.', a.attr('href'));
        return a.attr('href');
    }

    async savePost(post) {
        let item = new Post(post);
        return item.save();
    }

    async checkPost(id) {
        let post = await Post.findOne({'source.id': id});
        return !!post;
    }

    getNextPage(base, page) {
        let $ = this.$;
        let pageBtn = $('#pageNav').children('a');
        let paramIndex = base.indexOf('?');
        if (paramIndex) base = base.substr(0, paramIndex);
        if (pageBtn.length > 0) {
            for (let i = 0; i < pageBtn.length; i++) {
                let theBtn = $(pageBtn.get(i));

                if (parseInt(theBtn.text()) === page) {
                    return base + theBtn.attr('href');
                }
            }
        }
        return null;
    }
}
function importFromTecent(url, page, min, max) {
    if (!page) page = 1;
    logger.debug('=>page:', page, url);
    if (page > max) {
        logger.debug('stoped');
        return;
    }
    Spider.fetch(url).then($ => {
        let spider = new TecentSpider($);
        let next = spider.getNextPage(url, page + 1);
        if (next) {
            importFromTecent(next, page + 1, min, max);
        }
        else {
            logger.debug('< No more pages.');
        }
        if (page < min || page > max) {
            logger.debug('=> skip fetching', page);
        } else {
            logger.debug('====> fetching:', page);
            spider.extractAll();
        }
    });
}
exports = module.exports = {
    importFromTecent: importFromTecent,
    Spider: Spider,
};


text:
package co.omise.live;

import co.omise.Client;
import co.omise.models.OmiseException;
import co.omise.models.Refund;
import co.omise.models.RefundStatus;
import co.omise.models.ScopedList;
import co.omise.requests.Request;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public class LiveRefundRequestTest extends BaseLiveTest {

    private final String LIVETEST_CHARGE = "[YOUR_CHARGE]";
    private final String LIVETEST_REFUND = "[YOUR_REFUND]";

    private Client client;

    @Before
    public void setup() throws Exception {
        client = getLiveClient();
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveCreateRefund() throws IOException, OmiseException {
        Request<Refund> request = new Refund.CreateRequestBuilder(LIVETEST_CHARGE)
                .amount(10000)
                .metadata("description", "DESCRIPTION")
                .metadata("invoice_id", "inv_N1ayTWJ2FV")
                .build();
        Refund refund = client.sendRequest(request);

        System.out.println("created refund: " + refund.getId());

        assertEquals("DESCRIPTION", refund.getMetadata().get("description"));
        assertEquals("inv_N1ayTWJ2FV", refund.getMetadata().get("invoice_id"));
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveGetRefund() throws IOException, OmiseException {
        Request<Refund> request = new Refund.GetRequestBuilder(LIVETEST_CHARGE, LIVETEST_REFUND).build();
        Refund refund = client.sendRequest(request);

        System.out.println("retrieved refund: " + refund.getId());

        assertEquals(LIVETEST_REFUND, refund.getId());
        assertEquals(RefundStatus.Closed, refund.getStatus());
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveGetRefundList() throws IOException, OmiseException {
        Request<ScopedList<Refund>> request = new Refund.ListRequestBuilder(LIVETEST_CHARGE).build();
        ScopedList<Refund> refunds = client.sendRequest(request);

        System.out.println("retrieved refund list total no.: " + refunds.getTotal());

        assertNotNull(refunds.getData().get(0));
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'test_helper'

class ApiAuthorizationsControllerTest < ActionController::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
package main

import (
	"bytes"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha512"
	"encoding/base64"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"strconv"
	"text/template"
	"time"
)

var (
	//These keys are purely for demonstration purposes.  They won't provide access to anything, anywhere at anytime.
	pubkey   = "mbRgpR2eYAdJkhvrfwjlmMC+L/0Vbrj4KvVo5nvnScwsx25LK+tPE3AM/IMcHuDW5zzp4Kup9xKd5YXupRJHzw=="
	privkey  = "7F22ZeY+mlHtALq3sXcjrLdcID7whhVIQ5zD4bl4raKdBTYVgAjfdbvdfB5lmQa4wVP1o4frD5tmUcKON4ueVA=="
	httpAddr = flag.String("http", "www.order-demo.com:8090", "Server address")
)

func main() {
	flag.Parse()
	http.HandleFunc("/", homeHandler)
	http.HandleFunc("/send", sendHandler)
	http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("resources"))))
	log.Printf("Remote requests will be sent to %v\n", *httpAddr)
	log.Printf("Listening on localhost:8080")
	http.ListenAndServe("localhost:8080", nil)

}

type Page struct {
	Title    string
	Label    string
	LoadTime time.Time
}

type OrderMessage struct {
	NumShares     int
	MaxPrice      int
	PublicKey     []byte
	Nonce         []byte
	OrderDateTime time.Time
	Verb          string
	URL           string
}

type SignedMessage struct {
	Hash  string
	Order OrderMessage
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
	p := &Page{Title: "Place an Order!", Label: "Place an Order", LoadTime: time.Now().Local()}
	t, _ := template.ParseFiles("template1.html")
	t.Execute(w, p)
}

func sendHandler(w http.ResponseWriter, r *http.Request) {
	remoteUrl := fmt.Sprintf("http://%v/process", *httpAddr)
	numshares, _ := strconv.Atoi(r.FormValue("numshares"))
	maxprice, _ := strconv.Atoi(r.FormValue("maxprice"))
	order := BuildOrder(numshares, maxprice, remoteUrl, "POST")
	signedMsg := SignedMessage{Order: order}

	signedMsg.SetHash([]byte(privkey))
	sm, _ := json.Marshal(signedMsg)
	client := &http.Client{}

	req, _ := http.NewRequest("POST", remoteUrl, bytes.NewBufferString(string(sm)))
	resp, _ := client.Do(req)
	log.Println("----------")
	log.Println("Sent: ", string(sm))
	log.Println("Return Code:", resp.Status)

	defer resp.Body.Close()
	contents, _ := ioutil.ReadAll(resp.Body)
	log.Println("Received: ", string(contents))
	w.Header().Set("Content-Type", "application/json")
	if resp.StatusCode < 200 || resp.StatusCode > 299 {
		http.Error(w, string(contents), resp.StatusCode)
		return
	}
	w.Write(contents)
}

func BuildOrder(numshares int, maxprice int, url string, verb string) OrderMessage {
	result := OrderMessage{}

	result.NumShares = numshares
	result.MaxPrice = maxprice

	result.PublicKey = []byte(pubkey)
	result.Nonce, _ = GenerateKey(32)
	result.OrderDateTime = time.Now().Local()
	result.Verb = verb
	result.URL = url
	return result
}

func (sm *SignedMessage) SetHash(privkey []byte) {
	jsonbody, _ := json.Marshal(sm.Order)
	h := hmac.New(sha512.New, privkey)
	h.Write([]byte(jsonbody))
	sm.Hash = base64.StdEncoding.EncodeToString(h.Sum(nil))
}

func GenerateKey(keylength int) ([]byte, string) {
	key := make([]byte, keylength)
	rand.Read(key)
	base64str := base64.StdEncoding.EncodeToString(key)
	return key, base64str
}


text:
namespace mazecore.control.test {

    using mazecore.control;
    using NUnit.Framework;

    class TrapController : Controller {

        public bool tripped;
        public int last_tick;
        public TrapController() {
            this.reset();
        }

        public void reset(){
            this.tripped = false;
            this.last_tick = -1;
        }

        protected override void do_update(int tick) {
            this.tripped = true;
            this.last_tick = tick;
        }

    }

    [TestFixture]
    class TestController {

        [Test]
        public void test_get_set_active() {

            TrapController trap_controller = new TrapController();

            Assert.True(trap_controller.get_active());
            trap_controller.set_active(false);
            Assert.False(trap_controller.get_active());
        }

        [Test]
        public void test_tick(){

            TrapController trap_controller = new TrapController();

            Assert.False(trap_controller.tripped);
            Assert.AreEqual(trap_controller.last_tick, -1);

            trap_controller.update(1);
            Assert.True(trap_controller.tripped);
            Assert.AreEqual(trap_controller.last_tick, 1);

            trap_controller.reset();
            trap_controller.set_active(false);
            trap_controller.update(2);
            Assert.False(trap_controller.tripped);
            Assert.AreEqual(trap_controller.last_tick, -1);
        }

    }

}


text:
print "Using Oracle\n"
require_dependency 'fixtures/course'
require 'logger'

ActiveRecord::Base.logger = Logger.new STDOUT
ActiveRecord::Base.logger.level = Logger::WARN

# Set these to your database connection strings
db = ENV['ARUNIT_DB'] || 'activerecord_unittest'

ActiveRecord::Base.establish_connection(
  :adapter  => 'oracle',
  :username => 'arunit',
  :password => 'arunit',
  :database => db
)

Course.establish_connection(
  :adapter  => 'oracle',
  :username => 'arunit2',
  :password => 'arunit2',
  :database => db
)


text:
using System;

namespace ModMaker.Lua.Parser.Items {
  /// <summary>
  /// Defines a variable assignment statement.
  /// e.g. i, x = foo();
  /// </summary>
  public sealed class AssignmentItem : IParseStatement {
    /// <summary>
    /// Creates a new instance of AssignmentItem.
    /// </summary>
    /// <param name="local">True if this is a local definition, otherwise false.</param>
    public AssignmentItem(IParseVariable[] names, IParseExp[] exps) {
      Names = names;
      Expressions = exps;
    }

    /// <summary>
    /// Gets the name expression of this item.
    /// </summary>
    public IParseVariable[] Names { get; set; }
    /// <summary>
    /// Gets the value expression of this item.
    /// </summary>
    public IParseExp[] Expressions { get; set; }
    /// <summary>
    /// Gets or sets whether this is a local definition.
    /// </summary>
    public bool Local { get; set; } = false;
    /// <summary>
    /// Gets or sets whether the last expression is single.  Namely whether the last expression
    /// is wrapped in parentheses, e.g. i = (foo()).
    /// </summary>
    public bool IsLastExpressionSingle { get; set; } = false;

    public DebugInfo Debug { get; set; }

    public IParseItem Accept(IParseItemVisitor visitor) {
      return visitor.Visit(this);
    }
  }
}


text:
package jsonTools

import "encoding/json"

/*
json模块封装
@author: yubang
 */

// json字符串转map对象
func JsonToInterface(jsonString []byte) map[string]interface{}{
	r := make(map[string]interface{})
	err := json.Unmarshal(jsonString, &r)
	if err != nil{
		return nil
	}
	return r
}

// json字符串转map列表
func JsonToInterfaceList(jsonString []byte) []interface{}{
	var r interface{}
	err := json.Unmarshal(jsonString, &r)
	if err != nil{
		return nil
	}
	return r.([]interface{})
}

//map对象转json字符串
func InterfaceToJson(obj map[string]interface{})[]byte{
	r, err := json.Marshal(obj)
	if err != nil{
		return nil
	}
	return r
}

//map对象列表转json字符串
func InterfaceListToJson(obj []map[string]interface{})[]byte{
	r, err := json.Marshal(obj)
	if err != nil{
		return nil
	}
	return r
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.panryba.mc.cannon;

import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.bukkit.WGBukkit;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.plugin.java.JavaPlugin;

/**
 *
 * @author PanRyba.pl
 */
public class Plugin extends JavaPlugin implements Listener {

    ProtectedRegion region;
    int xMin, zMin, xMax, zMax;
    ProtectedRegion igniteRegion;
    World world;
    double x, y, z;
    double tntx, tnty, tntz;

    Location explosion;

    boolean fired;

    @Override
    public void onEnable() {
        FileConfiguration config = getConfig();
        String worldName = config.getString("world");
        world = getServer().getWorld(worldName);

        RegionManager manager = WGBukkit.getRegionManager(world);
        String regionName = config.getString("region");
        region = manager.getRegion(regionName);

        BlockVector vmin = this.region.getMinimumPoint();
        BlockVector vmax = this.region.getMaximumPoint();
        Location min = new Location(this.world, vmin.getX(), vmin.getY(), vmin.getZ());
        Location max = new Location(this.world, vmax.getX(), vmax.getY(), vmax.getZ());
        Chunk c1 = min.getChunk();
        Chunk c2 = max.getChunk();
        xMin = Math.min(c1.getX(), c2.getX());
        xMax = Math.max(c1.getX(), c2.getX());
        zMin = Math.min(c1.getZ(), c2.getZ());
        zMax = Math.max(c1.getZ(), c2.getZ());

        String igniteName = config.getString("ignite");
        igniteRegion = manager.getRegion(igniteName);

        x = config.getDouble("velocity.player.x");
        y = config.getDouble("velocity.player.y");
        z = config.getDouble("velocity.player.z");

        tntx = config.getDouble("velocity.tnt.x");
        tnty = config.getDouble("velocity.tnt.y");
        tntz = config.getDouble("velocity.tnt.z");

        double ex = config.getDouble("explosion.x");
        double ey = config.getDouble("explosion.y");
        double ez = config.getDouble("explosion.z");

        explosion = new Location(world, ex, ey, ez);

        getServer().getPluginManager().registerEvents(this, this);
        getCommand("ignite").setExecutor(this);
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player)) {
            return false;
        }

        ignite((Player) sender);
        return true;
    }

    @EventHandler(ignoreCancelled = true)
    private void onBlockIgnite(BlockIgniteEvent event) {
        if (event.getPlayer() == null) {
            return;
        }

        if (isIgnition(event.getBlock().getLocation())) {
            ignite(event.getPlayer());
        }
    }

    private void ignite(Player ignitedBy) {
        long now = new Date().getTime();
        if (fired) {
            ignitedBy.sendMessage(ChatColor.BLUE + "Lont juz jest podpalony - armata za chwile wystrzeli!");
            return;
        }

        fired = true;
        scheduleIgnition(ignitedBy);
    }

    private boolean inCannon(Player player) {
        Location loc = player.getLocation();
        if (loc.getWorld() != this.world) {
            return false;
        }

        Vector v = new Vector(loc.getX(), loc.getY(), loc.getZ());
        return this.region.contains(v);
    }

    private void launch(Player player) {
        player.setVelocity(new org.bukkit.util.Vector(x, y, z));
    }

    private boolean isIgnition(Location location) {
        if(this.igniteRegion == null) {
            return false;
        }

        if (location.getWorld() != this.world) {
            return false;
        }

        Vector v = new Vector(location.getX(), location.getY(), location.getZ());
        return this.igniteRegion.contains(v);
    }

    private Set<TNTPrimed> prepareTnts() {
        Set<TNTPrimed> tnts = new HashSet<>();

        for (int cx = xMin; cx <= xMax; cx++) {
            for (int cz = zMin; cz <= zMax; cz++) {
                for (Entity e : world.getChunkAt(cx, cz).getEntities()) {
                    if ((e instanceof TNTPrimed)) {
                        Location eLoc = e.getLocation();
                        BlockVector loc = new BlockVector(eLoc.getX(), eLoc.getY(), eLoc.getZ());

                        if (region.contains(loc)) {
                            tnts.add((TNTPrimed) e);
                        }
                    }
                }
            }
        }

        return tnts;
    }

    private void launchTnts(Set<TNTPrimed> tnts) {
        for (TNTPrimed tnt : tnts) {
            tnt.setVelocity(new org.bukkit.util.Vector(tntx, tnty, tntz));
        }
    }

    private Set<Player> preparePlayers() {
        Set<Player> players = new HashSet<>();

        for (Player player : this.getServer().getOnlinePlayers()) {
            if (inCannon(player)) {
                players.add(player);
            }
        }

        return players;
    }

    private void launchPlayers(Set<Player> players) {
        for (Player player : players) {
            launch(player);
        }
    }

    private void scheduleIgnition(final Player ignitedBy) {
        ignitedBy.sendMessage(ChatColor.BLUE + "Podpaliles lont - armata za chwile wystrzeli!");

        getServer().getScheduler().runTaskLaterAsynchronously(this, new Runnable() {
            @Override
            public void run() {
                final Set<TNTPrimed> tnts = prepareTnts();
                final Set<Player> players = preparePlayers();

                getServer().getScheduler().runTask(Plugin.this, new Runnable() {

                    @Override
                    public void run() {
                        fired = false;

                        launchTnts(tnts);
                        launchPlayers(players);
                        Plugin.this.world.createExplosion(explosion, 1.0f, false);
                    }
                });

            }
        }, 20 * 5);
    }
}


text:
require 'rails_helper'

RSpec.describe TeamMembership, type: :model do
  it { should belong_to(:user) }
  it { should belong_to(:team) }
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Epicr. syst. mycol. (Upsaliae) 273 (1838)

#### Original name
Cortinarius subtortus var. subtortus (Pers.) Fr.

### Remarks
null