text:
"""
Implement a time series control chart.

Copyright 2014 Daniel Couture (GNU GPLv3)

Usage:

    cat data | python{3} control_chart.py

Control Tests:

    [x] is < 3 sigma
    [x] is > 3 sigma
    [..] is 2/3 points > 2 sigma
    [..] is 2/3 points < 2 sigma
    [..] is 4/5 points > 1 sigma
    [..] is 4/5 points < 1 sigma
    [..] is 8/8 points > centerline
    [..] is 8/8 points < centerline

Centerline Shift Tests:

    [..] is 10/11 points > centerline
    [..] is 10/11 points < centerline
    [..] is 12/14 points > centerline
    [..] is 12/14 points < centerline
    [..] is 14/17 points > centerline
    [..] is 14/17 points < centerline
    [..] is 16/20 points > centerline
    [..] is 16/20 points < centerline

References:
    Implementing Six Sigma
    Smarter Solutions Using Statistical Methods
    Forrest W. Breyfogle III
    Second Edition, pp. 221
"""

import os
import sys
import numpy as np
from argparse import ArgumentParser

class Window(object):
    """
    Create a variable sized rolling window of data points.

    Usage::

        w = Window(4)
        for x in range(10):
            w.append(x)
        print("Rolling average for %s is %g" % (w, w.data.mean()))
        # Rolling average for [ 8.  9.  6.  7.] is 7.5

    :param n: size of the rolling window
    :type  n: int
    :param init: Initialize all entries to a value (np.nan by default)
    :type  init: numeric
    """
    def __init__(self, n, init=None):
        self.idx = 0
        self.n = n
        self.data = np.empty(n)
        if init is None:
            self.data.fill(np.nan)
        else:
            self.data.fill(init)

    def append(self, value):
        try:
            self.data[self.idx] = value
        except IndexError:
            self.idx = 0
            self.data[self.idx] = value
        self.idx += 1

    def __str__(self):
        return str(self.data)

def err_out(msg):
    """
    Helper function to write to stdout

    :param msg: message to write
    :type  msg: str
    """
    sys.stderr.write("%s\n" % msg)
    sys.stderr.flush()

def test_3_sigma(options):
    """
    Create a test for a single value outside 3 standard deviations
    """
    lcl = options.m - 3 * options.s
    ucl = options.m + 3 * options.s

    def test(x):
        if x < lcl:
            err_out("%g is < 3 sigma" % x)
        elif x > ucl:
            err_out("%g is > 3 sigma" % x)
    return test

def test_2_sigma(options):
    """
    Create a test for 2 out of 3 values outside of 2 standard deviations
    """
    w = Window(3, init=options.m)
    lcl = options.m - 2 * options.s
    ucl = options.m + 2 * options.s

    def test(x):
        w.append(x)
        if np.sum(w.data > ucl) >= 2:
            err_out("%s is 2/3 points > 2 sigma" % w.data)
        elif np.sum(w.data < lcl) >= 2:
            err_out("%s is 2/3 points < 2 sigma" % w.data)
    return test

def test_1_sigma(options):
    """
    Create a test for 4 out of 5 values outside of 1 standard deviation
    """
    w = Window(5, init=options.m)
    lcl = options.m - 1 * options.s
    ucl = options.m + 1 * options.s

    def test(x):
        w.append(x)
        if np.sum(w.data > ucl) >= 4:
            err_out("%s is 4/5 points > 1 sigma" % w.data)
        elif np.sum(w.data < lcl) >= 4:
            err_out("%s is 4/5 points < 1 sigma" % w.data)
    return test

def test_cl_shift(options):
    """
    Create tests for centerline shifts

    8 out of 8 points are on one side of the mean
    >= 10 out of 11 points are on one side of the mean
    >= 12 out of 14 points are on one side of the mean
    >= 14 out of 17 points are on one side of the mean
    >= 16 out of 20 points are on one side of the mean
    """
    windows = [
        (8, Window(8, init=options.m)),
        (10, Window(11, init=options.m)),
        (12, Window(14, init=options.m)),
        (14, Window(17, init=options.m)),
        (16, Window(20, init=options.m)),
    ]
    cl = options.m

    def test(x):
        for n, w in windows:
            w.append(x)
            if np.sum(w.data > cl) >= n:
                err_out("%s is %g/%g points > centerline" %
                        (w.data, n, w.n))
            elif np.sum(w.data < cl) >= n:
                err_out("%s is %g/%g points < centerline" %
                        (w.data, n, w.n))
    return test

def control_chart(stream, options):
    """
    Run the control chart tests.  For each new value yielded by the stream,
    pass it to each of the tests for checking.

    :param stream: generator that yields the next value to test
    :type  stream: generator
    :param options: values for defining the tests (mean, standard deviation)
    :type  options: argparse.Namespace
    """
    tests = []
    tests.append(test_3_sigma(options))
    tests.append(test_2_sigma(options))
    tests.append(test_1_sigma(options))
    tests.append(test_cl_shift(options))

    for x in stream:
        for test in tests:
            test(x)
    return 0

def load_stream(input_stream):
    """
    Format the input stream to create numeric data points.

    :param input_stream: data generator.  Lines are excepted of str type
    :type  input_stream: generator (sys.stdin)
    """
    for line in input_stream:
        clean_line = line.strip()
        if not clean_line:
            # skip empty lines (ie: newlines)
            continue
        if clean_line[0] in ['"', "'"]:
            clean_line = clean_line.strip('"').strip("'")
        try:
            yield float(clean_line)
        except:
            err_out("invalid line %r" % line)

def parse_args():
    """
    Parse out testing arguments.
    """
    _, fname = os.path.split(__file__)
    usage = "cat data | python %s" % fname

    parser = ArgumentParser(usage=usage)
    parser.add_argument("-m", "--center", dest="m", required=True,
                        type=float, help="control chart centerline")
    parser.add_argument("-s", "--stdev", dest="s", required=True,
                        type=float, help="standard deviation")

    if sys.stdin.isatty():
        # if isatty() that means it's run without anything piped into it
        parser.print_usage()
        print("for more help use --help")
        sys.exit(1)
    return parser.parse_args()

def main():
    """
    Setup and run the tests from a stdin stream of data
    """
    options = parse_args()
    return control_chart(load_stream(sys.stdin), options)

if __name__ == "__main__":
    exit(main())


