text:
import {Box, Grid, Paper, useMediaQuery, useTheme} from "@material-ui/core";
import {PageTitle} from "../../common/theme/typography/Tags";
import {FormProvider, useForm} from "react-hook-form";
import React, {useEffect} from "react";
import {useTranslation} from "react-i18next";
import {MessageJobsOverview} from "./messagejobs/MessageJobsOverview";
import MessageHeadline from "./MessageHeadline";
import {PrimaryButton} from "../../common/theme/PrimaryButton";
import MessageSubject from "./MessageSubject";
import MessageContent from "./MessageContent";
import {RecipientSelection} from "./RecipientSelection";
import {MessagePreview} from "./MessagePreview";
import {
  BaseAdminIdProps,
  BaseMessage,
  DINNERROUTE_MESSAGE_VALIDATION_SCHEMA,
  fetchInitialMessageData, findEntityById,
  getExampleDinnerRouteMessage,
  getExampleParticipantMessage,
  getExampleTeamMessage,
  getRecipientsSelector,
  isArrayNotEmpty,
  MessageType,
  PARTICIPANT_MESSAGE_VALIDATION_SCHEMA,
  sendMessages,
  setCustomSelectedRecipients,
  TEAM_MESSAGE_VALIDATION_SCHEMA,
  updateDinnerRouteHostsPartTemplatePreviewAsync,
  updateDinnerRouteSelfPartTemplatePreviewAsync,
  updateHostMessagePartTemplatePreviewAsync,
  updateMessageContentPreviewAsync,
  updateMessageSubjectPreviewAsync,
  updateNonHostMessagePartTemplatePreviewAsync,
  useAdminDispatch,
  useAdminSelector,
  useBackendIssueHandler,
  CONSTANTS,
  setupInitialMessageType
} from "@runningdinner/shared";
import {useNotificationHttpError} from "../../common/NotificationHttpErrorHook";
import {BrowserTitle} from "../../common/mainnavigation/BrowserTitle";
import {useMessagesQueryHandler} from "./MessagesQueryHandlerHook";
import {FetchStatus} from "@runningdinner/shared/src/redux";
import { useCustomSnackbar } from "../../common/theme/CustomSnackbarHook";

export function TeamMessages({adminId}: BaseAdminIdProps) {
  const templates = ['{firstname}', '{lastname}', '{meal}', '{mealtime}', '{host}', '{partner}', '{managehostlink}'];

  const dispatch = useAdminDispatch();
  useEffect(() => {
    dispatch(fetchInitialMessageData(adminId, MessageType.MESSAGE_TYPE_TEAMS))
  }, [dispatch, adminId]);

  return (
    <>
      <MessagesView adminId={adminId}
                    exampleMessage={getExampleTeamMessage()}
                    validationSchema={TEAM_MESSAGE_VALIDATION_SCHEMA}
                    templates={templates}
                    messageType={MessageType.MESSAGE_TYPE_TEAMS}/>
      <BrowserTitle titleI18nKey={"admin:mails_send_teams_title"} namespaces={"admin"} />
    </>
  );
}

export function DinnerRouteMessages({adminId}: BaseAdminIdProps) {

  const templates = ['{firstname}', '{lastname}', '{route}', '{routelink}'];

  const dispatch = useAdminDispatch();
  useEffect(() => {
    dispatch(fetchInitialMessageData(adminId, MessageType.MESSAGE_TYPE_DINNERROUTE))
  }, [dispatch, adminId]);

  return (
    <>
      <MessagesView adminId={adminId}
                    exampleMessage={getExampleDinnerRouteMessage()}
                    validationSchema={DINNERROUTE_MESSAGE_VALIDATION_SCHEMA}
                    templates={templates}
                    messageType={MessageType.MESSAGE_TYPE_DINNERROUTE}/>
      <BrowserTitle titleI18nKey={"admin:mails_send_dinnerroutes_title"} namespaces={"admin"} />
    </>
  );
}

export function ParticipantMessages({adminId}: BaseAdminIdProps) {
  const templates = ['{firstname}', '{lastname}'];

  const dispatch = useAdminDispatch();
  useEffect(() => {
    dispatch(fetchInitialMessageData(adminId, MessageType.MESSAGE_TYPE_PARTICIPANTS))
  }, [dispatch, adminId]);

  return (
    <>
      <MessagesView adminId={adminId}
                    exampleMessage={getExampleParticipantMessage()}
                    validationSchema={PARTICIPANT_MESSAGE_VALIDATION_SCHEMA}
                    templates={templates}
                    messageType={MessageType.MESSAGE_TYPE_PARTICIPANTS} />
      <BrowserTitle titleI18nKey={"admin:mails_send_participants_title"} namespaces={"admin"} />
    </>
  );
}

interface MessagesViewProps<T extends BaseMessage> extends BaseAdminIdProps {
  exampleMessage: T;
  validationSchema?: any;
  templates: string[];
  messageType: MessageType
}

function MessagesView<T extends BaseMessage>({adminId, exampleMessage, templates, messageType}: MessagesViewProps<T>) {

  const {t} = useTranslation(['admin', 'common']);
  const {showSuccess} = useCustomSnackbar();

  const theme = useTheme();
  const isMdDeviceOrUp = useMediaQuery(theme.breakpoints.up('md'));

  const {applyValidationIssuesToForm, getIssuesTranslated} = useBackendIssueHandler({
    defaultTranslationResolutionSettings: {
      namespaces: 'admin'
    }
  });
  const {showHttpErrorDefaultNotification} = useNotificationHttpError(getIssuesTranslated);

  const dispatch = useAdminDispatch();
  const {recipients} = useAdminSelector(getRecipientsSelector);

  const {headline, selectedTeamIds, preselectAllRecipients} = useMessagesQueryHandler(messageType);

  const formMethods = useForm({
    // @ts-ignore
    defaultValues: exampleMessage,
    // resolver: yupResolver(validationSchema), // Currently I use only backend validation...
    mode: 'onBlur'
  });
  const { handleSubmit, clearErrors, setError, formState, setValue } = formMethods;
  const { isSubmitting } = formState;

  useEffect(() => {
    // Reset all our selection values on mounting this component:
     // @ts-ignore We get the correct field name...:
    setValue(getRecipientFormFieldName(messageType), "");
    dispatch(setupInitialMessageType({adminId, messageType}));
    dispatch(setCustomSelectedRecipients([]));
  }, [dispatch, messageType, adminId, setValue]);

  useEffect(() => {
    if (messageType !== MessageType.MESSAGE_TYPE_PARTICIPANTS && isArrayNotEmpty(selectedTeamIds) && recipients.fetchStatus === FetchStatus.SUCCEEDED) {
      const preSelectedTeams = selectedTeamIds
                                .map(id => findEntityById(recipients.data, id))
                                .filter(elem => elem);
      // @ts-ignore When running in this case, we have always teamSelection
      setValue("teamSelection", CONSTANTS.RECIPIENT_SELECTION_COMMON.CUSTOM_SELECTION);
      dispatch(setCustomSelectedRecipients(preSelectedTeams));
    }
    // else if (recipients.fetchStatus === FetchStatus.SUCCEEDED && isArrayEmpty(selectedTeamIds)) {
    //   dispatch(setCustomSelectedRecipients([]));
    // }
    else if (preselectAllRecipients && recipients.fetchStatus === FetchStatus.SUCCEEDED) {
      // @ts-ignore We get the correct field name...:
      setValue(getRecipientFormFieldName(messageType), CONSTANTS.RECIPIENT_SELECTION_COMMON.ALL);
    }
    // eslint-disable-next-line
  }, [JSON.stringify(selectedTeamIds), messageType, recipients.fetchStatus, preselectAllRecipients, setValue]);

  const handleSendMessages = async (values: T) => {
    clearErrors();
    try {
      const sendMessagesPromise = dispatch(sendMessages(values)).unwrap();
      window.scrollTo(0, 0);
      await sendMessagesPromise;
      showSuccess(t("admin:mails_sending_submitted"));
    } catch(e) {
      applyValidationIssuesToForm(e, setError);
      showHttpErrorDefaultNotification(e);
    }
  };

  function getRecipientFormFieldName(messageType: MessageType) {
    return messageType !== MessageType.MESSAGE_TYPE_PARTICIPANTS ? "teamSelection" : "participantSelection";
  }

  const handleMessageContentChange = (content: string) => updateMessageContentPreviewAsync(content);
  const handleMessageSubjectChange = (subject: string) => updateMessageSubjectPreviewAsync(subject);
  const handleNonHostMessagePartTemplateChange = (changedValue: string) => updateNonHostMessagePartTemplatePreviewAsync(changedValue);
  const handleHostMessagePartTemplateChange = (changedValue: string) => updateHostMessagePartTemplatePreviewAsync(changedValue);
  const handleDinnerRouteHostsPartTemplateChange = (changedValue: string) => updateDinnerRouteHostsPartTemplatePreviewAsync(changedValue);
  const handleDinnerRouteSelfPartTemplateChange = (changedValue: string) => updateDinnerRouteSelfPartTemplatePreviewAsync(changedValue);

  // @ts-ignore
  return (
      <>
        <Grid container>
          <Grid item xs={12}><PageTitle>{t(headline)}</PageTitle></Grid>
        </Grid>

        <FormProvider {...formMethods}>
          <form>

            <Grid container spacing={3}>

              <Grid item xs={12} lg={7}>
                <Paper elevation={3}>
                  <Box p={2}>
                    <Grid container>
                      <Grid item xs={12}><MessageHeadline /></Grid>
                      <Grid item xs={12}>
                        <RecipientSelection messageType={messageType} adminId={adminId} />
                        <MessageSubject onMessageSubjectChange={handleMessageSubjectChange}/>
                        <MessageContent templates={templates}
                                        onMessageContentChange={handleMessageContentChange}
                                        rows={15}
                                        showTemplatesHelpIcon={true}
                                        name="message"
                                        label={t('common:content')}/>
                      </Grid>
                      { messageType === MessageType.MESSAGE_TYPE_TEAMS &&
                        <Grid container spacing={1}>
                          <Grid item xs={12} md={6}>
                            <MessageContent templates={[]}
                                            onMessageContentChange={handleHostMessagePartTemplateChange}
                                            rows={5}
                                            showTemplatesHelpIcon={true}
                                            name="hostMessagePartTemplate"
                                            helperText={t('admin:mails_template_replacement_host')}
                                            label={t('admin:mails_sendteams_host')}/>
                          </Grid>
                          <Grid item xs={12} md={6}>
                            <MessageContent templates={[]}
                                            onMessageContentChange={handleNonHostMessagePartTemplateChange}
                                            rows={5}
                                            showTemplatesHelpIcon={true}
                                            name="nonHostMessagePartTemplate"
                                            helperText={t('admin:mails_template_replacement_nonhost')}
                                            label={t('admin:mails_sendteams_nonhost')}/>
                          </Grid>
                        </Grid> }

                        { messageType === MessageType.MESSAGE_TYPE_DINNERROUTE &&
                        <Grid container spacing={1}>
                          <Grid item xs={12} lg={6}>
                            <MessageContent templates={['{firstname}', '{lastname}', '{meal}', '{mealtime}', '{mealspecifics}']}
                                            onMessageContentChange={handleDinnerRouteSelfPartTemplateChange}
                                            rows={7}
                                            showTemplatesHelpIcon={isMdDeviceOrUp}
                                            name="selfTemplate"
                                            helperText={t('admin:mails_template_replacement_route_host')}
                                            label={t('admin:mails_senddinnerroute_self')}/>
                          </Grid>
                          <Grid item xs={12} lg={6}>
                            <MessageContent templates={['{firstname}', '{lastname}', '{meal}', '{mealtime}', '{hostaddress}', '{mobilenumber}']}
                                            onMessageContentChange={handleDinnerRouteHostsPartTemplateChange}
                                            rows={7}
                                            showTemplatesHelpIcon={isMdDeviceOrUp}
                                            name="hostsTemplate"
                                            helperText={t('admin:mails_template_replacement_route_guest')}
                                            label={t('admin:mails_senddinnerroute_hosts')}/>
                          </Grid>
                        </Grid> }

                      <Grid container justify="flex-end">
                        <Grid item>
                          <Box mt={3}>
                            {/* @ts-ignore */}
                            <PrimaryButton onClick={handleSubmit(handleSendMessages)}
                                           disabled={isSubmitting}
                                           size="large">
                              {t('messages_send_general')}
                            </PrimaryButton>
                          </Box>
                        </Grid>
                      </Grid>
                    </Grid>
                  </Box>
                </Paper>
              </Grid>

              <Grid item xs={12} lg={5}>
                <Grid item xs={12}>
                  <MessageJobsOverview adminId={adminId} messageType={messageType} />
                </Grid>
                <Grid item xs={12}>
                  <Box mt={3}>
                    <Paper elevation={3}>
                      <Box p={2}>
                        <MessagePreview adminId={adminId} messageType={messageType} />
                      </Box>
                    </Paper>
                  </Box>
                </Grid>
              </Grid>

            </Grid>

          </form>
        </FormProvider>
      </>
  );
}


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Client.Hubs;

