text:
import React, { PureComponent } from 'react'
import onClickOutside from 'react-onclickoutside'
import styled, { css } from 'styled-components'
import moment from 'moment'

import styles, { fonts } from 'src/dashboard-refactor/styles'
import colors from 'src/dashboard-refactor/colors'

import { LoadingIndicator, ToggleSwitch } from 'src/common-ui/components'
import { Icon } from 'src/dashboard-refactor/styled-components'

import { DisableableState, RootState } from './types'
import { HoverState } from 'src/dashboard-refactor/types'
import { HoverBox } from 'src/common-ui/components/design-library/HoverBox'
import * as icons from 'src/common-ui/components/design-library/icons'
import Margin from 'src/dashboard-refactor/components/Margin'

const StyledHoverBox = styled(HoverBox)`
    height: min-content;
    width: 230px;
    padding: 15px;
    background-color: ${colors.white};
    flex-direction: column;
    box-shadow: ${styles.boxShadow.overlayElement};
`

const Row = styled(Margin)`
    height: min-content;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;

    &:last-child {
        margin-bottom: 0px;
    }
`

const RowContainer = styled.div`
    height: max-content;
    width: 100%;
    display: flex;
    flex-direction: column;
`

const NotificationBox = styled(RowContainer)`
    height: 40px;
    padding: 0 !important;
    justify-content: center;
    align-items: center;
    background-color: ${colors.error.pink};
    box-shadow: ${styles.boxShadow.overlayElement};
    border-radius: ${styles.borderRadius.medium};
`

const IconContainer = styled(Icon)<{
    disabled: boolean
}>`
    padding-right: 10px;
    ${(props) =>
        props.disabled &&
        css`
            opacity: 0.5;
        `}
    ${(props) =>
        !props.disabled &&
        css`
            cursor: pointer;
        `}

    &:hover {
        background-color: #e8e8e8;
    }
    border-radius: 3px;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 24px;
    width: 24px;
    background-size: 16px;
`

const textStyles = `
    font-family: ${fonts.primary.name};
    color: ${colors.fonts.primary};
`

const TextBlock = styled.div<{
    bold: boolean
}>`
    height: 18px;
    ${textStyles}
    font-size: 12px;
    line-height: 15px;
    display: flex;
    align-items: center;

    ${(props) =>
        css`
            font-weight: ${props.bold
                ? fonts.primary.weight.bold
                : fonts.primary.weight.normal};
        `}
`

const TextBlockSmall = styled.div`
    ${textStyles}
    font-weight: ${fonts.primary.weight.normal};
    font-size: 10px;
    line-height: 12px;
    text-align: center;
`

const StyledAnchor = styled.a`
    color: ${colors.fonts.secondary};
    text-decoration: none;
`

const AutoBackupBox = styled(Margin)`
    display: flex;
    justify-content: space-between;
`

const BackupReminderBox = styled(Margin)``

export const timeSinceNowToString = (date: Date | null): string => {
    if (date === null) {
        return 'Never'
    }

    const now = moment(new Date())
    const dt = moment(date)
    const seconds = now.diff(dt, 'seconds')
    const minutes = now.diff(dt, 'minutes')
    const hours = now.diff(dt, 'hours')
    const days = now.diff(dt, 'days')
    const years = now.diff(dt, 'years')

    if (seconds < 60) {
        return `${seconds} seconds ago`
    }
    if (minutes < 2) {
        return '1 min ago'
    }
    if (hours < 1) {
        return `${minutes} minutes ago`
    }
    if (hours < 2) {
        return `${hours} hours ago`
    }
    if (days < 1) {
        return `${hours} hours ago`
    }
    if (days < 2) {
        return 'One day ago'
    }
    if (days < 30) {
        return `${days} days ago`
    }
    if (years < 1) {
        return dt.format('MMM Do')
    }
    return dt.format('ll')
}

export interface SyncStatusMenuProps extends RootState {
    outsideClickIgnoreClass?: string
    goToSyncRoute: () => void
    goToBackupRoute: () => void
    onClickOutside: React.MouseEventHandler
    onInitiateSync: React.MouseEventHandler
    onInitiateBackup: React.MouseEventHandler
    onToggleAutoBackup: React.MouseEventHandler
    onToggleDisplayState: React.MouseEventHandler
    onShowUnsyncedItemCount: React.MouseEventHandler
    onHideUnsyncedItemCount: React.MouseEventHandler
}

type ServiceType = 'Sync' | 'Backup'

class SyncStatusMenu extends PureComponent<SyncStatusMenuProps> {
    handleClickOutside = this.props.onClickOutside

    private renderNotificationBox = (
        topSpanContent: JSX.Element | string,
        bottomSpanContent: JSX.Element | string,
    ) => {
        return (
            <Row>
                <NotificationBox>
                    <TextBlockSmall>{topSpanContent}</TextBlockSmall>
                    <TextBlockSmall>{bottomSpanContent}</TextBlockSmall>
                </NotificationBox>
            </Row>
        )
    }

    private renderBackupReminder = () => {
        return this.renderNotificationBox(
            'Memex stores all data locally.',
            'Backup your data.',
        )
    }

    private renderError = (
        serviceType: ServiceType,
        serviceStatus: DisableableState,
    ) => {
        if (serviceStatus !== 'error') {
            return null
        }

        return this.renderNotificationBox(
            `Your last ${serviceType.toLocaleLowerCase()} failed.`,
            <span>
                <StyledAnchor href="">Contact Support</StyledAnchor> if retry
                fails too.
            </span>,
        )
    }

    private renderRowTextBlock = (
        serviceType: ServiceType,
        serviceStatus: DisableableState,
        lastRunDate: Date | null,
    ) => {
        if (serviceStatus === 'disabled') {
            return serviceType === 'Sync'
                ? 'No device paired yet'
                : 'No backup set yet'
        }

        if (serviceStatus === 'running') {
            return 'In progress'
        }

        return (
            'Last ' +
            serviceType.toLocaleLowerCase() +
            ': ' +
            timeSinceNowToString(lastRunDate)
        )
    }

    private renderRow = (
        serviceType: ServiceType,
        serviceStatus: DisableableState,
        otherServiceStatus: DisableableState,
        lastRunDate: Date | null,
        clickHandler: React.MouseEventHandler,
    ) => {
        return (
            <>
                <Row bottom="10px">
                    <RowContainer>
                        <TextBlock bold>{`${serviceType} Status`}</TextBlock>
                        <TextBlock>
                            {this.renderRowTextBlock(
                                serviceType,
                                serviceStatus,
                                lastRunDate,
                            )}
                        </TextBlock>
                    </RowContainer>
                    {serviceStatus === 'running' ? (
                        <LoadingIndicator />
                    ) : (
                        <IconContainer
                            path={
                                serviceStatus === 'disabled'
                                    ? icons.arrowRight
                                    : icons.reload
                            }
                            disabled={otherServiceStatus === 'running'}
                            onClick={clickHandler}
                            heightAndWidth="15px"
                        />
                    )}
                </Row>
                {this.renderError(serviceType, serviceStatus)}
            </>
        )
    }

    render() {
        const {
            syncState,
            backupState,
            isDisplayed,
            onInitiateSync,
            goToSyncRoute,
            goToBackupRoute,
            onInitiateBackup,
            lastSuccessfulSyncDate,
            lastSuccessfulBackupDate,
        } = this.props

        if (!isDisplayed) {
            return null
        }

        console.log(this.props)

        return (
            <StyledHoverBox width="min-content" right="50px" top="45px">
                {this.renderRow(
                    'Sync',
                    syncState,
                    backupState,
                    lastSuccessfulSyncDate,
                    syncState === 'disabled' ? goToSyncRoute : onInitiateSync,
                )}
                {this.renderRow(
                    'Backup',
                    backupState,
                    syncState,
                    lastSuccessfulBackupDate,
                    backupState === 'disabled'
                        ? goToBackupRoute
                        : onInitiateBackup,
                )}
                <AutoBackupBox>
                    <TextBlock bold>Auto Backup</TextBlock>
                    <ToggleSwitch
                        isChecked={this.props.isAutoBackupEnabled}
                        onChange={
                            !lastSuccessfulBackupDate
                                ? this.props.goToBackupRoute
                                : this.props.onToggleAutoBackup
                        }
                    />
                </AutoBackupBox>
                {backupState === 'disabled' && (
                    <BackupReminderBox top="10px">
                        {this.renderBackupReminder()}
                    </BackupReminderBox>
                )}
            </StyledHoverBox>
        )
    }
}

export default onClickOutside(SyncStatusMenu)


text:
set -o errexit
set -o nounset
set -o pipefail

# keep in sync with hack/update-toc.sh
TOOL_VERSION=b8c54a57d69f29386d055584e595f38d65ce2a1f

# cd to the root path
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
cd "${ROOT}"

# create a temporary directory
TMP_DIR=$(mktemp -d)

# cleanup
exitHandler() (
  echo "Cleaning up..."
  rm -rf "${TMP_DIR}"
)
trap exitHandler EXIT

# perform go install in a temp dir as we are not tracking this version in a go module
# if we do the go install in the repo, it will create / update a go.mod and go.sum
cd "${TMP_DIR}"
GO111MODULE=on GOBIN="${TMP_DIR}" go install "sigs.k8s.io/mdtoc@${TOOL_VERSION}"
export PATH="${TMP_DIR}:${PATH}"
cd "${ROOT}"

echo "Checking table of contents are up to date..."
# Verify tables of contents are up-to-date
find keps -name '*.md' \
    | grep -Fxvf hack/.notableofcontents \
    | xargs mdtoc --inplace --max-depth=5 --dryrun || (
      echo "Table of content not up to date. If this failed silently and you are on mac, try 'brew install grep'"
      exit 1
    )

redpajama_set_name: RedPajamaGithub


text: require 'sensu-plugins-request-tracker/version'


text:
namespace _05_RetrieveImagesFromNorthwind
{
    using System;
    using System.Data.SqlClient;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;

    public class Program
    {
        private static string path = @"Images_From_DB_Northwind";

        public static void Main()
        {
            CreateDirectoryForImagesSave();

            //The images will be placed in the bin directory of the project
            ExtractImageFromDB();
        }

        private static void CreateDirectoryForImagesSave()
        {
            try
            {
                // Delete directory whether the directory exists.
                if (Directory.Exists(path))
                {
                    Directory.Delete(path, true);
                }

                // Try to create the directory.
                DirectoryInfo di = Directory.CreateDirectory(path);
                Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));
            }
            catch (Exception e)
            {
                Console.WriteLine("The process failed: {0}", e.ToString());
            }
        }

        public static void ExtractImageFromDB()
        {
            SqlConnection dbConn = new SqlConnection("Server=.; " + "Database=Northwind; Integrated Security=true");
            dbConn.Open();

            using (dbConn)
            {
                SqlCommand cmd = new SqlCommand(
                    "SELECT PICTURE, CategoryID, CategoryName FROM Categories", dbConn);

                SqlDataReader reader = cmd.ExecuteReader();

                using (reader)
                {
                    while (reader.Read())
                    {
                        byte[] rawData = (byte[])reader["Picture"];
                        string fileName = reader["CategoryName"].ToString().Replace('/', '_') + ".jpg";
                        int len = rawData.Length;
                        int header = 78;
                        byte[] imgData = new byte[len - header];
                        Array.Copy(rawData, 78, imgData, 0, len - header);

                        MemoryStream memoryStream = new MemoryStream(imgData);
                        Image image = System.Drawing.Image.FromStream(memoryStream);
                        image.Save(new FileStream(path + "/" + fileName, FileMode.Create), ImageFormat.Jpeg);
                    }

                }
            }
        }
    }
}


