text:
package ru.spbau.twiktor;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.spbau.twiktor.transform.TwitTransformer;
import ru.spbau.twiktor.transform.TwitTransformerSynonymizationImpl;
import ru.spbau.twiktor.utils.ThreadUtils;
import twitter4j.*;
import twitter4j.Query.ResultType;
import twitter4j.auth.AccessToken;

public class Twiktor {
	private final static Logger LOG = LoggerFactory.getLogger(Twiktor.class);
    private final static AtomicInteger counter = new AtomicInteger();
	public static final int TwitterMaxLength = 140;
	private final TwitTransformer transformer;
	private final Twitter twitter;
	private String[] tags;
	private Timer timer;
	private volatile boolean isRunning = false;
    private final int id;
    private final String login;
    private final int followersCount;

    private static final Map<Long, Boolean> cache = new LinkedHashMap<Long, Boolean>() {
        @Override
        protected boolean removeEldestEntry(Map.Entry<Long, Boolean> eldest) {
            return size() > 1000;
        }
    };

    public Twiktor(String login, TwitTransformer transformer, String[] tags, AccessToken accessToken) throws IllegalStateException, TwitterException {
        this.login = login;
        id = counter.incrementAndGet();
		this.transformer = transformer;
		this.tags = tags;
		twitter = getTwitter(accessToken);
		long authUserId = twitter.getId();
        followersCount = twitter.users().showUser(login).getFollowersCount();
        LOG.info("Twitter created. Used user id is '{}'", authUserId);
    }

    public int getFollowersCount() {
        return followersCount;
    }

	public boolean isRunning() {
		return isRunning;
	}

    public String getLogin() {
        return login;
    }

	public void start() {
		if(isRunning) {
			return;
		}
		timer = new Timer();
		timer.schedule(new PostStatusTask(), 0, 30000);
		isRunning = true;
	}

	public void stop() {
		if(!isRunning) {
			return;
		}
		timer.cancel();
		timer.purge();
		timer = null;
        isRunning = false;
	}

	public void postStatus(String text) throws TwitterException {
        TwitTransformer synonimTransofrmer = new TwitTransformerSynonymizationImpl();
		Status newStatus = twitter.updateStatus(synonimTransofrmer.tranform(text));
		LOG.info("Status updated. Id is '{}'", newStatus.getId());
	}

	public Trends getTrends(int woeid)
	{
		Trends trends = null;
		try {
			trends = twitter.getPlaceTrends(woeid);
		} catch (TwitterException e) {
			e.printStackTrace();
		}

		return trends;
	}

	private static Twitter getTwitter(AccessToken accessToken) {
		TwitterFactory factory = new TwitterFactory();
		Twitter twitter = factory.getInstance();
		// TODO load secret
		twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
		twitter.setOAuthAccessToken(accessToken);
		return twitter;
	}

    public int getId() {
        return id;
    }

    public void setTags(String[] tags) {
    	this.tags = tags;
    }

    public void follow(String login) {
        try {
            twitter.createFriendship(login);
        } catch (TwitterException e) {
            LOG.error("Can not to follow " + login);
        }
    }

    private class PostStatusTask extends TimerTask {

		@Override
		public void run() {
			try {
                ThreadUtils.sleep(0, 5000); // случайная пауза от 0 до 5с
				String tag = tags[ThreadLocalRandom.current().nextInt(tags.length)];
				LOG.info("Tag to process: '{}'", tag);
				Status status = getTwit(tag);
				LOG.info("Used status text is '{}'", status.getText());

				String newText = transformer.tranform(status, twitter, tag);
                TwitTransformer synonymization = new TwitTransformerSynonymizationImpl();
                if(ThreadLocalRandom.current().nextInt(4) == 0) {
                    // повысил качество на ночь
                    newText = synonymization.tranform(newText);
                }
				if(newText == null) {
					return;
				}
				if(newText.length() > TwitterMaxLength) {
					newText = newText.substring(0, TwitterMaxLength);
				}
				LOG.info("New text is '{}'", newText);

                boolean reply = ThreadLocalRandom.current().nextBoolean();

                if(needToFollow()) {
                    twitter.createFriendship(status.getUser().getId());
                }

                if(ThreadLocalRandom.current().nextInt(5) == 0) {
                    twitter.createFavorite(status.getId());
                }

                // сделал ответы чуть чаще
                if(reply || ThreadLocalRandom.current().nextInt(4) == 1) {
                    replyTwit(status, newText);
                } else {
                    Status newStatus = twitter.updateStatus(newText);
                    LOG.info("Status updated. Id is '{}'", newStatus.getId());
                }
			} catch (Exception e) {
				LOG.error(e.getMessage());
			}
		}