text:
package io.swagger.server.api.model;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ModelUser   {

  private Long id = null;
  private String username = null;
  private String firstName = null;
  private String lastName = null;
  private String email = null;
  private String password = null;
  private String phone = null;
  private Integer userStatus = null;

  public ModelUser () {

  }

  public ModelUser (Long id, String username, String firstName, String lastName, String email, String password, String phone, Integer userStatus) {
    this.id = id;
    this.username = username;
    this.firstName = firstName;
    this.lastName = lastName;
    this.email = email;
    this.password = password;
    this.phone = phone;
    this.userStatus = userStatus;
  }

  @JsonProperty("id")
  public Long getId() {
    return id;
  }
  public ModelUser setId(Long id) {
    this.id = id;
    return this;
  }

  @JsonProperty("username")
  public String getUsername() {
    return username;
  }
  public ModelUser setUsername(String username) {
    this.username = username;
    return this;
  }

  @JsonProperty("firstName")
  public String getFirstName() {
    return firstName;
  }
  public ModelUser setFirstName(String firstName) {
    this.firstName = firstName;
    return this;
  }

  @JsonProperty("lastName")
  public String getLastName() {
    return lastName;
  }
  public ModelUser setLastName(String lastName) {
    this.lastName = lastName;
    return this;
  }

  @JsonProperty("email")
  public String getEmail() {
    return email;
  }
  public ModelUser setEmail(String email) {
    this.email = email;
    return this;
  }

  @JsonProperty("password")
  public String getPassword() {
    return password;
  }
  public ModelUser setPassword(String password) {
    this.password = password;
    return this;
  }

  @JsonProperty("phone")
  public String getPhone() {
    return phone;
  }
  public ModelUser setPhone(String phone) {
    this.phone = phone;
    return this;
  }

  @JsonProperty("userStatus")
  public Integer getUserStatus() {
    return userStatus;
  }
  public ModelUser setUserStatus(Integer userStatus) {
    this.userStatus = userStatus;
    return this;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    ModelUser _user = (ModelUser) o;
    return Objects.equals(id, _user.id) &&
        Objects.equals(username, _user.username) &&
        Objects.equals(firstName, _user.firstName) &&
        Objects.equals(lastName, _user.lastName) &&
        Objects.equals(email, _user.email) &&
        Objects.equals(password, _user.password) &&
        Objects.equals(phone, _user.phone) &&
        Objects.equals(userStatus, _user.userStatus);
  }

  @Override
  public int hashCode() {
    return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class ModelUser {\n");

    sb.append("    id: ").append(toIndentedString(id)).append("\n");
    sb.append("    username: ").append(toIndentedString(username)).append("\n");
    sb.append("    firstName: ").append(toIndentedString(firstName)).append("\n");
    sb.append("    lastName: ").append(toIndentedString(lastName)).append("\n");
    sb.append("    email: ").append(toIndentedString(email)).append("\n");
    sb.append("    password: ").append(toIndentedString(password)).append("\n");
    sb.append("    phone: ").append(toIndentedString(phone)).append("\n");
    sb.append("    userStatus: ").append(toIndentedString(userStatus)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.AR;
using Lucene.Net.Analysis.Fa;
using Lucene.Net.Test.Analysis;
using NUnit.Framework;

namespace Lucene.Net.Analyzers.Fa
{
    /*
     * Test the Arabic Normalization Filter
     *
     */
    [TestFixture]
    public class TestPersianNormalizationFilter : BaseTokenStreamTestCase
    {
        [Test]
        public void TestFarsiYeh()
        {
            Check("های", "هاي");
        }

        [Test]
        public void TestYehBarree()
        {
            Check("هاے", "هاي");
        }

        [Test]
        public void TestKeheh()
        {
            Check("کشاندن", "كشاندن");
        }

        [Test]
        public void TestHehYeh()
        {
            Check("كتابۀ", "كتابه");
        }

        [Test]
        public void TestHehHamzaAbove()
        {
            Check("كتابهٔ", "كتابه");
        }

        [Test]
        public void TestHehGoal()
        {
            Check("زادہ", "زاده");
        }

        private void Check(String input, String expected)
        {
            ArabicLetterTokenizer tokenStream = new ArabicLetterTokenizer(
                new StringReader(input));
            PersianNormalizationFilter filter = new PersianNormalizationFilter(
                tokenStream);
            AssertTokenStreamContents(filter, new String[] { expected });
        }
    }
}


text:
package com.huaijie.android_hacks.ui.activity;

import android.app.Activity;
import android.os.Bundle;
import com.huaijie.android_hacks.R;

/**
 * Created by fenghb on 2014/4/30.
 */
public class LazyLoading extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lazy_loading);
    }
}


text:
import os
from contextlib import suppress
from multiprocessing import Process
from typing import Optional

from astropy import units as u
from panoptes.pocs.base import PanBase
from panoptes.pocs.observatory import Observatory
from panoptes.pocs.scheduler.observation.base import Observation
from panoptes.pocs.state.machine import PanStateMachine
from panoptes.utils.time import current_time
from panoptes.utils.utils import get_free_space
from panoptes.utils.time import CountdownTimer
from panoptes.pocs.utils import error

class POCS(PanStateMachine, PanBase):
    """The main class representing the Panoptes Observatory Control Software (POCS).

    Interaction with a PANOPTES unit is done through instances of this class. An instance consists
    primarily of an `Observatory` object, which contains the mount, cameras, scheduler, etc.
    See `pocs.Observatory`. The observatory should create all attached hardware
    but leave the initialization up to POCS (i.e. this class will call the observatory
    `initialize` method).

    The POCS instance itself is designed to be run as a state machine via
    the `run` method.

    Args:
        observatory(Observatory): An instance of a `pocs.observatory.Observatory`
            class. POCS will call the `initialize` method of the observatory.
        state_machine_file(str): Filename of the state machine to use, defaults to
            'panoptes'.
        simulators(list): A list of the different modules that can run in simulator mode. Possible
            modules include: all, mount, camera, weather, night. Defaults to an empty list.

    Attributes:
        name (str): Name of PANOPTES unit
        observatory (`pocs.observatory.Observatory`): The `~pocs.observatory.Observatory` object

    """

    def __init__(
            self,
            observatory,
            state_machine_file=None,
            simulators=None,
            *args, **kwargs):

        # Explicitly call the base classes in the order we want.
        PanBase.__init__(self, *args, **kwargs)

        if simulators:
            self.logger.warning(f'Using simulators={simulators!r}')
            self.set_config('simulator', simulators)

        assert isinstance(observatory, Observatory)

        self.name = self.get_config('name', default='Generic PANOPTES Unit')
        location = self.get_config('location.name', default='Unknown location')
        self.logger.info(f'Initializing PANOPTES unit - {self.name} - {location}')

        if state_machine_file is None:
            state_machine_file = self.get_config('state_machine', default='panoptes')

        self.logger.info(f'Making a POCS state machine from {state_machine_file}')
        PanStateMachine.__init__(self, state_machine_file, **kwargs)

        # Add observatory object, which does the bulk of the work.
        self.observatory = observatory

        self.is_initialized = False
        self._free_space = None

        self.run_once = kwargs.get('run_once', False)
        self._obs_run_retries = self.get_config('pocs.RETRY_ATTEMPTS', default=3)
        self.connected = True
        self.interrupted = False

        self.say("Hi there!")

    @property
    def is_initialized(self):
        """ Indicates if POCS has been initialized or not """
        return self.get_config('pocs.INITIALIZED', default=False)

    @is_initialized.setter
    def is_initialized(self, new_value):
        self.set_config('pocs.INITIALIZED', new_value)

    @property
    def interrupted(self):
        """If POCS has been interrupted.

        Returns:
            bool: If an interrupt signal has been received
        """
        return self.get_config('pocs.INTERRUPTED', default=False)

    @interrupted.setter
    def interrupted(self, new_value):
        self.set_config('pocs.INTERRUPTED', new_value)
        if new_value:
            self.logger.critical(f'POCS has been interrupted')

    @property
    def connected(self):
        """ Indicates if POCS is connected """
        return self.get_config('pocs.CONNECTED', default=False)

    @connected.setter
    def connected(self, new_value):
        self.set_config('pocs.CONNECTED', new_value)

    @property
    def do_states(self):
        return self.get_config('pocs.DO_STATES', default=True)

    @do_states.setter
    def do_states(self, new_value):
        self.set_config('pocs.DO_STATES', new_value)

    @property
    def keep_running(self):
        """If POCS should keep running.

        Currently reads:

        * `connected`
        * `do_states`
        * `observatory.can_observe`

        Returns:
            bool: If POCS should keep running.
        """
        return self.connected and self.do_states and self.observatory.can_observe

    @property
    def run_once(self):
        """If POCS should exit the run loop after a single iteration.

        This value reads the `pocs.RUN_ONCE` config value.

        Returns:
            bool: if machine should stop after single iteration, default False.
        """
        return self.get_config('pocs.RUN_ONCE', default=False)

    @run_once.setter
    def run_once(self, new_value):
        self.set_config('pocs.RUN_ONCE', new_value)

    @property
    def should_retry(self):
        return self._obs_run_retries >= 0

    @property
    def status(self):
        status = dict()

        try:
            status['state'] = self.state
            status['system'] = {
                'free_space': str(self._free_space),
            }
            status['observatory'] = self.observatory.status
        except Exception as e:  # pragma: no cover
            self.logger.warning(f"Can't get status: {e!r}")

        return status

    ################################################################################################
    # Methods
    ################################################################################################

    def initialize(self):
        """Initialize POCS.

        Calls the Observatory `initialize` method.

        Returns:
            bool: True if all initialization succeeded, False otherwise.
        """

        if not self.observatory.can_observe:
            self.say("Looks like we're missing some required hardware.")
            return False

        if not self.is_initialized:
            self.logger.info('*' * 80)
            self.say("Initializing the system! Woohoo!")

            try:
                self.logger.debug("Initializing observatory")
                self.observatory.initialize()

            except Exception as e:
                self.say(f"Oh wait. There was a problem initializing: {e!r}")
                self.say("Since we didn't initialize, I'm going to exit.")
                self.power_down()
            else:
                self.is_initialized = True
                self.do_states = True

        return self.is_initialized

    def say(self, msg):
        """ PANOPTES Units like to talk!

        Send a message.

        Args:
            msg(str): Message to be sent to topic PANCHAT.
        """
        self.logger.success(f'Unit says: {msg}')

    def power_down(self):
        """Actions to be performed upon shutdown

        Note:
            This method is automatically called from the interrupt handler. The definition should
            include what you want to happen upon shutdown but you don't need to worry about calling
            it manually.
        """
        if self.connected:
            self.say("I'm powering down")
            self.logger.info(f'Shutting down {self.name}, please be patient and allow for exit.')

            if not self.observatory.close_dome():
                self.logger.critical('Unable to close dome!')

            # Park if needed
            if self.state not in ['parking', 'parked', 'sleeping', 'housekeeping']:
                # TODO(jamessynge): Figure out how to handle the situation where we have both
                # mount and dome, but this code is only checking for a mount.
                if self.observatory.mount.is_connected:
                    if not self.observatory.mount.is_parked:
                        self.logger.info("Parking mount")
                        self.park()

            if self.state == 'parking':
                if self.observatory.mount.is_connected:
                    if self.observatory.mount.is_parked:
                        self.logger.info("Mount is parked, setting state to 'parked'")
                        self.set_park()

            if self.observatory.mount and self.observatory.mount.is_parked is False:
                self.logger.info('Mount not parked, parking')
                self.observatory.mount.park()

            # Observatory shut down
            self.observatory.power_down()

            self.connected = False

            # Clear all the config items.
            self.logger.success("Power down complete")

    def reset_observing_run(self):
        """Reset an observing run loop. """
        self.logger.debug("Resetting observing run attempts")
        self._obs_run_retries = self.get_config('pocs.RETRY_ATTEMPTS', default=3)

    def observe_target(self,
                       observation: Optional[Observation] = None,
                       park_if_unsafe: bool = True):
        """Observe something! 🔭🌠

        Note: This is a long-running blocking method.

        This is a high-level method to call the various `observation` methods that
        allow for observing.
        """
        current_observation = observation or self.observatory.current_observation
        self.say(f"Observing {current_observation}")

        for pic_num in range(current_observation.min_nexp):
            self.logger.debug(f"Starting observation {pic_num} of {current_observation.min_nexp}")
            if self.is_safe() is False:
                self.say(f'Safety warning! Stopping {current_observation}.')
                if park_if_unsafe:
                    self.say('Parking the mount!')
                    self.observatory.mount.park()
                break

            if not self.observatory.mount.is_tracking:
                self.say(f'Mount is not tracking, stopping observations.')
                break

            # Do the observing, once per exptime (usually only one unless a compound observation).
            for exptime in current_observation.exptimes:
                self.logger.info(f'Starting {pic_num:03d} of {current_observation.min_nexp:03d} '
                                 f'with {exptime=}')
                try:
                    self.observatory.take_observation(blocking=True)
                except error.CameraNotFound:
                    self.logger.error('No cameras available, stopping observation')
                    break

                # Do processing in background.
                process_proc = Process(target=self.observatory.process_observation)
                process_proc.start()
                self.logger.debug(f'Processing {current_observation} on {process_proc.pid=}')

            pic_num += 1

    ################################################################################################
    # Safety Methods
    ################################################################################################

    def is_safe(self, no_warning=False, horizon='observe', ignore=None, park_if_not_safe=True):
        """Checks the safety flag of the system to determine if safe.

        This will check the weather station as well as various other environmental
        aspects of the system in order to determine if conditions are safe for operation.

        Note:
            This condition is called by the state machine during each transition.

        Args:
            no_warning (bool, optional): If a warning message should show in logs,
                defaults to False.
            horizon (str, optional): For nighttime check use given horizon,
                default 'observe'.
            ignore (abc.Iterable, optional): A list of safety checks to ignore when deciding
                whether it is safe or not. Valid list entries are: 'ac_power', 'is_dark',
                'good_weather', 'free_space_root' and 'free_space_images'. Useful e.g. when
                the state machine needs to wait for dark to enter the next state.
            park_if_not_safe (bool, optional): If True (default), will go to park if safety check
                fails. Set to False if you want to check the safety without sending the state
                machine to parking.
        Returns:
            bool: Latest safety flag.
        """
        if not self.connected:
            return False
        if ignore is None:
            ignore = list()

        is_safe_values = dict()

        # Check if AC power connected and return immediately if not.
        has_power = self.has_ac_power()
        if not has_power:
            return False

        is_safe_values['ac_power'] = has_power

        # Check if nighttime
        is_safe_values['is_dark'] = self.is_dark(horizon=horizon)

        # Check weather
        is_safe_values['good_weather'] = self.is_weather_safe()

        # Hard-drive space in root
        is_safe_values['free_space_root'] = self.has_free_space('/')

        # Hard-drive space in images directory.
        images_dir = self.get_config('directories.images')
        is_safe_values['free_space_images'] = self.has_free_space(images_dir)

        # Check overall safety, ignoring some checks if necessary
        missing_keys = [k for k in ignore if k not in is_safe_values.keys()]
        if missing_keys:
            self.logger.warning("Found the following invalid checks to ignore in "
                                f"is_safe: {missing_keys}. Valid keys are: "
                                f"{list(is_safe_values.keys())}.")
        safe = all([v for k, v in is_safe_values.items() if k not in ignore])

        # Insert safety reading
        self.db.insert_current('safety', is_safe_values)

        if not safe:
            if no_warning is False:
                self.logger.warning(f'Unsafe conditions: {is_safe_values}')

            # These states are already "parked" so don't send to parking.
            state_always_safe = self.get_state(self.state).is_always_safe
            if not state_always_safe and park_if_not_safe:
                self.logger.warning(f'Safety failed, setting {self.next_state=} to "parking"')
                self.next_state = 'parking'

        return safe

    def _in_simulator(self, key):
        """Checks the config server for the given simulator key value."""
        with suppress(KeyError):
            if key in self.get_config('simulator', default=list()):
                self.logger.debug(f'Using {key} simulator')
                return True

        return False

    def is_dark(self, horizon='observe'):
        """Is it dark

        Checks whether it is dark at the location provided. This checks for the config
        entry `location.flat_horizon` by default.

        Args:
            horizon (str, optional): Which horizon to use, 'flat', 'focus', or
                'observe' (default).

        Returns:
            bool: Is sun below horizon at location
        """
        # See if dark - we check this first because we want to know
        # the sun position even if using a simulator.
        is_dark = self.observatory.is_dark(horizon=horizon)
        self.logger.debug(f'Observatory is_dark: {is_dark}')

        if self._in_simulator('night'):
            return True

        self.logger.debug(f"Dark Check: {is_dark}")
        return is_dark

    def is_weather_safe(self, stale=180):
        """Determines whether current weather conditions are safe or not.

        Args:
            stale (int, optional): Number of seconds before record is stale, defaults to 180

        Returns:
            bool: Conditions are safe (True) or unsafe (False)

        """

        # Always assume False
        self.logger.debug("Checking weather safety")

        if self._in_simulator('weather'):
            return True

        # Get current weather readings from database
        is_safe = False
        try:
            record = self.db.get_current('weather')
            if record is None:
                return False

            is_safe = bool(record['data'].get('safe', False))

            timestamp = record['date'].replace(tzinfo=None)  # current_time is timezone naive
            age = (current_time().datetime - timestamp).total_seconds()

            self.logger.debug(f"Weather Safety: {is_safe=} {age=:.0f}s [{timestamp:%c}]")

        except Exception as e:  # pragma: no cover
            self.logger.error(f"No weather record in database: {e!r}")
        else:
            if age >= stale:
                self.logger.warning("Weather record looks stale, marking unsafe.")
                is_safe = False

        return is_safe

    def has_free_space(self, directory=None, required_space=0.25 * u.gigabyte,
                       low_space_percent=1.5):
        """Does hard drive have disk space (>= 0.5 GB).

        Args:
            directory (str, optional): The path to check free space on, the default
                `None` will check `$PANDIR`.
            required_space (u.gigabyte, optional): Amount of free space required
                for operation
            low_space_percent (float, optional): Give warning if space is less
                than this times the required space, default 1.5, i.e.,
                the logs will show a warning at `.25 GB * 1.5 = 0.375 GB`.

        Returns:
            bool: True if enough space
        """
        directory = directory or os.getenv('PANDIR')
        req_space = required_space.to(u.gigabyte)
        self._free_space = get_free_space(directory=directory)

        space_is_low = self._free_space.value <= (req_space.value * low_space_percent)

        # Explicitly cast to bool (instead of numpy.bool)
        has_space = bool(self._free_space.value >= req_space.value)

        if not has_space:
            self.logger.error(f'No disk space for directory={directory!r}: '
                              f'Free {self._free_space:.02f}\t req_space={req_space:.02f}')
        elif space_is_low:  # pragma: no cover
            self.logger.warning(f'Low disk space for directory={directory!r}: '
                                f'Free {self._free_space:.02f}\t req_space={req_space:.02f}')

        return has_space

    def has_ac_power(self, stale=90):
        """Check for system AC power.

        Power readings are done by the arduino and are placed in the metadata
        database. This method looks for entries saved with type `power` and key
        `main` the `current` collection. The method will also return False if
        the record is older than `stale` seconds.

        Args:
            stale (int, optional): Number of seconds before record is stale,
                defaults to 90 seconds.

        Returns:
            bool: True if system AC power is present.
        """
        # Always assume False
        self.logger.debug("Checking for AC power")
        has_power = False

        if self._in_simulator('power'):
            return True

        # Get current power readings from database
        try:
            record = self.db.get_current('power')
            if record is None:
                self.logger.warning(f'No mains "power" reading found in database.')

            has_power = False  # Assume not.
            for power_key in ['main', 'mains', 'ac_ok']:  # Legacy support.
                with suppress(KeyError):
                    has_power = bool(record['data'][power_key])

            date = record['date'].replace(tzinfo=None)  # current_time is timezone naive
            age = (current_time().datetime - date).total_seconds()

            self.logger.debug(f"Power Safety: {has_power} [{age:.0f}s old - {date:%m-%d %H:%M:%S}]")

        except (TypeError, KeyError) as e:
            self.logger.warning(f"No record found in DB: {e!r}")
        except Exception as e:  # pragma: no cover
            self.logger.error(f"Error checking weather: {e!r}")
        else:
            if age > stale:
                self.logger.warning("Power record looks stale, marking unsafe.")
                has_power = False

        if not has_power:
            self.logger.critical('AC power not detected.')

        return has_power

    ################################################################################################
    # Convenience Methods
    ################################################################################################

    def wait(self, delay=None):
        """ Send POCS to wait.

        Loops for `delay` number of seconds. If `delay` is more than 30.0 seconds,
        then check for status signals (which are updated every 60 seconds by default).

        Keyword Arguments:
            delay {float|None} -- Number of seconds to wait. If default `None`, look up value in
                config, otherwise 2.5 seconds.
        """
        if delay is None:  # pragma: no cover
            delay = self.get_config('wait_delay', default=2.5)

        sleep_timer = CountdownTimer(delay, name='POCSWait')
        self.logger.info(f'Starting a wait timer of {delay} seconds')
        while not sleep_timer.expired() and not self.interrupted:
            self.logger.debug(f'Wait timer: {sleep_timer.time_left():.02f} / {delay:.02f}')
            sleep_timer.sleep(max_sleep=30)

        is_expired = sleep_timer.expired()
        self.logger.debug(f'Leaving wait timer: expired={is_expired}')
        return is_expired


text:
/*
 * Global and Integration Styles Only
 * Component styles go in component
 */

body {
    padding: .5rem;
}

.CarFilter {
    margin-bottom: .5rem;
}

.CarList {
    margin-bottom: .5rem;
}

.CarForm {}


text:
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////

#include "tink/primitive_set.h"

#include <memory>
#include <string>
#include <thread>  // NOLINT(build/c++11)
#include <utility>
#include <vector>

#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "tink/crypto_format.h"
#include "tink/mac.h"
#include "tink/util/test_matchers.h"
#include "tink/util/test_util.h"
#include "proto/tink.pb.h"

using ::crypto::tink::test::DummyMac;
using ::crypto::tink::test::IsOk;
using ::google::crypto::tink::KeysetInfo;
using ::google::crypto::tink::KeyStatusType;
using ::google::crypto::tink::OutputPrefixType;
using ::testing::UnorderedElementsAreArray;

namespace crypto {
namespace tink {
namespace {

class PrimitiveSetTest : public ::testing::Test {
};

void add_primitives(PrimitiveSet<Mac>* primitive_set,
                    int key_id_offset,
                    int primitives_count) {
  for (int i = 0; i < primitives_count; i++) {
    int key_id = key_id_offset + i;
    KeysetInfo::KeyInfo key_info;
    key_info.set_output_prefix_type(OutputPrefixType::TINK);
    key_info.set_key_id(key_id);
    key_info.set_status(KeyStatusType::ENABLED);
    std::unique_ptr<Mac> mac(new DummyMac("dummy MAC"));
    auto add_result = primitive_set->AddPrimitive(std::move(mac), key_info);
    EXPECT_TRUE(add_result.ok()) << add_result.status();
  }
}

void access_primitives(PrimitiveSet<Mac>* primitive_set,
                       int key_id_offset,
                       int primitives_count) {
  for (int i = 0; i < primitives_count; i++) {
    int key_id = key_id_offset + i;
    KeysetInfo::KeyInfo key_info;
    key_info.set_output_prefix_type(OutputPrefixType::TINK);
    key_info.set_key_id(key_id);
    key_info.set_status(KeyStatusType::ENABLED);
    std::string prefix = CryptoFormat::GetOutputPrefix(key_info).value();
    auto get_result = primitive_set->get_primitives(prefix);
    EXPECT_TRUE(get_result.ok()) << get_result.status();
    EXPECT_GE(get_result.value()->size(), 1);
  }
}

TEST_F(PrimitiveSetTest, ConcurrentOperations) {
  PrimitiveSet<Mac> mac_set;
  int offset_a = 100;
  int offset_b = 150;
  int count = 100;

  // Add some primitives.
  std::thread add_primitives_a(add_primitives, &mac_set, offset_a, count);
  std::thread add_primitives_b(add_primitives, &mac_set, offset_b, count);
  add_primitives_a.join();
  add_primitives_b.join();

  // Access primitives.
  std::thread access_primitives_a(access_primitives, &mac_set, offset_a, count);
  std::thread access_primitives_b(access_primitives, &mac_set, offset_b, count);
  access_primitives_a.join();
  access_primitives_b.join();

  // Verify the common key ids added by both threads.
  for (int key_id = offset_a; key_id < offset_b + count; key_id++) {
    KeysetInfo::KeyInfo key_info;
    key_info.set_output_prefix_type(OutputPrefixType::TINK);
    key_info.set_key_id(key_id);
    key_info.set_status(KeyStatusType::ENABLED);
    std::string prefix = CryptoFormat::GetOutputPrefix(key_info).value();
    auto get_result = mac_set.get_primitives(prefix);
    EXPECT_TRUE(get_result.ok()) << get_result.status();
    auto macs = get_result.value();
    if (key_id >= offset_b && key_id < offset_a + count) {
      EXPECT_EQ(2, macs->size());  // overlapping key_id range
    } else {
      EXPECT_EQ(1, macs->size());
    }
  }
}

TEST_F(PrimitiveSetTest, Basic) {
  std::string mac_name_1 = "MAC#1";
  std::unique_ptr<Mac> mac_1(new DummyMac(mac_name_1));
  std::string mac_name_2 = "MAC#2";
  std::unique_ptr<Mac> mac_2(new DummyMac(mac_name_2));
  std::string mac_name_3 = "MAC#3";
  std::unique_ptr<Mac> mac_3(new DummyMac(mac_name_3));
  std::string mac_name_4 = "MAC#3";
  std::unique_ptr<Mac> mac_4(new DummyMac(mac_name_4));
  std::string mac_name_5 = "MAC#3";
  std::unique_ptr<Mac> mac_5(new DummyMac(mac_name_5));
  std::string mac_name_6 = "MAC#3";
  std::unique_ptr<Mac> mac_6(new DummyMac(mac_name_6));

  uint32_t key_id_1 = 1234543;
  KeysetInfo::KeyInfo key_1;
  key_1.set_output_prefix_type(OutputPrefixType::TINK);
  key_1.set_key_id(key_id_1);
  key_1.set_status(KeyStatusType::ENABLED);

  uint32_t key_id_2 = 7213743;
  KeysetInfo::KeyInfo key_2;
  key_2.set_output_prefix_type(OutputPrefixType::LEGACY);
  key_2.set_key_id(key_id_2);
  key_2.set_status(KeyStatusType::ENABLED);

  uint32_t key_id_3 = key_id_2;    // same id as key_2
  KeysetInfo::KeyInfo key_3;
  key_3.set_output_prefix_type(OutputPrefixType::TINK);
  key_3.set_key_id(key_id_3);
  key_3.set_status(KeyStatusType::ENABLED);

  uint32_t key_id_4 = 947327;
  KeysetInfo::KeyInfo key_4;
  key_4.set_output_prefix_type(OutputPrefixType::RAW);
  key_4.set_key_id(key_id_4);
  key_4.set_status(KeyStatusType::ENABLED);

  uint32_t key_id_5 = 529472;
  KeysetInfo::KeyInfo key_5;
  key_5.set_output_prefix_type(OutputPrefixType::RAW);
  key_5.set_key_id(key_id_5);
  key_5.set_status(KeyStatusType::ENABLED);

  uint32_t key_id_6 = key_id_1;    // same id as key_1
  KeysetInfo::KeyInfo key_6;
  key_6.set_output_prefix_type(OutputPrefixType::TINK);
  key_6.set_key_id(key_id_6);
  key_6.set_status(KeyStatusType::ENABLED);

  PrimitiveSet<Mac> primitive_set;
  EXPECT_TRUE(primitive_set.get_primary() == nullptr);
  EXPECT_EQ(absl::StatusCode::kNotFound,
            primitive_set.get_raw_primitives().status().code());
  EXPECT_EQ(absl::StatusCode::kNotFound,
            primitive_set.get_primitives("prefix").status().code());

  // Add all the primitives.
  auto add_primitive_result =
      primitive_set.AddPrimitive(std::move(mac_1), key_1);
  EXPECT_TRUE(add_primitive_result.ok()) << add_primitive_result.status();

  add_primitive_result = primitive_set.AddPrimitive(std::move(mac_2), key_2);
  EXPECT_TRUE(add_primitive_result.ok()) << add_primitive_result.status();

  add_primitive_result = primitive_set.AddPrimitive(std::move(mac_3), key_3);
  EXPECT_TRUE(add_primitive_result.ok()) << add_primitive_result.status();
  EXPECT_THAT(primitive_set.set_primary(add_primitive_result.value()), IsOk());

  add_primitive_result = primitive_set.AddPrimitive(std::move(mac_4), key_4);
  EXPECT_TRUE(add_primitive_result.ok()) << add_primitive_result.status();

  add_primitive_result = primitive_set.AddPrimitive(std::move(mac_5), key_5);
  EXPECT_TRUE(add_primitive_result.ok()) << add_primitive_result.status();

  add_primitive_result = primitive_set.AddPrimitive(std::move(mac_6), key_6);
  EXPECT_TRUE(add_primitive_result.ok()) << add_primitive_result.status();

  // Try adding a "consumed" unique_ptr as a primitive.
  add_primitive_result = primitive_set.AddPrimitive(std::move(mac_6), key_6);
  EXPECT_FALSE(add_primitive_result.ok());
  EXPECT_EQ(absl::StatusCode::kInvalidArgument,
            add_primitive_result.status().code());

  std::string data = "some data";

  {  // Check the primary.
    auto primary = primitive_set.get_primary();
    EXPECT_FALSE(primary == nullptr);
    EXPECT_EQ(KeyStatusType::ENABLED, primary->get_status());
    EXPECT_EQ(DummyMac(mac_name_3).ComputeMac(data).value(),
              primary->get_primitive().ComputeMac(data).value());
  }

  {  // Check raw primitives.
    auto& primitives = *(primitive_set.get_raw_primitives().value());
    EXPECT_EQ(2, primitives.size());
    EXPECT_EQ(DummyMac(mac_name_4).ComputeMac(data).value(),
              primitives[0]->get_primitive().ComputeMac(data).value());
    EXPECT_EQ(KeyStatusType::ENABLED, primitives[0]->get_status());
    EXPECT_EQ(key_4.key_id(), primitives[0]->get_key_id());
    EXPECT_EQ(OutputPrefixType::RAW, primitives[0]->get_output_prefix_type());
    EXPECT_EQ(DummyMac(mac_name_5).ComputeMac(data).value(),
              primitives[1]->get_primitive().ComputeMac(data).value());
    EXPECT_EQ(KeyStatusType::ENABLED, primitives[1]->get_status());
    EXPECT_EQ(key_5.key_id(), primitives[1]->get_key_id());
    EXPECT_EQ(OutputPrefixType::RAW, primitives[1]->get_output_prefix_type());
  }

  {  // Check Tink primitives.
    std::string prefix = CryptoFormat::GetOutputPrefix(key_1).value();
    auto& primitives = *(primitive_set.get_primitives(prefix).value());
    EXPECT_EQ(2, primitives.size());
    EXPECT_EQ(DummyMac(mac_name_1).ComputeMac(data).value(),
              primitives[0]->get_primitive().ComputeMac(data).value());
    EXPECT_EQ(KeyStatusType::ENABLED, primitives[0]->get_status());
    EXPECT_EQ(key_1.key_id(), primitives[0]->get_key_id());
    EXPECT_EQ(OutputPrefixType::TINK, primitives[0]->get_output_prefix_type());
    EXPECT_EQ(DummyMac(mac_name_6).ComputeMac(data).value(),
              primitives[1]->get_primitive().ComputeMac(data).value());
    EXPECT_EQ(KeyStatusType::ENABLED, primitives[1]->get_status());
    EXPECT_EQ(key_1.key_id(), primitives[1]->get_key_id());
    EXPECT_EQ(OutputPrefixType::TINK, primitives[1]->get_output_prefix_type());
  }

  {  // Check another Tink primitive.
    std::string prefix = CryptoFormat::GetOutputPrefix(key_3).value();
    auto& primitives = *(primitive_set.get_primitives(prefix).value());
    EXPECT_EQ(1, primitives.size());
    EXPECT_EQ(DummyMac(mac_name_3).ComputeMac(data).value(),
              primitives[0]->get_primitive().ComputeMac(data).value());
    EXPECT_EQ(KeyStatusType::ENABLED, primitives[0]->get_status());
    EXPECT_EQ(key_3.key_id(), primitives[0]->get_key_id());
    EXPECT_EQ(OutputPrefixType::TINK, primitives[0]->get_output_prefix_type());
  }

  {  // Check legacy primitive.
    std::string prefix = CryptoFormat::GetOutputPrefix(key_2).value();
    auto& primitives = *(primitive_set.get_primitives(prefix).value());
    EXPECT_EQ(1, primitives.size());
    EXPECT_EQ(DummyMac(mac_name_2).ComputeMac(data).value(),
              primitives[0]->get_primitive().ComputeMac(data).value());
    EXPECT_EQ(KeyStatusType::ENABLED, primitives[0]->get_status());
    EXPECT_EQ(key_2.key_id(), primitives[0]->get_key_id());
    EXPECT_EQ(OutputPrefixType::LEGACY,
              primitives[0]->get_output_prefix_type());
  }
}

TEST_F(PrimitiveSetTest, PrimaryKeyWithIdCollisions) {
  std::string mac_name_1 = "MAC#1";
  std::string mac_name_2 = "MAC#2";

  uint32_t key_id_1 = 1234543;
  KeysetInfo::KeyInfo key_info_1;
  key_info_1.set_key_id(key_id_1);
  key_info_1.set_status(KeyStatusType::ENABLED);

  uint32_t key_id_2 = key_id_1;    // same id as key_2
  KeysetInfo::KeyInfo key_info_2;
  key_info_2.set_key_id(key_id_2);
  key_info_2.set_status(KeyStatusType::ENABLED);

  {  // Test with RAW-keys.
    std::unique_ptr<Mac> mac_1(new DummyMac(mac_name_1));
    std::unique_ptr<Mac> mac_2(new DummyMac(mac_name_2));
    key_info_1.set_output_prefix_type(OutputPrefixType::RAW);
    key_info_2.set_output_prefix_type(OutputPrefixType::RAW);
    PrimitiveSet<Mac> primitive_set;
    EXPECT_TRUE(primitive_set.get_primary() == nullptr);

    // Add the first primitive, and set it as primary.
    auto add_primitive_result =
        primitive_set.AddPrimitive(std::move(mac_1), key_info_1);
    EXPECT_TRUE(add_primitive_result.ok()) << add_primitive_result.status();
    ASSERT_THAT(primitive_set.set_primary(add_primitive_result.value()),
                IsOk());

    std::string identifier = "";
    const auto& primitives =
        *(primitive_set.get_primitives(identifier).value());
    EXPECT_EQ(1, primitives.size());
    EXPECT_EQ(primitive_set.get_primary(), primitives[0].get());

    //  Adding another primitive should not invalidate the primary.
    add_primitive_result =
        primitive_set.AddPrimitive(std::move(mac_2), key_info_2);
    EXPECT_TRUE(add_primitive_result.ok()) << add_primitive_result.status();
    EXPECT_EQ(2, primitives.size());
    EXPECT_EQ(primitive_set.get_primary(), primitives[0].get());
  }

  {  // Test with TINK-keys.
    std::unique_ptr<Mac> mac_1(new DummyMac(mac_name_1));
    std::unique_ptr<Mac> mac_2(new DummyMac(mac_name_2));
    key_info_1.set_output_prefix_type(OutputPrefixType::TINK);
    key_info_2.set_output_prefix_type(OutputPrefixType::TINK);
    PrimitiveSet<Mac> primitive_set;
    EXPECT_TRUE(primitive_set.get_primary() == nullptr);

    // Add the first primitive, and set it as primary.
    auto add_primitive_result =
        primitive_set.AddPrimitive(std::move(mac_1), key_info_1);
    EXPECT_TRUE(add_primitive_result.ok()) << add_primitive_result.status();
    ASSERT_THAT(primitive_set.set_primary(add_primitive_result.value()),
                IsOk());

    std::string identifier = CryptoFormat::GetOutputPrefix(key_info_1).value();
    const auto& primitives =
        *(primitive_set.get_primitives(identifier).value());
    EXPECT_EQ(1, primitives.size());
    EXPECT_EQ(primitive_set.get_primary(), primitives[0].get());

    //  Adding another primitive should not invalidate the primary.
    add_primitive_result =
        primitive_set.AddPrimitive(std::move(mac_2), key_info_2);
    EXPECT_TRUE(add_primitive_result.ok()) << add_primitive_result.status();
    EXPECT_EQ(2, primitives.size());
    EXPECT_EQ(primitive_set.get_primary(), primitives[0].get());
  }

  {  // Test with LEGACY-keys.
    std::unique_ptr<Mac> mac_1(new DummyMac(mac_name_1));
    std::unique_ptr<Mac> mac_2(new DummyMac(mac_name_2));
    key_info_1.set_output_prefix_type(OutputPrefixType::LEGACY);
    key_info_2.set_output_prefix_type(OutputPrefixType::LEGACY);
    PrimitiveSet<Mac> primitive_set;
    EXPECT_TRUE(primitive_set.get_primary() == nullptr);

    // Add the first primitive, and set it as primary.
    auto add_primitive_result =
        primitive_set.AddPrimitive(std::move(mac_1), key_info_1);
    EXPECT_TRUE(add_primitive_result.ok()) << add_primitive_result.status();
    ASSERT_THAT(primitive_set.set_primary(add_primitive_result.value()),
                IsOk());

    std::string identifier = CryptoFormat::GetOutputPrefix(key_info_1).value();
    const auto& primitives =
        *(primitive_set.get_primitives(identifier).value());
    EXPECT_EQ(1, primitives.size());
    EXPECT_EQ(primitive_set.get_primary(), primitives[0].get());

    //  Adding another primitive should not invalidate the primary.
    add_primitive_result =
        primitive_set.AddPrimitive(std::move(mac_2), key_info_2);
    EXPECT_TRUE(add_primitive_result.ok()) << add_primitive_result.status();
    EXPECT_EQ(2, primitives.size());
    EXPECT_EQ(primitive_set.get_primary(), primitives[0].get());
  }
}

TEST_F(PrimitiveSetTest, DisabledKey) {
  std::string mac_name_1 = "MAC#1";
  std::unique_ptr<Mac> mac_1(new DummyMac(mac_name_1));

  uint32_t key_id_1 = 1234543;
  KeysetInfo::KeyInfo key_info_1;
  key_info_1.set_output_prefix_type(OutputPrefixType::TINK);
  key_info_1.set_key_id(key_id_1);
  key_info_1.set_status(KeyStatusType::DISABLED);

  PrimitiveSet<Mac> primitive_set;
  // Add all the primitives.
  auto add_primitive_result =
      primitive_set.AddPrimitive(std::move(mac_1), key_info_1);
  EXPECT_FALSE(add_primitive_result.ok());
}

KeysetInfo::KeyInfo CreateKey(uint32_t key_id,
                              OutputPrefixType output_prefix_type,
                              KeyStatusType key_status,
                              absl::string_view type_url) {
  KeysetInfo::KeyInfo key_info;
  key_info.set_output_prefix_type(output_prefix_type);
  key_info.set_key_id(key_id);
  key_info.set_status(key_status);
  std::string type_url_str(type_url);
  key_info.set_type_url(type_url_str);
  return key_info;
}

// Struct to hold MAC, Id and type_url.
struct MacIdAndTypeUrl {
  std::string mac;
  std::string id;
  std::string type_url;
};

bool operator==(const MacIdAndTypeUrl& first, const MacIdAndTypeUrl& other) {
  return first.mac == other.mac && first.id == other.id &&
         first.type_url == other.type_url;
}

TEST_F(PrimitiveSetTest, GetAll) {
  PrimitiveSet<Mac> pset;
  EXPECT_THAT(
      pset.AddPrimitive(
              absl::make_unique<DummyMac>("MAC1"),
              CreateKey(0x01010101, OutputPrefixType::TINK,
                        KeyStatusType::ENABLED, /*type_url=*/
                        "type.googleapis.com/google.crypto.tink.HmacKey"))
          .status(),
      IsOk());

  EXPECT_THAT(
      pset.AddPrimitive(
              absl::make_unique<DummyMac>("MAC2"),
              CreateKey(0x02020202, OutputPrefixType::TINK,
                        KeyStatusType::ENABLED, /*type_url=*/
                        "type.googleapis.com/google.crypto.tink.HmacKey"))
          .status(),
      IsOk());
  // Add primitive and make it primary.
  auto entry_or = pset.AddPrimitive(
      absl::make_unique<DummyMac>("MAC3"),
      CreateKey(0x02020202, OutputPrefixType::TINK,
                KeyStatusType::ENABLED, /*type_url=*/
                "type.googleapis.com/google.crypto.tink.AesCmacKey"));
  ASSERT_THAT(entry_or, IsOk());
  EXPECT_THAT(pset.set_primary(entry_or.value()), IsOk());

  EXPECT_THAT(
      pset.AddPrimitive(
              absl::make_unique<DummyMac>("MAC4"),
              CreateKey(0x02020202, OutputPrefixType::RAW,
                        KeyStatusType::ENABLED, /*type_url=*/
                        "type.googleapis.com/google.crypto.tink.AesCmacKey"))
          .status(),
      IsOk());

  EXPECT_THAT(
      pset.AddPrimitive(
              absl::make_unique<DummyMac>("MAC5"),
              CreateKey(0x01010101, OutputPrefixType::TINK,
                        KeyStatusType::ENABLED, /*type_url=*/
                        "type.googleapis.com/google.crypto.tink.AesCmacKey"))
          .status(),
      IsOk());

  std::vector<MacIdAndTypeUrl> mac_id_and_type;
  for (auto* entry : pset.get_all()) {
    auto mac_or = entry->get_primitive().ComputeMac("");
    ASSERT_THAT(mac_or, IsOk());
    mac_id_and_type.push_back({mac_or.value(), entry->get_identifier(),
                               std::string(entry->get_key_type_url())});
  }

  // In the following id part, the first byte is 1 for Tink.
  std::vector<MacIdAndTypeUrl> expected_result = {
      {/*mac=*/"13:0:DummyMac:MAC1", /*id=*/absl::StrCat("\1\1\1\1\1"),
       /*type_url=*/"type.googleapis.com/google.crypto.tink.HmacKey"},
      {/*mac=*/"13:0:DummyMac:MAC2", /*id=*/absl::StrCat("\1\2\2\2\2"),
       /*type_url=*/"type.googleapis.com/google.crypto.tink.HmacKey"},
      {/*mac=*/"13:0:DummyMac:MAC3", /*id=*/absl::StrCat("\1\2\2\2\2"),
       /*type_url=*/"type.googleapis.com/google.crypto.tink.AesCmacKey"},
      {/*mac=*/"13:0:DummyMac:MAC4", /*id=*/"",
       /*type_url=*/"type.googleapis.com/google.crypto.tink.AesCmacKey"},
      {/*mac=*/"13:0:DummyMac:MAC5", /*id=*/absl::StrCat("\1\1\1\1\1"),
       /*type_url=*/"type.googleapis.com/google.crypto.tink.AesCmacKey"}};

  EXPECT_THAT(mac_id_and_type, UnorderedElementsAreArray(expected_result));
}

}  // namespace
}  // namespace tink
}  // namespace crypto


text:
import { assert } from '@ember/debug';
import BaseHelper from '../-private/helpers/-format-base';

export default BaseHelper.extend({
  format(key, options) {
    assert('[ember-intl] translation lookup attempted but no translation key was provided.', key);

    return this.intl.t(key, options);
  },
});


text:
module CSVMagic
  class FileHandler

    attr_reader :path, :filename

    def initialize()
      @path = ::File.join(::Rails.root.to_s, "tmp")
    end

    def save_temp_file(tempfile)
      @filename = unique_filename
      ::FileUtils.copy_file(tempfile.path, file_path)
      ::File.exists?(file_path)
    end

    def load_file(filename)
      @filename = filename
      ::File.exist?(file_path)
    end

    def remove_file
      ::File.delete(file_path)
    end

    def file_path
      ::File.join(@path, @filename)
    end

    def unique_filename
      t = ::Time.now.strftime("%Y%m%d")
      "#{t}-#{$$}-#{rand(0x100000000000000).to_s(36)}"
    end

  end
end


text:
<?php

namespace DmMailerAdmin\Factory\Controller;

use Zend\Mvc\Controller\ControllerManager;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

use DmCommon\View\Helper\UserText as UserTextHelper;

use DmMailer\Manager\Template as TemplateManager;
use DmMailer\Repository\Template as TemplateRepository;

use DmMailerAdmin\Controller\TemplateController;

class Template implements FactoryInterface
{
    /**
     * @param ServiceLocatorInterface $serviceLocator
     *
     * @return TemplateController
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        if ($serviceLocator instanceof ControllerManager) {
            $serviceLocator = $serviceLocator->getServiceLocator();
        }

        /** @var TemplateRepository $templateRepository */
        $templateRepository = $serviceLocator->get('DmMailer\Repository\Template');

        /** @var TemplateManager $templateManager */
        $templateManager = $serviceLocator->get('DmMailer\Manager\Template');

        /** @var UserTextHelper $userText */
        $userText = $serviceLocator->get('DmMailerAdmin\View\Helper\UserText');

        $controller = new TemplateController(
            $templateRepository,
            $templateManager,
            $userText
        );

        return $controller;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--L
  Copyright SAIC, SAIC-Frederick.

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/caadapter/LICENSE.txt for details.
L-->

<wsdl:definitions targetNamespace="http://caadapter-dev.nci.nih.gov/caAdapterWS/ws/caAdapterTransformationService" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://caadapter-dev.nci.nih.gov/caAdapterWS/ws/caAdapterTransformationService" xmlns:intf="http://caadapter-dev.nci.nih.gov/caAdapterWS/ws/caAdapterTransformationService" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<!--WSDL created by Apache Axis version: 1.3
Built on Oct 05, 2005 (05:23:37 EDT)-->
 <wsdl:types>
  <schema targetNamespace="http://caadapter-dev.nci.nih.gov/caAdapterWS/ws/caAdapterTransformationService" xmlns="http://www.w3.org/2001/XMLSchema">
   <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
   <complexType name="ArrayOf_xsd_anyType">
    <complexContent>
     <restriction base="soapenc:Array">
      <attribute ref="soapenc:arrayType" wsdl:arrayType="xsd:anyType[]"/>
     </restriction>
    </complexContent>
   </complexType>
  </schema>
 </wsdl:types>

   <wsdl:message name="transformationServiceResponse">

      <wsdl:part name="transformationServiceReturn" type="impl:ArrayOf_xsd_anyType"/>

   </wsdl:message>

   <wsdl:message name="transformationServiceRequest">

      <wsdl:part name="mappingScenario" type="xsd:string"/>

      <wsdl:part name="csvString" type="xsd:string"/>

   </wsdl:message>

   <wsdl:portType name="caAdapterTransformationService">

      <wsdl:operation name="transformationService" parameterOrder="mappingScenario csvString">

         <wsdl:input message="impl:transformationServiceRequest" name="transformationServiceRequest"/>

         <wsdl:output message="impl:transformationServiceResponse" name="transformationServiceResponse"/>

      </wsdl:operation>

   </wsdl:portType>

   <wsdl:binding name="caAdapterTransformationServiceSoapBinding" type="impl:caAdapterTransformationService">

      <wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>

      <wsdl:operation name="transformationService">

         <wsdlsoap:operation soapAction=""/>

         <wsdl:input name="transformationServiceRequest">

            <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://ws.caadapter.nci.nih.gov" use="encoded"/>

         </wsdl:input>

         <wsdl:output name="transformationServiceResponse">

            <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://caadapter-dev.nci.nih.gov/caAdapterWS/ws/caAdapterTransformationService" use="encoded"/>

         </wsdl:output>

      </wsdl:operation>

   </wsdl:binding>

   <wsdl:service name="caAdapterTransformationServiceService">

      <wsdl:port binding="impl:caAdapterTransformationServiceSoapBinding" name="caAdapterTransformationService">

         <wsdlsoap:address location="http://caadapter-dev.nci.nih.gov/caAdapterWS/ws/caAdapterTransformationService"/>

      </wsdl:port>

   </wsdl:service>

</wsdl:definitions>


text:
from bemio.io.wamit import read
from bemio.io.output import write_hdf5
import os

import matplotlib.pyplot as plt
plt.close('all')
plt.interactive(True)

# Load the data
wamit_data = read(out_file='./wamit_data/oswec.out')
num_bodies = wamit_data.body[0].num_bodies

# Calculate IRF and plot
for i in xrange(num_bodies):
	wamit_data.body[i].calc_irf_excitation(t_end=30.)
	wamit_data.body[i].calc_irf_radiation(t_end=30.)
	# wamit_data.body[i].calc_ss_radiation()

# Save the data in HDF5 format
write_hdf5(wamit_data,out_file='oswec.h5')


text:
<Record>
<Term>Pargeverine</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Antispasmotic Agent</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Adjuvant/Antispasmotic Agent/Pargeverine</ClassificationPath>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Pargeverine</BroaderTerm>
<BroaderTerm>Adjuvant</BroaderTerm>
<BroaderTerm>Antispasmotic Agent</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<Synonym>PARGEVERINE</Synonym>
<Synonym>Pargeverine</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
package io.gravitee.am.gateway.reactor.impl;

import io.gravitee.am.gateway.handler.SecurityDomainRouterFactory;
import io.gravitee.am.gateway.handler.vertx.VertxSecurityDomainHandler;
import io.gravitee.am.gateway.reactor.Reactor;
import io.gravitee.am.gateway.reactor.SecurityDomainHandlerRegistry;
import io.gravitee.am.model.Domain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author Titouan COMPIEGNE (titouan.compiegne at graviteesource.com)
 * @author GraviteeSource Team
 */
public class DefaultSecurityDomainHandlerRegistry implements SecurityDomainHandlerRegistry {

    private static final Logger logger = LoggerFactory.getLogger(DefaultSecurityDomainHandlerRegistry.class);
    private final ConcurrentMap<String, VertxSecurityDomainHandler> handlers = new ConcurrentHashMap<>();

    @Autowired
    private SecurityDomainRouterFactory securityDomainRouterFactory;

    @Autowired
    private Reactor reactor;

    @Override
    public void create(Domain domain) {

        if(domain.isVhostMode()) {
            logger.info("Register a new domain [{}] on vhosts [{}]", domain.getId(), domain.getVhosts());
        } else {
            logger.info("Register a new domain [{}] on path [{}]", domain.getId(), domain.getPath());
        }

        VertxSecurityDomainHandler handler = create0(domain);
        if (handler != null) {
            try {
                handler.start();
                handlers.putIfAbsent(domain.getId(), handler);
                reactor.mountDomain(handler);
            } catch (Exception ex) {
                logger.error("Unable to register handler", ex);
            }
        }
    }

    @Override
    public void update(Domain domain) {

        VertxSecurityDomainHandler handler = handlers.get(domain.getId());
        if (handler != null) {
            remove(domain);
            create(domain);
        } else {
            create(domain);
        }
    }

    @Override
    public void remove(Domain domain) {

        VertxSecurityDomainHandler handler = handlers.remove(domain.getId());
        if (handler != null) {
            try {
                handler.stop();
                handlers.remove(domain.getId());
                reactor.unMountDomain(handler);
                logger.info("Security Domain has been unregistered");
            } catch (Exception e) {
                logger.error("Unable to un-register handler", e);
            }
        }
    }

    @Override
    public void clear() {
        handlers.forEach((s, handler) -> {
            try {
                handler.stop();
                handlers.remove(handler.getDomain().getId());
            } catch (Exception e) {
                logger.error("Unable to un-register handler", e);
            }
        });
    }

    @Override
    public Collection<VertxSecurityDomainHandler> getSecurityDomainHandlers() {
        return handlers.values();
    }

    private VertxSecurityDomainHandler create0(Domain domain) {
        return securityDomainRouterFactory.create(domain);
    }

}


text:
package main

import (
	"crypto/tls"
	"fmt"
	"io/ioutil"
	"log"
	"net/url"
	"os"

	"github.com/koding/kite"
	"github.com/koding/kite/config"
	"github.com/koding/kite/kontrol"
	"github.com/koding/multiconfig"
)

type Kontrol struct {
	Ip          string
	Port        int
	TLSCertFile string
	TLSKeyFile  string
	RegisterUrl string

	Initial    bool
	Username   string
	KontrolURL string

	PublicKeyFile  string
	PrivateKeyFile string

	Machines []string
	Version  string `default:"0.0.1"`

	Postgres struct {
		Host           string `default:"localhost"`
		Port           int    `default:"5432"`
		Username       string
		Password       string
		DBName         string
		ConnectTimeout int `default:"20"`
	}
}

func main() {
	conf := new(Kontrol)

	multiconfig.New().MustLoad(conf)

	publicKey, err := ioutil.ReadFile(conf.PublicKeyFile)
	if err != nil {
		log.Fatalf("cannot read public key file: %s", err.Error())
	}

	privateKey, err := ioutil.ReadFile(conf.PrivateKeyFile)
	if err != nil {
		log.Fatalf("cannot read private key file: %s", err.Error())
	}

	if conf.Initial {
		initialKey(conf, publicKey, privateKey)
		os.Exit(0)
	}

	kiteConf := config.MustGet()
	kiteConf.IP = conf.Ip
	kiteConf.Port = conf.Port

	k := kontrol.New(kiteConf, conf.Version)

	if conf.TLSCertFile != "" || conf.TLSKeyFile != "" {
		cert, err := tls.LoadX509KeyPair(conf.TLSCertFile, conf.TLSKeyFile)
		if err != nil {
			log.Fatalf("cannot load TLS certificate: %s", err.Error())
		}

		k.Kite.TLSConfig = &tls.Config{Certificates: []tls.Certificate{cert}}
	}

	if conf.RegisterUrl != "" {
		k.RegisterURL = conf.RegisterUrl
	}

	switch os.Getenv("KONTROL_STORAGE") {
	case "etcd":
		k.SetStorage(kontrol.NewEtcd(conf.Machines, k.Kite.Log))
	case "postgres":
		postgresConf := &kontrol.PostgresConfig{
			Host:     conf.Postgres.Host,
			Port:     conf.Postgres.Port,
			Username: conf.Postgres.Username,
			Password: conf.Postgres.Password,
			DBName:   conf.Postgres.DBName,
		}

		p := kontrol.NewPostgres(postgresConf, k.Kite.Log)
		k.SetStorage(p)
		k.SetKeyPairStorage(p)
	default:
		k.SetStorage(kontrol.NewEtcd(conf.Machines, k.Kite.Log))
	}

	k.AddKeyPair("", string(publicKey), string(privateKey))
	k.Kite.SetLogLevel(kite.DEBUG)
	k.Run()
}

func initialKey(kontrolConf *Kontrol, publicKey, privateKey []byte) {
	conf := config.New()

	if kontrolConf.Username == "" {
		log.Fatalln("empty username")
	}
	conf.Username = kontrolConf.Username

	_, err := url.Parse(kontrolConf.KontrolURL)
	if err != nil {
		log.Fatalln("cannot parse kontrol URL")
	}

	conf.KontrolURL = kontrolConf.KontrolURL

	k := kontrol.New(conf, kontrolConf.Version)
	k.AddKeyPair("", string(publicKey), string(privateKey))
	err = k.InitializeSelf()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("kite.key is written to ~/.kite/kite.key. You can see it with:\n\tkitectl showkey")
}


text:
layout: post
title: Wordpress vs. Drupal
tags:
- cms
- Drupal
- drupal
- vergleich
- vs
- wordpress
status: publish
type: post
published: true
meta:
  _edit_last: '1'
  _wp_old_slug: wordpress-vs--drupal
  dsq_thread_id: '794982998'
  better-related-: ''
---
Um ein Wordpress Modul nach Drupal zu portieren habe ich mir mal eben schnell eine Wordpress Installation eingerichtet. Ich war eigentlich angenehm überrascht, wie schnell das ganze installiert war. UI ist super schön gemacht. Gratulationen an dieser Stelle an die Designer von Wordpress. Sehr intuitiv. Wirklich gut.

So war ich dann auch angenehm überrascht, als ich schnell einen Blick in die Datenbank geworfen habe. Gerade mal 10 Tabellen wurden angelegt (Drupal im Vergleich legt ca. 40 an). Nach 5 Minuten lässt sich bereits mit Bloggen beginnen.

Wie bereits früher erwähnt, gibt es auch viele gute Themes für Wordpress. Will jemand somit wirklich nur ein Blog, ohne zu basteln und zu schrauben -> Wordpress. Wer halt eben mehr will als nur ein Blog -> Drupal.

Ich werde Wordpress auf jeden Fall weiter im Kopf behalten und es als Blogging Software weiterempfehlen.


text:
package gensupport

import (
	"bytes"
	"io"
	"io/ioutil"
	"reflect"
	"testing"
)

func TestContentSniffing(t *testing.T) {
	type testCase struct {
		data     []byte // the data to read from the Reader
		finalErr error  // error to return after data has been read

		wantContentType       string
		wantContentTypeResult bool
	}

	for _, tc := range []testCase{
		{
			data:                  []byte{0, 0, 0, 0},
			finalErr:              nil,
			wantContentType:       "application/octet-stream",
			wantContentTypeResult: true,
		},
		{
			data:                  []byte(""),
			finalErr:              nil,
			wantContentType:       "text/plain; charset=utf-8",
			wantContentTypeResult: true,
		},
		{
			data:                  []byte(""),
			finalErr:              io.ErrUnexpectedEOF,
			wantContentType:       "text/plain; charset=utf-8",
			wantContentTypeResult: false,
		},
		{
			data:                  []byte("abc"),
			finalErr:              nil,
			wantContentType:       "text/plain; charset=utf-8",
			wantContentTypeResult: true,
		},
		{
			data:                  []byte("abc"),
			finalErr:              io.ErrUnexpectedEOF,
			wantContentType:       "text/plain; charset=utf-8",
			wantContentTypeResult: false,
		},
		// The following examples contain more bytes than are buffered for sniffing.
		{
			data:                  bytes.Repeat([]byte("a"), 513),
			finalErr:              nil,
			wantContentType:       "text/plain; charset=utf-8",
			wantContentTypeResult: true,
		},
		{
			data:                  bytes.Repeat([]byte("a"), 513),
			finalErr:              io.ErrUnexpectedEOF,
			wantContentType:       "text/plain; charset=utf-8",
			wantContentTypeResult: true, // true because error is after first 512 bytes.
		},
	} {
		er := &errReader{buf: tc.data, err: tc.finalErr}

		sct := newContentSniffer(er)

		// Even if was an error during the first 512 bytes, we should still be able to read those bytes.
		buf, err := ioutil.ReadAll(sct)

		if !reflect.DeepEqual(buf, tc.data) {
			t.Fatalf("Failed reading buffer: got: %q; want:%q", buf, tc.data)
		}

		if err != tc.finalErr {
			t.Fatalf("Reading buffer error: got: %v; want: %v", err, tc.finalErr)
		}

		ct, ok := sct.ContentType()
		if ok != tc.wantContentTypeResult {
			t.Fatalf("Content type result got: %v; want: %v", ok, tc.wantContentTypeResult)
		}
		if ok && ct != tc.wantContentType {
			t.Fatalf("Content type got: %q; want: %q", ct, tc.wantContentType)
		}
	}
}

type staticContentTyper struct {
	io.Reader
}

func (sct staticContentTyper) ContentType() string {
	return "static content type"
}

func TestDetermineContentType(t *testing.T) {
	data := []byte("abc")
	rdr := func() io.Reader {
		return bytes.NewBuffer(data)
	}

	type testCase struct {
		r                  io.Reader
		explicitConentType string
		wantContentType    string
	}

	for _, tc := range []testCase{
		{
			r:               rdr(),
			wantContentType: "text/plain; charset=utf-8",
		},
		{
			r:               staticContentTyper{rdr()},
			wantContentType: "static content type",
		},
		{
			r:                  staticContentTyper{rdr()},
			explicitConentType: "explicit",
			wantContentType:    "explicit",
		},
	} {
		r, ctype := DetermineContentType(tc.r, tc.explicitConentType)
		got, err := ioutil.ReadAll(r)
		if err != nil {
			t.Fatalf("Failed reading buffer: %v", err)
		}
		if !reflect.DeepEqual(got, data) {
			t.Fatalf("Failed reading buffer: got: %q; want:%q", got, data)
		}

		if ctype != tc.wantContentType {
			t.Fatalf("Content type got: %q; want: %q", ctype, tc.wantContentType)
		}
	}
}


text:
#include <fstream>
#include <iomanip>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/smart_ptr/make_shared_object.hpp>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>

namespace logging = boost::log;
namespace src = boost::log::sources;
namespace expr = boost::log::expressions;
namespace sinks = boost::log::sinks;
namespace keywords = boost::log::keywords;

//[ example_tutorial_formatters_stream_manual
void init()
{
    typedef sinks::synchronous_sink< sinks::text_ostream_backend > text_sink;
    boost::shared_ptr< text_sink > sink = boost::make_shared< text_sink >();

    sink->locked_backend()->add_stream(
        boost::make_shared< std::ofstream >("sample.log"));

    sink->set_formatter
    (
        expr::stream
               // line id will be written in hex, 8-digits, zero-filled
            << std::hex << std::setw(8) << std::setfill('0') << expr::attr< unsigned int >("LineID")
            << ": <" << logging::trivial::severity
            << "> " << expr::smessage
    );

    logging::core::get()->add_sink(sink);
}
//]

int main(int, char*[])
{
    init();
    logging::add_common_attributes();

    using namespace logging::trivial;
    src::severity_logger< severity_level > lg;

    BOOST_LOG_SEV(lg, trace) << "A trace severity message";
    BOOST_LOG_SEV(lg, debug) << "A debug severity message";
    BOOST_LOG_SEV(lg, info) << "An informational severity message";
    BOOST_LOG_SEV(lg, warning) << "A warning severity message";
    BOOST_LOG_SEV(lg, error) << "An error severity message";
    BOOST_LOG_SEV(lg, fatal) << "A fatal severity message";

    return 0;
}


text:
/** Used for built-in method references. */
var objectProto = Object.prototype;

/**
 * Checks if `value` is likely a prototype object.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
 */
function isPrototype(value) {
    var Ctor = value && value.constructor,
        proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;

    return value === proto;
}

module.exports = isPrototype;


text:
package org.spongepowered.api.event;

/**
 * Represents an event that can be cancelled.
 */
public interface Cancellable {

    /**
     * Gets if the {@link Event} has been cancelled.
     *
     * @return Is this event cancelled
     */
    boolean isCancelled();

    /**
     * Sets the cancelled state of the {@link Event}.
     *
     *
This will also cancel any callbacks on the event if {@code cancel}
     * is {@code true}. However, no callbacks will be un-cancelled if
     * {@code cancel} is {@code false}.

     *
     * @param cancel The new cancelled state
     */
    void setCancelled(boolean cancel);

}


text:
require_relative 'result'

module Realm
  module Messaging
    class ResultFactory
      # Pass in MessageFactory objects for the commands and response messages -
      # these could be the same object if that is convenient for the client
      def initialize(commands: required(:commands), responses: required(:responses))
        @commands   = commands
        @responses  = responses
      end

      def new_unresolved_result(message)
        Result.new(responses: response_for(message.message_type_name))
      end

      private

      def response_for(message_type_name)
        @commands.determine_responses_to(message_type_name, from: @responses).tap do |responses|
          raise NoResponsesFoundError.new(message_type_name) if responses.none?
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>

<gora-otd>

    <family name="info"/>

    <family name="common"/>
    <family name="content"/>
    <family name="parsedContent"/>
    <family name="outlinks"/>

  <class name="org.apache.gora.examples.generated.Employee" keyClass="java.lang.String" table="Employee">
    <field name="name" family="info" qualifier="nm"/>
    <field name="dateOfBirth" family="info" qualifier="db"/>
    <field name="ssn" family="info" qualifier="sn"/>
    <field name="value" family="info" qualifier="vl"/>
    <field name="salary" family="info" qualifier="sl"/>
    <field name="boss" family="info" qualifier="bs"/>
    <field name="webpage" family="info" qualifier="wp"/>
  </class>

  <class name="org.apache.gora.examples.generated.TokenDatum" keyClass="java.lang.String">
    <field name="count" family="common" qualifier="count"/>
  </class>

</gora-otd>


text:
layout: post-by-category
category: slide-shows
title: "Data Intensive Tutorials"
permalink: /slide-shows/
comments: false
author_profile: true
---

## Online Presentations!

Presentations created using markdown.

{% for slides in site.slide-shows %}

{{ slides.title }}

{% endfor %}


text:
{% extends "base.html" %}
{% load static %}
{% load django_es_tags %}

{% block title %}¿Qué es Django?{% endblock %}

{% block content %}
{% ultima_version_django as ultima_version %}

Descarga Django

        	Django está disponible bajo la licencia libre BSD. Django requiere Python versión 2.4 o superior pero no depende de otras librerías de Python. Hay un par de maneras de obtener Django:

Opción 1. Obtener la última versión oficial de Django

        		La última versión oficial de Django es la {{ ultima_version }}. Para conseguirla descarga primero Django-{{ ultima_version }}.tar.gz. Después:

tar xzvf Django-{{ ultima_version }}.tar.gz
cd Django-{{ ultima_version }}
sudo python setup.py install

Opción 2. Obtener la última versión de desarrollo

        		La última y mejor versión de Django es la que está en el repositorio Subversion (sistema de control de versiones). Consíguela usando este comando de shell que requiere Git:

git clone https://github.com/django/django.git

Después de descargar Django

        		Lee la guía de instalación para más información.

        		Asegúrate de darte de alta en la lista de correo de Django en español y/o la lista de correo oficial en inglés donde otros usuarios de Django y los desarrolladores de Django se ayudan mutuamente. Lee el blog de django.es o suscríbete al feed RSS. También nos puedes seguir en Twitter.

{% endblock %}


text:
@interface CPJSONRPCRequest ()

@property (readwrite) NSString *method;
@property (readwrite) id params;
@property (readwrite) NSNumber *msgId;

@end

@implementation CPJSONRPCRequest

+ (instancetype)requestWithMethod:(NSString *)method params:(id)params msgId:(NSNumber *)msgId error:(NSError *__autoreleasing *)err {
    if (method == nil) {
        *err = [NSError errorWithDomain:CPJSONRPC_DOMAIN code:CPJSONRPCObjectErrorInvalidRequestNilMethod userInfo:nil];
        return nil;
    } else if (msgId == nil) {
        *err = [NSError errorWithDomain:CPJSONRPC_DOMAIN code:CPJSONRPCObjectErrorInvalidRequestNilId userInfo:nil];
        return nil;
    } else if (params != nil &&
               ![params isKindOfClass:[NSDictionary class]] &&
               ![params isKindOfClass:[NSArray class]]) {
        *err = [NSError errorWithDomain:CPJSONRPC_DOMAIN code:CPJSONRPCObjectErrorInvalidRequestInvalidParamsType userInfo:nil];
        return nil;
    }

    CPJSONRPCRequest *req = [[CPJSONRPCRequest alloc] init];
    req.method = method;
    req.params = params;
    req.msgId = msgId;
    return req;
}

- (NSString *)createJSONStringAndReturnError:(NSError *__autoreleasing *)err {
    NSMutableDictionary *req = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                JSON_RPC_VERSION, JSON_RPC_VERSION_KEY,
                                self.method, JSON_RPC_METHOD_KEY,
                                self.msgId, JSON_RPC_ID_KEY,
                                nil];
    if (self.params != nil) {
        [req setObject:self.params forKey:JSON_RPC_PARAMS_KEY];
    }
    return [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:req options:0 error:err]
                                 encoding:NSUTF8StringEncoding];
}

