text:
/* AUTOGENERATED FILE. DO NOT EDIT. */

/*=======Test Runner Used To Run Each Test Below=====*/
#define RUN_TEST(TestFunc, TestLineNum) \
{ \
  Unity.CurrentTestName = #TestFunc; \
  Unity.CurrentTestLineNumber = TestLineNum; \
  Unity.NumberOfTests++; \
  if (TEST_PROTECT()) \
  { \
      setUp(); \
      TestFunc(); \
  } \
  if (TEST_PROTECT() && !TEST_IS_IGNORED) \
  { \
    tearDown(); \
  } \
  UnityConcludeTest(); \
}

/*=======Automagically Detected Files To Include=====*/
#include "unity.h"
#include <setjmp.h>
#include <stdio.h>
#include "funky.h"
#include "stanky.h"
#include <setjmp.h>

/*=======External Functions This Runner Calls=====*/
extern void setUp(void);
extern void tearDown(void);
extern void test_TheFirstThingToTest(void);
extern void test_TheSecondThingToTest(void);
extern void test_TheThirdThingToTest(void);
extern void test_TheFourthThingToTest(void);

/*=======Test Reset Option=====*/
void resetTest(void);
void resetTest(void)
{
  tearDown();
  setUp();
}

/*=======MAIN=====*/
int main(void)
{
  UnityBegin("testdata/testsample.c");
  RUN_TEST(test_TheFirstThingToTest, 21);
  RUN_TEST(test_TheSecondThingToTest, 43);
  RUN_TEST(test_TheThirdThingToTest, 53);
  RUN_TEST(test_TheFourthThingToTest, 58);

  return (UnityEnd());
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>GInitable</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.77.1">
<link rel="home" href="index.html" title="GIO Reference Manual">
<link rel="up" href="failable_initialization.html" title="Failable Initialization">
<link rel="prev" href="failable_initialization.html" title="Failable Initialization">
<link rel="next" href="GAsyncInitable.html" title="GAsyncInitable">
<meta name="generator" content="GTK-Doc V1.18 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">

GIO Reference Manual

Top
                   |
                  Description
                   |
                  Object Hierarchy
                   |
                  Prerequisites
                   |
                  Known Derived Interfaces
                   |
                  Known Implementations

GInitable

GInitable — Failable object initialization interface

Synopsis

#include <gio/gio.h>

                    GInitable;
struct              GInitableIface;
gboolean            g_initable_init                     (GInitable *initable,
                                                         GCancellable *cancellable,
                                                         GError **error);
gpointer            g_initable_new                      (GType object_type,
                                                         GCancellable *cancellable,
                                                         GError **error,
                                                         const gchar *first_property_name,
                                                         ...);
GObject *           g_initable_new_valist               (GType object_type,
                                                         const gchar *first_property_name,
                                                         va_list var_args,
                                                         GCancellable *cancellable,
                                                         GError **error);
gpointer            g_initable_newv                     (GType object_type,
                                                         guint n_parameters,
                                                         GParameter *parameters,
                                                         GCancellable *cancellable,
                                                         GError **error);

Object Hierarchy

  GInterface
   +----GInitable

Prerequisites

GInitable requires
 GObject.

Known Derived Interfaces

GInitable is required by
 GNetworkMonitor.

Known Implementations

GInitable is implemented by
 GCharsetConverter,  GDBusConnection,  GDBusObjectManagerClient,  GDBusProxy,  GDBusServer and  GSocket.

Description

GInitable is implemented by objects that can fail during
initialization. If an object implements this interface then
it must be initialized as the first thing after construction,
either via g_initable_init() or g_async_initable_init_async()
(the latter is only available if it also implements GAsyncInitable).

If the object is not initialized, or initialization returns with an
error, then all operations on the object except g_object_ref() and
g_object_unref() are considered to be invalid, and have undefined
behaviour. They will often fail with g_critical() or g_warning(), but
this must not be relied on.

Users of objects implementing this are not intended to use
the interface method directly, instead it will be used automatically
in various ways. For C applications you generally just call
g_initable_new() directly, or indirectly via a foo_thing_new() wrapper.
This will call g_initable_init() under the cover, returning NULL and
setting a GError on failure (at which point the instance is
unreferenced).

For bindings in languages where the native constructor supports
exceptions the binding could check for objects implemention GInitable
during normal construction and automatically initialize them, throwing
an exception on failure.

Details

GInitable

typedef struct _GInitable GInitable;

Interface for initializable objects.

Since 2.22

struct GInitableIface

struct GInitableIface {
  GTypeInterface g_iface;

  /* Virtual Table */

  gboolean    (* init) (GInitable    *initable,
			GCancellable *cancellable,
			GError      **error);
};

Provides an interface for initializing object such that initialization
may fail.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

GTypeInterface g_iface;

The parent interface.

init ()

Initializes the object.

Since 2.22

g_initable_init ()

gboolean            g_initable_init                     (GInitable *initable,
                                                         GCancellable *cancellable,
                                                         GError **error);

Initializes the object implementing the interface.

The object must be initialized before any real use after initial
construction, either with this function or g_async_initable_init_async().

Implementations may also support cancellation. If cancellable is not NULL,
then initialization can be cancelled by triggering the cancellable object
from another thread. If the operation was cancelled, the error
G_IO_ERROR_CANCELLED will be returned. If cancellable is not NULL and
the object doesn't support cancellable initialization the error
G_IO_ERROR_NOT_SUPPORTED will be returned.

If the object is not initialized, or initialization returns with an
error, then all operations on the object except g_object_ref() and
g_object_unref() are considered to be invalid, and have undefined
behaviour. See the ??? section introduction
for more details.

Implementations of this method must be idempotent, i.e. multiple calls
to this function with the same argument should return the same results.
Only the first call initializes the object, further calls return the result
of the first call. This is so that it's safe to implement the singleton
pattern in the GObject constructor function.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

initable :

a GInitable.

cancellable :

optional GCancellable object, NULL to ignore.

error :

a GError location to store the error occurring, or NULL to
ignore.

Returns :

TRUE if successful. If an error has occurred, this function will
return FALSE and set error appropriately if present.

Since 2.22

g_initable_new ()

gpointer            g_initable_new                      (GType object_type,
                                                         GCancellable *cancellable,
                                                         GError **error,
                                                         const gchar *first_property_name,
                                                         ...);

Helper function for constructing GInitable object. This is
similar to g_object_new() but also initializes the object
and returns NULL, setting an error on failure.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

object_type :

a GType supporting GInitable.

cancellable :

optional GCancellable object, NULL to ignore.

error :

a GError location to store the error occurring, or NULL to
ignore.

first_property_name :

the name of the first property, or NULL if no
properties. [<acronym title="NULL is ok, both for passing and for returning.">allow-none</acronym>]

... :

the value if the first property, followed by and other property
value pairs, and ended by NULL.

Returns :

a newly allocated GObject, or NULL on error. [<acronym title="Free data after the code is done.">transfer full</acronym>]

Since 2.22

g_initable_new_valist ()

GObject *           g_initable_new_valist               (GType object_type,
                                                         const gchar *first_property_name,
                                                         va_list var_args,
                                                         GCancellable *cancellable,
                                                         GError **error);

Helper function for constructing GInitable object. This is
similar to g_object_new_valist() but also initializes the object
and returns NULL, setting an error on failure.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

object_type :

a GType supporting GInitable.

first_property_name :

the name of the first property, followed by
the value, and other property value pairs, and ended by NULL.

var_args :

The var args list generated from first_property_name.

cancellable :

optional GCancellable object, NULL to ignore.

error :

a GError location to store the error occurring, or NULL to
ignore.

Returns :

a newly allocated GObject, or NULL on error. [<acronym title="Free data after the code is done.">transfer full</acronym>]

Since 2.22

g_initable_newv ()

gpointer            g_initable_newv                     (GType object_type,
                                                         guint n_parameters,
                                                         GParameter *parameters,
                                                         GCancellable *cancellable,
                                                         GError **error);

Helper function for constructing GInitable object. This is
similar to g_object_newv() but also initializes the object
and returns NULL, setting an error on failure.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

object_type :

a GType supporting GInitable.

n_parameters :

the number of parameters in parameters

parameters :

the parameters to use to construct the object. [<acronym title="Parameter points to an array of items.">array</acronym> length=n_parameters]

cancellable :

optional GCancellable object, NULL to ignore.

error :

a GError location to store the error occurring, or NULL to
ignore.

Returns :

a newly allocated GObject, or NULL on error. [<acronym title="Free data after the code is done.">transfer full</acronym>]

Since 2.22

See Also

GAsyncInitable

          Generated by GTK-Doc V1.18

redpajama_set_name: RedPajamaGithub


text:
static NSString *CELL_KEY = @"cell";

@implementation ProductManagerParameter

@end

@interface ProductManagerViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, weak) IBOutlet UITableView *tblvMain;
@property (nonatomic, assign) NSIndexPath *currentRow;
@property (nonatomic, assign) BOOL editModel;
@property (nonatomic, strong) void(^tapMoreOperate)(ProductManagerCell *cell);
@property (nonatomic, strong) void(^tapEditOperate)(ProductManagerCell *cell);
@property (nonatomic, strong) void(^tapUpOrDownOperate)(ProductManagerCell *cell);
@property (nonatomic, strong) void(^tapShareOperate)(ProductManagerCell *cell);
@property (nonatomic, strong) void(^tapDeleteOperate)(ProductManagerCell *cell);

@property (nonatomic, strong) NSMutableArray *selectedRow;
@property (nonatomic, strong) NSMutableArray *dataSources;

@end

