text:
package org.drools.workbench.screens.guided.dtable.backend.server;

import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Stream;

import org.drools.workbench.models.datamodel.rule.BaseSingleFieldConstraint;
import org.drools.workbench.models.guided.dtable.shared.model.ConditionCol52;
import org.drools.workbench.models.guided.dtable.shared.model.DTCellValue52;
import org.drools.workbench.models.guided.dtable.shared.model.DescriptionCol52;
import org.drools.workbench.models.guided.dtable.shared.model.GuidedDecisionTable52;
import org.drools.workbench.models.guided.dtable.shared.model.Pattern52;
import org.drools.workbench.models.guided.dtable.shared.model.RowNumberCol52;
import org.drools.workbench.screens.guided.dtable.service.GuidedDecisionTableEditorService;
import org.drools.workbench.screens.guided.dtable.type.GuidedDTableResourceTypeDefinition;
import org.guvnor.common.services.backend.file.FileDiscoveryService;
import org.guvnor.common.services.project.model.Package;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.soup.project.datamodel.imports.Import;
import org.kie.soup.project.datamodel.imports.Imports;
import org.kie.workbench.common.services.shared.project.KieModuleService;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.uberfire.io.IOService;
import org.uberfire.java.nio.file.FileSystem;
import org.uberfire.java.nio.file.Path;

import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class GuidedDecisionTableSourceServiceTest {

    @Mock
    Path path;

    @Mock
    Package packageMock;

    @Mock
    FileSystem fileSystem;

    @Mock
    KieModuleService moduleService;

    @Mock
    FileDiscoveryService discoveryService;

    @Mock
    GuidedDTableResourceTypeDefinition resourceTypeDefinition;

    @Mock
    GuidedDecisionTableEditorService guidedDecisionTableEditorService;

    @Mock
    IOService ioService;

    @Mock
    FileDiscoveryService fileDiscoveryService;

    GuidedDecisionTable52 model;

    GuidedDecisionTableSourceService service;

    Pattern52 pattern;

    ConditionCol52 nameEqualToLiteralCondition;

    List<List<DTCellValue52>> data;

    @Before
    public void setUp() throws Exception {
        service = new GuidedDecisionTableSourceService(resourceTypeDefinition,
                                                       guidedDecisionTableEditorService,
                                                       ioService,
                                                       fileDiscoveryService,
                                                       moduleService);

        // Simulates that no DSL files are present
        when(moduleService.resolvePackage(any())).thenReturn(packageMock);
        when(discoveryService.discoverFiles(any(),
                                            any())).thenReturn(new ArrayList<Path>());
        when(fileSystem.supportedFileAttributeViews()).thenReturn(new HashSet<String>());
        when(path.getFileSystem()).thenReturn(fileSystem);
        when(path.toString()).thenReturn("/");
        when(path.getFileName()).thenReturn(path);
        when(path.toUri()).thenReturn(new URI("/"));

        model = new GuidedDecisionTable52();

        model.setPackageName("com.sample");
        model.setImports(new Imports(Arrays.asList(new Import("com.sample.Person"))));
        model.setRowNumberCol(new RowNumberCol52());
        model.setDescriptionCol(new DescriptionCol52());

        pattern = new Pattern52();
        pattern.setBoundName("$p");
        pattern.setFactType("Person");

        nameEqualToLiteralCondition = new ConditionCol52();
        nameEqualToLiteralCondition.setConstraintValueType(BaseSingleFieldConstraint.TYPE_LITERAL);
        nameEqualToLiteralCondition.setHeader("name equals to");
        nameEqualToLiteralCondition.setFactField("name");
        nameEqualToLiteralCondition.setOperator("==");

        pattern.setChildColumns(Arrays.asList(nameEqualToLiteralCondition));

        model.setConditionPatterns(Arrays.asList(pattern));

        data = new ArrayList<>();
    }

    @Test
    public void testOtherwise() throws Exception {
        addRow(1,
               "John",
               false);
        addRow(2,
               "Peter",
               false);
        addRow(3,
               null,
               true);

        model.setData(data);

        String source = service.getSource(path,
                                          model);
        assertTrue("Expected: name == \"John\"",
                   source.contains("$p : Person( name == \"John\" )"));
        assertTrue("Expected: name == \"Peter\"",
                   source.contains("$p : Person( name == \"Peter\" )"));
        assertTrue("Expected: name not in ( \"John\", \"Peter\" )",
                   source.contains("$p : Person( name not in ( \"John\", \"Peter\" )"));
    }

    @Test
    public void testOtherwiseTwoSameValues() throws Exception {
        addRow(1,
               "John",
               false);
        addRow(2,
               "John",
               false);
        addRow(3,
               null,
               true);

        model.setData(data);

        String source = service.getSource(path,
                                          model);
        assertTrue("Expected: name not in ( \"John\" )",
                   source.contains("$p : Person( name not in ( \"John\" )"));
    }

    @Test
    public void testOtherwiseEmptyValue() throws Exception {
        addRow(1,
               "John",
               false);
        addRow(2,
               "",
               false);
        addRow(3,
               null,
               true);

        model.setData(data);

        String source = service.getSource(path,
                                          model);
        assertTrue("Expected: name not in ( \"John\", \"\" )",
                   source.contains("$p : Person( name not in ( \"John\", \"\" )"));
    }

    @Test
    public void testOtherwiseEmptyAndNullValue() throws Exception {
        addRow(1,
               "",
               false);
        addRow(2,
               null,
               false);
        addRow(3,
               null,
               true);

        model.setData(data);

        String source = service.getSource(path,
                                          model);
        assertTrue("Expected: name not in ( \"\" )",
                   source.contains("$p : Person( name not in ( \"\" )"));
    }

    @Test
    public void testOtherwiseTwoTimes() throws Exception {
        addRow(1,
               "John",
               false);
        addRow(2,
               null,
               true);
        addRow(3,
               "Peter",
               false);
        addRow(4,
               null,
               true);

        model.setData(data);

        String source = service.getSource(path,
                                          model);
        assertTrue("Expected: name not in ( \"John\", \"Peter\" )",
                   source.contains("$p : Person( name not in ( \"John\", \"Peter\" )"));
        source.replaceFirst("John",
                            "");
        assertTrue("Expected: name not in ( \"John\", \"Peter\" )",
                   source.contains("$p : Person( name not in ( \"John\", \"Peter\" )"));
    }

    @Test
    public void testCustomRuleName() throws Exception {
        adRowWithCustomRuleName(1,
                                "John is important",
                                "John");
        model.setData(data);
        String source = service.getSource(path,
                                          model);

        assertTrue("Expected custom rule name to be present",
                   source.contains("rule \"John is important\"\n"));
    }

    @Test
    public void testFormulaFieldBinding() throws Exception {
        final ConditionCol52 ageEqualToFormulaCondition = new ConditionCol52();
        ageEqualToFormulaCondition.setConstraintValueType(BaseSingleFieldConstraint.TYPE_RET_VALUE);
        ageEqualToFormulaCondition.setHeader("age equals to");
        ageEqualToFormulaCondition.setFactField("age");
        ageEqualToFormulaCondition.setOperator("==");
        ageEqualToFormulaCondition.setBinding("$age");

        pattern.setChildColumns(Arrays.asList(ageEqualToFormulaCondition));
        model.setConditionPatterns(Arrays.asList(pattern));
        addRow(1, "1 + 1");
        model.setData(data);

        final String source = service.getSource(path, model);
        assertTrue(source.contains("$p : Person( $age : age == ( 1 + 1 ) )"));
    }

    private void addRow(int rowNumber,
                        String nameEqualToCostraint,
                        boolean isOtherwise) {
        data.add(new ArrayList<DTCellValue52>() {{
            add(new DTCellValue52(rowNumber));
            add(new DTCellValue52(""));
            add(new DTCellValue52("row " + rowNumber));
            if (!isOtherwise) {
                add(new DTCellValue52(nameEqualToCostraint));
            } else {
                DTCellValue52 otherwise = new DTCellValue52();
                otherwise.setOtherwise(true);
                add(otherwise);
            }
        }});
    }

    private void addRow(int rowNumber,
                        String... constraintValues) {

        adRowWithCustomRuleName(rowNumber, "", constraintValues);
    }

    private void adRowWithCustomRuleName(int rowNumber,
                                         String customRuleName,
                                         String... constraintValues) {
        data.add(new ArrayList<DTCellValue52>() {{
            add(new DTCellValue52(rowNumber));
            add(new DTCellValue52(customRuleName));
            add(new DTCellValue52("row " + rowNumber));
            Stream.of(constraintValues).forEach(value -> add(new DTCellValue52(value)));
        }});
    }
}


