text:
from gevent import monkey
monkey.patch_all()

import socket
import yaml
from pysandesh.gen_py.sandesh.ttypes import SandeshLevel
from sandesh_common.vns.constants import ThreadPoolNames,\
    SERVICE_CONTRAIL_DATABASE
from sandesh_common.vns.ttypes import Module
from pysandesh.sandesh_logger import SandeshLogger
from pysandesh.gen_py.sandesh.ttypes import SandeshLevel
from database.sandesh.database.ttypes import CassandraThreadPoolStats,\
    CassandraStatusUVE, CassandraStatusData, CassandraThreadPoolStats,\
    CassandraCompactionTask, DatabaseUsageStats, DatabaseUsageInfo,\
    DatabaseUsage

class CassandraManager(object):
    def __init__(self, cassandra_repair_logdir, db_owner, table,
                 hostip, minimum_diskgb, db_port, db_jmx_port,
                 db_user, db_password, process_info_manager):
        self.cassandra_repair_logdir = cassandra_repair_logdir
        self._db_owner = db_owner
        self.table = table
        self.hostip = hostip
        self.hostname = socket.gethostname()
        self.minimum_diskgb = minimum_diskgb
        self.db_port = db_port
        self.db_jmx_port = db_jmx_port
        self.db_user = db_user
        self.db_password = db_password
        self.process_info_manager = process_info_manager
        # Initialize tpstat structures
        self.status_old = CassandraStatusData()
        self.status_old.cassandra_compaction_task = CassandraCompactionTask()
        self.status_old.thread_pool_stats = []

    def status(self):
        # TODO: here was a call to contrail-cassandra-status utility
        # it could stop cassandra's service but this tool is not present
        # and this is not allowed in micrioservices setup
        pass

    def repair(self):
        # TODO: here was a call to contrail-cassandra-repair utility
        # but this tool is not present in microservices
        pass

    def exec_cmd(self, cmd):
        # unit name must be equal to definition in main.py
        unit_name = 'cassandra'
        return self.process_info_manager.exec_cmd(unit_name, cmd)

    def _get_cassandra_config_option(self, config):
        # NOTE: assume that we have debian-based installation of cassandra
        raw_cfg = self.exec_cmd('cat /etc/cassandra/cassandra.yaml')
        cfg = yaml.load(raw_cfg)
        return cfg[config]

    def disk_free(self, cdir):
        output = self.exec_cmd("df " + cdir)
        _, _, used, available, _, _ = output.split("\n")[1].split()
        return (used, available)

    def disk_usage(self, cdir):
        output = self.exec_cmd("du -skl " + cdir)
        usage, _ = output.split()
        return usage

    def get_tp_status(self, tp_stats_output):
        tpstats_rows = tp_stats_output.split('\n')
        thread_pool_stats_list = []
        for row_index in range(1, len(tpstats_rows)):
            cols = tpstats_rows[row_index].split()
            # If tpstats len(cols) > 2, else we have reached the end
            if len(cols) > 2:
                if (cols[0] in ThreadPoolNames):
                    # Create a CassandraThreadPoolStats for matching entries
                    tpstat = CassandraThreadPoolStats()
                    tpstat.pool_name = cols[0]
                    tpstat.active = int(cols[1])
                    tpstat.pending = int(cols[2])
                    tpstat.all_time_blocked = int(cols[5])
                    thread_pool_stats_list.append(tpstat)
            else:
                # Reached end of tpstats, breaking because dropstats follows
                break
        return thread_pool_stats_list
    # end get_tp_status

    def has_cassandra_status_changed(self, current_status, old_status):
        if (current_status.cassandra_compaction_task.pending_compaction_tasks !=
                old_status.cassandra_compaction_task.pending_compaction_tasks):
            return True
        i = 0
        if len(current_status.thread_pool_stats) != \
            len(old_status.thread_pool_stats):
            return True
        while i < len(current_status.thread_pool_stats):
            if (current_status.thread_pool_stats[i].active != \
                old_status.thread_pool_stats[i].active or
                current_status.thread_pool_stats[i].pending != \
                old_status.thread_pool_stats[i].pending or
                current_status.thread_pool_stats[i].all_time_blocked != \
                old_status.thread_pool_stats[i].all_time_blocked):
                return True
            i += 1
        return False
    # end has_cassandra_status_changed

    def get_pending_compaction_count(self, pending_count_output):
        lines = pending_count_output.split('\n')
        pending_count = next(iter(
            [i for i in lines if i.startswith('pending tasks:')]), None)
        compaction_count_val = pending_count.strip()
        # output is of the format pending tasks: x
        pending_count_val = compaction_count_val.split(':')
        return int(pending_count_val[1].strip())
    # end get_pending_compaction_count

    def database_periodic(self, event_mgr):
        try:
            cassandra_data_dirs = self._get_cassandra_config_option("data_file_directories")
            cassandra_data_dir_exists = False
            total_disk_space_used = 0
            total_disk_space_available = 0
            total_db_size = 0
            for data_dir in cassandra_data_dirs:
                cdir = None
                if self._db_owner == 'analytics':
                    data = self.exec_cmd("ls -1 {}/".format(data_dir))
                    all_analytics_dirs = [
                        n.strip() for n in data.split('\n')
                                  if n.startswith("ContrailAnalyticsCql")]
                    if all_analytics_dirs:
                        # for now we assume the partition for all analytics
                        # clusters are the same
                        cdir = data_dir + '/' + all_analytics_dirs[0]
                elif self._db_owner == 'config':
                    cdir = data_dir
                if not cdir:
                    continue

                cassandra_data_dir_exists = True
                msg = "dir for " + self._db_owner + " is " + cdir
                event_mgr.msg_log(msg, level=SandeshLevel.SYS_DEBUG)
                (disk_space_used, disk_space_available) = (
                    self.disk_free(cdir))
                total_disk_space_used += int(disk_space_used)
                total_disk_space_available += int(disk_space_available)
                db_size = self.disk_usage(cdir)
                total_db_size += int(db_size)

            if not cassandra_data_dir_exists:
                event_mgr.fail_status_bits |= event_mgr.FAIL_STATUS_DISK_SPACE_NA
            else:
                event_mgr.fail_status_bits &= ~event_mgr.FAIL_STATUS_DISK_SPACE_NA

                disk_space = int(total_disk_space_used) + int(total_disk_space_available)
                if (disk_space / (1024 * 1024) < self.minimum_diskgb):
                    # TODO: here was a call that stops cassandra's service
                    event_mgr.fail_status_bits |= event_mgr.FAIL_STATUS_DISK_SPACE

                db_stat = DatabaseUsageStats()
                db_info = DatabaseUsageInfo()

                db_stat.disk_space_used_1k = int(total_disk_space_used)
                db_stat.disk_space_available_1k = int(total_disk_space_available)
                if self._db_owner == 'analytics':
                    db_stat.analytics_db_size_1k = int(total_db_size)
                elif self._db_owner == 'config':
                    db_stat.config_db_size_1k = int(total_db_size)

                db_info.name = self.hostname
                db_info.database_usage = [db_stat]
                usage_stat = DatabaseUsage(table=self.table, data=db_info)
                usage_stat.send()
        except Exception as e:
            msg = "Failed to get database usage: " + str(e)
            event_mgr.msg_log(msg, level=SandeshLevel.SYS_ERR)
            event_mgr.fail_status_bits |= event_mgr.FAIL_STATUS_DISK_SPACE_NA

        # just check connectivity
        if (self.db_user and self.db_password):
            cqlsh_cmd = "cqlsh -u {} -p {} {} {} -e quit".format(
                self.db_user, self.db_password, self.hostip, self.db_port)
        else:
            cqlsh_cmd = "cqlsh {} {} -e quit".format(self.hostip, self.db_port)
        try:
            self.exec_cmd(cqlsh_cmd)
            event_mgr.fail_status_bits &= ~event_mgr.FAIL_STATUS_SERVER_PORT
        except Exception as e:
            msg = "Failed to connect to database by CQL: " + str(e)
            event_mgr.msg_log(msg, level=SandeshLevel.SYS_ERR)
            event_mgr.fail_status_bits |= event_mgr.FAIL_STATUS_SERVER_PORT
        event_mgr.send_nodemgr_process_status()
        # Send cassandra nodetool information
        self.send_database_status(event_mgr)
        # Record cluster status and shut down cassandra if needed
        self.status()
    # end database_periodic

    def send_database_status(self, event_mgr):
        status = CassandraStatusData()
        status.cassandra_compaction_task = CassandraCompactionTask()
        # Get compactionstats
        base_cmd = "nodetool -p {}".format(self.db_jmx_port)
        try:
            res = self.exec_cmd(base_cmd + " compactionstats")
            status.cassandra_compaction_task.pending_compaction_tasks = \
                self.get_pending_compaction_count(res)
        except Exception as e:
            msg = "Failed to get nodetool compactionstats: {}".format(e)
            event_mgr.msg_log(msg, level=SandeshLevel.SYS_ERR)
            return

        # Get the tpstats value
        try:
            res = self.exec_cmd(base_cmd + " tpstats")
            status.thread_pool_stats = self.get_tp_status(res)
        except Exception as e:
            msg = "Failed to get nodetool tpstats {}".format(e)
            event_mgr.msg_log(msg, level=SandeshLevel.SYS_ERR)
            return

        status.name = self.hostname
        status_uve = CassandraStatusUVE(table=self.table, data=status)
        if self.has_cassandra_status_changed(status, self.status_old):
            # Assign status to status_old
            self.status_old.thread_pool_stats = status.thread_pool_stats
            self.status_old.cassandra_compaction_task.\
                pending_compaction_tasks = status.\
                cassandra_compaction_task.pending_compaction_tasks
            msg = 'Sending UVE: ' + str(status_uve)
            event_mgr.msg_log(msg, level=SandeshLevel.SYS_DEBUG)
            status_uve.send()
    # end send_database_status

    def get_failbits_nodespecific_desc(self, event_mgr, fail_status_bits):
        description = []
        if fail_status_bits & event_mgr.FAIL_STATUS_DISK_SPACE:
            description.append("Disk for DB is too low.")
        if fail_status_bits & event_mgr.FAIL_STATUS_SERVER_PORT:
            description.append("Cassandra state detected DOWN.")
        if fail_status_bits & event_mgr.FAIL_STATUS_DISK_SPACE_NA:
            description.append("Disk space for DB not retrievable.")
        return description


text:
package org.everit.persistence.querydsl.ecm;

/**
 * Exception that says if the database type could not have been determined based on the production
 * name and version of the database.
 */
public class UnknownDatabaseTypeException extends RuntimeException {

  /**
   * Serial version UID.
   */
  private static final long serialVersionUID = -7422125247222807335L;

  public UnknownDatabaseTypeException(final String message) {
    super(message);
  }

}

redpajama_set_name: RedPajamaGithub


text:
"""Test for the retaliate strategy."""

import axelrod

from .test_player import TestPlayer

C, D = axelrod.Actions.C, axelrod.Actions.D

class TestRetaliate(TestPlayer):

    name = "Retaliate (0.1)"
    player = axelrod.Retaliate
    expected_classifier = {
        'memory_depth': float('inf'),  # Long memory
        'stochastic': False,
        'makes_use_of': set(),
        'inspects_source': False,
        'manipulates_source': False,
        'manipulates_state': False
    }

    def test_strategy(self):
        """Starts by cooperating."""
        self.first_play_test(C)

    def test_effect_of_strategy(self):
        """If opponent has defected more than 10 percent of the time, defect."""
        P1 = axelrod.Retaliate()
        P2 = axelrod.Player()
        self.responses_test([C] * 4, [C] * 4, [C])
        self.responses_test([C, C, C, C, D], [C, C, C, D, C], [D])
        self.responses_test([C] * 6, [C] * 5 + [D], [D])