+ (NSDictionary *)ValidAndExpectedKeys {
    return [NSDictionary dictionaryWithObjectsAndKeys:
            [NSNumber numberWithBool:YES], JSON_RPC_VERSION_KEY,
            [NSNumber numberWithBool:YES], JSON_RPC_METHOD_KEY,
            [NSNumber numberWithBool:NO], JSON_RPC_PARAMS_KEY,
            [NSNumber numberWithBool:YES], JSON_RPC_ID_KEY,
            nil];
}

@end


text:
<?php

namespace Test\MainBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Test\MainBundle\Entity\Factura;
use Test\MainBundle\Form\FacturaType;

/**
 * Factura controller.
 *
 * @Route("/factura")
 */
class FacturaController extends Controller
{

    /**
     * Lists all Factura entities.
     *
     * @Route("/", name="factura")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('MainBundle:Factura')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new Factura entity.
     *
     * @Route("/", name="factura_create")
     * @Method("POST")
     * @Template("MainBundle:Factura:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity  = new Factura();
        $form = $this->createForm(new FacturaType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('factura_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Displays a form to create a new Factura entity.
     *
     * @Route("/new", name="factura_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Factura();
        $form   = $this->createForm(new FacturaType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a Factura entity.
     *
     * @Route("/{id}", name="factura_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MainBundle:Factura')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Factura entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Factura entity.
     *
     * @Route("/{id}/edit", name="factura_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MainBundle:Factura')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Factura entity.');
        }

        $editForm = $this->createForm(new FacturaType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing Factura entity.
     *
     * @Route("/{id}", name="factura_update")
     * @Method("PUT")
     * @Template("MainBundle:Factura:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MainBundle:Factura')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Factura entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new FacturaType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('factura_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a Factura entity.
     *
     * @Route("/{id}", name="factura_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('MainBundle:Factura')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Factura entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('factura'));
    }

    /**
     * Creates a form to delete a Factura entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}


text:
CLASS({
  package: 'foam.demos.wat',
  name: 'Slides',
  extends: 'foam.flow.Element',
  traits: ['foam.memento.MemorableTrait'],

  requires: [
    'foam.flow.Grid',
    'foam.graphics.ActionButtonCView'
  ],

  properties: [
    {
      name: 'slides',
      singular: 'slide',
      factory: function() { return []; }
    },
    {
      name: 'currentSlide',
      getter: function() { return this.slides[this.position-1]; },
      transient: true
    },
    {
      model_: 'IntProperty',
      name: 'position',
      memorable: true,
      displayWidth: 5,
      defaultValue: 1,
      preSet: function(o, n) {
        return Math.max(1, Math.min(n, this.slides.length));
      },
      postSet: function(_, p) {
        if ( this.$ ) this.setView(this.currentSlide());
      }
    }
  ],

  methods: {
    initHTML: function() {
      this.SUPER();
      this.position = 1;
    },
    fromElement: function(e) {
      var slides = [];
      for ( var i = 0 ; i < e.children.length ; i++ )
        if ( e.children[i].nodeName === 'slide' )
          slides.push(ViewFactoryProperty.ADAPT.defaultValue(null, e.children[i].innerHTML));
      this.slides = slides;
    },
    setView: function(v) {
      this.currentView_ && this.currentView_.destroy && this.currentView_.destroy();
      this.currentView_ = v;
      this.$.querySelector('deck').innerHTML = v.toHTML();
      v.initHTML();
    }
  },

  actions: [
    {
      name: 'back',
      label: '<',
      keyboardShortcuts: [ '<', 33 /* Page Down */ /*, 38*/ /* Down Arrow */ ],
      isEnabled: function() { return this.position > 1; },
      code: function() {
        this.position--;
      }
    },
    {
      name: 'forth',
      label: '>',
      keyboardShortcuts: [ '>', 34 /* Page Up */ /*, 40*/ /* Up Arrow */ ],
      isEnabled: function() { return this.position < this.slides.length; },
      code: function() {
        this.position++;
      }
    },
    {
      name: 'legend',
      label: '+',
      keyboardShortcuts: [ '+' ],
      code: function() { this.setView(this.Grid.create({cards: this.slides})); }
    }
  ],

  templates: [
    function CSS() {/*
      slides * {
        box-sizing: border-box;
      }
      slides, slides > deck, slides > controls {
        display: block;
      }
      slides > deck {
        border: 1px solid black;
        border: 1px solid gray;
        flex-grow: 1;
        overflow: auto;
        width: 100%;
      }
      slides > controls {
        background: #f5f5f0;
        border: 1px solid #aaa;
        flex-shrink: 0;
        font-size: 20px;
        height: 48px;
        padding: 10px;
        width: 100%;
        z-index: 2;
      }
      slides > controls input {
        font-size: 20px;
        margin: 0 10px 0 0;
        width: 50px;
      }
      slides > controls .of {
        margin-top: 2px;
      }
      slides > controls .actionButton-back {
        margin-left: 20px;
      }
      slides > controls .actionButtonCView {
        margin-top: -6px;
      }
    */},
    function toInnerHTML() {/*
      <deck></deck>
      <controls style="display:flex;display:-webkit-flex">
        $$position of {{this.slides.length}}
        $$legend{model_:'foam.graphics.ActionButtonCView', radius: 20, font: '28px Aria'}
        $$back{model_:'foam.graphics.ActionButtonCView',   radius: 20, font: '28px Aria'}
        $$forth{model_:'foam.graphics.ActionButtonCView',  radius: 20, font: '28px Aria'}
      </controls>
    */}
  ]
});