text:
//
//  ViewController.m
//  One
//
//  Created by suntop on 2017/5/4.
//  Copyright © 2017年 suntop. All rights reserved.
//

#import "ViewController.h"
#import "BBViewController.h"

@interface ViewController ()<UIScrollViewDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    scrollView.backgroundColor = [UIColor redColor];
    // 是否支持滑动最顶端
    //    scrollView.scrollsToTop = NO;
    scrollView.delegate = self;
    // 设置内容大小
    scrollView.contentSize = CGSizeMake(320, 460*10);
    // 是否反弹
    //    scrollView.bounces = NO;
    // 是否分页
    //    scrollView.pagingEnabled = YES;
    // 是否滚动
    //    scrollView.scrollEnabled = NO;
    //    scrollView.showsHorizontalScrollIndicator = NO;
    // 设置indicator风格
    //    scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    // 设置内容的边缘和Indicators边缘
    //    scrollView.contentInset = UIEdgeInsetsMake(0, 50, 50, 0);
    //    scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 50, 0, 0);
    // 提示用户,Indicators flash
    [scrollView flashScrollIndicators];
    // 是否同时运动,lock
    scrollView.directionalLockEnabled = YES;
    [self.view addSubview:scrollView];

    //创建手势对象
    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc]initWithTarget:self     action:@selector(tapAction:)];
    //配置属性
    //轻拍次数
    tap.numberOfTapsRequired =1;
    //轻拍手指个数
    tap.numberOfTouchesRequired =1;
    //讲手势添加到指定的视图上
    [scrollView addGestureRecognizer:tap];

}
-(void)tapAction:(UITapGestureRecognizer *)tap
{

    //图片切换
    NSLog(@"拍一下");

    BBViewController * vcv= [[BBViewController alloc] init];
    [self presentViewController:vcv animated:YES completion:nil];

}
#pragma mark -
/*
 // 返回一个放大或者缩小的视图
 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
 {

 }
 // 开始放大或者缩小
 - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:
 (UIView *)view
 {

 }

 // 缩放结束时
 - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
 {

 }

 // 视图已经放大或缩小
 - (void)scrollViewDidZoom:(UIScrollView *)scrollView
 {
 NSLog(@"scrollViewDidScrollToTop");
 }
 */