namespace Microsoft.AspNet.SignalR.Client.Samples
{
    class Program
    {
        static void Main(string[] args)
        {
            var writer = Console.Out;
            var client = new CommonClient(writer);
            client.RunAsync("http://localhost:40476/").Wait();

            Console.ReadKey();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using namespace std;

// applying sieve of erastothenes
void sieve(bool primes[], int x) {
    primes[1] = false;

    // if a number is prime mark all its multiples
    // as non prime
    for (int i=2; i*i <= x; i++) {
        if (primes[i] == true) {
            for (int j=2; j*i <= x; j++)
                primes[i*j] = false;
        }
    }
}

// function that returns numbers of number that have
// n divisors in range from a to b. x is sqrt(b) + 1.
int nDivisors(bool primes[], int x, int a, int b, int n)
{
    // result holds number of numbers having n divisors
    int result = 0;

    // vector to hold all the prime numbers between 1
    // ans sqrt(b)
    vector <int> v;
    for (int i = 2; i <= x; i++)
        if (primes[i] == true)
            v.push_back (i);

    // Traversing all numbers in given range
    for (int i=a; i<=b; i++)
    {
        // initialising temp as i
        int temp = i;

        // total holds the number of divisors of i
        int total = 1;
        int j = 0;

        // we need to use that prime numbers that
        // are less than equal to sqrt(temp)
        for (int k = v[j]; k*k <= temp; k = v[++j])
        {
            // holds the exponent of k in prime
            // factorization of i
            int count = 0;

            // repeatedly divide temp by k till it is
            // divisble and accordingly increase count
            while (temp%k == 0)
            {
                count++;
                temp = temp/k;
            }

            // using the formula  no.of divisors =
            // (e1+1)*(e2+1)....
            total = total*(count+1);
        }

        // if temp is not equal to 1 then there is
        // prime number in prime factorization of i
        // greater than sqrt(i)
        if (temp != 1)
            total = total*2;

        // if i is a ndvisor number increase result
        if (total == n)
            result++;
    }
    return result;
}

// Returns count of numbers in [a..b] having
// n divisors.
int countNDivisors(int a, int b, int n)
{
    int x = sqrt(b) + 1;

    // primes[i] = true if i is a prime number
    bool primes[x];

    // initialising each number as prime
    memset(primes, true, sizeof(primes));
    sieve(primes, x);

    return nDivisors(primes, x, a, b, n);
}

// driver code
int main()
{
    int a = 1, b = 7, n = 2;
    cout << countNDivisors(a, b, n);
    return 0;
}


text:
Dependency Injection Command Engine

[![Build status](https://ci.appveyor.com/api/projects/status/osvbuuva76454cb8?branch=develop&retina=true)](https://ci.appveyor.com/project/olegsych/dice/branch/develop)


text:
BlobDialog::BlobDialog(QWidget *parent)
  : QDialog(parent) {
  setupUi(this);
}

void BlobDialog::setBlob(QVariant blob) {
  textViewer->setPlainText(blob.toString());
  htmlViewer->setHtml(blob.toString());
}


text:
/* eslint-disable func-names */
/**
 * A function that emits a side effect and does not return anything.
 */
export type Procedure = (...args: any[]) => void;

export type Options = {
  isImmediate: boolean,
};

export function debounce<F extends Procedure>(
  func: F,
  waitMilliseconds = 50,
  options: Options = {
    isImmediate: false,
  },
): (this: ThisParameterType<F>, ...args: Parameters<F>) => void {
  let timeoutId: ReturnType<typeof setTimeout> | undefined;

  return function (this: ThisParameterType<F>, ...args: Parameters<F>) {
    const context = this;

    const doLater = function () {
      timeoutId = undefined;
      if (!options.isImmediate) {
        func.apply(context, args);
      }
    };

    const shouldCallNow = options.isImmediate && timeoutId === undefined;

    if (timeoutId !== undefined) {
      clearTimeout(timeoutId);
    }

    timeoutId = setTimeout(doLater, waitMilliseconds);

    if (shouldCallNow) {
      func.apply(context, args);
    }
  };
}


text:
@echo off
SETLOCAL

@REM  ----------------------------------------------------------------------------
@REM  vstest-console.cmd
@REM
@REM  author: m4mc3r@gmail.com
@REM  ----------------------------------------------------------------------------

set start_time=%time%
set working_dir=%CD%\..\..
set msbuild_bin_path="%PROGRAMFILES(X86)%\MSBuild\14.0\Bin\MSBuild.exe"
set vstestconsole_bin_path="%PROGRAMFILES(X86)%\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe"
set vstestconsole_proj_path=\vstest-console.proj

if "%1"=="/?" goto help

@REM run vstestconsole
%msbuild_bin_path% "%working_dir%%vstestconsole_proj_path%" /p:WorkingDirectory="%working_dir%" /p:VSTestConsoleBinPath=%vstestconsole_bin_path%
@if %errorlevel% NEQ 0 goto error
goto success

:error
@exit /b errorLevel

:help
echo looks for test assemblies and runs vstestconsole
echo usage: vstest-console.cmd [/?]
echo "/?" shows this help test

:success
echo process successfully finished
echo start time: %start_time%
echo end time: %time%

ENDLOCAL
echo on


text:
```scheme
(define (make-accumulator initial-value)
  (lambda (n)
    (begin (set! initial-value (+ initial-value n))
	   initial-value)))
```

###Ex 3.2

```scheme
(define (make-monitored f)
  (let ((calls 0))
    (lambda (m)
      (cond ((and (symbol? m) (eq? m 'how-many-calls?)) calls)
	    ((and (symbol? m) (eq? m 'reset-count)) (set! calls 0))
	    (else (begin (set! calls (+ calls 1))
			 (f m)))))))
```

###Ex 3.3
```scheme
(define (make-account balance password)
  (define (withdraw amount)
    (if (>= balance amount)
	(begin (set! balance (- balance amount))
	       balance)
	"Insufficient funds"))
  (define (deposit amount)
    (set! balance (+ balance amount))
    balance)
  (define (dispatch pw m)
    (if (eq? pw password)
	(cond ((eq? m 'withdraw) withdraw)
	      ((eq? m 'deposit) deposit)
	      (else (error "Unknown request -- MAKE-ACCOUNT"
			   m)))
	(lambda (ignored) "Incorrect password")))
  dispatch)
```

The problem wasn't specific about wether we should use `error` to raise the complaint, so I just return a `lambda` that ignores the argument and returns the "Incorrect password" message in the case when the password is wrong.  That way, if we try to do `((acc 'the-wrong-password deposit) 10)`, we just get returned the string, instead of some message about not being able to apply the arguments to the given procedure if we just returned the string.

###Ex 3.4

```scheme
(define (make-account balance password)
  (let ((consecutive-incorrect-pws 0))
    (define (withdraw amount)
      (if (>= balance amount)
	  (begin (set! balance (- balance amount))
		 balance)
	  "Insufficient funds"))
    (define (deposit amount)
      (set! balance (+ balance amount))
      balance)

    (define (call-the-cops)
      (error "Seven consecutive failures to provide correct password.  Calling the cops!  WEE-OOO-WEE-OOO!"))

    (define (inc-incorrect-pws)
      (set! consecutive-incorrect-pws (+ 1 consecutive-incorrect-pws)))

    (define (reset-incorrect-pws)
      (set! consecutive-incorrect-pws 0))

    (define (dispatch pw m)
      (if (eq? pw password)
	  (begin
	    (reset-incorrect-pws)
	    (cond ((eq? m 'withdraw) withdraw)
		  ((eq? m 'deposit) deposit)
		  (else (error "Unknown request -- MAKE-ACCOUNT"
			       m))))
	  (begin
	    (inc-incorrect-pws)
	    (if (> consecutive-incorrect-pws 7)
		(call-the-cops)
		(lambda (ingored) "Incorrect password")))))

    dispatch))
```

Sidenote, it would probably be "secure" if it didn't allow furher access to the account after 7 failures.

###Ex 3.5
```scheme
(define (random-in-range low high)
  (let ((range (- high low)))
    (+ low (random range))))

(define (estimate-integral P x1 x2 y1 y2 trials)
  (define (experiment)
    (let ((x (random-in-range x1 x2))
	  (y (random-in-range y1 y2)))
      (P x y)))
  (let ((portion (monte-carlo trials experiment))
	(rect-area (* (- y2 y1) (- x2 x1))))
    (* 1.0 portion rect-area)))

(define (estimate-pi)
  (define (P x y)
    (<= (+ (square x) (square y)) 1))
  (estimate-integral P -1 1 -1 1 5000))
```

Here we just estimate the area of the circle centered around $$(0,0)$$.  We do indeed get results that are close to $$\pi$$.

###Ex 3.6

```scheme
(define (rand)
  (let ((x random-init))
    (lambda (m)
      (cond ((eq? m 'generate)
	     (set! x (rand-update x))
	     x)
	    ((eq? m 'reset)
	     (lambda (val) (set! x val)))
	    (else (error "Unkown message -- RAND"
			 m))))))
```

One of the changes is easy to miss, so I'll point it out: we define `rand` as a procedure that takes no arguments, and returns a `lambda`.  This is in contrast to the original definition in the book, which defines `rand` *as* a lambda.  The returned `lambda` checks the message that is passed in, and either returns the next value in the sequence (for `'generate`), or returns a 1-arg lambda for `'reset`, that resets the value of `x`.

###Ex 3.7

```scheme
(define (make-joint acc pass 2ndpass)
  (lambda (pw m)
    (if (eq? pw 2ndpass)
	(acc pass m)
	(lambda (ignored) "Incorrect password to joint account"))))
```

`make-account` is unchanged from 3.3.  Here we return a `lambda` that checks if the given password matches the second one given to `make-joint` (the new password), and if it does, passes the message to the `acc` with its password.

###Ex 3.8

```scheme
(define f-calls 0)

(define (f n)
  (if (<= f-calls 0)
      (begin (set! f-calls (+ f-calls 1))
	     n)
      0))
```

Here `f` makes use of globally-defined variable `f-calls` to track how many times it's been called previously.  If it's the first time, it returns `n`, otherwise, it returns `0`.  We can check that it meets the condition in the question with the following:

```scheme
(define (reset) (set! f-calls 0))

(let ((n1 (f 0))
      (n2 (f 1)))
  (+ n1 n2))
=> 0

(reset)

(let ((n1 (f 1))
      (n2 (f 0)))
	  (+ n1 n2))
=> 1
```

On a sidenote, my particular implementation (DrRacket using `#lang scheme`) seems to evalute them from left to right as the expression `(+ (f 0) (f 1))` returns `0`.


text:
int main(int argc, const char* argv[]);

// Exported to the tester app.
__declspec(dllexport) int deqp_libtester_main(int argc, const char *argv[])
{
    return main(argc, argv);
}


text:
from util.tipo import tipo
class S_USER_LOCATION_IN_ACTION(object):

    def __init__(self, tracker, time, direction, opcode, data):
        print(str(type(self)).split('.')[3]+'('+str(len(data))+'): '+ str(data.get_array_hex(1))[1:-1])


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>output_format</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../index.html" title="Boost.Test">
<link rel="up" href="../rt_param_reference.html" title="Runtime parameters reference">
<link rel="prev" href="logger.html" title="logger">
<link rel="next" href="random.html" title="random">

Home
Libraries
People
FAQ
More

output_format

          Parameter output_format combines an effect of report_format and log_format parameters. This parameter
          does not have a default value. The only acceptable values are string names
          of output formats (see below).

Note

            This parameter has precedence over report_format
            and log_format on the command line.

          Acceptable
          values

          Enumeration name:

              HRF

              XML

          HRF stands for human readable format, while XML
          is dedicated to automated output processing

          Command
          line syntax

              --output_format=<format>

              -o
              <format>

          Environment
          variable

BOOST_TEST_OUTPUT_FORMAT

Copyright © 2001-2016 Boost.Test contributors

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
var noteService = require('../../services/note');
var userService = require('../../services/user');
var loanService = require('../../services/loan');

var db = require('../../utils/db');
var dates = require('../../utils/dates');
var async = require('simpleasync');

var noteId;
var investorId;
var borrowerId;
var loanId;

exports['clear data'] = function (test) {
    test.async();

    db.clear(function (err, data) {
        test.ok(!err);
        test.done();
    });
};

exports['new investor user'] = function (test) {
    test.async();

    userService.newUser({ name: "Eve" }, function (err, id) {
        test.ok(!err);
        test.ok(id);
        investorId = id;
        test.done();
    });
};

exports['new borrower user'] = function (test) {
    test.async();

    userService.newUser({ name: "Adam" }, function (err, id) {
        test.ok(!err);
        test.ok(id);
        borrowerId = id;
        test.done();
    });
};

exports['new loan'] = function (test) {
    test.async();

    loanService.newLoan({ user: borrowerId }, function (err, id) {
        test.ok(!err);
        test.ok(id);
        loanId = id;
        test.done();
    });
};

exports['new note'] = function (test) {
    test.async();

    noteService.newNote({ loan: loanId.toString(), amount: 1000, user: investorId.toString() }, function (err, id) {
        test.ok(!err);
        test.ok(id);
        noteId = id;
        test.done();
    });
};

exports['get note by id'] = function (test) {
    test.async();

    noteService.getNoteById(noteId, function (err, note) {
        test.ok(!err);
        test.ok(note);
        test.equal(typeof note, 'object');

        test.equal(note.status, 'open');
        test.equal(note.currency, 'ARS');

        test.ok(db.isNativeId(note.loan));
        test.ok(db.isNativeId(note.user));
        test.equal(note.loan.toString(), loanId.toString());
        test.equal(note.id.toString(), noteId.toString());

        test.ok(dates.isDateTimeString(note.datetime));

        test.done();
    });
};

exports['get unknown note by id'] = function (test) {
    test.async();

    noteService.getNoteById(0, function (err, note) {
        test.ok(!err);
        test.strictEqual(note, null);

        test.done();
    });
};

exports['get notes by user'] = function (test) {
    test.async();

    noteService.getNotesByUser(investorId, function (err, notes) {
        test.ok(!err);
        test.ok(notes);
        test.ok(Array.isArray(notes));
        test.equal(notes.length, 1);

        test.equal(notes[0].user.toString(), investorId.toString());
        test.equal(notes[0].id.toString(), noteId.toString());

        test.done();
    });
};

exports['get note by unknown user'] = function (test) {
    test.async();

    noteService.getNotesByUser(0, function (err, notes) {
        test.ok(!err);
        test.ok(notes);
        test.ok(Array.isArray(notes));
        test.equal(notes.length, 0);

        test.done();
    });
};

exports['get notes by loan'] = function (test) {
    test.async();

    noteService.getNotesByLoan(loanId, function (err, notes) {
        test.ok(!err);
        test.ok(notes);
        test.ok(Array.isArray(notes));
        test.equal(notes.length, 1);

        test.equal(notes[0].loan.toString(), loanId.toString());
        test.equal(notes[0].user.toString(), investorId.toString());
        test.equal(notes[0].id.toString(), noteId.toString());

        test.done();
    });
};

exports['get note by unknown loan'] = function (test) {
    test.async();

    noteService.getNotesByLoan(0, function (err, notes) {
        test.ok(!err);
        test.ok(notes);
        test.ok(Array.isArray(notes));
        test.equal(notes.length, 0);

        test.done();
    });
};

exports['get notes'] = function (test) {
    test.async();

    noteService.getNotes(function (err, notes) {
        test.ok(!err);
        test.ok(notes);
        test.ok(Array.isArray(notes));
        test.equal(notes.length, 1);

        test.equal(notes[0].user.toString(), investorId.toString());
        test.equal(notes[0].loan.toString(), loanId.toString());
        test.equal(notes[0].id.toString(), noteId.toString());

        test.done();
    });
};

exports['update note data'] = function (test) {
    test.async();

    noteService.updateNote(noteId, { description: 'A note' }, function (err, data) {
        test.ok(!err);

        noteService.getNoteById(noteId, function (err, note) {
            test.ok(!err);
            test.ok(note);
            test.equal(note.id.toString(), noteId.toString());
            test.equal(note.description, 'A note');
            test.equal(note.user.toString(), investorId.toString());

            test.done();
        });
    });
};


text:
module App {

    export class AlbumListPage extends Page {

        public criteria: IAlbumsCriteria;
        public model: IAlbumsViewModel;
        public artist: IListItem;
        public genre: IListItem;
        public genreFilterOpen: boolean;
        public artistFilterOpen: boolean;

        constructor(context: Context, public html: IHtmlHelper, private dataService: IAlbumsService) {

            super(context);
            this.initCriteria(true);

            this.dataService.getAlbumsWithfilters(this.criteria)
                .then((r: ng.IHttpPromiseCallbackArg<IAlbumsViewModel>) => this.getAlbumsWithfiltersDone(r));
        }

        private getAlbumsWithfiltersDone(r: ng.IHttpPromiseCallbackArg<IAlbumsViewModel>) {
            this.genre = _.findWhere(r.data.genres, { id: this.criteria.genreId });
            this.artist = _.findWhere(r.data.artists, { id: this.criteria.artistId });
            this.model = r.data;

            this.updateQueryString(true);
        }

        private initCriteria(onload?: boolean) {

            this.criteria = { page: 1, pageSize: 6 };
            this.artist = null;
            this.genre = null;

            if (onload) {
                var query = this.context.getSearch();

                this.criteria.artistId = parseInt(query.artistId) || null;
                this.criteria.genreId = parseInt(query.genreId) || null;
                this.criteria.search = query.search;
                this.criteria.page = parseInt(query.page) || 1;
            }
        }

        private currQueryString: string;
        private updateQueryString(onload?: boolean) {

            if (!onload) {
                this.context.updateSearch(this.filterQueryObject(), true);
            }

            this.currQueryString = this.context.getQuery();
        }

        updateGenre(genre?: IListItem) {
            this.genre = genre;
            this.criteria.genreId = genre == null ? null : genre.id;
            this.criteria.page = 1;
            this.updateAlbums();
        }

        updateArtist(artist?: IListItem) {
            this.artist = artist;
            this.criteria.artistId = artist == null ? null : artist.id;
            this.artistFilterOpen = false;
            this.criteria.page = 1;
            this.updateAlbums();
        }

        linkGenre(genreId: number, genreName: string) {
            this.initCriteria();
            this.updateGenre({ id: genreId, name: genreName });
        }

        linkArtist(artistId: number, artistName: string) {
            this.initCriteria();
            this.updateArtist({ id: artistId, name: artistName });
        }

        updateAlbums() {

            this.dataService.getAlbums(this.criteria)
                .then((r: ng.IHttpPromiseCallbackArg<IPagingList<IAlbumHeader>>) => {
                    this.model.albums = r.data;
                    this.updateQueryString();
                });
        }

        refresh() {
            this.initCriteria();
            this.updateAlbums();
        }

        detailsUrl(album: IAlbumHeader) {

            return '#/albums/' + album.id + this.currQueryString;
        }

        private filterQueryObject() {
            return {
                artistId: this.criteria.artistId,
                genreId: this.criteria.genreId,
                search: this.criteria.search,
                page: this.criteria.page == 1 ? null : this.criteria.page
            }
        }
    }

    angular.module('app')
        .controller('Albums', ['Context', 'HtmlHelper', 'AlbumsService', AlbumListPage]);

}


text:
class Digdag < Formula
  desc "Workload Automation System"
  homepage "https://www.digdag.io/"
  url "https://dl.digdag.io/digdag-0.10.0.jar"
  sha256 "0a3aed836d8af1a47ed53dda63c02ce3ecfec6b564d55b556a18b122dec7f3d7"
  license "Apache-2.0"

  livecheck do
    url "https://github.com/treasure-data/digdag.git"
    regex(/^v?(\d+(?:\.\d+)+)$/i)
  end

  bottle :unneeded

  depends_on "openjdk@8"

  def install
    libexec.install "digdag-#{version}.jar"
    (libexec/"bin").write_jar_script libexec/"digdag-#{version}.jar", "digdag"
    (libexec/"bin/digdag").chmod 0755
    (bin/"digdag").write_env_script libexec/"bin/digdag", Language::Java.java_home_env("1.8")
  end

  test do
    assert_match version.to_s, shell_output("#{bin}/digdag --version")
  end
end


text:
package yokohama.unit.translator.experimental;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import yokohama.unit.ast.Ident;
import yokohama.unit.ast.QuotedExpr;
import yokohama.unit.ast_junit.BooleanLitExpr;
import yokohama.unit.ast_junit.CatchClause;
import yokohama.unit.ast_junit.ClassDecl;
import yokohama.unit.ast_junit.ClassType;
import yokohama.unit.ast_junit.FieldStaticExpr;
import yokohama.unit.ast_junit.InstanceOfMatcherExpr;
import yokohama.unit.ast_junit.InvokeExpr;
import yokohama.unit.ast_junit.InvokeVoidStatement;
import yokohama.unit.ast_junit.IsStatement;
import yokohama.unit.ast_junit.NewExpr;
import yokohama.unit.ast_junit.Statement;
import yokohama.unit.ast_junit.StrLitExpr;
import yokohama.unit.ast_junit.Type;
import yokohama.unit.ast_junit.VarInitStatement;
import yokohama.unit.position.Span;
import yokohama.unit.translator.ExpressionStrategy;
import yokohama.unit.util.ClassResolver;
import yokohama.unit.util.GenSym;
import yokohama.unit.util.Sym;

@RequiredArgsConstructor
public class ScalaExpressionStrategy implements ExpressionStrategy {
    final String name;
    final String packageName;
    final GenSym genSym;
    final ClassResolver classResolver;

    static final String MATCHER = "org.hamcrest.Matcher";
    static final String IMAIN = "scala.tools.nsc.interpreter.IMain";
    static final String SETTINGS = "scala.tools.nsc.Settings";
    static final String ABS_SETTING =
            "scala.tools.nsc.settings.AbsSettings$AbsSetting";
    static final String BOOLEAN_SETTING =
            "scala.tools.nsc.settings.MutableSettings$BooleanSetting";
    static final String NIL$ = "scala.collection.immutable.Nil$";
    static final String LIST = "scala.collection.immutable.List";
    static final String RESULT = "scala.tools.nsc.interpreter.Results$Result";
    static final String SUCCESS$ = "scala.tools.nsc.interpreter.Results$Success$";
    static final String OPTION = "scala.Option";

    @SneakyThrows(ClassNotFoundException.class)
    ClassType classTypeOf(String name) {
        return new ClassType(classResolver.lookup(name));
    }
    Type typeOf(String name) {
        return classTypeOf(name).toType();
    }

    @Override
    public Collection<ClassDecl> auxClasses() {
        return Collections.emptyList();
    }

    @Override
    public List<Statement> env(Sym var) {
        Sym settings = genSym.generate("settings");
        Sym usejavacp = genSym.generate("usejavacp");
        Sym true_ = genSym.generate("true_");
        Stream<Statement> main = Stream.of(
                new VarInitStatement(
                        typeOf(SETTINGS),
                        settings,
                        new NewExpr(
                                SETTINGS,
                                Arrays.asList(),
                                Arrays.asList()),
                        Span.dummySpan()),
                new VarInitStatement(
                        typeOf(BOOLEAN_SETTING),
                        usejavacp,
                        new InvokeExpr(
                                classTypeOf(SETTINGS),
                                settings,
                                "usejavacp",
                                Arrays.asList(),
                                Arrays.asList(),
                                typeOf(ABS_SETTING)),
                        Span.dummySpan()),
                new VarInitStatement(
                        Type.BOOLEAN,
                        true_,
                        new BooleanLitExpr(true),
                        Span.dummySpan()),
                new InvokeVoidStatement(
                        classTypeOf(BOOLEAN_SETTING),
                        usejavacp,
                        "v_$eq",
                        Arrays.asList(Type.BOOLEAN),
                        Arrays.asList(true_),
                        Span.dummySpan()),
                new VarInitStatement(
                        typeOf(IMAIN),
                        var,
                        new NewExpr(
                                IMAIN,
                                Arrays.asList(typeOf(SETTINGS)),
                                Arrays.asList(settings)),
                        Span.dummySpan()));
        Stream<Statement> importClasses = classResolver.flatMap((shortName, longName) -> {
            int dotIndex = longName.lastIndexOf('.');
            String packageName = longName.substring(0, dotIndex);
            String simpleName = longName.substring(dotIndex + 1);
            Sym importVar = genSym.generate("import_");
            Sym resultVar = genSym.generate("result");
            return Stream.of(new VarInitStatement(
                        Type.STRING,
                        importVar,
                        new StrLitExpr("import " + packageName + ".{" + simpleName + " => " + shortName + "}"),
                        Span.dummySpan()),
                new VarInitStatement(
                        typeOf(RESULT),
                        resultVar,
                        new InvokeExpr(
                                classTypeOf(IMAIN),
                                var,
                                "interpret",
                                Arrays.asList(Type.STRING),
                                Arrays.asList(importVar),
                                typeOf(RESULT)),
                        Span.dummySpan()));
        });
        return Stream.concat(main, importClasses).collect(Collectors.toList());
    }

    @Override
    public List<Statement> bind(Sym envVar, Ident ident, Sym rhs) {
        Sym nameVar = genSym.generate(ident.getName());
        Sym boundTypeVar = genSym.generate("boundType");
        Sym modifiersVar = genSym.generate("modifiers");
        return Arrays.asList(
                new VarInitStatement(
                        Type.STRING,
                        nameVar,
                        new StrLitExpr(ident.getName()),
                        ident.getSpan()),
                new VarInitStatement(
                        Type.STRING,
                        boundTypeVar,
                        new StrLitExpr("java.lang.Object"),
                        Span.dummySpan()),
                new VarInitStatement(
                        typeOf(LIST),
                        modifiersVar,
                        new FieldStaticExpr(
                                classTypeOf(NIL$),
                                typeOf(NIL$),
                                "MODULE$"),
                        Span.dummySpan()),
                new VarInitStatement(
                        typeOf(RESULT),
                        genSym.generate("__"),
                        new InvokeExpr(
                                classTypeOf(IMAIN),
                                envVar,
                                "bind",
                                Arrays.asList(
                                        Type.STRING,
                                        Type.STRING,
                                        Type.OBJECT,
                                        typeOf(LIST)),
                                Arrays.asList(
                                        nameVar,
                                        boundTypeVar,
                                        rhs,
                                        modifiersVar),
                                typeOf(RESULT)),
                        Span.dummySpan()));
    }

    @Override
    public Optional<CatchClause> catchAndAssignCause(Sym causeVar) {
        return Optional.empty();
    }

    @Override
    public List<Statement> eval(Sym var, QuotedExpr quotedExpr, Class<?> expectedType, Sym envVar) {
        Span span = quotedExpr.getSpan();
        Sym exprVar = genSym.generate("expression");
        Sym resultVar = genSym.generate("result");
        Sym messageVar = genSym.generate("message");
        Sym instanceOfMatcherVar = genSym.generate("instanceOfMatcher");
        Sym mostRecentVar = genSym.generate("mostRecent");
        Sym valueOfTermVar = genSym.generate("valueOfTerm");
        return Arrays.asList(
                new VarInitStatement(
                        Type.STRING,
                        exprVar,
                        new StrLitExpr(quotedExpr.getText()),
                        span),
                new VarInitStatement(
                        typeOf(RESULT),
                        resultVar,
                        new InvokeExpr(
                                classTypeOf(IMAIN),
                                envVar,
                                "interpret",
                                Arrays.asList(Type.STRING),
                                Arrays.asList(exprVar),
                                typeOf(RESULT)),
                        Span.dummySpan()),
                new VarInitStatement(
                        Type.STRING,
                        messageVar,
                        new StrLitExpr(""),
                        Span.dummySpan()),
                new VarInitStatement(
                        typeOf(MATCHER),
                        instanceOfMatcherVar,
                        new InstanceOfMatcherExpr(classTypeOf(SUCCESS$)),
                        Span.dummySpan()),
                new IsStatement(
                        messageVar,
                        resultVar,
                        instanceOfMatcherVar,
                        Span.dummySpan()),
                new VarInitStatement(
                        Type.STRING,
                        mostRecentVar,
                        new InvokeExpr(
                                classTypeOf(IMAIN),
                                envVar,
                                "mostRecentVar",
                                Arrays.asList(),
                                Arrays.asList(),
                                Type.STRING),
                        Span.dummySpan()),
                new VarInitStatement(
                        typeOf(OPTION),
                        valueOfTermVar,
                        new InvokeExpr(
                                classTypeOf(IMAIN),
                                envVar,
                                "valueOfTerm",
                                Arrays.asList(Type.STRING),
                                Arrays.asList(mostRecentVar),
                                typeOf(OPTION)),
                        Span.dummySpan()),
                new VarInitStatement(
                        Type.fromClass(expectedType),
                        var,
                        new InvokeExpr(
                                classTypeOf(OPTION),
                                valueOfTermVar,
                                "get",
                                Arrays.asList(),
                                Arrays.asList(),
                                Type.OBJECT),
                        Span.dummySpan()));
    }

    @Override
    public List<Statement> dumpEnv(Sym var, Sym envVar) {
        return Arrays.asList(
                new VarInitStatement(
                        Type.STRING,
                        var,
                        new StrLitExpr(""),
                        Span.dummySpan()));
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

@implementation UIScreen (ASTKit)

+ (CGFloat)screenScale {
    return [[UIScreen mainScreen] scale];
}

- (CGSize)sizeInPixel {
    CGSize size;
    if ([self respondsToSelector:@selector(nativeBounds)]) {
        size = self.nativeBounds.size;
    } else {
        size = self.bounds.size;
        size.width *= self.scale;
        size.height *= self.scale;
    }
    if (UIDevice.isLandscape) {
        CGFloat tmp = size.height;
        size.height = size.width;
        size.width = tmp;
    }

    return size;
}

- (CGFloat)pixelsPerInch {
    CGFloat ppi = 0;

    if ([[UIScreen mainScreen] isEqual:self]) {
        NSString *model = UIDevice.machineModel;
        if ([model hasPrefix:@"iPhone"]) {
            if ([model hasPrefix:@"iPhone1"]) ppi = 163;
            else if ([model hasPrefix:@"iPhone2"]) ppi = 163;
            else if ([model hasPrefix:@"iPhone3"]) ppi = 326;
            else if ([model hasPrefix:@"iPhone4"]) ppi = 326;
            else if ([model hasPrefix:@"iPhone5"]) ppi = 326;
            else if ([model hasPrefix:@"iPhone6"]) ppi = 326;
            else if ([model hasPrefix:@"iPhone7,1"]) ppi = 401;
            else if ([model hasPrefix:@"iPhone7,2"]) ppi = 326;
            else if ([model hasPrefix:@"iPhone8,1"]) ppi = 401;
            else if ([model hasPrefix:@"iPhone8,2"]) ppi = 326;
            else if ([model hasPrefix:@"iPhone8,4"]) ppi = 326;
        } else if ([model hasPrefix:@"iPod"]) {
            if ([model hasPrefix:@"iPod1"]) ppi = 163;
            else if ([model hasPrefix:@"iPod2"]) ppi = 163;
            else if ([model hasPrefix:@"iPod3"]) ppi = 163;
            else if ([model hasPrefix:@"iPod4"]) ppi = 326;
            else if ([model hasPrefix:@"iPod5"]) ppi = 326;
            else if ([model hasPrefix:@"iPod7"]) ppi = 326;
        } else if ([model hasPrefix:@"iPad"]) {
            if ([model hasPrefix:@"iPad1"]) ppi = 132;
            else if ([model hasPrefix:@"iPad2,1"]) ppi = 132;
            else if ([model hasPrefix:@"iPad2,2"]) ppi = 132;
            else if ([model hasPrefix:@"iPad2,3"]) ppi = 132;
            else if ([model hasPrefix:@"iPad2,4"]) ppi = 132;
            else if ([model hasPrefix:@"iPad2,5"]) ppi = 163;
            else if ([model hasPrefix:@"iPad2,6"]) ppi = 163;
            else if ([model hasPrefix:@"iPad2,7"]) ppi = 163;
            else if ([model hasPrefix:@"iPad3"]) ppi = 264;
            else if ([model hasPrefix:@"iPad4,1"]) ppi = 264;
            else if ([model hasPrefix:@"iPad4,2"]) ppi = 264;
            else if ([model hasPrefix:@"iPad4,3"]) ppi = 264;
            else if ([model hasPrefix:@"iPad4,4"]) ppi = 324;
            else if ([model hasPrefix:@"iPad4,5"]) ppi = 324;
            else if ([model hasPrefix:@"iPad4,6"]) ppi = 324;
            else if ([model hasPrefix:@"iPad4,7"]) ppi = 324;
            else if ([model hasPrefix:@"iPad4,8"]) ppi = 324;
            else if ([model hasPrefix:@"iPad4,9"]) ppi = 324;
            else if ([model hasPrefix:@"iPad5,3"]) ppi = 264;
            else if ([model hasPrefix:@"iPad5,4"]) ppi = 324;
            else if ([model hasPrefix:@"iPad6,3"]) ppi = 264;
            else if ([model hasPrefix:@"iPad6,4"]) ppi = 264;
            else if ([model hasPrefix:@"iPad6,7"]) ppi = 264;
            else if ([model hasPrefix:@"iPad6,8"]) ppi = 264;
        }
    }

    if (ppi == 0) ppi = 326;
    return ppi;
}

@end

NS_ASSUME_NONNULL_END


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.krminc.phr.domain;

import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
 *
 * @author cmccall
 */

//Proposed fields:
//
//    * Contact name* (Ex. Aunt Cindy)  [removed]
//    * First Name
//    * Middle Name
//    * Last Name
//    * Relationship
//    * Phone Number (multiple)
//    * Ph. # Description
//    * Email Address (multiple)        [removed]
//    * Email Description               [removed]
//    * Organization
//    * ID
//    * Address Description (multiple)
//    * Street Address Line 1
//    * Street Address Line 2
//    * City
//    * State
//    * Zip
//    * Note

@Entity
@Table(name="phr.data_emergencycontacts")
public class EmergencyContact implements Serializable {
    private static final long serialVersionUID = 20091110L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="emergencycontact_id")
    private Long id;

    @Basic(optional = false)
    @Column(name = "first_name", nullable = false, length = 100)
    private String firstName;
    @Column(name = "middle_name", length = 50)
    private String middleName;
    @Basic(optional = false)
    @Column(name = "last_name", nullable = false, length = 50)
    private String lastName;

    @Basic(optional = false)
    @Column(name = "relationship", nullable = false, length = 100)
    private String relationship;

    @Column(name = "organization", length = 100)
    private String organization;

    @Column(name = "note", length = 255)
    private String note;

    @OneToMany(mappedBy = "contact")
    private List<ContactAddress> addresses;

    @OneToMany(mappedBy = "contact")
    private List<ContactPhone> phones;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getMiddleName() {
        return middleName;
    }

    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public String getOrganization() {
        return organization;
    }

    public void setOrganization(String organization) {
        this.organization = organization;
    }

    public List<ContactPhone> getPhones() {
        return phones;
    }

    public void setPhones(List<ContactPhone> phones) {
        this.phones = phones;
    }

    public List<ContactAddress> getAddresses() {
        return addresses;
    }

    public void setAddresses(List<ContactAddress> addresses) {
        this.addresses = addresses;
    }

    public String getRelationship() {
        return relationship;
    }

    public void setRelationship(String relationship) {
        this.relationship = relationship;
    }

    //custom methods
    public String getFullName(){
        String fullName = getFirstName().concat(" ");
        if (getMiddleName().length() > 0) {
            fullName.concat(getMiddleName()).concat(" ");
        }
        return (fullName.concat(getLastName()));
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof EmergencyContact)) {
            return false;
        }
        EmergencyContact other = (EmergencyContact) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.krminc.phr.domain.EmergencyContact[id=" + id + "]";
    }

}


text:
require 'spec_helper'

RSpec.describe Karafka::Routing::Route do
  subject(:route) { described_class.new }

  let(:group) { rand.to_s }
  let(:topic) { rand.to_s }

  describe '#build' do
    it 'expect to eager load all the attributes' do
      expect(route)
        .to receive(:worker)

      expect(route)
        .to receive(:parser)

      expect(route)
        .to receive(:interchanger)

      expect(route)
        .to receive(:group)

      expect(route.build).to eq route
    end
  end

  describe '#group=' do
    it { expect { route.group = group }.not_to raise_error }
  end

  describe '#group' do
    before do
      route.group = group
      route.topic = topic
    end

    context 'when group is not set' do
      let(:group) { nil }

      it 'expect to build group from app name and topic' do
        expect(route.group).to eq "#{Karafka::App.config.name.underscore}_#{topic}".to_s
      end
    end

    context 'when group is set' do
      it { expect(route.group).to eq group }
    end
  end

  describe '#topic=' do
    it { expect { route.topic = topic }.not_to raise_error }
  end

  describe '#topic' do
    let(:topic) { rand }

    before { route.topic = topic }

    it 'expect to return stringified topic' do
      expect(route.topic).to eq topic.to_s
    end
  end

  describe '#worker=' do
    let(:worker) { double }

    it { expect { route.worker = worker }.not_to raise_error }
  end

  describe '#worker' do
    let(:controller) { double }

    before do
      route.worker = worker
      route.controller = controller
    end

    context 'when worker is not set' do
      let(:worker) { nil }
      let(:built_worker) { double }
      let(:builder) { double }

      it 'expect to build worker using builder' do
        expect(Karafka::Workers::Builder)
          .to receive(:new)
          .with(controller)
          .and_return(builder)

        expect(builder)
          .to receive(:build)
          .and_return(built_worker)

        expect(route.worker).to eq built_worker
      end
    end

    context 'when worker is set' do
      let(:worker) { double }

      it { expect(route.worker).to eq worker }
    end
  end

  describe '#parser=' do
    let(:parser) { double }

    it { expect { route.parser = parser }.not_to raise_error }
  end

  describe '#parser' do
    before { route.parser = parser }

    context 'when parser is not set' do
      let(:parser) { nil }

      it 'expect to use default one' do
        expect(route.parser).to eq JSON
      end
    end

    context 'when parser is set' do
      let(:parser) { double }

      it { expect(route.parser).to eq parser }
    end
  end

  describe '#interchanger=' do
    let(:interchanger) { double }

    it { expect { route.interchanger = interchanger }.not_to raise_error }
  end

  describe '#interchanger' do
    before { route.interchanger = interchanger }

    context 'when interchanger is not set' do
      let(:interchanger) { nil }

      it 'expect to use default one' do
        expect(route.interchanger).to eq Karafka::Params::Interchanger
      end
    end

    context 'when interchanger is set' do
      let(:interchanger) { double }

      it { expect(route.interchanger).to eq interchanger }
    end
  end

  describe '#validate!' do
    before { route.topic = topic }

    context 'when topic name is invalid' do
      %w(
        & /31 ół !@
      ).each do |topic_name|
        let(:topic) { topic_name }

        it { expect { route.validate! }.to raise_error(Karafka::Errors::InvalidTopicName) }
      end
    end

    context 'when topic name is valid' do
      let(:topic) { rand(1000).to_s }

      before { route.group = group }

      context 'but group name is invalid' do
        %w(
          & /31 ół !@
        ).each do |group_name|
          let(:group) { group_name }

          it { expect { route.validate! }.to raise_error(Karafka::Errors::InvalidGroupName) }
        end
      end

      context 'and group name is valid' do
        let(:group) { rand(1000).to_s }

        it { expect { route.validate! }.not_to raise_error }
      end
    end
  end
end


text:
#include <stdarg.h>
#include <stdio.h>
#include <libioP.h>
#include <wchar.h>

/* Read formatted input from S, according to the format string FORMAT.  */
/* VARARGS2 */
int
__isoc99_swscanf (const wchar_t *s, const wchar_t *format, ...)
{
  va_list arg;
  int done;

  va_start (arg, format);
  done = __isoc99_vswscanf (s, format, arg);
  va_end (arg);

  return done;
}


text:
// Copyright (C) 2002-2004 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in Irrlicht.h

#ifndef __I_MESH_H_INCLUDED__
#define __I_MESH_H_INCLUDED__

#include "IUnknown.h"
#include "IMeshBuffer.h"

namespace irr
{
namespace scene
{
	//! Class for accessing a mesh with multiple mesh buffers.
	/** A IMesh is nothing more than a collection of some mesh buffers (IMeshBuffer).
	SMesh is a simple implementation of an IMesh.
	*/
	class IMesh : public IUnknown
	{
	public:

		//! destructor
		virtual ~IMesh(){};

		//! Returns the amount of mesh buffers.
		//! \return Returns the amount of mesh buffers (IMeshBuffer) in this mesh.
		virtual s32 getMeshBufferCount() = 0;

		//! Returns pointer to a mesh buffer.
		//! \param Zero based index of the mesh buffer. The maximum value is
		//! getMeshBufferCount() - 1;
		//! \return Returns the pointer to the mesh buffer or
		//! NULL if there is no such mesh buffer.
		virtual IMeshBuffer* getMeshBuffer(s32 nr) = 0;

		//! Returns an axis aligned bounding box of the mesh.
		//! \return A bounding box of this mesh is returned.
		virtual const core::aabbox3d<f32>& getBoundingBox() const = 0;

		//! Returns an axis aligned bounding box of the mesh.
		//! \return A bounding box of this mesh is returned.
		virtual core::aabbox3d<f32>& getBoundingBox() = 0;

		//! Sets a flag of all contained materials to a new value.
		//! \param flag: Flag to set in all materials.
		//! \param newvalue: New value to set in all materials.
		virtual void setMaterialFlag(video::E_MATERIAL_FLAG flag, bool newvalue) = 0;
	};

} // end namespace scene
} // end namespace irr

#endif


text:
@implementation MeCardHeardView

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.backgroundColor=[UIColor whiteColor];

        _isAlreadyBuy=YES;

        _alreadyBuyLab=[UILabel new];
        _alreadyBuyLab.tag=101;
        _alreadyBuyLab.text=@"已购买会员";
        _alreadyBuyLab.textColor=HESCOLOR_WORD_BLACK;
        _alreadyBuyLab.textAlignment=NSTextAlignmentCenter;
        _alreadyBuyLab.font=LayOutBOLDFont(32);
        _alreadyBuyLab.userInteractionEnabled=YES;
        [self addSubview:_alreadyBuyLab];
        _alreadyBuyLab.sd_layout
        .topSpaceToView(self,0)
        .bottomSpaceToView(self,0)
        .leftSpaceToView(self,LayOutW(135))
        .widthIs(LayOutW(180));

        _notBuyLab=[UILabel new];
        _notBuyLab.tag=102;
        _notBuyLab.font=LayOutBOLDFont(32);
        _notBuyLab.textColor=HESHEXCOLOR(@"999999");
        _notBuyLab.text=@"可购买会员";
        _notBuyLab.textAlignment=NSTextAlignmentCenter;
        _notBuyLab.userInteractionEnabled=YES;
        [self addSubview:_notBuyLab];
        _notBuyLab.sd_layout
        .topSpaceToView(self,0)
        .bottomSpaceToView(self,0)
        .rightSpaceToView(self,LayOutW(135))
        .widthIs(LayOutW(180));

        _line=[UILabel new];
        _line.backgroundColor=HESHEXCOLOR(@"00a652");
        [self addSubview:_line];
        _line.sd_layout
        .bottomSpaceToView(self,0)
        .centerXEqualToView(_alreadyBuyLab)
        .widthIs(LayOutW(180))
        .heightIs(2);
        UITapGestureRecognizer*tapGesture1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(actiondo:)];
        [_alreadyBuyLab addGestureRecognizer:tapGesture1];

        UITapGestureRecognizer*tapGesture2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(actiondo:)];
        [_notBuyLab addGestureRecognizer:tapGesture2];
    }
    return self;
}

-(void)actiondo:(UITapGestureRecognizer*)recognizer{

    if (self.isAlreadyBuy) {
        if (recognizer.view.tag==101) {
            return;
        }
    }else{
        if (recognizer.view.tag==102) {

            return;
        }
    }

    self.isAlreadyBuy=!self.isAlreadyBuy;
}
-(void)setIsAlreadyBuy:(BOOL)isAlreadyBuy{
    _isAlreadyBuy=isAlreadyBuy;

    if (isAlreadyBuy) {
        if ([self.delegate respondsToSelector:@selector(switchToLastController)]) {
            [self.delegate switchToLastController];
        }
    } else {
        if ([self.delegate respondsToSelector:@selector(switchToNextController)]) {
            [self.delegate switchToNextController];
        }
    }

    [UIView animateWithDuration:0.3 animations:^{
        if (isAlreadyBuy) {
            _line.sd_layout
            .centerXEqualToView(_alreadyBuyLab);

        }else{
            _line.sd_layout
            .centerXEqualToView(_notBuyLab);

        }
        [_line updateLayout];
    } completion:^(BOOL finished) {

        _alreadyBuyLab.textColor=isAlreadyBuy?HESCOLOR_WORD_BLACK:HESHEXCOLOR(@"999999");
        _notBuyLab.textColor=isAlreadyBuy?HESHEXCOLOR(@"999999"):HESCOLOR_WORD_BLACK;
    }];
}
@end


text:
<?php

use League\FactoryMuffin\Facade as FactoryMuffin;

FactoryMuffin::define('WebservicesNl\Protocol\Soap\Exception\SoapFault', [
    'detail' => 'sentence',
    'faultActor' => 'something',
    'faultCode' => 'Server',
    'faultName' => 'word',
    'faultString' => 'Something went wrong',
    'headerFault' => '',
    'errorMessage' => 'sentence',
]);


text:
<!--
Description: item guid not permalink is not resolved as a URL
Expect:      not bozo and entries[0]['id'] == 'abc'
-->
<rss version="2.0" xml:base="http://dom.test/">
<channel>
<item>
<guid isPermaLink="false">abc</guid>
</item>
</channel>
</rss>


text:
#region "Copyright"
/*
FOR FURTHER DETAILS ABOUT LICENSING, PLEASE VISIT "LICENSE.txt" INSIDE THE SAGEFRAME FOLDER
*/
#endregion

#region "References"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SageFrame.Web.Utilities;
using System.Data.SqlClient;
using System.Data;
using SageFrame.Web;
using SageFrame.ModuleManager;
#endregion

namespace SageFrame.ModuleManager
{
    /// <summary>
    /// Manupulates data for LayoutMgrDataProvider.
    /// </summary>
    public class LayoutMgrDataProvider
    {
        /// <summary>
        /// Connect to database and get modules based on PortalID.
        /// </summary>
        /// <param name="PortalID">PortalID</param>
        /// <returns>List of LayoutMgrInfo class.</returns>
        public static List<LayoutMgrInfo> GetModules(int PortalID)
        {
            SQLHandler SQLH = new SQLHandler();
            List<KeyValuePair<string, object>> ParaMeterCollection = new List<KeyValuePair<string, object>>();
            ParaMeterCollection.Add(new KeyValuePair<string, object>("@PortalID", PortalID));
            return SQLH.ExecuteAsList<LayoutMgrInfo>("[usp_ModuleManagerGetPortalModules]",ParaMeterCollection);
        }
        /// <summary>
        /// Connect to database and obtain admin modules.
        /// </summary>
        /// <param name="PortalID">PortalID</param>
        /// <returns>List of LayoutMgrInfo.</returns>
        public static List<LayoutMgrInfo> GetAdminModules(int PortalID)
        {
            SQLHandler SQLH = new SQLHandler();
            List<KeyValuePair<string, object>> ParaMeterCollection = new List<KeyValuePair<string, object>>();
            ParaMeterCollection.Add(new KeyValuePair<string, object>("@PortalID", PortalID));
            return SQLH.ExecuteAsList<LayoutMgrInfo>("[dbo].[usp_ModuleManagerGetAdminModules]",ParaMeterCollection);
        }
        /// <summary>
        /// Connect to database and obtain module information based onmodule name.
        /// </summary>
        /// <param name="ModuleName">Module name.</param>
        /// <returns>List of LayoutMgrInfo class.</returns>
        public static List<LayoutMgrInfo> GetModuleInformation(string ModuleName)
        {
            SQLHandler SQLH = new SQLHandler();
            List<KeyValuePair<string, object>> ParaMeterCollection = new List<KeyValuePair<string, object>>();
            ParaMeterCollection.Add(new KeyValuePair<string, object>("@FriendlyName", ModuleName));

            return SQLH.ExecuteAsList<LayoutMgrInfo>("[dbo].[usp_GetModuleInformation]", ParaMeterCollection);
        }
        /// <summary>
        /// Connect to database and search module.
        /// </summary>
        /// <param name="search">Searching string.</param>
        /// <param name="PortalID">PortalID</param>
        /// <param name="IsAdmin">true if admin modules.</param>
        /// <returns>List of LayoutMgrInfo class.</returns>
        public static List<LayoutMgrInfo> SearchModules(string search,int PortalID,bool IsAdmin)
        {
            SQLHandler SQLH = new SQLHandler();
            List<KeyValuePair<string, object>> ParaMeterCollection = new List<KeyValuePair<string, object>>();
            ParaMeterCollection.Add(new KeyValuePair<string, object>("@SearchText", search));
            ParaMeterCollection.Add(new KeyValuePair<string, object>("@PortalID", PortalID));
            ParaMeterCollection.Add(new KeyValuePair<string, object>("@IsAdmin", IsAdmin));
            return SQLH.ExecuteAsList<LayoutMgrInfo>("[dbo].[usp_ModuleManagerGetSearchModules]", ParaMeterCollection);
        }
        /// <summary>
        /// Connect to database and obtain sort modules.
        /// </summary>
        /// <param name="flag">flag</param>
        /// <param name="isAdmin">true for admin.</param>
        /// <param name="PortalID">PortalID</param>
        /// <param name="IncludePortalModules">IncludePortalModules</param>
        /// <returns>List of LayoutMgrInfo class.</returns>
        public static List<LayoutMgrInfo> GetSortModules(int flag, bool isAdmin, int PortalID, int IncludePortalModules)
        {
            SQLHandler SQLH = new SQLHandler();
            List<KeyValuePair<string, object>> ParaMeterCollection = new List<KeyValuePair<string, object>>();
            ParaMeterCollection.Add(new KeyValuePair<string, object>("@flag", flag));
            ParaMeterCollection.Add(new KeyValuePair<string, object>("@isAdmin", isAdmin));
            ParaMeterCollection.Add(new KeyValuePair<string, object>("@PortalID", PortalID));
            ParaMeterCollection.Add(new KeyValuePair<string, object>("@IncludePortalModules", IncludePortalModules));
            try
            {
                return SQLH.ExecuteAsList<LayoutMgrInfo>("[dbo].[usp_ModuleMgrSortModules]", ParaMeterCollection);
            }
            catch (Exception)
            {

                throw;
            }

        }
        /// <summary>
        /// Connect to database and add lay out.
        /// </summary>
        /// <param name="obj">Object of LayoutMgrInfo class.</param>
        /// <returns>Newly added ID.</returns>
        public static int AddLayOutMgr(LayoutMgrInfo obj)
        {
            try
            {

                SqlConnection SQLConn = new SqlConnection(SystemSetting.SageFrameConnectionString);
                SqlCommand SQLCmd = new SqlCommand();
                int ReturnValue = -1;
                SQLCmd.Connection = SQLConn;
                SQLCmd.CommandText = "[dbo].[usp_AddModulesOrder]";
                SQLCmd.CommandType = CommandType.StoredProcedure;
                SQLCmd.Parameters.Add(new SqlParameter("@ModuleOrder", obj.ModuleOrder));
                SQLCmd.Parameters.Add(new SqlParameter("@PortelID", obj.PortelID));
                SQLCmd.Parameters.Add(new SqlParameter("@ModuleID", obj.ModuleID));
                SQLCmd.Parameters.Add(new SqlParameter("@ModuleName", obj.ModuleName));
                SQLCmd.Parameters.Add(new SqlParameter("@PaneName", obj.PaneName));
                SQLCmd.Parameters.Add(new SqlParameter("@UserModuleID", obj.UserModuleID));

                SQLCmd.Parameters.Add(new SqlParameter("@NewModuleID", SqlDbType.Int));
                SQLCmd.Parameters["@NewModuleID"].Direction = ParameterDirection.Output;

                SQLConn.Open();
                SQLCmd.ExecuteNonQuery();
                ReturnValue = (int)SQLCmd.Parameters["@NewModuleID"].Value;
                return ReturnValue;
            }
            catch (Exception e)
            {
                throw e;
            }

        }
    }
}


text:
angular.module('<%= _.camelCase(appname) %>').factory('api',function(angAws, $http) {
    //create our service object
	var api = {};

	api.defaults = {
		url: 'http://192.168.7.24:3002'
	};

	api.call = function(method, endpoint, data) {
		var config = {
			cache: false,
			method: method,
			url: api.defaults.url + endpoint
		}
		if (data) {
			config.data = data;
		}
		return $http(config);
	};

	//our crud
	api.put = function(model, item) {
		var endpoint = '/api/rest/' + model + '/' + item.id;
		return api.call('PUT', endpoint, item);
	};
	api.get = function(model, hash) {
		var endpoint = '/api/rest/' + model;
		if (hash)
			endpoint += '/' + hash;
		return api.call('GET', endpoint, null);
	};
	api.post = function(model, hash, range) {
		var endpoint = '/api/rest/' + model;
		return api.call('POST', endpoint, item);
	};
	api.delete = function(model, item) {
		var endpoint = '/api/rest/' + model + '/' + item.id;
		return api.call('DELETE', endpoint, item);
	};

	//login
	api.login = function(user) {
		return api.call('POST', '/api/login', user);
	}

	//return service object
	return api;
});


text:
# Function Libraries

You can add custom function libraries in `src/Synful/App/Functions`.

> Note: These function libraries will be loaded before anything else.

---

**Example**

`src/App/Functions/MyFunctionLib.php`

```php
<?php

if (! function_exists('my_custom_function')) {
    /**
     * A custom function
     */
    function my_custom_function()
    {
        return 'this is a custom function';
    }
}
```

You can now call `my_custom_function` from anywhere in your application.

---
Next: [CORS](./Cors.md) - ([Back to Index](./README.md))


text:
package com.tyrfing.games.id17.effects;

import com.tyrfing.games.id17.buildings.Building;
import com.tyrfing.games.id17.houses.House;

public class EnableBuildingEffect implements IEffect {

	public final String[] buildingNames;
	public final String[] holdingTypes;

	public EnableBuildingEffect(String[] buildingNames, String[] holdingTypes) {
		this.buildingNames = buildingNames;
		this.holdingTypes = holdingTypes;
	}

	@Override
	public void apply(House house) {
		for (int i = 0; i < buildingNames.length; ++i) {
			int buildingID = Building.TYPE.valueOf(buildingNames[i]).ordinal();
			for (int j = 0; j < holdingTypes.length; ++j) {
				house.enableBuilding(holdingTypes[j], buildingID);
			}
		}
	}

	@Override
	public void unapply(House house) {
		for (int i = 0; i < buildingNames.length; ++i) {
			int buildingID = Building.TYPE.valueOf(buildingNames[i]).ordinal();
			for (int j = 0; j < holdingTypes.length; ++j) {
				house.disableBuilding(holdingTypes[j], buildingID);
			}
		}
	}

}


text:
package io.cattle.platform.docker.constants;

public class DockerIpAddressConstants {

    public static final String KIND_DOCKER = "docker";

}


text:
package org.apache.cassandra.db.compaction;

import java.nio.ByteBuffer;
import java.io.*;
import java.util.*;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;

import org.apache.cassandra.db.*;
import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
import org.apache.cassandra.io.sstable.*;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.io.sstable.format.SSTableWriter;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.io.util.RandomAccessReader;
import org.apache.cassandra.service.ActiveRepairService;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.JVMStabilityInspector;
import org.apache.cassandra.utils.OutputHandler;
import org.apache.cassandra.utils.UUIDGen;

public class Scrubber implements Closeable
{
    private final ColumnFamilyStore cfs;
    private final SSTableReader sstable;
    private final LifecycleTransaction transaction;
    private final File destination;
    private final boolean skipCorrupted;

    private final CompactionController controller;
    private final boolean isCommutative;
    private final boolean isIndex;
    private final boolean checkData;
    private final long expectedBloomFilterSize;

    private final RandomAccessReader dataFile;
    private final RandomAccessReader indexFile;
    private final ScrubInfo scrubInfo;
    private final RowIndexEntry.IndexSerializer rowIndexEntrySerializer;

    private final boolean isOffline;

    private SSTableReader newSstable;
    private SSTableReader newInOrderSstable;

    private int goodRows;
    private int badRows;
    private int emptyRows;

    private ByteBuffer currentIndexKey;
    private ByteBuffer nextIndexKey;
    long currentRowPositionFromIndex;
    long nextRowPositionFromIndex;

    private final OutputHandler outputHandler;

    private static final Comparator<Row> rowComparator = new Comparator<Row>()
    {
         public int compare(Row r1, Row r2)
         {
             return r1.key.compareTo(r2.key);
         }
    };
    private final SortedSet<Row> outOfOrderRows = new TreeSet<>(rowComparator);

    public Scrubber(ColumnFamilyStore cfs, LifecycleTransaction transaction, boolean skipCorrupted, boolean isOffline, boolean checkData) throws IOException
    {
        this(cfs, transaction, skipCorrupted, new OutputHandler.LogOutput(), isOffline, checkData);
    }

    @SuppressWarnings("resource")
    public Scrubber(ColumnFamilyStore cfs, LifecycleTransaction transaction, boolean skipCorrupted, OutputHandler outputHandler, boolean isOffline, boolean checkData) throws IOException
    {
        this.cfs = cfs;
        this.transaction = transaction;
        this.sstable = transaction.onlyOne();
        this.outputHandler = outputHandler;
        this.skipCorrupted = skipCorrupted;
        this.isOffline = isOffline;
        this.rowIndexEntrySerializer = sstable.descriptor.version.getSSTableFormat().getIndexSerializer(sstable.metadata);

        List<SSTableReader> toScrub = Collections.singletonList(sstable);

        // Calculate the expected compacted filesize
        this.destination = cfs.directories.getWriteableLocationAsFile(cfs.getExpectedCompactedFileSize(toScrub, OperationType.SCRUB));
        if (destination == null)
            throw new IOException("disk full");

        // If we run scrub offline, we should never purge tombstone, as we cannot know if other sstable have data that the tombstone deletes.
        this.controller = isOffline
                        ? new ScrubController(cfs)
                        : new CompactionController(cfs, Collections.singleton(sstable), CompactionManager.getDefaultGcBefore(cfs));
        this.isCommutative = cfs.metadata.isCounter();

        boolean hasIndexFile = (new File(sstable.descriptor.filenameFor(Component.PRIMARY_INDEX))).exists();
        this.isIndex = cfs.isIndex();
        if (!hasIndexFile)
        {
            // if there's any corruption in the -Data.db then rows can't be skipped over. but it's worth a shot.
            outputHandler.warn("Missing component: " + sstable.descriptor.filenameFor(Component.PRIMARY_INDEX));
        }
        this.checkData = checkData && !this.isIndex; //LocalByPartitionerType does not support validation
        this.expectedBloomFilterSize = Math.max(
            cfs.metadata.getMinIndexInterval(),
            hasIndexFile ? SSTableReader.getApproximateKeyCount(toScrub) : 0);

        // loop through each row, deserializing to check for damage.
        // we'll also loop through the index at the same time, using the position from the index to recover if the
        // row header (key or data size) is corrupt. (This means our position in the index file will be one row
        // "ahead" of the data file.)
        this.dataFile = isOffline
                        ? sstable.openDataReader()
                        : sstable.openDataReader(CompactionManager.instance.getRateLimiter());

        this.indexFile = hasIndexFile
                ? RandomAccessReader.open(new File(sstable.descriptor.filenameFor(Component.PRIMARY_INDEX)))
                : null;

        this.scrubInfo = new ScrubInfo(dataFile, sstable);

        this.currentRowPositionFromIndex = 0;
        this.nextRowPositionFromIndex = 0;
    }

    public void scrub()
    {
        outputHandler.output(String.format("Scrubbing %s (%s bytes)", sstable, dataFile.length()));
        try (SSTableRewriter writer = new SSTableRewriter(cfs, transaction, sstable.maxDataAge, isOffline))
        {
            nextIndexKey = indexAvailable() ? ByteBufferUtil.readWithShortLength(indexFile) : null;
            if (indexAvailable())
            {
                // throw away variable so we don't have a side effect in the assert
                long firstRowPositionFromIndex = rowIndexEntrySerializer.deserialize(indexFile, sstable.descriptor.version).position;
                assert firstRowPositionFromIndex == 0 : firstRowPositionFromIndex;
            }

            writer.switchWriter(CompactionManager.createWriter(cfs, destination, expectedBloomFilterSize, sstable.getSSTableMetadata().repairedAt, sstable));

            DecoratedKey prevKey = null;

            while (!dataFile.isEOF())
            {
                if (scrubInfo.isStopRequested())
                    throw new CompactionInterruptedException(scrubInfo.getCompactionInfo());

                updateIndexKey();

                if (prevKey != null && indexFile != null)
                {
                    long nextRowStart = currentRowPositionFromIndex == -1 ? dataFile.length() : currentRowPositionFromIndex;
                    if (dataFile.getFilePointer() < nextRowStart)
                    {
                        // Encountered CASSANDRA-10791. Place post-END_OF_ROW data in the out-of-order table.
                        saveOutOfOrderRow(prevKey,
                                          SSTableIdentityIterator.createFragmentIterator(sstable, dataFile, prevKey, nextRowStart - dataFile.getFilePointer(), checkData),
                                          String.format("Row fragment detected after END_OF_ROW at key %s", prevKey));
                        if (dataFile.isEOF())
                            break;
                    }
                }

                long rowStart = dataFile.getFilePointer();
                outputHandler.debug("Reading row at " + rowStart);

                DecoratedKey key = null;
                try
                {
                    key = sstable.partitioner.decorateKey(ByteBufferUtil.readWithShortLength(dataFile));
                }
                catch (Throwable th)
                {
                    throwIfFatal(th);
                    // check for null key below
                }

                long dataStart = dataFile.getFilePointer();

                long dataStartFromIndex = -1;
                long dataSizeFromIndex = -1;
                if (currentIndexKey != null)
                {
                    dataStartFromIndex = currentRowPositionFromIndex + 2 + currentIndexKey.remaining();
                    dataSizeFromIndex = nextRowPositionFromIndex - dataStartFromIndex;
                }

                // avoid an NPE if key is null
                String keyName = key == null ? "(unreadable key)" : ByteBufferUtil.bytesToHex(key.getKey());
                outputHandler.debug(String.format("row %s is %s bytes", keyName, dataSizeFromIndex));

                assert currentIndexKey != null || !indexAvailable();

                try
                {
                    if (key == null)
                        throw new IOError(new IOException("Unable to read row key from data file"));

                    if (currentIndexKey != null && !key.getKey().equals(currentIndexKey))
                    {
                        throw new IOError(new IOException(String.format("Key from data file (%s) does not match key from index file (%s)",
                                ByteBufferUtil.bytesToHex(key.getKey()), ByteBufferUtil.bytesToHex(currentIndexKey))));
                    }

                    if (indexFile != null && dataSizeFromIndex > dataFile.length())
                        throw new IOError(new IOException("Impossible row size (greater than file length): " + dataSizeFromIndex));

                    if (indexFile != null && dataStart != dataStartFromIndex)
                        outputHandler.warn(String.format("Data file row position %d differs from index file row position %d", dataStart, dataStartFromIndex));

                    SSTableIdentityIterator atoms = new SSTableIdentityIterator(sstable, dataFile, key, checkData);

                    if (prevKey != null && prevKey.compareTo(key) > 0)
                    {
                        saveOutOfOrderRow(prevKey, key, atoms);
                        continue;
                    }

                    @SuppressWarnings("resource")
                    AbstractCompactedRow compactedRow = new LazilyCompactedRow(controller, Collections.singletonList(atoms));
                    if (writer.tryAppend(compactedRow) == null)
                        emptyRows++;
                    else
                        goodRows++;

                    prevKey = key;
                }
                catch (Throwable th)
                {
                    throwIfFatal(th);
                    outputHandler.warn("Error reading row (stacktrace follows):", th);

                    if (currentIndexKey != null
                        && (key == null || !key.getKey().equals(currentIndexKey) || dataStart != dataStartFromIndex))
                    {
                        outputHandler.output(String.format("Retrying from row index; data is %s bytes starting at %s",
                                                  dataSizeFromIndex, dataStartFromIndex));
                        key = sstable.partitioner.decorateKey(currentIndexKey);
                        try
                        {
                            dataFile.seek(dataStartFromIndex);

                            SSTableIdentityIterator atoms = new SSTableIdentityIterator(sstable, dataFile, key, checkData);
                            if (prevKey != null && prevKey.compareTo(key) > 0)
                            {
                                saveOutOfOrderRow(prevKey, key, atoms);
                                continue;
                            }

                            @SuppressWarnings("resource")
                            AbstractCompactedRow compactedRow = new LazilyCompactedRow(controller, Collections.singletonList(atoms));
                            if (writer.tryAppend(compactedRow) == null)
                                emptyRows++;
                            else
                                goodRows++;

                            prevKey = key;
                        }
                        catch (Throwable th2)
                        {
                            throwIfFatal(th2);
                            throwIfCannotContinue(key, th2);

                            outputHandler.warn("Retry failed too. Skipping to next row (retry's stacktrace follows)", th2);
                            badRows++;
                            seekToNextRow();
                        }
                    }
                    else
                    {
                        throwIfCannotContinue(key, th);

                        outputHandler.warn("Row starting at position " + dataStart + " is unreadable; skipping to next");
                        badRows++;
                        if (currentIndexKey != null)
                            seekToNextRow();
                    }
                }
            }

            if (!outOfOrderRows.isEmpty())
            {
                // out of order rows, but no bad rows found - we can keep our repairedAt time
                long repairedAt = badRows > 0 ? ActiveRepairService.UNREPAIRED_SSTABLE : sstable.getSSTableMetadata().repairedAt;
                try (SSTableWriter inOrderWriter = CompactionManager.createWriter(cfs, destination, expectedBloomFilterSize, repairedAt, sstable);)
                {
                    for (Row row : outOfOrderRows)
                        inOrderWriter.append(row.key, row.cf);
                    newInOrderSstable = inOrderWriter.finish(-1, sstable.maxDataAge, true);
                }
                transaction.update(newInOrderSstable, false);
                outputHandler.warn(String.format("%d out of order rows found while scrubbing %s; Those have been written (in order) to a new sstable (%s)", outOfOrderRows.size(), sstable, newInOrderSstable));
            }

            // finish obsoletes the old sstable
            List<SSTableReader> finished = writer.setRepairedAt(badRows > 0 ? ActiveRepairService.UNREPAIRED_SSTABLE : sstable.getSSTableMetadata().repairedAt).finish();
            if (!finished.isEmpty())
                newSstable = finished.get(0);
        }
        catch (IOException e)
        {
            throw Throwables.propagate(e);
        }
        finally
        {
            controller.close();
        }

        if (newSstable == null)
        {
            if (badRows > 0)
                outputHandler.warn("No valid rows found while scrubbing " + sstable + "; it is marked for deletion now. If you want to attempt manual recovery, you can find a copy in the pre-scrub snapshot");
            else
                outputHandler.output("Scrub of " + sstable + " complete; looks like all " + emptyRows + " rows were tombstoned");
        }
        else
        {
            outputHandler.output("Scrub of " + sstable + " complete: " + goodRows + " rows in new sstable and " + emptyRows + " empty (tombstoned) rows dropped");
            if (badRows > 0)
                outputHandler.warn("Unable to recover " + badRows + " rows that were skipped.  You can attempt manual recovery from the pre-scrub snapshot.  You can also run nodetool repair to transfer the data from a healthy replica, if any");
        }
    }

    private void updateIndexKey()
    {
        currentIndexKey = nextIndexKey;
        currentRowPositionFromIndex = nextRowPositionFromIndex;
        try
        {
            nextIndexKey = !indexAvailable() ? null : ByteBufferUtil.readWithShortLength(indexFile);

            nextRowPositionFromIndex = !indexAvailable()
                    ? dataFile.length()
                    : rowIndexEntrySerializer.deserialize(indexFile, sstable.descriptor.version).position;
        }
        catch (Throwable th)
        {
            JVMStabilityInspector.inspectThrowable(th);
            outputHandler.warn("Error reading index file", th);
            nextIndexKey = null;
            nextRowPositionFromIndex = dataFile.length();
        }
    }

    private boolean indexAvailable()
    {
        return indexFile != null && !indexFile.isEOF();
    }

    private void seekToNextRow()
    {
        while(nextRowPositionFromIndex < dataFile.length())
        {
            try
            {
                dataFile.seek(nextRowPositionFromIndex);
                return;
            }
            catch (Throwable th)
            {
                throwIfFatal(th);
                outputHandler.warn(String.format("Failed to seek to next row position %d", nextRowPositionFromIndex), th);
                badRows++;
            }

            updateIndexKey();
        }
    }

    private void saveOutOfOrderRow(DecoratedKey prevKey, DecoratedKey key, SSTableIdentityIterator atoms)
    {
        saveOutOfOrderRow(key, atoms, String.format("Out of order row detected (%s found after %s)", key, prevKey));
    }

    void saveOutOfOrderRow(DecoratedKey key, SSTableIdentityIterator atoms, String message)
    {
        // TODO bitch if the row is too large?  if it is there's not much we can do ...
        outputHandler.warn(message);
        // adding atoms in sorted order is worst-case for TMBSC, but we shouldn't need to do this very often
        // and there's no sense in failing on mis-sorted cells when a TreeMap could safe us
        ColumnFamily cf = atoms.getColumnFamily().cloneMeShallow(ArrayBackedSortedColumns.factory, false);
        while (atoms.hasNext())
        {
            OnDiskAtom atom = atoms.next();
            cf.addAtom(atom);
        }
        outOfOrderRows.add(new Row(key, cf));
    }

    public SSTableReader getNewSSTable()
    {
        return newSstable;
    }

    public SSTableReader getNewInOrderSSTable()
    {
        return newInOrderSstable;
    }

    private void throwIfFatal(Throwable th)
    {
        if (th instanceof Error && !(th instanceof AssertionError || th instanceof IOError))
            throw (Error) th;
    }

    private void throwIfCannotContinue(DecoratedKey key, Throwable th)
    {
        if (isIndex)
        {
            outputHandler.warn(String.format("An error occurred while scrubbing the row with key '%s' for an index table. " +
                                             "Scrubbing will abort for this table and the index will be rebuilt.", key));
            throw new IOError(th);
        }

        if (isCommutative && !skipCorrupted)
        {
            outputHandler.warn(String.format("An error occurred while scrubbing the row with key '%s'.  Skipping corrupt " +
                                             "rows in counter tables will result in undercounts for the affected " +
                                             "counters (see CASSANDRA-2759 for more details), so by default the scrub will " +
                                             "stop at this point.  If you would like to skip the row anyway and continue " +
                                             "scrubbing, re-run the scrub with the --skip-corrupted option.", key));
            throw new IOError(th);
        }
    }

    public void close()
    {
        FileUtils.closeQuietly(dataFile);
        FileUtils.closeQuietly(indexFile);
    }

    public CompactionInfo.Holder getScrubInfo()
    {
        return scrubInfo;
    }

    private static class ScrubInfo extends CompactionInfo.Holder
    {
        private final RandomAccessReader dataFile;
        private final SSTableReader sstable;
        private final UUID scrubCompactionId;

        public ScrubInfo(RandomAccessReader dataFile, SSTableReader sstable)
        {
            this.dataFile = dataFile;
            this.sstable = sstable;
            scrubCompactionId = UUIDGen.getTimeUUID();
        }

        public CompactionInfo getCompactionInfo()
        {
            try
            {
                return new CompactionInfo(sstable.metadata,
                                          OperationType.SCRUB,
                                          dataFile.getFilePointer(),
                                          dataFile.length(),
                                          scrubCompactionId);
            }
            catch (Exception e)
            {
                throw new RuntimeException();
            }
        }
    }

    private static class ScrubController extends CompactionController
    {
        public ScrubController(ColumnFamilyStore cfs)
        {
            super(cfs, Integer.MAX_VALUE);
        }

        @Override
        public long maxPurgeableTimestamp(DecoratedKey key)
        {
            return Long.MIN_VALUE;
        }
    }

    @VisibleForTesting
    public ScrubResult scrubWithResult()
    {
        scrub();
        return new ScrubResult(this);
    }

    public static final class ScrubResult
    {
        public final int goodRows;
        public final int badRows;
        public final int emptyRows;

        public ScrubResult(Scrubber scrubber)
        {
            this.goodRows = scrubber.goodRows;
            this.badRows = scrubber.badRows;
            this.emptyRows = scrubber.emptyRows;
        }
    }
}


text:
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as chat from '../actions/chat-actions.js';
import * as ui from '../actions/ui-actions.js';
import PanelPage from '../components/_shared/Panel-Page/Panel-Page-component.js';

function mapStateToProps(state) {
  return {
    list: state.chat.messages,
    icon: state.chat.icon,
    panelMessage: state.chat.panelMessageArray[state.chat.panelMessagePlayIndex] || 'Your current active chat',
    panelMessageArray: state.chat.panelMessageArray,
    selected: state.chat.activeRepoId,
    uiSelected: state.ui.selected,
    currentUi: 'chat',
    activeUi: state.ui.activeUi
  };
	}

function mapDispatchToProps(dispatch) {
  return {
    toggleComponent: bindActionCreators(ui.toggleComponent, dispatch),
  }
}

// function mapDispatchToProps(dispatch) {
//   return {
//     changeSelected: bindActionCreators(chat.changeActiveRepo, dispatch),
//     addSelected: bindActionCreators(chat.addChannel, dispatch),
//     removeSelected: bindActionCreators(chat.removeChannel, dispatch),
//     getList: bindActionCreators(chat.getUserRepos, dispatch)
//   }
// }

export default connect(mapStateToProps, mapDispatchToProps)(PanelPage)
// export default connect(mapStateToProps, mapDispatchToProps)(PanelPage)


text:
[% SET config_hspw = env.RAILO_WEB_ADMIN_PASSWORD_HSPW %]
[% SET config_salt = env.RAILO_WEB_ADMIN_PASSWORD_SALT %]

[% MACRO mysql_datasource BLOCK %]
<data-source blob="false" class="org.gjt.mm.mysql.Driver" clob="false" connectionLimit="-1" connectionTimeout="1" custom="characterEncoding=UTF-8&autoReconnect=true&useUnicode=true&allowMultiQueries=true" database="[% database %]" dsn="jdbc:mysql://{host}:{port}/{database}" host="mysql" metaCacheTimeout="60000" name="[% dsn_name %]" password="[% password %]" port="3306" storage="false" username="[% username %]" validate="false"/>
[% END %]

[% datasources = BLOCK %]
[% mysql_datasource( dsn_name='ourdb', database=env.DSN_OURDB_DATABASE, username=env.DSN_OURDB_USERNAME, password=env.DSN_OURDB_PASSWORD ) %]
[% mysql_datasource( dsn_name='theirdb', database=env.DSN_THEIRDB_DATABASE, username=env.DSN_THEIRDB_USERNAME, password=env.DSN_THEIRDB_PASSWORD ) %]
[% END %]

[% mail = BLOCK %]
<server password="" port="25" smtp="mail" ssl="false" tls="false" username=""/>
[% END %]

[% directory_mappings = BLOCK %]
<mapping physical="{railo-web}/components/lib" primary="physical" toplevel="true" trusted="false" virtual="/lib"/>
[% END %]

[% regional = BLOCK %]
<regional locale="[% env.RAILO_LOCALE %]" timezone="[% env.TZ %]"/>
[% END %]

[% PROCESS templates/railo_web.xml.cfm %]


text:
package fr.lteconsulting.hexa.client.tools;

public interface Action
{
	void exec();
}