class TestLimitedRetaliate(TestPlayer):

    name = 'Limited Retaliate (0.1/20)'
    player = axelrod.LimitedRetaliate
    expected_classifier = {
        'memory_depth': float('inf'),  # Long memory
        'stochastic': False,
        'makes_use_of': set(),
        'inspects_source': False,
        'manipulates_source': False,
        'manipulates_state': False
    }

    def test_strategy(self):
        """Starts by cooperating."""
        self.first_play_test(C)

    def test_effect_of_strategy(self):
        P1 = axelrod.LimitedRetaliate()
        P2 = axelrod.Player()
        """If opponent has never defected, co-operate"""
        self.responses_test([C] * 4, [C] * 4, [C])
        P1.history = [C] * 5
        self.assertFalse(P1.retaliating)

        """If opponent has previously defected and won, defect and be retaliating"""
        self.responses_test([C, C, C, C, D], [C, C, C, D, C], [D])
        P1.history = [C, C, C, C, D, D]
        self.assertFalse(P1.retaliating)

        """If opponent has just defected and won, defect and be retaliating"""
        self.responses_test([C, C, C, C, C, C], [C, C, C, C, C, D], [D])
        P1.history = [C] * 6 + [D]
        self.assertFalse(P1.retaliating)

        """If I've hit the limit for retaliation attempts, co-operate"""
        P1.history = [C, C, C, C, D]
        P2.history = [C, C, C, D, C]
        P1.retaliation_count = 20
        self.assertEqual(P1.strategy(P2), C)
        self.assertFalse(P1.retaliating)

    def test_reset(self):
        P1 = axelrod.LimitedRetaliate()
        P1.history = [C, C, C, C, D]
        P1.retaliating = True
        P1.retaliation_count = 4
        P1.reset()
        self.assertEqual(P1.history, [])
        self.assertFalse(P1.retaliating)
        self.assertEqual(P1.retaliation_count, 0)


text:
package com.intellij.refactoring;

import java.io.IOException;

import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiClassOwner;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiReferenceExpression;
import com.intellij.refactoring.extractMethod.PrepareFailedException;
import com.intellij.refactoring.inline.InlineMethodProcessor;
import com.intellij.testFramework.LightCodeInsightTestCase;

/**
 * Is assumed to contain tests that include more than one refactoring into the processing.
 *
 * @author Denis Zhdanov
 * @since 1/12/12 2:35 PM
 */
public abstract class SequentialRefactoringTest extends LightCodeInsightTestCase {

  public void testFormattingAfterInlineExtractMethod() throws IOException, PrepareFailedException {
    String text =
      "public class BrokenAlignment {\n" +
      "\n" +
      "    public Object test() {\n" +
      "        if (System.currentTimeMillis() > 1) {\n" +
      "            if (System.currentTimeMillis() > 2) {\n" +
      "                getData();\n" +
      "            }\n" +
      "        }\n" +
      "        return \"hey\";\n" +
      "    }\n" +
      "\n" +
      "    private void getData() {\n" +
      "        String[] args = new String[]{};\n" +
      "        String result = \"data: \";\n" +
      "        int i = 0;\n" +
      "        while (i < args.length) {\n" +
      "            result += args[i];\n" +
      "            if (i % 2 == 0) {\n" +
      "                result += \", it's even!\";\n" +
      "            } else {\n" +
      "                System.out.println(\"It's odd :(\");\n" +
      "                break;\n" +
      "            }\n" +
      "        }\n" +
      "        int k = 1;\n" +
      "    }\n" +
      "\n" +
      "}";
    configureFromFileText("test.java", text);

    // Perform inline.
    final PsiClass clazz = ((PsiClassOwner)myFile).getClasses()[0];
    final PsiMethod[] methods = clazz.findMethodsByName("getData", false);
    final PsiReferenceExpression ref = (PsiReferenceExpression)myFile.findReferenceAt(text.indexOf("getData") + 1);
    final InlineMethodProcessor processor = new InlineMethodProcessor(getProject(), methods[0], ref, myEditor, false);
    processor.run();

    // Perform extract.
    final String currentText = myEditor.getDocument().getText();
    int start = currentText.indexOf("String[] args");
    int end = currentText.indexOf("\n", currentText.indexOf("int k"));
    myEditor.getSelectionModel().setSelection(start, end);
    ExtractMethodTest.performExtractMethod(true, true, myEditor, myFile, getProject());

    checkResultByText(text.replace("getData", "newMethod"));
  }
}


text:
using System;
using System.Collections.Generic;
using Aurora.Framework;
using C5;

namespace Aurora.DataManager.Migration.Migrators
{
    public class UserInfoMigrator_1 : Migrator
    {
        public UserInfoMigrator_1()
        {
            Version = new Version(0, 0, 1);
            MigrationName = "UserInfo";

            schema = new List<Rec<string, ColumnDefinition[], IndexDefinition[]>>();

            //
            // Change summery:
            //
            //   Add the new UserInfo table that replaces the GridUser and Presence tables
            //
            RemoveSchema("userinfo");
            AddSchema("userinfo", ColDefs(
                ColDef("UserID", ColumnTypes.String50),
                ColDef("RegionID", ColumnTypes.String50),
                ColDef("LastSeen", ColumnTypes.Integer30),
                ColDef("IsOnline", ColumnTypes.String36),
                ColDef("LastLogin", ColumnTypes.String50),
                ColDef("LastLogout", ColumnTypes.String50),
                ColDef("Info", ColumnTypes.String512),
                ColDef("CurrentRegionID", ColumnTypes.Char36),
                ColDef("CurrentPosition", ColumnTypes.String16),
                ColDef("CurrentLookat", ColumnTypes.String16),
                ColDef("HomeRegionID", ColumnTypes.Char36),
                ColDef("HomePosition", ColumnTypes.String16),
                ColDef("HomeLookat", ColumnTypes.String16)
            ), IndexDefs(
                IndexDef(new string[1]{ "UserID" }, IndexType.Primary)
            ));
        }

        protected override void DoCreateDefaults(IDataConnector genericData)
        {
            EnsureAllTablesInSchemaExist(genericData);
        }

        protected override bool DoValidate(IDataConnector genericData)
        {
            return TestThatAllTablesValidate(genericData);
        }

        protected override void DoMigrate(IDataConnector genericData)
        {
            DoCreateDefaults(genericData);
        }

        protected override void DoPrepareRestorePoint(IDataConnector genericData)
        {
            CopyAllTablesToTempVersions(genericData);
        }
    }
}


text:
namespace Ui {
class ManageCSVs;
}

class ManageCSVs : public QWidget
{
    Q_OBJECT

public:
    explicit ManageCSVs(QWidget *parent = 0);
    ~ManageCSVs();

signals:
    void windowClosed();

private slots:
    void on_selectFirst_clicked();
    void on_selectSecond_clicked();
    void on_mergeButton_clicked();
    void on_backButton_clicked();
    void cleanupab();
    void cleanuptmp();
    void save();

    void on_selectCSVFolderButton_clicked();
    void on_selectTwoColumnCSV_clicked();
    void on_exportButton_clicked();
    void importMergeQueue();

private:
    Ui::ManageCSVs *ui;

    QStringList selectFiles();
    QStringList convertToNewFormat(QString file);
    QHash<QString,QString> loadHighRes();
    QHash<QString,QString> loadAgents();

    QStringList imageFields;
    QStringList organismFields;
    void parseCSVs(const QStringList fileNames, bool identifierIsFileName, bool hasHeader, bool idInFirstColumn, const QString separator, const QString field);

    QString oldAgent;
    QString oldDeterm;
    QString oldImage;
    QString oldOrgan;
    QString oldSensu;
    QStringList oldHeaders;

    QString agent;
    QString determ;
    QString image;
    QString organ;
    QString sensu;
    QString names;
    QStringList headers;

    QStringList firstFileNames;
    QStringList secondFileNames;
    QString dbLastPublished;
    QStringList selectedCSVs;
    void resizeEvent(QResizeEvent *);
    void moveEvent(QMoveEvent *);
    void changeEvent(QEvent *event);
    bool screenPosLoaded;
};

#endif // MANAGECSVS_H


text:
On action validate: nothing, field, subform, form; if not valid -> no action (b/e)

Ajax actions: button, field change (grace? f/e and b/e?): either during change or after

Per-field JS settings (e.g. ajax behavior, default ajax behavior)

How to enable specifying text field width/height on the f/e?

Ajax update on any change (blur) - configurable per-field (path)? e.g. refresh_onblur_a_b_c


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
	STIX Phishing Indicator (Nested) Example

	Copyright (c) 2015, The MITRE Corporation. All rights reserved.
    The contents of this file are subject to the terms of the STIX License located at http://stix.mitre.org/about/termsofuse.html.

	This example demonstrates a more complex usage of STIX to represent indicators of phishing activity along with suggested courses of action, previous sightings, and handling guidance.

	It demonstrates the use of:

	   * STIX Indicators
	   * Simple STIX TTPs
	   * STIX Courses of Action
	   * Handling (inline)
	   * Confidence
	   * Sightings
	   * CybOX within STIX
	   * The CybOX Email Object (w/ Attachment)
	   * CybOX Patterns (condition="Contains")
	   * Controlled vocabularies

	Created by Sean Barnum
-->
<stix:STIX_Package xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:stix="http://stix.mitre.org/stix-1" xmlns:stixCommon="http://stix.mitre.org/common-1"
	xmlns:indicator="http://stix.mitre.org/Indicator-2" xmlns:TTP="http://stix.mitre.org/TTP-1"
	xmlns:COA="http://stix.mitre.org/CourseOfAction-1" xmlns:ciq="urn:oasis:names:tc:ciq:xpil:3"
	xmlns:n="urn:oasis:names:tc:ciq:xnl:3"
	xmlns:capec="http://stix.mitre.org/extensions/AP#CAPEC2.5-1"
	xmlns:marking="http://data-marking.mitre.org/Marking-1"
	xmlns:tlpMarking="http://data-marking.mitre.org/extensions/MarkingStructure#TLP-1"
	xmlns:stixVocabs="http://stix.mitre.org/default_vocabularies-1"
	xmlns:cybox="http://cybox.mitre.org/cybox-2" xmlns:cyboxCommon="http://cybox.mitre.org/common-2"
	xmlns:AddressObj="http://cybox.mitre.org/objects#AddressObject-2"
	xmlns:FileObj="http://cybox.mitre.org/objects#FileObject-2"
	xmlns:URIObj="http://cybox.mitre.org/objects#URIObject-2"
	xmlns:EmailMessageObj="http://cybox.mitre.org/objects#EmailMessageObject-2"
	xmlns:cyboxVocabs="http://cybox.mitre.org/default_vocabularies-2"
	xmlns:example="http://example.com/"
	xsi:schemaLocation="