// 是否支持滑动至顶部
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView
{
    return YES;
}

// 滑动到顶部时调用该方法
- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
{
    NSLog(@"scrollViewDidScrollToTop");
}

// scrollView 已经滑动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSLog(@"scrollViewDidScroll");
}

// scrollView 开始拖动
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    NSLog(@"scrollViewWillBeginDragging");
}

// scrollView 结束拖动
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    NSLog(@"scrollViewDidEndDragging");
}

// scrollView 开始减速(以下两个方法注意与以上两个方法加以区别)
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    NSLog(@"scrollViewWillBeginDecelerating");
}

// scrollview 减速停止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSLog(@"scrollViewDidEndDecelerating");
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"%s",__func__);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

redpajama_set_name: RedPajamaGithub


text:
Article 434
----
La sauvegarde de justice peut également résulter d'une déclaration faite au
procureur de la République dans les conditions prévues par l'article L. 3211-6
du code de la santé publique.


text:
<?php

    // First we execute our common code to connection to the database and start the session
    require("common.php");

    // At the top of the page we check to see whether the user is logged in or not
    if(empty($_SESSION['user']))
    {
        // If they are not, we redirect them to the signin page.
        header("Location: signin.php");

        // Remember that this die statement is absolutely critical.  Without it,
        // people can view your members-only content without logging in.
        die("Redirecting to signin.php");
    }

    $query = "DELETE FROM category WHERE user_id = :user_id AND name = :category_name";

    try
    {
        // Execute the query
        $stmt = $db->prepare($query);
        $stmt->bindParam(':category_name', $_POST['category_name']);
        $stmt->bindParam(':user_id', $_SESSION['user']['id']);
        $result = $stmt->execute();
    }
    catch(PDOException $ex)
    {
        error_log($ex);
        // Note: On a production website, you should not output $ex->getMessage().
        // It may provide an attacker with helpful information about your code.
        die("Failed to run query: " . $ex->getMessage());
    }
?>


text:
require 'test_helper'

class TestingThirteensControllerTest < ActionController::TestCase
  setup do
    @testing_thirteen = testing_thirteens(:one)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:testing_thirteens)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create testing_thirteen" do
    assert_difference('TestingThirteen.count') do
      post :create, testing_thirteen: { account_id: @testing_thirteen.account_id, one: @testing_thirteen.one, status: @testing_thirteen.status, three: @testing_thirteen.three, two: @testing_thirteen.two }
    end

    assert_redirected_to testing_thirteen_path(assigns(:testing_thirteen))
  end

  test "should show testing_thirteen" do
    get :show, id: @testing_thirteen
    assert_response :success
  end

  test "should get edit" do
    get :edit, id: @testing_thirteen
    assert_response :success
  end

  test "should update testing_thirteen" do
    patch :update, id: @testing_thirteen, testing_thirteen: { account_id: @testing_thirteen.account_id, one: @testing_thirteen.one, status: @testing_thirteen.status, three: @testing_thirteen.three, two: @testing_thirteen.two }
    assert_redirected_to testing_thirteen_path(assigns(:testing_thirteen))
  end

  test "should destroy testing_thirteen" do
    assert_difference('TestingThirteen.count', -1) do
      delete :destroy, id: @testing_thirteen
    end

    assert_redirected_to testing_thirteens_path
  end
end


text:
This playbook blocks domains using Zscaler.
The playbook checks whether the Zscaler integration is enabled, whether the Domain input has been provided and if so, blocks the domain.

## Dependencies
This playbook uses the following sub-playbooks, integrations, and scripts.

### Sub-playbooks
This playbook does not use any sub-playbooks.

### Integrations
* Zscaler

### Scripts
This playbook does not use any scripts.

### Commands
* zscaler-blacklist-url

## Playbook Inputs
---

| **Name** | **Description** | **Default Value** | **Required** |
| --- | --- | --- | --- |
| Domain | The Domain to block. |  | Optional |

## Playbook Outputs
---
There are no outputs for this playbook.

