text:
import {Viewer} from '../../src/viewer';
import {platform} from '../../src/platform';

describe('Viewer', () => {

  let sandbox;
  let windowMock;
  let viewer;
  let windowApi;

  beforeEach(() => {
    sandbox = sinon.sandbox.create();
    var WindowApi = function() {};
    WindowApi.prototype.setTimeout = function(callback, delay) {};
    windowApi = new WindowApi();
    windowApi.location = {hash: '', href: '/test/viewer'};
    windowMock = sandbox.mock(windowApi);
    viewer = new Viewer(windowApi);
  });

  afterEach(() => {
    viewer = null;
    windowMock.verify();
    windowMock = null;
    sandbox.restore();
    sandbox = null;
  });

  it('should configure as natural viewport by default', () => {
    expect(viewer.getViewportType()).to.equal('natural');
    expect(viewer.getViewportWidth()).to.equal(0);
    expect(viewer.getViewportHeight()).to.equal(0);
    expect(viewer.getScrollTop()).to.equal(0);
    expect(viewer.getPaddingTop()).to.equal(0);
  });

  it('should configure correctly based on window name and hash', () => {
    windowApi.name = '__AMP__viewportType=virtual&width=222&height=333' +
        '&scrollTop=15';
    windowApi.location.hash = '#width=111&paddingTop=17&other=something';
    windowApi.document = {body: {style: {}}};
    let viewer = new Viewer(windowApi);
    expect(viewer.getViewportType()).to.equal('virtual');
    expect(viewer.getViewportWidth()).to.equal(111);
    expect(viewer.getViewportHeight()).to.equal(333);
    expect(viewer.getScrollTop()).to.equal(15);
    expect(viewer.getPaddingTop()).to.equal(17);

    // All of the startup params are also available via getParam.
    expect(viewer.getParam('paddingTop')).to.equal('17');
    expect(viewer.getParam('width')).to.equal('111');
    expect(viewer.getParam('other')).to.equal('something');
  });

  it('should configure visibilityState visible by default', () => {
    expect(viewer.getVisibilityState()).to.equal('visible');
    expect(viewer.isVisible()).to.equal(true);
    expect(viewer.getPrerenderSize()).to.equal(1);
  });

  it('should configure visibilityState and prerender', () => {
    windowApi.location.hash = '#visibilityState=hidden&prerenderSize=3';
    let viewer = new Viewer(windowApi);
    expect(viewer.getVisibilityState()).to.equal('hidden');
    expect(viewer.isVisible()).to.equal(false);
    expect(viewer.getPrerenderSize()).to.equal(3);
  });

  it('should configure correctly for iOS embedding', () => {
    windowApi.name = '__AMP__viewportType=natural';
    windowApi.parent = {};
    let body = {style: {}};
    let documentElement = {style: {}};
    windowApi.document = {body: body, documentElement: documentElement};
    sandbox.mock(platform).expects('isIos').returns(true).once();
    let viewer = new Viewer(windowApi);

    expect(viewer.getViewportType()).to.equal('natural-ios-embed');
  });

  it('should receive viewport event', () => {
    let viewportEvent = null;
    viewer.onViewportEvent((event) => {
      viewportEvent = event;
    });
    viewer.receiveMessage('viewport', {
      scrollTop: 11,
      scrollLeft: 12,
      width: 13,
      height: 14,
      paddingTop: 19
    });
    expect(viewportEvent).to.not.equal(null);
    expect(viewer.getScrollTop()).to.equal(11);
    expect(viewer.getViewportWidth()).to.equal(13);
    expect(viewer.getViewportHeight()).to.equal(14);
    expect(viewer.getPaddingTop()).to.equal(19);
  });

  it('should receive visibilitychange event', () => {
    let visEvent = null;
    viewer.onVisibilityChanged((event) => {
      visEvent = event;
    });
    viewer.receiveMessage('visibilitychange', {
      state: 'other',
      prerenderSize: 4
    });
    expect(visEvent).to.not.equal(null);
    expect(viewer.getVisibilityState()).to.equal('other');
    expect(viewer.isVisible()).to.equal(false);
    expect(viewer.getPrerenderSize()).to.equal(4);
  });

  it('should post documentLoaded event', () => {
    viewer.postDocumentReady(11, 12);
    let m = viewer.messageQueue_[0];
    expect(m.eventType).to.equal('documentLoaded');
    expect(m.data.width).to.equal(11);
    expect(m.data.height).to.equal(12);
  });

  it('should post documentResized event', () => {
    viewer.postDocumentResized(13, 14);
    let m = viewer.messageQueue_[0];
    expect(m.eventType).to.equal('documentResized');
    expect(m.data.width).to.equal(13);
    expect(m.data.height).to.equal(14);
  });

  it('should post request/cancelFullOverlay event', () => {
    viewer.requestFullOverlay();
    viewer.cancelFullOverlay();
    expect(viewer.messageQueue_[0].eventType).to.equal('requestFullOverlay');
    expect(viewer.messageQueue_[1].eventType).to.equal('cancelFullOverlay');
  });

  it('should queue non-dupe events', () => {
    viewer.postDocumentReady(11, 12);
    viewer.postDocumentResized(13, 14);
    viewer.postDocumentResized(15, 16);
    expect(viewer.messageQueue_.length).to.equal(2);
    expect(viewer.messageQueue_[0].eventType).to.equal('documentLoaded');
    let m = viewer.messageQueue_[1];
    expect(m.eventType).to.equal('documentResized');
    expect(m.data.width).to.equal(15);
    expect(m.data.height).to.equal(16);
  });

  it('should dequeue events when deliverer set', () => {
    viewer.postDocumentReady(11, 12);
    viewer.postDocumentResized(13, 14);
    expect(viewer.messageQueue_.length).to.equal(2);

    let delivered = [];
    viewer.setMessageDeliverer((eventType, data) => {
      delivered.push({eventType: eventType, data: data});
    });

    expect(viewer.messageQueue_.length).to.equal(0);
    expect(delivered.length).to.equal(2);
    expect(delivered[0].eventType).to.equal('documentLoaded');
    expect(delivered[0].data.width).to.equal(11);
    expect(delivered[1].eventType).to.equal('documentResized');
    expect(delivered[1].data.width).to.equal(13);
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data class="GroupBinding">

        <variable
            name="title"
            type="String"/>

        <variable
            name="description"
            type="String"/>

    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        >

        <TextView
            android:id="@+id/licence_title_tv"
            style="@style/TextAppearance.AppCompat.Medium"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:text="@{title}"
            android:textStyle="bold"
            />

        <TextView
            android:id="@+id/licence_description_tv"
            style="@style/TextAppearance.AppCompat.Small"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:text="@{description}"
            />
    </LinearLayout>
</layout>

redpajama_set_name: RedPajamaGithub


text:
@interface CorrelationStateDataBase ()

@property (nonatomic , strong ) FMDatabaseQueue *queue;

@end

@implementation CorrelationStateDataBase

+(CorrelationStateDataBase *)shareDataBase{

    static CorrelationStateDataBase *dataBase;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        dataBase = [[CorrelationStateDataBase alloc]init];

    });

    return dataBase;
}

- (instancetype)init
{
    self = [super init];
    if (self) {

        //创建数据库对象

        [self createDB];

        //创建数据库表

        [self createTable];

    }
    return self;
}

#pragma mark - 创建数据库对象

- (void)createDB{

    NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;

    NSString *dbPath = [documentsPath stringByAppendingPathComponent:@"CorrelationStateDB.sqlite"];

    _queue = [FMDatabaseQueue databaseQueueWithPath:dbPath];
}

#pragma mark - 创建资讯列表的表

- (void)createTable{

    [_queue inDatabase:^(FMDatabase *db) {

        //创建表

        BOOL succeed = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS 't_correlationstate' ('type' TEXT NOT NULL , 'state' TEXT NOT NULL , 'userid' TEXT NOT NULL , 'identifier' TEXT NOT NULL , 'time' TEXT NOT NULL , PRIMARY KEY ('type' , 'state' , 'userid' , 'identifier'));"];

        if (succeed){

            NSLog(@"创建数据库t_correlationstate成功");

        } else {

            NSLog(@"创建数据库t_correlationstate失败");
        }

    }];

}

#pragma mark - 移除数据

-(BOOL)removeDataWithType:(NSInteger)type
                    State:(NSInteger)state
                   UserId:(NSString *)userId
               Identifier:(NSString *)identifier{

    __block BOOL succeed = YES;

    [_queue inDatabase:^(FMDatabase *db) {

        succeed = [db executeUpdate:@"DELETE FROM t_correlationstate WHERE type = ? AND state = ? AND userid = ? AND identifier = ?" , [NSNumber numberWithInteger:type] , [NSNumber numberWithInteger:state] , userId ? userId : @"0" , identifier];

        if (succeed){

            NSLog(@"数据库t_correlationstate删除数据成功");

        } else {

            NSLog(@"数据库t_correlationstate删除数据失败");
        }
    }];

    return succeed;
}

- (void)removeDataWithType:(NSInteger)type
                     State:(NSInteger)state
                    UserId:(NSString *)userId
                       Day:(NSInteger)day{

    [_queue inDatabase:^(FMDatabase *db) {

        if ([db executeUpdate:@"DELETE FROM t_correlationstate WHERE type = ? AND state = ? AND userid = ? AND time < ?" , [NSNumber numberWithInteger:type] , [NSNumber numberWithInteger:state] , userId ? userId : @"0" , [NSString stringWithFormat:@"%.f", [[NSDate dateWithTimeIntervalSinceNow:-(60 * 60 * 24 * day)] timeIntervalSince1970]]]){

            NSLog(@"数据库t_correlationstate删除%ld天前数据成功" , day);

        } else {

            NSLog(@"数据库t_correlationstate删除%ld天前数据失败" , day);
        }

    }];

}

- (void)removeDataWithDay:(NSInteger)day{

    [_queue inDatabase:^(FMDatabase *db) {

        if ([db executeUpdate:@"DELETE FROM t_correlationstate WHERE time < ?" , [NSString stringWithFormat:@"%.f", [[NSDate dateWithTimeIntervalSinceNow:-(60 * 60 * 24 * day)] timeIntervalSince1970]]]){

            NSLog(@"数据库t_correlationstate删除%ld天前数据成功" , day);

        } else {

            NSLog(@"数据库t_correlationstate删除%ld天前数据失败" , day);
        }

    }];

}

#pragma mark - 移除全部数据

-(BOOL)removeAllData{

    __block BOOL succeed = YES;

    [_queue inDatabase:^(FMDatabase *db) {

        succeed = [db executeUpdate:@"DELETE FROM t_correlationstate"];

        if (succeed){

            NSLog(@"删除数据库t_correlationstate成功");

        } else {

            NSLog(@"删除数据库t_correlationstate失败");
        }

    }];

    return succeed;
}

#pragma mark - 添加数据

-(BOOL)addDataWithType:(NSInteger)type
                 State:(NSInteger)state
                UserId:(NSString *)userId
            Identifier:(NSString *)identifier{

    __block BOOL succeed = NO;

    [_queue inDatabase:^(FMDatabase *db) {

        //插入数据 如果存在 则更新

        succeed = [db executeUpdate:@"REPLACE INTO 't_correlationstate' ( 'type' , 'state' , 'userid' , 'identifier' , 'time' ) VALUES ( ? , ? , ? , ? , ? );" , [NSNumber numberWithInteger:type] , [NSNumber numberWithInteger:state] , userId ? userId : @"0" , identifier , [NSString stringWithFormat:@"%.f" , [[NSDate date] timeIntervalSince1970]]];

        if (succeed){

            NSLog(@"数据库t_correlationstate添加数据成功");

        } else {

            NSLog(@"数据库t_correlationstate添加数据失败");
        }

    }];

    return succeed;
}

#pragma mark - 检查数据是否存在

- (BOOL)checkDataWithType:(NSInteger)type
                    State:(NSInteger)state
                   UserId:(NSString *)userId
               Identifier:(NSString *)identifier{

    __block BOOL result = NO;

    [_queue inDatabase:^(FMDatabase *db) {

        FMResultSet *set = [db executeQuery:@"SELECT * FROM t_correlationstate WHERE type = ? AND state = ? AND userid = ? AND identifier = ?;" , [NSNumber numberWithInteger:type] , [NSNumber numberWithInteger:state] , userId ? userId : @"0" , identifier];

        if ([set next]) {

            result = YES;
        }

        [set close];

    }];

    return result;
}

@end


text:
#include <px4_platform_common/module.h>
#include <px4_platform_common/time.h>

using namespace time_literals;

static void	usage();

extern "C" {
	__EXPORT int system_time_main(int argc, char *argv[]);
}

int
system_time_main(int argc, char *argv[])
{
	if (argc >= 2) {
		if (!strcmp(argv[1], "get")) {
			//get system time
			struct timespec ts = {};
			px4_clock_gettime(CLOCK_REALTIME, &ts);
			time_t utc_time_sec = ts.tv_sec + (ts.tv_nsec / 1e9);

			//convert to date time
			char buf[80];
			struct tm date_time;
			localtime_r(&utc_time_sec, &date_time);
			strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", &date_time);

			//get time since boot
			hrt_abstime since_boot_sec = hrt_absolute_time() / 1_s;

			PX4_INFO("Unix epoch time: %ld", (long)utc_time_sec);
			PX4_INFO("System time: %s", buf);
			PX4_INFO("Uptime (since boot): %" PRIu64 " s", since_boot_sec);
			return 0;
		}

		if (!strcmp(argv[1], "set")) {
			if (argc == 3) {
				//set system time
				struct timespec ts = {};
				ts.tv_sec = (time_t)strtoul(argv[2], nullptr, 0);
				ts.tv_nsec = 0.0;

				int res = px4_clock_settime(CLOCK_REALTIME, &ts);

				if (res == 0) {
					PX4_INFO("Successfully set system time");
					return 0;

				} else {
					PX4_ERR("Failed to set system time (%i)", res);
					return 1;
				}

			} else {
				usage();
				return 1;
			}
		}

		//unknown command
		PX4_ERR("system_time: Unknown subcommand");
		usage();
		return 1;
	}

	//not enough arguments
	PX4_ERR("system_time: not enough arguments");
	usage();
	return 1;
}

static void
usage()
{

	PRINT_MODULE_DESCRIPTION(
		R"DESCR_STR(
### Description

Command-line tool to set and get system time.

### Examples

Set the system time and read it back
$ system_time set 1600775044
$ system_time get
)DESCR_STR");

	PRINT_MODULE_USAGE_NAME("system_time", "command");
	PRINT_MODULE_USAGE_COMMAND_DESCR("set", "Set the system time, provide time in unix epoch time format");
	PRINT_MODULE_USAGE_COMMAND_DESCR("get", "Get the system time");

}


text:
package com.github.fakemongo.integration;

import com.github.fakemongo.Fongo;
import com.mongodb.Mongo;
import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;

public class SpringQueryTest {

  // Issue #92 : mixed source of date (Integer vs Long) problem.
  @Test
  public void should_mixed_data_works_in_spring() throws Exception {
    //Given
    ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(FongoConfig.class);
    QueryRepository repository = ctx.getBean(QueryRepository.class);

    //When
    DomainObject object = new DomainObject();
    ArrayList<Long> longList = new ArrayList<Long>();
    longList.add(25L);
    longList.add(10L);
    object.setLongList(longList);

    repository.save(object);

    //Then

    //Queries generated from method names always work
    assertThat(repository.findByLongList(longList)).isNotNull();
    assertThat(repository.findByLongList(10L)).isNotNull();
    assertThat(repository.findByLongList(longList)).hasSize(1);
    assertThat(repository.findByLongList(10L)).hasSize(1);

    //Hand written queries do not work on Fongo
    assertThat(repository.findLongListWithQuery(longList)).isNotNull();
    assertThat(repository.findLongListWithQuery(10L)).isNotNull();
    assertThat(repository.findLongListWithQuery(longList)).hasSize(1);
    assertThat(repository.findLongListWithQuery(10L)).hasSize(1);
    ctx.close();
  }

  @Test
  public void should_IN_query_work_in_spring() throws Exception {
    //Given
    ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(FongoConfig.class);
    QueryRepository repository = ctx.getBean(QueryRepository.class);

    DomainObject object = new DomainObject();
    object.setOther(1L);
    repository.save(object);

    DomainObject object2 = new DomainObject();
    object2.setOther(2L);
    repository.save(object2);

    DomainObject object3 = new DomainObject();
    object3.setOther(3L);
    repository.save(object3);

    // When
    final List<? extends DomainObject> withInQuery = repository.findOtherWithInQuery(Arrays.asList(1L, 2L));

    // Then
    assertEquals(2, withInQuery.size());

    ctx.close();
  }

  @Configuration
  @EnableMongoRepositories
  public static class FongoConfig extends AbstractMongoConfiguration {

    @Override
    protected String getDatabaseName() {
      return "FongoDB";
    }

    @Override
    public Mongo mongo() throws Exception {
      return new Fongo(getDatabaseName()).getMongo();
    }

  }

  @Document
  public static class DomainObject {

    @Id
    private String _id;
    private List<Long> longList;

    private Long other;

    public List<Long> getLongList() {
      return longList;
    }

    public void setLongList(List<Long> longList) {
      this.longList = longList;
    }

    public String get_id() {
      return _id;
    }

    public void set_id(String _id) {
      this._id = _id;
    }

    public Long getOther() {
      return other;
    }

    public void setOther(Long other) {
      this.other = other;
    }
  }

}

@Repository
interface QueryRepository extends MongoRepository<SpringQueryTest.DomainObject, String> {

  @Query("{'longList' : ?0}")
  List<? extends SpringQueryTest.DomainObject> findLongListWithQuery(Long foo);

  @Query("{'longList' : ?0}")
  List<? extends SpringQueryTest.DomainObject> findLongListWithQuery(List<Long> foo);

  @Query("{'other' : {$in: ?0 }}")
  List<? extends SpringQueryTest.DomainObject> findOtherWithInQuery(List<Long> foo);

  List<? extends SpringQueryTest.DomainObject> findByLongList(Long foo);

  List<? extends SpringQueryTest.DomainObject> findByLongList(List<Long> foo);
}


text:
title:  Миссионерская история
date:   01/01/2021
---

#### Обманутый

_Эндрю Макчесни_

Дьякон адвентистской церкви Валентин Зайцев никогда бы не подумал, что его обманет женщина с сыном, которых он пригласил в свой дом, — они бежали от конфликта в восточной Украине. Но он ни о чем не жалеет.

«Мы искренне служили Богу, пусть Он будет судьей между ней и нами», — говорит мужчина.

Эта история произошла в 2015 году, когда Валентин узнал, что первая волна переселенцев достигла его черноморского города Николаева. Тяжелое положение беженцев коснулось и его сердца. Поэтому Валентин, прораб по роду деятельности, отправился вместе с женой в государственное общежитие, в котором проживало пятьдесят переселенцев, по шесть—восемь человек в комнате.

Валентин представился как христианин и спросил, в чем люди нуждаются. Они сразу же попросили памперсы и влажные салфетки.

«Мы пошли в супермаркет и все купили, — рассказал Валентин. — Затем мы спросили, чем еще мы можем помочь, и они попросили нижнее белье, предметы женской гигиены и картофель. Власти дали им крышу над головой, но не более того».

Их дружба росла. Валентин начал приглашать своих новых друзей на группу по изучению Библии. Одиннадцать человек согласились изучать Писание, и адвентистский пастор каждый вечер начал проводить с ними библейские уроки. Затем в общежитии произошла драка, в которой Валерий, 19-летний парень, получил несколько ножевых ранений и был госпитализирован. Когда Валентин с женой навестили его в больнице, его мать Наташа умоляла найти им новое место для жилья. Валентин жил в трехкомнатной квартире, поэтому он предложил одну комнату для женщины и ее сына.

Какое-то время все казалось прекрасным. Наташа даже посещала адвентистскую церковь. Но затем Валентин обнаружил, что она не была «без гроша в кармане», как она утверждала, и что она пользуется добротой людей, чтобы обмануть их.

— Мы кормили ее и сына, оплачивали их мобильные телефоны, — сказал он. — Но потом мы узнали, что у них есть деньги и они не бедствуют. И тогда мы попросили их съехать.

Наташа с сыном прожили с семьей Валентина полгода.

Оглядываясь назад, Валентин говорит, что этот неприятный опыт был благословением. Наташа оказывала большую помощь по дому, готовила, убирала, сидела с их тремя детьми.

«Но самым большим благословением была возможность учиться любить ее, — говорит он. — Мы получили радость и благословения, потому что смогли послужить кому-то. Отношения в нашей семье стали еще лучше. Я бы не хотел ничего изменить из того, что произошло».

Валентин убежден, что важно помогать людям независимо от того, принимают они Иисуса или нет.

«Мы призваны служить людям, а все остальное в руках Божьих, — уверен он. — Мы поливаем семена с добротой, а Бог собирает жатву».

Часть пожертвований Тринадцатой субботы поможет в строительстве начальной и средней школы в Буче, Украина.


text:
package com.capitalone.dashboard.collector;

import com.capitalone.dashboard.client.project.ProjectDataClientImpl;
import com.capitalone.dashboard.client.story.StoryDataClientImpl;
import com.capitalone.dashboard.client.team.TeamDataClientImpl;
import com.capitalone.dashboard.model.FeatureCollector;
import com.capitalone.dashboard.repository.BaseCollectorRepository;
import com.capitalone.dashboard.repository.FeatureCollectorRepository;
import com.capitalone.dashboard.repository.FeatureRepository;
import com.capitalone.dashboard.repository.ProjectRepository;
import com.capitalone.dashboard.repository.TeamRepository;
import com.capitalone.dashboard.util.FeatureSettings;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Component;

/**
 * Collects {@link FeatureCollector} data from feature content source system.
 *
 * @author KFK884
 */
@Component
public class FeatureCollectorTask extends CollectorTask<FeatureCollector> {
	private static final Log logger = LogFactory
			.getLog(FeatureCollectorTask.class);

	private final FeatureRepository featureRepository;
	private final TeamRepository teamRepository;
	private final ProjectRepository projectRepository;
	private final FeatureCollectorRepository featureCollectorRepository;
	private final FeatureSettings featureSettings;

	/**
	 * Default constructor for the collector task. This will construct this
	 * collector task with all repository, scheduling, and settings
	 * configurations custom to this collector.
	 *
	 * @param taskScheduler
	 *            A task scheduler artifact
	 * @param teamRepository
	 *            The repository being use for feature collection
	 * @param featureSettings
	 *            The settings being used for feature collection from the source
	 *            system
	 */
	@Autowired
	public FeatureCollectorTask(TaskScheduler taskScheduler,
			FeatureRepository featureRepository, TeamRepository teamRepository,
			ProjectRepository projectRepository,
			FeatureCollectorRepository featureCollectorRepository,
			FeatureSettings featureSettings) {
		super(taskScheduler, "Jira");
		this.featureCollectorRepository = featureCollectorRepository;
		this.teamRepository = teamRepository;
		this.projectRepository = projectRepository;
		this.featureRepository = featureRepository;
		this.featureSettings = featureSettings;
	}

	/**
	 * Accessor method for the collector prototype object
	 */
	@Override
	public FeatureCollector getCollector() {
		return FeatureCollector.prototype();
	}

	/**
	 * Accessor method for the collector repository
	 */
	@Override
	public BaseCollectorRepository<FeatureCollector> getCollectorRepository() {
		return featureCollectorRepository;
	}

	/**
	 * Accessor method for the current chronology setting, for the scheduler
	 */
	@Override
	public String getCron() {
		return featureSettings.getCron();
	}

	/**
	 * The collection action. This is the task which will run on a schedule to
	 * gather data from the feature content source system and update the
	 * repository with retrieved data.
	 */
	@Override
	public void collect(FeatureCollector collector) {
		logger.info("Starting Feature collection...");

		TeamDataClientImpl teamData = new TeamDataClientImpl(
				this.featureCollectorRepository, this.featureSettings,
				this.teamRepository);
		teamData.updateTeamInformation();

		ProjectDataClientImpl projectData = new ProjectDataClientImpl(
				this.featureSettings, this.projectRepository,
				this.featureCollectorRepository);
		projectData.updateProjectInformation();

		StoryDataClientImpl storyData = new StoryDataClientImpl(
				this.featureSettings, this.featureRepository,
				this.featureCollectorRepository);
		storyData.updateStoryInformation();

		logger.info("Feature Data Collection Finished");
	}
}


text:
import sys
import logging
import argparse
import threading
import time
import os
import errno
import importlib
from six.moves import queue

from captain_comeback.index import CgroupIndex
from captain_comeback.cgroup import Cgroup
from captain_comeback.restart.engine import RestartEngine, restart
from captain_comeback.activity.engine import ActivityEngine

logger = logging.getLogger()

DEFAULT_ROOT_CG = "/sys/fs/cgroup/memory/docker"
DEFAULT_ACTIVITY_DIR = "/var/log/container-activity"
DEFAULT_SYNC_TARGET_INTERVAL = 1
DEFAULT_RESTART_ADAPTER = "captain_comeback.restart.adapter.docker"
DEFAULT_RESTART_GRACE_PERIOD = 10

def run_loop(root_cg_path, activity_path, sync_target_interval,
             restart_adapter, restart_grace_period):
    threading.current_thread().name = "index"

    job_queue = queue.Queue()
    activity_queue = queue.Queue()
    index = CgroupIndex(root_cg_path, job_queue, activity_queue)
    index.open()

    restarter = RestartEngine(restart_adapter, restart_grace_period, job_queue,
                              activity_queue)
    restarter_thread = threading.Thread(target=restarter.run, name="restarter")
    restarter_thread.daemon = True

    activity = ActivityEngine(activity_path, activity_queue)
    activity_thread = threading.Thread(target=activity.run, name="activity")
    activity_thread.daemon = True

    # Now, fire an initial sync, then empty the activity queue (we don't want
    # to fire notifications for "new" containers if Captain Comeback is the one
    # that's starting), and start all worker threads.
    index.sync()

    while True:
        try:
            activity_queue.get_nowait()
        except queue.Empty:
            break

    restarter_thread.start()
    activity_thread.start()

    while True:
        index.sync()
        next_sync = time.time() + sync_target_interval
        while True:
            poll_timeout = next_sync - time.time()
            if poll_timeout <= 0:
                break
            logger.debug("poll with timeout: %s", poll_timeout)

            try:
                index.poll(poll_timeout)
            except IOError as e:
                if e.errno != errno.EINTR:
                    raise
                logger.warning("interrupted")

        for thread in [activity_thread, restarter_thread]:
            if not thread.is_alive():
                logger.critical("thread %s is dead", thread.name)
                return 1

    return 0

def restart_one(root_cg_path, restart_adapter, restart_grace_period,
                container_id):
    q = queue.Queue()
    cg = Cgroup(os.path.join(root_cg_path, container_id))

    try:
        restart(restart_adapter, restart_grace_period, cg, q, q)
    except IOError:
        logger.error("%s: container does not exist", cg.name())
        return 1
    finally:
        while not q.empty():
            m = q.get()
            logger.debug("%s: received %s", cg.name(), m.__class__.__name__)

    return 0

def main_wrapper(args):
    desc = "Autorestart containers that exceed their memory allocation"
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument("--root-cg",
                        default=DEFAULT_ROOT_CG,
                        help="parent cgroup (children will be monitored)")
    parser.add_argument("--activity",
                        default=DEFAULT_ACTIVITY_DIR,
                        help="where to log activity")
    parser.add_argument("--sync-interval",
                        default=DEFAULT_SYNC_TARGET_INTERVAL, type=float,
                        help="target sync interval to refresh cgroups")
    parser.add_argument("--restart-adapter",
                        default=DEFAULT_RESTART_ADAPTER, type=str,
                        help="module must expose thread safe restart function")
    parser.add_argument("--restart-grace-period",
                        default=DEFAULT_RESTART_GRACE_PERIOD, type=int,
                        help="how long to wait before sending SIGKILL")
    parser.add_argument("--debug", default=False, action="store_true",
                        help="enable debug logging")
    parser.add_argument("--restart", dest="container_id",
                        help="restart one container and exit")
    parser.add_argument("--wipe-fs", default=False, action="store_true",
                        help="wipe filesystems on restart (use adapter)")

    ns = parser.parse_args(args)

    log_level = logging.DEBUG if ns.debug else logging.INFO
    log_format = "%(asctime)-15s %(levelname)-8s %(threadName)-10s -- " \
                 "%(message)s"
    logging.basicConfig(level=log_level, format=log_format)
    logger.setLevel(log_level)

    sync_interval = ns.sync_interval
    if sync_interval < 0:
        logger.warning("invalid sync interval %s, must be > 0", sync_interval)
        sync_interval = DEFAULT_SYNC_TARGET_INTERVAL

    if ns.wipe_fs:
        if ns.restart_adapter == DEFAULT_RESTART_ADAPTER:
            ns.restart_adapter = "{0}_wipe_fs".format(DEFAULT_RESTART_ADAPTER)
        else:
            logger.error("--wipe-fs compatibility requires default adapter")
            return 1

    logger.info("using restart adapter: %s", ns.restart_adapter)
    restart_adapter = importlib.import_module(ns.restart_adapter)

    restart_grace_period = ns.restart_grace_period
    if restart_grace_period < 0:
        logger.warning("invalid restart grace period %s, must be > 0",
                       restart_grace_period)
        restart_grace_period = DEFAULT_RESTART_GRACE_PERIOD

    # If the --restart argument is present, just restart one container and
    # exit.
    if ns.container_id:
        return restart_one(ns.root_cg, restart_adapter, restart_grace_period,
                           ns.container_id)

    # Otherwise the --restart argument was not there, start the main loop.
    return run_loop(ns.root_cg, ns.activity, sync_interval,
                    restart_adapter, restart_grace_period)

def cli_entrypoint():
    sys.exit(main_wrapper(sys.argv[1:]))

if __name__ == "__main__":
    cli_entrypoint()


text:
package org.apache.camel.component.influxdb;

import org.apache.camel.Exchange;
import org.apache.camel.InvalidPayloadException;
import org.apache.camel.support.DefaultProducer;
import org.apache.camel.support.MessageHelper;
import org.apache.camel.util.ObjectHelper;
import org.influxdb.InfluxDB;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;

/**
 * Producer for the InfluxDB components
 *
 */
public class InfluxDbProducer extends DefaultProducer {

    InfluxDbEndpoint endpoint;
    InfluxDB connection;

    public InfluxDbProducer(InfluxDbEndpoint endpoint) {
        super(endpoint);

        if (ObjectHelper.isEmpty(endpoint.getInfluxDB())) {
            throw new IllegalArgumentException("Can't create a producer when the database connection is null");
        }

        this.connection = endpoint.getInfluxDB();
        this.endpoint = endpoint;
    }

    /**
     * Processes the message exchange
     *
     * @param exchange the message exchange
     * @throws Exception if an internal processing error has occurred.
     */
    @Override
    public void process(Exchange exchange) throws Exception {

        String dataBaseName = calculateDatabaseName(exchange);
        String retentionPolicy = calculateRetentionPolicy(exchange);
        switch (endpoint.getOperation()) {
        case InfluxDbOperations.INSERT:
            doInsert(exchange, dataBaseName, retentionPolicy);
            break;
        case InfluxDbOperations.QUERY:
            doQuery(exchange, dataBaseName, retentionPolicy);
            break;
        default:
            throw new IllegalArgumentException("The operation " + endpoint.getOperation() + " is not supported");
        }
    }

    private void doInsert(Exchange exchange, String dataBaseName, String retentionPolicy) throws InvalidPayloadException {
        if (!endpoint.isBatch()) {
            Point p = exchange.getIn().getMandatoryBody(Point.class);

            try {
                log.debug("Writing point {}", p.lineProtocol());

                if (!connection.databaseExists(dataBaseName)) {
                    log.debug("Database {} doesn't exist. Creating it...", dataBaseName);
                    connection.createDatabase(dataBaseName);
                }
                connection.write(dataBaseName, retentionPolicy, p);
            } catch (Exception ex) {
                exchange.setException(new CamelInfluxDbException(ex));
            }
        } else {
            BatchPoints batchPoints = exchange.getIn().getMandatoryBody(BatchPoints.class);

            try {
                log.debug("Writing BatchPoints {}", batchPoints.lineProtocol());

                connection.write(batchPoints);
            } catch (Exception ex) {
                exchange.setException(new CamelInfluxDbException(ex));
            }
        }
    }

    private void doQuery(Exchange exchange, String dataBaseName, String retentionPolicy) {
        String query = calculateQuery(exchange);
        Query influxdbQuery = new Query(query, dataBaseName);
        QueryResult resultSet = connection.query(influxdbQuery);
        MessageHelper.copyHeaders(exchange.getIn(), exchange.getOut(), true);
        exchange.getOut().setBody(resultSet);
    }

    private String calculateRetentionPolicy(Exchange exchange) {
        String retentionPolicy = exchange.getIn().getHeader(InfluxDbConstants.RETENTION_POLICY_HEADER, String.class);

        if (ObjectHelper.isNotEmpty(retentionPolicy)) {
            return retentionPolicy;
        }

        return endpoint.getRetentionPolicy();
    }

    private String calculateDatabaseName(Exchange exchange) {
        String dbName = exchange.getIn().getHeader(InfluxDbConstants.DBNAME_HEADER, String.class);

        if (ObjectHelper.isNotEmpty(dbName)) {
            return dbName;
        }

        return endpoint.getDatabaseName();
    }

    private String calculateQuery(Exchange exchange) {
        String query = exchange.getIn().getHeader(InfluxDbConstants.INFLUXDB_QUERY, String.class);

        if (ObjectHelper.isNotEmpty(query)) {
            return query;
        } else {
            query = endpoint.getQuery();
        }

        if (ObjectHelper.isEmpty(query)) {
            throw new IllegalArgumentException("The query option must be set if you want to run a query operation");
        }
        return query;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:layout_marginStart="12dp"
        android:layout_marginEnd="12dp"
        android:orientation="vertical"
        card_view:cardElevation="1dp"
        card_view:cardCornerRadius="6dp"
        card_view:cardBackgroundColor="@color/cardview_light_background">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <android.support.v4.widget.NestedScrollView
                android:layout_width="match_parent"
                android:layout_height="300dp"
                >
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center_horizontal"
                    android:paddingTop="36dp"
                    android:paddingStart="24dp"
                    android:paddingEnd="24dp"
                    android:paddingBottom="48dp"
                    android:textSize="@dimen/text_size_small"
                    android:text="协议"/>
            </android.support.v4.widget.NestedScrollView>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@color/color_divider"/>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="48dp"
                android:padding="12dp"
                android:gravity="center_vertical"
                >
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:textColor="#4C4C4C"
                    android:textSize="@dimen/text_size_medium"
                    android:text="@string/settings_ue_improvement"/>

                <android.support.v7.widget.SwitchCompat
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

        </LinearLayout>
    </android.support.v7.widget.CardView>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="12dp"
        android:layout_marginEnd="12dp"
        android:text="为了改善产品的用户体验,RxTwitch会针对各个功能的使用情况进行统计,但绝不会涉及用户的隐私数据。"/>
</LinearLayout>


text:
package org.jboss.resteasy.plugins.providers.jaxb.json;

import org.jboss.resteasy.plugins.providers.jaxb.JAXBXmlRootElementProvider;

import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.ext.Provider;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
@Provider
@Produces("application/*+json")
@Consumes("application/*+json")
public class JettisonXmlRootElementProvider extends JAXBXmlRootElementProvider
{
   @Override
   protected boolean needsSecurity()
   {
      return false;
   }
}


text:
package org.apache.harmony.jndi.tests.javax.naming.spi;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Properties;

import javax.naming.CompositeName;
import javax.naming.CompoundName;
import javax.naming.InvalidNameException;
import javax.naming.Name;
import javax.naming.spi.ResolveResult;

import junit.framework.TestCase;

public class ResolveResultTest extends TestCase {

	private String strObj;

	private String strName;

	private CompositeName name;

	@Override
    protected void setUp() throws InvalidNameException {
		strObj = "String object";
		strName = "www.eclipse.org/org/index.html";
		name = new CompositeName(strName);
	}

	public void testConstructor_NoParms() {
		MyResolveResult resolveResult = new MyResolveResult();
		assertNull(resolveResult.getResolvedObj());
		assertNull(resolveResult.getRemainingName());
	}

	public void tsetConstructor_Simple() throws InvalidNameException {
		CompositeName expectedName = new CompositeName(strName);
		ResolveResult resolveResult = new ResolveResult(strObj, strName);

		assertEquals(strObj, resolveResult.getResolvedObj());
		assertEquals(expectedName, resolveResult.getRemainingName());
	}

	public void testConstructor_SimpleNull() {
		strName = null;
		try {
			new ResolveResult(null, strName);
			fail("Should throw NullPointerException.");
		} catch (NullPointerException e) {
		}
	}

	public void testConstructor_ByName() {
		ResolveResult resolveResult = new ResolveResult(strObj, strName);

		assertEquals(strObj, resolveResult.getResolvedObj());
		assertEquals(name, resolveResult.getRemainingName());
		// TO DO R: Is name is cloned? Confirm: yes.
		assertSame(strObj, resolveResult.getResolvedObj());
		assertNotSame(name, resolveResult.getRemainingName());
	}

	public void testConstructor_ByNameNull() {
		/*
		 * try { ResolveResult resolveResult = new ResolveResult(strObj,
		 * (Name)null); fail("Should throw NullPointerException."); } catch
		 * (NullPointerException e) { }
		 */

		ResolveResult resolveResult = new ResolveResult(strObj, (Name) null);
		assertNull(resolveResult.getRemainingName());
		assertSame(strObj, resolveResult.getResolvedObj());
	}

	public void testConstructor_ByNameObjectNull() {
		ResolveResult resolveResult = new ResolveResult(null, name);
		assertNull(resolveResult.getResolvedObj());
	}

	public void testConstructor_InvalidName() {
		strName = "a/'a/b/b";
		ResolveResult resolveResult = new ResolveResult(strObj, strName);

		assertNull(resolveResult.getRemainingName());
		assertEquals(strObj, resolveResult.getResolvedObj());
	}

	public void testConstrcutor_ByCompoundName() throws InvalidNameException {
		Properties props = new Properties();
		props.put("jndi.syntax.separator", "/");
		props.put("jndi.syntax.direction", "left_to_right");
		props.put("jndi.syntax.escape", "\\");
		props.put("jndi.syntax.beginquote", "<");
		props.put("jndi.syntax.endquote", ">");
		props.put("jndi.syntax.beginquote2", "'");
		props.put("jndi.syntax.endquote2", "'");
		props.put("jndi.syntax.ignorecase", "false");
		props.put("jndi.syntax.trimblanks", "false");
		CompoundName compoundName = new CompoundName("a", props);

		ResolveResult resolveResult = new ResolveResult(strObj, compoundName);
		assertEquals(strObj, resolveResult.getResolvedObj());
		assertEquals(compoundName, resolveResult.getRemainingName());
	}

	public void testAppendRemainingComponent() throws InvalidNameException {
		ResolveResult resolveResult = new ResolveResult(strObj, name);
		String nameComponent = "abc";
		resolveResult.appendRemainingComponent(nameComponent);

		assertEquals(strObj, resolveResult.getResolvedObj());
		name.add(nameComponent);
		assertEquals(name, resolveResult.getRemainingName());
	}

	public void testAppendRemainingComponent_Null() {
		ResolveResult resolveResult = new ResolveResult(strObj, name);
		resolveResult.appendRemainingComponent(null);

		assertEquals(strObj, resolveResult.getResolvedObj());
		assertEquals(name, resolveResult.getRemainingName());
	}

	public void testAppendRemainingComponent_InvalidName()
			throws InvalidNameException {
		ResolveResult resolveResult = new ResolveResult(strObj, name);
		String nameComponent = "a/'a/b/b";
		resolveResult.appendRemainingComponent(nameComponent);

		assertEquals(strObj, resolveResult.getResolvedObj());
		name.add(nameComponent);

		assertEquals(name, resolveResult.getRemainingName());
		// Impossible to throw exception
	}

	public void testAppendRemainingComponent_NullRemainingName()
			throws InvalidNameException {
		ResolveResult resolveResult = new ResolveResult(strObj, (Name) null);
		String nameComponent = "a/'a/b'/b";
		CompositeName newName = new CompositeName();
		newName.add(nameComponent);
		resolveResult.appendRemainingComponent(nameComponent);

		assertEquals(newName, resolveResult.getRemainingName());
	}

	public void testAppendRemainingName() throws InvalidNameException {
		ResolveResult resolveResult = new ResolveResult(strObj, name);

		CompositeName newName = new CompositeName("a/b/c/d");
		resolveResult.appendRemainingName(newName);

		assertEquals(strObj, resolveResult.getResolvedObj());
		name.addAll(newName);
		assertEquals(name, resolveResult.getRemainingName());
	}

	public void testAppendRemainingName_Null() {
		ResolveResult resolveResult = new ResolveResult(strObj, name);
		resolveResult.appendRemainingName(null);

		assertEquals(strObj, resolveResult.getResolvedObj());
		assertEquals(name, resolveResult.getRemainingName());
	}

	public void testAppendRemainingName_InvalidName()
			throws InvalidNameException {
		ResolveResult resolveResult = new ResolveResult(strObj, name);

		Properties props = new Properties();
		props.put("jndi.syntax.separator", "/");
		props.put("jndi.syntax.direction", "left_to_right");
		props.put("jndi.syntax.escape", "\\");
		props.put("jndi.syntax.beginquote", "<");
		props.put("jndi.syntax.endquote", ">");
		props.put("jndi.syntax.beginquote2", "'");
		props.put("jndi.syntax.endquote2", "'");
		props.put("jndi.syntax.ignorecase", "false");
		props.put("jndi.syntax.trimblanks", "false");
		CompoundName compoundName = new CompoundName("a", props);
		try {
			resolveResult.appendRemainingName(compoundName);
			fail("Should throw a Error.");
		} catch (Error e) {
		}
	}

	public void testAppendRemainingName_withCompoundName()
			throws InvalidNameException {
		Properties props = new Properties();
		props.put("jndi.syntax.separator", "/");
		props.put("jndi.syntax.direction", "left_to_right");
		props.put("jndi.syntax.escape", "\\");
		props.put("jndi.syntax.beginquote", "<");
		props.put("jndi.syntax.endquote", ">");
		props.put("jndi.syntax.beginquote2", "'");
		props.put("jndi.syntax.endquote2", "'");
		props.put("jndi.syntax.ignorecase", "false");
		props.put("jndi.syntax.trimblanks", "false");
		CompoundName compoundName = new CompoundName("a", props);

		ResolveResult resolveResult = new ResolveResult(strObj, compoundName);
		CompositeName newName = new CompositeName("a/b/c/d");
		try {
			resolveResult.appendRemainingName(newName);
			fail("Should throw a Error here.");
		} catch (Error e) {
		}

		// compoundName.addAll(newName);
		// assertEquals(compoundName, resolveResult.getRemainingName());
	}

	public void testAppendRemainingName_withCompoundName2()
			throws InvalidNameException {
		Properties props = new Properties();
		props.put("jndi.syntax.separator", "/");
		props.put("jndi.syntax.direction", "left_to_right");
		props.put("jndi.syntax.escape", "\\");
		props.put("jndi.syntax.beginquote", "<");
		props.put("jndi.syntax.endquote", ">");
		props.put("jndi.syntax.beginquote2", "'");
		props.put("jndi.syntax.endquote2", "'");
		props.put("jndi.syntax.ignorecase", "false");
		props.put("jndi.syntax.trimblanks", "false");
		CompoundName compoundName = new CompoundName("a", props);

		ResolveResult resolveResult = new ResolveResult(strObj, compoundName);
		CompoundName newName = new CompoundName("b", props);
		resolveResult.appendRemainingName(newName);

		compoundName.addAll(newName);
		assertEquals(compoundName, resolveResult.getRemainingName());
	}

	public void testAppendRemainingName_NullRemainingName()
			throws InvalidNameException {
		ResolveResult resolveResult = new ResolveResult(strObj, (Name) null);
		String nameComponent = "a/'a/b'/b";
		CompositeName newName = new CompositeName();
		newName.add(nameComponent);
		resolveResult.appendRemainingName(newName);

		assertEquals(newName, resolveResult.getRemainingName());
		assertNotSame(newName, resolveResult.getRemainingName());
	}

	public void testSetRemainingName() throws InvalidNameException {
		ResolveResult resolveResult = new ResolveResult(strObj, name);
		name.add("1/2/3/4");
		resolveResult.setRemainingName(name);

		assertNotSame(name, resolveResult.getRemainingName());
		assertEquals(strObj, resolveResult.getResolvedObj());
		assertEquals(name, resolveResult.getRemainingName());
		name.remove(name.size() - 1);
		assertFalse(name.equals(resolveResult.getRemainingName()));
	}

	public void testSetRemainingName_Null() {
		ResolveResult resolveResult = new ResolveResult(strObj, name);
		resolveResult.setRemainingName(null);
		assertNull(resolveResult.getRemainingName());
	}

	public void testSetRemainingName_InvalidName() throws InvalidNameException {
		ResolveResult resolveResult = new ResolveResult(strObj, name);

		Properties props = new Properties();
		props.put("jndi.syntax.separator", "/");
		props.put("jndi.syntax.direction", "left_to_right");
		props.put("jndi.syntax.escape", "\\");
		props.put("jndi.syntax.beginquote", "<");
		props.put("jndi.syntax.endquote", ">");
		props.put("jndi.syntax.beginquote2", "'");
		props.put("jndi.syntax.endquote2", "'");
		props.put("jndi.syntax.ignorecase", "false");
		props.put("jndi.syntax.trimblanks", "false");
		CompoundName compoundName = new CompoundName("a", props);

		resolveResult.setRemainingName(compoundName);
		assertEquals(compoundName, resolveResult.getRemainingName());
	}

	public void testSetRemainingName_withCompoundName()
			throws InvalidNameException {
		ResolveResult resolveResult = new ResolveResult(strObj, name);

		Properties props = new Properties();
		props.put("jndi.syntax.separator", "/");
		props.put("jndi.syntax.direction", "left_to_right");
		props.put("jndi.syntax.escape", "\\");
		props.put("jndi.syntax.beginquote", "<");
		props.put("jndi.syntax.endquote", ">");
		props.put("jndi.syntax.beginquote2", "'");
		props.put("jndi.syntax.endquote2", "'");
		props.put("jndi.syntax.ignorecase", "false");
		props.put("jndi.syntax.trimblanks", "false");
		CompoundName compoundName = new CompoundName("a", props);

		resolveResult.setRemainingName(compoundName);

		CompositeName newName = new CompositeName("a/b/c/d");
		try {
			resolveResult.appendRemainingName(newName);
			fail("Should throw a Error here");
		} catch (Error e) {
		}
		// compoundName.addAll(newName);
		// assertEquals(compoundName, resolveResult.getRemainingName());
	}

	public void testSetRemainingName_withCompoundName2()
			throws InvalidNameException {
		ResolveResult resolveResult = new ResolveResult(strObj, name);

		Properties props = new Properties();
		props.put("jndi.syntax.separator", "/");
		props.put("jndi.syntax.direction", "left_to_right");
		props.put("jndi.syntax.escape", "\\");
		props.put("jndi.syntax.beginquote", "<");
		props.put("jndi.syntax.endquote", ">");
		props.put("jndi.syntax.beginquote2", "'");
		props.put("jndi.syntax.endquote2", "'");
		props.put("jndi.syntax.ignorecase", "false");
		props.put("jndi.syntax.trimblanks", "false");
		CompoundName compoundName = new CompoundName("a", props);

		resolveResult.setRemainingName(compoundName);

		CompoundName newName = new CompoundName("b", props);
		resolveResult.appendRemainingName(newName);

		compoundName.addAll(newName);
		assertEquals(compoundName, resolveResult.getRemainingName());
	}

	public void testSetResolvedObj() {
		ResolveResult resolveResult = new ResolveResult(strObj, name);
		Integer intObj = new Integer(123456);
		resolveResult.setResolvedObj(intObj);

		assertEquals(intObj, resolveResult.getResolvedObj());
		assertSame(intObj, resolveResult.getResolvedObj());
	}

	public void testGetRemainingName() throws InvalidNameException {
		CompositeName expectedName = new CompositeName(strName);
		ResolveResult resolveResult = new ResolveResult(strObj, strName);

		assertEquals(expectedName, resolveResult.getRemainingName());
	}

	public void testGetResolvedObj() throws InvalidNameException {
		ResolveResult resolveResult = new ResolveResult(strObj, strName);
		assertEquals(strObj, resolveResult.getResolvedObj());
	}

	public void testSerializable_Simple() throws ClassNotFoundException,
			IOException {
		ResolveResult resolveResult = new ResolveResult(strObj, strName);

		// write to byte array
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(resolveResult);
		byte[] buffer = baos.toByteArray();
		oos.close();
		baos.close();

		// read from byte array
		ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
		ObjectInputStream ois = new ObjectInputStream(bais);
		ResolveResult resolveResult2 = (ResolveResult) ois.readObject();
		ois.close();
		bais.close();

		assertEquals(resolveResult.getResolvedObj(), resolveResult2
				.getResolvedObj());
		assertEquals(resolveResult.getRemainingName(), resolveResult2
				.getRemainingName());
	}

	public void testSerializable_compatibility() throws ClassNotFoundException,
			IOException {
		ObjectInputStream ois = new ObjectInputStream(getClass()
                .getClassLoader().getResourceAsStream(
                        "/serialization/javax/naming/spi/ResolveResult.ser"));
		ResolveResult resolveResult2 = (ResolveResult) ois.readObject();
		ois.close();

		ResolveResult resolveResult = new ResolveResult(strObj, strName);

		assertEquals(resolveResult.getResolvedObj(), resolveResult2
				.getResolvedObj());
		assertEquals(resolveResult.getRemainingName(), resolveResult2
				.getRemainingName());
	}

	class MyResolveResult extends ResolveResult {
		/**
         *

         */
        private static final long serialVersionUID = 1L;

        public MyResolveResult() {
			super();
		}
	}
}


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

// Copyright 2008 Google Inc. All Rights Reserved.

/**
 * @fileoverview Provides functions to parse and pretty-print HTML strings.
 *
 */

goog.provide('goog.format.HtmlPrettyPrinter');
goog.provide('goog.format.HtmlPrettyPrinter.Buffer');

goog.require('goog.object');
goog.require('goog.string.StringBuffer');

/**
 * This class formats HTML to be more human-readable.
 * TODO: Add hierarchical indentation.
 * @param {number} opt_timeOutMillis Max # milliseconds to spend on #format. If
 *     this time is exceeded, return partially formatted. 0 or negative number
 *     indicates no timeout.
 * @constructor
 */
goog.format.HtmlPrettyPrinter = function(opt_timeOutMillis) {
  /**
   * Max # milliseconds to spend on #format.
   * @type {number}
   * @private
   */
  this.timeOutMillis_ = opt_timeOutMillis && opt_timeOutMillis > 0 ?
      opt_timeOutMillis : 0;
};

/**
 * Singleton.
 * @type {goog.format.HtmlPrettyPrinter?}
 * @private
 */
goog.format.HtmlPrettyPrinter.instance_ = null;

/**
 * Singleton lazy initializer.
 * @return {goog.format.HtmlPrettyPrinter} Singleton.
 * @private
 */
goog.format.HtmlPrettyPrinter.getInstance_ = function() {
  if (!goog.format.HtmlPrettyPrinter.instance_) {
    goog.format.HtmlPrettyPrinter.instance_ =
        new goog.format.HtmlPrettyPrinter();
  }
  return goog.format.HtmlPrettyPrinter.instance_;
};

/**
 * Static utility function. See prototype #format.
 * @param {string} html The HTML text to pretty print.
 * @return {string} Formatted result.
 */
goog.format.HtmlPrettyPrinter.format = function(html) {
  return goog.format.HtmlPrettyPrinter.getInstance_().format(html);
};

/**
 * List of patterns used to tokenize HTML for pretty printing. Cache
 * subexpression for tag name.
 * comment|meta-tag|tag|text|other-less-than-characters
 * @type {RegExp}
 * @private
 */
goog.format.HtmlPrettyPrinter.TOKEN_REGEX_ =
    /(?:<!--.*?-->|<!.*?>|<(\/?)(\w+)[^>]*>|[^<]+|<)/g;

/**
 * Tags whose contents we don't want pretty printed.
 * @type {Object}
 * @private
 */
goog.format.HtmlPrettyPrinter.NON_PRETTY_PRINTED_TAGS_ = goog.object.createSet(
    'script',
    'style',
    'pre',
    'xmp');

/**
 * 'Block' tags. We should add newlines before and after these tags during
 * pretty printing. Tags drawn mostly from HTML4 definitions for block and other
 * non-online tags, excepting the ones in
 * #goog.format.HtmlPrettyPrinter.NON_PRETTY_PRINTED_TAGS_.
 *
 * @type {Object}
 * @private
 */
goog.format.HtmlPrettyPrinter.BLOCK_TAGS_ = goog.object.createSet(
    'address',
    'applet',
    'area',
    'base',
    'basefont',
    'blockquote',
    'body',
    'caption',
    'center',
    'col',
    'colgroup',
    'dir',
    'div',
    'dl',
    'fieldset',
    'form',
    'frame',
    'frameset',
    'h1',
    'h2',
    'h3',
    'h4',
    'h5',
    'h6',
    'head',
    'hr',
    'html',
    'iframe',
    'isindex',
    'legend',
    'link',
    'menu',
    'meta',
    'noframes',
    'noscript',
    'ol',
    'optgroup',
    'option',
    'p',
    'param',
    'table',
    'tbody',
    'td',
    'tfoot',
    'th',
    'thead',
    'title',
    'tr',
    'ul');

/**
 * Non-block tags that break flow. We insert a line break after, but not before
 * these. Tags drawn from HTML4 definitions.
 * @type {Object}
 * @private
 */
goog.format.HtmlPrettyPrinter.BREAKS_FLOW_TAGS_ = goog.object.createSet(
    'br',
    'dd',
    'dt',
    'br',
    'li',
    'noframes');

/**
 * Empty tags. These are treated as both start and end tags.
 * @type {Object}
 * @private
 */
goog.format.HtmlPrettyPrinter.EMPTY_TAGS_ = goog.object.createSet(
    'br',
    'hr',
    'isindex');

/**
 * Breaks up HTML so it's easily readable by the user.
 * @param {string} html The HTML text to pretty print.
 * @return {string} Formatted result.
 * @throws {Error} Regex error, data loss, or endless loop detected.
 */
goog.format.HtmlPrettyPrinter.prototype.format = function(html) {
  // Trim leading whitespace, but preserve first indent; in other words, keep
  // any spaces immediately before the first non-whitespace character (that's
  // what $1 is), but remove all other leading whitespace. This adjustment
  // historically had been made in Docs. The motivation is that some
  // browsers prepend several line breaks in designMode.
  html = html.replace(/^\s*?( *\S)/, '$1');

  // Trim trailing whitespace.
  html = html.replace(/\s+$/, '');

  // Keep track of how much time we've used.
  var timeOutMillis = this.timeOutMillis_;
  var startMillis = timeOutMillis ? goog.now() : 0;

  // Handles concatenation of the result and required line breaks.
  var buffer = new goog.format.HtmlPrettyPrinter.Buffer();

  // Declare these for efficiency since we access them in a loop.
  var tokenRegex = goog.format.HtmlPrettyPrinter.TOKEN_REGEX_;
  var nonPpTags = goog.format.HtmlPrettyPrinter.NON_PRETTY_PRINTED_TAGS_;
  var blockTags = goog.format.HtmlPrettyPrinter.BLOCK_TAGS_;
  var breaksFlowTags = goog.format.HtmlPrettyPrinter.BREAKS_FLOW_TAGS_;
  var emptyTags = goog.format.HtmlPrettyPrinter.EMPTY_TAGS_;

  // Used to verify we're making progress through our regex tokenization.
  var lastIndex = 0;

  // Use this to track non-pretty-printed tags and childen.
  var nonPpTagStack = [];

  // Loop through each matched token.
  var match;
  while (match = tokenRegex.exec(html)) {
    // Get token.
    var token = match[0];

    // Is this token a tag? match.length == 3 for tags, 1 for all others.
    if (match.length == 3) {
      var tagName = match[2];
      if (tagName) {
        tagName = tagName.toLowerCase();
      }

      // Non-pretty-printed tags?
      if (nonPpTags.hasOwnProperty(tagName)) {
        // End tag?
        if (match[1] == '/') {
          // Do we have a matching start tag?
          var stackSize = nonPpTagStack.length;
          var startTagName = stackSize ? nonPpTagStack[stackSize - 1] : null;
          if (startTagName == tagName) {
            // End of non-pretty-printed block. Line break after.
            nonPpTagStack.pop();
            buffer.pushToken(false, token, !nonPpTagStack.length);
          } else {
            // Malformed HTML. No line breaks.
            buffer.pushToken(false, token, false);
          }
        } else {
          // Start of non-pretty-printed block. Line break before.
          buffer.pushToken(!nonPpTagStack.length, token, false);
          nonPpTagStack.push(tagName);
        }
      } else if (nonPpTagStack.length) {
        // Inside non-pretty-printed block, no new line breaks.
        buffer.pushToken(false, token, false);
      } else if (blockTags.hasOwnProperty(tagName)) {
        // Put line break before start block and after end block tags.
        var isEmpty = emptyTags.hasOwnProperty(tagName);
        var isEndTag = match[1] == '/';
        buffer.pushToken(isEmpty || !isEndTag, token, isEmpty || isEndTag);
      } else if (breaksFlowTags.hasOwnProperty(tagName)) {
        var isEmpty = emptyTags.hasOwnProperty(tagName);
        var isEndTag = match[1] == '/';
        // Put line break after end flow-breaking tags.
        buffer.pushToken(false, token, isEndTag || isEmpty);
      } else {
        // All other tags, no line break.
        buffer.pushToken(false, token, false);
      }
    } else {
      // Non-tags, no line break.
      buffer.pushToken(false, token, false);
    }

    // Double check that we're making progress.
    var newLastIndex = tokenRegex.lastIndex;
    if (!token || newLastIndex <= lastIndex) {
      throw Error('Regex failed to make progress through source html.');
    }
    lastIndex = newLastIndex;

    // Out of time?
    if (timeOutMillis) {
      if (goog.now() - startMillis > timeOutMillis) {
        // Push unprocessed data as one big token and reset regex object.
        buffer.pushToken(false, html.substring(tokenRegex.lastIndex), false);
        tokenRegex.lastIndex = 0;
        break;
      }
    }
  }

  // Ensure we end in a line break.
  buffer.lineBreak();

  // Construct result string.
  var result = String(buffer);

  // Length should be original length plus # line breaks added.
  var expectedLength = html.length + buffer.breakCount;
  if (result.length != expectedLength) {
    throw Error('Lost data pretty printing html.');
  }

  return result;
};

/**
 * This class is a buffer to which we push our output. It tracks line breaks to
 * make sure we don't add unnecessary ones.
 * @constructor
 */
goog.format.HtmlPrettyPrinter.Buffer = function() {
  /**
   * Tokens to be output in #toString.
   * @type {goog.string.StringBuffer}
   * @private
   */
  this.out_ = new goog.string.StringBuffer();
};

/**
 * Tracks number of line breaks added.
 * @type {number}
 */
goog.format.HtmlPrettyPrinter.Buffer.prototype.breakCount = 0;

/**
 * Tracks if we are at the start of a new line.
 * @type {boolean}
 * @private
 */
goog.format.HtmlPrettyPrinter.Buffer.prototype.isBeginningOfNewLine_ = true;

/**
 * Tracks if we need a new line before the next token.
 * @type {boolean}
 * @private
 */
goog.format.HtmlPrettyPrinter.Buffer.prototype.needsNewLine_ = false;

/**
 * Adds token and necessary line breaks to output buffer.
 * @param {boolean} breakBefore If true, add line break before token if
 *     necessary.
 * @param {string} token Token to push.
 * @param {boolean} breakAfter If true, add line break after token if
 *     necessary.
 */
goog.format.HtmlPrettyPrinter.Buffer.prototype.pushToken = function(
    breakBefore, token, breakAfter) {
  // If this token needs a preceeding line break, and
  // we haven't already added a line break, and
  // this token does not start with a line break,
  // then add line break.
  // Due to FF3.0 bug with lists, we don't insert a /n
  // right before </ul>. See bug 1520665.
  if ((this.needsNewLine_ || breakBefore) &&
      !/^\r?\n/.test(token) &&
      !/\/ul/i.test(token)) {
    this.lineBreak();
  }

  // Token.
  this.out_.append(token);

  // Remember if this string ended with a line break so we know we don't have to
  // insert another one before the next token.
  this.isBeginningOfNewLine_ = /\r?\n$/.test(token);

  // Remember if this token requires a line break after it. We don't insert it
  // here because we might not have to if the next token starts with a line
  // break.
  this.needsNewLine_ = breakAfter && !this.isBeginningOfNewLine_;
};

/**
 * Append line break if we need one.
 */
goog.format.HtmlPrettyPrinter.Buffer.prototype.lineBreak = function() {
  if (!this.isBeginningOfNewLine_) {
    this.out_.append('\n');
    ++this.breakCount;
  }
};

/**
 * @return {string} String representation of tokens.
 */
goog.format.HtmlPrettyPrinter.Buffer.prototype.toString = function() {
  return this.out_.toString();
};


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\UserBundle\Factory;

use Sylius\Component\Resource\Factory\FactoryInterface;
use Sylius\Component\User\Model\UserInterface;
use Webmozart\Assert\Assert;

final class UserWithEncoderFactory implements FactoryInterface
{
    private FactoryInterface $decoratedUserFactory;

    private string $encoderName;

    public function __construct(FactoryInterface $decoratedUserFactory, string $encoderName)
    {
        $this->decoratedUserFactory = $decoratedUserFactory;
        $this->encoderName = $encoderName;
    }

    public function createNew(): UserInterface
    {
        $user = $this->decoratedUserFactory->createNew();

        /** @var UserInterface $user */
        Assert::isInstanceOf($user, UserInterface::class);

        $user->setEncoderName($this->encoderName);

        return $user;
    }
}


text:
$: << File.join(File.dirname(__FILE__), "/../../lib" )

require 'i18n'
require 'active_record'
require 'assignable_values'
require 'rspec_candy/all'
require 'gemika'

I18n.enforce_available_locales = true
I18n.load_path = [File.join(File.dirname(__FILE__), 'support/i18n.yml')]
I18n.default_locale = :en

ActiveRecord::Base.default_timezone = :local

Dir["#{File.dirname(__FILE__)}/support/*.rb"].sort.each {|f| require f}

Gemika::RSpec.configure_clean_database_before_example
Gemika::RSpec.configure_should_syntax


text:
4.1.2 - 2016-05-16
==================
* Added Delayed::Worker.queue_attributes
* Limit what we require in ActiveSupport
* Fix pid file creation when there is no tmp directory
* Rails 5 support

4.1.1 - 2015-09-24
==================
* Fix shared specs for back-ends that reload objects

4.1.0 - 2015-09-22
==================
* Alter `Delayed::Command` to work with or without Rails
* Allow `Delayed::Worker.delay_jobs` configuration to be a proc
* Add ability to set destroy failed jobs on a per job basis
* Make `Delayed::Worker.new` idempotent
* Set quiet from the environment
* Rescue `Exception` instead of `StandardError` in worker
* Fix worker crash on serialization error

4.0.6 - 2014-12-22
==================
* Revert removing test files from the gem

4.0.5 - 2014-12-22
==================
* Support for Rails 4.2
* Allow user to override where DJ writes log output
* First attempt at automatic code reloading
* Clearer error message when ActiveRecord object no longer exists
* Various improvements to the README

4.0.4 - 2014-09-24
==================
* Fix using options passed into delayed_job command
* Add the ability to set a default queue for a custom job
* Add the ability to override the max_run_time on a custom job. MUST be lower than worker setting
* Psych YAML overrides are now exclusively used only when loading a job payload
* SLEEP_DELAY and READ_AHEAD can be set for the rake task
* Some updates for Rails 4.2 support

4.0.3 - 2014-09-04
==================
* Added --pools option to delayed_job command
* Removed a bunch of the Psych hacks
* Improved deserialization error reporting
* Misc bug fixes

4.0.2 - 2014-06-24
==================
* Add support for RSpec 3

4.0.1 - 2014-04-12
==================
* Update gemspec for Rails 4.1
* Make logger calls more universal
* Check that records are persisted? instead of new_record?

4.0.0 - 2013-07-30
==================
* Rails 4 compatibility
* Reverted threaded startup due to daemons incompatibilities
* Attempt to recover from job reservation errors

4.0.0.beta2 - 2013-05-28
========================
* Rails 4 compatibility
* Threaded startup script for faster multi-worker startup
* YAML compatibility changes
* Added jobs:check rake task

4.0.0.beta1 - 2013-03-02
========================
* Rails 4 compatibility

3.0.5 - 2013-01-28
==================
* Better job timeout error logging
* psych support for delayed_job_data_mapper deserialization
* User can configure the worker to raise a SignalException on TERM and/or INT
* Add the ability to run all available jobs and exit when complete

3.0.4 - 2012-11-09
==================
* Allow the app to specify a default queue name
* Capistrano script now allows user to specify the DJ command, allowing the user to add "bundle exec" if necessary
* Persisted record check is now more general

3.0.3 - 2012-05-25
==================
* Fix a bug where the worker would not respect the exit condition
* Properly handle sleep delay command line argument

3.0.2 - 2012-04-02
==================
* Fix deprecation warnings
* Raise ArgumentError if attempting to enqueue a performable method on an object that hasn't been persisted yet
* Allow the number of jobs read at a time to be configured from the command line using --read-ahead
* Allow custom logger to be configured through Delayed::Worker.logger
* Various documentation improvements

3.0.1 - 2012-01-24
==================
* Added RecordNotFound message to deserialization error
* Direct JRuby's yecht parser to syck extensions
* Updated psych extensions for better compatibility with ruby 1.9.2
* Updated syck extension for increased compatibility with class methods
* Test grooming

3.0.0 - 2011-12-30
==================
* New: Named queues
* New: Job/Worker lifecycle callbacks
* Change: daemons is no longer a runtime dependency
* Change: Active Record backend support is provided by a separate gem
* Change: Enqueue hook is called before jobs are saved so that they may be modified
* Fix problem deserializing models that use a custom primary key column
* Fix deserializing AR models when the object isn't in the default scope
* Fix hooks not getting called when delay_jobs is false

2.1.4 - 2011-02-11
==================
* Working around issues when psych is loaded, fixes issues with bundler 1.0.10 and Rails 3.0.4
* Added -p/--prefix option to help differentiate multiple delayed job workers on the same host.

2.1.3 - 2011-01-20
==================
* Revert worker contention fix due to regressions
* Added Delayed::Worker.delay_jobs flag to support running jobs immediately

2.1.2 - 2010-12-01
==================
* Remove contention between multiple workers by performing an update to lock a job before fetching it
* Job payloads may implement #max_attempts to control how many times it should be retried
* Fix for loading ActionMailer extension
* Added 'delayed_job_server_role' Capistrano variable to allow delayed_job to run on its own worker server
    set :delayed_job_server_role, :worker
* Fix `rake jobs:work` so it outputs to the console

2.1.1 - 2010-11-14
==================
* Fix issue with worker name not getting properly set when locking a job
* Fixes for YAML serialization

2.1.0 - 2010-11-14
==================
* Added enqueue, before, after, success, error, and failure. See the README
* Remove Merb support
* Remove all non Active Record backends into separate gems. See https://github.com/collectiveidea/delayed_job/wiki/Backends
* remove rails 2 support. delayed_job 2.1 will only support Rails 3
* New pure-YAML serialization
* Added Rails 3 railtie and generator
* Changed @@sleep_delay to self.class.sleep_delay to be consistent with other class variable usage
* Added --sleep-delay command line option

2.0.8 - Unreleased
==================
* Backport fix for deserialization errors that bring down the daemon

2.0.7 - 2011-02-10
==================
* Fixed missing generators and recipes for Rails 2.x

2.0.6 - 2011-01-20
==================
* Revert worker contention fix due to regressions

2.0.5 - 2010-12-01
==================
* Added #reschedule_at hook on payload to determine when the job should be rescheduled [backported from 2.1]
* Added --sleep-delay command line option [backported from 2.1]
* Added 'delayed_job_server_role' Capistrano variable to allow delayed_job to run on its own worker server
    set :delayed_job_server_role, :worker
* Changed AR backend to reserve jobs using an UPDATE query to reduce worker contention [backported from 2.1]

2.0.4 - 2010-11-14
==================
* Fix issue where dirty tracking prevented job from being properly unlocked
* Add delayed_job_args variable for Capistrano recipe to allow configuration of started workers (e.g. "-n 2 --max-priority 10")
* Added options to handle_asynchronously
* Added Delayed::Worker.default_priority
* Allow private methods to be delayed
* Fixes for Ruby 1.9
* Added -m command line option to start a monitor process
* normalize logging in worker
* Deprecate #send_later and #send_at in favor of new #delay method
* Added @#delay@ to Object that allows you to delay any method and pass options:
    options = {:priority => 19, :run_at => 5.minutes.from_now}
    UserMailer.delay(options).deliver_confirmation(@user)

2.0.3 - 2010-04-16
==================
* Fix initialization for Rails 2.x

2.0.2 - 2010-04-08
==================
* Fixes to Mongo Mapper backend [ "14be7a24":http://github.com/collectiveidea/delayed_job/commit/14be7a24, "dafd5f46":http://github.com/collectiveidea/delayed_job/commit/dafd5f46, "54d40913":http://github.com/collectiveidea/delayed_job/commit/54d40913 ]
* DataMapper backend performance improvements [ "93833cce":http://github.com/collectiveidea/delayed_job/commit/93833cce, "e9b1573e":http://github.com/collectiveidea/delayed_job/commit/e9b1573e, "37a16d11":http://github.com/collectiveidea/delayed_job/commit/37a16d11, "803f2bfa":http://github.com/collectiveidea/delayed_job/commit/803f2bfa ]
* Fixed Delayed::Command to create tmp/pids directory [ "8ec8ca41":http://github.com/collectiveidea/delayed_job/commit/8ec8ca41 ]
* Railtie to perform Rails 3 initialization [ "3e0fc41f":http://github.com/collectiveidea/delayed_job/commit/3e0fc41f ]
* Added on_permanent_failure hook [ "d2f14cd6":http://github.com/collectiveidea/delayed_job/commit/d2f14cd6 ]

2.0.1 - 2010-04-03
==================
* Bug fix for using ActiveRecord backend with daemon [martinbtt]

2.0.0 - 2010-04-03
==================
* Multiple backend support (See README for more details)
* Added MongoMapper backend [zbelzer, moneypools]
* Added DataMapper backend [lpetre]
* Reverse priority so the jobs table can be indexed. Lower numbers have higher priority. The default priority is 0, so increase it for jobs that are not important.
* Move most of the heavy lifting from Job to Worker (#work_off, #reschedule, #run, #min_priority, #max_priority, #max_run_time, #max_attempts, #worker_name) [albus522]
* Remove EvaledJob. Implement your own if you need this functionality.
* Only use Time.zone if it is set. Closes #20
* Fix for last_error recording when destroy_failed_jobs = false, max_attempts = 1
* Implemented worker name_prefix to maintain dynamic nature of pid detection
* Some Rails 3 compatibility fixes [fredwu]

1.8.5 - 2010-03-15
==================
* Set auto_flushing=true on Rails logger to fix logging in production
* Fix error message when trying to send_later on a method that doesn't exist
* Don't use rails_env in capistrano if it's not set. closes #22
* Delayed job should append to delayed_job.log not overwrite
* Version bump to 1.8.5
* fixing Time.now to be Time.zone.now if set to honor the app set local TimeZone
* Replaced @Worker::SLEEP@, @Job::MAX_ATTEMPTS@, and @Job::MAX_RUN_TIME@ with class methods that can be overridden.


text:
package fr.goui.restapiconsumer.login.view;

import fr.goui.restapiconsumer.IView;

/**
 *
 */
public interface ILoginView extends IView {

    void onCompleted();

    void showError(String message);
}


text:
Psych-Button
============
USB response boxes with real-time accuracy.

![](images/four.jpg)

![](images/eight.jpg)

Often in psychological experiments, researchers wish to record button presses with accurate timing.  Operating system timing resolution may be inadequate, so out-of-band timing channels are required.

This project centers around a USB keyboard-like device that allows a user to measure its latency.

# Keyboard Quick Start
To use as a USB keyboard, plug-and-play.  The default keys are:

* Four-button version (left-to-right)

  * Top row: w x y z
  * Metal: _

* Eight-button version (left-to-right)

  * Top row: a b c d
  * Middle row: e f g h
  * Metal: _

> Note: if the home key (the metal pin near the center-bottom of the response box) is held, subsequent key presses will be shifted, e.g. 'a' will become 'A'.

### Timing Measurements
Round-trip delay `d` is calculated as per the [SNTP protocol, section 5](https://tools.ietf.org/html/rfc4330#section-5):

    Timestamp Name          ID   When Generated
    ------------------------------------------------------------
    Originate Timestamp     T1   time request sent by client
    Receive Timestamp       T2   time request received by server
    Transmit Timestamp      T3   time reply sent by server
    Destination Timestamp   T4   time reply received by client

    The roundtrip delay d and system clock offset t are defined as:

    d = (T4 - T1) - (T3 - T2)     t = ((T2 - T1) + (T3 - T4)) / 2.

Timing measurement from `psych-button` uses a modified version of SNTP, where `psych-button` responds to a timing request with a single number that corresponds to T3-T2.  In this scheme, T2 is always 0.  T3 is measured in integer microseconds.  Offset is not used, because `psych-button` doesn't keep a wall clock time.  The only figure we're interested in is the round-trip delay.

This procedure is done at least once, usually before an experiment, but can be done at any point in time except during data collection.

    PC (note system time T1), send character: 'T'
    psych-button: T3
    PC (note time of reply T4, calculate d given T3, T2=0)

### Python pyserial example

    cd examples/
    python pythonExample.py

The results from this test is a list of 100 numbers, corresponding to timing measurements before (t1) sending a `T` and after (t2).  The plot below (generated by [this script](images/stats.ijs), written in [J](http://www.jsoftware.com/)) shows the results of one such test, highlighting the standard deviation (blue), variance (red), arithmetic mean (green) and differences (t2i - t1i, violet):

![](images/round_trip_timing.png)

Usage (Keyboard)
----------------
The Keyboard interface sends a `keydown` event when a button is pressed, or a `keyup` event when it is released.

The Keyboard interface is plug and play.  By default, the 4 (or 8) buttons correspond to w, x, y, and z keyboard events.  The "home" button prints a `_` (underbar).  Open a text editor and use the response box to "type" letters.

| button | key          |
|--------|:------------:|
| 0      | w |
| 1      | x |
| 2      | y |
| 3      | z |

> Note: the 8-button box has the default alphabet `abcdefgh`

Usage (Serial)
--------------
Serial mode allows for monitoring the keys pressed, just like Keyboard mode, but in addition provides the following commands:

| Command | Function        |
|---------|-----------------|
| `l`     | list alphabet   |
| `L`     | modify alphabet |
| `T`     | query latency   |

> Note: These commands are processed immediately and may interrupt data taking, so only use them when not waiting for data.

When any button changes, the Serial interface responds by printing the state of all the buttons on a single line.

To use the serial interface, open a serial terminal on your computer using a program such as [pyserial](https://github.com/pyserial/pyserial).  Use the following settings:

* 9600 baud
* 8 data bits
* no parity
* 1 stop bit

Pressing and holding the `b0` button (and no others) will result in one line of output:

    1 0 0 0 0

Meanwhile, if you press the `b3` button, while continuing to hold `b0`, the next output will be:

    1 0 0 1 0

Finally, releasing the `b3` button, and then releasing the `b0` button, will produce this output:

    0 0 0 1 0
    0 0 0 0 0

The eight-button box is similar (here showing `b1` pressed, then released):

    0 1 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0

> Note: the "home" button is the last value in the line.

Notes
-----
Source code built with [platformio](http://platformio.org/#!/), a cross-platform command-line based build tool and dependency manager.

Related Reading
---------------
* [example Python serial application](http://eli.thegreenplace.net/2009/08/07/a-live-data-monitor-with-python-pyqt-and-pyserial/)
* [Synchronization Explained](http://www.ni.com/white-paper/11369/en/)
* [NTP](https://en.wikipedia.org/wiki/Network_Time_Protocol#Clock_synchronization_algorithm)
* [PTP](https://en.wikipedia.org/wiki/Precision_Time_Protocol)


text:
Queremos ouvir (na verdade, ler) tudo que você tem a nos dizer

Contato

Queremos saber o que você tem a nos dizer

Basta preencher esse formulário e vamos receber sua mensagem! Responderemos assim que possível :)

					<form action="${pageContext.request.contextPath}/contato" method="post" class="form-horizontal">

							Seu Nome

								<input type="text" class="form-control" name="name" id="name" placeholder="Como devemos lhe chamar?" aria-describedby="name-help-block" ng-model="contato.name">

Preencha seu nome neste campo. Não precisa ser nome completo, pode até mesmo ser um apelido. Se preferir o anonimato, basta não preencher. Respeitamos bastante isso!

							Seu E-mail

								<input type="email" class="form-control" name="email" id="email" placeholder="Seu E-mail" aria-describedby="email-help-block" ng-model="contato.email">

Preencha seu e-mail neste campo. Atenção Só vamos conseguir lhe responder se soubermos seu e-mail. Se não quiser resposta (ou quiser anonimato), não preencha.

							O que se passa em sua cabeça, hmm?

								<textarea class="form-control" name="content" id="text-content" placeholder="Não se acanhe! Pode falar bem e também pode falar mal! Pode falar muito bem também :P" required autofocus aria-describedby="content-help-block" ng-model="contato.content"></textarea>

Neste campo, digite o que você quer nos dizer. Toda sugestão é bem vinda, toda crítica será considerada e se só quiser conversar mesmo nós estamos de ouvidos em pé para todos :)

							Você é Humano(a)?

								A seguir, uma verificação Captcha. Para evitar robôs malignos rastejando pela internet.

Se não for: Gort, Klaatu barada nikto!

								<button type="submit" class="ajuda-ai-btn">Enviar ➜</button>

					</form>


text:
module Core.FreeVars where

import qualified Data.Generics.Fixplate as Fix

import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.Map as Map

import Syntax.Type (Type, TypeF)
import qualified Syntax.Type as Type

import Syntax.Term (Term, TermF)
import qualified Syntax.Term as Term

freeVarsOp :: Ord id => Term.Operation (Set id) -> Set id
freeVarsOp opn =
  case opn of

    -- A binary operation has a left and right
    -- argument. Both arguments may contain free variables.
    Term.BinaryOperation _ left right ->
      Set.union left right

    -- A unary operation has an argument which may contain
    -- free variables.
    Term.UnaryOperation _ vars ->
      vars

freeVarsF :: Ord id => TermF typeId id (Set id) -> Set id
freeVarsF termF =
  case termF of

    -- A constant does not have any free variables.
    Term.Constant _ ->
      Set.empty

    -- A variable itself is inherently a free variable.
    Term.Variable var ->
      Set.singleton var

    -- An operation may contain free variables in its arguments.
    Term.Operation op ->
      freeVarsOp op

    -- An abstraction creates binding for variables,
    -- and thus eliminates free variables from its body.
    Term.Abstraction argVars vars ->
      Set.difference vars (Set.fromList argVars)

    -- An application consists of a body term,
    -- and multiple argument terms, all of which
    -- can have free variables.
    Term.Application leftVars rightVars ->
      Set.union leftVars (Set.unions rightVars)

    -- A record introduction has a term per record field, all of which
    -- might contain free variables.
    Term.RecordIntroduction mapping ->
      Set.unions (Map.elems mapping)

    -- A record elimination has a body that might contain free variables.
    Term.RecordElimination vars _ ->
      vars

freeVars :: Ord id => Term typeId id -> Set id
freeVars mu =
  Fix.cata freeVarsF mu

freeTypeVarsF :: Ord typeId => TermF typeId id (Set typeId) -> Set typeId
freeTypeVarsF termF =
  case termF of

    -- A constant doesn't have any free type variables.
    Term.Constant _ ->
      Set.empty

    -- A type variable itself is inherently a free variable.
    Term.Variable _ ->
      Set.empty

    -- An operation may contain free type variables in its arguments.
    Term.Operation op ->
      freeVarsOp op

    -- An abstraction has a body that might contain free type variables.
    Term.Abstraction _ typeVars ->
      typeVars

    -- An application consists of two terms, both of which
    -- can have free type variables.
    Term.Application leftVars rightVars ->
      Set.union leftVars (Set.unions rightVars)

    -- A record introduction has a term per record field, all of which
    -- might contain free type variables.
    Term.RecordIntroduction mapping ->
      Set.unions (Map.elems mapping)

    -- A record elimination has a body that might contain free type variables.
    Term.RecordElimination typeVars _ ->
      typeVars

freeTypeVars :: Ord typeId => Term typeId id -> Set typeId
freeTypeVars mu =
  Fix.cata freeTypeVarsF mu

freeVarsTypeF :: Ord typeId => TypeF typeId (Set typeId) -> Set typeId
freeVarsTypeF typeF =
  case typeF of

    -- A constant doesn't have any free type variables.
    Type.Constant _ ->
      Set.empty

    -- A type variable itself is inherently a free variable.
    Type.Variable var ->
      Set.singleton var

    -- An function consists of multiple types, both in its
    -- arguments and in its body, all of which can have free
    -- type variables.
    Type.Function args body ->
      Set.union (Set.unions args) body

freeVarsType :: Ord typeId => Type typeId -> Set typeId
freeVarsType mu =
  Fix.cata freeVarsTypeF mu

annotateFreeVarsType :: Ord typeId => Type typeId -> Fix.Attr (TypeF typeId) (Set typeId)
annotateFreeVarsType mu =
  Fix.synthetise freeVarsTypeF mu


text:
package fr.cvlaminck.merging.impl.strategy;

import fr.cvlaminck.merging.api.CloneableObjectMergingStrategy;
import fr.cvlaminck.merging.api.ObjectMergingStrategy;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ImmutableObjectMergingStrategyTest {

    @Test
    public void testConstructorWithCloneableObjectMergingStrategy() throws CloneNotSupportedException {
        final ObjectMergingStrategy strategy = mock(ObjectMergingStrategy.class);
        when(strategy.getObject()).thenReturn((Class) Object.class);
        when(strategy.getSpecificStrategyForField("A")).thenReturn("A");
        when(strategy.getDefaultStrategyForType(Object.class)).thenReturn("B");

        final CloneableObjectMergingStrategy cloneableStrategy = mock(CloneableObjectMergingStrategy.class);
        when(cloneableStrategy.clone()).thenReturn(strategy);

        final ImmutableObjectMergingStrategy immutable = new ImmutableObjectMergingStrategy(cloneableStrategy);

        assertEquals(Object.class, immutable.getObject());
        assertEquals("A", immutable.getSpecificStrategyForField("A"));
        assertEquals("B", immutable.getDefaultStrategyForType(Object.class));
    }

    @Test
    public void testConstructorWithVariableArgs() {
        final ImmutableObjectMergingStrategy immutable = new ImmutableObjectMergingStrategy(
                Object.class,
                new ImmutablePair<>("A", "A"),
                new ImmutablePair<>(Object.class, "B")
        );

        assertEquals(Object.class, immutable.getObject());
        assertEquals("A", immutable.getSpecificStrategyForField("A"));
        assertEquals("B", immutable.getDefaultStrategyForType(Object.class));
    }

}


text:
"""
Tests specific to the patches module.
"""
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import six

import numpy as np
from numpy.testing import assert_array_equal
from numpy.testing import assert_equal
from numpy.testing import assert_almost_equal

from matplotlib.patches import Polygon
from matplotlib.patches import Rectangle
from matplotlib.testing.decorators import image_comparison
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.collections as mcollections
from matplotlib import path as mpath
from matplotlib import transforms as mtrans

def test_Polygon_close():
    #: Github issue #1018 identified a bug in the Polygon handling
    #: of the closed attribute; the path was not getting closed
    #: when set_xy was used to set the vertices.

    # open set of vertices:
    xy = [[0, 0], [0, 1], [1, 1]]
    # closed set:
    xyclosed = xy + [[0, 0]]

    # start with open path and close it:
    p = Polygon(xy, closed=True)
    assert_array_equal(p.get_xy(), xyclosed)
    p.set_xy(xy)
    assert_array_equal(p.get_xy(), xyclosed)

    # start with closed path and open it:
    p = Polygon(xyclosed, closed=False)
    assert_array_equal(p.get_xy(), xy)
    p.set_xy(xyclosed)
    assert_array_equal(p.get_xy(), xy)

    # start with open path and leave it open:
    p = Polygon(xy, closed=False)
    assert_array_equal(p.get_xy(), xy)
    p.set_xy(xy)
    assert_array_equal(p.get_xy(), xy)

    # start with closed path and leave it closed:
    p = Polygon(xyclosed, closed=True)
    assert_array_equal(p.get_xy(), xyclosed)
    p.set_xy(xyclosed)
    assert_array_equal(p.get_xy(), xyclosed)

def test_rotate_rect():
    loc = np.asarray([1.0, 2.0])
    width = 2
    height = 3
    angle = 30.0

    # A rotated rectangle
    rect1 = Rectangle(loc, width, height, angle=angle)

    # A non-rotated rectangle
    rect2 = Rectangle(loc, width, height)

    # Set up an explicit rotation matrix (in radians)
    angle_rad = np.pi * angle / 180.0
    rotation_matrix = np.array([[np.cos(angle_rad), -np.sin(angle_rad)],
                                [np.sin(angle_rad),  np.cos(angle_rad)]])

    # Translate to origin, rotate each vertex, and then translate back
    new_verts = np.inner(rotation_matrix, rect2.get_verts() - loc).T + loc

    # They should be the same
    assert_almost_equal(rect1.get_verts(), new_verts)

@image_comparison(baseline_images=['clip_to_bbox'])
def test_clip_to_bbox():
    fig = plt.figure()

    ax = fig.add_subplot(111)
    ax.set_xlim([-18, 20])
    ax.set_ylim([-150, 100])

    path = mpath.Path.unit_regular_star(8).deepcopy()
    path.vertices *= [10, 100]
    path.vertices -= [5, 25]

    path2 = mpath.Path.unit_circle().deepcopy()
    path2.vertices *= [10, 100]
    path2.vertices += [10, -25]

    combined = mpath.Path.make_compound_path(path, path2)

    patch = mpatches.PathPatch(
        combined, alpha=0.5, facecolor='coral', edgecolor='none')
    ax.add_patch(patch)

    bbox = mtrans.Bbox([[-12, -77.5], [50, -110]])
    result_path = combined.clip_to_bbox(bbox)
    result_patch = mpatches.PathPatch(
        result_path, alpha=0.5, facecolor='green', lw=4, edgecolor='black')

    ax.add_patch(result_patch)

@image_comparison(baseline_images=['patch_alpha_coloring'], remove_text=True)
def test_patch_alpha_coloring():
    """
    Test checks that the patch and collection are rendered with the specified
    alpha values in their facecolor and edgecolor.
    """
    star = mpath.Path.unit_regular_star(6)
    circle = mpath.Path.unit_circle()
    # concatenate the star with an internal cutout of the circle
    verts = np.concatenate([circle.vertices, star.vertices[::-1]])
    codes = np.concatenate([circle.codes, star.codes])
    cut_star1 = mpath.Path(verts, codes)
    cut_star2 = mpath.Path(verts + 1, codes)

    ax = plt.axes()
    patch = mpatches.PathPatch(cut_star1,
                               linewidth=5, linestyle='dashdot',
                               facecolor=(1, 0, 0, 0.5),
                               edgecolor=(0, 0, 1, 0.75))
    ax.add_patch(patch)

    col = mcollections.PathCollection([cut_star2],
                                      linewidth=5, linestyles='dashdot',
                                      facecolor=(1, 0, 0, 0.5),
                                      edgecolor=(0, 0, 1, 0.75))
    ax.add_collection(col)

    ax.set_xlim([-1, 2])
    ax.set_ylim([-1, 2])

@image_comparison(baseline_images=['patch_alpha_override'], remove_text=True)
def test_patch_alpha_override():
    #: Test checks that specifying an alpha attribute for a patch or
    #: collection will override any alpha component of the facecolor
    #: or edgecolor.
    star = mpath.Path.unit_regular_star(6)
    circle = mpath.Path.unit_circle()
    # concatenate the star with an internal cutout of the circle
    verts = np.concatenate([circle.vertices, star.vertices[::-1]])
    codes = np.concatenate([circle.codes, star.codes])
    cut_star1 = mpath.Path(verts, codes)
    cut_star2 = mpath.Path(verts + 1, codes)

    ax = plt.axes()
    patch = mpatches.PathPatch(cut_star1,
                               linewidth=5, linestyle='dashdot',
                               alpha=0.25,
                               facecolor=(1, 0, 0, 0.5),
                               edgecolor=(0, 0, 1, 0.75))
    ax.add_patch(patch)

    col = mcollections.PathCollection([cut_star2],
                                      linewidth=5, linestyles='dashdot',
                                      alpha=0.25,
                                      facecolor=(1, 0, 0, 0.5),
                                      edgecolor=(0, 0, 1, 0.75))
    ax.add_collection(col)

    ax.set_xlim([-1, 2])
    ax.set_ylim([-1, 2])

@image_comparison(baseline_images=['patch_custom_linestyle'],
                  remove_text=True)
def test_patch_custom_linestyle():
    #: A test to check that patches and collections accept custom dash
    #: patterns as linestyle and that they display correctly.
    star = mpath.Path.unit_regular_star(6)
    circle = mpath.Path.unit_circle()
    # concatenate the star with an internal cutout of the circle
    verts = np.concatenate([circle.vertices, star.vertices[::-1]])
    codes = np.concatenate([circle.codes, star.codes])
    cut_star1 = mpath.Path(verts, codes)
    cut_star2 = mpath.Path(verts + 1, codes)

    ax = plt.axes()
    patch = mpatches.PathPatch(cut_star1,
                   linewidth=5, linestyle=(0.0, (5.0, 7.0, 10.0, 7.0)),
                   facecolor=(1, 0, 0),
                   edgecolor=(0, 0, 1))
    ax.add_patch(patch)

    col = mcollections.PathCollection([cut_star2],
                  linewidth=5, linestyles=[(0.0, (5.0, 7.0, 10.0, 7.0))],
                  facecolor=(1, 0, 0),
                  edgecolor=(0, 0, 1))
    ax.add_collection(col)

    ax.set_xlim([-1, 2])
    ax.set_ylim([-1, 2])

def test_wedge_movement():
    param_dict = {'center': ((0, 0), (1, 1), 'set_center'),
                  'r': (5, 8, 'set_radius'),
                  'width': (2, 3, 'set_width'),
                  'theta1': (0, 30, 'set_theta1'),
                  'theta2': (45, 50, 'set_theta2')}

    init_args = dict((k, v[0]) for (k, v) in six.iteritems(param_dict))

    w = mpatches.Wedge(**init_args)
    for attr, (old_v, new_v, func) in six.iteritems(param_dict):
        assert_equal(getattr(w, attr), old_v)
        getattr(w, func)(new_v)
        assert_equal(getattr(w, attr), new_v)

if __name__ == '__main__':
    import nose
    nose.runmodule(argv=['-s', '--with-doctest'], exit=False)


text:
package de.st_ddt.crazyutil.paramitrisable;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import de.st_ddt.crazyplugin.exceptions.CrazyCommandNoSuchException;
import de.st_ddt.crazyplugin.exceptions.CrazyException;

public class MapParamitrisable<S> extends TypedParamitrisable<S>
{

	protected final String type;
	protected final Map<String, ? extends S> values;
	private final boolean lowercase;

	public MapParamitrisable(final String type, final Map<String, ? extends S> values, final S defaultValue)
	{
		super(defaultValue);
		this.type = type;
		this.values = values;
		this.lowercase = false;
	}

	public MapParamitrisable(final String type, final Map<String, ? extends S> values, final boolean foo, final String defaultValue)
	{
		super(values.get(defaultValue));
		this.type = type;
		this.values = values;
		this.lowercase = false;
	}

	public MapParamitrisable(final String type, final Map<String, ? extends S> values, final S defaultValue, final boolean lowercase)
	{
		super(defaultValue);
		this.type = type;
		this.values = values;
		this.lowercase = lowercase;
	}

	@Override
	public void setParameter(String parameter) throws CrazyException
	{
		if (lowercase)
			parameter = parameter.toLowerCase();
		if (values.containsKey(parameter))
			value = values.get(parameter);
		else
			throw new CrazyCommandNoSuchException(type, parameter, values.keySet());
	}

	@Override
	public List<String> tab(final String parameter)
	{
		return tabHelp(values, parameter);
	}

	public static List<String> tabHelp(final Map<String, ?> values, final String parameter)
	{
		final List<String> res = new LinkedList<String>();
		for (final String entry : values.keySet())
			if (entry.startsWith(parameter))
				res.add(entry);
		return res;
	}

	public final Map<String, ? extends S> getValues()
	{
		return values;
	}
}