http://stix.mitre.org/stix-1 ../stix_core.xsd
http://stix.mitre.org/common-1 ../stix_common.xsd
http://stix.mitre.org/Indicator-2 ../indicator.xsd
http://stix.mitre.org/TTP-1 ../ttp.xsd
http://stix.mitre.org/CourseOfAction-1 ../course_of_action.xsd
http://stix.mitre.org/extensions/AP#CAPEC2.5-1 ../extensions/attack_pattern/capec_2.5.xsd
http://data-marking.mitre.org/Marking-1  ../data_marking.xsd
http://data-marking.mitre.org/extensions/MarkingStructure#TLP-1 ../extensions/marking/tlp.xsd
http://stix.mitre.org/default_vocabularies-1 ../stix_default_vocabularies.xsd
http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.0/cybox_core.xsd
http://cybox.mitre.org/common-2 http://cybox.mitre.org/XMLSchema/common/2.0/cybox_common.xsd
http://cybox.mitre.org/objects#AddressObject-2 http://cybox.mitre.org/XMLSchema/objects/Address/2.0/Address_Object.xsd
http://cybox.mitre.org/objects#FileObject-2 http://cybox.mitre.org/XMLSchema/objects/File/2.0/File_Object.xsd
http://cybox.mitre.org/objects#URIObject-2 http://cybox.mitre.org/XMLSchema/objects/URI/2.0/URI_Object.xsd
http://cybox.mitre.org/objects#EmailMessageObject-2 http://cybox.mitre.org/XMLSchema/objects/Email_Message/2.0/Email_Message_Object.xsd
http://cybox.mitre.org/default_vocabularies-2 http://cybox.mitre.org/XMLSchema/default_vocabularies/2.0.0/cybox_default_vocabularies.xsd
"
	id="example:Indicator-ba1d406e-937c-414f-9231-6e1dbe64fe8b" version="1.0">
	<stix:STIX_Header>
		<stix:Title>STIX Phishing Indicator (Nested) Example</stix:Title>
		<stix:Package_Intent xsi:type="stixVocabs:PackageIntentVocab-1.0">Indicators -
			Phishing</stix:Package_Intent>
	</stix:STIX_Header>
	<stix:Indicators>

	  <stix:Indicator xsi:type="indicator:IndicatorType" id="example:Indicator-example-three-level-composition">
	    <indicator:Title>(Example) Three Level Composition Indicator</indicator:Title>
	    <indicator:Type xsi:type="stixVocabs:IndicatorTypeVocab-1.0">Malicious
	      E-mail</indicator:Type>
	    <indicator:Description></indicator:Description>

	    <indicator:Composite_Indicator_Expression operator="AND">
	      <indicator:Indicator>
	        <indicator:Composite_Indicator_Expression operator="OR">
	          <indicator:Indicator idref="example:Indicator-19e5d914-cc0e-478f-a523-b099a34383f7" />
	          <indicator:Indicator>
	            <indicator:Composite_Indicator_Expression operator="AND">
	              <indicator:Indicator idref="example:Indicator-19e5d914-cc0e-478f-a523-b099a34383f7" />
	              <indicator:Indicator idref="example:Indicator-19e5d914-cc0e-478f-a523-b099a34383f7" />
	              <indicator:Indicator idref="example:Indicator-19e5d914-cc0e-478f-a523-b099a34383f7" />
	            </indicator:Composite_Indicator_Expression>
	          </indicator:Indicator>
	          <indicator:Indicator idref="example:Indicator-19e5d914-cc0e-478f-a523-b099a34383f7" />
	          <indicator:Indicator idref="example:Indicator-19e5d914-cc0e-478f-a523-b099a34383f7" />
	        </indicator:Composite_Indicator_Expression>
	      </indicator:Indicator>
	      <indicator:Indicator idref="example:Indicator-19e5d914-cc0e-478f-a523-b099a34383f7" />
	      <indicator:Indicator idref="example:Indicator-19e5d914-cc0e-478f-a523-b099a34383f7" />
	    </indicator:Composite_Indicator_Expression>
	  </stix:Indicator>

		<stix:Indicator xsi:type="indicator:IndicatorType"
			id="example:Indicator-19e5d914-cc0e-478f-a523-b099a34383f7">
			<indicator:Title>"US-China" Phishing Indicator</indicator:Title>
			<indicator:Type xsi:type="stixVocabs:IndicatorTypeVocab-1.0">Malicious
				E-mail</indicator:Type>
			<indicator:Description>This is a cyber threat indicator for instances of "US-China" phishing attempts.</indicator:Description>
			<indicator:Valid_Time_Position>
				<indicator:Start_Time>2012-12-01T09:30:47Z</indicator:Start_Time>
				<indicator:End_Time>2013-02-01T09:30:47Z</indicator:End_Time>
			</indicator:Valid_Time_Position>
			<!-- The CybOX observable pattern is defined inline here for completeness. It could just as easily be included by reference.to save space. -->
			<indicator:Observable
				id="example:Observable-Pattern-5f1dedd3-ece3-4007-94cd-7d52784c1474">
				<cybox:Object id="example:Object-3a7aa9db-d082-447c-a422-293b78e24238">
					<cybox:Properties xsi:type="EmailMessageObj:EmailMessageObjectType">
						<EmailMessageObj:Header>
							<EmailMessageObj:From category="e-mail">
								<AddressObj:Address_Value condition="Contains"
									>@state.gov</AddressObj:Address_Value>
							</EmailMessageObj:From>
						</EmailMessageObj:Header>
					</cybox:Properties>
					<cybox:Related_Objects>
						<cybox:Related_Object>
							<cybox:Properties xsi:type="FileObj:FileObjectType">
								<FileObj:File_Extension>pdf</FileObj:File_Extension>
								<FileObj:Size_In_Bytes>87022</FileObj:Size_In_Bytes>
								<FileObj:Hashes>
									<cyboxCommon:Hash>
										<cyboxCommon:Type xsi:type="cyboxVocabs:HashNameVocab-1.0"
											>MD5</cyboxCommon:Type>
										<cyboxCommon:Simple_Hash_Value>cf2b3ad32a8a4cfb05e9dfc45875bd70</cyboxCommon:Simple_Hash_Value>
									</cyboxCommon:Hash>
								</FileObj:Hashes>
							</cybox:Properties>
							<cybox:Relationship xsi:type="cyboxVocabs:ObjectRelationshipVocab-1.0"
								>Contains</cybox:Relationship>
						</cybox:Related_Object>
					</cybox:Related_Objects>
				</cybox:Object>
			</indicator:Observable>
			<indicator:Indicated_TTP>
				<stixCommon:TTP xsi:type="TTP:TTPType">
					<TTP:Behavior>
						<TTP:Attack_Patterns>
							<TTP:Attack_Pattern capec_id="CAPEC-98">
								<TTP:Description>Phishing</TTP:Description>
							</TTP:Attack_Pattern>
						</TTP:Attack_Patterns>
					</TTP:Behavior>
				</stixCommon:TTP>
			</indicator:Indicated_TTP>
			<indicator:Kill_Chain_Phases>
				<stixCommon:Kill_Chain_Phase
					phase_id="example:TTP-79a0e041-9d5f-49bb-ada4-8322622b162d" name="Delivery"
					ordinality="3" kill_chain_id="example:TTP-af3e707f-2fb9-49e5-8c37-14026ca0a5ff"
					kill_chain_name="LMCO Kill Chain"/>
			</indicator:Kill_Chain_Phases>
			<indicator:Suggested_COAs>
				<indicator:Suggested_COA>
					<stixCommon:Course_Of_Action xsi:type="COA:CourseOfActionType"
						id="example:COA-346075c3-f3a4-48db-8e71-31b053f7838a">
						<COA:Stage xsi:type="stixVocabs:COAStageVocab-1.0">Remedy</COA:Stage>
						<COA:Type>Email Block</COA:Type>
						<COA:Description>Redirect and quarantine new matching email</COA:Description>
						<COA:Objective>
							<COA:Description>Prevent future instances of similar phishing attempts from reaching targeted recipients in order to eliminate possibility of compromise from targeted recipient falling for phishing lure.</COA:Description>
						</COA:Objective>
					</stixCommon:Course_Of_Action>
				</indicator:Suggested_COA>
				<indicator:Suggested_COA>
					<stixCommon:Course_Of_Action xsi:type="COA:CourseOfActionType"
						id="example:COA-a157f596-e1bf-4599-9dad-748511d68c3a">
						<COA:Stage xsi:type="stixVocabs:COAStageVocab-1.0">Remedy</COA:Stage>
						<COA:Type>Web Link Block</COA:Type>
						<COA:Description>Block malicous links on web proxies</COA:Description>
						<COA:Objective>
							<COA:Description>Prevent execution/navigation to known malicious web URLs.</COA:Description>
						</COA:Objective>
					</stixCommon:Course_Of_Action>
				</indicator:Suggested_COA>
				<indicator:Suggested_COA>
					<stixCommon:Course_Of_Action xsi:type="COA:CourseOfActionType"
						id="example:COA-0ac78ae1-661d-4845-ace1-a460c6075080">
						<COA:Stage xsi:type="stixVocabs:COAStageVocab-1.0">Remedy</COA:Stage>
						<COA:Type>Domain Traffic Block</COA:Type>
						<COA:Description>Block traffic to/from malicous domains via firewalls and DNS servers.</COA:Description>
						<COA:Objective>
							<COA:Description>Prevent any traffic (potentially containing malicious logic, data exfil, C2, etc.) to or from known malicious domains.</COA:Description>
						</COA:Objective>
					</stixCommon:Course_Of_Action>
				</indicator:Suggested_COA>
				<indicator:Suggested_COA>
					<stixCommon:Course_Of_Action xsi:type="COA:CourseOfActionType"
						id="example:COA-a09c17a4-d05e-48f3-b629-7de9a8c42162">
						<COA:Stage xsi:type="stixVocabs:COAStageVocab-1.0">Response</COA:Stage>
						<COA:Type>Malicous Email Cleanup</COA:Type>
						<COA:Description>Remove existing matching email from the mail servers</COA:Description>
						<COA:Objective>
							<COA:Description>Cleanup any known malicious emails from mail servers (potentially in Inboxes, Sent folders, Deleted folders, etc.) to prevent any future exploitation from those particular emails.</COA:Description>
						</COA:Objective>
					</stixCommon:Course_Of_Action>
				</indicator:Suggested_COA>
				<indicator:Suggested_COA>
					<stixCommon:Course_Of_Action xsi:type="COA:CourseOfActionType"
						id="example:COA-98cf40a2-e2be-448e-8474-c6e8c02628ef">
						<COA:Stage xsi:type="stixVocabs:COAStageVocab-1.0">Response</COA:Stage>
						<COA:Type>Phishing Target Identification</COA:Type>
						<COA:Description>Review mail logs to identify other targeted recipients</COA:Description>
						<COA:Objective>
							<COA:Description>Identify all targeted victims of a particular phishing campaign in order to enable notification and to support more strategic cyber threat intelligence activities (TTP characterization, Campaign analysis, ThreatActor attribution, etc.).</COA:Description>
						</COA:Objective>
					</stixCommon:Course_Of_Action>
				</indicator:Suggested_COA>
				<indicator:Suggested_COA>
					<stixCommon:Course_Of_Action xsi:type="COA:CourseOfActionType"
						id="example:COA-d470b8d7-3717-4a42-a3bc-3b57f1b2c300">
						<COA:Stage xsi:type="stixVocabs:COAStageVocab-1.0">Response</COA:Stage>
						<COA:Type>Phishing Target Notification</COA:Type>
						<COA:Description>Notify targeted recipients</COA:Description>
						<COA:Objective>
							<COA:Description>Notify all targeted victims of a particular phishing campaign to ensure they are aware they have been targeted and to help them understand how to avoid falling for phishing attacks.</COA:Description>
						</COA:Objective>
					</stixCommon:Course_Of_Action>
				</indicator:Suggested_COA>
				<indicator:Suggested_COA>
					<stixCommon:Course_Of_Action xsi:type="COA:CourseOfActionType"
						id="example:COA-e46d2565-754e-4ac3-9f44-2de1bfb1e71d">
						<COA:Stage xsi:type="stixVocabs:COAStageVocab-1.0">Response</COA:Stage>
						<COA:Type>Super Secret Proprietary Response</COA:Type>
						<COA:Description>Carry out some sensitive action that is applicable only within the environment of the affected organization.</COA:Description>
					</stixCommon:Course_Of_Action>
				</indicator:Suggested_COA>
			</indicator:Suggested_COAs>
			<indicator:Handling>
				<marking:Marking id="example:Marking-88501eee-135a-429b-9848-9a992456bd91"
					version="1.0">
					<marking:Controlled_Structure>ancestor-or-self::stix:Indicator//node()</marking:Controlled_Structure>
					<marking:Marking_Structure xsi:type="tlpMarking:TLPMarkingStructureType"
						marking_model_name="TLP" marking_model_ref="http://www.us-cert.gov/tlp/"
						color="GREEN"/>
				</marking:Marking>
				<marking:Marking id="example:Marking-d50a3e6b-142e-4b8e-92ab-2bb61a273d61"
					version="1.0">
					<marking:Controlled_Structure>ancestor-or-self::stix:Indicator//indicator:SuggestedCOAs/indicator:SuggestedCOA/stixCommon:Course_Of_Action[@id="example:COA-e46d2565-754e-4ac3-9f44-2de1bfb1e71d"]</marking:Controlled_Structure>
					<marking:Marking_Structure xsi:type="tlpMarking:TLPMarkingStructureType"
						marking_model_name="TLP" marking_model_ref="http://www.us-cert.gov/tlp/"
						color="RED"/>
				</marking:Marking>
			</indicator:Handling>
			<indicator:Confidence timestamp="2012-12-01T09:30:47Z">
				<stixCommon:Value vocab_reference="someURLtoConfidenceModelDescription.foo.com"
					>High</stixCommon:Value>
				<stixCommon:Source>MITRE</stixCommon:Source>
			</indicator:Confidence>
			<indicator:Sightings sightings_count="1">
				<indicator:Sighting timestamp="2012-12-01T09:30:47Z">
					<indicator:Source>MITRE</indicator:Source>
				</indicator:Sighting>
			</indicator:Sightings>
			<indicator:Producer>
				<stixCommon:Identity id="example:Org-ba680284-6865-44b4-ba36-dd48d402a589">
					<stixCommon:Name>MITRE</stixCommon:Name>
				</stixCommon:Identity>
				<stixCommon:Time>
					<cyboxCommon:Produced_Time>2012-12-01T09:30:47Z</cyboxCommon:Produced_Time>
				</stixCommon:Time>
			</indicator:Producer>
		</stix:Indicator>
	</stix:Indicators>