## Playbook Image
---
![Block Domain - Zscaler](https://raw.githubusercontent.com/demisto/content/7d20d193ddfe06ad3ead0effb87db3e71fe675a8/Packs/Zscaler/doc_files/Block_Domain_-_Zscaler.png)


text:
import { combineReducers } from 'redux';

import auth from './reducers/auth.js';
import ical from './reducers/ical.js';

export default combineReducers({
    auth,
    ical
});


text:
/*************************************************************************
  This is an Arduino library for the Adafruit Thermal Printer.
  Pick one up at --> http://www.adafruit.com/products/597
  These printers use TTL serial to communicate, 2 pins are required.

  Adafruit invests time and resources providing this open source code.
  Please support Adafruit and open-source hardware by purchasing products
  from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  MIT license, all text above must be included in any redistribution.
 *************************************************************************/

#ifndef Thermal_h
#define Thermal_h

#if ARDUINO >= 100
 #include "Arduino.h"
 #include "SoftwareSerial.h"
#else
 #include "WProgram.h"
 #include "WConstants.h"
 #include "NewSoftSerial.h"
#endif

// Barcode types
#define UPC_A   0
#define UPC_E   1
#define EAN13   2
#define EAN8    3
#define CODE39  4
#define I25     5
#define CODEBAR 6
#define CODE93  7
#define CODE128 8
#define CODE11  9
#define MSI    10

#if ARDUINO >= 100
  #define SERIAL_IMPL      SoftwareSerial
  #define PRINTER_PRINT(a) _printer->write(a);
#else
  #define SERIAL_IMPL      NewSoftSerial
  #define PRINTER_PRINT(a) _printer->print(a, BYTE);
#endif

class Adafruit_Thermal : public Print {

 public:

  Adafruit_Thermal(int RX_Pin, int TX_Pin);

  void
    begin(int heatTime=200),
    reset(),
    setDefault(),
    test(),
    testPage(),

    normal(),
    inverseOn(),
    inverseOff(),
    upsideDownOn(),
    upsideDownOff(),
    doubleHeightOn(),
    doubleHeightOff(),
    doubleWidthOn(),
    doubleWidthOff(),
    boldOn(),
    boldOff(),
    underlineOn(uint8_t weight=1),
    underlineOff(),
    strikeOn(),
    strikeOff(),

    justify(char value),
    feed(uint8_t x=1),
    feedRows(uint8_t),
    flush(),
    online(),
    offline(),
    sleep(),
    sleepAfter(uint8_t seconds),
    wake(),
    listen(),

    setSize(char value),
    setLineHeight(int val=32),

    printBarcode(char * text, uint8_t type),
    setBarcodeHeight(int val=50),

    printBitmap(int w, int h, const uint8_t *bitmap, bool fromProgMem = true),
    printBitmap(int w, int h, Stream *stream),
    printBitmap(Stream *stream),

    timeoutSet(unsigned long),
    timeoutWait(),
    setTimes(unsigned long, unsigned long),
    setMaxChunkHeight(int val),

    setCharSpacing(int spacing), // Not working
    tab();                       // Not working

  bool hasPaper();

#if ARDUINO >= 100
  size_t write(uint8_t c);
#else
  void   write(uint8_t c);
#endif

 protected:

  SERIAL_IMPL
    *_printer;
  uint8_t
    prevByte,      // Last character issued to printer
    column,        // Last horizontal column printed
    maxColumn,     // Page width (output 'wraps' at this point)
    charHeight,    // Height of characters, in 'dots'
    lineSpacing,   // Inter-line spacing (not line height), in dots
    barcodeHeight; // Barcode height in dots, not including text
  unsigned long
    resumeTime,    // Wait until micros() exceeds this before sending byte
    dotPrintTime,  // Time to print a single dot line, in microseconds
    dotFeedTime;   // Time to feed a single dot line, in microseconds
  int
    printMode,
    _RX_Pin,
    _TX_Pin,
    maxChunkHeight;
  void
    setPrintMode(uint8_t mask),
    unsetPrintMode(uint8_t mask),
    writePrintMode(),
    writeBytes(uint8_t a),
    writeBytes(uint8_t a, uint8_t b),
    writeBytes(uint8_t a, uint8_t b, uint8_t c),
    writeBytes(uint8_t a, uint8_t b, uint8_t c, uint8_t d);
};

#endif // Thermal_h


text:
import math

import numpy as np
import torch
from fairseq.data import FairseqDataset

class BlockPairDataset(FairseqDataset):
    """Break a Dataset of tokens into sentence pair blocks for next sentence
       prediction as well as masked language model.

       High-level logics are:
       1. break input tensor to tensor blocks
       2. pair the blocks with 50% next sentence and 50% random sentence
       3. return paired blocks as well as related segment labels

    Args:
        dataset (~torch.utils.data.Dataset): dataset to break into blocks
        sizes: array of sentence lengths
        dictionary: dictionary for the task
        block_size: maximum block size
        break_mode: mode for breaking copurs into block pairs. currently we support
            2 modes
            doc: respect document boundaries and each part of the pair should belong to on document
            none: don't respect any boundary and cut tokens evenly
        short_seq_prob: probability for generating shorter block pairs
        doc_break_size: Size for empty line separating documents. Typically 1 if
                        the sentences have eos, 0 otherwise.
    """

    def __init__(
        self,
        dataset,
        dictionary,
        sizes,
        block_size,
        break_mode="doc",
        short_seq_prob=0.1,
        doc_break_size=1,
    ):
        super().__init__()
        self.dataset = dataset
        self.pad = dictionary.pad()
        self.eos = dictionary.eos()
        self.cls = dictionary.cls()
        self.mask = dictionary.mask()
        self.sep = dictionary.sep()
        self.break_mode = break_mode
        self.dictionary = dictionary
        self.short_seq_prob = short_seq_prob
        self.block_indices = []

        assert len(dataset) == len(sizes)

        if break_mode == "doc":
            cur_doc = []
            for sent_id, sz in enumerate(sizes):
                assert doc_break_size == 0 or sz != 0, (
                    "when doc_break_size is non-zero, we expect documents to be"
                    "separated by a blank line with a single eos."
                )
                # empty line as document separator
                if sz == doc_break_size:
                    if len(cur_doc) == 0:
                        continue
                    self.block_indices.append(cur_doc)
                    cur_doc = []
                else:
                    cur_doc.append(sent_id)
            max_num_tokens = block_size - 3  # Account for [CLS], [SEP], [SEP]
            self.sent_pairs = []
            self.sizes = []
            for doc_id, doc in enumerate(self.block_indices):
                self._generate_sentence_pair(doc, doc_id, max_num_tokens, sizes)
        elif break_mode is None or break_mode == "none":
            # each block should have half of the block size since we are constructing block pair
            sent_length = (block_size - 3) // 2
            total_len = sum(dataset.sizes)
            length = math.ceil(total_len / sent_length)

            def block_at(i):
                start = i * sent_length
                end = min(start + sent_length, total_len)
                return (start, end)

            sent_indices = np.array([block_at(i) for i in range(length)])
            sent_sizes = np.array([e - s for s, e in sent_indices])
            dataset_index = self._sent_to_dataset_index(sent_sizes)

            # pair sentences
            self._pair_sentences(dataset_index)
        else:
            raise ValueError("Invalid break_mode: " + break_mode)

    def _pair_sentences(self, dataset_index):
        """
        Give a list of evenly cut blocks/sentences, pair these sentences with 50%
        consecutive sentences and 50% random sentences.
        This is used for none break mode
        """
        # pair sentences
        for sent_id, sent in enumerate(dataset_index):
            next_sent_label = (
                1 if np.random.rand() > 0.5 and sent_id != len(dataset_index) - 1 else 0
            )
            if next_sent_label:
                next_sent = dataset_index[sent_id + 1]
            else:
                next_sent = dataset_index[
                    self._skip_sampling(len(dataset_index), [sent_id, sent_id + 1])
                ]
            self.sent_pairs.append((sent, next_sent, next_sent_label))

            # The current blocks don't include the special tokens but the
            # sizes already account for this
            self.sizes.append(3 + sent[3] + next_sent[3])

    def _sent_to_dataset_index(self, sent_sizes):
        """
        Build index mapping block indices to the underlying dataset indices
        """
        dataset_index = []
        ds_idx, ds_remaining = -1, 0
        for to_consume in sent_sizes:
            sent_size = to_consume
            if ds_remaining == 0:
                ds_idx += 1
                ds_remaining = sent_sizes[ds_idx]
            start_ds_idx = ds_idx
            start_offset = sent_sizes[ds_idx] - ds_remaining
            while to_consume > ds_remaining:
                to_consume -= ds_remaining
                ds_idx += 1
                ds_remaining = sent_sizes[ds_idx]
            ds_remaining -= to_consume
            dataset_index.append(
                (
                    start_ds_idx,  # starting index in dataset
                    start_offset,  # starting offset within starting index
                    ds_idx,  # ending index in dataset
                    sent_size,  # sentence length
                )
            )
        assert ds_remaining == 0
        assert ds_idx == len(self.dataset) - 1
        return dataset_index

    def _generate_sentence_pair(self, doc, doc_id, max_num_tokens, sizes):
        """
        Go through a single document and genrate sentence paris from it
        """
        current_chunk = []
        current_length = 0
        curr = 0
        # To provide more randomness, we decrease target seq length for parts of
        # samples (10% by default). Note that max_num_tokens is the hard threshold
        # for batching and will never be changed.
        target_seq_length = max_num_tokens
        if np.random.random() < self.short_seq_prob:
            target_seq_length = np.random.randint(2, max_num_tokens)
        # loop through all sentences in document
        while curr < len(doc):
            sent_id = doc[curr]
            current_chunk.append(sent_id)
            current_length = sum(sizes[current_chunk])
            # split chunk and generate pair when exceed target_seq_length or
            # finish the loop
            if curr == len(doc) - 1 or current_length >= target_seq_length:
                # split the chunk into 2 parts
                a_end = 1
                if len(current_chunk) > 2:
                    a_end = np.random.randint(1, len(current_chunk) - 1)
                sent_a = current_chunk[:a_end]
                len_a = sum(sizes[sent_a])
                # generate next sentence label, note that if there is only 1 sentence
                # in current chunk, label is always 0
                next_sent_label = (
                    1 if np.random.rand() > 0.5 and len(current_chunk) != 1 else 0
                )
                if not next_sent_label:
                    # if next sentence label is 0, sample sent_b from a random doc
                    target_b_length = target_seq_length - len_a
                    rand_doc_id = self._skip_sampling(len(self.block_indices), [doc_id])
                    random_doc = self.block_indices[rand_doc_id]
                    random_start = np.random.randint(0, len(random_doc))
                    sent_b = []
                    len_b = 0
                    for j in range(random_start, len(random_doc)):
                        sent_b.append(random_doc[j])
                        len_b = sum(sizes[sent_b])
                        if len_b >= target_b_length:
                            break
                    # return the second part of the chunk since it's not used
                    num_unused_segments = len(current_chunk) - a_end
                    curr -= num_unused_segments
                else:
                    # if next sentence label is 1, use the second part of chunk as sent_B
                    sent_b = current_chunk[a_end:]
                    len_b = sum(sizes[sent_b])
                # currently sent_a and sent_B may be longer than max_num_tokens,
                # truncate them and return block idx and offsets for them
                sent_a, sent_b = self._truncate_sentences(
                    sent_a, sent_b, max_num_tokens
                )
                self.sent_pairs.append((sent_a, sent_b, next_sent_label))
                self.sizes.append(3 + sent_a[3] + sent_b[3])
                current_chunk = []
            curr += 1

    def _skip_sampling(self, total, skip_ids):
        """
        Generate a random integer which is not in skip_ids. Sample range is [0, total)
        TODO: ids in skip_ids should be consecutive, we can extend it to more generic version later
        """
        rand_id = np.random.randint(total - len(skip_ids))
        return rand_id if rand_id < min(skip_ids) else rand_id + len(skip_ids)

    def _truncate_sentences(self, sent_a, sent_b, max_num_tokens):
        """
        Trancate a pair of sentence to limit total length under max_num_tokens
        Logics:
            1. Truncate longer sentence
            2. Tokens to be truncated could be at the beginning or the end of the sentnce
        Returns:
            Truncated sentences represented by dataset idx
        """
        len_a, len_b = sum(self.dataset.sizes[sent_a]), sum(self.dataset.sizes[sent_b])
        front_cut_a = front_cut_b = end_cut_a = end_cut_b = 0

        while True:
            total_length = (
                len_a + len_b - front_cut_a - front_cut_b - end_cut_a - end_cut_b
            )
            if total_length <= max_num_tokens:
                break

            if len_a - front_cut_a - end_cut_a > len_b - front_cut_b - end_cut_b:
                if np.random.rand() < 0.5:
                    front_cut_a += 1
                else:
                    end_cut_a += 1
            else:
                if np.random.rand() < 0.5:
                    front_cut_b += 1
                else:
                    end_cut_b += 1

        # calculate ds indices as well as offsets and return
        truncated_sent_a = self._cut_sentence(sent_a, front_cut_a, end_cut_a)
        truncated_sent_b = self._cut_sentence(sent_b, front_cut_b, end_cut_b)
        return truncated_sent_a, truncated_sent_b

    def _cut_sentence(self, sent, front_cut, end_cut):
        """
        Cut a sentence based on the numbers of tokens to be cut from beginning and end
        Represent the sentence as dataset idx and return
        """
        start_ds_idx, end_ds_idx, offset = sent[0], sent[-1], 0
        target_len = sum(self.dataset.sizes[sent]) - front_cut - end_cut
        while front_cut > 0:
            if self.dataset.sizes[start_ds_idx] > front_cut:
                offset += front_cut
                break
            else:
                front_cut -= self.dataset.sizes[start_ds_idx]
                start_ds_idx += 1
        while end_cut > 0:
            if self.dataset.sizes[end_ds_idx] > end_cut:
                break
            else:
                end_cut -= self.dataset.sizes[end_ds_idx]
                end_ds_idx -= 1
        return start_ds_idx, offset, end_ds_idx, target_len

    def _fetch_block(self, start_ds_idx, offset, end_ds_idx, length):
        """
        Fetch a block of tokens based on its dataset idx
        """
        buffer = torch.cat(
            [self.dataset[idx] for idx in range(start_ds_idx, end_ds_idx + 1)]
        )
        s, e = offset, offset + length
        return buffer[s:e]

    def __getitem__(self, index):
        block1, block2, next_sent_label = self.sent_pairs[index]
        block1 = self._fetch_block(*block1)
        block2 = self._fetch_block(*block2)
        return block1, block2, next_sent_label

    def __len__(self):
        return len(self.sizes)

    @property
    def supports_prefetch(self):
        return getattr(self.dataset, "supports_prefetch", False)

    def prefetch(self, indices):
        prefetch_idx = set()
        for index in indices:
            for block1, block2, _ in [self.sent_pairs[index]]:
                for ds_idx in range(block1[0], block1[2] + 1):
                    prefetch_idx.add(ds_idx)
                for ds_idx in range(block2[0], block2[2] + 1):
                    prefetch_idx.add(ds_idx)
        self.dataset.prefetch(prefetch_idx)


text:
class Font;
class TextCache;

// Used to display/edit a value between some min and max values.
class SliderComponent : public GuiComponent
{
public:
	//Minimum value (far left of the slider), maximum value (far right of the slider), increment size (how much just pressing L/R moves by), unit to display (optional).
	SliderComponent(Window* window, float min, float max, float increment, const std::string& suffix = "");

	void setValue(float val);
	float getValue();

	bool input(InputConfig* config, Input input) override;
	void update(int deltaTime) override;
	void render(const Transform4x4f& parentTrans) override;

	void onSizeChanged() override;

	virtual std::vector<HelpPrompt> getHelpPrompts() override;

private:
	void onValueChanged();

	float mMin, mMax;
	float mValue;
	float mSingleIncrement;
	float mMoveRate;
	int mMoveAccumulator;

	ImageComponent mKnob;

	std::string mSuffix;
	std::shared_ptr<Font> mFont;
	std::shared_ptr<TextCache> mValueCache;
};

#endif // ES_CORE_COMPONENTS_SLIDER_COMPONENT_H


text:
    //
//  SFViewController.m
//  ZombieArcade
//
//  Created by Adam Iredale on 23/06/10.
//  Copyright 2010 Stormforge Software. All rights reserved.
//

#import "SFViewController.h"
#import "SFGL.h"
#import "SFUtils.h"
#import "SFDebug.h"
#import "SFGameEngine.h"

@implementation SFViewController

@synthesize glView;
@synthesize movieView;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    SFGL::startUp();
    [glView destroyFramebuffer];
    [glView createFramebuffer];
    _loc = new SFVec(3);
    _scl = new SFVec(3);
    _curr_time = [SFUtils getAppTime];
    _accel_smooth = 0.9f;
    [self updateViewPort];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    delete _loc;
    delete _scl;
    [super dealloc];
}