        private void replyTwit(Status status, String newText) throws TwitterException {
			TwitterRTFilter twitterRTFilter = new TwitterRTFilter(newText);
			newText = twitterRTFilter.filter();

            long inReply = status.getId();
            String userNameToReply = getUserName(status);

			String fullMessage = "@" + userNameToReply + " " + newText;
			if(fullMessage.length() > TwitterMaxLength) {
				fullMessage = fullMessage.substring(0, TwitterMaxLength);
			}

			StatusUpdate update = new StatusUpdate(fullMessage);
            update.setInReplyToStatusId(inReply);
            twitter.updateStatus(update);
        }

        private String getUserName(Status status) {
			if(!status.isRetweet()) {
				return status.getUser().getScreenName();
			}
			return status.getUserMentionEntities()[0].getScreenName();
		}

		private Status getTwit(String tag) throws TwitterException {
			List<Status> statusList = twitter.search(new Query(tag).count(100).resultType(ResultType.recent)).getTweets();
			Status status = statusList.get(ThreadLocalRandom.current().nextInt(statusList.size()));

            int tryCount = 0;
            while (cache.containsKey(status.getId())) {
                tryCount++;
                status = statusList.get(ThreadLocalRandom.current().nextInt(statusList.size()));
                if(tryCount > 10) {
                    throw new RuntimeException("Error, too many repeated tweets with tag " + (tag));
                }
            }
            cache.put(status.getId(), Boolean.TRUE);

			return status;
		}
	}

    public AccessToken getAccessToken() {
        try {
            return twitter.getOAuthAccessToken();
        } catch (TwitterException e) {
            throw new RuntimeException(e);
        }
    }

    private boolean needToFollow() {
        return ThreadLocalRandom.current().nextInt(10) == 0;
    }
}


text:
class SurveyAdmin::AnswersController < SurveyAdmin::BaseController
  helper_method :survey_properties

  def index
    @question   = Question.find(params[:question_id])
    @answers    = @question.answers.all
  end

  def show
    @answer = Answer.find(params[:id])
  end

  def new
    @question   = Question.find(params[:question_id])
    @answer     = @question.answers.new
    @survey_image = @answer.survey_images.build
    form_info
  end

  def create
    @question   = Question.find(params[:question_id])
    @answer = @question.answers.new(params[:answer])
    if @answer.save
      redirect_to [:survey_admin, @answer.question, @answer], :notice => "Successfully created answer."
    else
      @survey_image = @answer.survey_images.build
      form_info
      render :new
    end
  end

  def edit
    @answer = Answer.find(params[:id])
    @survey_image = @answer.survey_images.empty? ? @answer.survey_images.build : @answer.survey_images.first
    form_info
  end

  def update
    @answer = Answer.find(params[:id])
    if @answer.update_attributes(params[:answer])
      redirect_to [:survey_admin, @answer.question, @answer], :notice  => "Successfully updated answer."
    else
      @survey_image = @answer.survey_images.empty? ? @answer.survey_images.build : @answer.survey_images.first
      form_info
      render :edit
    end
  end

  def destroy
    @answer = Answer.find(params[:id])
    @answer.active = false
    @answer.save
    redirect_to survey_admin_question_answers_url(@answer.question), :notice => "Successfully inactivated answer."
  end

  private
    def survey_properties
      @survey_properties ||= SurveyProperty.all.map{|sp| [sp.name, sp.id]}
    end

    def form_info

    end
end