text:
exports.createXmlParser = function(base_handler, user_data) {
  var saxn = {};
  saxn.userData = user_data || {};

  if(typeof base_handler === 'function') {
    base_handler = base_handler();
  }

  var internal = {
    depth: 0,
    handlers: [ base_handler ],
  };

  internal.topHandler = function() { return this.handlers[ this.handlers.length - 1 ]; };
  internal.pushHandler = function(handler, depth) {
    handler.$depth = depth;
    this.handlers.push(handler);
  };
  internal.popHandler = function() { return this.handlers.pop(); }

  saxn.onOpenTag = function(tag) {
    var topHandler = internal.topHandler();
    // if there is a handler for this element, use it; otherwise go to wildcard
    var handlerEntry = topHandler[tag.name] ? topHandler[tag.name] : topHandler['*'];
    internal.depth++;
    if(handlerEntry) {
      if(typeof handlerEntry === 'function') {
        saxn.userData.depth = internal.depth;
        var newHandler = handlerEntry.apply( saxn.userData, [ tag ]);
        if(newHandler) {
          internal.pushHandler(newHandler, internal.depth);
        }
      }
      else {
        internal.pushHandler(handlerEntry, internal.depth);
      }
    }
  };

  saxn.onCloseTag = function(tag) {
    if(internal.topHandler().$depth === internal.depth) {
      var oldHandler = internal.popHandler();
      if(oldHandler.$end) {
        oldHandler.$end.apply(saxn.userData, [ tag ]);
      }
    }
    internal.depth--;
  };

  saxn.onText = function(text) {
    if(internal.topHandler().$text) {
      internal.topHandler().$text.apply(saxn.userData, [ text ]);
    }
  };

  saxn.onCData = function(data) {
    if(internal.topHandler().$cdata) {
      internal.topHandler().$cdata.apply(saxn.userData, [ data ]);
    }
  };

  saxn.onComment = function(comment) {
    if(internal.topHandler().$comment) {
      internal.topHandler().$comment.apply(saxn.userData, [ comment ]);
    }
  };

  return saxn;
};