- (IBAction)startGLAnimation{
    //start gl drawing!
    if (glView) {
        [glView startAnimation];
    }
}

- (IBAction)stopGLAnimation{
    //for some reason we need to stop drawing gl - GREE etc
    if (glView) {
        [glView stopAnimation];
    }
}

-(SFVec*)loc{
    return _loc;
}

-(SFVec*)scl{
    return _scl;
}

-(float)deltaTime{
    return _d_time;
}

-(void)doSwapBuffersAccounting{
    _currTime = [SFUtils getAppTime];

    if( _lastSync )
    {
        if (_sync_time >= 1.0f )
        {
            _sync_time = 0.0f;
            _fps = _fra;
            _fra = 0.0f;
        }

        _d_time = SF_CLAMP( ( _currTime - _lastSync ) * 0.001f, 0.0f, 1.0f );
        _sync_time += _d_time;

        ++_fra;
    }

    _lastSync = _currTime;
}

-(void)getViewPortMatrix{
    //PERF ISSUE:
    //this should be called infrequently as it may cause the
    //gl hardware to lockstep with the cpu
    [SFUtils assertGlContext];
    glGetIntegerv( GL_VIEWPORT, (GLint*)&_matViewport);
}

-(void)updateViewPort{
    [SFUtils assertGlContext];
    glViewport(0, 0, [glView backingWidth], [glView backingHeight]);

    [self getViewPortMatrix];

    sfDebug(TRUE, "Viewport Matrix Recalculated:");
    [SFUtils debugIntMatrix:_matViewport width:4 height:1];

    _loc->setVec2(Vec2Make(0,0));

    _scl->setX((float)( _matViewport[2] - _matViewport[0]));
    _scl->setY((float)( _matViewport[3] - _matViewport[1]));
}