@implementation ProductManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.dataSources = @[@(0), @(1)];

    __weak typeof(self) weakSelf = self;
    self.selectedRow = [NSMutableArray new];
    self.editModel = NO;
    self.currentRow = nil;
    self.tapMoreOperate = ^(ProductManagerCell *cell){
        if(weakSelf.editModel){
            return;
        }
        NSIndexPath *indexPath = [weakSelf.tblvMain indexPathForCell:cell];
        if(indexPath){
            if(weakSelf.currentRow){
                if(weakSelf.currentRow.row == indexPath.row){
                    weakSelf.currentRow = nil;
                    [weakSelf.tblvMain reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                }else{
                    NSIndexPath *temp = weakSelf.currentRow;
                    weakSelf.currentRow = indexPath;
                    [weakSelf.tblvMain reloadRowsAtIndexPaths:@[temp,indexPath] withRowAnimation:UITableViewRowAnimationNone];
                }
            }else{
                weakSelf.currentRow = indexPath;
                [weakSelf.tblvMain reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            }
        }
    };
    self.tapEditOperate = ^(ProductManagerCell *cell){
        NSLog(@"edit");
    };
    self.tapUpOrDownOperate = ^(ProductManagerCell *cell){
        NSLog(@"up or down");
    };
    self.tapShareOperate = ^(ProductManagerCell *cell){
        NSLog(@"share");
    };
    self.tapDeleteOperate = ^(ProductManagerCell *cell){
        NSLog(@"delete");
    };
    [self.tblvMain registerNib:[UINib nibWithNibName:@"ProductManagerCell" bundle:nil] forCellReuseIdentifier:CELL_KEY];
    [self.tblvMain reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:YES];
}

- (void)switchToEditModel:(BOOL)editModel{
    self.currentRow = nil;
    [self.selectedRow removeAllObjects];
    self.editModel = editModel;
    [self.tblvMain reloadData];
}

- (BOOL)allSelected{
    return self.selectedRow.count == self.dataSources.count;
}

- (void)selectRow:(BOOL)selectAll{
    [self.selectedRow removeAllObjects];
    if(selectAll){
        for (NSInteger index=0; index < self.dataSources.count; index++) {
            [self.selectedRow addObject:@(index)];
        }
    }
    CGPoint offset = self.tblvMain.contentOffset;
    [self.tblvMain reloadData];
    self.tblvMain.contentOffset = offset;
    if(self.delegate) {
        [self.delegate viewController:self selectAll:selectAll];
    }
}

- (void)deleteSelectRow{

}

- (void)upOrDwonSelectRow{

}

#pragma mark UITableView

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.editModel){
        return 137.0;
    }else{
        if(self.currentRow && indexPath.row == self.currentRow.row){
            return 177.0;
        }else{
            return 137.0;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSources.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ProductManagerCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL_KEY];
    cell.tapMoreOperate = self.tapMoreOperate;
    cell.tapEditOperate = self.tapEditOperate;
    cell.tapUpOrDownOperate = self.tapUpOrDownOperate;
    cell.tapShareOperate = self.tapShareOperate;
    cell.tapDeleteOperate = self.tapDeleteOperate;
    [cell updateEditModel:self.editModel];
    if(self.editModel){
        if([self.selectedRow containsObject:@(indexPath.row)]){
            [cell updateSelected:YES];
        }else{
            [cell updateSelected:NO];
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.editModel){
        ProductManagerCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if(cell){
            NSNumber *row = @(indexPath.row);
            if([self.selectedRow containsObject:row]){
                [cell updateSelected:NO];
                [self.selectedRow removeObject:row];
            }else{
                [cell updateSelected:YES];
                [self.selectedRow addObject:row];
            }
            if(self.delegate){
                if(self.selectedRow.count == self.dataSources.count){
                    [self.delegate viewController:self selectAll:YES];
                }else{
                    [self.delegate viewController:self selectAll:NO];
                }
            }
        }
    }else{
        ProductPreviewViewController *vc = [ProductPreviewViewController new];
        if(self.navigationController){
            [self.navigationController pushViewController:vc animated:YES];
        }else if(self.parameter && self.parameter.segmentViewController){
            [self.parameter.segmentViewController.navigationController pushViewController:vc animated:YES];
        }
    }
}

@end


text:
<meta http-equiv="content-type" content="text/html; charset=utf-8">
  1 /**
  2  * (Required)申请权限,每个URL只调用一次
  3  * @param boolean location 定位权限
  4  * @param boolean notify 发送系统通知权限
  5  * @param boolean vibration 震动手机权限
  6  */
  7 config : function(location, notify, vibration) {
  8 }
  9 /**
 10  * 申请定位(异步)
 11  * @author YOLANDA
 12  * @param string succeed 定位成功后执行的方法,方法须包含一个参数
 13  * @param string failed 定位失败后的方法,方法须包含一个参数
 14  */
 15 location : function(succeed, failed) {
 16 }
 17 /**
 18  * 发送通知
 19  * @author YOLANDA
 20  * @param string title 通知的标题
 21  * @param string message 通知的内容
 22  */
 23 notify : function(title, message) {
 24 }
 25 /**
 26  * 震动手机
 27  * @param long time 单位是毫秒,推荐200 - 500
 28  */
 29 vibration : function(time) {
 30 }
 31 /**
 32  * 显示一个普通消息
 33  * @author YOLANDA
 34  * @param string message 消息内容
 35  */
 36 message : function(message) {
 37 }
 38 /**
 39  * 设置标题
 40  * @author YOLANDA
 41  * @param string title 标题内容
 42  */
 43 setTitle:function(title) {
 44 }


text:
package cmd

import (
	"encoding/binary"
	"fmt"
	"math/rand"
	"os"
	"time"

	v3 "github.com/coreos/etcd/clientv3"
	v3sync "github.com/coreos/etcd/clientv3/concurrency"
	"github.com/coreos/etcd/pkg/report"

	"github.com/spf13/cobra"
	"golang.org/x/net/context"
	"gopkg.in/cheggaaa/pb.v1"
)

// stmCmd represents the STM benchmark command
var stmCmd = &cobra.Command{
	Use:   "stm",
	Short: "Benchmark STM",

	Run: stmFunc,
}

type stmApply func(v3sync.STM) error

var (
	stmIsolation string
	stmIso       v3sync.Isolation

	stmTotal        int
	stmKeysPerTxn   int
	stmKeyCount     int
	stmValSize      int
	stmWritePercent int
	stmMutex        bool
)

func init() {
	RootCmd.AddCommand(stmCmd)

	stmCmd.Flags().StringVar(&stmIsolation, "isolation", "r", "Read Committed (c), Repeatable Reads (r), Serializable (s), or Snapshot (ss)")
	stmCmd.Flags().IntVar(&stmKeyCount, "keys", 1, "Total unique keys accessible by the benchmark")
	stmCmd.Flags().IntVar(&stmTotal, "total", 10000, "Total number of completed STM transactions")
	stmCmd.Flags().IntVar(&stmKeysPerTxn, "keys-per-txn", 1, "Number of keys to access per transaction")
	stmCmd.Flags().IntVar(&stmWritePercent, "txn-wr-percent", 50, "Percentage of keys to overwrite per transaction")
	stmCmd.Flags().BoolVar(&stmMutex, "use-mutex", false, "Wrap STM transaction in a distributed mutex")
	stmCmd.Flags().IntVar(&stmValSize, "val-size", 8, "Value size of each STM put request")
}

func stmFunc(cmd *cobra.Command, args []string) {
	if stmKeyCount <= 0 {
		fmt.Fprintf(os.Stderr, "expected positive --keys, got (%v)", stmKeyCount)
		os.Exit(1)
	}

	if stmWritePercent < 0 || stmWritePercent > 100 {
		fmt.Fprintf(os.Stderr, "expected [0, 100] --txn-wr-percent, got (%v)", stmWritePercent)
		os.Exit(1)
	}

	if stmKeysPerTxn < 0 || stmKeysPerTxn > stmKeyCount {
		fmt.Fprintf(os.Stderr, "expected --keys-per-txn between 0 and %v, got (%v)", stmKeyCount, stmKeysPerTxn)
		os.Exit(1)
	}

	switch stmIsolation {
	case "c":
		stmIso = v3sync.ReadCommitted
	case "r":
		stmIso = v3sync.RepeatableReads
	case "s":
		stmIso = v3sync.Serializable
	case "ss":
		stmIso = v3sync.Snapshot
	default:
		fmt.Fprintln(os.Stderr, cmd.Usage())
		os.Exit(1)
	}

	requests := make(chan stmApply, totalClients)
	clients := mustCreateClients(totalClients, totalConns)

	bar = pb.New(stmTotal)
	bar.Format("Bom !")
	bar.Start()

	r := newReport()
	for i := range clients {
		wg.Add(1)
		go doSTM(clients[i], requests, r.Results())
	}

	go func() {
		for i := 0; i < stmTotal; i++ {
			kset := make(map[string]struct{})
			for len(kset) != stmKeysPerTxn {
				k := make([]byte, 16)
				binary.PutVarint(k, int64(rand.Intn(stmKeyCount)))
				s := string(k)
				kset[s] = struct{}{}
			}

			applyf := func(s v3sync.STM) error {
				wrs := int(float32(len(kset)*stmWritePercent) / 100.0)
				for k := range kset {
					s.Get(k)
					if wrs > 0 {
						s.Put(k, string(mustRandBytes(stmValSize)))
						wrs--
					}
				}
				return nil
			}

			requests <- applyf
		}
		close(requests)
	}()

	rc := r.Run()
	wg.Wait()
	close(r.Results())
	bar.Finish()
	fmt.Printf("%s", <-rc)
}

func doSTM(client *v3.Client, requests <-chan stmApply, results chan<- report.Result) {
	defer wg.Done()

	var m *v3sync.Mutex
	if stmMutex {
		s, err := v3sync.NewSession(client)
		if err != nil {
			panic(err)
		}
		m = v3sync.NewMutex(s, "stmlock")
	}

	for applyf := range requests {
		st := time.Now()
		if m != nil {
			m.Lock(context.TODO())
		}
		_, err := v3sync.NewSTM(client, applyf, v3sync.WithIsolation(stmIso))
		if m != nil {
			m.Unlock(context.TODO())
		}
		results <- report.Result{Err: err, Start: st, End: time.Now()}
		bar.Increment()
	}
}


text:
/* @test
 * @bug 7082443
 * @summary JComboBox not backward compatible (with Java 6)
 * @author Pavel Porvatov
 */

import javax.swing.*;
import java.awt.*;

public class bug7082443 {
    public static final String GTK_LAF_CLASS = "GTKLookAndFeel";

    public static void main(String[] args) throws Exception {
        for (UIManager.LookAndFeelInfo lookAndFeelInfo : UIManager.getInstalledLookAndFeels()) {
            if (lookAndFeelInfo.getClassName().contains(GTK_LAF_CLASS)) {
                UIManager.setLookAndFeel(lookAndFeelInfo.getClassName());

                SwingUtilities.invokeAndWait(new Runnable() {
                    @Override
                    public void run() {
                        TestComboBox testComboBox = new TestComboBox();

                        if (testComboBox.isOldRendererOpaque()) {
                            System.out.println("Passed for " + GTK_LAF_CLASS);
                        } else {
                            throw new RuntimeException("Failed for " + GTK_LAF_CLASS);
                        }
                    }
                });

                return;
            }
        }

        System.out.println(GTK_LAF_CLASS + " is not found. The test skipped");
    }

    private static class TestComboBox extends JComboBox {
        private final ListCellRenderer renderer = new ListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList list, Object value, int index,
                                                          boolean isSelected, boolean cellHasFocus) {
                return TestComboBox.super.getRenderer().getListCellRendererComponent(list, value, index,
                        isSelected, cellHasFocus);
            }
        };

        @Override
        public ListCellRenderer getRenderer() {
            return renderer;
        }

        public boolean isOldRendererOpaque() {
            return ((JLabel) super.getRenderer()).isOpaque();
        }
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__int64_t_rand_square_12.c
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-12.tmpl.c
*/
/*
 * @description
 * CWE: 190 Integer Overflow
 * BadSource: rand Set data to result of rand()
 * GoodSource: Set data to a small, non-zero number (two)
 * Sinks: square
 *    GoodSink: Ensure there will not be an overflow before squaring data
 *    BadSink : Square data, which can lead to overflow
 * Flow Variant: 12 Control flow: if(globalReturnsTrueOrFalse())
 *
 * */

#include "std_testcase.h"

#include <math.h>

#ifndef OMITBAD

void CWE190_Integer_Overflow__int64_t_rand_square_12_bad()
{
    int64_t data;
    data = 0LL;
    if(globalReturnsTrueOrFalse())
    {
        /* POTENTIAL FLAW: Use a random value */
        data = (int64_t)RAND64();
    }
    else
    {
        /* FIX: Use a small, non-zero value that will not cause an overflow in the sinks */
        data = 2;
    }
    if(globalReturnsTrueOrFalse())
    {
        {
            /* POTENTIAL FLAW: if (data*data) > LLONG_MAX, this will overflow */
            int64_t result = data * data;
            printLongLongLine(result);
        }
    }
    else
    {
        /* FIX: Add a check to prevent an overflow from occurring */
        if (abs((long)data) <= (long)sqrt((double)LLONG_MAX))
        {
            int64_t result = data * data;
            printLongLongLine(result);
        }
        else
        {
            printLine("data value is too large to perform arithmetic safely.");
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G() - use badsource and goodsink by changing the first "if" so that
   both branches use the BadSource and the second "if" so that both branches
   use the GoodSink */
static void goodB2G()
{
    int64_t data;
    data = 0LL;
    if(globalReturnsTrueOrFalse())
    {
        /* POTENTIAL FLAW: Use a random value */
        data = (int64_t)RAND64();
    }
    else
    {
        /* POTENTIAL FLAW: Use a random value */
        data = (int64_t)RAND64();
    }
    if(globalReturnsTrueOrFalse())
    {
        /* FIX: Add a check to prevent an overflow from occurring */
        if (abs((long)data) <= (long)sqrt((double)LLONG_MAX))
        {
            int64_t result = data * data;
            printLongLongLine(result);
        }
        else
        {
            printLine("data value is too large to perform arithmetic safely.");
        }
    }
    else
    {
        /* FIX: Add a check to prevent an overflow from occurring */
        if (abs((long)data) <= (long)sqrt((double)LLONG_MAX))
        {
            int64_t result = data * data;
            printLongLongLine(result);
        }
        else
        {
            printLine("data value is too large to perform arithmetic safely.");
        }
    }
}

/* goodG2B() - use goodsource and badsink by changing the first "if" so that
   both branches use the GoodSource and the second "if" so that both branches
   use the BadSink */
static void goodG2B()
{
    int64_t data;
    data = 0LL;
    if(globalReturnsTrueOrFalse())
    {
        /* FIX: Use a small, non-zero value that will not cause an overflow in the sinks */
        data = 2;
    }
    else
    {
        /* FIX: Use a small, non-zero value that will not cause an overflow in the sinks */
        data = 2;
    }
    if(globalReturnsTrueOrFalse())
    {
        {
            /* POTENTIAL FLAW: if (data*data) > LLONG_MAX, this will overflow */
            int64_t result = data * data;
            printLongLongLine(result);
        }
    }
    else
    {
        {
            /* POTENTIAL FLAW: if (data*data) > LLONG_MAX, this will overflow */
            int64_t result = data * data;
            printLongLongLine(result);
        }
    }
}

void CWE190_Integer_Overflow__int64_t_rand_square_12_good()
{
    goodB2G();
    goodG2B();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE190_Integer_Overflow__int64_t_rand_square_12_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE190_Integer_Overflow__int64_t_rand_square_12_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
UPDATE validation_options
SET text = 'notsure'
WHERE text = 'unclear';

-- For users who validated the same label multiple times, remove all but the newest validation.
DELETE
FROM label_validation val_a
    USING label_validation val_b
WHERE val_a.label_id = val_b.label_id
  AND val_a.user_id = val_b.user_id
  AND val_a.end_timestamp < val_b.end_timestamp;

-- Add validation count columns to the label table.
ALTER TABLE label
    ADD COLUMN agree_count INTEGER NOT NULL DEFAULT 0,
    ADD COLUMN disagree_count INTEGER NOT NULL DEFAULT 0,
    ADD COLUMN notsure_count INTEGER NOT NULL DEFAULT 0,
    ADD COLUMN correct BOOLEAN;

-- Populate table with current validation info.
UPDATE label
SET (agree_count, disagree_count, notsure_count, correct) = (n_agree, n_disagree, n_notsure, is_correct)
FROM (
     SELECT label.label_id,
            COUNT(CASE WHEN validation_result = 1 THEN 1 END) AS n_agree,
            COUNT(CASE WHEN validation_result = 2 THEN 1 END) AS n_disagree,
            COUNT(CASE WHEN validation_result = 3 THEN 1 END) AS n_notsure,
            CASE
                WHEN COUNT(CASE WHEN validation_result = 1 THEN 1 END) > COUNT(CASE WHEN validation_result = 2 THEN 1 END) THEN TRUE
                WHEN COUNT(CASE WHEN validation_result = 2 THEN 1 END) > COUNT(CASE WHEN validation_result = 1 THEN 1 END) THEN FALSE
                ELSE NULL
            END AS is_correct
     FROM mission
     INNER JOIN label ON mission.mission_id = label.mission_id
     INNER JOIN label_validation
        ON label.label_id = label_validation.label_id AND mission.user_id <> label_validation.user_id
     GROUP BY label.label_id
 ) AS validation_count
WHERE label.label_id = validation_count.label_id;

TRUNCATE TABLE global_clustering_session CASCADE;
TRUNCATE TABLE user_clustering_session CASCADE;

ALTER TABLE global_attribute
    ADD COLUMN street_edge_id INTEGER NOT NULL DEFAULT -1;

# --- !Downs
ALTER TABLE global_attribute DROP COLUMN street_edge_id;

ALTER TABLE label
    DROP COLUMN correct,
    DROP COLUMN notsure_count,
    DROP COLUMN disagree_count,
    DROP COLUMN agree_count;

UPDATE validation_options
SET text = 'unclear'
WHERE text = 'notsure';


text:
Advanced Databox Development
============================

Some developers may find that what they want to create goes beyond what they can use the SDK for. Expecially when designing drivers or tweaking system components, it becomes necessary to get your hands dirty and develop at the container level.

The workflow for writing, testing, and debugging code that runs in Docker containers can be a painful and arduous process. This guide describes a practical development cycle, with a focus on writing drivers and apps for Databox.

Preparing a Staging Container
-----------------------------

Depending on the language and framework you want to develop in, you may find some template Dockerfiles already provided. The following instructions can apply to any language, but for the purpose of this guide, we'll use a basic Dockerfile for a Databox app written in Node.js from `databox-app-template-node`.

    # Use node:alpine base image
    FROM node:alpine

    # Copy files from working directory to container root
    COPY . .
    # Install dependencies
    RUN npm install

    # Add Databox container type label
    LABEL databox.type="app"

    # Start program
    CMD ["npm","start"]

Note three things:
  - Our working directory within the container is the default (root). You may prefer to `ADD`/`COPY` files elsewhere and set a new working directory with `WORKDIR`. If so, make note of the location.
  - Because this is an interpreted language, we have no compliation step. If you are using a compiled language (e.g. based off of the Java template) make note of the compilation command.
  - The container will start running with `npm start` and exit when that command exits.

Normally, in this dev environment, if we want to modify, rebuild, and rerun our program, we would have to stop and remove the container first, build a new container image, push it to the local registry, then re-launch it, and cross our fingers that we didn't make a stupid mistake when querying Docker logs. This is too impractical.

We want to launch this container once, and be limited at most by the time it takes to build our code. One way we can achieve this is by setting up a container for staging. To do so, have the container start and keep itself alive, by for example changing the last line in the Dockerfile to:

    CMD ["sleep","2147483647"]

Now build and push this container as usual to the local registry. If you're using a template repo, refer to its documentation as it may have scripts built in to do this automatically. Otherwise, you can use the Docker CLI in the following manner, replacing the container name with what your component is called:

    docker build -t databox-app-template-node .
    docker tag databox-app-template-node localhost:5000/databox-app-template-node
    docker push localhost:5000/databox-app-template-node

Similarly, if you're deploying your container on a different host (such as an actual Databox) replace `localhost` with its hostname or IP address.

Before you can launch the container, you must also upload its manifest to a local development manifest server, in the same way you would when publishing an app or driver. Browse to port 8181 on the host (e.g. http://localhost:8181) and follow the instructions there. As long as you don't need to update your container manifest, you will only need to do this once.

Now you can launch your container through the dashboard by browsing to the URL indicated by the Databox system. If you're deploying on the same host that you're developing on, this will likely be http://localhost:8989.

Once launched the container should do nothing yet.

Running your Code
-----------------

Having set up this container, you can now manually have it launch your program through the Docker CLI. For the above example:

    docker exec -it databox-app-template-node npm start

Program output will be written straight to stdout, and on exiting, the container will remain alive.

Modifying and Rerunning your Code
---------------------------------

So you had some errors, did some debugging, and want your latest source code to run in that same container. To do so, we use the Docker CLI to copy some or all files in our working directory, to the container working directory. In the above Dockerfile, the latter is the root directory.

    docker cp . databox-app-template-node:/

This is the point at which if you were programming in a compiled language, you would recompile inside the container before rerunning it, e.g.

    docker exec -it databox-app-template-node javac *.java

For our example, we only need to rerun it:

    docker exec -it databox-app-template-node npm start

Build Systems
-------------

It may be possible to instead launch a program that watches for file changes (`watch`, `nodemon`, `forever`, etc) and triggers a build script and/or relaunches your program inside Docker. To do this, you would simply need to replace the `CMD` command in your Dockerfile with one that starts the file watcher.

Then you can have the same host-side that triggers `docker cp` when you've changed your source code. This would make it so that every time you hit save on your source code, the the Docker container in Databox automatically "hot-swaps" your program.

Doing so may not always work however, as most of these tools rely on `inotify` to detect file changes, which can be feeble in Docker containers. They may fall back to polling files, which is slow, inefficient, and wastes resources.

Tweaking UIs
------------

> :warning: Warning: The way UIs work may change soon, so this may become deprecated

In most cases, you will not need to relaunch your program to update a web UI. Once you copy your modified files over, you can simply refresh the UI page, i.e. after something like:

    docker cp ./www databox-app-template-node:/www

Debugging Container Permissions
-------------------------------

This should be rare, but if somehow you find that stores are rejecting your requests even though you think your container has the correct permissions, you can check Arbiter records by browsing to the Arbiter UI in the dashboard, and hopefully narrow down what's missing.

Mock Containers
---------------

> :construction: Coming soon!


text:
using System;
using System.Collections.Generic;

namespace com.vzaar.api
{
	public class VideoDetails
	{
		public string version;
		public string type;

		public string title;
		public string description;
		public bool borderless;

		public decimal duration;

		public int height;
		public int width;

		public string url;
		public string poster;
		public string html;

		public Int64 playCount;
		public Int64 totalSize;

		public VideoDetailsAuthor author;
		public VideoDetailsProvider provider;
		public VideoDetailsThumbnail thumbnail;
		public VideoDetailsFramegrab framegrab;
		public VideoDetailsVideoStatus videoStatus;
        public List<VideoRendition> renditions = new List<VideoRendition>();

	}

	public class VideoDetailsVideoStatus
	{
		public int id;
		public string description;
	}

	public class VideoDetailsAuthor
	{
		public string name;
		public string url;
	}

	public class VideoDetailsProvider
	{
		public string name;
		public string url;
	}

	public class VideoDetailsThumbnail
	{
		public int width;
		public int height;
		public string url;
	}

	public class VideoDetailsFramegrab
	{
		public int width;
		public int height;
		public string url;
	}

    public class VideoRendition
    {
        public int statusId;
        public string status;
        public string type;
    }
}


text:
        Mapping ({{model.Id}})

          <button *ngIf="showActionButtons" type="button" class="icon-button" (click)="mappingEdit.show()"></button>
          <button *ngIf="showActionButtons" type="button" class="icon-button" (click)="deleteItem.show()"></button>

CmEnvironmentId

{{model.CmEnvironmentId}}

PublicationId

{{model.PublicationId}}

EnvironmentPurpose

{{model.EnvironmentPurpose}}

WebApplicationId

{{model.WebApplicationId}}

RelativeUrl

{{model.RelativeUrl}}

PrimaryMappedUrl

{{model.PrimaryMappedUrl}}

IsOffline

{{model.IsOffline}}

          {{c.Name}}
          {{c.Value}}

  <mapping-edit #mappingEdit [Model]="model"></mapping-edit>
  <delete-item #deleteItem [Model]="model" (onDelete)="delete($event)"></delete-item>


text:
OCAMLINCLUDES += ../common

FILES[] +=
	cfg/printer_tests
	cfg/cfg_suite
	cfg/refactor_tests
	cfg/scope_cfg_tests
	cfg/cfg_test_helper
	cfg/cfg_locals_test
	cfg/iface_to_cfg_test
	cfg/iface_progs

../unit_tests.results:	\
	$(glob iface_succeed/*/*)	\
	$(glob iface_fail iface_succeed/*/*)


text:
template<typename T, typename Signature> class Event;

#pragma region classes generation

// R ()
#define FX_TYPES
#define FX_PARAMS
#define FX_ARGS

#include "DelegateEvent.hpp"

#undef FX_TYPES
#undef FX_PARAMS
#undef FX_ARGS

// R (P0 a0)

#define FX_TYPES , typename P0
#define FX_PARAMS P0 a0
#define FX_ARGS a0

#include "DelegateEvent.hpp"

#undef FX_TYPES
#undef FX_PARAMS
#undef FX_ARGS

// R (P0 a0, P1 a1)

#define FX_TYPES , typename P0, typename P1
#define FX_PARAMS P0 a0, P1 a1
#define FX_ARGS a0, a1

#include "DelegateEvent.hpp"

#undef FX_TYPES
#undef FX_PARAMS
#undef FX_ARGS

// R (P0 a0, P1 a1, P2 a2)

#define FX_TYPES , typename P0, typename P1, typename P2
#define FX_PARAMS P0 a0, P1 a1, P2 a2
#define FX_ARGS a0, a1, a2

#include "DelegateEvent.hpp"

#undef FX_TYPES
#undef FX_PARAMS
#undef FX_ARGS

// R (P0 a0, P1 a1, P2 a2, P3 a3)

#define FX_TYPES , typename P0, typename P1, typename P2, typename P3
#define FX_PARAMS P0 a0, P1 a1, P2 a2, P3 a3
#define FX_ARGS a0, a1, a2, a3

#include "DelegateEvent.hpp"

#undef FX_TYPES
#undef FX_PARAMS
#undef FX_ARGS

#pragma endregion

#ifdef DFTS_RESTORE_NEW
#pragma pop_macro("new")
#undef DFTS_RESTORE_NEW
#endif
#endif


text:
package pl.letscode.tanks.player;

import java.io.IOException;

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

import pl.letscode.tanks.guice.GuiceInjector;
import pl.letscode.tanks.session.Session;

import com.google.inject.Injector;

/**
 * Servlet used to choose name and join the game.
 */
public class UsernameServlet extends HttpServlet {

	private static final long serialVersionUID = 8628963769752471982L;
	private static final String USERNAME = "playerName";
	private static final String FORM_URL = "/index.jsp";
	private static final String GAME_URL = "/client/index.html";

	private static final Injector INJECTOR = GuiceInjector.getInstance();

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Session sessions = INJECTOR.getInstance(Session.class);
		String sessionId = request.getSession(true).getId();
		Player player = sessions.get(sessionId);

		if (player != null) {
			request.getRequestDispatcher(GAME_URL).forward(request, response);
		} else {
			request.getRequestDispatcher(FORM_URL).forward(request, response);
		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Session session = INJECTOR.getInstance(Session.class);
		String sessionId = request.getSession(true).getId();

		String username = request.getParameter(USERNAME);

		Player player = session.get(sessionId);

		PlayerFactory factory = INJECTOR.getInstance(PlayerFactory.class);
		PlayerRepository repository = INJECTOR.getInstance(PlayerRepository.class);

		// what if player pressed F5
		if (player != null) {
			request.getRequestDispatcher(GAME_URL).forward(request, response);
		} else if (username != null && !repository.existsByName(username)) {
			Player newPlayer = factory.createPlayer(username);
			session.put(sessionId, newPlayer);
			repository.save(newPlayer);
			request.getRequestDispatcher(GAME_URL).forward(request, response);
		} else {
			request.getRequestDispatcher(FORM_URL).forward(request, response);
		}
	}

}


text:
<?php

namespace Aidantwoods\SecureHeaders;

interface ExposesErrors
{
    /**
     * Return an array of Errors, clearing any stored Errors
     *
     * @param void
     * @return Error[]
     */
    public function collectErrors();
}


text:
define([

], function () {
  function Translation (dict) {
    this.dict = dict || {};
  }

  Translation.prototype.all = function () {
    return this.dict;
  };

  Translation.prototype.get = function (key) {
    return this.dict[key];
  };

  Translation.prototype.extend = function (translation) {
    this.dict = $.extend({}, translation.all(), this.dict);
  };

  // Static functions

  Translation._cache = {};

  Translation.loadPath = function (path) {
    if (!(path in Translation._cache)) {
      var translations = require(path);

      Translation._cache[path] = translations;
    }

    return new Translation(Translation._cache[path]);
  };

  return Translation;
});


text:
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var React = require('react');
var core = require('primereact/core');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);

function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

function _defineProperties(target, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target, descriptor.key, descriptor);
  }
}

function _createClass(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties(Constructor, staticProps);
  return Constructor;
}

function _assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return self;
}

function _setPrototypeOf(o, p) {
  _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };

  return _setPrototypeOf(o, p);
}

function _inherits(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }

  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      writable: true,
      configurable: true
    }
  });
  if (superClass) _setPrototypeOf(subClass, superClass);
}