text:
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards   #-}

module Snap.Snaplet.LiftAjax.Callback
    ( addCallback
    , handleRequest
    , handleGC
    , collector
    ) where

------------------------------------------------------------------------------
import           Control.Applicative
import           Control.Category
import           Control.Concurrent
import           Control.Concurrent.STM
import           Control.Monad.State
import qualified Data.Map                       as Map
import           Data.Maybe
import           Data.Time.Clock.POSIX
import           Prelude                        hiding (id, (.))
import           Snap.Core
import           Snap.Snaplet
import           Snap.Snaplet.LiftAjax.State
------------------------------------------------------------------------------

------------------------------------------------------------------------------
-- Callbacks
------------------------------------------------------------------------------

addCallback :: Handler b b () -> AjaxHandler b CallbackId
addCallback c = do
  touchPage
  callbackId <- newCallbackId
  pageId <- getPageId
  modifyCallbacks $ insertCallback pageId callbackId
  return callbackId
      where
        insertCallback pid cid = Map.insertWith Map.union pid $ Map.singleton cid c

runCallback :: AjaxHandler b ()
runCallback = do
  maybeCallbacks <- Map.lookup <$> getPageId <*> getCallbacks
  params <- getsRequest rqParams
  withTop' id $ fromMaybe pass $ do
    callbacks <- maybeCallbacks
    listToMaybe $ mapMaybe (flip Map.lookup callbacks . CallbackId) (Map.keys params)