text:
'use strict';

var _ = require('lodash');

function claimBadge (args, callback) {
  var seneca = this;
  var plugin = args.role;
  var options = seneca.export('options');
  if (!args.badge) return callback(null, { error: 'Invalid request. No badge received.' });
  var badge = args.badge;
  var requestingUser = args.user;
  var claimCodePrefix = options.claimCodePrefix;

  badge.status = 'accepted';
  badge.dateAccepted = new Date();

  // Remove code tag from badge tags so it doesn't show up on user profile page.
  // TODO - this is not good _ usage, needs to be refactored!!
  var indexFound;
  _.find(badge.tags, function (tag, index) {
    indexFound = index;
    return _.contains(tag.value, claimCodePrefix);
  });
  badge.tags.splice(indexFound, 1);

  seneca.act({role: 'cd-profiles', cmd: 'list', query: {userId: requestingUser.id}}, function (err, response) {
    if (err) return callback(err);
    seneca.act({role: plugin, cmd: 'addBadgeToProfile', profile: response[0], badge: badge}, function (err, response) {
      if (err) return callback(err);
      if (response.error) return callback(null, {error: response.error});
      return callback(null, response);
    });
  });
}

module.exports = claimBadge;


text:
package org.hawkular.metrics.tasks.impl;

import java.util.Objects;

import org.joda.time.DateTime;

/**
 * Tasks are associated with a lease. Clients must acquire a lease before they can start executing tasks associated
 * with it; however, leases are not directly exposed to clients. The actions of acquiring, renewing, and finishing a
 * lease are handled internally allowing clients to focus on their tasks.
 *
 * @author jsanda
 */
class Lease {

    public static final Lease NOT_ACQUIRED = new Lease(null, null, 0, null, false);

    private DateTime timeSlice;

    private String taskType;

    private int segmentOffset;

    private String owner;

    private boolean finished;

    public Lease(DateTime timeSlice, String taskType, int segmentOffset, String owner, boolean finished) {
        this.timeSlice = timeSlice;
        this.taskType = taskType;
        this.segmentOffset = segmentOffset;
        this.owner = owner;
        this.finished = finished;
    }

    /**
     * The time slice for which the lease has been allocated. For example, if a client schedules a task to aggregate
     * data every hour and if the current time is 13:33, then a lease will be created and persisted for 14:00.
     */
    public DateTime getTimeSlice() {
        return timeSlice;
    }

    /**
     *
     * @return The {@link org.hawkular.metrics.tasks.api.TaskType task type} name
     */
    public String getTaskType() {
        return taskType;
    }

    /**
     * Specifies how many tasks in terms of segments are associated with this lease. Suppose there are 100 segments and
     * use a segment offset size of 10. There will be 10 task segments per lease. When a client acquires this lease,
     * all tasks in each of the 10 segments assigned to this lease will be executed.
     */
    public int getSegmentOffset() {
        return segmentOffset;
    }

    /**
     * The current lease owner or null if there is no owner.
     */
    public String getOwner() {
        return owner;
    }

    public Lease setOwner(String owner) {
        this.owner = owner;
        return this;
    }

    /**
     * @return True if all tasks associated with the lease are finished, false otherwise.
     */
    public boolean isFinished() {
        return finished;
    }

    public Lease setFinished(boolean finished) {
        this.finished = finished;
        return this;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Lease lease = (Lease) o;
        return Objects.equals(segmentOffset, lease.segmentOffset) &&
                Objects.equals(finished, lease.finished) &&
                Objects.equals(timeSlice, lease.timeSlice) &&
                Objects.equals(taskType, lease.taskType) &&
                Objects.equals(owner, lease.owner);
    }

    @Override
    public int hashCode() {
        return Objects.hash(timeSlice, taskType, segmentOffset, owner, finished);
    }

    @Override
    public String toString() {
        return com.google.common.base.Objects.toStringHelper(this)
                .add("timeSlice", timeSlice)
                .add("taskType", taskType)
                .add("segmentOffset", segmentOffset)
                .add("owner", owner)
                .add("finished", finished)
                .toString();
    }
}


text:
"""
actor - defines the actor top state 'ActorTopState'.

Actors, within the hsm library, are an implementation of hierarchical state.

Actors support the following features:
- *State Inheritance*
- *Hierarchical transitions*, with automatic _entry()/_exit()
- *Automatic protocol implementation*, to define an event just define an on_xxx
  method.

"""

import types
import traceback
from runtime_queue import actor_message_queue
import logging

__all__ = ["TopState", "initial_state", "error_state", "trace_state", "MissingInitialStateError", "NotAStateError", "ErrorState"]

def create_msg_sender(handler_name):
    def post_msg(*args, **kwargs):
        actor_message_queue.append((handler_name, args, kwargs))
    return post_msg

def create_except_receiver(fun, handler_name):
    def receive_msg(*args, **kwargs):
        msg_name = handler_name
        try:
            fun(*args, **kwargs)
        except Exception, ex:
            pass
    return receive_msg

def create_msg_receiver(fun, handler_name):
    def receive_msg(*args, **kwargs):
        msg_name = handler_name
        fun(*args, **kwargs)
    return receive_msg

def create_trace_enter(method, logger):
    assert logger is not None

    def tracing_execute(*args, **kwargs):
        logger.debug("%s: about to enter %s", id(args[0]), args[0].__class__.__name__)
        return method(*args, **kwargs)
    return tracing_execute

def create_trace_exit(method, logger):
    def tracing_execute(*args, **kwargs):
        logger.debug("%s: about to exit %s", id(args[0]), args[0].__class__.__name__)
        return method(*args, **kwargs)
    return tracing_execute

def create_trace_sender(method, logger):
    def tracing_execute(*args, **kwargs):
        name = method.func_closure[0].cell_contents
        logger.debug("%s: about to send msg ('%s' %s %s)", id(args[0]), name,args, kwargs)
        return method(*args, **kwargs)
    return tracing_execute

def create_trace_receiver(method, logger):
    def tracing_execute(*args, **kwargs):
        name = method.func_closure[1].cell_contents
        logger.debug("%s: about to receive msg %s %s %s", id(args[0]), name,args, kwargs)
        return method(*args, **kwargs)
    return tracing_execute

def create_trace_transition(logger):
    def tracing_execute(*args):
        return args[0].transition()(args[1])
    return tracing_execute

def add_tracing(cls, logger):
    if logger is not None:
        for (method_name, method) in cls.__dict__.items():
            if method_name.startswith("send_"):
                setattr(cls, method_name, create_trace_sender(method, logger))
                continue
            if method_name.startswith("on_"):
                setattr(cls, method_name, create_trace_receiver(method, logger))
                continue
            if method_name.startswith("_enter"):
                setattr(cls, method_name, create_trace_enter(method, logger))
                continue
            if method_name.startswith("_exit"):
                setattr(cls, method_name, create_trace_exit(method, logger))
                continue

class MissingInitialStateError(Exception):
    def __init__(self, state):
        self._state = state

    def __str__(self):
        return "%s is missing the initial state. Use @initialState to mark the initial state" % (self._state.__name__)

class NotAStateError(Exception):
    def __init__(self, state):
        self._state = state

    def __str__(self):
        return "@initial_state can only by applied to a child class of TopState. '%s' doesn't inherit from " \
               "hsm.actor.TopState" % self._state.__name__

class ReservedNameError(Exception):
    def __init__(self, state):
        self._state = state

    def __str__(self):
        return """class '%s': %s the 'send_' prefix is reserved to send messages""" % self._state.__name__

class MultipleInheritanceNotSupportedError(Exception):
    def __init__(self, state):
        self._state = state

    def __str__(self):
        return """class '%s': multiple inheritance not supported""" % self._state.__name__

class MissingParentState(Exception):
    def __init__(self, state):
        self._state = state

    def __str__(self):
        return """class '%s': missing parent state""" % self._state.__name__

def empty_function(self):
    pass

def inheritMethod(cls, cls_dct, method_name):
    if method_name not in cls_dct:
        fun = getattr(TopState, method_name).__func__
        method = types.MethodType(fun, None, cls)
        cls_dct[method_name] = method

class state(type):
    def __new__(mcs, name, bases, dct):
        """
        :rtype : object
        :param name:
        :param bases:
        :param dct:
        :return:
        """
        return type.__new__(mcs, name, bases, dct)

    def __init__(cls, name, bases, dct):
        """

        :param name:
        :param bases:
        :param dct:
        :raise:
        """
        super(state, cls).__init__(name, bases, dct)
        if len(bases) == 0:
            raise MissingParentState(cls)
        if len(bases) > 1:
            raise MultipleInheritanceNotSupportedError(cls)

        setattr(cls, "__initial_state__", None)
        setattr(cls, "__error_state__", None)

        #add standard methods to all states
        if cls.__name__ != 'TopState':
            inheritMethod(cls, dct, '_exit',)
            inheritMethod(cls, dct, '_enter',)
            inheritMethod(cls, dct, 'transition',)
            inheritMethod(cls, dct, 'on_fini',)

        for (k, v) in dct.items():
            if k.startswith("send_"):
                raise ReservedNameError(name, cls)
            if k.startswith("on_"):
                sig = k[3:]
                send_method_name = "send_" + sig
                if sig == "except":
                    receiver = create_except_receiver(v, k)
                else:
                    receiver = create_msg_receiver(v, k)
                sender = create_msg_sender(k)
                setattr(cls, k, receiver)
                setattr(cls, send_method_name, sender)

        #Setup tracing
        parent_state = bases[0]
        parent_state_name = parent_state.__name__
        if parent_state_name != "object":
            logger = getattr(parent_state, '__trace_logger__')
            setattr(cls, "__trace_logger__", logger)
            add_tracing(cls, logger)
        else:
            setattr(cls, "__trace_logger__", None)
            pass

    def __call__(cls, *args, **kwargs):
        if cls.__initial_state__ == None:
            raise MissingInitialStateError(cls)
        instance = type.__call__(cls, *args, **kwargs)
        instance._enter()
        initial_state = cls.__initial_state__
        while initial_state is not None:
            instance.__class__ = initial_state
            instance._enter()
            initial_state = initial_state.__initial_state__
        instance._initial_state = cls
        return instance