function _typeof(obj) {
  "@babel/helpers - typeof";

  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof = function _typeof(obj) {
      return typeof obj;
    };
  } else {
    _typeof = function _typeof(obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
  }

  return _typeof(obj);
}

function _possibleConstructorReturn(self, call) {
  if (call && (_typeof(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }

  return _assertThisInitialized(self);
}

function _getPrototypeOf(o) {
  _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return _getPrototypeOf(o);
}

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var ToggleButton = /*#__PURE__*/function (_Component) {
  _inherits(ToggleButton, _Component);

  var _super = _createSuper(ToggleButton);

  function ToggleButton(props) {
    var _this;

    _classCallCheck(this, ToggleButton);

    _this = _super.call(this, props);
    _this.toggle = _this.toggle.bind(_assertThisInitialized(_this));
    _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this));
    return _this;
  }

  _createClass(ToggleButton, [{
    key: "toggle",
    value: function toggle(e) {
      if (!this.props.disabled && this.props.onChange) {
        this.props.onChange({
          originalEvent: e,
          value: !this.props.checked,
          stopPropagation: function stopPropagation() {},
          preventDefault: function preventDefault() {},
          target: {
            name: this.props.name,
            id: this.props.id,
            value: !this.props.checked
          }
        });
      }
    }
  }, {
    key: "onKeyDown",
    value: function onKeyDown(event) {
      if (event.key === 'Enter') {
        this.toggle(event);
        event.preventDefault();
      }
    }
  }, {
    key: "hasLabel",
    value: function hasLabel() {
      return this.props.onLabel && this.props.onLabel.length > 0 && this.props.offLabel && this.props.offLabel.length > 0;
    }
  }, {
    key: "hasIcon",
    value: function hasIcon() {
      return this.props.onIcon && this.props.onIcon.length > 0 && this.props.offIcon && this.props.offIcon.length > 0;
    }
  }, {
    key: "getLabel",
    value: function getLabel() {
      return this.hasLabel() ? this.props.checked ? this.props.onLabel : this.props.offLabel : ' ';
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      if (this.props.tooltip) {
        this.renderTooltip();
      }
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      if (prevProps.tooltip !== this.props.tooltip || prevProps.tooltipOptions !== this.props.tooltipOptions) {
        if (this.tooltip) this.tooltip.update(_objectSpread({
          content: this.props.tooltip
        }, this.props.tooltipOptions || {}));else this.renderTooltip();
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      if (this.tooltip) {
        this.tooltip.destroy();
        this.tooltip = null;
      }
    }
  }, {
    key: "renderTooltip",
    value: function renderTooltip() {
      this.tooltip = core.tip({
        target: this.container,
        content: this.props.tooltip,
        options: this.props.tooltipOptions
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var className = core.classNames('p-button p-togglebutton p-component', {
        'p-button-icon-only': this.hasIcon() && !this.hasLabel(),
        'p-highlight': this.props.checked,
        'p-disabled': this.props.disabled
      }, this.props.className),
          iconClassName = null;
      var hasIcon = this.hasIcon();
      var label = this.getLabel();

      if (hasIcon) {
        iconClassName = core.classNames('p-button-icon p-c', {
          'p-button-icon-left': this.props.iconPos === 'left' && label,
          'p-button-icon-right': this.props.iconPos === 'right' && label
        }, this.props.checked ? this.props.onIcon : this.props.offIcon);
      }

      return /*#__PURE__*/React__default['default'].createElement("div", {
        ref: function ref(el) {
          return _this2.container = el;
        },
        id: this.props.id,
        className: className,
        style: this.props.style,
        onClick: this.toggle,
        onFocus: this.props.onFocus,
        onBlur: this.props.onBlur,
        onKeyDown: this.onKeyDown,
        tabIndex: !this.props.disabled && this.props.tabIndex,
        "aria-labelledby": this.props.ariaLabelledBy
      }, hasIcon && /*#__PURE__*/React__default['default'].createElement("span", {
        className: iconClassName
      }), /*#__PURE__*/React__default['default'].createElement("span", {
        className: "p-button-label"
      }, label), /*#__PURE__*/React__default['default'].createElement(core.Ripple, null));
    }
  }]);

  return ToggleButton;
}(React.Component);

_defineProperty(ToggleButton, "defaultProps", {
  id: null,
  onIcon: null,
  offIcon: null,
  onLabel: 'Yes',
  offLabel: 'No',
  iconPos: 'left',
  style: null,
  className: null,
  checked: false,
  tabIndex: 0,
  tooltip: null,
  tooltipOptions: null,
  ariaLabelledBy: null,
  onChange: null,
  onFocus: null,
  onBlur: null
});

exports.ToggleButton = ToggleButton;


text:
using System;
/*Problem 12. Extract Bit from Integer

Write an expression that extracts from given integer n the value of given bit at index p.*/

namespace ExtractBitFromInteger
{
    class ExtractBitFromInteger
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter integer number");
            int number = int.Parse(Console.ReadLine());
            Console.WriteLine("The binary representation is:" + Convert.ToString(number, 2).PadLeft(32, '0'));
            Console.WriteLine("Please enter number of the bit which index you'd like to see:");
            int p = int.Parse(Console.ReadLine());
            int mask = 1 << p;
            int nAndMask = number & mask;
            int bit = nAndMask >> p;
            Console.WriteLine(bit);
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Disk</title>
<meta name="date" content="2013-12-01">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

edu.ku.eecs.db.disk

Class Disk

java.lang.Object

edu.ku.eecs.db.disk.Disk

public class Disk
extends java.lang.Object

Author:

hgrimberg

 Class that simulates a disk. A disk contains a page table of a given
 capacity and page size.

Constructor Summary

Constructors

Constructor and Description

Disk(int sizeInBytes)

Disk(int sizeInBytes,
    int pageSize)

Method Summary

Methods

Modifier and Type
Method and Description

PageTable
getPageTable()

void
setPageTable(PageTable pageTable)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Disk

public Disk(int sizeInBytes)

Parameters:

sizeInBytes -

Disk

public Disk(int sizeInBytes,
    int pageSize)

Parameters:

sizeInBytes -

pageSize -

Method Detail

getPageTable

public PageTable getPageTable()

Returns:

setPageTable

public void setPageTable(PageTable pageTable)

Parameters:

pageTable -

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
#include "v_video.h"
#include "v_font.h"
#include "cmdlib.h"
#include "gstrings.h"
#include "g_level.h"
#include "gi.h"
#include "v_palette.h"
#include "d_gui.h"
#include "d_event.h"
#include "c_dispatch.h"
#include "c_console.h"
#include "c_cvars.h"
#include "c_bind.h"
#include "gameconfigfile.h"
#include "menu/menu.h"

//=============================================================================
//
// Draws a string in the console font, scaled to the 8x8 cells
// used by the default console font.
//
//=============================================================================

void M_DrawConText (int color, int x, int y, const char *str)
{
	screen->DrawText (ConFont, color, x, y, str,
		DTA_CellX, 8 * CleanXfac_1,
		DTA_CellY, 8 * CleanYfac_1,
		TAG_DONE);
}

IMPLEMENT_CLASS(DOptionMenu)

//=============================================================================
//
//
//
//=============================================================================

DOptionMenu::DOptionMenu(DMenu *parent, FOptionMenuDescriptor *desc)
: DMenu(parent)
{
	CanScrollUp = false;
	CanScrollDown = false;
	VisBottom = 0;
	mFocusControl = NULL;
	Init(parent, desc);
}

//=============================================================================
//
//
//
//=============================================================================

void DOptionMenu::Init(DMenu *parent, FOptionMenuDescriptor *desc)
{
	mParentMenu = parent;
	GC::WriteBarrier(this, parent);
	mDesc = desc;
	if (mDesc != NULL && mDesc->mSelectedItem == -1) mDesc->mSelectedItem = FirstSelectable();

}

//=============================================================================
//
//
//
//=============================================================================

int DOptionMenu::FirstSelectable()
{
	if (mDesc != NULL)
	{
		// Go down to the first selectable item
		int i = -1;
		do
		{
			i++;
		}
		while (i < (int)mDesc->mItems.Size() && !mDesc->mItems[i]->Selectable());
		if (i>=0 && i < (int)mDesc->mItems.Size()) return i;
	}
	return -1;
}

//=============================================================================
//
//
//
//=============================================================================

FOptionMenuItem *DOptionMenu::GetItem(FName name)
{
	for(unsigned i=0;i<mDesc->mItems.Size(); i++)
	{
		FName nm = mDesc->mItems[i]->GetAction(NULL);
		if (nm == name) return mDesc->mItems[i];
	}
	return NULL;
}

//=============================================================================
//
//
//
//=============================================================================

bool DOptionMenu::Responder (event_t *ev)
{
	if (ev->type == EV_GUI_Event)
	{
		if (ev->subtype == EV_GUI_WheelUp)
		{
			int scrollamt = MIN(2, mDesc->mScrollPos);
			mDesc->mScrollPos -= scrollamt;
			return true;
		}
		else if (ev->subtype == EV_GUI_WheelDown)
		{
			if (CanScrollDown)
			{
				if (VisBottom < (int)(mDesc->mItems.Size()-2))
				{
					mDesc->mScrollPos += 2;
					VisBottom += 2;
				}
				else
				{
					mDesc->mScrollPos++;
					VisBottom++;
				}
			}
			return true;
		}
	}
	return Super::Responder(ev);
}

//=============================================================================
//
//
//
//=============================================================================

bool DOptionMenu::MenuEvent (int mkey, bool fromcontroller)
{
	int startedAt = mDesc->mSelectedItem;

	switch (mkey)
	{
	case MKEY_Up:
		if (mDesc->mSelectedItem == -1)
		{
			mDesc->mSelectedItem = FirstSelectable();
			break;
		}
		do
		{
			--mDesc->mSelectedItem;

			if (mDesc->mScrollPos > 0 &&
				mDesc->mSelectedItem <= mDesc->mScrollTop + mDesc->mScrollPos)
			{
				mDesc->mScrollPos = MAX(mDesc->mSelectedItem - mDesc->mScrollTop - 1, 0);
			}

			if (mDesc->mSelectedItem < 0)
			{
				// Figure out how many lines of text fit on the menu
				int y = mDesc->mPosition;

				if (y <= 0)
				{
					if (BigFont && mDesc->mTitle.IsNotEmpty())
					{
						y = -y + BigFont->GetHeight();
					}
					else
					{
						y = -y;
					}
				}
				y *= CleanYfac_1;
				int	rowheight = OptionSettings.mLinespacing * CleanYfac_1;
				int maxitems = (screen->GetHeight() - rowheight - y) / rowheight + 1;

				mDesc->mScrollPos = MAX (0, (int)mDesc->mItems.Size() - maxitems + mDesc->mScrollTop);
				mDesc->mSelectedItem = mDesc->mItems.Size()-1;
			}
		}
		while (!mDesc->mItems[mDesc->mSelectedItem]->Selectable() && mDesc->mSelectedItem != startedAt);
		break;

	case MKEY_Down:
		if (mDesc->mSelectedItem == -1)
		{
			mDesc->mSelectedItem = FirstSelectable();
			break;
		}
		do
		{
			++mDesc->mSelectedItem;

			if (CanScrollDown && mDesc->mSelectedItem == VisBottom)
			{
				mDesc->mScrollPos++;
				VisBottom++;
			}
			if (mDesc->mSelectedItem >= (int)mDesc->mItems.Size())
			{
				if (startedAt == -1)
				{
					mDesc->mSelectedItem = -1;
					mDesc->mScrollPos = -1;
					break;
				}
				else
				{
					mDesc->mSelectedItem = 0;
					mDesc->mScrollPos = 0;
				}
			}
		}
		while (!mDesc->mItems[mDesc->mSelectedItem]->Selectable() && mDesc->mSelectedItem != startedAt);
		break;

	case MKEY_PageUp:
		if (mDesc->mScrollPos > 0)
		{
			mDesc->mScrollPos -= VisBottom - mDesc->mScrollPos - mDesc->mScrollTop;
			if (mDesc->mScrollPos < 0)
			{
				mDesc->mScrollPos = 0;
			}
			if (mDesc->mSelectedItem != -1)
			{
				mDesc->mSelectedItem = mDesc->mScrollTop + mDesc->mScrollPos + 1;
				while (!mDesc->mItems[mDesc->mSelectedItem]->Selectable())
				{
					if (++mDesc->mSelectedItem >= (int)mDesc->mItems.Size())
					{
						mDesc->mSelectedItem = 0;
					}
				}
				if (mDesc->mScrollPos > mDesc->mSelectedItem)
				{
					mDesc->mScrollPos = mDesc->mSelectedItem;
				}
			}
		}
		break;

	case MKEY_PageDown:
		if (CanScrollDown)
		{
			int pagesize = VisBottom - mDesc->mScrollPos - mDesc->mScrollTop;
			mDesc->mScrollPos += pagesize;
			if (mDesc->mScrollPos + mDesc->mScrollTop + pagesize > (int)mDesc->mItems.Size())
			{
				mDesc->mScrollPos = mDesc->mItems.Size() - mDesc->mScrollTop - pagesize;
			}
			if (mDesc->mSelectedItem != -1)
			{
				mDesc->mSelectedItem = mDesc->mScrollTop + mDesc->mScrollPos;
				while (!mDesc->mItems[mDesc->mSelectedItem]->Selectable())
				{
					if (++mDesc->mSelectedItem >= (int)mDesc->mItems.Size())
					{
						mDesc->mSelectedItem = 0;
					}
				}
				if (mDesc->mScrollPos > mDesc->mSelectedItem)
				{
					mDesc->mScrollPos = mDesc->mSelectedItem;
				}
			}
		}
		break;

	case MKEY_Enter:
		if (mDesc->mSelectedItem >= 0 && mDesc->mItems[mDesc->mSelectedItem]->Activate())
		{
			return true;
		}
		// fall through to default
	default:
		if (mDesc->mSelectedItem >= 0 &&
			mDesc->mItems[mDesc->mSelectedItem]->MenuEvent(mkey, fromcontroller)) return true;
		return Super::MenuEvent(mkey, fromcontroller);
	}

	if (mDesc->mSelectedItem != startedAt)
	{
		S_Sound (CHAN_VOICE | CHAN_UI, "menu/cursor", snd_menuvolume, ATTN_NONE);
	}
	return true;
}

//=============================================================================
//
//
//
//=============================================================================

bool DOptionMenu::MouseEvent(int type, int x, int y)
{
	y = (y / CleanYfac_1) - mDesc->mDrawTop;

	if (mFocusControl)
	{
		mFocusControl->MouseEvent(type, x, y);
		return true;
	}
	else
	{
		int yline = (y / OptionSettings.mLinespacing);
		if (yline >= mDesc->mScrollTop)
		{
			yline += mDesc->mScrollPos;
		}
		if ((unsigned)yline < mDesc->mItems.Size() && mDesc->mItems[yline]->Selectable())
		{
			if (yline != mDesc->mSelectedItem)
			{
				mDesc->mSelectedItem = yline;
				//S_Sound (CHAN_VOICE | CHAN_UI, "menu/cursor", snd_menuvolume, ATTN_NONE);
			}
			mDesc->mItems[yline]->MouseEvent(type, x, y);
			return true;
		}
	}
	mDesc->mSelectedItem = -1;
	return Super::MouseEvent(type, x, y);
}

//=============================================================================
//
//
//
//=============================================================================

void DOptionMenu::Ticker ()
{
	Super::Ticker();
	for(unsigned i=0;i<mDesc->mItems.Size(); i++)
	{
		mDesc->mItems[i]->Ticker();
	}
}

//=============================================================================
//
//
//
//=============================================================================

void DOptionMenu::Drawer ()
{
	int y = mDesc->mPosition;

	if (y <= 0)
	{
		if (BigFont && mDesc->mTitle.IsNotEmpty())
		{
			const char *tt = mDesc->mTitle;
			if (*tt == '$') tt = GStrings(tt+1);
			screen->DrawText (BigFont, OptionSettings.mTitleColor,
				(screen->GetWidth() - BigFont->StringWidth(tt) * CleanXfac_1) / 2, 10*CleanYfac_1,
				tt, DTA_CleanNoMove_1, true, TAG_DONE);
			y = -y + BigFont->GetHeight();
		}
		else
		{
			y = -y;
		}
	}
	mDesc->mDrawTop = y;
	int fontheight = OptionSettings.mLinespacing * CleanYfac_1;
	y *= CleanYfac_1;

	int indent = mDesc->mIndent;
	if (indent > 280)
	{ // kludge for the compatibility options with their extremely long labels
		if (indent + 40 <= CleanWidth_1)
		{
			indent = (screen->GetWidth() - ((indent + 40) * CleanXfac_1)) / 2 + indent * CleanXfac_1;
		}
		else
		{
			indent = screen->GetWidth() - 40 * CleanXfac_1;
		}
	}
	else
	{
		indent = (indent - 160) * CleanXfac_1 + screen->GetWidth() / 2;
	}

	int ytop = y + mDesc->mScrollTop * 8 * CleanYfac_1;
	int lastrow = screen->GetHeight() - SmallFont->GetHeight() * CleanYfac_1;

	unsigned i;
	for (i = 0; i < mDesc->mItems.Size() && y <= lastrow; i++, y += fontheight)
	{
		// Don't scroll the uppermost items
		if ((int)i == mDesc->mScrollTop)
		{
			i += mDesc->mScrollPos;
			if (i >= mDesc->mItems.Size()) break;	// skipped beyond end of menu
		}
		bool isSelected = mDesc->mSelectedItem == (int)i;
		int cur_indent = mDesc->mItems[i]->Draw(mDesc, y, indent, isSelected);
		if (cur_indent >= 0 && isSelected && mDesc->mItems[i]->Selectable())
		{
			if (((DMenu::MenuTime%8) < 6) || DMenu::CurrentMenu != this)
			{
				M_DrawConText(OptionSettings.mFontColorSelection, cur_indent + 3 * CleanXfac_1, y+fontheight-9*CleanYfac_1, "\xd");
			}
		}
	}

	CanScrollUp = (mDesc->mScrollPos > 0);
	CanScrollDown = (i < mDesc->mItems.Size());
	VisBottom = i - 1;

	if (CanScrollUp)
	{
		M_DrawConText(CR_ORANGE, 3 * CleanXfac_1, ytop, "\x1a");
	}
	if (CanScrollDown)
	{
		M_DrawConText(CR_ORANGE, 3 * CleanXfac_1, y - 8*CleanYfac_1, "\x1b");
	}
	Super::Drawer();
}

//=============================================================================
//
// base class for menu items
//
//=============================================================================

FOptionMenuItem::~FOptionMenuItem()
{
	if (mLabel != NULL) delete [] mLabel;
}

int FOptionMenuItem::Draw(FOptionMenuDescriptor *desc, int y, int indent, bool selected)
{
	return indent;
}

bool FOptionMenuItem::Selectable()
{
	return true;
}

bool FOptionMenuItem::MouseEvent(int type, int x, int y)
{
	if (Selectable() && type == DMenu::MOUSE_Release)
	{
		return DMenu::CurrentMenu->MenuEvent(MKEY_Enter, true);
	}
	return false;
}

int  FOptionMenuItem::GetIndent()
{
	if (mCentered)
	{
		return 0;
	}
	const char *label = mLabel;
	if (*label == '$') label = GStrings(label+1);
	return SmallFont->StringWidth(label);
}

void FOptionMenuItem::drawLabel(int indent, int y, EColorRange color, bool grayed)
{
	const char *label = mLabel;
	if (*label == '$') label = GStrings(label+1);

	int overlay = grayed? MAKEARGB(96,48,0,0) : 0;

	int x;
	int w = SmallFont->StringWidth(label) * CleanXfac_1;
	if (!mCentered) x = indent - w;
	else x = (screen->GetWidth() - w) / 2;
	screen->DrawText (SmallFont, color, x, y, label, DTA_CleanNoMove_1, true, DTA_ColorOverlay, overlay, TAG_DONE);
}

void FOptionMenuDescriptor::CalcIndent()
{
	// calculate the menu indent
	int widest = 0, thiswidth;

	for (unsigned i = 0; i < mItems.Size(); i++)
	{
		thiswidth = mItems[i]->GetIndent();
		if (thiswidth > widest) widest = thiswidth;
	}
	mIndent =  widest + 4;
}

//=============================================================================
//
//
//
//=============================================================================

FOptionMenuItem *FOptionMenuDescriptor::GetItem(FName name)
{
	for(unsigned i=0;i<mItems.Size(); i++)
	{
		FName nm = mItems[i]->GetAction(NULL);
		if (nm == name) return mItems[i];
	}
	return NULL;
}

class DGameplayMenu : public DOptionMenu
{
	DECLARE_CLASS(DGameplayMenu, DOptionMenu)

public:
	DGameplayMenu()
	{}

	void Drawer ()
	{
		Super::Drawer();

		char text[64];
		mysnprintf(text, 64, "dmflags = %d   dmflags2 = %d", *dmflags, *dmflags2);
		screen->DrawText (SmallFont, OptionSettings.mFontColorValue,
			(screen->GetWidth() - SmallFont->StringWidth (text) * CleanXfac_1) / 2, 0, text,
			DTA_CleanNoMove_1, true, TAG_DONE);
	}
};

IMPLEMENT_CLASS(DGameplayMenu)

class DCompatibilityMenu : public DOptionMenu
{
	DECLARE_CLASS(DCompatibilityMenu, DOptionMenu)

public:
	DCompatibilityMenu()
	{}

	void Drawer ()
	{
		Super::Drawer();

		char text[64];
		mysnprintf(text, 64, "compatflags = %d  compatflags2 = %d", *compatflags, *compatflags2);
		screen->DrawText (SmallFont, OptionSettings.mFontColorValue,
			(screen->GetWidth() - SmallFont->StringWidth (text) * CleanXfac_1) / 2, 0, text,
			DTA_CleanNoMove_1, true, TAG_DONE);
	}
};

IMPLEMENT_CLASS(DCompatibilityMenu)


text:
module Pageflow
  class EntryDuplicate < Struct.new(:original_entry)
    def create!
      create_entry

      copy_draft
      copy_memberships

      new_entry
    end

    def self.of(entry)
      new(entry)
    end

    private

    attr_reader :new_entry

    def create_entry
      @new_entry = Entry.create!(new_attributes)
    end

    def copy_draft
      original_entry.draft.copy do |revision|
        revision.entry = new_entry
      end
    end

    def copy_memberships
      original_entry.memberships.each do |membership|
        Membership.create(user: membership.user, role: membership.role.to_sym, entity: new_entry)
      end
    end

    def new_attributes
      {
        title: new_title,
        account: original_entry.account,
        theming: original_entry.theming,
        features_configuration: original_entry.features_configuration,

        skip_draft_creation: true
      }
    end

    def new_title
      I18n.t('pageflow.entry.duplicated_title', title: original_entry.title)
    end
  end
end


text:
package org.apache.hadoop.io.erasurecode.rawcoder;

import org.apache.hadoop.classification.InterfaceAudience;

import java.io.IOException;

/**
 * Thrown for invalid decoding.
 */
@InterfaceAudience.Private
public class InvalidDecodingException
    extends IOException {
  private static final long serialVersionUID = 0L;

  public InvalidDecodingException(String description) {
    super(description);
  }
}


text:
using System.ComponentModel;
using System.Configuration.Install;

namespace Middleman.Service
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }
    }
}


text:
import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';

// components
import RecentActivityTeaser from '../RecentActivityTeaser';

import './RecentActivityList.css';

const RecentActivityList = ({ comments, loadMore }) => (

		{comments.map((comment, i) => (
			<RecentActivityTeaser
				key={i}
				comment={comment}
			/>
		))}

			<RaisedButton
				onClick={loadMore}
				label="Load More"
				primary
			/>

);

export default RecentActivityList;


text:
using System;
using System.Collections.Generic;
using Xunit;
using Xunit.Abstractions;

namespace System.Xml.Tests
{
    public sealed class CThreads
    {
        //Data
        private IList<CThread> _rgThreads = new List<CThread>();

        //Static
        public static int MaxThreads = 20;

        private ITestOutputHelper _output;
        public CThreads(ITestOutputHelper output)
        {
            _output = output;
        }

        //Accessors
        private IList<CThread> Internal
        {
            get { return _rgThreads; }
        }

        public CThread this[int index]
        {
            get { return _rgThreads[index]; }
        }

        public CThread Add(CThread rThread)
        {
            _rgThreads.Add(rThread);
            return rThread;
        }

        public void Add(ThreadFunc func, object oParam)
        {
            Add(1, func, oParam);
        }

        public void Add(int cThreads, ThreadFunc func, object oParam)
        {
            //Default to one iteration
            Add(cThreads, 1, func, oParam);
        }

        public void Add(int cThreads, int iterations, ThreadFunc func, object oParam)
        {
            for (int i = 0; i < cThreads; i++)
                Add(new CThread(iterations, func, oParam, _output));
        }

        public void Start()
        {
            for (int i = 0; i < _rgThreads.Count; i++)
                this[i].Start();
        }

        public void Abort()
        {
            for (int i = 0; i < _rgThreads.Count; i++)
                this[i].Abort();
        }

        public void Wait()
        {
            Exception eReturn = null;

            //Wait for all the threads to complete...
            for (int i = 0; i < _rgThreads.Count; i++)
            {
                //Even if a thread ends up throwing, we still having to wait for all the
                //other threads to complete first.  Then throw the first exception received.
                try
                {
                    this[i].Wait();
                }
                catch (Exception e)
                {
                    //Only need to save off the first exception
                    if (eReturn == null)
                        eReturn = e;
                }
            }

            //If any of the threads failed, throw an exception...
            if (eReturn != null)
                throw eReturn;
        }

        public void StartSingleThreaded()
        {
            //This is mainly a debugging tool to ensure your threading scenario works
            //if it was run actually sequentially.  (ie: non-multlthreaded).
            for (int i = 0; i < _rgThreads.Count; i++)
            {
                this[i].Start();
                this[i].Wait();
            }
        }

        public int ReturnCodes(int iReturnCode)
        {
            int cMatches = 0;
            for (int i = 0; i < _rgThreads.Count; i++)
            {
                if (this[i].ReturnCode == iReturnCode)
                    cMatches++;
            }

            return cMatches;
        }

        public void Verify(int cThreads, int iReturnCode)
        {
            //Make sure the number of threads expected had the correct return code...
            Assert.Equal(ReturnCodes(iReturnCode), cThreads);
        }
    }
}


text:
package com.github.teamcalendar.middleware.services;

import java.util.List;

import com.github.teamcalendar.middleware.dto.Country;
import com.github.teamcalendar.middleware.services.impl.CountryServiceImpl;

/**
 * @author Artem Ivanov
 * @see {@link CountryServiceImpl}
 */
public interface CountryService
{

    boolean addCountry(Country country);

    List<Country> getAllCountries();

    Country getCountryById(Integer id);

    Country getCountryByName(String name);

}


text:
#region License

#endregion License

using System;

namespace LinkupSharp.Security.Authentication
{
    public class AuthenticatedAttribute : Attribute
    {
    }
}


text:
package org.eclipse.bpel.model;

/**
 *
 * A representation of the model object 'Retry Delay'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link org.eclipse.bpel.model.RetryDelay#getValue Value}

 *

 *

 *
 * @see org.eclipse.bpel.model.BPELPackage#getRetryDelay()
 * @model
 * @generated
 */
public interface RetryDelay extends BPELExtensibleElement {
	/**
	 * Returns the value of the 'Value' attribute.
	 *
	 *

	 * If the meaning of the 'Value' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Value' attribute.
	 * @see #setValue(int)
	 * @see org.eclipse.bpel.model.BPELPackage#getRetryDelay_Value()
	 * @model
	 * @generated
	 */
	int getValue();

	/**
	 * Sets the value of the '{@link org.eclipse.bpel.model.RetryDelay#getValue Value}' attribute.
	 *
	 *
	 * @param value the new value of the 'Value' attribute.
	 * @see #getValue()
	 * @generated
	 */
	void setValue(int value);

} // RetryDelay


text:
import { VERIFICATION_STATUS } from 'pmcrypto-v7/lib/constants';

import { captureMessage } from '@proton/shared/lib/helpers/sentry';

import { serverTime } from '../serverTime';
import type { ApiInterface as CryptoApiInterface } from '../worker/api';
import { WorkerVerifyOptions } from '../worker/api.models';

export { CryptoApiInterface, VERIFICATION_STATUS };

const assertNotNull = (value: CryptoApiInterface | null): CryptoApiInterface => {
    if (value === null) {
        throw new Error('CryptoProxy: endpoint not initialized');
    }
    return value;
};

let endpoint: CryptoApiInterface | null = null;
let onEndpointRelease: (endpoint?: any) => Promise<void> = async () => {};

interface CryptoProxyInterface extends CryptoApiInterface {
    /**
     * Set proxy endpoint.
     * The provided instance must be already initialised and ready to resolve requests.
     * @param endpoint
     * @param onRelease - callback called after `this.releaseEndpoint()` is invoked and endpoint is released
     */
    setEndpoint<T extends CryptoApiInterface>(endpoint: T, onRelease?: (endpoint: T) => Promise<void>): void;
    /**
     * Release endpoint. Afterwards, a different one may be set via `setEndpoint()`.
     * If a `onRelease` callback was passed to `setEndpoint()`, the callback is called before returning.
     * Note that this function does not have any other side effects, e.g. it does not clear the key store automatically.
     * Any endpoint-specific clean up logic should be done inside the `onRelease` callback.
     */
    releaseEndpoint(): Promise<void>;
}

/**
 * Prior to OpenPGP.js v5.4.0, trailing spaces were not properly stripped with \r\n line endings (see https://github.com/openpgpjs/openpgpjs/pull/1548).
 * In order to verify the signatures generated over the incorrectly normalised data, we fallback to not normalising the input.
 * Currently, this is done inside the CryptoProxy, to transparently track the number of signatures that are affected throughout the apps.
 * @param options - verification options, with `date` already set to server time
 */
async function verifyMessageWithFallback<
    DataType extends string | Uint8Array,
    FormatType extends WorkerVerifyOptions<DataType>['format'] = 'utf8'
>(options: WorkerVerifyOptions<DataType> & { format?: FormatType }) {
    const verificationResult = await assertNotNull(endpoint).verifyMessage<DataType, FormatType>(options);

    const { textData, stripTrailingSpaces } = options;
    if (
        verificationResult.verified === VERIFICATION_STATUS.SIGNED_AND_INVALID &&
        stripTrailingSpaces &&
        textData &&
        verificationResult.data !== textData // detect whether some normalisation was applied
    ) {
        const fallbackverificationResult = await assertNotNull(endpoint).verifyMessage<string, FormatType>({
            ...options,
            binaryData: undefined,
            stripTrailingSpaces: false,
        });

        if (fallbackverificationResult.verified === VERIFICATION_STATUS.SIGNED_AND_VALID) {
            captureMessage('Fallback verification needed', {
                level: 'info',
            });
            return fallbackverificationResult;
        }

        // detect whether the message has trailing spaces followed by a mix of \r\n and \n line endings
        const legacyRemoveTrailingSpaces = (text: string) => {
            return text
                .split('\n')
                .map((line) => {
                    let i = line.length - 1;
                    for (; i >= 0 && (line[i] === ' ' || line[i] === '\t'); i--) {}
                    return line.substr(0, i + 1);
                })
                .join('\n');
        };

        if (textData !== legacyRemoveTrailingSpaces(textData)) {
            captureMessage('Fallback verification insufficient', {
                level: 'info',
            });
        }
    }

    return verificationResult;
}

/**
 * CryptoProxy relays crypto requests to the specified endpoint, which is typically a worker(s), except if
 * CryptoProxy is already called (also indirectly) from inside a worker.
 * In such a case, the endpoint can be set to a `new WorkerApi()` instance, or to tbe worker instance itself,
 * provided it implements/extends WorkerApi.
 */
export const CryptoProxy: CryptoProxyInterface = {
    setEndpoint(endpointInstance, onRelease = onEndpointRelease) {
        if (endpoint) {
            throw new Error('already initialised');
        }
        endpoint = endpointInstance;
        onEndpointRelease = onRelease;
    },

    releaseEndpoint() {
        const tmp = endpoint;
        endpoint = null;
        return onEndpointRelease(assertNotNull(tmp));
    },

    encryptMessage: async ({ date = serverTime(), ...opts }) =>
        assertNotNull(endpoint).encryptMessage({ ...opts, date }),
    decryptMessage: async ({ date = serverTime(), ...opts }) =>
        assertNotNull(endpoint).decryptMessage({ ...opts, date }),
    decryptMessageLegacy: async ({ date = serverTime(), ...opts }) =>
        assertNotNull(endpoint).decryptMessageLegacy({ ...opts, date }),
    signMessage: async ({ date = serverTime(), ...opts }) => assertNotNull(endpoint).signMessage({ ...opts, date }),
    verifyMessage: async ({ date = serverTime(), ...opts }) => verifyMessageWithFallback({ ...opts, date }),
    verifyCleartextMessage: async ({ date = serverTime(), ...opts }) =>
        assertNotNull(endpoint).verifyCleartextMessage({ ...opts, date }),
    processMIME: async ({ date = serverTime(), ...opts }) => assertNotNull(endpoint).processMIME({ ...opts, date }),

    generateSessionKey: async ({ date = serverTime(), ...opts }) =>
        assertNotNull(endpoint).generateSessionKey({ ...opts, date }),
    generateSessionKeyForAlgorithm: async (opts) => assertNotNull(endpoint).generateSessionKeyForAlgorithm(opts),
    encryptSessionKey: async ({ date = serverTime(), ...opts }) =>
        assertNotNull(endpoint).encryptSessionKey({ ...opts, date }),
    decryptSessionKey: async ({ date = serverTime(), ...opts }) =>
        assertNotNull(endpoint).decryptSessionKey({ ...opts, date }),

    importPrivateKey: async (opts) => assertNotNull(endpoint).importPrivateKey(opts),
    importPublicKey: async (opts) => assertNotNull(endpoint).importPublicKey(opts),
    generateKey: async ({ date = serverTime(), ...opts }) => assertNotNull(endpoint).generateKey({ ...opts, date }),
    reformatKey: async ({ date = serverTime(), ...opts }) => assertNotNull(endpoint).reformatKey({ ...opts, date }),
    exportPublicKey: async (opts) => assertNotNull(endpoint).exportPublicKey(opts),
    exportPrivateKey: async (opts) => assertNotNull(endpoint).exportPrivateKey(opts),
    clearKeyStore: () => assertNotNull(endpoint).clearKeyStore(),
    clearKey: async (opts) => assertNotNull(endpoint).clearKey(opts),
    replaceUserIDs: async (opts) => assertNotNull(endpoint).replaceUserIDs(opts),

    isRevokedKey: async ({ date = serverTime(), ...opts }) => assertNotNull(endpoint).isRevokedKey({ ...opts, date }),
    isExpiredKey: async ({ date = serverTime(), ...opts }) => assertNotNull(endpoint).isExpiredKey({ ...opts, date }),
    canKeyEncrypt: async ({ date = serverTime(), ...opts }) => assertNotNull(endpoint).canKeyEncrypt({ ...opts, date }),
    getSHA256Fingerprints: async (opts) => assertNotNull(endpoint).getSHA256Fingerprints(opts),
    computeHash: async (opts) => assertNotNull(endpoint).computeHash(opts),

    getArmoredMessage: async (opts) => assertNotNull(endpoint).getArmoredMessage(opts),
    getArmoredKeys: async (opts) => assertNotNull(endpoint).getArmoredKeys(opts),
    getArmoredSignature: async (opts) => assertNotNull(endpoint).getArmoredSignature(opts),
    getSignatureInfo: async (opts) => assertNotNull(endpoint).getSignatureInfo(opts),
    getMessageInfo: async (opts) => assertNotNull(endpoint).getMessageInfo(opts),
    getKeyInfo: async (opts) => assertNotNull(endpoint).getKeyInfo(opts),
};


text:
/*******************************************************************************
* Author: Marco Zamora
* Class: CS 162
* Date: 3/10/15
* Edited: 3/14/15
* Final Project
*
* Purpose: provides declarations for the functions that run the main function
*******************************************************************************/
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
#include "objects.h"
#include <fstream>
#include <cstdlib> //exit
#include <limits> //numeric_limits
#include <time.h> //clock
#include <iomanip> //setprecision

using std::cin;
using std::ifstream;
using std::ios;
using std::streamsize;
using std::max;
using std::numeric_limits;
using std::setprecision;
using std::fixed;

//types of possible actions. Starts at 1
enum action { LEAVE = 1, GRAB, INTERACT };

//types of possible rooms. Starts at 1
enum direction { NORTH = 1, EAST, SOUTH, WEST };

const double MAX_TIME = 5;

//allows user to see answers to the game
void showGoal();

//saves rooms in vector
void loadRooms( vector<Room*>& map );

//gets room names from a file and reads them into the proper room
void nameRooms(vector<Room*>& map);

//links rooms together
void linkRooms( vector<Room*>& map );

//creates items and puts them in appropriate room
void loadItems(vector<Room*>& map );

//runs the game loop
void play( Player* player, vector<Room*> map );

//get input from user on next choice
int getAction();

//gets user input of next room and puts player in that room
Room* getDirection(Player* player, Room* room);

//follow through on player's choice
void performAction(int act, Player* player, Room* room, vector<Room*> map );

//free rooms and items in rooms
void deleteRooms(vector<Room*>& map);

//displays the objective of the game
void introduction();

//requires the user to press enter to continue
void pressEnter();

//sets elapsed time and reports time left
void timeLeft(time_t s, double& e);

#endif


text:
ifndef VIDEO_SRC_FOLDER
    $(error VIDEO_SRC_FOLDER is not defined; it should be a path to a video folder in a compatible format)
endif

video.gbc: video.o $(VIDEO_SRC_FOLDER)/video.gbv
	rgblink -o $@ -m video.map -n video.sym $<
	cat $(VIDEO_SRC_FOLDER)/video.gbv >> $@
	rgbfix -Cv -i GBVP -t "GBVideo" -m 25 $@
CLEAN += video.gbc video.sym video.map

video.o: video.asm music.gbm gbhw.asm
	rgbasm -o $@ $<
CLEAN += video.o

music.gbm: music.itt
	@# 3571 is the hardcoded length for the Pokémon Theme
	python itt.py $< 3571 > $@
CLEAN += music.gbm

$(VIDEO_SRC_FOLDER)/video.gbv: $(VIDEO_SRC_FOLDER)
	python convert.py $(VIDEO_SRC_FOLDER) `ls -1 $(VIDEO_SRC_FOLDER)/*.png | wc -l`

clean:
	rm $(CLEAN)


text:
package io.github.moosbusch.museum.document.museumdat;

import de.zib.museum.museumdat.MuseumdatDocument.Museumdat;
import de.zib.museum.museumdat.MuseumdatWrapDocument;
import de.zib.museum.museumdat.MuseumdatWrapDocument.MuseumdatWrap;
import io.github.moosbusch.museum.document.MuseumXmlDocument;
import io.github.moosbusch.museum.document.MuseumXmlDocument;
import io.github.moosbusch.museum.document.museumdat.impl.DefaultMuseumDatObjectFactory;

/**
 *
 * @author moosbusch
 */
public interface MuseumDatXmlDocument<T extends DefaultMuseumDatObjectFactory>
    extends MuseumXmlDocument<MuseumdatWrapDocument, T, MuseumdatWrap, Museumdat> {

    public static final String MUSEUMDAT_NS_URI = "http://museum.zib.de/museumdat";
    public static final String MUSEUMDAT_NS_PREFIX = "museumdat";
    public static final String MUSEUMDAT_SCHEMA_LOCATION =
            "http://museum.zib.de/museumdat http://museum.zib.de/museumdat/museumdat-v1.0.xsd";
    public static final String DEFAULT_LANGUAGE_ENCODING = "RFC3066";
    public static final String DEFAULT_ENCODING_ANALOG = "DC";
}


text:
package com.yahoo.platform.yui.compressor.org.mozilla.javascript.jdk15;

import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
import java.util.Iterator;
import com.yahoo.platform.yui.compressor.org.mozilla.javascript.*;

public class VMBridge_jdk15 extends com.yahoo.platform.yui.compressor.org.mozilla.javascript.jdk13.VMBridge_jdk13
{
    public VMBridge_jdk15() throws SecurityException, InstantiationException {
        try {
            // Just try and see if we can access the isVarArgs method.
            // We want to fail loading if the method does not exist
            // so that we can load a bridge to an older JDK instead.
            Method.class.getMethod("isVarArgs", (Class[]) null);
        } catch (NoSuchMethodException e) {
            // Throw a fitting exception that is handled by
            // org.mozilla.javascript.Kit.newInstanceOrNull:
            throw new InstantiationException(e.getMessage());
        }
    }

    @Override
    public boolean isVarArgs(Member member) {
        if (member instanceof Method)
            return ((Method) member).isVarArgs();
        else if (member instanceof Constructor)
            return ((Constructor<?>) member).isVarArgs();
        else
            return false;
    }

    /**
     * If "obj" is a java.util.Iterator or a java.lang.Iterable, return a
     * wrapping as a JavaScript Iterator. Otherwise, return null.
     * This method is in VMBridge since Iterable is a JDK 1.5 addition.
     */
    @Override
    public Iterator<?> getJavaIterator(Context cx, Scriptable scope, Object obj) {
        if (obj instanceof Wrapper) {
            Object unwrapped = ((Wrapper) obj).unwrap();
            Iterator<?> iterator = null;
            if (unwrapped instanceof Iterator)
                iterator = (Iterator<?>) unwrapped;
            if (unwrapped instanceof Iterable)
                iterator = ((Iterable<?>)unwrapped).iterator();
            return iterator;
        }
        return null;
    }
}