</stix:STIX_Package>


text:
<?php

namespace App\Models\Items;

use App\Models\Attributes\Generic\District;
use App\Models\Attributes\Generic\ItemCategory;
use App\Models\Attributes\Generic\ItemPurchaseType;
use App\Models\Attributes\Generic\ItemStatus;
use App\Models\Attributes\Generic\ItemTaxOffice;
use App\Models\Attributes\Generic\Municipality;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

/**
 * This is the item model class.
 *
 * @author Fábio Santos <ffsantos92@gmail.com>
 *
 * @property string           $code
 * @property ItemCategory     $category
 * @property ItemStatus       $status
 * @property ItemPurchaseType $purchaseType
 * @property ItemTaxOffice    $taxOffice
 * @property District         $district
 * @property Municipality     $municipality
 * @property string           $title
 * @property string           $slug
 * @property int              $year
 * @property float            $price
 * @property int|null         $vat
 * @property float|null       $lat
 * @property float|null       $lng
 * @property string           $images
 * @property Carbon           $preview_dt_start
 * @property Carbon           $preview_dt_end
 * @property Carbon           $acceptance_dt
 * @property Carbon           $opening_dt
 * @property Carbon           $updated_at
 * @property Carbon           $created_at
 */
class Item extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'items';

    /**
     * The primary key column.
     *
     * @var string
     */
    protected $primaryKey = 'code';

    /**
     * Indicate if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = true;

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = ['created_at', 'updated_at'];

    /**
     * Convert some columns to instances of Carbon.
     *
     * @return array
     */
    public function getDates()
    {
        return [
            'preview_dt_start',
            'preview_dt_end',
            'acceptance_dt',
            'opening_dt',
            'created_at',
        ];
    }

    /**
     * Get all of the owning itemable models.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
     */
    public function itemable()
    {
        return $this->morphTo();
    }

    /**
     * An item must have a category.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function category()
    {
        return $this->hasOne(ItemCategory::class, 'id', 'category_id');
    }

    /**
     * An item must have a status.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function status()
    {
        return $this->hasOne(ItemStatus::class, 'id', 'status_id');
    }

    /**
     * An item must have a purchase type.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function purchaseType()
    {
        return $this->hasOne(ItemPurchaseType::class, 'id', 'purchase_type_id');
    }

    /**
     * An item must be associated with a tax office.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function taxOffice()
    {
        return $this->hasOne(ItemTaxOffice::class, 'id', 'tax_office_id');
    }

    /**
     * An item should be associated with a district.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function district()
    {
        return $this->hasOne(District::class, 'id', 'district_id');
    }

    /**
     * An item should be associated with a municipality.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function municipality()
    {
        return $this->hasOne(Municipality::class, 'id', 'municipality_id');
    }

    /**
     * Scope a query to set polymorphic relation with this model.
     *
     * @param Builder $query
     * @param string  $code
     * @param Model   $model
     */
    public function scopeSetPolymorphicRelation(Builder $query, $code, $model)
    {
        return $query->where('code', $code)->update([
            'itemable_id'   => $model->getKey(),
            'itemable_type' => $model->getMorphClass(),
        ]);
    }

    /**
     * Scope a query to only include the latest items.
     *
     * @param Builder $query
     * @param int     $howMany
     *
     * @return Builder
     */
    public function scopeLatest(Builder $query, $howMany)
    {
        return $query->whereNotNull('itemable_id')
            ->orderBy('created_at', 'desc')->take($howMany);
    }

    /**
     * Scope a query to only include the items ending soon.
     *
     * @param Builder $query
     * @param int     $howMany
     *
     * @return Builder
     */
    public function scopeEndingSoon(Builder $query, $howMany)
    {
        // Get active items first
        $query->where('acceptance_dt', '>=', Carbon::now())
            ->whereNotNull('itemable_id');

        return $query->orderBy('acceptance_dt', 'asc')->take($howMany);
    }

    /**
     * Scope a query to only include the item with a given slug.
     *
     * @param Builder $query
     * @param string  $slug
     *
     * @return Builder
     */
    public function scopeWithSlug(Builder $query, $slug)
    {
        return $query->where('slug', $slug);
    }

    /**
     * Scope a query to only include active items.
     *
     * @param Builder $query
     *
     * @return Builder
     */
    public function scopeActive(Builder $query)
    {
        return $query->where('acceptance_dt', '>', Carbon::now());
    }

    /**
     * Scope a query to only include inactive items.
     *
     * @param Builder $query
     *
     * @return Builder
     */
    public function scopeInactive(Builder $query)
    {
        return $query->where('acceptance_dt', '<', Carbon::now());
    }

    /**
     * Scope a query to only include items of a given type.
     *
     * @param Builder $query
     * @param string  $itemType
     *
     * @return Builder
     */
    public function scopeOfType(Builder $query, $itemType)
    {
        if (isset($itemType)) {
            return $query->where('itemable_type', $itemType);
        } else {
            $query->whereNull('itemable_id');
        }
    }

    /**
     * Scope a query to only include items of a given district.
     *
     * @param Builder $query
     * @param int     $districtId
     *
     * @return Builder
     */
    public function scopeOfDistrict(Builder $query, $districtId)
    {
        if (isset($districtId)) {
            return $query->where('district_id', $districtId);
        }
    }

    /**
     * Scope a query to only include items of a given municipality.
     *
     * @param Builder $query
     * @param int     $municipalityId
     *
     * @return Builder
     */
    public function scopeOfMunicipality(Builder $query, $municipalityId)
    {
        if (isset($municipalityId)) {
            return $query->where('municipality_id', $municipalityId);
        }
    }

    /**
     * Scope a query to only include items of a given purchase type.
     *
     * @param Builder $query
     * @param int     $purchaseTypeId
     *
     * @return Builder
     */
    public function scopeOfPurchaseType(Builder $query, $purchaseTypeId)
    {
        if (isset($purchaseTypeId)) {
            return $query->where('purchase_type_id', $purchaseTypeId);
        }
    }

    /**
     * Scope a query to only include items with images.
     *
     * @param Builder $query
     *
     * @return Builder
     */
    public function scopeOnlyWithImages(Builder $query)
    {
        return $query->whereNotNull('images');
    }

    /**
     * Scope a query to only include active items that are not suspended.
     *
     * @param Builder $query
     *
     * @return Builder
     */
    public function scopeIgnoreSuspended(Builder $query)
    {
        // Get the id of the suspended status
        $id = ItemStatus::where('name', 'Suspenso')->pluck('id');

        return $query->where('status_id', '!=', $id);
    }

    /**
     * Scope a query to only include items of a given price range.
     *
     * @param Builder  $query
     * @param int|null $minPrice
     * @param int|null $maxPrice
     *
     * @return Builder
     */
    public function scopeBetweenPrices(Builder $query, $minPrice, $maxPrice)
    {
        // Get items between a price range
        if (isset($minPrice) && isset($maxPrice)) {
            return $query->where('price', '>=', $minPrice)->where('price', '<=', $maxPrice);
        }

        // Get items more expensive than
        if (isset($minPrice)) {
            return $query->where('price', '>=', $minPrice);
        }

        // Get items more cheap than
        if (isset($maxPrice)) {
            return $query->where('price', '<=', $maxPrice);
        }
    }

    /**
     * Scope a query to only include items that match with a given search query.
     *
     * @param Builder     $query
     * @param string|null $searchQuery
     *
     * @return Builder
     */
    public function scopeSearchQuery(Builder $query, $searchQuery)
    {
        if (isset($searchQuery)) {
            $searchQuery = preg_replace('/\pP/', '_', $searchQuery);

            // Split a single query in multiple queries
            $queries = preg_split('/\s+/', $searchQuery, null);
            foreach ($queries as $q) {
                $query->where('full_description', 'LIKE', '%'.$q.'%');
            }

            $query->orWhere('code', $searchQuery);
        }
    }

    /**
     * Set the item's title and slug.
     *
     * @param string $value
     *
     * @return string
     */
    public function setTitleAttribute($value)
    {
        $this->attributes['title'] = $value;

        if (Str::contains($value, $this->attributes['code'])) {
            $this->attributes['slug'] = Str::slug($value);
        } else {
            $newValue = $this->attributes['code'];
            $newValue .= "-$value";

            $this->attributes['slug'] = Str::slug($newValue);
        }
    }

    /**
     * Get the municipality where item is located.
     *
     * @return string
     */
    public function getMunicipalityAttribute()
    {
        return $this->municipality()->pluck('name');
    }

    /**
     * Get the district where item is located.
     *
     * @return string
     */
    public function getDistrictAttribute()
    {
        return $this->district()->pluck('name');
    }
}


text:
package com.glub.secureftp.client.cli;

import com.glub.secureftp.client.framework.*;

import java.io.*;

public class LCDCommand extends LocalCommand {
  public LCDCommand() {
    super("lcd", CommandID.LCD_COMMAND_ID, 0, 1,
          "[directory]", "change local working directory");
  }

  public SecureFTPError doIt() throws CommandException {
    SecureFTPError result = super.doIt();

    FTPSession session = SecureFTP.getFTPSession();
    PrintStream out = session.getPrintStream();

    if ( getArgs().size() == 0 ) {
      try {
        session.setLocalDir( (String)System.getProperty("user.home") );
        out.println("Local directory now \"" + session.getLocalDir() +
                           "\"");
      }
      catch (FileNotFoundException fnfe) {
        out.println("No such directory: " +
                     System.getProperty("user.home"));
      }
    }
    else {
      String newDirStr = (String)getArgs().get(0);

      File newDir = new File( newDirStr );

      if ( !newDir.isAbsolute() ) {
        newDir = new File( session.getLocalDir(), newDirStr );
      }

      try {
        if ( session.isGlobOn() ) {
          newDir = CLIUtil.globLocalPathForDir( newDir.getAbsolutePath() );
        }

        if ( newDir.exists() ) {
          session.setLocalDir( newDir.getCanonicalPath() );
          out.println("Local directory now \"" + session.getLocalDir() + "\"");
        }
        else {
          out.println("No such directory: " + newDirStr);
          result.setCode( SecureFTPError.NOT_A_DIRECTORY );
        }
      }
      catch (FileNotFoundException fnfe) {
        out.println("No such directory: " + newDirStr);
        result.setCode( SecureFTPError.NOT_A_DIRECTORY );
      }
      catch (IOException ioe) {}
    }

    return result;
  }
}


text:
#include "gm.h"
#include "sk_tool_utils.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkFontPriv.h"
#include "SkGradientShader.h"
#include "SkImageGenerator.h"
#include "SkPaint.h"
#include "SkPath.h"
#include "SkPathOps.h"
#include "SkPicture.h"
#include "SkPictureRecorder.h"
#include "SkTextUtils.h"