redpajama_set_name: RedPajamaGithub


text:
import { mount, mountAsChild } from '../../../../src/vue-testing';
import { expect } from 'chai';
import Example from '../../../resources/components/Example.vue';

describe('Wrapper.text', () => {
    it('Example.vue renders the correct fullname (tested with mount())', () => {
        const wrapper = mount(Example, {
            propsData: {
                firstname: 'John',
                lastname: 'Doe'
            }
        });
        expect(wrapper.find('h1')[0].text()).to.equal('John Doe');
    });

    it('Example.vue renders the correct fullname (tested with mountAsChild())', () => {
        const wrapper = mountAsChild(Example, {
            props: {
                firstname: 'John',
                lastname: 'Doe'
            }
        });
        expect(wrapper.find('h1')[0].text()).to.equal('John Doe');
    });
});


text:
<?php

namespace FDevs\Locale\Tests;

use FDevs\Locale\LocaleInterface;
use FDevs\Locale\Model\PriorityLocale;

abstract class AbstractTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @param string $locale
     *
     * @return LocaleInterface
     */
    protected function createLocaleMock($locale)
    {
        $model = $this
            ->getMockBuilder('FDevs\Locale\LocaleInterface')
            ->setMethods(['isLocale', 'getLocale', 'setLocale'])
            ->getMock()
        ;

        $model
            ->expects($this->any())
            ->method('isLocale')
            ->with($this->anything())
            ->will($this->returnCallback(function ($loc) use ($locale) {
                return $loc === $locale;
            }))
        ;

        $model
            ->method('setLocale')
            ->will($this->returnSelf())
        ;

        $model
            ->method('getLocale')
            ->willReturn($locale)
        ;

        return $model;
    }

    /**
     * @param string $locale
     * @param array  $localeList
     *
     * @return PriorityLocale
     */
    protected function createPriorityLocaleMock($locale, array $localeList = [])
    {
        $model = $this
            ->getMockBuilder('FDevs\Locale\Model\PriorityLocale')
            ->setMethods(['getLocaleList', 'setLocaleList', 'setLocale', 'getLocale'])
            ->getMock()
        ;

        $model
            ->expects($this->any())
            ->method('getLocaleList')
            ->will($this->returnValue($localeList))
        ;
        $model
            ->method('setLocaleList')
            ->will($this->returnSelf())
        ;

        $model
            ->method('setLocale')
            ->will($this->returnSelf())
        ;

        $model
            ->method('getLocale')
            ->willReturn($locale)
        ;

        return $model;
    }
}


text:
from fake_ubersmith.api.base import Base
from fake_ubersmith.api.ubersmith import FakeUbersmithError
from fake_ubersmith.api.utils.response import response

class Order(Base):
    def __init__(self, data_store):
        super().__init__(data_store)

    def hook_to(self, entity):
        entity.register_endpoints(
            ubersmith_method='order.coupon_get',
            function=self.coupon_get
        )
        entity.register_endpoints(
            ubersmith_method='order.create',
            function=self.create_order
        )
        entity.register_endpoints(
            ubersmith_method='order.respond',
            function=self.order_respond
        )
        entity.register_endpoints(
            ubersmith_method='order.submit',
            function=self.submit_order
        )
        entity.register_endpoints(
            ubersmith_method='order.cancel',
            function=self.cancel_order
        )

    def coupon_get(self, form_data):
        coupon = next(
            (
                cf for cf in self.data_store.coupons
                if cf["coupon"]["coupon_code"] == form_data["coupon_code"]
            ),
            None
        )
        if coupon is not None:
            self.logger.info("Retrieved coupon data: {}".format(coupon))
            return response(data=coupon)
        else:
            self.logger.info("Getting coupon info failed")
            return response(
                error_code=1, message="could not get coupon info"
            )

    def create_order(self, form_data):
        order = self.data_store.order.get(form_data['order_queue_id'])
        if isinstance(order, FakeUbersmithError):
            self.logger.info("Creating order failed")
            return response(
                error_code=order.code, message=order.message
            )
        self.logger.info("Creating order: {}".format(order))
        return response(data=order)

    def order_respond(self, form_data):
        data = 8
        self.logger.info("order response: {}".format(data))
        return response(data=data)

    def submit_order(self, form_data):
        order_submit = self.data_store.order_submit.get(form_data['order_id'])

        if isinstance(order_submit, FakeUbersmithError):
            self.logger.error("Order submitted failed.")
            return response(
                error_code=order_submit.code, message=order_submit.message
            )
        self.logger.info("Order submitted info: {}".format(order_submit))
        return response(data=order_submit)

    def cancel_order(self, form_data):
        order_cancel = self.data_store.order_cancel.get(form_data['order_id'])
        if isinstance(order_cancel, FakeUbersmithError):
            self.logger.error("Cancel order failed.")
            return response(
                error_code=order_cancel.code, message=order_cancel.message
            )
        self.logger.info("Cancelling order info: {}".format(order_cancel))
        return response(data=order_cancel)


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "boletinnotas".
 *
 * @property integer $idBoletin
 * @property integer $idanio
 * @property integer $idfilial
 * @property string $nivel
 * @property string $grado
 * @property integer $idSeccion
 * @property integer $mes
 * @property string $fecha
 * @property string $nombreArchivo
 * @property string $archivo
 */