class TopState(object):
    __metaclass__ = state

    def __init__(self):
        object.__init__(self)

    def _enter(self):
        pass

    def _exit(self):
        pass

    def get_state_name(self):
        """Returns the current state name"""
        return self.__class__.__name__

    def get_state(self):
        """Returns the current state"""
        return self.__class__

    def on_msg(self, sig, *args, **kwargs):
        """
        Dynamically send a msg to the runtime.
        """
        assert isinstance(sig, str)
        assert len(args) > 1
        self._actor_message_queue.append(("on_" + sig, (self,) + args, kwargs,))

    def on_fini(self):
        """Close the finite state machine by exiting up to the top use state"""
        while True:
            self._exit()
            parent_state = self.__class__.__bases__[0]
            if parent_state != TopState:
                self.__class__ = parent_state
                continue
            break

    def transition(self, state):
        """Executes a transition from the current state to state"""
        outState = self.__class__
        inState = state
        left = outState
        right = inState
        if left == right:
            return
        assert left != TopState
        assert right != TopState

        while left != TopState and right != left:
            left = left.__bases__[0]
            right = inState
            while right != TopState and right != left:
                right = right.__bases__[0]

        assert left == right

        #Execute Exits
        while self.__class__ != left:
            self._exit()
            self.__class__ = self.__class__.__bases__[0]

        ### Fix Start ....
        # Left = Right --> Lowest Common Ancestor
        assert self.__class__ == left
        if inState != self.__class__:
            head = inState.__bases__[0]
            enterTrail = []
            if head != TopState:
                while head != left:
                    enterTrail.append(head)
                    head = head.__bases__[0]

            while enterTrail:
                head = enterTrail.pop()
                self.__class__ = head
                self._enter()

            #Enter target state
            self.__class__ = inState
            self._enter()

        #Drill down
        cls = self.__class__
        next_state = cls.__initial_state__
        while next_state is not None:
            self.__class__ = next_state
            self._enter()
            next_state = next_state.__initial_state__

class ErrorState(TopState):
    def on_except(self, (exc_type, exc_value, exc_traceback )):
        tb = traceback.format_exception(exc_type, exc_value, exc_traceback)
        for trace in tb:
            self._log.error(trace)

def error_state(state):
    """
    State anotation. Marks the annotated state as the error state of the
    the parent state.
    :param state: the state to be annotated
    """
    parent = state.__bases__[0]
    if not issubclass(parent, TopState):
        raise NotAStateError(state)
    if parent != TopState:
        parent.__error_state__ = state
    return state

def initial_state(state):
    """
    State anotation.
    :param state: the state to be annotated

    Marks the annotated state as the initial state of the
    the parent state.
    """
    parent = state.__bases__[0]
    if not issubclass(parent, TopState):
        raise NotAStateError(state)
    if parent != TopState:
        parent.__initial_state__ = state
    return state

class trace_state:
    def __init__(self, logger=None):
        self._logger = logger

    def __call__(self, state):
        if self._logger is not None:
            setattr(state, '__trace_logger__', self._logger)
            add_tracing(state, self._logger)
            assert getattr(state, '__trace_logger__') is not None
        return state


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Welcome to AppBooking</title>
        <link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
        <link rel="stylesheet" href="css/vendors/bootstrap.min.css">
        <link rel="stylesheet" href="css/style.css">
        <link rel="stylesheet" href="css/home.css">
        <link rel="stylesheet" href="css/admin.css">

                    AppBooking

 {{'LOGOUT' | translate}}

            <form class="navbar-form admin-access">

Accès Administrateur

                    <input type="email" class="form-control" ng-model="user.email" placeholder="Email">

                    <input type="password" class="form-control" ng-model="user.password" placeholder="Password">

                <button type="submit" class="btn btn-default" ng-click="updateUser()">CHANGER</button>
            </form>

Design & Coding by Quentin THAI © 2014

Version beta 0.1.3

Last modified : 2014-11-19 01:37


text:
package org.apache.manifoldcf.core.util;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * Wrapper of {@link java.net.URLEncoder}
 * Intends to replace java.net.URLEncoder.encode(String s, "UTF-8")
 * avoiding {@link UnsupportedEncodingException} handling.
 * {@link StandardCharsets} are guaranteed to be available
 * on every implementation of the Java platform.
 *
 * @since 1.7
 */
public class URLEncoder {

  public static String encode(String s) {

    String str = null;

    try {
      str = java.net.URLEncoder.encode(s, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
      // Can't happen. java.nio.charset.StandardCharsets are guaranteed
      // to be available on every implementation of the Java platform.
      throw new RuntimeException("UTF-8 not supported " + e.getMessage(), e);
    }

    return str;
  }
}


text:
export ZPROJ_ROOT_DIR="${HOME}/projects"
export ZPROJ_MAX_DEPTH=2


text:
create table SEC_REMEMBER_ME (
    ID varchar(36) not null,
    CREATE_TS timestamp,
    CREATED_BY varchar(50),
    VERSION integer,
    --
    USER_ID varchar(36) not null,
    TOKEN varchar(32) not null,
    --
    primary key (ID),
    constraint FK_SEC_REMEMBER_ME_USER foreign key (USER_ID) references SEC_USER(ID)
)^


text:
Version 1.3 Released 08.06.2015
Added:
- not logged in users adding to cart,
- landline phone number in properties,

Bugfix:
- cart update
---------------------------------
Version 1.2 Released 05.02.2015
Added:
- configurable newsletter tags
---------------------------------
Version 1.1 Released 22.01.2015
Added:
- newsletter
Bugfix:
- removed php notify
--------------------------------
Version 1.0
PrestaShop integration
Bugfix:
- force optin after login deleted
- forceOptOut -> forceOptIn after second purchase
- @up removeTags
- block/newsletter - was modyfing default contact email


text:
package de.tu_berlin.dima.bdapro.flink.palindrome.rparrapy

import org.apache.flink.api.scala._

/**
  * Created by rparra on 19/10/16.
  */
object Palindrome {