handleRequest :: AjaxHandler b ()
handleRequest = do
  maybePageId <- getRqParam "pageId"
  maybe pass (setPageId . PageId) maybePageId
  touchPage
  maybeGC <- getRqParam "__lift__GC"
  when (isNothing maybeGC) runCallback

touchPage :: AjaxHandler b ()
touchPage = do
  pageId <- getPageId
  currentTime <- liftIO getPOSIXTime
  modifyHeartbeats $ Map.insert pageId currentTime

------------------------------------------------------------------------------
-- Garbage Collection
------------------------------------------------------------------------------

deletePage :: Ajax b -> PageId -> IO ()
deletePage (Ajax {..}) pageId =
  atomically $ do
    modifyTVar ajaxHeartbeats (Map.delete pageId)
    modifyTVar ajaxCallbacks  (Map.delete pageId)

stalePages :: Ajax b -> IO [PageId]
stalePages (Ajax {..}) = do
  currentTime <- getPOSIXTime
  heartbeats <- readTVarIO ajaxHeartbeats
  return $ map fst
             $ filter ((< currentTime - ajaxPageLifetime) . snd)
             $ Map.toList heartbeats

collect :: Ajax b -> IO ()
collect ajax = stalePages ajax >>= mapM_ (deletePage ajax)