static void draw_vector_logo(SkCanvas* canvas, const SkRect& viewBox) {
    constexpr char kSkiaStr[] = "SKIA";
    constexpr SkScalar kGradientPad = .1f;
    constexpr SkScalar kVerticalSpacing = 0.25f;
    constexpr SkScalar kAccentScale = 1.20f;

    SkPaint paint;
    paint.setAntiAlias(true);

    SkFont font(sk_tool_utils::create_portable_typeface());
    font.setSubpixel(true);
    font.setEmbolden(true);

    SkPath path;
    SkRect iBox, skiBox, skiaBox;
    SkTextUtils::GetPath("SKI", 3, kUTF8_SkTextEncoding, 0, 0, font, &path);
    TightBounds(path, &skiBox);
    SkTextUtils::GetPath("I", 1, kUTF8_SkTextEncoding, 0, 0, font, &path);
    TightBounds(path, &iBox);
    iBox.offsetTo(skiBox.fRight - iBox.width(), iBox.fTop);

    const size_t textLen = strlen(kSkiaStr);
    SkTextUtils::GetPath(kSkiaStr, textLen, kUTF8_SkTextEncoding, 0, 0, font, &path);
    TightBounds(path, &skiaBox);
    skiaBox.outset(0, 2 * iBox.width() * (kVerticalSpacing + 1));

    const SkScalar accentSize = iBox.width() * kAccentScale;
    const SkScalar underlineY = iBox.bottom() +
        (kVerticalSpacing + SkScalarSqrt(3) / 2) * accentSize;
    SkMatrix m;
    m.setRectToRect(skiaBox, viewBox, SkMatrix::kFill_ScaleToFit);
    SkAutoCanvasRestore acr(canvas, true);
    canvas->concat(m);

    canvas->drawCircle(iBox.centerX(),
                       iBox.y() - (0.5f + kVerticalSpacing) * accentSize,
                       accentSize / 2,
                       paint);

    path.reset();
    path.moveTo(iBox.centerX() - accentSize / 2, iBox.bottom() + kVerticalSpacing * accentSize);
    path.rLineTo(accentSize, 0);
    path.lineTo(iBox.centerX(), underlineY);
    canvas->drawPath(path, paint);

    SkRect underlineRect = SkRect::MakeLTRB(iBox.centerX() - iBox.width() * accentSize * 3,
                                            underlineY,
                                            iBox.centerX(),
                                            underlineY + accentSize / 10);
    const SkPoint pts1[] = { SkPoint::Make(underlineRect.x(), 0),
                             SkPoint::Make(iBox.centerX(), 0) };
    const SkScalar pos1[] = { 0, 0.75f };
    const SkColor colors1[] = { SK_ColorTRANSPARENT, SK_ColorBLACK };
    SkASSERT(SK_ARRAY_COUNT(pos1) == SK_ARRAY_COUNT(colors1));
    paint.setShader(SkGradientShader::MakeLinear(pts1, colors1, pos1, SK_ARRAY_COUNT(pos1),
                                                 SkShader::kClamp_TileMode));
    canvas->drawRect(underlineRect, paint);

    const SkPoint pts2[] = { SkPoint::Make(iBox.x() - iBox.width() * kGradientPad, 0),
                             SkPoint::Make(iBox.right() + iBox.width() * kGradientPad, 0) };
    const SkScalar pos2[] = { 0, .01f, 1.0f/3, 1.0f/3, 2.0f/3, 2.0f/3, .99f, 1 };
    const SkColor colors2[] = {
        SK_ColorBLACK,
        0xffca5139,
        0xffca5139,
        0xff8dbd53,
        0xff8dbd53,
        0xff5460a5,
        0xff5460a5,
        SK_ColorBLACK
    };
    SkASSERT(SK_ARRAY_COUNT(pos2) == SK_ARRAY_COUNT(colors2));
    paint.setShader(SkGradientShader::MakeLinear(pts2, colors2, pos2, SK_ARRAY_COUNT(pos2),
                                                 SkShader::kClamp_TileMode));
    canvas->drawSimpleText(kSkiaStr, textLen, kUTF8_SkTextEncoding, 0, 0, font, paint);
}

// This GM exercises SkPictureImageGenerator features
// (in particular its matrix vs. bounds semantics).
class PictureGeneratorGM : public skiagm::GM {
protected:
    SkString onShortName() override {
        return SkString("pictureimagegenerator");
    }

    SkISize onISize() override {
        return SkISize::Make(1160, 860);
    }

    void onOnceBeforeDraw() override {
        const SkRect rect = SkRect::MakeWH(kPictureWidth, kPictureHeight);
        SkPictureRecorder recorder;
        SkCanvas* canvas = recorder.beginRecording(rect);
        draw_vector_logo(canvas, rect);
        fPicture = recorder.finishRecordingAsPicture();
    }

    void onDraw(SkCanvas* canvas) override {
        const struct {
            SkISize  size;
            SkScalar scaleX, scaleY;
            SkScalar opacity;
        } configs[] = {
            { SkISize::Make(200, 100), 1, 1, 1 },
            { SkISize::Make(200, 200), 1, 1, 1 },
            { SkISize::Make(200, 200), 1, 2, 1 },
            { SkISize::Make(400, 200), 2, 2, 1 },

            { SkISize::Make(200, 100), 1, 1, 0.9f  },
            { SkISize::Make(200, 200), 1, 1, 0.75f },
            { SkISize::Make(200, 200), 1, 2, 0.5f  },
            { SkISize::Make(400, 200), 2, 2, 0.25f },

            { SkISize::Make(200, 200), 0.5f, 1,    1 },
            { SkISize::Make(200, 200), 1,    0.5f, 1 },
            { SkISize::Make(200, 200), 0.5f, 0.5f, 1 },
            { SkISize::Make(200, 200), 2,    2,    1 },

            { SkISize::Make(200, 100), -1,  1, 1    },
            { SkISize::Make(200, 100),  1, -1, 1    },
            { SkISize::Make(200, 100), -1, -1, 1    },
            { SkISize::Make(200, 100), -1, -1, 0.5f },
        };

        auto srgbColorSpace = SkColorSpace::MakeSRGB();
        const unsigned kDrawsPerRow = 4;
        const SkScalar kDrawSize = 250;

        for (size_t i = 0; i < SK_ARRAY_COUNT(configs); ++i) {
            SkPaint p;
            p.setAlphaf(configs[i].opacity);

            SkMatrix m = SkMatrix::MakeScale(configs[i].scaleX, configs[i].scaleY);
            if (configs[i].scaleX < 0) {
                m.postTranslate(SkIntToScalar(configs[i].size.width()), 0);
            }
            if (configs[i].scaleY < 0) {
                m.postTranslate(0, SkIntToScalar(configs[i].size.height()));
            }
            std::unique_ptr<SkImageGenerator> gen =
                SkImageGenerator::MakeFromPicture(configs[i].size, fPicture, &m,
                                                 p.getAlpha() != 255 ? &p : nullptr,
                                                 SkImage::BitDepth::kU8, srgbColorSpace);

            SkImageInfo bmInfo = gen->getInfo().makeColorSpace(canvas->imageInfo().refColorSpace());

            SkBitmap bm;
            bm.allocPixels(bmInfo);
            SkAssertResult(gen->getPixels(bm.info(), bm.getPixels(), bm.rowBytes()));

            const SkScalar x = kDrawSize * (i % kDrawsPerRow);
            const SkScalar y = kDrawSize * (i / kDrawsPerRow);

            p.setColor(0xfff0f0f0);
            p.setAlphaf(1.0f);
            canvas->drawRect(SkRect::MakeXYWH(x, y,
                                              SkIntToScalar(bm.width()),
                                              SkIntToScalar(bm.height())), p);
            canvas->drawBitmap(bm, x, y);
        }
    }

private:
    sk_sp<SkPicture> fPicture;

    const SkScalar kPictureWidth = 200;
    const SkScalar kPictureHeight = 100;

    typedef skiagm::GM INHERITED;
};

DEF_GM(return new PictureGeneratorGM;)