class Boletinnotas extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'boletinnotas';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['idanio', 'idfilial', 'nivel', 'grado', 'idSeccion', 'mes', 'fecha', 'nombreArchivo', 'archivo'], 'required'],
            [['idanio', 'idfilial', 'idSeccion', 'mes'], 'integer'],
            [['fecha'], 'safe'],
            [['nivel', 'grado'], 'string', 'max' => 50],
            [['nombreArchivo', 'archivo'], 'string', 'max' => 100],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'idBoletin' => 'Id Boletin',
            'idanio' => 'Idanio',
            'idfilial' => 'Idfilial',
            'nivel' => 'Nivel',
            'grado' => 'Grado',
            'idSeccion' => 'Id Seccion',
            'mes' => 'Mes',
            'fecha' => 'Fecha',
            'nombreArchivo' => 'Nombre Archivo',
            'archivo' => 'Archivo',
        ];
    }
}


text:
/*jshint -W003*/
'use strict';

var patio = require("../../lib"),
    config = require("../test.config.js"),
    comb = require("comb"),
    DB;

module.exports = {
    createSchemaAndSync: createSchemaAndSync,
    dropModels: dropModels
};

function createSchemaAndSync(underscore) {
    return createTables(underscore).chain(function(db){
        return patio.syncModels().chain(db);
    });
}

function dropModels() {
    return dropTableAndDisconnect();
}

function dropTableAndDisconnect() {
    return DB.dropTable(["works", "employee"])
        .chain(function () {
            return patio.disconnect();
        })
        .chain(function () {
            patio.resetIdentifierMethods();
        });
}

function createTables(underscore) {
    underscore = underscore === true;
    if (underscore) {
        patio.camelize = underscore;
    } else {
        patio.resetIdentifierMethods();
    }
    DB = patio.connect(config.DB_URI + "/sandbox");

    return DB.forceDropTable(["works", "employee"])
        .chain(function () {
            return DB.createTable("employee", function () {
                this.primaryKey("id");
                this[underscore ? "first_name" : "firstname"]("string", {size: 20, allowNull: false});
                this[underscore ? "last_name" : "lastname"]("string", {size: 20, allowNull: false});
                this[underscore ? "mid_initial" : "midinitial"]("char", {size: 1});
                this.position("integer");
                this.gender("char", {size: 1});
                this.street("string", {size: 50, allowNull: false});
                this.city("string", {size: 20, allowNull: false});
            });
        }).chain(function () {
            return DB.createTable("works", function () {
                this.primaryKey("id");
                this[underscore ? "company_name" : "companyName"]("string", {size: 20, allowNull: false});
                this.salary("float", {size: [20, 8], allowNull: false});
                this.foreignKey(underscore ? "employee_id" : "employeeId", "employee", {key: "id"});
            });
        }).chain(DB);
}