collector :: Ajax b -> IO ()
collector ajax = go
    where go = collect ajax >> threadDelay (ajaxGCDelay ajax) >> go

handleGC :: AjaxHandler b ()
handleGC = get >>= liftIO . collect


text:
Todo list for the IView X Java library.

## General ##

- Make a list of features that the SDK supports for the RED-m eyetracker, that have not yet been implemented in this library
- Add package-info for serialization package
- Add package-info for serialization.json package
- Add tests for ETEventReceiver / ETSampleReceiver
- Add Eyetracking Server Version information to the Readme
- Add remove to ETChronologicCollection
- Add documentation to ETChronologicCollection iterator that it is unmodifiable
- Add pollrate information to ETRecorder (milliseconds)
- Add accuracy results for validation method in IViewX

## Future Improvements ##
 - Refactor ETRecorder and ETStreamService to use ExecutorService instead of raw threads

## Possible Future Features ##
 - Binary Serialization for ETEvent/ETSample using Protocol Buffers

## Bugs ##
 - Package documentation is not added for packages that only include a package-info.java and other packages


text:
set :stage, :production
set :stage_url, "http://www.glasgoweb.net"
server "XXX.XXX.XX.XXX", user: "SSHUSER", roles: %w{web app db}
set :deploy_to, "/home/glasgowe/public_html/ragm2"