text:
(function( $ ) {

var state = TestHelpers.tabs.state;

module( "tabs: events" );

test( "create", function() {
	expect( 10 );

	var element = $( "#tabs1" ),
		tabs = element.find( "ul li" ),
		panels = element.children( "div" );

	element.tabs({
		create: function( event, ui ) {
			equal( ui.tab.length, 1, "tab length" );
			strictEqual( ui.tab[ 0 ], tabs[ 0 ], "tab" );
			equal( ui.panel.length, 1, "panel length" );
			strictEqual( ui.panel[ 0 ], panels[ 0 ], "panel" );
		}
	});
	element.tabs( "destroy" );

	element.tabs({
		active: 2,
		create: function( event, ui ) {
			equal( ui.tab.length, 1, "tab length" );
			strictEqual( ui.tab[ 0 ], tabs[ 2 ], "tab" );
			equal( ui.panel.length, 1, "panel length" );
			strictEqual( ui.panel[ 0 ], panels[ 2 ], "panel" );
		}
	});
	element.tabs( "destroy" );

	element.tabs({
		active: false,
		collapsible: true,
		create: function( event, ui ) {
			equal( ui.tab.length, 0, "tab length" );
			equal( ui.panel.length, 0, "panel length" );
		}
	});
	element.tabs( "destroy" );
});

test( "beforeActivate", function() {
	expect( 38 );

	var element = $( "#tabs1" ).tabs({
			active: false,
			collapsible: true
		}),
		tabs = element.find( ".ui-tabs-nav li" ),
		anchors = tabs.find( ".ui-tabs-anchor" ),
		panels = element.find( ".ui-tabs-panel" );

	// from collapsed
	element.one( "tabsbeforeactivate", function( event, ui ) {
		ok( !( "originalEvent" in event ), "originalEvent" );
		equal( ui.oldTab.length, 0, "oldTab length" );
		equal( ui.oldPanel.length, 0, "oldPanel length" );
		equal( ui.newTab.length, 1, "newTab length" );
		strictEqual( ui.newTab[ 0 ], tabs[ 0 ], "newTab" );
		equal( ui.newPanel.length, 1, "newPanel length" );
		strictEqual( ui.newPanel[ 0 ], panels[ 0 ], "newPanel" );
		state( element, 0, 0, 0 );
	});
	element.tabs( "option", "active", 0 );
	state( element, 1, 0, 0 );

	// switching tabs
	element.one( "tabsbeforeactivate", function( event, ui ) {
		equal( event.originalEvent.type, "click", "originalEvent" );
		equal( ui.oldTab.length, 1, "oldTab length" );
		strictEqual( ui.oldTab[ 0 ], tabs[ 0 ], "oldTab" );
		equal( ui.oldPanel.length, 1, "oldPanel length" );
		strictEqual( ui.oldPanel[ 0 ], panels[ 0 ], "oldPanel" );
		equal( ui.newTab.length, 1, "newTab length" );
		strictEqual( ui.newTab[ 0 ], tabs[ 1 ], "newTab" );
		equal( ui.newPanel.length, 1, "newPanel length" );
		strictEqual( ui.newPanel[ 0 ], panels[ 1 ], "newPanel" );
		state( element, 1, 0, 0 );
	});
	anchors.eq( 1 ).click();
	state( element, 0, 1, 0 );

	// collapsing
	element.one( "tabsbeforeactivate", function( event, ui ) {
		ok( !( "originalEvent" in event ), "originalEvent" );
		equal( ui.oldTab.length, 1, "oldTab length" );
		strictEqual( ui.oldTab[ 0 ], tabs[ 1 ], "oldTab" );
		equal( ui.oldPanel.length, 1, "oldPanel length" );
		strictEqual( ui.oldPanel[ 0 ], panels[ 1 ], "oldPanel" );
		equal( ui.newTab.length, 0, "newTab length" );
		equal( ui.newPanel.length, 0, "newPanel length" );
		state( element, 0, 1, 0 );
	});
	element.tabs( "option", "active", false );
	state( element, 0, 0, 0 );

	// prevent activation
	element.one( "tabsbeforeactivate", function( event, ui ) {
		ok( !( "originalEvent" in event ), "originalEvent" );
		equal( ui.oldTab.length, 0, "oldTab length" );
		equal( ui.oldPanel.length, 0, "oldTab" );
		equal( ui.newTab.length, 1, "newTab length" );
		strictEqual( ui.newTab[ 0 ], tabs[ 1 ], "newTab" );
		equal( ui.newPanel.length, 1, "newPanel length" );
		strictEqual( ui.newPanel[ 0 ], panels[ 1 ], "newPanel" );
		event.preventDefault();
		state( element, 0, 0, 0 );
	});
	element.tabs( "option", "active", 1 );
	state( element, 0, 0, 0 );
});

test( "activate", function() {
	expect( 30 );

	var element = $( "#tabs1" ).tabs({
			active: false,
			collapsible: true
		}),
		tabs = element.find( ".ui-tabs-nav li" ),
		anchors = element.find( ".ui-tabs-anchor" ),
		panels = element.find( ".ui-tabs-panel" );

	// from collapsed
	element.one( "tabsactivate", function( event, ui ) {
		ok( !( "originalEvent" in event ), "originalEvent" );
		equal( ui.oldTab.length, 0, "oldTab length" );
		equal( ui.oldPanel.length, 0, "oldPanel length" );
		equal( ui.newTab.length, 1, "newTab length" );
		strictEqual( ui.newTab[ 0 ], tabs[ 0 ], "newTab" );
		equal( ui.newPanel.length, 1, "newPanel length" );
		strictEqual( ui.newPanel[ 0 ], panels[ 0 ], "newPanel" );
		state( element, 1, 0, 0 );
	});
	element.tabs( "option", "active", 0 );
	state( element, 1, 0, 0 );

	// switching tabs
	element.one( "tabsactivate", function( event, ui ) {
		equal( event.originalEvent.type, "click", "originalEvent" );
		equal( ui.oldTab.length, 1, "oldTab length" );
		strictEqual( ui.oldTab[ 0 ], tabs[ 0 ], "oldTab" );
		equal( ui.oldPanel.length, 1, "oldPanel length" );
		strictEqual( ui.oldPanel[ 0 ], panels[ 0 ], "oldPanel" );
		equal( ui.newTab.length, 1, "newTab length" );
		strictEqual( ui.newTab[ 0 ], tabs[ 1 ], "newTab" );
		equal( ui.newPanel.length, 1, "newPanel length" );
		strictEqual( ui.newPanel[ 0 ], panels[ 1 ], "newPanel" );
		state( element, 0, 1, 0 );
	});
	anchors.eq( 1 ).click();
	state( element, 0, 1, 0 );

	// collapsing
	element.one( "tabsactivate", function( event, ui ) {
		ok( !( "originalEvent" in event ), "originalEvent" );
		equal( ui.oldTab.length, 1, "oldTab length" );
		strictEqual( ui.oldTab[ 0 ], tabs[ 1 ], "oldTab" );
		equal( ui.oldPanel.length, 1, "oldPanel length" );
		strictEqual( ui.oldPanel[ 0 ], panels[ 1 ], "oldPanel" );
		equal( ui.newTab.length, 0, "newTab length" );
		equal( ui.newPanel.length, 0, "newPanel length" );
		state( element, 0, 0, 0 );
	});
	element.tabs( "option", "active", false );
	state( element, 0, 0, 0 );

	// prevent activation
	element.one( "tabsbeforeactivate", function( event ) {
		ok( true, "tabsbeforeactivate" );
		event.preventDefault();
	});
	element.one( "tabsactivate", function() {
		ok( false, "tabsactivate" );
	});
	element.tabs( "option", "active", 1 );
});

test( "beforeLoad", function() {
	expect( 32 );

	var tab, panelId, panel,
		element = $( "#tabs2" );

	// init
	element.one( "tabsbeforeload", function( event, ui ) {
		tab = element.find( ".ui-tabs-nav li" ).eq( 2 );
		panelId = tab.attr( "aria-controls" );
		panel = $( "#" + panelId );

		ok( !( "originalEvent" in event ), "originalEvent" );
		ok( "abort" in ui.jqXHR, "jqXHR" );
		ok( ui.ajaxSettings.url, "data/test.html", "ajaxSettings.url" );
		equal( ui.tab.length, 1, "tab length" );
		strictEqual( ui.tab[ 0 ], tab[ 0 ], "tab" );
		equal( ui.panel.length, 1, "panel length" );
		strictEqual( ui.panel[ 0 ], panel[ 0 ], "panel" );
		equal( ui.panel.html(), "", "panel html" );
		event.preventDefault();
		state( element, 0, 0, 1, 0, 0 );
	});
	element.tabs({ active: 2 });
	state( element, 0, 0, 1, 0, 0 );
	equal( panel.html(), "", "panel html after" );
	element.tabs( "destroy" );

	// .option()
	element.one( "tabsbeforeload", function( event, ui ) {
		tab = element.find( ".ui-tabs-nav li" ).eq( 2 );
		panelId = tab.attr( "aria-controls" );
		panel = $( "#" + panelId );

		ok( !( "originalEvent" in event ), "originalEvent" );
		ok( "abort" in ui.jqXHR, "jqXHR" );
		ok( ui.ajaxSettings.url, "data/test.html", "ajaxSettings.url" );
		equal( ui.tab.length, 1, "tab length" );
		strictEqual( ui.tab[ 0 ], tab[ 0 ], "tab" );
		equal( ui.panel.length, 1, "panel length" );
		strictEqual( ui.panel[ 0 ], panel[ 0 ], "panel" );
		equal( ui.panel.html(), "", "panel html" );
		event.preventDefault();
		state( element, 1, 0, 0, 0, 0 );
	});
	element.tabs();
	element.tabs( "option", "active", 2 );
	state( element, 0, 0, 1, 0, 0 );
	equal( panel.html(), "", "panel html after" );

	// click, change panel content
	element.one( "tabsbeforeload", function( event, ui ) {
		tab = element.find( ".ui-tabs-nav li" ).eq( 3 );
		panelId = tab.attr( "aria-controls" );
		panel = $( "#" + panelId );

		equal( event.originalEvent.type, "click", "originalEvent" );
		ok( "abort" in ui.jqXHR, "jqXHR" );
		ok( ui.ajaxSettings.url, "data/test.html", "ajaxSettings.url" );
		equal( ui.tab.length, 1, "tab length" );
		strictEqual( ui.tab[ 0 ], tab[ 0 ], "tab" );
		equal( ui.panel.length, 1, "panel length" );
		strictEqual( ui.panel[ 0 ], panel[ 0 ], "panel" );
		ui.panel.html( "
testing
" );
		event.preventDefault();
		state( element, 0, 0, 1, 0, 0 );
	});
	element.find( ".ui-tabs-nav .ui-tabs-anchor" ).eq( 3 ).click();
	state( element, 0, 0, 0, 1, 0 );
	// .toLowerCase() is needed to convert
 to
 in old IEs
	equal( panel.html().toLowerCase(), "
testing
", "panel html after" );
});

if ( $.uiBackCompat === false ) {
	asyncTest( "load", function() {
		expect( 21 );

		var tab, panelId, panel,
			element = $( "#tabs2" );

		// init
		element.one( "tabsload", function( event, ui ) {
			tab = element.find( ".ui-tabs-nav li" ).eq( 2 );
			panelId = tab.attr( "aria-controls" );
			panel = $( "#" + panelId );

			ok( !( "originalEvent" in event ), "originalEvent" );
			equal( ui.tab.length, 1, "tab length" );
			strictEqual( ui.tab[ 0 ], tab[ 0 ], "tab" );
			equal( ui.panel.length, 1, "panel length" );
			strictEqual( ui.panel[ 0 ], panel[ 0 ], "panel" );
			equal( ui.panel.find( "p" ).length, 1, "panel html" );
			state( element, 0, 0, 1, 0, 0 );
			tabsload1();
		});
		element.tabs({ active: 2 });

		function tabsload1() {
			// .option()
			element.one( "tabsload", function( event, ui ) {
				tab = element.find( ".ui-tabs-nav li" ).eq( 3 );
				panelId = tab.attr( "aria-controls" );
				panel = $( "#" + panelId );

				ok( !( "originalEvent" in event ), "originalEvent" );
				equal( ui.tab.length, 1, "tab length" );
				strictEqual( ui.tab[ 0 ], tab[ 0 ], "tab" );
				equal( ui.panel.length, 1, "panel length" );
				strictEqual( ui.panel[ 0 ], panel[ 0 ], "panel" );
				equal( ui.panel.find( "p" ).length, 1, "panel html" );
				state( element, 0, 0, 0, 1, 0 );
				tabsload2();
			});
			element.tabs( "option", "active", 3 );
		}

		function tabsload2() {
			// click, change panel content
			element.one( "tabsload", function( event, ui ) {
				tab = element.find( ".ui-tabs-nav li" ).eq( 4 );
				panelId = tab.attr( "aria-controls" );
				panel = $( "#" + panelId );

				equal( event.originalEvent.type, "click", "originalEvent" );
				equal( ui.tab.length, 1, "tab length" );
				strictEqual( ui.tab[ 0 ], tab[ 0 ], "tab" );
				equal( ui.panel.length, 1, "panel length" );
				strictEqual( ui.panel[ 0 ], panel[ 0 ], "panel" );
				equal( ui.panel.find( "p" ).length, 1, "panel html" );
				state( element, 0, 0, 0, 0, 1 );
				start();
			});
			element.find( ".ui-tabs-nav .ui-tabs-anchor" ).eq( 4 ).click();
		}
	});
}

}( jQuery ) );


text:
package se.jlim.jfake.expression;

import se.jlim.jfake.Token;

/**
 *
 * @author Jonas Lund
 */
public class IndexExpression extends CompoundExpression implements Generator {

	public IndexExpression(Token tok, Expression... subs) {
		super(tok, subs);
	}

	@Override
	public Generator compileExpr() {
		return this;
	}

	@Override
	public Long size() {
		return compiled[1].size();
	}

	@Override
	public Object get(long idx, long seed) {
		Object idxValue=compiled[1].get(idx, seed);
		if (idxValue instanceof Long)  {
			return compiled[0].get((Long)idxValue, seed);
		}
		throw new RuntimeException("Index value "+idxValue+" not usable as an index at "+tok.toString());
	}

	@Override
	public String toString() {
		return subs[0]+"["+subs[1]+"]";
	}
}


text:
title: Penny Bainbridge
headshot: vGrFSB8
gender: female
submitted: false
graduated: 2015
course:
 - Psychlogy

links:
  - type: CastingCallPro
    href: "https://www.castingcallpro.com/uk/actor/profile/penelope-bainbridge"
---


text:
package org.red5.server.net.rtmp.event;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import org.apache.mina.core.buffer.IoBuffer;
import org.red5.server.api.stream.IStreamPacket;
import org.red5.server.stream.IStreamData;

public class AudioData extends BaseEvent implements IStreamData<AudioData>, IStreamPacket {

	private static final long serialVersionUID = -4102940670913999407L;

	protected IoBuffer data;

	/**
	 * Data type
	 */
	private byte dataType = TYPE_AUDIO_DATA;

	/** Constructs a new AudioData. */
	public AudioData() {
		this(IoBuffer.allocate(0).flip());
	}

	public AudioData(IoBuffer data) {
		super(Type.STREAM_DATA);
		setData(data);
	}

	/**
	 * Create audio data event with given data buffer
	 * @param data Audio data
	 * @param copy true to use a copy of the data or false to use reference
	 */
	public AudioData(IoBuffer data, boolean copy) {
		super(Type.STREAM_DATA);
		if (copy) {
			byte[] array = new byte[data.limit()];
			data.mark();
			data.get(array);
			data.reset();
			setData(array);
		} else {
			setData(data);
		}
	}

	/** {@inheritDoc} */
	@Override
	public byte getDataType() {
		return dataType;
	}

	public void setDataType(byte dataType) {
		this.dataType = dataType;
	}

	/** {@inheritDoc} */
	public IoBuffer getData() {
		return data;
	}

	public void setData(IoBuffer data) {
		this.data = data;
	}

	public void setData(byte[] data) {
		this.data = IoBuffer.allocate(data.length);
		this.data.put(data).flip();
	}

	/** {@inheritDoc} */
	@Override
	protected void releaseInternal() {
		if (data != null) {
			data.free();
			data = null;
		}
	}

	@Override
	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		super.readExternal(in);
		byte[] byteBuf = (byte[]) in.readObject();
		if (byteBuf != null) {
			data = IoBuffer.allocate(0);
			data.setAutoExpand(true);
			SerializeUtils.ByteArrayToByteBuffer(byteBuf, data);
		}
	}

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		super.writeExternal(out);
		if (data != null) {
			out.writeObject(SerializeUtils.ByteBufferToByteArray(data));
		} else {
			out.writeObject(null);
		}
	}

	/**
	 * Duplicate this message / event.
	 *
	 * @return  duplicated event
	 */
	public AudioData duplicate() throws IOException, ClassNotFoundException {
		AudioData result = new AudioData();
		// serialize
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		writeExternal(oos);
		oos.close();
		// convert to byte array
		byte[] buf = baos.toByteArray();
		baos.close();
		// create input streams
		ByteArrayInputStream bais = new ByteArrayInputStream(buf);
		ObjectInputStream ois = new ObjectInputStream(bais);
		// deserialize
		result.readExternal(ois);
		ois.close();
		bais.close();
		// clone the header if there is one
		if (header != null) {
			result.setHeader(header.clone());
		}
		return result;
	}

	/** {@inheritDoc} */
	@Override
	public String toString() {
		return String.format("Audio - ts: %s length: %s", getTimestamp(), (data != null ? data.limit() : '0'));
	}

}


text:
<?php

namespace Tests\Command;

use AppBundle\Command\AddUserCommand;
use AppBundle\Entity\User;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Tester\CommandTester;

class AddUserCommandTest extends KernelTestCase
{
    private $userData = [
        'username' => 'chuck_norris',
        'password' => 'foobar',
        'email' => 'chuck@norris.com',
        'full-name' => 'Chuck Norris',
    ];

    /**
     * @dataProvider isAdminDataProvider
     *
     * This test provides all the arguments required by the command, so the
     * command runs non-interactively and it won't ask for any argument.
     */
    public function testCreateUserNonInteractive($isAdmin)
    {
        $input = $this->userData;
        if ($isAdmin) {
            $input['--admin'] = 1;
        }
        $this->executeCommand($input);

        $this->assertUserCreated($isAdmin);
    }