-(u_int64_t)currentTime{
    return _currTime;
}

-(u_int64_t)lastSyncTime{
    return _lastSync;
}

-(GLint*)matViewPort{
    return (GLint*)&_matViewport;
}

-(void)moviesFinished:(id)notification{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:SF_NOTIFY_MOVIES_FINISHED
                                                  object:movieView];
    //now ditch the movie view
    [movieView removeFromSuperview];
    [movieView release];
    movieView = nil;
    //and continue animation on the gl view
    [self startGLAnimation];
    //let anyone who is interested know that the movies are over
    [[NSNotificationCenter defaultCenter] postNotificationName:SF_NOTIFY_VIEW_CONTROLLER_EVENT
                                                        object:self];
}

-(void)playMovieList:(NSArray*)movieList{
    //play the list of movies given using the movie view
    //first stop the animation of the gl view and then switch to movie
    //view - once done, return to animating the gl view
    [self stopGLAnimation];
    movieView = [[SFMovieView alloc] initWithMovieList:movieList];
    [[[SFGameEngine mainViewController] view] insertSubview:movieView aboveSubview:glView];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviesFinished:)
                                                 name:SF_NOTIFY_MOVIES_FINISHED
                                               object:movieView];
    [movieView playNextMovie];
}

@end


text:
typedef struct
{
    // The current width of the texture atlas. This is constant.
    taUInt16 width;

    // The current height of the texture atlas. This is constant.
    taUInt16 height;

    // The number of bytes per pixel.
    taUInt32 bpp;

    // Option flags: TA_TEXTURE_PACKER_FLAG_*
    taUInt32 flags;

    // The cursor position on the x axis. This is where the next image will try to be placed.
    taUInt16 cursorPosX;
    taUInt16 cursorPosY;

    // The height of the current row.
    taUInt16 currentRowHeight;

    // The buffer containing the packed image data.
    taUInt8* pImageData;
} taTexturePacker;