  def main(args: Array[String]): Unit = {
    // set up the execution environment
    val env = ExecutionEnvironment.getExecutionEnvironment

    val lines = env.readTextFile(args(0))

    val result = lines.distinct
      .filter { x => x.nonEmpty && x.replaceAll("[^A-Za-z0-9]", "") == x.replaceAll("[^A-Za-z0-9]", "").reverse }
      .map { x => PalindromeResult(List(x)) }
      .reduce { (x, y) => x.combine(y) }
      .flatMap {
        _.palindromes.map { p => s"The biggest palindrome sentence: <$p>" }
      }

    result.print()
  }

}

case class PalindromeResult(val palindromes: List[String]) {
  def size() = palindromes.head.replaceAll("[^A-Za-z0-9]", "").size

  def combine(other: PalindromeResult): PalindromeResult = {
    if (this.size == other.size) PalindromeResult(this.palindromes ::: other.palindromes)
    else {
      if (this.size > other.size) this
      else other
    }
  }
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.collections;

/**
 * A pair of values.
 *
 * This class is to avoid littering a class with thin wrapper objects for
 * passing around e.g. the state of an operation and the result value. Using
 * this class may be correct, but it is a symptom that you may want to redesign
 * your code. (Should you pass mutable objects to the method instead? Create a
 * new class and do the work inside that class instead? Etc.)
 *
 * @author Steinar Knutsen
 */
public final class Tuple2<T1, T2> {

    public final T1 first;
    public final T2 second;

    public Tuple2(final T1 first, final T2 second) {
        this.first = first;
        this.second = second;
    }

    /**
     * hashCode() will always throw UnsupportedOperationException. The reason is
     * this class is not meant for being put in Container implementation or
     * similar use where Java generics will lead to a type unsafe maintenance
     * nightmare.
     *
     * @throws UnsupportedOperationException
     *             will always throw this when invoked
     */
    @Override
    public int hashCode() {
        throw new UnsupportedOperationException(
                "com.yahoo.collections.Tuple2<T1, T2> does not support equals(Object) by design. Refer to JavaDoc for details.");
    }

    /**
     * equals(Object) will always throw UnsupportedOperationException. The
     * intention is always using the objects contained in the tuple directly.
     *
     * @param obj
     *            ignored
     * @throws UnsupportedOperationException
     *             will always throw this when invoked
     */
    @Override
    public boolean equals(final Object obj) {
        throw new UnsupportedOperationException(
                "com.yahoo.collections.Tuple2<T1, T2> does not support equals(Object) by design. Refer to JavaDoc for details.");
    }

    /**
     * Human readable string representation which invokes the contained
     * instances' toString() implementation.
     */
    @Override
    public String toString() {
        return "Tuple2(" + first + ", " + second + ")";
    }
}


text:
@interface SampleTest : SenTestCase
@end

@implementation SampleTest

- (void)testDateIsOnASaturday
{
    // Example of a successful match.
    NSCalendarDate* date = [NSCalendarDate dateWithString:@"26 Apr 2008" calendarFormat:@"%d %b %Y"];
    assertThat(date, is(onASaturday()));
}

- (void)testFailsWithMismatchedDate
{
    // Example of what happens with date that doesn't match.
    NSCalendarDate* date = [NSCalendarDate dateWithString:@"06 Apr 2008" calendarFormat:@"%d %b %Y"];
    assertThat(date, is(onASaturday()));
}

- (void)testFailsWithNonDate
{
    // Example of what happens with object that isn't a date.
    NSString* nonDate = @"oops";
    assertThat(nonDate, is(onASaturday()));
}

@end


text:
@interface BeeUINavigationBar()
{
	BOOL						_inited;
	UILabel *					_titleLabel;
	UIImage *					_backgroundImage;
	UINavigationController *	_navigationController;
}

- (void)initSelf;
- (void)applyBarStyle;

@end

#pragma mark -

@implementation BeeUINavigationBar

DEF_NOTIFICATION( STYLE_CHANGED )

DEF_INT( LEFT,	0 )
DEF_INT( RIGHT,	1 )

DEF_SIGNAL( LEFT_TOUCHED )
DEF_SIGNAL( RIGHT_TOUCHED )

@dynamic backgroundImage;
@synthesize navigationController = _navigationController;

static UIColor *	__titleShadowColor = nil;
static UIColor *	__titleColor = nil;
static UIFont *		__titleFont = nil;
static CGSize		__buttonSize = { 44.0f, 44.0f };
static UIColor *	__buttonColor = nil;
static UIFont *		__buttonFont = nil;
static UIColor *	__backgroundTintColor = nil;
static UIColor *	__backgroundColor = nil;
static UIImage *	__backgroundImage = nil;

- (id)init
{
    self = [super initWithFrame:CGRectZero];
    if ( self )
	{
		[self initSelf];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if ( self )
	{
		[self initSelf];
    }
    return self;
}

- (void)initSelf
{
	if ( NO == _inited )
	{
		if ( IOS7_OR_LATER )
		{
			self.translucent = NO;
			self.shadowImage = [[UIImage new] autorelease];
		}

		[self observeNotification:self.STYLE_CHANGED];
		[self applyBarStyle];

		_inited = YES;

//		[self load];
		[self performLoad];
	}
}

- (void)dealloc
{
//	[self unload];
	[self performUnload];

	[self unobserveAllNotifications];

    [_backgroundImage release];
	_backgroundImage = nil;

	[_titleLabel removeFromSuperview];
	[_titleLabel release];
	_titleLabel = nil;

    [super dealloc];
}

- (void)setFrame:(CGRect)frame
{
	[super setFrame:frame];

	[self applyBarStyle];
}

- (void)layoutSubviews
{
    [super layoutSubviews];

	[self applyBarStyle];
}

- (void)applyBarStyle
{
	if ( __backgroundColor )
	{
		[self setBackgroundColor:__backgroundColor];
	}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
	if ( IOS7_OR_LATER )
	{
//        for ( id subview in self.subviews )
//		{
//            if ( [subview isKindOfClass:[UIImageView class]] )
//			{
//				UIImageView * imageView = subview;
//				imageView.layer.shadowColor = [UIColor clearColor].CGColor;
//				imageView.layer.shadowOffset = CGSizeZero;
//				imageView.layer.shadowOpacity = 0.0f;
//            }
//        }

		if ( __backgroundTintColor )
		{
			[self setTintColor:__backgroundTintColor];
			[self setBarTintColor:__backgroundTintColor];
		}
	}
#endif	// #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000

	if ( IOS6_OR_LATER )
	{
		NSMutableDictionary * attributes = [NSMutableDictionary dictionary];

		if ( __titleShadowColor )
		{
			[attributes setObject:__titleShadowColor forKey:UITextAttributeTextShadowColor];
		}

		if ( __titleColor )
		{
			[attributes setObject:__titleColor forKey:UITextAttributeTextColor];
		}

		if ( __titleFont )
		{
			[attributes setObject:__titleFont forKey:UITextAttributeFont];
		}

		if ( attributes.count )
		{
			[self setTitleTextAttributes:attributes];
		}
	}

	if ( IOS5_OR_LATER )
	{
		if ( IOS7_OR_LATER )
		{
		#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
			[self setBackgroundImage:(_backgroundImage ? _backgroundImage : __backgroundImage) forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
		#endif	// #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
		}
		else
		{
		#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 50000
			[self setBackgroundImage:(_backgroundImage ? _backgroundImage : __backgroundImage) forBarMetrics:UIBarMetricsDefault];
		#endif	// #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 50000
		}
	}

//	self.layer.shadowOpacity = 0.7f;
//	self.layer.shadowRadius = 1.5f;
//	self.layer.shadowOffset = CGSizeMake(0.0f, 0.6f);
//	self.layer.shadowColor = [UIColor blackColor].CGColor;
//	self.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
//	self.layer.shouldRasterize = YES;

//	CAShapeLayer * maskLayer = nil;
//
//	for ( CALayer * layer in self.layer.sublayers )
//	{
//		if ( [layer isKindOfClass:[CAShapeLayer class]] && [layer.name isEqualToString:@"maskLayer"] )
//		{
//			maskLayer = (CAShapeLayer *)layer;
//			break;
//		}
//	}
//
//	if ( nil == maskLayer )
//	{
//		maskLayer = [CAShapeLayer layer];
//		[self.layer addSublayer:maskLayer];
//		[self.layer setMask:maskLayer];
//	}
//
//	CGRect bounds = self.bounds;
//	UIBezierPath * maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds
//													byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight)
//														  cornerRadii:CGSizeMake(4.0, 4.0)];
//	if ( maskPath && maskLayer )
//	{
//		maskLayer.frame = bounds;
//		maskLayer.path = maskPath.CGPath;
//		maskLayer.name = @"maskLayer";
//	}

	[self setNeedsDisplay];
}

- (void)handleUISignal:(BeeUISignal *)signal
{
//	if ( _navigationController )
//	{
//		UIViewController * vc = _navigationController.topViewController;
//		if ( vc )
//		{
//			[signal forward:vc];
//		}
//	}
//	else
	{
		SIGNAL_FORWARD( signal );
	}
}

- (void)handleNotification:(NSNotification *)notification
{
	if ( [notification is:BeeUINavigationBar.STYLE_CHANGED] )
	{
		[self applyBarStyle];
	}
}

- (void)setBackgroundImage:(UIImage *)image
{
	if ( image != _backgroundImage )
	{
		[_backgroundImage release];
		_backgroundImage = [image retain];

		[self applyBarStyle];
	}
}

#pragma mark -

+ (void)setTitleColor:(UIColor *)color
{
	if ( color != __titleColor )
	{
		[__titleColor release];
		__titleColor = [color retain];

		[[NSNotificationCenter defaultCenter] postNotificationName:self.STYLE_CHANGED object:nil];
	}
}

+ (void)setTitleFont:(UIFont *)font
{
	if ( font != __titleFont )
	{
		[__titleFont release];
		__titleFont = [font retain];

		[[NSNotificationCenter defaultCenter] postNotificationName:self.STYLE_CHANGED object:nil];
	}
}

+ (void)setTitleShadowColor:(UIColor *)color
{
    if ( color != __titleShadowColor )
    {
        [__titleShadowColor release];
        __titleShadowColor = [color retain];

        [[NSNotificationCenter defaultCenter] postNotificationName:self.STYLE_CHANGED object:nil];
    }
}

+ (CGSize)buttonSize
{
	return __buttonSize;
}

+ (void)setButtonSize:(CGSize)size
{
	__buttonSize = size;
}

+ (UIColor *)buttonColor
{
	return __buttonColor;
}

+ (void)setButtonColor:(UIColor *)color
{
	if ( color != __buttonColor )
	{
		[__buttonColor release];
		__buttonColor = [color retain];

		[[NSNotificationCenter defaultCenter] postNotificationName:self.STYLE_CHANGED object:nil];
	}
}

+ (UIFont *)buttonFont
{
	return __buttonFont;
}

+ (void)setButtonFont:(UIFont *)font
{
	if ( font != __buttonFont )
	{
		[__buttonFont release];
		__buttonFont = [font retain];

		[[NSNotificationCenter defaultCenter] postNotificationName:self.STYLE_CHANGED object:nil];
	}
}

+ (void)setBackgroundColor:(UIColor *)color
{
	if ( color != __backgroundColor )
	{
		[__backgroundColor release];
		__backgroundColor = [color retain];

		[[NSNotificationCenter defaultCenter] postNotificationName:self.STYLE_CHANGED object:nil];
	}
}

+ (void)setBackgroundTintColor:(UIColor *)color
{
	if ( color != __backgroundTintColor )
	{
		[__backgroundTintColor release];
		__backgroundTintColor = [color retain];

		[[NSNotificationCenter defaultCenter] postNotificationName:self.STYLE_CHANGED object:nil];
	}
}

+ (void)setBackgroundImage:(UIImage *)image
{
	if ( image != __backgroundImage )
	{
		[__backgroundImage release];
		__backgroundImage = [image retain];

		[[NSNotificationCenter defaultCenter] postNotificationName:self.STYLE_CHANGED object:nil];
	}
}

@end

#endif	// #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)


text:
@interface NSURLCredential (TFEasyCoder)

//superclass pros NSObject
-(NSURLCredential  *(^)(NSArray *  accessibilityElements))set_accessibilityElements;
-(NSURLCredential  *(^)(NSArray *  accessibilityCustomActions))set_accessibilityCustomActions;
-(NSURLCredential  *(^)(BOOL  isAccessibilityElement))set_isAccessibilityElement;
-(NSURLCredential  *(^)(NSString *  accessibilityLabel))set_accessibilityLabel;
-(NSURLCredential  *(^)(NSString *  accessibilityHint))set_accessibilityHint;
-(NSURLCredential  *(^)(NSString *  accessibilityValue))set_accessibilityValue;
-(NSURLCredential  *(^)(unsigned long long  accessibilityTraits))set_accessibilityTraits;
-(NSURLCredential  *(^)(UIBezierPath *  accessibilityPath))set_accessibilityPath;
-(NSURLCredential  *(^)(CGPoint  accessibilityActivationPoint))set_accessibilityActivationPoint;
-(NSURLCredential  *(^)(NSString *  accessibilityLanguage))set_accessibilityLanguage;
-(NSURLCredential  *(^)(BOOL  accessibilityElementsHidden))set_accessibilityElementsHidden;
-(NSURLCredential  *(^)(BOOL  accessibilityViewIsModal))set_accessibilityViewIsModal;
-(NSURLCredential  *(^)(BOOL  shouldGroupAccessibilityChildren))set_shouldGroupAccessibilityChildren;
-(NSURLCredential  *(^)(long long  accessibilityNavigationStyle))set_accessibilityNavigationStyle;

@end


text:
//
// Author: Emin Ilker Cetinbas (niw3_at_yahoo_d0t_com)
// Copyright (C) 2005 Emin Ilker Cetinbas
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//

#ifndef LINEAR_MOBILITY_H
#define LINEAR_MOBILITY_H

#include "INETDefs.h"

#include "CustomMovingMobilityBase.h"

/**
 * @brief Linear movement model. See NED file for more info.
 *
 * @ingroup mobility
 * @author Emin Ilker Cetinbas
 */
class INET_API CustomLinearMobility : public CustomMovingMobilityBase
{

    private:
        //Se�al para emitir la aceleraci�n del l�der
        simsignal_t accelerationLeaderSignal;

   protected:
        double speed;          ///< speed of the host
        double angle;          ///< angle of linear motion
        double acceleration;   ///< acceleration of linear motion
        // configuration
        double currentSpeed; //Velocidad actual del host
        double totalTime; //Tiempo objetivo para llegar a la meta
        double totalDistance; //Distancia total para llegar a la meta
        double variability; //Variabilidad en la velocidad objetivo
        bool leader; //Bandera para indicar si es lider o no
        bool stopModule;

    protected:
        virtual int numInitStages() const
        {
            return 3;
        }

        /** @brief Initializes mobility model parameters.*/
        virtual void initialize(int stage);

        /** @brief Move the host*/
        virtual void move();
        /** @brief Function to get a pointer to the host module*/
        cModule* findHost(void);
        const cModule* findHost(void) const;

    public:
        CustomLinearMobility();
        virtual void stop();
        //Obtener velocidad del modulo
        virtual double getMySpeed();
        //Obtener aceleracion del modulo
        virtual double getMyAcceleration();
        //Modificar aceleracion del modulo
        virtual void setAcceleration(double newAcceleration);

        /**
         * @brief Function to get the logging name of the host
         *
         * The logging name is the ned module name of the host (unless the
         * host ned variable loggingName is specified). It can be used for
         * logging messages to simplify debugging in TKEnv.
         */
        std::string logName(void) const;
};

#endif


text:
Bootstrap Responsive Hexagon
====================

Bootstrap Responsive Hexagon are simple to use that has ability to scale its size according to its parent container and here we have used bootstrap grid as the parent container.

Check out [the demo page](http://shariarbd.com/demo/bootstrap-responsive-hexagon/)

For Support Leave a comment at [Bootstrap Responsive Hexagon](http://shariarbd.com/2014/11/css-hexagon-buttons/)


text:
from __future__ import division
import logging
import operator
import sys
import re

def compose_dict(time, lineno, msg, loglevel = logging.INFO):
	return {
		"issip" : 0,
		"isimsbr" : 1,
		"timestamp" : time,
		"lineno" : lineno,
		"msg" : msg,
		"loglevel" : loglevel,
	}

class imsbr_parser:
	def __init__(self):
		# Reg pattern:
		self.patterns = {}

		# Packets and other error statistics
		self.pkts_fromcp = 0
		self.pkts_tocp = 0
		self.sipc_fails = 0
		self.output_fails = 0

		# Tuple infos
		self.volte_tuples = 0
		self.vowifi_tuples = 0

		# Handover stat:
		self.last_ho = "ho-finish"

		self.results = []

	def search_pattern(self, name, line, regex):
		if name not in self.patterns:
			self.patterns[name] = re.compile(regex)
		return self.patterns[name].search(line)

	def add_result(self, res):
		self.results.append(res)

	def clear_stat(self):
		self.pkts_fromcp = 0
		self.pkts_tocp = 0
		self.sipc_fails = 0
		self.output_fails = 0

	def parse_tuple(self, lineno, time, line):
		'''
		Format:
		c2 imsbr: volte-add(sip) l3=41 l4=50 fd00:0:5:1::1 0 -> fd00:0:20:1::20 0
		'''
		match = self.search_pattern("tuple", line, "imsbr: (volte|vowifi)-(add|del)(.*)")
		if not match:
			return False

		if match.group(2) == "add":
			op = operator.add
		else:
			op = operator.sub

		if match.group(1) == "volte":
			self.volte_tuples = op(self.volte_tuples, 1)
		else:
			self.vowifi_tuples = op(self.vowifi_tuples, 1)

		msg = match.group(1) + "-" + match.group(2) + match.group(3)
		self.add_result(compose_dict(time, lineno, msg))
		return True

	def parse_calls(self, lineno, time, line):
		'''
		Format:
		c0 imsbr: call switch to [volte] init=volte curr=volte ho=ho-finish->ho-finish
		'''
		match = self.search_pattern("calls", line, "imsbr: call switch to \[(.*)\]")
		if not match:
			return False

		msg = "Start " + match.group(1) + " call"
		self.add_result(compose_dict(time, lineno, msg))
		return True

	def parse_sipcfail(self, lineno, time, line):
		'''
		Format:
		c2 imsbr: sblock_send ... fail, error=-1
		'''
		match = self.search_pattern("sipcfail", line, "(imsbr: sblock.*error.*)")
		if not match:
			return False

		self.sipc_fails += 1
		self.add_result(compose_dict(time, lineno, match.group(1)))
		return True

	def parse_outfail(self, lineno, time, line):
		'''
		Format:
		ip_route_output_key s=%pI4 d=%pI4 e=%ld\n
		ip_local_out s=%pI4 d=%pI4 p=%d err=%d\n
		ip6_route_output s=%pI6c d=%pI6c e=%d\n
		xfrm_lookup s=%pI6c d=%pI6c p=%d e=%ld\n
		ip6_local_out s=%pI6c d=%pI6c p=%d e=%d\n

		imsbr_packet_output_v6: 224 callbacks suppressed
		imsbr_packet_output: 224 callbacks suppressed
		'''

		match = self.search_pattern("outfail", line,
			"imsbr: (ip_route_output_key|ip_local_out|ip6_route_output|xfrm_lookup|ip6_local_out).*(e|err)=")
		if match:
			self.output_fails += 1
		else:
			match = self.search_pattern("outfail2", line,
					"imsbr_packet_output(_v6)?: (\d+) callbacks suppressed")
			if not match:
				return False
			self.output_fails += int(match.group(2))

		return True

	def parse_packet(self, lineno, time, line):
		'''
		Format:
		c0 imsbr: process packet from cp: src=2405:204:1a09:c645::9f7:e8b0 dst=2405:200:330:1587::10 ...
		c0 imsbr: relay packet to cp: src=2405:200:330:1587::10 dst=2405:204:1a09:c645::9f7:e8b0 ...

		c0 imsbr_process_packet: 304 callbacks suppressed
		c0 imsbr_packet_relay2cp: 304 callbacks suppressed
		'''
		match = self.search_pattern("packet", line, "imsbr: (process|relay) packet (from|to) cp:")

		if match:
			if match.group(1) == "process":
				self.pkts_fromcp += 1
			else:
				self.pkts_tocp += 1
		else:
			match = self.search_pattern("packet2", line,
					"imsbr_(process_packet|packet_relay2cp): (\d+) callbacks suppressed")
			if not match:
				return False
			if match.group(1) == "process_packet":
				self.pkts_fromcp += int(match.group(2))
			else:
				self.pkts_tocp += int(match.group(2))

		return True

	def dump_overview(self, lineno, time, ho):
		errmsg = None

		if ho == "ho-wifi2lte" and self.vowifi_tuples < 2:
			errmsg = "VOWIFI TUPLES %d ADDED, BUT HANDOVER TO VOLTE!" %(self.vowifi_tuples)
		elif ho == "ho-lte2wifi" and self.volte_tuples < 2:
			errmsg = "VOLTE TUPLES %d ADDED, BUT HANDOVER TO VOWIFI!" %(self.volte_tuples)
		elif ho == "ho-finish":
			# Dump overview stats
			msg = "Handover overview: fromcp=%d, tocp=%d, sipcfails=%d, outputfails=%d" \
				%(self.pkts_fromcp, self.pkts_tocp, self.sipc_fails, self.output_fails)
			self.add_result(compose_dict(time, lineno, msg))

			if self.pkts_fromcp == 0:
				errmsg = "NO PACKETS FROM CP, NEED CP CHECK IT FIRST!"
			elif self.pkts_tocp == 0:
				if self.last_ho == "ho-lte2wifi":
					# No pakcets from wifi, and there are many packets from cp output failed.
					if self.pkts_fromcp > 0 and self.output_fails/self.pkts_fromcp > 0.7:
						errmsg = "IP ROUTE FAIL, SECURITY CHECK IT FIRST!"
					else:
						errmsg = "NO PACKETS RECV FROM WIFI!"
				elif self.last_ho == "ho-wifi2lte":
					errmsg = "NO PACKETS FROM USERSPACE, NEED CHECK VIRTUAL ROUTE!"

		if errmsg:
			self.add_result(compose_dict(time, lineno, errmsg, logging.ERROR))

	def parse_handover(self, lineno, time, line):
		'''
		Format:
		c0 imsbr: trigger handover [ho-lte2wifi]
		'''
		match = self.search_pattern("handover", line, "imsbr: trigger handover \[(.*)\]")
		if not match:
			return False

		ho = match.group(1)
		self.add_result(compose_dict(time, lineno, "Trigger " + ho))
		self.dump_overview(lineno, time, ho)

		self.last_ho = ho
		self.clear_stat()
		return True

def parse_imsbr(logname):
	try:
		f = open(logname, "r")
	except IOError, e:
		print "Open fail:", e
		return None

	p = imsbr_parser()
	last_lineno = 0
	last_time = ""

	for _lineno, line in enumerate(f):
		if " imsbr" not in line:
			continue

		#Format: 01-01 08:04:05.743 ...
		t = line.split()
		t = t[0] + " " + t[1]

		lineno = _lineno + 1
		last_lineno = lineno
		last_time = t

		if p.parse_tuple(lineno, t, line):
			continue
		if p.parse_calls(lineno, t, line):
			continue
		if p.parse_sipcfail(lineno, t, line):
			continue
		if p.parse_outfail(lineno, t, line):
			continue
		if p.parse_packet(lineno, t, line):
			continue
		if p.parse_handover(lineno, t, line):
			continue

	# Handover log maybe incomplete, in such situation, also
	# dump the overview
	if p.last_ho != "ho-finish":
		p.dump_overview(last_lineno, last_time, "ho-finish")

	f.close()
	return p.results

def main():
	if len(sys.argv) != 2:
		print "Usage:", sys.argv[0], "kernel.log"
		sys.exit(1)

	results = parse_imsbr(sys.argv[1])
	if not results:
		return

	for d in results:
		print "line%d: %s %s " %(d["lineno"], d["timestamp"], d["msg"])

if __name__ == '__main__':
	main()


text:
DefaultPrepareTransfers is the default prepare transfers function used by the account, if non is specified.
> **Important note:** This API is currently in Beta and is subject to change. Use of these APIs in production applications is not supported.

## Input

| Parameter       | Type | Required or Optional | Description |
|:---------------|:--------|:--------| :--------|
| a | API | Optional |   |
| provider | SeedProvider | Optional |   |

## Output

| Return type     | Description |
|:---------------|:--------|
| PrepareTransfersFunc |  |


text:
package pcap.reconst.http;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpException;

import pcap.reconst.http.datamodel.RecordedHttpFlow;
import pcap.reconst.http.datamodel.RecordedHttpRequestMessage;
import pcap.reconst.http.datamodel.RecordedHttpResponse;
import pcap.reconst.tcp.MessageMetadata;
import pcap.reconst.tcp.StatusHandle;
import pcap.reconst.tcp.TcpConnection;
import pcap.reconst.tcp.TcpReassembler;

public class HttpFlowParser {

	private static Log log = LogFactory.getLog(HttpFlowParser.class);

	public static final Pattern HTTP_REQ_REGEX = Pattern.compile("(GET|POST|HEAD|OPTIONS|PUT|DELETE|TRACE|CONNECT)\\s\\S+\\sHTTP/[1-2]\\.[0-9]\\s");
	//Don't treat HTTP 100 status codes as the start of a response, e.g. "100 Continue" is a provisional response
	//and will later result in another response code for the same conversation
	public static final Pattern HTTP_RESP_REGEX = Pattern.compile("HTTP/[1-2]\\.[0-9]\\s[2-5][0-9][0-9](.[0-9][0-9]?)?\\s");

	private final static int ZERO = 0;

	private Map<TcpConnection, TcpReassembler> map;

	public HttpFlowParser(Map<TcpConnection, TcpReassembler> map) {
		this.map = map;
	}

	protected static SortedMap<Integer, Boolean> buildMessageStartIndex(String buf){
		List<Integer> reqIndexes = matchStartLocations(buf, HTTP_REQ_REGEX);
		List<Integer> respIndexes = matchStartLocations(buf, HTTP_RESP_REGEX);
		SortedMap<Integer, Boolean> matchLocations = new TreeMap<Integer, Boolean>();
		for(Integer key : reqIndexes){
			matchLocations.put(key, true); //true = request
		}
		for(Integer key : respIndexes){
			matchLocations.put(key, false); //false = response
		}
		return matchLocations;
	}

	//TODO fix for the chunked encoding case containing a request in a chunk
	private static boolean isPipelined(TcpReassembler assembler){
		SortedMap<Integer, Boolean> matchLocations = buildMessageStartIndex(assembler.getOrderedPacketData());
		List<Integer> matchIndexes = new ArrayList<Integer>(matchLocations.keySet());

		if(matchIndexes.size() > 1){
			for(int i = 0; i < matchIndexes.size() - 1; i++){
				int posA = matchIndexes.get(i);
				int posB = matchIndexes.get(i+1);
				int posC = assembler.getOrderedPacketData().length();
				//i+2 should give us the end of packet at i+1
				if(i+2 < matchIndexes.size()){
					posC = matchIndexes.get(i+2);
				}
				boolean messageA = matchLocations.get(posA);
				boolean messageB = matchLocations.get(posB);
				boolean errorBetween = assembler.errorBetween(posA, posC);

				//if there are errors in the stream then two requests can
				//look pipelined for the fact that a response is missing
				if(messageA && messageB && !errorBetween){
					return true;
				}
			}
		}
		return false;
	}

	protected static List<FlowBuf> parsePipelinedFlows(String buf) {
		List<FlowBuf> retval = new ArrayList<FlowBuf>();
		SortedMap<Integer, Boolean> matchLocations = buildMessageStartIndex(buf);
		List<Integer> matchIndexes = new ArrayList<Integer>(matchLocations.keySet());

		if(log.isDebugEnabled()){
			String logval = "Match Locations:\n";
			for(int index : matchIndexes){
				logval += index + " " + (matchLocations.get(index) ? "Request" : "Response") + "\n";
			}
			log.debug(logval);
		}

		if(matchIndexes.size() > 0){
			//get rid of any leading responses
			while(!matchLocations.get(matchIndexes.get(ZERO))){
				matchIndexes.remove(ZERO);
				if(matchIndexes.isEmpty()){
					break;
				}
			}

			List<FlowBuf> pReqSection = new ArrayList<FlowBuf>();
			List<FlowBuf> pRespSection = new ArrayList<FlowBuf>();
			FlowBuf singReqFlow = null;
			for(int i = 0; i < matchIndexes.size(); i++){
				boolean current = matchLocations.get(matchIndexes.get(i));
				if(i + 1 < matchIndexes.size()){
					boolean next = matchLocations.get(matchIndexes.get(i + 1));
					if(current){
						FlowBuf reqchunk = new FlowBuf();
						reqchunk.reqStart = matchIndexes.get(i);
						reqchunk.reqEnd = matchIndexes.get(i+1);
						if(next){
							//if request then request
							pReqSection.add(reqchunk);
						} else {
							//if request then response
							if(pReqSection.size() > 0){
								pReqSection.add(reqchunk);
							} else {
								singReqFlow=reqchunk;
							}
						}
					} else {
						FlowBuf respchunk = new FlowBuf();
						respchunk.respStart = matchIndexes.get(i);
						respchunk.respEnd = matchIndexes.get(i+1);
						if(next){
							//if response then request
							if(singReqFlow != null){
								retval.add(mergeFlowBuf(singReqFlow, respchunk));
								singReqFlow = null;
							} else {
								pRespSection.add(respchunk);
							}
							if(pReqSection.size() != pRespSection.size()){
								if(log.isDebugEnabled()){
									log.debug("Unequal pipeline sections. Returning parsed stream section.");
								}
								return retval;
								/*if(log.isWarnEnabled()){
									log.warn("Unequal pipeline sections. Attempting to fix.");
								}
								if(fixPipelinedSections(pReqSection, pRespSection, assembler)){
									if(log.isInfoEnabled()){
										log.info("Fixed unequal pipeline sections.");
									}
								} else {
									throw new RuntimeException("Unable to fix unequal pipeline sections.");
								}*/
							}
						} else {
							//if response then response
							if(pReqSection.size() > 0){
								pRespSection.add(respchunk);
							} else {
								//throw new RuntimeException("Two adjacent responses in error.");
								if(log.isDebugEnabled()){
									log.debug("Two adjacent responses in error. Returning parsed stream section.");
								}
								return retval;
							}
						}
						if(pReqSection.size() == pRespSection.size()){
							for(int q = 0; q < pReqSection.size(); q++){
								retval.add(mergeFlowBuf(pReqSection.get(q), pRespSection.get(q)));
							}
							pReqSection.clear();
							pRespSection.clear();
						}
					}
				} else {
					//i = len - 1
					if(current){ // if request
						FlowBuf reqchunk = new FlowBuf();
						reqchunk.reqStart = matchIndexes.get(i);
						reqchunk.reqEnd = buf.length();
						pReqSection.add(reqchunk);
						for(FlowBuf req : pReqSection){
							retval.add(req);
						}
					} else { //if response
						FlowBuf respchunk = new FlowBuf();
						respchunk.respStart = matchIndexes.get(i);
						respchunk.respEnd = buf.length();
						if(singReqFlow != null){ //single flow
							retval.add(mergeFlowBuf(singReqFlow, respchunk));
							singReqFlow = null;
						} else if (pReqSection.size() > 0) { //pipelined request section
							pRespSection.add(respchunk);
						} else {
							//throw new RuntimeException("Single unmatched response");
							if(log.isDebugEnabled()){
								log.debug("Single unmatched response. Returning parsed stream section.");
							}
							return retval;
						}
					}

					//if at the end of the stream, should be the end of the pipelined section
					if(pReqSection.size() == pRespSection.size()){
						//if pReqSection and pRespSection are empty then the loop is never executed
						for(int q = 0; q < pReqSection.size(); q++){
							retval.add(mergeFlowBuf(pReqSection.get(q), pRespSection.get(q)));
						}
						pReqSection.clear();
						pRespSection.clear();
					} else {
						if(pReqSection.size() > pRespSection.size()){
							//throw new RuntimeException("Incompleted pipelined response section.");
							if(log.isDebugEnabled()){
								log.debug("Incomplete pipelined response section. Returning parsed stream section.");
							}
						} else {
							//throw new RuntimeException("Incompleted pipelined request section.");
							if(log.isDebugEnabled()){
								log.debug("Incomplete pipelined request section. Returning parsed stream section.");
							}
						}
					}
				}
			}
		}
		return retval;
	}

	private static List<Integer> matchStartLocations(String buf, Pattern httpReqRegex){
		List<Integer> indexes = new ArrayList<Integer>();
		Matcher matcher = httpReqRegex.matcher(buf);
		while (matcher.find()) {
			indexes.add(matcher.start());
		}
		return indexes;
	}

	private static List<FlowBuf> splitFlows(String buf) {
		List<FlowBuf> retval = new ArrayList<FlowBuf>();
		SortedMap<Integer, Boolean> matchLocations = buildMessageStartIndex(buf);
		List<Integer> matchIndexes = new ArrayList<Integer>(matchLocations.keySet());

		if(matchIndexes.size() > 0){

			//get rid of any leading responses
			while(!matchLocations.get(matchIndexes.get(ZERO))){
				matchIndexes.remove(ZERO);
				if(matchIndexes.isEmpty()){
					break;
				}
			}

			if(log.isDebugEnabled()){
				log.debug("Number of match indexes: " + matchIndexes.size());
			}

			FlowBuf temp = null;
			for(int i = 0; i < matchIndexes.size(); i++){
				boolean current = matchLocations.get(matchIndexes.get(i));
				if(i + 1 < matchIndexes.size()){
					boolean next = matchLocations.get(matchIndexes.get(i + 1));
					if(current){ //is request
						if(!next){ //is response
							if(temp == null){
								temp = new FlowBuf();
								temp.reqStart = matchIndexes.get(i);
								temp.reqEnd = matchIndexes.get(i + 1);
							} else {
								throw new RuntimeException("FlowBuf should be null at this point.");
								// FlowBuf should be null, error
							}
						} else { //is request
							if(log.isDebugEnabled()){
								log.debug("Two adjacent requests in non pipelined flow.  " +
										"Request starting at index " + matchIndexes.get(i) + " has no response.");
							}
							temp = new FlowBuf();
							temp.reqStart = matchIndexes.get(i);
							temp.reqEnd = matchIndexes.get(i + 1);
							retval.add(temp);
							temp = null;
							// two requests back to back, error
						}
					} else { //is response
						if(next){ //is request
							if(temp != null){
								temp.respStart = matchIndexes.get(i);
								temp.respEnd = matchIndexes.get(i+1);
								retval.add(temp);
								temp = null;
							} else {
								throw new RuntimeException("FlowBuf should not be null at this point.");
								// FlowBuf should not be null, error
							}
						} else { // is response
							if(log.isDebugEnabled()){
								log.debug("Two adjacent responses in non pipelined flow.  " +
										"Response starting at index " + matchIndexes.get(i+1) + " has no request.");
							}
							temp.respStart = matchIndexes.get(i);
							temp.respEnd = matchIndexes.get(i+1);
							retval.add(temp);
							temp = null;
							i++; //skips the erroneous response
							// two responses back to back, error
						}
					}
				} else {
					if(current){ // is request
						if(temp == null){
							temp = new FlowBuf();
							temp.reqStart = matchIndexes.get(i);
							temp.reqEnd = buf.length();
							retval.add(temp);
						} else {
							throw new RuntimeException("FlowBuf should be null at this point.");
							// FlowBuf should be equal to null, error
						}
					} else { // is response
						if(temp != null){
							temp.respStart = matchIndexes.get(i);
							temp.respEnd = buf.length();
							retval.add(temp);
						} else {
							throw new RuntimeException("FlowBuf should not be null at this point.");
							// FlowBuf should not be equal to null, error
						}
					}
				}
			}
		}

		return retval;
	}

	@SuppressWarnings("unused")
	private int numRequests(String buf) {
		int retval = this.numMatches(buf, HTTP_REQ_REGEX);
		if (log.isDebugEnabled()) {
			log.debug("Number of Requests: " + retval);
		}
		return retval;
	}

	@SuppressWarnings("unused")
	private int numResponses(String buf) {
		int retval = this.numMatches(buf, HTTP_RESP_REGEX);
		if (log.isDebugEnabled()) {
			log.debug("Number of Responses: " + retval);
		}
		return retval;
	}

	private int numMatches(String buf, Pattern regex) {
		int retval = 0;
		Matcher matcher = regex.matcher(buf);
		while (matcher.find()) {
			retval++;
		}
		return retval;
	}

	private static boolean hasRequestData(String buf) {
		return hasDesiredData(buf, HTTP_REQ_REGEX);
	}

	private static boolean hasDesiredData(String buf, Pattern regex) {
		Matcher matcher = regex.matcher(buf);
		return matcher.find();
	}

	private List<RecordedHttpFlow> parseFlows(TcpConnection connection, TcpReassembler assembler) {
		String flowbuf = assembler.getOrderedPacketData();
		List<RecordedHttpFlow> outputlist = new ArrayList<RecordedHttpFlow>();
		if (hasRequestData(flowbuf)) {

			List<FlowBuf> flows = null;
			if(isPipelined(assembler)){
				if(log.isDebugEnabled()){
					log.debug("Parsing pipelined stream. " + connection);
				}
				flows = parsePipelinedFlows(flowbuf);

			} else {
				if(log.isDebugEnabled()){
					log.debug("Parsing non-pipelined stream. " + connection);
				}
				flows = splitFlows(flowbuf);
			}
			for (FlowBuf flow : flows) {
				try {
					RecordedHttpFlow httpOutput = this.toHttp(flow, assembler);
					outputlist.add(httpOutput);
				} catch (Exception e) {
					if (log.isErrorEnabled()) {
						log.error("", e);
					}
				}
			}
		}
		return outputlist;
	}

	public Map<TcpConnection, List<RecordedHttpFlow>> parse(StatusHandle status) {
		Map<TcpConnection, List<RecordedHttpFlow>> httpPackets =
				new HashMap<TcpConnection, List<RecordedHttpFlow>>();

		for (Entry<TcpConnection, TcpReassembler> entry : map.entrySet() ) {
			if (status.isCancelled())
			{
				break;
			}
			try{
				List<RecordedHttpFlow> flows = parseFlows(entry.getKey(), entry.getValue());
				if(flows.size() > 0){
					httpPackets.put(entry.getKey(), flows);
				} else {
					if(log.isDebugEnabled()){
						log.debug("No HTTP flows found in stream: " + entry.getKey());
					}
				}
				if (log.isDebugEnabled()) {
					log.debug("Processed stream: " + entry.getKey());
				}
			} catch (Exception e) {
				if(log.isErrorEnabled()){
					log.error("Error processing stream: " + entry.getKey(), e);
				}
			}
		}
		return httpPackets;
	}

	protected RecordedHttpFlow toHttp(FlowBuf flow, TcpReassembler assembler) throws IOException, HttpException {
		if (log.isDebugEnabled()) {
			log.debug("Processing flow " + flow);
		}
		byte[] rawdata = null;
		if (flow.hasRequestData()) {
			rawdata = assembler.getOrderedPacketDataBytes(flow.reqStart, flow.reqEnd);

			RecordedHttpRequestMessage request;
			RecordedHttpResponse response = null;

			if (flow.hadResponseData()) {
				byte[] respBytes = assembler.getOrderedPacketDataBytes(flow.respStart, flow.respEnd);
				byte[] reqRespbytes = new byte[rawdata.length + respBytes.length];
				System.arraycopy(rawdata, 0, reqRespbytes, 0, rawdata.length);
				System.arraycopy(respBytes, 0, reqRespbytes, rawdata.length, respBytes.length);
				rawdata = reqRespbytes;
				request = getRequest(flow, assembler);
				response = getResponse(flow, assembler);
			} else {
				request = getRequest(flow, assembler);
			}
			return new RecordedHttpFlow(rawdata, request, response);
		}
		return null;
	}

	protected static RecordedHttpRequestMessage getRequest(FlowBuf flow, TcpReassembler assembler) throws IOException, HttpException{
		String reqstring = assembler.getOrderedPacketData().substring(
				flow.reqStart, flow.reqEnd);
		MessageMetadata mdata = assembler
				.getMessageMetadata(flow.reqStart, flow.reqEnd);
		return (RecordedHttpRequestMessage)RecordedHttpMessageParser.
				parseRecordedRequest(reqstring, mdata);
	}

	protected static RecordedHttpResponse getResponse(FlowBuf flow,
			TcpReassembler assembler) throws IOException, HttpException{
		String respstring = assembler.getOrderedPacketData().substring(
				flow.respStart, flow.respEnd);
		MessageMetadata mdata = assembler
				.getMessageMetadata(flow.respStart, flow.respEnd);
		return (RecordedHttpResponse)RecordedHttpMessageParser.
				parseRecordedResponse(respstring, mdata);
	}

	public static FlowBuf mergeFlowBuf(FlowBuf reqChunk, FlowBuf respChunk){
		FlowBuf retval = new FlowBuf();
		retval.reqStart = reqChunk.reqStart;
		retval.reqEnd = reqChunk.reqEnd;
		retval.respStart = respChunk.respStart;
		retval.respEnd = respChunk.respEnd;
		return retval;
	}

	protected static class FlowBuf{
		public int reqStart = -1, reqEnd = -1, respStart = -1, respEnd = -1;

		public boolean hasRequestData(){
			return reqStart != -1 && reqEnd != -1;
		}

		public boolean hadResponseData(){
			return respStart != -1 && respEnd != -1;
		}

		@Override
		public String toString(){
			return "Request Start: " + reqStart + " Request End: " + reqEnd + " Response Start: " +
					respStart + " Response End: " + respEnd;
		}
	}

}


text:
class City < ActiveRecord::Base
  belongs_to :owner, :class_name => "User"
  has_many :buildings

  attr_accessible :name

  validates_presence_of :name, :owner

  before_create :set_defaults
  before_save :limit_population_by_capacity

  def is_full?
    self.population == total_capacity
  end

  def total_capacity
    self.buildings.to_a.sum(&:capacity)
  end

  private
  def set_defaults
    self.total_space = 9 unless self.total_space
    self.free_space = 9 unless self.free_space
    self.budget = 1000 unless self.budget
    self.population = 0 unless self.population
  end

  def limit_population_by_capacity
    self.population = [population, total_capacity].min
  end
end


text:
using System.Collections.Generic;
using AVF.MemberManagement.StandardLibrary.Interfaces;
using AVF.MemberManagement.StandardLibrary.Tbo;
using Newtonsoft.Json;

namespace AVF.MemberManagement.StandardLibrary.Tables
{
    public class TblTests : ITable<Test>
    {
        public const string TableName = "tblTest";

        public string Uri { get; set; } = TableName;

        [JsonProperty(PropertyName = TableName)]
        public List<Test> Rows { get; set; }
    }
}


text:
require 'spec_helper'

describe_recipe 'harden_macos::default' do
  context 'When running on mac_os_x 10.11' do
    let(:node_attributes) do
      { platform: 'mac_os_x', version: '10.11.1' }
    end

    # let(:context_node_attributes) do
    #   os_version == 11
    # end

    it 'converges successfully' do
       expect { chef_run }.to_not raise_error
    end

    it 'runs harden task with the default action' do
      expect(chef_run).to secure_harden_macos('firewall')
    end
    # it 'runs the harden_os updates topic' do
    #   expect(chef_run).to run_harden_macos('updates')
    # end

    # https://github.com/sethvargo/chefspec#testing-lwrps
  end
end


text:
from pyfftw import FFTW, n_byte_align, n_byte_align_empty
import numpy
import struct
from timeit import Timer

import unittest

class FFTWBaseTest(unittest.TestCase):

    def reference_fftn(self, a, axes):
        return numpy.fft.fftn(a, axes=axes)

    def __init__(self, *args, **kwargs):

        super(FFTWBaseTest, self).__init__(*args, **kwargs)
        self.make_shapes()

        if not hasattr(self, 'assertRaisesRegex'):
            self.assertRaisesRegex = self.assertRaisesRegexp

    def setUp(self):

        self.input_dtype = numpy.complex64
        self.output_dtype = numpy.complex64
        self.np_fft_comparison = numpy.fft.fft

        self.direction = 'FFTW_FORWARD'
        return

    def tearDown(self):

        return

    def get_input_dtype_alignment(self):
        return self.input_dtype([]).real.dtype.alignment

    def get_output_dtype_alignment(self):
        return self.input_dtype([]).real.dtype.alignment

    def make_shapes(self):
        self.input_shapes = {
                'small_1d': (16,),
                '1d': (2048,),
                '2d': (256, 2048),
                '3d': (5, 256, 2048)}

        self.output_shapes = {
                'small_1d': (16,),
                '1d': (2048,),
                '2d': (256, 2048),
                '3d': (5, 256, 2048)}

    def create_test_arrays(self, input_shape, output_shape, axes=None):
        a = self.input_dtype(numpy.random.randn(*input_shape)
                +1j*numpy.random.randn(*input_shape))

        b = self.output_dtype(numpy.random.randn(*output_shape)
                +1j*numpy.random.randn(*output_shape))

        return a, b

    def timer_routine(self, pyfftw_callable, numpy_fft_callable,
            comparison_string='numpy.fft'):

        N = 100

        t = Timer(stmt=pyfftw_callable)
        t_numpy_fft = Timer(stmt=numpy_fft_callable)

        t_str = ("%.2f" % (1000.0/N*t.timeit(N)))+' ms'
        t_numpy_str = ("%.2f" % (1000.0/N*t_numpy_fft.timeit(N)))+' ms'

        print('One run: '+ t_str + \
                ' (versus ' + t_numpy_str + ' for ' + comparison_string + \
                ')')

    def run_validate_fft(self, a, b, axes, fft=None, ifft=None,
            force_unaligned_data=False, create_array_copies=True,
            threads=1, flags=('FFTW_ESTIMATE',)):
        ''' Run a validation of the FFTW routines for the passed pair
        of arrays, a and b, and the axes argument.

        a and b are assumed to be the same shape (but not necessarily
        the same layout in memory).

        fft and ifft, if passed, should be instantiated FFTW objects.

        If force_unaligned_data is True, the flag FFTW_UNALIGNED
        will be passed to the fftw routines.

        The threads argument runs the validation with multiple threads.

        flags is passed to the creation of the FFTW object.
        '''

        if create_array_copies:
            # Don't corrupt the original mutable arrays
            a = a.copy()
            b = b.copy()

        a_orig = a.copy()

        flags = list(flags)

        if force_unaligned_data:
            flags.append('FFTW_UNALIGNED')

        if fft == None:
            fft = FFTW(a,b,axes=axes, direction='FFTW_FORWARD',
                    flags=flags, threads=threads)
        else:
            fft.update_arrays(a,b)

        if ifft == None:
            ifft = FFTW(b, a, axes=axes, direction='FFTW_BACKWARD',
                    flags=flags, threads=threads)
        else:
            ifft.update_arrays(b,a)

        a[:] = a_orig

        # Test the forward FFT by comparing it to the result from numpy.fft
        fft.execute()
        ref_b = self.reference_fftn(a, axes=axes)

        # This is actually quite a poor relative error, but it still
        # sometimes fails. I assume that numpy.fft has different internals
        # to fftw.
        self.assertTrue(numpy.allclose(b, ref_b, rtol=1e-2, atol=1e-3))

        # Test the inverse FFT by comparing the result to the starting
        # value (which is scaled as per FFTW being unnormalised).
        ifft.execute()
        # The scaling is the product of the lengths of the fft along
        # the axes along which the fft is taken.
        scaling = numpy.prod(numpy.array(a.shape)[list(axes)])

        self.assertEqual(ifft.N, scaling)
        self.assertEqual(fft.N, scaling)

        self.assertTrue(numpy.allclose(a/scaling, a_orig, rtol=1e-2, atol=1e-3))
        return fft, ifft

def run_test_suites(test_suites, run_tests=None):
    '''From each test case (derived from TestCase) in test_suites,
    load and run all the test cases within.

    If run_tests is not None, then it should be a dictionary with
    keys being the test suite class name, and the values being
    a list of test methods to run. Alternatively, the key can
    be 'all' in which case all the test suites will be run with
    the provided list of test suites.
    '''
    suite = unittest.TestSuite()

    for test_class in test_suites:
        tests = unittest.TestLoader().loadTestsFromTestCase(test_class)

        if run_tests is not None:
            if test_class.__name__ in run_tests:
                this_suite_run = set(run_tests[test_class.__name__])
            else:
                this_suite_run = set()

            if 'all' in run_tests:
                this_suite_run = this_suite_run.union(run_tests['all'])

            _tests = []
            for each_test in tests:
                if (each_test.id().split('.')[-1] in this_suite_run):
                    _tests.append(each_test)

            tests = _tests

        suite.addTests(tests)

    unittest.TextTestRunner(verbosity=2).run(suite)


text:
package org.wisdom.api.http;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import org.junit.Test;
import org.wisdom.api.bodies.NoHttpBody;

import static org.assertj.core.api.Assertions.assertThat;
import static org.wisdom.api.cookies.Cookie.cookie;

/**
 * Checks the Result class.
 */
public class ResultTest {
    @Test
    public void testRenderWithStrings() throws Exception {
        Result result = Results.ok().render("hello");
        assertThat(result.getRenderable()).isNotNull();
        assertThat(result.getRenderable().content()).isEqualTo("hello");
        assertThat(result.getRenderable().requireSerializer()).isFalse();
        assertThat(result.getRenderable().length()).isGreaterThan(0);
        assertThat(result.getRenderable().mustBeChunked()).isFalse();

        result = Results.ok().render(new StringBuilder("hello"));
        assertThat(result.getRenderable()).isNotNull();
        assertThat(result.getRenderable().content()).isEqualTo("hello");
        assertThat(result.getRenderable().requireSerializer()).isFalse();
        assertThat(result.getRenderable().length()).isGreaterThan(0);
        assertThat(result.getRenderable().mustBeChunked()).isFalse();

        result = Results.ok().render(new StringBuffer("hello"));
        assertThat(result.getRenderable()).isNotNull();
        assertThat(result.getRenderable().content()).isEqualTo("hello");
        assertThat(result.getRenderable().requireSerializer()).isFalse();
        assertThat(result.getRenderable().length()).isGreaterThan(0);
        assertThat(result.getRenderable().mustBeChunked()).isFalse();
    }

    @Test
    public void testRenderObjects() throws Exception {
        Result result = Results.ok().render(ImmutableList.of());
        assertThat(result.getRenderable().requireSerializer()).isTrue();
        assertThat(result.getRenderable().length()).isLessThan(0);
    }

    @Test
    public void testRenderJson() throws Exception {
        Result result = Results.ok().render(new ObjectMapper().createObjectNode().put("hello", "value"));
        assertThat(result.getContentType()).isEqualTo(MimeTypes.JSON);
        assertThat(result.getRenderable().requireSerializer()).isFalse();
        assertThat(result.getRenderable().length()).isGreaterThan(0);
        assertThat(result.getRenderable().mustBeChunked()).isFalse();
    }

    @Test
    public void testGetContentType() throws Exception {
        Result result = Results.ok().json();
        assertThat(result.getContentType()).contains(MimeTypes.JSON).doesNotContain(Charsets.UTF_8.toString());
        result = Results.ok().as(MimeTypes.BINARY);
        assertThat(result.getContentType()).contains(MimeTypes.BINARY).doesNotContain(Charsets.UTF_8.toString());
    }

    @Test
    public void testGetFullContentType() throws Exception {
        Result result = Results.ok().json();
        assertThat(result.getFullContentType()).contains(MimeTypes.JSON).contains(Charsets.UTF_8.toString());
        result = Results.ok().as(MimeTypes.BINARY);
        assertThat(result.getFullContentType()).contains(MimeTypes.BINARY).doesNotContain(Charsets.UTF_8.toString());
    }

    @Test
    public void testAs() throws Exception {
        Result result = new Result(200).as(MimeTypes.CSS);
        assertThat(result.getContentType()).isEqualTo(MimeTypes.CSS);
        assertThat(result.getHeaders().get(HeaderNames.CONTENT_TYPE)).isEqualTo(MimeTypes.CSS);
        assertThat(result.getCharset()).isNotEqualTo(Charsets.UTF_8);

        // Check complete mime type
        result = new Result(200).as("application/json; charset=utf-8").render("{}");
        assertThat(result.getCharset()).isEqualTo(Charsets.UTF_8);
        assertThat(result.getContentType()).contains(MimeTypes.JSON);
        result.getRenderable().render(null, result);
        assertThat(result.getCharset()).isEqualTo(Charsets.UTF_8);
    }

    @Test
    public void testGetHeaders() throws Exception {
        Result result = Results.ok();
        assertThat(result.getHeaders()).isEmpty();
        result.with("Header", "Value");
        assertThat(result.getHeaders().get("Header")).isEqualTo("Value");
    }

    @Test
    public void testWithCharset() throws Exception {
        Result result = Results.ok().with(Charsets.US_ASCII);
        assertThat(result.getCharset()).isEqualTo(Charsets.US_ASCII);
    }

    @Test
    public void testGetCookies() throws Exception {
        Result result = Results.ok();
        assertThat(result.getCookies()).isEmpty();

        result.with(cookie("hello", "value").build());
        assertThat(result.getCookies()).hasSize(1);
        assertThat(result.getCookie("hello").value()).isEqualTo("value");
        assertThat(result.getCookie("missing")).isNull();
    }

    @Test
    public void testWithout() throws Exception {
        Result result = Results.ok()
                .with("header", "value")
                .with(cookie("hello", "value").setMaxAge(10L).build());

        assertThat(result.getHeaders().get("header")).isEqualTo("value");
        result.without("header");
        assertThat(result.getHeaders().get("header")).isNull();
        result.without("hello");
        assertThat(result.getCookie("hello").maxAge()).isEqualTo(0L);
    }

    @Test
    public void testDiscard() throws Exception {
        Result result = Results.ok().discard("cookie");
        // A cookie is discarded by setting its max-age to 0
        assertThat(result.getCookie("cookie").maxAge()).isEqualTo(0L);

        result.with(cookie("hello", "value").setMaxAge(10L).build());
        result.discard("hello");
        assertThat(result.getCookie("hello").maxAge()).isEqualTo(0L);
    }

    @Test
    public void testStatus() throws Exception {
        Result result = Results.ok().status(418);
        // I'm a teapot
        assertThat(result.getStatusCode()).isEqualTo(418);

    }

    @Test
    public void testRedirect() throws Exception {
        Result result = new Result(200).redirect("/foo");
        assertThat(result.getStatusCode()).isEqualTo(Status.SEE_OTHER);
        assertThat(result.getHeaders().get(HeaderNames.LOCATION)).isEqualTo("/foo");

    }

    @Test
    public void testRedirectTemporary() throws Exception {
        Result result = new Result(200).redirectTemporary("/foo");
        assertThat(result.getStatusCode()).isEqualTo(Status.TEMPORARY_REDIRECT);
        assertThat(result.getHeaders().get(HeaderNames.LOCATION)).isEqualTo("/foo");
    }

    @Test
    public void testHtml() throws Exception {
        Result result = new Result(200).html();
        assertThat(result.getContentType()).isEqualTo(MimeTypes.HTML);
        assertThat(result.getHeaders().get(HeaderNames.CONTENT_TYPE)).isEqualTo(MimeTypes.HTML);
        assertThat(result.getCharset()).isEqualTo(Charsets.UTF_8);
    }

    @Test
    public void testJson() throws Exception {
        Result result = new Result(200).json();
        assertThat(result.getContentType()).isEqualTo(MimeTypes.JSON);
        assertThat(result.getHeaders().get(HeaderNames.CONTENT_TYPE)).isEqualTo(MimeTypes.JSON);
        assertThat(result.getCharset()).isEqualTo(Charsets.UTF_8);

    }

    @Test
    public void testXml() throws Exception {
        Result result = new Result(200).xml();
        assertThat(result.getContentType()).isEqualTo(MimeTypes.XML);
        assertThat(result.getHeaders().get(HeaderNames.CONTENT_TYPE)).isEqualTo(MimeTypes.XML);
        assertThat(result.getCharset()).isEqualTo(Charsets.UTF_8);
    }

    @Test
    public void testNoCache() throws Exception {
        Result result = new Result(200);
        result.noCache();
        assertThat(result.getHeaders()).containsEntry(HeaderNames.CACHE_CONTROL, HeaderNames.NOCACHE_VALUE);
    }

    @Test
    public void testNoContentIfNone() throws Exception {
        Result result = new Result(200);
        // We don't have content.
        assertThat(result.getRenderable()).isNull();
        result.noContentIfNone();
        assertThat(result.getRenderable()).isInstanceOf(NoHttpBody.class);

        result = Results.ok("hello");
        result.noContentIfNone();
        assertThat(result.getRenderable()).isNotInstanceOf(NoHttpBody.class);
    }
}


text:
"""Support for Greenwave Reality (TCP Connected) lights."""
from __future__ import annotations

from datetime import timedelta
import logging
import os

import greenwavereality as greenwave
import voluptuous as vol

from homeassistant.components.light import (
    ATTR_BRIGHTNESS,
    PLATFORM_SCHEMA,
    ColorMode,
    LightEntity,
)
from homeassistant.const import CONF_HOST
from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.util import Throttle

_LOGGER = logging.getLogger(__name__)

CONF_VERSION = "version"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {vol.Required(CONF_HOST): cv.string, vol.Required(CONF_VERSION): cv.positive_int}
)

MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=1)

def setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the Greenwave Reality Platform."""
    host = config.get(CONF_HOST)
    tokenfilename = hass.config.path(".greenwave")
    if config.get(CONF_VERSION) == 3:
        if os.path.exists(tokenfilename):
            with open(tokenfilename, encoding="utf8") as tokenfile:
                token = tokenfile.read()
        else:
            try:
                token = greenwave.grab_token(host, "hass", "homeassistant")
            except PermissionError:
                _LOGGER.error("The Gateway Is Not In Sync Mode")
                raise
            with open(tokenfilename, "w+", encoding="utf8") as tokenfile:
                tokenfile.write(token)
    else:
        token = None
    bulbs = greenwave.grab_bulbs(host, token)
    add_entities(
        GreenwaveLight(device, host, token, GatewayData(host, token))
        for device in bulbs.values()
    )

class GreenwaveLight(LightEntity):
    """Representation of an Greenwave Reality Light."""

    _attr_color_mode = ColorMode.BRIGHTNESS
    _attr_supported_color_modes = {ColorMode.BRIGHTNESS}

    def __init__(self, light, host, token, gatewaydata):
        """Initialize a Greenwave Reality Light."""
        self._did = int(light["did"])
        self._name = light["name"]
        self._state = int(light["state"])
        self._brightness = greenwave.hass_brightness(light)
        self._host = host
        self._online = greenwave.check_online(light)
        self._token = token
        self._gatewaydata = gatewaydata

    @property
    def available(self):
        """Return True if entity is available."""
        return self._online

    @property
    def name(self):
        """Return the display name of this light."""
        return self._name

    @property
    def brightness(self):
        """Return the brightness of the light."""
        return self._brightness

    @property
    def is_on(self):
        """Return true if light is on."""
        return self._state

    def turn_on(self, **kwargs):
        """Instruct the light to turn on."""
        temp_brightness = int((kwargs.get(ATTR_BRIGHTNESS, 255) / 255) * 100)
        greenwave.set_brightness(self._host, self._did, temp_brightness, self._token)
        greenwave.turn_on(self._host, self._did, self._token)

    def turn_off(self, **kwargs):
        """Instruct the light to turn off."""
        greenwave.turn_off(self._host, self._did, self._token)

    def update(self):
        """Fetch new state data for this light."""
        self._gatewaydata.update()
        bulbs = self._gatewaydata.greenwave

        self._state = int(bulbs[self._did]["state"])
        self._brightness = greenwave.hass_brightness(bulbs[self._did])
        self._online = greenwave.check_online(bulbs[self._did])
        self._name = bulbs[self._did]["name"]

class GatewayData:
    """Handle Gateway data and limit updates."""

    def __init__(self, host, token):
        """Initialize the data object."""
        self._host = host
        self._token = token
        self._greenwave = greenwave.grab_bulbs(host, token)

    @property
    def greenwave(self):
        """Return Gateway API object."""
        return self._greenwave

    @Throttle(MIN_TIME_BETWEEN_UPDATES)
    def update(self):
        """Get the latest data from the gateway."""
        self._greenwave = greenwave.grab_bulbs(self._host, self._token)
        return self._greenwave


text:
package gradle.udacity.com.practice_androidunittesting.paid;

import android.util.Log;
import gradle.udacity.com.practice_androidunittesting.Echo;

public class PaidEcho extends Echo {

    public static <T> T echo(T o, boolean log) {
        if (log) {
            Log.i(Echo.class.getName(), o.toString());
        }
        return o;
    }

    public static <T> T echo(T o) {
        return echo(o, false);
    }
}