    /**
     * This is used to execute the same test twice: first for normal users
     * (isAdmin = false) and then for admin users (isAdmin = true).
     */
    public function isAdminDataProvider()
    {
        yield [false];
        yield [true];
    }

    /**
     * This helper method checks that the user was correctly created and saved
     * in the database.
     */
    private function assertUserCreated($isAdmin)
    {
        $container = self::$kernel->getContainer();

        /** @var User $user */
        $user = $container->get('doctrine')->getRepository(User::class)->findOneByEmail($this->userData['email']);
        $this->assertNotNull($user);

        $this->assertSame($this->userData['full-name'], $user->getFullName());
        $this->assertSame($this->userData['username'], $user->getUsername());
        $this->assertTrue($container->get('security.password_encoder')->isPasswordValid($user, $this->userData['password']));
        $this->assertSame($isAdmin ? ['ROLE_ADMIN'] : ['ROLE_USER'], $user->getRoles());
    }

    /**
     * This helper method abstracts the boilerplate code needed to test the
     * execution of a command.
     *
     * @param array $arguments All the arguments passed when executing the command
     * @param array $inputs    The (optional) answers given to the command when it asks for the value of the missing arguments
     */
    private function executeCommand(array $arguments, array $inputs = [])
    {
        self::bootKernel();

        $command = new AddUserCommand();
        $command->setApplication(new Application(self::$kernel));

        $commandTester = new CommandTester($command);
        $commandTester->setInputs($inputs);
        $commandTester->execute($arguments);
    }
}


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/include/usr/eeprom/eeprom_const.H $                       */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2019,2022                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#ifndef __EEPROM_CONST_H
#define __EEPROM_CONST_H

#include <targeting/common/entitypath.H>
#include <string.h>

namespace EEPROM
{

// Hardware OP related consts
constexpr uint16_t EEPROM_PAGE_SIZE = 0x100;
constexpr uint8_t  EEPROM_DEVADDR_INC = 2;
constexpr uint8_t MAX_BYTE_ADDR = 2;
constexpr uint8_t EEPROM_MAX_RETRIES = 2;

// EECACHE OP related consts
constexpr uint32_t UNSET_INTERNAL_OFFSET_VALUE = 0xFFFFFFFF;
constexpr uint32_t UNSET_END_OF_CACHE_VALUE = UNSET_INTERNAL_OFFSET_VALUE;
constexpr uint8_t  NUM_BYTE_UNIQUE_ID = 13;
constexpr uint32_t END_OF_CACHE_PTR_EMPTY = 0x00000000;
// Note: If any of these max eeprom counts are changed here, also change them in
// src/build/tools/eecache_editor.pl and src/build/simics/eecache-gen.py
constexpr uint8_t  MAX_EEPROMS_VERSION_1 = 50;
constexpr uint8_t  MAX_EEPROMS_VERSION_2 = 100;
constexpr uint8_t  MAX_EEPROMS_LATEST = MAX_EEPROMS_VERSION_2;

/**
 * @brief Enumerations to link EEPROM types to EEPROM's chip number behind
 *        a device
*/
enum EEPROM_ROLE
{
    VPD_PRIMARY   = 0,  // MVPD from Primary SEEPROM
    VPD_BACKUP    = 1,  // MVPD from Backup SEEPROM
    SBE_PRIMARY   = 2,
    SBE_BACKUP    = 3,
    WOF_DATA      = 4,  // WOF data from Backup SEEPROM
    LAST_CHIP_TYPE,

    VPD_AUTO      = 6,  // Autoselect primary vs. backup (not a real role, only
                        // used at the device driver layer)

    // Test-only eeprom_role
    // Keep after LAST_CHIP_TYPE so these are not cached/used in production code
    SPARE_TEST    = 10,

    // Useful Enums
    INVALID_CHIP_TYPE = LAST_CHIP_TYPE,
    FIRST_CHIP_TYPE = VPD_PRIMARY
};

/**
 * @brief Enumerations to help direct if we want to perform a given op on
 *        the eeprom cache in pnor or the actual hardware. Or if the user
 *        wants the driver to determine if reading from cache is possible, and
 *        if not fall back to doing the op on HW (AUTOSELECT)
*/
enum EEPROM_SOURCE
{
    AUTOSELECT = 0x0000,
    CACHE      = 0x0001,
    HARDWARE   = 0x0002,
};

/**
* @brief Enumerations to describe the type of devices to be accessed.
*/
typedef enum
{
    ZERO_BYTE_ADDR             = 0,
    ONE_BYTE_ADDR_PAGESELECT   = 1,  // page select
    TWO_BYTE_ADDR              = 2,
    ONE_BYTE_ADDR              = 3,
    LAST_DEVICE_TYPE
} eeprom_addr_size_t;

/**
* @brief Enumerations to describe version of the eepromRecordHeader
*        and eecacheSectionHeader structs
*/
enum EECACHE_VERSION
{
    EECACHE_VERSION_UNSET = 0xFF,
    EECACHE_VERSION_1     = 0x01,
    EECACHE_VERSION_2     = 0x02,
    // Useful Enum
    EECACHE_VERSION_LATEST = EECACHE_VERSION_2,
};

/**
* @brief Enumerations to describe how the eeprom is accessed
*/
enum class EepromHwAccessMethodType : uint8_t
{
    EEPROM_HW_ACCESS_METHOD_UNKNOWN  = 0x00,
    EEPROM_HW_ACCESS_METHOD_I2C      = 0x01,
    EEPROM_HW_ACCESS_METHOD_SPI      = 0x02,
};

/**
* @brief Handy union of two structs which represents the layout
*        of bits to describe a record in the EECACHE ToC. The
*        EECACHE ToC will have room for multiple of these record
*        headers.
*
*        completeRecord is the standard way to access data in the union.
*
*        uniqueRecord is useful if you want to quickly compare the "unique"
*        bits of a header entry which includes the accessType, target_huid,
*        port, engine, devAddr, mux_huid, and mux_select, and size
*
*/
union eepromRecordHeader
{
    struct completeRecord
    {
        EepromHwAccessMethodType accessType;  // how to access record
        union eepromAccess_t
        {
            struct i2cAccess_t
            {
                uint32_t i2c_master_huid;   // HUID of i2c Master
                uint8_t  port;              // I2C Port
                uint8_t  engine;            // I2C Engine
                uint8_t  devAddr;           // I2C Device Address
                uint8_t  mux_select;        // Some I2C devices are behind a mux, this says
                                            // what setting on the mux is required
            } PACKED i2cAccess;
            struct spiAccess_t
            {
                uint32_t spi_master_huid;  // HUID of SPI master
                uint8_t  engine;           // engine specific to eeprom
                uint16_t offset_KB;        // offset in KB of where record begins in eeprom
                uint8_t  pad_byte;         // just padding
            } PACKED spiAccess;
        } PACKED eepromAccess;
        uint32_t cache_copy_size;   // Size of data saved in cache (in KB)
        uint32_t internal_offset;   // Offset from start of EECACHE section where cached data exists
                                    // This variable is used in src/build/simics/eecache-gen.py to
                                    // create empty header entries for a prebuilt EECACHE
        union
        {
            uint8_t flags;

            struct
            {
                uint8_t  cached_copy_valid : 1,   // This bit is set when we think the contents of the
                                                  // cache is valid.
                master_eeprom              : 1,   // This bit marks this record as the master one (i.e. look at this one for change)
                pnor_write_in_progress     : 1,   // Whether a write to the backing PNOR storage is
                                                  // in progress.
                                                  // This bit is set at the beginning of a PNOR flush
                                                  // and cleared at the end of the flush. If this
                                                  // bit is set at the beginning of an IPL, it means
                                                  // that the EECACHE is partially written and may
                                                  // be corrupted; in that case we should delete
                                                  // the EECACHE entry and reload all the data
                                                  // from backing storage. (Used at IPL-time or
                                                  // on BMC systems at runtime only).
                unused                     : 5;
            };
        };
    } PACKED completeRecord;

    struct uniqueRecord
    {
        uint8_t uniqueID [NUM_BYTE_UNIQUE_ID];
        uint8_t metaData [sizeof(completeRecord) - NUM_BYTE_UNIQUE_ID];
    } PACKED uniqueRecord;

    inline bool operator<(const eepromRecordHeader& rhs) const{
      return memcmp(this->uniqueRecord.uniqueID, rhs.uniqueRecord.uniqueID, NUM_BYTE_UNIQUE_ID) < 0;
    }

    // Default ctor
    eepromRecordHeader()
    {
        memset(this, 0, sizeof(eepromRecordHeader));
    };

} PACKED;

/**
* @brief Struct which represents the Table of Contents (ToC) for
*        the EECACHE section in pnor
*
*/
struct eecacheSectionHeader
{
    uint8_t version;         // EECACHE_VERSION
    uint32_t end_of_cache;   // End point of the last cache entry
    eepromRecordHeader recordHeaders[MAX_EEPROMS_LATEST];
} PACKED ;

/**
 * @brief Structure of common parameters describing a unqiue eeprom.
 *        This is used all over the eeprom code, often functions will
 *        fill in information they know and pass on the struct.
 *
 *        Some functions require fields to be filled in prior to being
 *        passed to said function.
 */
struct eeprom_addr_t
{
    EepromHwAccessMethodType accessMethod;
    union accessAddr_t
    {
        struct i2c_addr_t
        {
            TARGETING::EntityPath i2cMasterPath;
            uint8_t engine;
            uint8_t devAddr;
            uint8_t port;
            eeprom_addr_size_t addrSize;
            uint64_t writePageSize;  // in bytes
            uint64_t chipCount;      // number of chips making up eeprom device
            uint64_t writeCycleTime;  // in milliseconds
            uint8_t i2cMuxBusSelector;
            TARGETING::EntityPath i2cMuxPath;
        } PACKED i2c_addr;
        struct spi_addr_t
        {
            TARGETING::EntityPath spiMasterPath;
            uint8_t engine;
            uint64_t roleOffset_KB;  // offset of the eepromRole's data
        } PACKED spi_addr;
        accessAddr_t()
        {
            memset(this, 0, sizeof(accessAddr_t));
        }
        ~accessAddr_t() {}
    } PACKED accessAddr;
    int64_t  eepromRole;
    uint64_t offset;      // offset from devAddr
    uint64_t devSize_KB; // size of data area starting from devAddr

    /**
     *  @brief Construct a default eeprom_addr_t
     */
    eeprom_addr_t()
      : accessMethod(EepromHwAccessMethodType::EEPROM_HW_ACCESS_METHOD_UNKNOWN),
        eepromRole(INVALID_CHIP_TYPE),
        offset(0),
        devSize_KB(0)
    {
    }
} PACKED;

/**
 * @brief Define a set of information about all EEPROMs in the
 *        system (primarily used to populate HDAT)
 */
struct EepromInfo_t
{
    EepromHwAccessMethodType accessMethod;
    union access_t
    {
        struct i2cAccess
        {
            TARGETING::Target* i2cMaster; //< I2C Master chip
            uint64_t engine; //< I2C engine (relative to master chip)
            uint64_t port; //< I2C port (relative to engine)
            uint64_t busFreq; //< Bus speed in Hz
            uint64_t devAddr; //< I2C device address (relative to port)
            uint64_t chipCount; //< Number of chips making up eeprom device
            uint64_t addrBytes; //< Number of bytes required for addressing
        } PACKED i2cInfo;
        struct spiAccess
        {
            TARGETING::Target* spiMaster; //< SPI Master chip
            uint64_t engine; //< SPI engine (relative to master chip)
        } PACKED spiInfo;
    } PACKED eepromAccess;

    EEPROM_ROLE deviceRole; //< Identifies role of eeprom
    TARGETING::Target* assocTarg; //< Target associated with this device

    EepromInfo_t()
      : accessMethod(EepromHwAccessMethodType::EEPROM_HW_ACCESS_METHOD_UNKNOWN),
        deviceRole(INVALID_CHIP_TYPE)
    {
    }
};

/**
 * @brief Define a set of information that describes the
          different virtual addresses associated with a given
          cache entry along with a byte telling us if there has been
          an update detected on the eeprom this boot
 */
struct EepromEntryMetaData_t
{
    uint64_t header_entry_address;
    uint64_t cache_entry_address;
    uint8_t  mark_target_changed;  // This byte is set after we detect a target has changed.
                                   // Either removed, replaced, or added we don't care. But
                                   // we need to use this bits so future targets associated
                                   // with this eeprom can know they need to notify HWAS that
                                   // they have been changed. This bit should get cleared after
                                   // all eeproms have been cached.