typedef struct
{
    taUInt16 posX;
    taUInt16 posY;
    taUInt16 width;
    taUInt16 height;
} taTexturePackerSlot;

// Initializes the given texture packer. The minimum and maximum size should be a power of 2.
taBool32 taTexturePackerInit(taTexturePacker* pPacker, taUInt16 width, taUInt16 height, taUInt32 bytesPerPixel, taUInt32 flags);

// Uninitializes the given texture packer.
void taTexturePackerUninit(taTexturePacker* pPacker);

// Efficiently resets the texture packer. If you need to use a different sized packer you will need to uninitialize
// and re-initialize it.
void taTexturePackerReset(taTexturePacker* pPacker);

// Packs a sub-texture into the packer. If there is no room this will simply return TA_FALSE.
taBool32 taTexturePackerPackSubTexture(taTexturePacker* pPacker, taUInt16 width, taUInt16 height, const void* pSubTextureData, taTexturePackerSlot* pSlotOut);

// Determines if the texture packer is empty or not.
taBool32 taTexturePackerIsEmpty(const taTexturePacker* pPacker);


text:
package org.elasticsearch.license;

import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.watcher.ResourceWatcherService;
import org.junit.After;
import org.junit.Before;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import static org.hamcrest.Matchers.equalTo;

public class OperationModeFileWatcherTests extends ESTestCase {
    private ResourceWatcherService watcherService;
    private TestThreadPool threadPool;
    private Path licenseModePath;
    private OperationModeFileWatcher operationModeFileWatcher;
    private AtomicReference<CountDownLatch> onChangeCounter;