############################################
# Setup Git
############################################

set :branch, "master"

############################################
# Extra Settings
############################################

#specify extra ssh options:

#set :ssh_options, {
#    auth_methods: %w(password),
#    password: 'password',
#    user: 'username',
#}

#specify a specific temp dir if user is jailed to home
#set :tmp_dir, "/path/to/custom/tmp"


text:
package core;

import javax.swing.JFrame;
import javax.swing.JLabel;

import crypt.*;
import frame.DrawGraph;
import frame.DrawTable;
import javax.swing.JPanel;

public class UtilLogic {

	public Options myOptions;
	String currentAlphabet;
	public UtilLogic() //constructor
	{
		myOptions = Options.getInstance();
	}
	Chiffre [] monos = {new Caesar(), new Multiplikativ(), new Affine()};
	String [] bezeichner = {"Caesar Chiffre", "Multiplikative Chiffre", "Affine Chiffre"};
	public JPanel initTable(String key, int cipher) {
		if(cipher > -1) {
                currentAlphabet = myOptions.getAlphabet();
		String verify = monos[cipher].encrypt(String.valueOf(currentAlphabet.charAt(0)), key);
		if (verify.length() != 1) {
			fehlerMeldung(verify);
                        return fehlerMeldung(verify);
		}
		else {

			//DrawTable ist jetzt ein JPanel
			 return new DrawTable(currentAlphabet, monos[cipher].encrypt(currentAlphabet, key),  key);
		}
                } else {return fehlerMeldung("Kein Werkzeug verfügbar!");}
	}

        protected JPanel fehlerMeldung(String text) {
		JPanel p = new JPanel();
		p.add(new JLabel(text));
                return p;
	}

	public JPanel initGraph(String key, int cipher) {
		int m = 1;
                int t = 0;
                if(cipher > -1) {
                currentAlphabet = myOptions.getAlphabet();
		String verify = monos[cipher].encrypt(String.valueOf(currentAlphabet.charAt(0)), key);
		if (verify.length() != 1) {
                        return fehlerMeldung(verify);
		}
		else {
			switch(cipher) {
                                case 0:     t = Tools.string2int(key, currentAlphabet); System.out.println(t); break;
                                case 1:     m = Tools.string2int(key, currentAlphabet); break;
                                case 2:     m = Tools.string2int(String.valueOf(key.charAt(0)), currentAlphabet);
                                            t = Tools.string2int(String.valueOf(key.charAt(1)), currentAlphabet); break;
                        }
                        return new DrawGraph(m, t);
			//DrawGraph jetzt im Konstruktor. Funktion wird von alleine initialisiert.
			//String function = "E(x) = " + a + "x + " + b;
			//DrawGraph.createAndShowGui(a, b, currentAlphabet.length(), bezeichner[cipher], function);
                    }
                } else {return fehlerMeldung("Kein Werkzeug verfügbar!");}
	}

	public static void main(String[] args)
    {
		UtilLogic u = new UtilLogic();
		u.initTable("c", 0);
		u.initGraph("c", 0);
    }
}