    EepromEntryMetaData_t()
      : header_entry_address(0),
        cache_entry_address(0),
        mark_target_changed(0)
    {
    }
};

}
#endif


text:
Print HTML information ( title, description, keywords ).
HTMLファイルのタイトルやディスクリプションをタブ文字区切りで出力します。

## Install

Direct downloads are available through the [releases page](https://github.com/daikiueda/htmlinfo/releases/latest).
実行ファイルは、[release page](https://github.com/daikiueda/htmlinfo/releases/latest)から直接ダウンロードできます。

If you have Go installed on your computer just run go get.
Goがインストールされている環境であれば、go getでインストールできます。
```Bash
$ go get github.com/daikiueda/htmlinfo
```

## Usage
```
$ htmlinfo [options]
```

### options
* __--dir__, __-d__
Set top directory of HTML files.

* __--charset__, __-c__
Set charset of HTML files.

* __--no-header__
Hide header.


text:
package org.easylenium.selenium.page.action;

import java.util.List;

import org.easylenium.selenium.page.action.wait.ExpectedConditionsCustom;
import org.easylenium.selenium.page.exception.ElementNotFoundException;
import org.easylenium.selenium.settings.Timeout;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Actions
{
	private By selector;

	private WebDriver webDriver;

	private WebDriverWait wait;

	public Actions(WebDriver current, Timeout timeout, By selector)
	{
		this.webDriver = current;
		this.selector = selector;
		this.wait = new WebDriverWait(current, timeout.getTimeUnit().toSeconds(timeout.getTime()));
	}

	public WebElement findElement()
	{
		return findElement(Boolean.TRUE, Boolean.TRUE);
	}

	public WebElement findElement(boolean needToBeDisplayed, boolean needToBeEnabled)
	{
		for (WebElement element : findElements(needToBeDisplayed, needToBeEnabled))
			if ((!needToBeDisplayed || (needToBeDisplayed && element.isDisplayed())) && (!needToBeEnabled || (needToBeEnabled && element.isEnabled())))
				return element;

		throw new ElementNotFoundException("The element is not found.");
	}

	public List<WebElement> findElements()
	{
		return findElements(Boolean.TRUE, Boolean.TRUE);
	}

	public List<WebElement> findElements(boolean needToBeDisplayed, boolean needToBeEnabled)
	{
		wait.until(ExpectedConditionsCustom.stateOfDocumentIsComplete());

		if (needToBeDisplayed)
			waittUntilIsVisible();

		if (needToBeEnabled)
			waitUntilIsEnabled();

		return webDriver.findElements(selector);
	}

	public Actions click()
	{

		findElement().click();

		return this;
	}

	public Actions fill(CharSequence... text)
	{
		findElement().sendKeys(text);
		return this;
	}

	public Actions clear()
	{
		findElement().clear();
		return this;
	}

	public Select select()
	{
		return new Select(findElement());
	}

	public boolean existElement()
	{
		try
		{
			wait.until(ExpectedConditionsCustom.stateOfDocumentIsComplete());

			return !webDriver.findElements(selector).isEmpty();

		} catch (Exception e)
		{
			return Boolean.FALSE;
		}
	}

	public WebElement waitUntilTextMatch(String text){
		return wait.until(ExpectedConditionsCustom.textMatchWithElementText(selector, text));
	}

	public WebElement waitUntilTextContains(String text){
		return wait.until(ExpectedConditionsCustom.textContainsWithElementText(selector, text));
	}

	public WebElement waittUntilIsVisible()
	{
		return wait.until(ExpectedConditions.visibilityOfElementLocated(selector));
	}

	public WebElement waitUntilIsEnabled()
	{
		return wait.until(ExpectedConditionsCustom.enabledOfElementLocated(selector));
	}

	public WebElement waitUntilHide()
	{
		return wait.until(ExpectedConditionsCustom.invisibilityOfElementLocated(selector));
	}

	public boolean isSelected()
	{
		return findElement().isSelected();
	}

	public boolean isEnable()
	{
		return findElement().isEnabled();
	}

	public String getAttribute(String name)
	{
		return findElement().getAttribute(name);
	}

	public String getText()
	{
		return findElement().getText();
	}

	public void focus()
	{
		new org.openqa.selenium.interactions.Actions(webDriver).moveToElement(findElement()).perform();
	}

}


text:
package org.apache.directory.server.core.api.sp.java;

import org.apache.directory.server.core.api.sp.StoredProcEngine;
import org.apache.directory.server.core.api.sp.StoredProcEngineConfig;

/**
 * A {@link StoredProcEngineConfig} implementation specific to Java stored procedures.
 *
 * @author Apache Directory Project
 */
public class JavaStoredProcEngineConfig implements StoredProcEngineConfig
{

    /* (non-Javadoc)
     * @see org.apache.directory.server.core.sp.StoredProcEngineConfig#getStoredProcEngineType()
     */
    public Class<? extends StoredProcEngine> getStoredProcEngineType()
    {
        return JavaStoredProcEngine.class;
    }

    /* (non-Javadoc)
     * @see org.apache.directory.server.core.sp.StoredProcEngineConfig#getStoredProcLangId()
     */
    public String getStoredProcLangId()
    {
        return JavaStoredProcEngine.STORED_PROC_LANG_ID;
    }

}


text:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Actions, Effect } from '@ngrx/effects';
import { Observable } from 'rxjs/Observable';

import { StorageService } from "../../services/storage-service";
import { LoadBlockService } from '../../services/load-block';
import { ActionTypes, AuthAction, AuthSuccessAction } from '../actions/auth';
import { User } from "../../entities/user";
import { AuthUser }  from "../../entities/auth-user";

const STORAGE_KEY = 'auth';

@Injectable()
export class AuthEffects {

  private errorUser: AuthUser = new AuthUser(null);
  private authUrl = "/api/auth/login";

  constructor(
    private http: Http,
    private actions$: Actions,
    private loadBlockService: LoadBlockService,
    private storage: StorageService
  ) {}

  @Effect() login$ = this.actions$
    .ofType(ActionTypes.AUTH)
    .map( (action: AuthAction) => (action.payload) )
    .do(()=>{this.loadBlockService.show()})
    .switchMap((user: User) => {
        if (!user) {
          return Observable.of(new AuthSuccessAction(this.errorUser))
        }
        return this.http.post(this.authUrl, {
            login: user.name,
            password: user.password
          })
          .map((response:Response) => {
            let body = response.json();
            let theUser = new User(user.name, '', body.token);
            this.storage.setItem(STORAGE_KEY, theUser);

            return new AuthSuccessAction(new AuthUser(theUser))
          })
          .catch(this.handleError.bind(this, user))
      })
     .do(()=>{this.loadBlockService.hide()})
 ;

  private handleError(user: User, response: Response): Observable<AuthSuccessAction> {
    return Observable.of(new AuthSuccessAction(new AuthUser(user, new Error(response.statusText))) );
  }

  @Effect() init$ = this.actions$
    .ofType('@ngrx/store/init')
    .map((action) => {
      let item = this.storage.getItem(STORAGE_KEY);
      return new AuthSuccessAction(new AuthUser(item))
    })
  ;

}


text:
direct_links = r'meta property="og:image" content="(.+?)"'

# same_filename (default=False): if True, uses filename specified on remote link.  Otherwise, creates own filename with incremental index.


text:
Note: Images for other Julia versions also available. Replace desired version number in instructions below.

See <https://github.com/tanmaykm/JuliaDockerImages> and <https://hub.docker.com/r/julialang/julia/tags/>

## Julia latest Docker Image

This docker image bundles:
- Latest Julia 0.3.12, Julia 0.4.7, Julia 0.5.0 and Julia 0.6.0-dev. Julia v0.4.7 is the default.
- Jupyter 4.2.x

image: julialang/julia
version: latest

## Getting the image:

To pull a pre-built image from dockerhub, run `docker pull <image>:<version>`

Alternatively, to build locally, run `git clone https://github.com/tanmaykm/JuliaDockerImages.git && docker build -t julialang/julia:latest JuliaDockerImages/base/latest`

## Running

- Run to get a shell prompt: docker run -it <image>:<version>
- Run Julia: docker run -it --entrypoint="/opt/julia/bin/julia" <image>:<version>
- Run Jupyter: docker run -it --net="host" --entrypoint="/usr/local/bin/jupyter" <image>:<version> notebook


text:
#include <gtest/gtest.h>

#include <cstring>

#include "com/centreon/broker/config/applier/init.hh"
#include "com/centreon/broker/io/events.hh"
#include "com/centreon/broker/io/raw.hh"
#include "com/centreon/broker/multiplexing/engine.hh"
#include "com/centreon/broker/multiplexing/muxer.hh"
#include "com/centreon/broker/multiplexing/publisher.hh"
#include "com/centreon/broker/multiplexing/subscriber.hh"

using namespace com::centreon::broker;

const std::string MSG1("0123456789abcdef");
const std::string MSG2("foo bar baz qux");

class PublisherWrite : public testing::Test {
 public:
  void SetUp() override { config::applier::init(0, "test_broker"); }

  void TearDown() override { config::applier::deinit(); }
};

/**
 *  We should be able to read from publisher.
 */
TEST_F(PublisherWrite, Write) {
  int retval{0};
  {
    // Publisher.
    multiplexing::publisher p;

    // Subscriber.
    std::unordered_set<uint32_t> filters;
    filters.insert(io::raw::static_type());
    multiplexing::subscriber s("core_multiplexing_publisher_write", "");
    s.get_muxer().set_read_filters(filters);
    s.get_muxer().set_write_filters(filters);

    // Publish event.
    {
      std::shared_ptr<io::raw> raw(new io::raw);
      raw->append(MSG1);
      p.write(std::static_pointer_cast<io::data>(raw));
    }

    // Launch multiplexing.
    multiplexing::engine::instance().start();

    // Publish another event.
    {
      std::shared_ptr<io::raw> raw(new io::raw);
      raw->append(MSG2);
      p.write(std::static_pointer_cast<io::data>(raw));
    }

    // Check data.
    std::array<std::string, 2> messages{MSG1, MSG2};
    for (auto& m : messages) {
      std::shared_ptr<io::data> data;
      s.get_muxer().read(data, 0);
      if (!data || data->type() != io::raw::static_type())
        retval |= 1;
      else {
        std::shared_ptr<io::raw> raw(std::static_pointer_cast<io::raw>(data));
        retval |= strncmp(raw->const_data(), m.c_str(), m.size());
      }
    }
  }
  // Return.
  ASSERT_EQ(retval, 0);
}


text:
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {
    MatButtonModule,
    MatFormFieldModule,
    MatInputModule,
    MatListModule,
    MatRadioModule,
    MatSlideToggleModule,
    MatTooltipModule,
} from '@angular/material';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { EventControlsComponent } from './event-controls/event-controls.component';
import { NoteControlsGHLComponent } from './note-controls/ghl/note-controls-ghl.component';
import { NoteControlsGuitarComponent } from './note-controls/guitar/note-controls-guitar.component';
import { NoteControlsComponent } from './note-controls/note-controls.component';
import { ParentControlsComponent } from './parent-controls/parent-controls.component';

import { BPMService } from './bpm/bpm.service';
import { LyricService } from './lyric/lyric.service';
import { PracticeSectionService } from './practice-section/practice-section.service';
import { SelectorService } from './selector/selector.service';
import { StepService } from './step/step.service';
import { TimeSignatureService } from './time-signature/time-signature.service';
import { TypeService } from './type/type.service';

@NgModule({
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        FormsModule,
        MatButtonModule,
        MatFormFieldModule,
        MatInputModule,
        MatListModule,
        MatRadioModule,
        MatSlideToggleModule,
        MatTooltipModule,
        ReactiveFormsModule,
    ],
    exports: [
        ParentControlsComponent,
    ],
    declarations: [
        EventControlsComponent,
        NoteControlsGHLComponent,
        NoteControlsGuitarComponent,
        NoteControlsComponent,
        ParentControlsComponent,
    ],
    providers: [
        BPMService,
        LyricService,
        PracticeSectionService,
        SelectorService,
        StepService,
        TimeSignatureService,
        TypeService,
    ],
})
export class AppControllerModule {
}