    @Before
    public void setup() throws Exception {
        threadPool = new TestThreadPool("license mode file watcher tests");
        Settings settings = Settings.builder()
                .put("resource.reload.interval.high", "10ms")
                .build();
        watcherService = new ResourceWatcherService(settings, threadPool);
        licenseModePath = createTempFile();
        onChangeCounter = new AtomicReference<>(new CountDownLatch(1));
        operationModeFileWatcher = new OperationModeFileWatcher(watcherService, licenseModePath, logger,
                () -> onChangeCounter.get().countDown());
    }

    @After
    public void shutdown() throws InterruptedException {
        watcherService.close();
        terminate(threadPool);
    }

    public void testInit() throws Exception {
        onChangeCounter.set(new CountDownLatch(2));
        writeMode("gold");
        assertThat(operationModeFileWatcher.getCurrentOperationMode(), equalTo(License.OperationMode.PLATINUM));
        operationModeFileWatcher.init();
        assertTrue(onChangeCounter.get().await(5, TimeUnit.SECONDS));
        assertThat(operationModeFileWatcher.getCurrentOperationMode(), equalTo(License.OperationMode.GOLD));
    }

    public void testUpdateModeFromFile() throws Exception {
        Files.delete(licenseModePath);
        operationModeFileWatcher.init();
        assertThat(operationModeFileWatcher.getCurrentOperationMode(), equalTo(License.OperationMode.PLATINUM));
        writeMode("gold");
        assertTrue(onChangeCounter.get().await(5, TimeUnit.SECONDS));
        assertThat(operationModeFileWatcher.getCurrentOperationMode(), equalTo(License.OperationMode.GOLD));
        onChangeCounter.set(new CountDownLatch(1));
        writeMode("basic");
        assertTrue(onChangeCounter.get().await(5, TimeUnit.SECONDS));
        assertThat(operationModeFileWatcher.getCurrentOperationMode(), equalTo(License.OperationMode.BASIC));
    }

    public void testDeleteModeFromFile() throws Exception {
        Files.delete(licenseModePath);
        operationModeFileWatcher.init();
        writeMode("gold");
        assertTrue(onChangeCounter.get().await(5, TimeUnit.SECONDS));
        assertThat(operationModeFileWatcher.getCurrentOperationMode(), equalTo(License.OperationMode.GOLD));
        onChangeCounter.set(new CountDownLatch(1));

        Files.delete(licenseModePath);
        assertTrue(onChangeCounter.get().await(5, TimeUnit.SECONDS));
        assertThat(operationModeFileWatcher.getCurrentOperationMode(), equalTo(License.OperationMode.PLATINUM));
    }

    public void testInvalidModeFromFile() throws Exception {
        writeMode("invalid");
        operationModeFileWatcher.init();
        assertThat(operationModeFileWatcher.getCurrentOperationMode(), equalTo(License.OperationMode.PLATINUM));
        operationModeFileWatcher.onFileChanged(licenseModePath);
        assertThat(operationModeFileWatcher.getCurrentOperationMode(), equalTo(License.OperationMode.PLATINUM));
    }

    public void testLicenseModeFileIsDirectory() throws Exception {
        licenseModePath = createTempDir();
        operationModeFileWatcher.init();
        assertThat(operationModeFileWatcher.getCurrentOperationMode(), equalTo(License.OperationMode.PLATINUM));
        operationModeFileWatcher.onFileChanged(licenseModePath);
        assertThat(operationModeFileWatcher.getCurrentOperationMode(), equalTo(License.OperationMode.PLATINUM));
    }

    public void testLicenseModeFileCreatedAfterInit() throws Exception {
        Files.delete(licenseModePath);
        operationModeFileWatcher.init();
        assertThat(operationModeFileWatcher.getCurrentOperationMode(), equalTo(License.OperationMode.PLATINUM));
        onChangeCounter.set(new CountDownLatch(1));
        Path tempFile = createTempFile();
        writeMode("gold", tempFile);
        licenseModePath = tempFile;
        assertTrue(onChangeCounter.get().await(5, TimeUnit.SECONDS));
        assertThat(operationModeFileWatcher.getCurrentOperationMode(), equalTo(License.OperationMode.GOLD));
    }

    private void writeMode(String mode) throws IOException {
        writeMode(mode, licenseModePath);
    }

    static void writeMode(String mode, Path file) throws IOException {
        Files.write(file, mode.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);
    }
}


text:
bundle exec rake db:test:prepare

#
# Prepare the cucumber database:
#  - checking if there are migrations not run on the development database
#  - drop cucumber database
#  - create cucumber database
#  - load schema.rb into cucumber database
#
bundle exec rake db:feature_test:prepare

#
# Add users, students, teachers, classes, resources, and assignments
#
RAILS_ENV=cucumber bundle exec rake app:setup:create_default_data

if [ "$1" == "setup" ]; then
    echo
    echo "Spec test setup completed."
    echo
    exit 0
fi

#
# Run spec tests
#
bundle exec rspec spec/