text:
import {LitElement, html} from "lit";
import UtilsNew from "../../../core/utils-new.js";
import LitUtils from "../utils/lit-utils.js";

// TODO reorganize props multiple/forceSelection

/** NOTE - Design choice: to allow deselection, the single mode (this.multiple=false), has been implemented with the multiple flag in bootstrap-select, but forcing 1 selection with data-max-options=1
 *  (this has no consequences for the developer point of view). This behaviour can be over overridden using "forceSelection" prop.
 *
 *  NOTE putting names in data-content attr instead of as <option> content itself allows HTML entities to be correctly decoded.
 *
 *  Usage:
 * <select-field-filter .data="${["A","B","C"]}" .value=${"A"} @filterChange="${e => console.log(e)}"></select-field-filter>
 * <select-field-filter .data="${[{id: "a", name: "A"}, {id:"b", name: "B"}, {id: "c", name: "C"}]}" .value=${"a"} @filterChange="${e => console.log(e)}"></select-field-filter>
 */

export default class SelectFieldFilter extends LitElement {

    constructor() {
        super();

        // Set status and init private properties
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            // NOTE value (default Values) can be either a single value as string or a comma separated list (in case of multiple=true we support array of strings)
            value: {
                type: String
            },
            placeholder: {
                type: String
            },
            multiple: {
                type: Boolean
            },
            disabled: {
                type: Boolean
            },
            required: {
                type: Boolean
            },
            maxOptions: {
                type: Number
            },
            liveSearch: {
                type: Boolean
            },
            forceSelection: {
                type: Boolean
            },
            classes: {
                type: String
            },
            size: {
                type: Number,
            },
            separator: {
                type: String,
            },
            // the expected format is either an array of string or an array of objects {id, name}
            data: {
                type: Object
            }
        };
    }

    _init() {
        this._prefix = UtilsNew.randomString(8);

        this.multiple = false;
        this.data = [];
        this.classes = "";
        this.elm = this._prefix + "selectpicker";
        this.size = 20; // Default size
        this.separator = ","; // Default separator
    }

    firstUpdated() {
        this.selectPicker = $("#" + this.elm, this);
        this.selectPicker.selectpicker({
            iconBase: "fas",
            tickIcon: "fa-check",
            val: "",
            multipleSeparator: this.separator
        });
        // this.selectPicker.selectpicker("val", "");
    }

    updated(changedProperties) {
        if (changedProperties.has("data")) {
            // TODO check why lit-element execute this for all existing select-field-filter instances..wtf
            this.data = this.data ?? [];
            this.selectPicker.selectpicker("refresh");
        }

        if (changedProperties.has("disabled")) {
            this.selectPicker.selectpicker("refresh");
        }

        if (changedProperties.has("value") || changedProperties.has("data") || changedProperties.has("disabled")) {
            let val = "";
            if (this.value) {
                if (this.multiple) {
                    if (Array.isArray(this.value)) {
                        val = this.value;
                    } else {
                        val = this.value.split(",");
                    }
                } else {
                    val = this.value;
                }
            }
            this.selectPicker.selectpicker("val", val);
        }

        if (changedProperties.has("classes")) {
            if (this.classes) {
                this.selectPicker.selectpicker("setStyle", this.classes, "add");
            } else {
                // if classes os removed then we need to removed the old assigned classes
                this.selectPicker.selectpicker("setStyle", changedProperties.get("classes"), "remove");
                this.selectPicker.selectpicker("setStyle", "btn-default", "add");
            }
        }
    }

    filterChange() {
        const selection = this.selectPicker.selectpicker("val");
        let val = null;
        if (selection && selection.length) {
            if (this.multiple) {
                val = selection.join(",");
            } else {
                if (this.forceSelection) {
                    // single mode that DOESN'T allow deselection
                    // forceSelection means multiple flag in selectpicker is false, this is the only case `selection` is not an array
                    val = selection;
                } else {
                    // single mode that allows deselection
                    val = selection[0];
                }
            }
        }

        LitUtils.dispatchCustomEvent(this, "filterChange", val, {
            data: this.data,
        }, null, {bubbles: false, composed: false});
    }

    renderOption(option) {
        let dataContent;
        if (option.description) {
            dataContent = `<span title="${option.description}">${option.name ?? option.id}</span>`;
        } else {
            dataContent = `<span>${option.name ?? option.id}</span>`;
        }
        return html`
            <option
                ?disabled="${option.disabled}"
                ?selected="${option.selected}"
                .value="${option.id ?? option.name}"
                data-content="${dataContent}">
            </option>
        `;
    }

    render() {
        return html`
            <div id="${this._prefix}-select-field-filter-wrapper" class="select-field-filter">
                <select id="${this.elm}"
                    class="${this.elm}"
                    ?multiple="${!this.forceSelection}"
                    ?disabled="${this.disabled}"
                    ?required="${this.required}"
                    data-live-search="${this.liveSearch ? "true" : "false"}"
                    data-size="${this.size}"
                    title="${this.placeholder ?? (this.multiple ? "Select option(s)" : "Select an option")}"
                    data-max-options="${!this.multiple ? 1 : this.maxOptions ? this.maxOptions : false}"
                    @change="${this.filterChange}"
                    data-width="100%"
                    data-style="btn-default ${this.classes}">
                    ${this.data?.map(opt => html`
                        ${opt?.separator ? html`
                            <option data-divider="true"></option>
                        ` : html`
                            ${opt?.fields ? html`
                                <optgroup label="${opt.id ?? opt.name}">
                                    ${opt.fields.map(subopt => html`
                                        ${UtilsNew.isObject(subopt) ?
                                            this.renderOption(subopt) :
                                            html`<option>${subopt}</option>`
                                        }
                                    `)}
                                </optgroup>
                            ` : html`
                                ${UtilsNew.isObject(opt) ?
                                    this.renderOption(opt) :
                                    html`<option data-content="${opt}">${opt}</option>`
                                }
                            `}
                        `}
                    `)}
                </select>
            </div>
        `;
    }

}

customElements.define("select-field-filter", SelectFieldFilter);


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <fraction name="keyguard_clock_y_fraction_max">32.500004%</fraction>
    <fraction name="keyguard_clock_y_fraction_min">18.500006%</fraction>
</resources>

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: Forbes Guardian Llc. Dinner
date: 2016-05-24
author: Christina Newton
tags: weekly links, java
status: published
summary: Sed venenatis accumsan turpis sed condimentum. Curabitur et arcu vel.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 09/23/2018
  endDate: 09/27/2018
  ctyhocn: TYSHSHX
  groupCode: FGLD
published: true
---
Suspendisse ullamcorper turpis est, in condimentum massa suscipit ut. Nullam nisi odio, elementum ut nibh et, tincidunt ultricies orci. Integer pretium tempus placerat. Etiam a congue tortor. Praesent iaculis purus quis dolor lacinia, in bibendum quam malesuada. Quisque interdum fermentum lacinia. Nam justo nisi, pulvinar ac augue sed, volutpat dapibus neque. Donec commodo ut odio in blandit.

* Nam sit amet tellus consequat, malesuada ex non, lacinia ante
* Donec pretium ipsum sed viverra viverra
* Nam id purus eget neque venenatis egestas.

Mauris semper et justo a lacinia. Donec et sapien sit amet turpis suscipit tincidunt. Pellentesque blandit lacus id ipsum pharetra, ac scelerisque ipsum consequat. Duis eget malesuada nisi, at molestie nisl. Donec mattis ex sit amet tortor convallis molestie. Sed ante leo, pretium in diam id, varius blandit mi. Donec semper maximus quam, ac molestie ex feugiat non. Quisque risus magna, lacinia non elementum eget, ornare non nisl. Phasellus iaculis nec nunc et aliquet. Aliquam scelerisque scelerisque massa vitae malesuada. Maecenas malesuada, justo sit amet pellentesque pellentesque, lorem risus facilisis magna, at tristique ipsum purus id turpis. Nullam ultrices sem eget sapien mollis rhoncus.


text:
{% extends "base.html" %}
{% load i18n wagtailsettings_tags %}
{% get_settings %}

{% block content %}

      {% trans "Hello " %} {{ user.profile.migrated_username|default:user.username }}

      <fieldset>
        {% trans "As you type your name comment will appear as:" %}

          {% trans "Anonymous" as defaultText %}
          {{ user.profile.alias | default:defaultText }}

      </fieldset>

    {% trans "Not set." as defaultText %}
    <fieldset>
      {% trans "Date of Birth: " %}

        {% if user.profile.date_of_birth %}
          {{ user.profile.date_of_birth | date:"M d, Y" }}
        {% else %}{{defaultText}}{% endif %}

    </fieldset>

    {% if settings.profiles.UserProfilesSettings.show_mobile_number_field and settings.profiles.UserProfilesSettings.country_code %}
    <fieldset>
      {% trans "Mobile number:" %}

{{ user.profile.mobile_number | default:defaultText}}

    </fieldset>
    {% endif %}

    {% if settings.profiles.UserProfilesSettings.activate_gender %}
    <fieldset>
      {% trans "Gender:" %}

        {{ user.profile.gender | default:defaultText }}

    </fieldset>
    {% endif %}

    {% if settings.profiles.UserProfilesSettings.activate_location %}
    <fieldset>
      {% trans "Location:" %}

{{ user.profile.location | default:defaultText }}

    </fieldset>
    {% endif %}

    {% if settings.profiles.UserProfilesSettings.activate_education_level %}
    <fieldset>
      {% trans "Education Level:" %}

{{ user.profile.education_level | default:defaultText }}

    </fieldset>
    {% endif %}

  <fieldset>
    {% if settings.profiles.UserProfilesSettings.show_email_field %}
      {% trans "Email Address:" %}

        {{ user.email | default:defaultText }}

    {% endif %}
  </fieldset>

    {% trans "log out" %}
    {% trans "Edit My Profile" %}
    {% trans "Change my password" %}

{% endblock %}


text:
export function store($http, BaseApiUrl) {
    const BASE = `${BaseApiUrl}/enum-value`;

    // --- FINDERS ---
    const findAll = () => $http
        .get(BASE)
        .then(r => r.data);

    return {
        findAll,
    };
}

store.$inject = [
    "$http",
    "BaseApiUrl"
];

export const serviceName = "EnumValueStore";

export const EnumValueStore_API = {
    findAll: {
        serviceName,
        serviceFnName: "findAll",
        description: "find all enum values"
    }
};


text:
from datetime import date, timedelta

from django.test import TestCase

from autoemails.actions import DeclinedInstructorsAction
from autoemails.models import EmailTemplate, Trigger
from recruitment.models import InstructorRecruitment, InstructorRecruitmentSignup
from workshops.models import Event, Organization, Person, Tag
from workshops.utils.dates import human_daterange

class TestDeclinedInstructorsAction(TestCase):
    def setUp(self):
        # we're missing some tags
        Tag.objects.bulk_create(
            [
                Tag(name="automated-email", priority=0),
                Tag(name="SWC", priority=10),
                Tag(name="DC", priority=20),
                Tag(name="LC", priority=30),
                Tag(name="TTT", priority=40),
            ]
        )
        Organization.objects.bulk_create(
            [Organization(domain="carpentries.org", fullname="Instructor Training")]
        )

        self.event = Event.objects.create(
            slug="test-event",
            host=Organization.objects.first(),
            administrator=Organization.objects.get(domain="carpentries.org"),
            start=date.today() + timedelta(days=7),
            end=date.today() + timedelta(days=8),
        )
        self.event.tags.set(Tag.objects.filter(name__in=["LC", "automated-email"]))
        self.person = Person.objects.create(
            username="test1",
            personal="Test1",
            family="Test1",
            email="test1@example.org",
        )
        self.recruitment = InstructorRecruitment.objects.create(
            event=self.event, status="o"
        )

        self.template = EmailTemplate.objects.create(
            slug="sample-template",
            subject="Welcome to {{ site.name }}",
            to_header="recipient@address.com",
            from_header="test@address.com",
            cc_header="copy@example.org",
            bcc_header="bcc@example.org",
            reply_to_header="{{ reply_to }}",
            body_template="Sample text.",
        )
        self.trigger = Trigger.objects.create(
            action="self-organised-request-form",
            template=self.template,
        )

    def test_launch_at(self) -> None:
        a = DeclinedInstructorsAction(trigger=self.trigger)
        self.assertEqual(a.get_launch_at(), timedelta(hours=1))

    def test_check_conditions_fail(self) -> None:
        # Arrange
        event = Event.objects.create(
            slug="test-event2",
            host=Organization.objects.first(),
            administrator=Organization.objects.get(domain="carpentries.org"),
            start=date.today() + timedelta(days=7),
            end=date.today() + timedelta(days=8),
        )
        recruitment_closed = InstructorRecruitment.objects.create(
            event=event, status="c"
        )
        signup1 = InstructorRecruitmentSignup(
            person=self.person, recruitment=self.recruitment, state="a"
        )
        signup2 = InstructorRecruitmentSignup(
            person=self.person, recruitment=recruitment_closed, state="a"
        )
        signup3 = InstructorRecruitmentSignup(
            person=self.person, recruitment=self.recruitment, state="d"
        )
        # Act & Assert
        self.assertFalse(DeclinedInstructorsAction.check(signup1))
        self.assertFalse(DeclinedInstructorsAction.check(signup2))
        self.assertFalse(DeclinedInstructorsAction.check(signup3))

    def test_check_conditions_pass(self) -> None:
        # Arrange
        event = Event.objects.create(
            slug="test-event2",
            host=Organization.objects.first(),
            administrator=Organization.objects.get(domain="carpentries.org"),
            start=date.today() + timedelta(days=7),
            end=date.today() + timedelta(days=8),
        )
        recruitment_closed = InstructorRecruitment.objects.create(
            event=event, status="c"
        )
        signup = InstructorRecruitmentSignup(
            person=self.person, recruitment=recruitment_closed, state="d"
        )
        # Act &  Assert
        self.assertTrue(DeclinedInstructorsAction.check(signup))

    def test_context_missing_keys(self) -> None:
        # Arrange
        action = DeclinedInstructorsAction(
            trigger=self.trigger,
            objects=dict(
                recruitment=self.recruitment,
                event=self.recruitment.event,
                person=self.person,
            ),
        )
        # Act & Assert
        with self.assertRaises(KeyError):
            # missing recruitment
            action.get_additional_context({})
        with self.assertRaises(KeyError):
            # missing event
            action.get_additional_context({"recruitment": self.recruitment})
        with self.assertRaises(KeyError):
            # missing person
            action.get_additional_context(
                {"recruitment": self.recruitment, "event": self.event}
            )

        # OK
        action.get_additional_context(
            {
                "recruitment": self.recruitment,
                "event": self.event,
                "person": self.person,
            }
        )

    def test_context(self) -> None:
        # Arrange
        action = DeclinedInstructorsAction(
            trigger=self.trigger,
            objects=dict(
                recruitment=self.recruitment,
                event=self.recruitment.event,
                person=self.person,
            ),
        )
        # Act
        context = action.get_additional_context(
            {
                "recruitment": self.recruitment,
                "event": self.event,
                "person": self.person,
            }
        )
        # Assert
        self.maxDiff = None
        expected = {
            "assignee": "Regional Coordinator",
            "dates": human_daterange(self.event.start, self.event.end),
            "email": self.person.email,
            "host": self.event.host,
            "person": self.person,
            "recruitment": self.recruitment,
            "regional_coordinator_email": ["workshops@carpentries.org"],
            "tags": ["automated-email", "LC"],
            "workshop": self.event,
            "workshop_main_type": "LC",
        }
        self.assertEqual(context, expected)

    def test_recipients(self) -> None:
        # Arrange
        action = DeclinedInstructorsAction(
            trigger=self.trigger,
            objects=dict(
                recruitment=self.recruitment,
                event=self.recruitment.event,
                person=self.person,
            ),
        )
        # Act
        email = action._email()
        # Assert
        self.assertEqual(email.to, ["test1@example.org"])

    def test_event_slug(self) -> None:
        # Arrange
        action = DeclinedInstructorsAction(
            trigger=self.trigger,
            objects=dict(
                recruitment=self.recruitment,
                event=self.recruitment.event,
                person=self.person,
            ),
        )
        # Act
        slug = action.event_slug()
        # Assert
        self.assertEqual(slug, "test-event")

    def test_all_recipients(self) -> None:
        # Arrange
        action = DeclinedInstructorsAction(
            trigger=self.trigger,
            objects=dict(
                recruitment=self.recruitment,
                event=self.recruitment.event,
                person=self.person,
            ),
        )
        # Act
        emails = action.all_recipients()
        # Assert
        self.assertEqual(emails, "test1@example.org")


text:
$$.View.Scrollspy=$$.View.createSubclass({
    template:'
${e~tablist}
',
    mg_elementConfigs:{
      tablist:['Loop',{tag:'ul',datas:'${options.links}',element:['Link',['javascript:;','$~{i~1}',{useHref:true,data:{target:'$~{i~0}'}}],{wrapper:'
{{}}
',location:'#${fullname}__tablist'}]},{cssClass:'nav navbar-nav navbar-left'}]
    },
    initShow:['tablist'],
    beforeInit:function(options){
      this.options=options||{};
      this.offset=this.options.offset||0;
    },
    afterInit:function(){
      //this.find('.scrollspy-target').css({position:'fixed'});
      $('body').css({position:'relative'});
      $('body').scrollspy({ target: '.scrollspy-target' });
      var _this=this;
      $(this.domnode).on('click','.nav li>a',function(){
        var target=$(this).data('target');
        var link=$(this);
        $('html, body').animate({scrollTop:$(target).offset().top-_this.offset},{complete:function(){
          $('body').scrollspy('clear');
          link.parent().addClass('active');
        }});

      });
    }
});


text:
/**
 * Module dependencies
 */

var Writable = require('stream').Writable;
var fsx = require('fs-extra');
var path = require('path');
var _ = require('lodash');

/**
 * Example of a simple receiver for file-parser.
 * This is used for handling file uploads and writing them
 * to a storage container.
 *
 * This is just a super-basic thing that writes files to disk.
 * It does include a garbage-collection mechanism for file uploads
 * which were not successful.
 *
 * @return {Stream.Writable}
 */

module.exports = function newReceiverStream(options) {
  options = options || {};
  _.defaults(options, {

    // By default, create new files on disk
    // using their uploaded filenames.
    // (no overwrite-checking is performed!!)
    getFilename: function (__newFile) {
      return __newFile.filename;
    },

    // By default, upload files to `./.tmp/uploads` (relative to cwd)
    dirname: '.tmp/uploads'
  });

  var receiver__ = Writable({
    objectMode: true
  });

  // This `_write` method is invoked each time a new file is received
  // from the Readable stream (Upstream) which is pumping filestreams
  // into this receiver.  (filename === `__newFile.filename`).
  receiver__._write = function onFile(__newFile, encoding, done) {

    // Determine location where file should be written
    var dirPath = path.resolve(options.dirname);
    var filename = options.getFilename(__newFile);
    var filePath = path.join(dirPath, filename);

    // Garbage-collect the bytes that were already written for this file.
    // (called when a read or write error occurs)
    function gc(err) {
      // console.log('************** Garbage collecting file `' + __newFile.filename + '` located @ ' + filePath + '...');
      fsx.unlink(filePath, function(gcErr) {
        if (gcErr) return done([err].concat([gcErr]));
        return done(err);
      });
    }

    // Ensure necessary parent directories exist:
    fsx.mkdirs(dirPath, function (err) {
      if (err) { /* ignore mkdir error */ }

      var outs = fsx.createWriteStream(filePath, encoding);
      __newFile.pipe(outs);

      __newFile.on('error', function(err) {
        // console.log('***** READ error on file ' + __newFile.filename, '::', err);
      });
      outs.on('error', function failedToWriteFile(err) {
        // console.log('Error on output stream- garbage collecting unfinished uploads...');
        gc(err);
      });

      outs.on('finish', function successfullyWroteFile() {
        done();
      });
    });

  };

  return receiver__;
};


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="space_small">8dp</dimen>
    <dimen name="space_normal">16dp</dimen>
</resources>


text:
[![Build Status](https://github.com/Innmind/neo4j-dbal/workflows/CI/badge.svg?branch=master)](https://github.com/Innmind/neo4j-dbal/actions?query=workflow%3ACI)
[![codecov](https://codecov.io/gh/Innmind/neo4j-dbal/branch/develop/graph/badge.svg)](https://codecov.io/gh/Innmind/neo4j-dbal)
[![Type Coverage](https://shepherd.dev/github/Innmind/neo4j-dbal/coverage.svg)](https://shepherd.dev/github/Innmind/neo4j-dbal)

PHP abstraction layer for neo4j graph database

## Installation

Run the following command in your project to add this library:

```sh
composer require innmind/neo4j-dbal
```

## Documentation

Basic example to run a query:

```php
use function Innmind\Neo4j\DBAL\bootstrap;
use Innmind\Neo4j\DBAL\{
    Query,
    Clause\Expression\Relationship
};
use Innmind\OperatingSystem\Factory;

$os = Factory::build();
$connection = bootstrap(
    $os->remote()->http(),
    $os->clock(),
);

$query = (new Query)
    ->match('n', ['LabelA', 'LabelB'])
        ->withProperty('foo', '$param')
        ->withParameter('param', 'value')
    ->linkedTo('n2')
    ->through('r', 'REL_TYPE', 'right')
    ->return('n', 'n2', 'r');
echo $query->cypher(); //MATCH (n:LabelA:LabelB { foo: $param })-[r:REL_TYPE]->(n2) RETURN n, n2, r

$result = $connection->execute($query);
echo $result->nodes()->count(); //2
echo $result->relationships()->count(); //1
```

**Note**: Each object in this library is **immutable**, so `$query->match('n')->match('n2')` is different than `$query->match('n'); $query->match('n2')`.

### Querying

You have 3 options to execute a query:

* use [`Query`](src/Query/Query.php) to build the query via its API
* use [`Cypher`](src/Query/Cypher.php) where you put the raw cypher query
* create your own class that implements [`Query`](src/Query.php)

## Structure

![](graph.svg)


text:
/* Maximum number of switching times per day */
const int MAX_VALUES = 15;

class ChannelHandler {
    unsigned int (&valueTable)[MAX_VALUES][2];
    int numberValues = MAX_VALUES;
    int currentIndex = 0;

  public:
    /* Constructor gets a reference to the time table */
    ChannelHandler(unsigned int (&valueTableParam)[MAX_VALUES][2]) : valueTable(valueTableParam) {
      // TODO Validate times (must be ascending and between 0 and 24h) and values (must be between 0 and 1000)
      /* Determine the number of switching times per day */
      for (int i = 1; i < MAX_VALUES; i++) {
        if (valueTable[i][0] == 0) {
          numberValues = i;
          break;
        }
      }
    }

    /* Calculates the light percentage value at the given time */
    float GetPercentageAtTime(long time) {
      int currentIdx = GetCurrentIndex(time);
      int nextIdx = GetNextIndex();

      float result = CalculateValue(valueTable[currentIdx][0], valueTable[currentIdx][1], valueTable[nextIdx][0], valueTable[nextIdx][1], time);
      return constrain(result, 0, 100);
    }

  private:
    /* Returns the position in the timetable we are at the moment */
    int GetCurrentIndex(long time) {
      FindCurrentIndex(time);
      return currentIndex;
    }

    /* Finds the position in the timetable we are at the moment */
    void FindCurrentIndex(long time) {
      while (!(
               ((long)valueTable[currentIndex][0] * 10 <= time && (long)valueTable[GetNextIndex()][0] * 10 > time) || /* Normally we are between two time value */
               (currentIndex == (numberValues - 1) && (long)valueTable[currentIndex][0] * 10 <= time) || /* End of day, after the last time value */
               (currentIndex == (numberValues - 1) && (long)valueTable[GetNextIndex()][0] * 10 > time) )) { /* Start of day, before the first time value */
        currentIndex = GetNextIndex();
      }
    }

    /* Determines the next index in the timetable */
    int GetNextIndex() {
      if (currentIndex < (numberValues - 1)) {
        return (currentIndex + 1);
      }
      return 0;
    }

    /* Determines the previous index in the timetable */
    int GetPrevIndex() {
      if (currentIndex > 0) {
        return (currentIndex - 1);
      }
      return (numberValues - 1);
    }

    /* Calculates the value at the given time using a linear interpolation between the value at the previous and the next timestamp in the timetable */
    float CalculateValue(long startTime, float startValue, long endTime, float endValue, long time) {
      float timeDiff = ((endTime - startTime) + 8640) % 8640;
      return ((((time - (startTime * 10)) / (timeDiff * 10)) * (endValue - startValue)) + startValue) / 10;
    }
};


text:
/*
 * 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.
 */
package com.facebook.presto.operator;

import com.facebook.presto.spi.type.Type;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;

import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

public final class SettableLookupSourceSupplier
        implements LookupSourceSupplier
{
    private final List<Type> types;
    private final SettableFuture<LookupSource> lookupSourceFuture = SettableFuture.create();

    public SettableLookupSourceSupplier(List<Type> types)
    {
        this.types = ImmutableList.copyOf(checkNotNull(types, "types is null"));
    }

    @Override
    public List<Type> getTypes()
    {
        return types;
    }

    @Override
    public ListenableFuture<LookupSource> getLookupSource(OperatorContext operatorContext)
    {
        return lookupSourceFuture;
    }

    public void setLookupSource(LookupSource lookupSource)
    {
        checkNotNull(lookupSource, "lookupSource is null");
        boolean wasSet = lookupSourceFuture.set(lookupSource);
        checkState(wasSet, "Lookup source already set");
    }
}


text:
package com.minsons.minmvc.FilterChain;

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

public interface BaseFilter {

	public void execute(Object obj );

	public void setNextFilter(BaseFilter baseFilter);

}


text:
package me.phoboslabs.illuminati.processor.executor;

import me.phoboslabs.illuminati.common.dto.IlluminatiInterfaceModel;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * Created by leekyoungil (leekyoungil@gmail.com) on 04/05/2018.
 */
public class IlluminatiBlockingQueue<E extends IlluminatiInterfaceModel> extends LinkedBlockingQueue<E> {

    private int listCount = 1;

    public IlluminatiBlockingQueue(int capacity, int listCount) {
        super(capacity);
        this.listCount = listCount;
    }

    public List<E> pollToList(long timeout, TimeUnit unit) throws Exception {
        int superQueueSize = super.size();
        if (superQueueSize == 0) {
            throw new Exception("Queue is empty.");
        }

        if (superQueueSize > this.listCount) {
            superQueueSize = this.listCount;
        }

        List<E> dataList = new ArrayList<>(superQueueSize);

        for (int i=0; i<superQueueSize; i++) {
            try {
                E data = super.poll(timeout, unit);
                if (data == null) {
                    break;
                }
                dataList.add(data);
            } catch (InterruptedException ignore) {}
        }

        if (CollectionUtils.isEmpty(dataList)) {
            throw new Exception("Queue is empty.");
        }

        return dataList;
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jada.ngeditor.model.elements;

import de.lessvoid.nifty.controls.dragndrop.builder.DroppableBuilder;
import jada.ngeditor.model.GUIFactory;
import jada.ngeditor.persistence.XmlTags;
import jada.ngeditor.model.visitor.Visitor;
import jada.ngeditor.persistence.ControlBinding;

/**
 *
 * @author cris
 */
@ControlBinding(name= XmlTags.DROPPABLE)
public class GDroppable extends GControl  {

    public GDroppable(String id) throws IllegalArgumentException {
        super(id);
        this.builder = new DroppableBuilder(id);
        this.name = "droppable";
    }

    private GDroppable() {
        super();
    }

    @Override
    public GElement create(String id) {
        return new GDroppable(id);
    }

    @Override
    public void initDefault() {

       attributes.put("width", "100px");
       attributes.put("height", "100px");
       attributes.put("childLayout", "center");
       attributes.put("backgroundImage", "jada/ngeditor/resources/drop.png");
    }

     @Override
    public void accept(Visitor visitor) {
        super.accept(visitor);
        visitor.visit(this);
    }
}


text:
#import "ZXParsedReaderResultTestCase.h"

@implementation ZXParsedReaderResultTestCase

- (void)testTextType {
  [self doTestResultWithContents:@"" goldenResult:@"" type:kParsedResultTypeText];
  [self doTestResultWithContents:@"foo" goldenResult:@"foo" type:kParsedResultTypeText];
  [self doTestResultWithContents:@"Hi." goldenResult:@"Hi." type:kParsedResultTypeText];
  [self doTestResultWithContents:@"This is a test\nwith newlines" goldenResult:@"This is a test\nwith newlines"
                            type:kParsedResultTypeText];
  [self doTestResultWithContents:@"This: a test with lots of @ nearly-random punctuation! No? OK then."
                    goldenResult:@"This: a test with lots of @ nearly-random punctuation! No? OK then."
                            type:kParsedResultTypeText];
}

- (void)testBookmarkType {
  [self doTestResultWithContents:@"MEBKM:URL:google.com;;" goldenResult:@"http://google.com" type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"MEBKM:URL:google.com;TITLE:Google;;" goldenResult:@"Google\nhttp://google.com"
                            type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"MEBKM:TITLE:Google;URL:google.com;;" goldenResult:@"Google\nhttp://google.com"
                            type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"MEBKM:URL:http://google.com;;" goldenResult:@"http://google.com" type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"MEBKM:URL:HTTPS://google.com;;" goldenResult:@"HTTPS://google.com" type:kParsedResultTypeURI];
}

- (void)testURLTOType {
  [self doTestResultWithContents:@"urlto:foo:bar.com" goldenResult:@"foo\nhttp://bar.com" type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"URLTO:foo:bar.com" goldenResult:@"foo\nhttp://bar.com" type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"URLTO::bar.com" goldenResult:@"http://bar.com" type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"URLTO::http://bar.com" goldenResult:@"http://bar.com" type:kParsedResultTypeURI];
}

- (void)testEmailType {
  [self doTestResultWithContents:@"MATMSG:TO:srowen@example.org;;" goldenResult:@"srowen@example.org"
                            type:kParsedResultTypeEmailAddress];
  [self doTestResultWithContents:@"MATMSG:TO:srowen@example.org;SUB:Stuff;;" goldenResult:@"srowen@example.org\nStuff"
                            type:kParsedResultTypeEmailAddress];
  [self doTestResultWithContents:@"MATMSG:TO:srowen@example.org;SUB:Stuff;BODY:This is some text;;"
                    goldenResult:@"srowen@example.org\nStuff\nThis is some text" type:kParsedResultTypeEmailAddress];
  [self doTestResultWithContents:@"MATMSG:SUB:Stuff;BODY:This is some text;TO:srowen@example.org;;"
                    goldenResult:@"srowen@example.org\nStuff\nThis is some text" type:kParsedResultTypeEmailAddress];
  [self doTestResultWithContents:@"TO:srowen@example.org;SUB:Stuff;BODY:This is some text;;"
                    goldenResult:@"TO:srowen@example.org;SUB:Stuff;BODY:This is some text;;" type:kParsedResultTypeText];
}

- (void)testEmailAddressType {
  [self doTestResultWithContents:@"srowen@example.org" goldenResult:@"srowen@example.org" type:kParsedResultTypeEmailAddress];
  [self doTestResultWithContents:@"mailto:srowen@example.org" goldenResult:@"srowen@example.org" type:kParsedResultTypeEmailAddress];
  [self doTestResultWithContents:@"MAILTO:srowen@example.org" goldenResult:@"srowen@example.org" type:kParsedResultTypeEmailAddress];
  [self doTestResultWithContents:@"srowen@example" goldenResult:@"srowen@example" type:kParsedResultTypeEmailAddress];
  [self doTestResultWithContents:@"srowen" goldenResult:@"srowen" type:kParsedResultTypeText];
  [self doTestResultWithContents:@"Let's meet @ 2" goldenResult:@"Let's meet @ 2" type:kParsedResultTypeText];
}

- (void)testAddressBookType {
  [self doTestResultWithContents:@"MECARD:N:Sean Owen;;" goldenResult:@"Sean Owen" type:kParsedResultTypeAddressBook];
  [self doTestResultWithContents:@"MECARD:TEL:+12125551212;N:Sean Owen;;" goldenResult:@"Sean Owen\n+12125551212"
                            type:kParsedResultTypeAddressBook];
  [self doTestResultWithContents:@"MECARD:TEL:+12125551212;N:Sean Owen;URL:google.com;;"
                    goldenResult:@"Sean Owen\n+12125551212\ngoogle.com" type:kParsedResultTypeAddressBook];
  [self doTestResultWithContents:@"MECARD:TEL:+12125551212;N:Sean Owen;URL:google.com;EMAIL:srowen@example.org;"
                    goldenResult:@"Sean Owen\n+12125551212\nsrowen@example.org\ngoogle.com" type:kParsedResultTypeAddressBook];
  [self doTestResultWithContents:@"MECARD:ADR:76 9th Ave;N:Sean Owen;URL:google.com;EMAIL:srowen@example.org;"
                    goldenResult:@"Sean Owen\n76 9th Ave\nsrowen@example.org\ngoogle.com" type:kParsedResultTypeAddressBook];
  [self doTestResultWithContents:@"MECARD:BDAY:19760520;N:Sean Owen;URL:google.com;EMAIL:srowen@example.org;"
                    goldenResult:@"Sean Owen\nsrowen@example.org\ngoogle.com\n19760520" type:kParsedResultTypeAddressBook];
  [self doTestResultWithContents:@"MECARD:ORG:Google;N:Sean Owen;URL:google.com;EMAIL:srowen@example.org;"
                    goldenResult:@"Sean Owen\nGoogle\nsrowen@example.org\ngoogle.com" type:kParsedResultTypeAddressBook];
  [self doTestResultWithContents:@"MECARD:NOTE:ZXing Team;N:Sean Owen;URL:google.com;EMAIL:srowen@example.org;"
                    goldenResult:@"Sean Owen\nsrowen@example.org\ngoogle.com\nZXing Team" type:kParsedResultTypeAddressBook];
  [self doTestResultWithContents:@"N:Sean Owen;TEL:+12125551212;;" goldenResult:@"N:Sean Owen;TEL:+12125551212;;"
                            type:kParsedResultTypeText];
}

- (void)testAddressBookAUType {
  [self doTestResultWithContents:@"MEMORY:\r\n" goldenResult:@"" type:kParsedResultTypeAddressBook];
  [self doTestResultWithContents:@"MEMORY:foo\r\nNAME1:Sean\r\n" goldenResult:@"Sean\nfoo" type:kParsedResultTypeAddressBook];
  [self doTestResultWithContents:@"TEL1:+12125551212\r\nMEMORY:\r\n" goldenResult:@"+12125551212" type:kParsedResultTypeAddressBook];
}

- (void)testBizcard {
  [self doTestResultWithContents:@"BIZCARD:N:Sean;X:Owen;C:Google;A:123 Main St;M:+12225551212;E:srowen@example.org;"
                    goldenResult:@"Sean Owen\nGoogle\n123 Main St\n+12225551212\nsrowen@example.org"
                            type:kParsedResultTypeAddressBook];
}

- (void)testUPCA {
  [self doTestResultWithContents:@"123456789012" goldenResult:@"123456789012" type:kParsedResultTypeProduct format:kBarcodeFormatUPCA];
  [self doTestResultWithContents:@"1234567890123" goldenResult:@"1234567890123" type:kParsedResultTypeProduct format:kBarcodeFormatUPCA];
  [self doTestResultWithContents:@"12345678901" goldenResult:@"12345678901" type:kParsedResultTypeText];
}

- (void)testUPCE {
  [self doTestResultWithContents:@"01234565" goldenResult:@"01234565" type:kParsedResultTypeProduct format:kBarcodeFormatUPCE];
}

- (void)testEAN {
  [self doTestResultWithContents:@"00393157" goldenResult:@"00393157" type:kParsedResultTypeProduct format:kBarcodeFormatEan8];
  [self doTestResultWithContents:@"00393158" goldenResult:@"00393158" type:kParsedResultTypeText];
  [self doTestResultWithContents:@"5051140178499" goldenResult:@"5051140178499" type:kParsedResultTypeProduct format:kBarcodeFormatEan13];
  [self doTestResultWithContents:@"5051140178490" goldenResult:@"5051140178490" type:kParsedResultTypeText];
}

- (void)testISBN {
  [self doTestResultWithContents:@"9784567890123" goldenResult:@"9784567890123" type:kParsedResultTypeISBN format:kBarcodeFormatEan13];
  [self doTestResultWithContents:@"9794567890123" goldenResult:@"9794567890123" type:kParsedResultTypeISBN format:kBarcodeFormatEan13];
  [self doTestResultWithContents:@"97845678901" goldenResult:@"97845678901" type:kParsedResultTypeText];
  [self doTestResultWithContents:@"97945678901" goldenResult:@"97945678901" type:kParsedResultTypeText];
}

- (void)testURI {
  [self doTestResultWithContents:@"http://google.com" goldenResult:@"http://google.com" type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"google.com" goldenResult:@"http://google.com" type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"https://google.com" goldenResult:@"https://google.com" type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"HTTP://google.com" goldenResult:@"HTTP://google.com" type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"http://google.com/foobar" goldenResult:@"http://google.com/foobar" type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"https://google.com:443/foobar" goldenResult:@"https://google.com:443/foobar" type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"google.com:443" goldenResult:@"http://google.com:443" type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"google.com:443/" goldenResult:@"http://google.com:443/" type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"google.com:443/foobar" goldenResult:@"http://google.com:443/foobar" type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"http://google.com:443/foobar" goldenResult:@"http://google.com:443/foobar" type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"https://google.com:443/foobar" goldenResult:@"https://google.com:443/foobar" type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"ftp://google.com/fake" goldenResult:@"ftp://google.com/fake" type:kParsedResultTypeURI];
  [self doTestResultWithContents:@"gopher://google.com/obsolete" goldenResult:@"gopher://google.com/obsolete" type:kParsedResultTypeURI];
}

- (void)testGeo {
  [self doTestResultWithContents:@"geo:1,2" goldenResult:@"1.000000, 2.000000" type:kParsedResultTypeGeo];
  [self doTestResultWithContents:@"geo:1,2,3" goldenResult:@"1.000000, 2.000000, 3.000000m" type:kParsedResultTypeGeo];
  [self doTestResultWithContents:@"geo:80.33,-32.3344,3.35" goldenResult:@"80.330000, -32.334400, 3.350000m" type:kParsedResultTypeGeo];
  [self doTestResultWithContents:@"geo" goldenResult:@"geo" type:kParsedResultTypeText];
  [self doTestResultWithContents:@"geography" goldenResult:@"geography" type:kParsedResultTypeText];
}

- (void)testTel {
  [self doTestResultWithContents:@"tel:+15551212" goldenResult:@"+15551212" type:kParsedResultTypeTel];
  [self doTestResultWithContents:@"TEL:+15551212" goldenResult:@"+15551212" type:kParsedResultTypeTel];
  [self doTestResultWithContents:@"tel:212 555 1212" goldenResult:@"212 555 1212" type:kParsedResultTypeTel];
  [self doTestResultWithContents:@"tel:2125551212" goldenResult:@"2125551212" type:kParsedResultTypeTel];
  [self doTestResultWithContents:@"tel:212-555-1212" goldenResult:@"212-555-1212" type:kParsedResultTypeTel];
  [self doTestResultWithContents:@"tel" goldenResult:@"tel" type:kParsedResultTypeText];
  [self doTestResultWithContents:@"telephone" goldenResult:@"telephone" type:kParsedResultTypeText];
}

- (void)testVCard {
  [self doTestResultWithContents:@"BEGIN:VCARD\r\nEND:VCARD" goldenResult:@"" type:kParsedResultTypeAddressBook];
  [self doTestResultWithContents:@"BEGIN:VCARD\r\nN:Owen;Sean\r\nEND:VCARD" goldenResult:@"Sean Owen"
                            type:kParsedResultTypeAddressBook];
  [self doTestResultWithContents:@"BEGIN:VCARD\r\nVERSION:2.1\r\nN:Owen;Sean\r\nEND:VCARD" goldenResult:@"Sean Owen"
                            type:kParsedResultTypeAddressBook];
  [self doTestResultWithContents:@"BEGIN:VCARD\r\nADR;HOME:123 Main St\r\nVERSION:2.1\r\nN:Owen;Sean\r\nEND:VCARD"
                    goldenResult:@"Sean Owen\n123 Main St" type:kParsedResultTypeAddressBook];
  [self doTestResultWithContents:@"BEGIN:VCARD" goldenResult:@"" type:kParsedResultTypeAddressBook];
}

- (void)testVEvent {
  // UTC times
  [self doTestResultWithContents:@"BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nSUMMARY:foo\r\nDTSTART:20080504T123456Z\r\n"
                                 @"DTEND:20080505T234555Z\r\nEND:VEVENT\r\nEND:VCALENDAR"
                    goldenResult:@"foo\nMay 4, 2008 12:34:56 PM\nMay 5, 2008 11:45:55 PM"
                            type:kParsedResultTypeCalendar];
  [self doTestResultWithContents:@"BEGIN:VEVENT\r\nSUMMARY:foo\r\nDTSTART:20080504T123456Z\r\n"
                                 @"DTEND:20080505T234555Z\r\nEND:VEVENT"
                    goldenResult:@"foo\nMay 4, 2008 12:34:56 PM\nMay 5, 2008 11:45:55 PM"
                            type:kParsedResultTypeCalendar];
  // Local times
  [self doTestResultWithContents:@"BEGIN:VEVENT\r\nSUMMARY:foo\r\nDTSTART:20080504T123456\r\n"
                                 @"DTEND:20080505T234555\r\nEND:VEVENT"
                    goldenResult:@"foo\nMay 4, 2008 12:34:56 PM\nMay 5, 2008 11:45:55 PM"
                            type:kParsedResultTypeCalendar];
  // Date only (all day event)
  [self doTestResultWithContents:@"BEGIN:VEVENT\r\nSUMMARY:foo\r\nDTSTART:20080504\r\n"
                                 @"DTEND:20080505\r\nEND:VEVENT"
                    goldenResult:@"foo\nMay 4, 2008\nMay 5, 2008"
                            type:kParsedResultTypeCalendar];
  // Start time only
  [self doTestResultWithContents:@"BEGIN:VEVENT\r\nSUMMARY:foo\r\nDTSTART:20080504T123456Z\r\nEND:VEVENT"
                    goldenResult:@"foo\nMay 4, 2008 12:34:56 PM" type:kParsedResultTypeCalendar];
  [self doTestResultWithContents:@"BEGIN:VEVENT\r\nSUMMARY:foo\r\nDTSTART:20080504T123456\r\nEND:VEVENT"
                    goldenResult:@"foo\nMay 4, 2008 12:34:56 PM" type:kParsedResultTypeCalendar];
  [self doTestResultWithContents:@"BEGIN:VEVENT\r\nSUMMARY:foo\r\nDTSTART:20080504\r\nEND:VEVENT"
                    goldenResult:@"foo\nMay 4, 2008" type:kParsedResultTypeCalendar];
  [self doTestResultWithContents:@"BEGIN:VEVENT\r\nDTEND:20080505T\r\nEND:VEVENT"
                    goldenResult:@"BEGIN:VEVENT\r\nDTEND:20080505T\r\nEND:VEVENT" type:kParsedResultTypeURI];
  // Yeah, it's OK that this is thought of as maybe a URI as long as it's not CALENDAR
  // Make sure illegal entries without newlines don't crash
  [self doTestResultWithContents:@"BEGIN:VEVENTSUMMARY:EventDTSTART:20081030T122030ZDTEND:20081030T132030ZEND:VEVENT"
                    goldenResult:@"BEGIN:VEVENTSUMMARY:EventDTSTART:20081030T122030ZDTEND:20081030T132030ZEND:VEVENT"
                            type:kParsedResultTypeURI];
}

- (void)testSMS {
  [self doTestResultWithContents:@"sms:+15551212" goldenResult:@"+15551212" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"SMS:+15551212" goldenResult:@"+15551212" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"sms:+15551212;via=999333" goldenResult:@"+15551212" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"sms:+15551212?subject=foo&body=bar" goldenResult:@"+15551212\nfoo\nbar" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"sms:+15551212,+12124440101" goldenResult:@"+15551212\n+12124440101" type:kParsedResultTypeSMS];
}

- (void)testSMSTO {
  [self doTestResultWithContents:@"SMSTO:+15551212" goldenResult:@"+15551212" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"smsto:+15551212" goldenResult:@"+15551212" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"smsto:+15551212:subject" goldenResult:@"+15551212\nsubject" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"smsto:+15551212:My message" goldenResult:@"+15551212\nMy message" type:kParsedResultTypeSMS];
  // Need to handle question mark in the subject
  [self doTestResultWithContents:@"smsto:+15551212:What's up?" goldenResult:@"+15551212\nWhat's up?" type:kParsedResultTypeSMS];
  // Need to handle colon in the subject
  [self doTestResultWithContents:@"smsto:+15551212:Directions: Do this"
                    goldenResult:@"+15551212\nDirections: Do this" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"smsto:212-555-1212:Here's a longer message. Should be fine."
                    goldenResult:@"212-555-1212\nHere's a longer message. Should be fine." type:kParsedResultTypeSMS];
}

- (void)testMMS {
  [self doTestResultWithContents:@"mms:+15551212" goldenResult:@"+15551212" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"MMS:+15551212" goldenResult:@"+15551212" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"mms:+15551212;via=999333" goldenResult:@"+15551212" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"mms:+15551212?subject=foo&body=bar" goldenResult:@"+15551212\nfoo\nbar" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"mms:+15551212,+12124440101" goldenResult:@"+15551212\n+12124440101" type:kParsedResultTypeSMS];
}

- (void)testMMSTO {
  [self doTestResultWithContents:@"MMSTO:+15551212" goldenResult:@"+15551212" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"mmsto:+15551212" goldenResult:@"+15551212" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"mmsto:+15551212:subject" goldenResult:@"+15551212\nsubject" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"mmsto:+15551212:My message" goldenResult:@"+15551212\nMy message" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"mmsto:+15551212:What's up?" goldenResult:@"+15551212\nWhat's up?" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"mmsto:+15551212:Directions: Do this"
                    goldenResult:@"+15551212\nDirections: Do this" type:kParsedResultTypeSMS];
  [self doTestResultWithContents:@"mmsto:212-555-1212:Here's a longer message. Should be fine."
                    goldenResult:@"212-555-1212\nHere's a longer message. Should be fine." type:kParsedResultTypeSMS];
}

- (void)doTestResultWithContents:(NSString *)contents
                    goldenResult:(NSString *)goldenResult
                            type:(ZXParsedResultType)type {
  [self doTestResultWithContents:contents goldenResult:goldenResult type:type format:kBarcodeFormatQRCode]; // QR code is arbitrary
}

- (void)doTestResultWithContents:(NSString *)contents
                    goldenResult:(NSString *)goldenResult
                            type:(ZXParsedResultType)type
                          format:(ZXBarcodeFormat)format {
  ZXResult *fakeResult = [ZXResult resultWithText:contents rawBytes:nil resultPoints:nil format:format];
  ZXParsedResult *result = [ZXResultParser parseResult:fakeResult];
  XCTAssertNotNil(result);
  XCTAssertEqual(type, result.type);

  NSString *displayResult = result.displayResult;
  XCTAssertEqualObjects(goldenResult, displayResult);
}

@end


text:
<?php
/*
Plugin Name: Simple Automatic Updates
Plugin URI:
Description: Sets WordPress to automatically update core (major and minor releases), plugins and themes.
Author: Jon Tejnung
Version: 0.1.3
*/

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

require_once dirname(__FILE__) . '/sau-automatic-mode.class.php';
require_once dirname(__FILE__) . '/sau-manual-mode.class.php';

// Check if get_plugins() function exists. This is required on the front end of the
// site, since it is in a file that is normally only loaded in the admin.
if ( ! function_exists( 'get_plugins' ) ) {
	require_once ABSPATH . 'wp-admin/includes/plugin.php';
}

/**
 * The chosen mode
 * @var string
 *
 * @since 0.1
 */
global $sau_mode;
$sau_mode	= get_option( 'sau_mode', 'automatic' );

/**
 * The standard footer that are sent in all emails
 * @var string
 *
 * @since 0.1
 */
global $sau_mail_footer;
$sau_mail_footer = '';

/**
 * Initiate the plugin depending on which mode is selected
 */

if ( $sau_mode == 'manual' )
{
	SAU_Manual_Mode::initialize();
}
else if ( $sau_mode == 'automatic-silent' )
{
	SAU_Automatic_Mode::initialize( true );
}
else
{
	// Default to automatic
	$sau_mode = 'automatic';
	SAU_Automatic_Mode::initialize( false );
}

/**
 * Load plugin textdomain.
 * @return null
 *
 * @since 0.1
 */
function sau_load_textdomain()
{
	load_plugin_textdomain(
		'simple-automatic-updates',
		false,
		plugin_basename( dirname( __FILE__ ) ) . '/languages'
	);

	/**
	 * Define some global strings that needs translation
	 */
	global $sau_mail_footer;

	$sau_mail_footer = __(
		"This message was automatically sent from %s.\nYou can change the mode of automatic updates in the WordPress dashboard\nunder Settings->General.",
		'simple-automatic-updates'
	);
	$sau_mail_footer = sprintf( $sau_mail_footer, get_site_url() );

	return null;
}
add_action( 'plugins_loaded', 'sau_load_textdomain' );

/**
 * Run on plugin activation
 * @return null
 *
 * @since  0.1
 */
function sau_activation()
{
	/**
	 * Set last checked to 0, so that you can force a check for manual
	 * updates by de- and re-activate the plugin.
	 * We still have to wait for the cron, though.
	 */
	update_option( 'sau_last_checked', '0' );

	/**
	 * Schedule hook to run hourly
	 */
	if ( ! wp_next_scheduled( 'sau_check_updates' ) )
	{
		wp_schedule_event( time(), 'hourly', 'sau_check_updates' );
	}

	return null;
}
register_activation_hook( __FILE__, 'sau_activation' );

/**
 * Run on plugin deactivation
 * @return null
 *
 * @since  0.1
 */
function sau_deactivation()
{
	/**
	 * Remove scheduled events on deactivation.
	 */
	$event_timestamp = wp_next_scheduled( 'sau_check_updates' );
	if ( $event_timestamp )
	{
		wp_unschedule_event( $event_timestamp, 'sau_check_updates' );
	}

	return null;
}
register_deactivation_hook( __FILE__, 'sau_deactivation' );

/**
 * The function that runs every cron cycle to check if
 * a mail should be sent.
 * @return null
 */
function sau_cron_check()
{
	global $sau_mode;

	if ( $sau_mode == 'manual' )
	{
		SAU_Manual_Mode::outdated_packages_send_notice();
	}
	else if ( $sau_mode == 'automatic-silent' )
	{
		SAU_Automatic_Mode::updated_packages_clear();
	}
	else
	{
		// Default to automatic
		SAU_Automatic_Mode::updated_packages_send_notice();
	}

	return null;
}
add_action( 'sau_check_updates', 'sau_cron_check' );

/**
 * Register the mode field on the options page
 * @return Null
 *
 * @since 0.1
 */
function sau_custom_options()
{
	add_settings_field(
		'sau_mode',
		__('Automatic updates mode', 'simple-automatic-updates' ),
		'sau_mode_html',
		'general'
	);

	register_setting( 'general', 'sau_mode' );

	return null;
}
add_action( 'admin_init', 'sau_custom_options' );

/**
 * Print the input on the options page
 * @return null
 *
 * @since 0.1
 */
function sau_mode_html()
{
	$setting = esc_attr( get_option( 'sau_mode', 'automatic' ) );

	$options = array(
		'automatic'			=> __(
			'Update automatically',
			'simple-automatic-updates'
		),
		'automatic-silent'	=> __(
			'Update automatically (no email)',
			'simple-automatic-updates'
		),
		'manual'			=> __(
			'Inform about available updates once a week',
			'simple-automatic-updates'
		)
	);

	$output = "<select name='sau_mode'>";

	foreach( $options as $value => $option )
	{
		$output .= "<option value='$value'";
		if ( $value == $setting )
			$output .= ' selected';
		$output .= ">$option</option>";
	}

	$output .= '</select>';
	$output .= '
';
	$output .= __(
		'A notification about available updates or updates made will be sent to the admin email address.',
		'simple-automatic-updates'
	);
	$output .= '
';

	echo $output;

	return null;
}


text:
import os
import sys
import logging

# Add script directory to the PYTHONPATH so we can import our modules (only if run from SecureCRT)
if 'crt' in globals():
    script_dir, script_name = os.path.split(crt.ScriptFullName)
    if script_dir not in sys.path:
        sys.path.insert(0, script_dir)
else:
    script_dir, script_name = os.path.split(os.path.realpath(__file__))

# Now we can import our custom modules
from securecrt_tools import scripts
from securecrt_tools import utilities

# Create global logger so we can write debug messages from any function (if debug mode setting is enabled in settings).
logger = logging.getLogger("securecrt")
logger.debug("Starting execution of {0}".format(script_name))

# ################################################   SCRIPT LOGIC   ###################################################

def script_main(session):
    """
    | SINGLE device script
    | Author: Jamie Caesar
    | Email: jcaesar@presidio.com

    This script will grab the detailed CDP information from a Cisco IOS or NX-OS device and export it to a CSV file
    containing the important information, such as Remote Device hostname, model and IP information, in addition to the
    local and remote interfaces that connect the devices.

    **Script Settings** (found in settings/settings.ini):

    * | **strip_domains** -  A list of domain names that will be stripped away if found in the CDP remote device name.

    :param session: A subclass of the sessions.Session object that represents this particular script session (either
                    SecureCRTSession or DirectSession)
    :type session: sessions.Session
    """
    # Get script object that owns this session, so we can check settings, get textfsm templates, etc
    script = session.script

    # Start session with device, i.e. modify term parameters for better interaction (assuming already connected)
    session.start_cisco_session()

    # Validate device is running a supported OS
    session.validate_os(["IOS", "NXOS"])

    # Define the command to send to the remote device
    send_cmd = "show cdp neighbors detail"
    logger.debug("Command set to '{0}'".format(send_cmd))

    # Get domain names to strip from device IDs from settings file
    strip_list = script.settings.getlist("cdp_to_csv", "strip_domains")

    # Get the output from our above command
    raw_cdp = session.get_command_output(send_cmd)

    # Choose the TextFSM template and process the data
    template_file = script.get_template("cisco_os_show_cdp_neigh_det.template")
    fsm_results = utilities.textfsm_parse_to_list(raw_cdp, template_file, add_header=True)

    # Since "System Name" is a newer NXOS feature -- try to extract it from the device ID when its empty.
    for entry in fsm_results[1:]:
        # entry[2] is system name, entry[1] is device ID
        if entry[2] == "":
            entry[2] = utilities.extract_system_name(entry[1], strip_list=strip_list)
        # Convert list of IPs into a comma-separated list of IPs
        entry[4] = ", ".join(entry[4])
        # Convert list of Mgmt IPs into a comma-separated list of IPs
        entry[7] = ", ".join(entry[7])

    output_filename = session.create_output_filename("cdp", ext=".csv")
    utilities.list_of_lists_to_csv(fsm_results, output_filename)

    # Return terminal parameters back to the original state.
    session.end_cisco_session()

# ################################################  SCRIPT LAUNCH   ###################################################

# If this script is run from SecureCRT directly, use the SecureCRT specific class
if __name__ == "__builtin__":
    # Initialize script object
    crt_script = scripts.CRTScript(crt)
    # Get session object for the SecureCRT tab that the script was launched from.
    crt_session = crt_script.get_main_session()
    # Run script's main logic against our session
    try:
        script_main(crt_session)
    except Exception:
        crt_session.end_cisco_session()
        raise
    # Shutdown logging after
    logging.shutdown()

# If the script is being run directly, use the simulation class
elif __name__ == "__main__":
    # Initialize script object
    direct_script = scripts.DebugScript(os.path.realpath(__file__))
    # Get a simulated session object to pass into the script.
    sim_session = direct_script.get_main_session()
    # Run script's main logic against our session
    script_main(sim_session)
    # Shutdown logging after
    logging.shutdown()


text:
var should = require('should');
var kiwi = require('../../index');
var tools = kiwi.tools;

describe('Tools', function() {
  it('should be exposed', function() {
    kiwi.should.have.property('tools');
  });

  describe('createFilter', function() {
    it('should be exposed', function() {
      kiwi.tools.should.have.property('createFilter');
    });

    it('should correctly define tags', function(done) {
      tools.createFilter('prependA', function(str) {
        return 'A' + str;
      });
      new kiwi.Template('${foo|prependA}').render({foo:'bar'}, function(err, rendered) {
        if(err) return done(err);
        rendered.should.equal('Abar');
        done();
      });
    });

    it('should work with optional arguments', function(done) {
      tools.createFilter('prepend', function(str, thing) {
        return thing + str;
      });
      new kiwi.Template('${foo|prepend("woo ")}').render({foo:'bar'}, function(err, rendered) {
        if(err) return done(err);
        rendered.should.equal('woo bar');
        done();
      });
    });

    it('should accept names with alphanumerical characters', function(done) {
      tools.createFilter('Test_1', function(str, thing) {
        return thing + str;
      });
      new kiwi.Template('${foo|Test_1("boo ")}').render({foo:'bar'}, function(err, rendered) {
        if(err) return done(err);
        rendered.should.equal('boo bar');
        done();
      });
    });

    it('should throw an error when an invalid name us used', function() {
      (function() {
        tools.createFilter('Test@', function(str, thing) {
          return thing + str;
        });
      }).should.throw(/is not a valid filter name.$/);
    });
  });

  describe('createSimpleTag', function() {
    it('should be exposed', function() {
      kiwi.tools.should.have.property('createSimpleTag');
    });

    it('should correctly define tags', function(done) {
      tools.createSimpleTag('cap', function(context, name) {
        return name.toUpperCase();
      });
      new kiwi.Template('{{cap "test"}}').render({}, function(err, rendered) {
        if(err) return done(err);
        rendered.should.equal('TEST');
        done();
      });
    });

    it('should escape markup by default', function(done) {
      tools.createSimpleTag('css', function(context, name) {
        return '<link rel="stylesheet" type="text/css" src="' + name + '">';
      });
      new kiwi.Template('{{css "file.css"}}').render({}, function(err, rendered) {
        if(err) return done(err);
        rendered.should.equal('<link rel="stylesheet" type="text/css" src="file.css">');
        done();
      });
    });

    it('should not escape safe markup', function(done) {
      tools.createSimpleTag('css', function(context, name) {
        return tools.safe('<link rel="stylesheet" type="text/css" src="' + name + '">');
      });
      new kiwi.Template('{{css "file.css"}}').render({}, function(err, rendered) {
        if(err) return done(err);
        rendered.should.equal('<link rel="stylesheet" type="text/css" src="file.css">');
        done();
      });
    });

    it('should work without argument', function(done) {
      tools.createSimpleTag('foo', function(context) {
        return 'bar';
      });
      new kiwi.Template('{{foo}}').render({}, function(err, rendered) {
        if(err) return done(err);
        rendered.should.equal('bar');
        done();
      });
    });

    it('should work with dynamic arguments', function(done) {
      tools.createSimpleTag('hello', function(context, name) {
        return 'Hello, ' + name;
      });
      new kiwi.Template('{{hello name}}').render({name: 'kiwi'}, function(err, rendered) {
        if(err) return done(err);
        rendered.should.equal('Hello, kiwi');
        done();
      });
    });

    it('should work with multiple arguments', function(done) {
      tools.createSimpleTag('hello', function(context, greeting, name) {
        return 'Hello, ' + greeting + ' ' + name;
      });
      new kiwi.Template('{{hello "dear" name}}').render({name: 'kiwi'}, function(err, rendered) {
        if(err) return done(err);
        rendered.should.equal('Hello, dear kiwi');
        done();
      });
    });

    it('should pass context to handler', function(done) {
      tools.createSimpleTag('foo', function(context) {
        context.name.should.equal('kiwi');
        context.name = 'woo';
        return 'bar';
      });
      new kiwi.Template('{{foo}} ${name}').render({name: 'kiwi'}, function(err, rendered) {
        if(err) return done(err);
        rendered.should.equal('bar woo');
        done();
      });
    });

    it('should throw an error when an invalid name us used', function() {
      (function() {
        tools.createSimpleTag('foo@', function(context) {
          return 'bar';
        });
      }).should.throw(/is not a valid tag name.$/);
    });
  });
});


text:
#ifndef GLEXCEPTION_HPP
#define GLEXCEPTION_HPP

#include <exception>
#include <initializer_list>
#include <vector>
#include <string>

namespace tetra
{
    /**
     * Throw a GLException if there is an error in the GL.
     * The result of glGetError is added to the messages like so:
     * GLException: glGetError -- $error string$ -- $messages$
     */
    void onGlError(std::string file, std::string line);

    /**
     * This class is used to represent exceptions while working with OpenGL.
     */
    class GLException : public std::exception
    {
    public:
        /**
         * Construct an exception with each of the messages joined with spaces.
         */
        GLException(std::vector<std::string> messages);
        GLException(std::initializer_list<std::string> messages);

        /**
         * Get the complete exception mesage.
         */
        const char* what() const noexcept override;

    private:
        std::string errorMsg;
    };
}; /* namespace tetra */

#define _EXPAND_GL_ERR_IMPL(file, line) \
    tetra::onGlError(#file, #line);

#define _EXPAND_GL_ERR(file, line) \
    _EXPAND_GL_ERR_IMPL(file, line)

#define THROW_ON_GL_ERROR() \
    _EXPAND_GL_ERR(__FILE__, __LINE__)

#endif


text:
require "unit_helper"
# require "revily/event"
require "revily/event/handler"

# class MockHandler < Revily::Event::Handler
#   events []
#   def handle
#     run Revily::Event::Job::Null
#   end
# end

module Revily::Event
  describe Handler do
    stub_events

    class MockHandler < Revily::Event::Handler
      # events []
      def handle
        run Revily::Event::Job::Null
      end
    end
  end

  describe ".events" do
    let(:handler) { MockHandler }
    let(:event_list) { double("Revily::Event::EventList") }
    let(:job) { double("Revily::Event::Job::Null") }

    before do
      handler.events = []
    end

    it "defaults to empty array" do
      expect(handler.events).to eq []
    end

    it "using setter" do
      handler.events = %w[ incident.trigger ]
      expect(handler.events).to match_array %w[ incident.trigger ]
    end

    it "with args" do
      puts EventList.new("incident.trigger", "incident.acknowledge").events.inspect
      handler.events %w[ incident.trigger incident.acknowledge ]
      expect(handler.events).to match_array %w[ incident.trigger incident.acknowledge ]
    end

    it "calling multiple times" do
      handler.events "incident.trigger"
      handler.events "incident.acknowledge"
      handler.events "incident.resolve"
      expect(handler.events).to eq(%w[ incident.trigger incident.acknowledge incident.resolve ])
    end

    it "removes duplicate events" do
      handler.events "incident.trigger"
      handler.events "incident.trigger"
      expect(handler.events).to eq(%w[ incident.trigger ])
    end

    it "removes unknown events" do
      handler.events "bogus.event"
      handler.events "fake.event"
      expect(handler.events).to eq(%w[])
    end
  end

  describe ".supports?" do
    let(:handler) { MockHandler }
    let(:event_list) { double("Revily::Event::EventList") }
    let(:job) { double("Revily::Event::Job::Null") }

    before do
      handler.events = []
    end

    it "supports supported event" do
      handler.events "incident.trigger", "incident.resolve"
      expect(handler).to support_event("incident.trigger")
    end

    it "does not support unsupported event" do
      handler.events "incident.trigger", "incident.resolve"
      expect(handler).to_not support_event("service.create")
    end

    context "wildcards" do
      it "supports all (*)" do
        handler.events %w[ * ]
        expect(handler).to support_event("incident.trigger")
        expect(handler).to support_event("service.create")
        expect(handler).to support_event("policy.update")
        expect(handler).to support_event("incident.*")
        expect(handler).to support_event("service.*")
        expect(handler).to support_event("*")
        expect(handler).to_not support_event("bogus.event")
      end

      it "supports single namespace" do
        handler.events %w[ incident.* ]
        expect(handler).to support_event("incident.*")
        expect(handler).to support_event("incident.trigger")
        expect(handler).to support_event("incident.acknowledge")
        expect(handler).to_not support_event("service.create")
        expect(handler).to_not support_event("policy.update")
      end

      it "does not support nonexistent events" do
        handler.events "incident.*"
        expect(handler).to_not support_event("incident.foobar")
      end

      it "supports multiple namespaces" do
        handler.events %w[ incident.* service.* ]
        expect(handler).to support_event("incident.*")
        expect(handler).to support_event("incident.trigger")
        expect(handler).to support_event("service.*")
        expect(handler).to support_event("service.create")
        expect(handler).to_not support_event("policy.update")
      end

      it "supports mix of specific and namespace events" do
        handler.events %w[ incident.* service.create ]
        expect(handler).to support_event("incident.*")
        expect(handler).to support_event("incident.trigger")
        expect(handler).to support_event("service.create")
        expect(handler).to_not support_event("service.update")
        expect(handler).to_not support_event("policy.update")
      end
    end

  end

  describe ".notify" do
    let(:event) { "incident.trigger" }
    let(:source) { double("Incident") }
    let(:config) { { foo: "bar", baz: "quz" } }
    let(:options) { { event: event, source: source, config: config } }
    let(:handler) { MockHandler.new(options) }
    let(:job) { double("Revily::Event::Job::Null") }

    before do
      allow(job).to receive(:run)
    end

    context "handle? is true", :pending do
      before do
        allow(handler).to receive(:handle?).and_return(true)
      end

      it "handles the job" do
        expect(job).to have_received(:run)
      end
    end

    context "handle? is false" do
      before do
        handler.stub(:handle? => false)
      end

      it "does not handle the job" do
        expect(job).to_not have_received(:run)
      end
    end
  end
end


text:
package com.hannesdorfmann.mosby3.mvp.delegate;

import android.app.Application;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import com.hannesdorfmann.mosby3.mvp.MvpPresenter;
import com.hannesdorfmann.mosby3.mvp.MvpView;
import com.hannesdorfmann.mosby3.mvp.viewstate.ViewState;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

/**
 * @author Hannes Dorfmann
 */
@RunWith(PowerMockRunner.class) @PrepareForTest({ Fragment.class })
public class FragmentMvpViewStateDelegateImplTest {

  // TODO write test for retaining fragment

  private MvpView view;
  private MvpPresenter<MvpView> presenter;
  private MvpViewStateDelegateCallback<MvpView, MvpPresenter<MvpView>, ViewState<MvpView>> callback;
  private FragmentMvpViewStateDelegateImpl<MvpView, MvpPresenter<MvpView>, ViewState<MvpView>>
      delegate;
  private Fragment fragment;
  private FragmentActivity activity;
  private Application application;
  private ViewState<MvpView> viewState;

  @Before public void initComponents() {
    view = new MvpView() {
    };

    viewState = Mockito.mock(ViewState.class);

    presenter = Mockito.mock(MvpPresenter.class);
    callback = Mockito.spy(PartialMvpViewStateDelegateCallbackImpl.class);
    Mockito.doCallRealMethod().when(callback).setPresenter(presenter);
    Mockito.doCallRealMethod().when(callback).getPresenter();
    Mockito.doCallRealMethod().when(callback).setViewState(viewState);
    Mockito.doCallRealMethod().when(callback).getViewState();

    fragment = PowerMockito.mock(Fragment.class);
    activity = Mockito.mock(FragmentActivity.class);
    application = Mockito.mock(Application.class);

    Mockito.when(callback.getMvpView()).thenReturn(view);
    Mockito.when(fragment.getActivity()).thenReturn(activity);

    Mockito.when(activity.getApplication()).thenReturn(application);

    Mockito.when(callback.createPresenter()).thenReturn(presenter);
    Mockito.when(callback.createViewState()).thenReturn(viewState);

    delegate = new FragmentMvpViewStateDelegateImpl<>(fragment, callback, true, true);
  }

  @Test public void appStartWithScreenOrientationChangeAndFinallyFinishing() {
    startFragment(null, 1, 1, 1, 1, 1, 0, null, 0, 1, 0);
    Bundle bundle = BundleMocker.create();
    finishFragment(bundle, 1, true, true, false);
    startFragment(bundle, 1, 2, 2, 1, 2, 1, true, 1, 1, 1);
    finishFragment(bundle, 1, false, false, true);
  }

  @Test public void appStartFinishing() {
    startFragment(null, 1, 1, 1, 1, 1, 0, null, 0, 1, 0);
    Bundle bundle = BundleMocker.create();
    finishFragment(bundle, 1, false, false, true);
    Mockito.verifyNoMoreInteractions(viewState);
  }

  @Test public void dontKeepPresenter() {
    delegate = new FragmentMvpViewStateDelegateImpl<>(fragment, callback, false, false);
    startFragment(null, 1, 1, 1, 1, 1, 0, null, 0, 1, 0);
    Bundle bundle = BundleMocker.create();
    finishFragment(bundle, 1, false, true, false);
    startFragment(null, 2, 2, 2, 2, 2, 0, null, 0, 2, 0);
    finishFragment(bundle, 2, false, false, true);
  }

  /**
   * Checks if two Fragments one that keeps presenter, the other who doesn't keep presenter during
   * screen orientation changes work properly
   *
   * https://github.com/sockeqwe/mosby/issues/231
   */
  @Test public void dontKeepPresenterWithSecondFragmentInPresenterManager() {
    MvpView view1 = new MvpView() {
    };
    ViewState<MvpView> viewState1 = Mockito.mock(ViewState.class);

    MvpPresenter<MvpView> presenter1 = Mockito.mock(MvpPresenter.class);
    PartialMvpViewStateDelegateCallbackImpl callback1 =
        Mockito.spy(PartialMvpViewStateDelegateCallbackImpl.class);
    Fragment fragment1 = PowerMockito.mock(Fragment.class);

    Mockito.doCallRealMethod().when(callback1).setPresenter(presenter1);
    Mockito.doCallRealMethod().when(callback1).getPresenter();
    Mockito.doCallRealMethod().when(callback1).setViewState(viewState1);
    Mockito.doCallRealMethod().when(callback1).getViewState();
    Mockito.when(callback1.getMvpView()).thenReturn(view1);
    Mockito.when(fragment1.getActivity()).thenReturn(activity);
    Mockito.when(callback1.createPresenter()).thenReturn(presenter1);
    Mockito.when(callback1.createViewState()).thenReturn(viewState1);

    FragmentMvpViewStateDelegateImpl<MvpView, MvpPresenter<MvpView>, ViewState<MvpView>>
        keepDelegate = new FragmentMvpViewStateDelegateImpl<>(fragment1, callback1, true, false);

    startFragment(keepDelegate, null);

    delegate = new FragmentMvpViewStateDelegateImpl<>(fragment, callback, false, false);
    startFragment(null, 1, 1, 1, 1, 1, 0, null, 0, 1, 0);
    Bundle bundle = BundleMocker.create();
    finishFragment(bundle, 1, false, true, false);
    startFragment(null, 2, 2, 2, 2, 2, 0, null, 0, 2, 0);
    finishFragment(bundle, 2, false, false, true);

    finishFragment(keepDelegate, BundleMocker.create());
  }

  @Test public void appStartAfterProcessDeathAndViewStateRecreationFromBundle() {
    Mockito.doAnswer(new Answer() {
      @Override public Object answer(InvocationOnMock invocation) throws Throwable {
        viewState = Mockito.spy(new SimpleRestorableViewState());
        return viewState;
      }
    }).when(callback).createViewState();

    Bundle bundle = BundleMocker.create();
    bundle.putString(FragmentMvpViewStateDelegateImpl.KEY_MOSBY_VIEW_ID, "123456789");

    startFragment(bundle, 1, 1, 1, 1, 1, 1, false, 1, 0, 1);
  }

  @Test public void appStartWithViewStateFromMemoryAndBundleShouldPreferViewStateFromMemory() {

    Mockito.doAnswer(new Answer() {
      @Override public Object answer(InvocationOnMock invocation) throws Throwable {
        viewState = Mockito.spy(new SimpleRestorableViewState());
        return viewState;
      }
    }).when(callback).createViewState();

    startFragment(null, 1, 1, 1, 1, 1, 0, null, 0, 1, 0);
    Bundle bundle = BundleMocker.create();
    finishFragment(bundle, 1, true, true, false);
    startFragment(bundle, 1, 2, 2, 1, 2, 1, true, 1, 1, 1);
    finishFragment(bundle, 1, false, false, true);
  }

  private void startFragment(
      FragmentMvpViewStateDelegateImpl<MvpView, MvpPresenter<MvpView>, ViewState<MvpView>> delegate,
      Bundle bundle) {

    delegate.onAttach(activity);
    delegate.onCreate(bundle);
    delegate.onViewCreated(null, bundle);
    delegate.onActivityCreated(bundle);
    delegate.onStart();
    delegate.onResume();
  }

  private void startFragment(Bundle bundle, int createPresenter, int setPresenter, int attachView,
      int createViewState, int setViewState, int applyViewState,
      Boolean viewsStateRestoredFromMemory, int setRestoreViewState, int onNewViewStateInstance,
      int onViewStateInstanceRestored) {

    startFragment(delegate, bundle);

    Mockito.verify(callback, Mockito.times(createPresenter)).createPresenter();
    Mockito.verify(callback, Mockito.times(setPresenter)).setPresenter(presenter);
    Mockito.verify(presenter, Mockito.times(attachView)).attachView(view);

    Mockito.verify(callback, Mockito.times(createViewState)).createViewState();
    Mockito.verify(callback, Mockito.times(setViewState)).setViewState(viewState);

    if (viewsStateRestoredFromMemory == null) {
      Mockito.verify(viewState, Mockito.times(0)).apply(Mockito.eq(view), Mockito.eq(true));
      Mockito.verify(viewState, Mockito.times(0)).apply(Mockito.eq(view), Mockito.eq(false));
    } else {
      Mockito.verify(viewState, Mockito.times(applyViewState))
          .apply(Mockito.eq(view), Mockito.eq(viewsStateRestoredFromMemory));
    }

    Mockito.verify(callback, Mockito.times(setRestoreViewState)).setRestoringViewState(true);
    Mockito.verify(callback, Mockito.times(setRestoreViewState)).setRestoringViewState(false);

    Mockito.verify(callback, Mockito.times(onNewViewStateInstance)).onNewViewStateInstance();

    if (viewsStateRestoredFromMemory == null) {
      Mockito.verify(callback, Mockito.times(0)).onViewStateInstanceRestored(true);
      Mockito.verify(callback, Mockito.times(0)).onViewStateInstanceRestored(false);
    } else {
      Mockito.verify(callback, Mockito.times(onViewStateInstanceRestored))
          .onViewStateInstanceRestored(viewsStateRestoredFromMemory);
    }
  }

  private void finishFragment(
      FragmentMvpViewStateDelegateImpl<MvpView, MvpPresenter<MvpView>, ViewState<MvpView>> delegate,
      Bundle bundle) {
    delegate.onPause();
    delegate.onSaveInstanceState(bundle);
    delegate.onStop();
    delegate.onDestroyView();
    delegate.onDestroy();
    delegate.onDetach();
  }

  private void finishFragment(Bundle bundle, int detachViewCount, boolean expectKeepPresenter,
      boolean changingConfigurations, boolean isFinishing) {
    Mockito.when(callback.getPresenter()).thenReturn(presenter);
    Mockito.when(activity.isChangingConfigurations()).thenReturn(changingConfigurations);
    Mockito.when(activity.isFinishing()).thenReturn(isFinishing);
    finishFragment(delegate, bundle);
    Mockito.verify(presenter, Mockito.times(detachViewCount)).detachView(expectKeepPresenter);
  }
}


text:
/* ###
 * IP: GHIDRA
 * REVIEWED: YES
 *
 * 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.
 */
package ghidra.program.model.lang;

import java.util.ArrayList;
import java.util.List;

/**
 * The RegisterTree class builds and represents relationships between registers. Any
 * register that "breaks down" into smaller registers can be represent by a
 * RegisterTree.  The largest register will be at the root and the registers that
 * make it up will be its children trees.  The children are RegisterTrees as well
 * and can have children trees of thier own.  The root of a RegisterTree may not
 * have an associated Register which means that its children are unrelated.  This
 * way all the registers of a processor can be represented as a single RegisterTree.
 */
public class RegisterTree implements Comparable<RegisterTree> {
	private static final String SEPARATOR = ".";
	private Register register;
	private RegisterTree parent;
	private ArrayList<RegisterTree> children;
	private String name;

	public RegisterTree(Register reg) {
		this.name = reg.getName();
		this.register = reg;
		List<Register> registerChildren = reg.getChildRegisters();
		this.children = new ArrayList<RegisterTree>();
		for (Register childReg : registerChildren) {
			RegisterTree tree = new RegisterTree(childReg);
			tree.parent = this;
			this.children.add(tree);
		}
	}

	/**
	 * Constructs a RegisterTree with the given name and set of registers
	 * @param name the name of the tree
	 * @param regs the array of registers to form into a tree
	 */
	public RegisterTree(String name, Register[] regs) {
		this.name = name;
		children = new ArrayList<RegisterTree>();
		for (Register reg : regs) {
			if (reg.isBaseRegister()) {
				RegisterTree tree = new RegisterTree(reg);
				tree.parent = this;
				children.add(tree);
			}
		}
	}

	/**
	 * Constructs a RegisterTree with one RegisterTree child
	 * @param name the name of this tree
	 * @param tree the child tree.
	 */
	public RegisterTree(String name, RegisterTree tree) {
		this.name = name;
		children = new ArrayList<RegisterTree>();
		children.add(tree);
	}

	/**
	 * Returns the name of this register tree.
	 */
	public String getName() {
		return name;
	}

	/**
	 * Adds a Register Tree to this tree.
	 * @param tree the register tree to add
	 */
	public void add(RegisterTree tree) {
		children.add(tree);
		tree.parent = this;
	}

	/**
	 * Get the RegisterTrees that are the children of this RegisterTree
	 * @return a array of RegisterTrees
	 */
	public RegisterTree[] getComponents() {
		return children.toArray(new RegisterTree[children.size()]);
	}

	/**
	 * Returns the Register associated with this tree. This may be null which
	 * indicates the children RegisterTrees are unrelated to each other.
	 */
	public Register getRegister() {
		return register;
	}

	/**
	 * Returns the parent RegisterTree.
	 */
	public RegisterTree getParent() {
		return parent;
	}

	/**
	 * The parent path of this RegisterTree if it exists or null if this tree has no parent or
	 * no parent with a register.
	 * @return The parent path of this RegisterTree.
	 */
	public String getParentRegisterPath() {
		RegisterTree parentTree = getParent();
		if (parentTree == null || (parentTree.getRegister() == null)) {
			return null;
		}

		return parentTree.getRegisterPath();
	}

	/**
	 * The path of this register, which includes the parent path of this RegisterTree if this
	 * RegisterTree has a parent.
	 * @return the path of this register.
	 */
	public String getRegisterPath() {
		String parentPath = getParentRegisterPath();

		if (parentPath != null) {
			return parentPath + SEPARATOR + getRegister().getName();
		}

		return getRegister().getName();
	}

	/**
	 * Returns the RegisterTree for the given register if one exists in this RegisterTree object.
	 * @param  register1 The register for which to get a RegisterTree.
	 * @return The RegisterTree for the given register if one exists in this RegisterTree object.
	 */
	public RegisterTree getRegisterTree(Register register1) {
		if (this.register == register1) {
			return this;
		}
		for (RegisterTree child : children) {
			RegisterTree tree = child.getRegisterTree(register1);
			if (tree != null) {
				return tree;
			}
		}
		return null;
	}

	/**
	 * @see java.lang.Comparable#compareTo(java.lang.Object)
	 */
	public int compareTo(RegisterTree other) {
		return name.compareTo(other.name);
	}

	/**
	 * Removes the register from the children
	 * @param reg the register to remove.
	 */
	public void remove(Register reg) {
		RegisterTree tree = getRegisterTree(reg);
		if (tree == null) {
			return;
		}
		if (tree.getParent() == null) {
			return;
		}
		tree.getParent().children.remove(tree);
	}

	/**
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		StringBuffer buffer = new StringBuffer(name);
		buffer.append('[');
		for (RegisterTree child : children) {
			buffer.append(child.toString());
			buffer.append(',');
		}
		buffer.append(']');
		return buffer.toString();
	}
}


text:
using System;
using System.Globalization;
using CG.Web.MegaApiClient;

namespace IgorSoft.PowerShellCloudProvider.Gateways.Mega.Auth
{
    internal static class Authenticator
    {
        private static MegaApiClient.AuthInfos LoadRefreshToken(string account)
        {
            var refreshTokens = Settings.Default.RefreshTokens;
            if (refreshTokens != null)
                foreach (RefreshTokenSetting setting in refreshTokens)
                    if (setting.Account == account)
                        return new MegaApiClient.AuthInfos(setting.EMail, setting.Hash, setting.PasswordAesKey);

            return  null;
        }

        private static void SaveRefreshToken(string account, MegaApiClient.AuthInfos refreshToken)
        {
            var refreshTokens = Settings.Default.RefreshTokens;
            if (refreshTokens != null) {
                foreach (RefreshTokenSetting setting in refreshTokens)
                    if (setting.Account == account) {
                        refreshTokens.Remove(setting);
                        break;
                    }
            } else {
                refreshTokens = Settings.Default.RefreshTokens = new System.Collections.ObjectModel.Collection<RefreshTokenSetting>();
            }

            refreshTokens.Insert(0, new RefreshTokenSetting() { Account = account, EMail = refreshToken.Email, Hash = refreshToken.Hash, PasswordAesKey = refreshToken.PasswordAesKey });

            Settings.Default.Save();
        }

        public static MegaApiClient Login(string account, string code)
        {
            if (string.IsNullOrEmpty(account))
                throw new ArgumentNullException(nameof(account));

            var client = new MegaApiClient();

            var refreshToken = LoadRefreshToken(account);

            if (refreshToken != null) {
                client.Login(refreshToken);
            } else {
                if (string.IsNullOrEmpty(code))
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.ProvideAuthenticationData, account));

                var parts = code.Split(new[] { ',' }, 2);
                if (parts.Length != 2)
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.ProvideAuthenticationData, account));

                client.Login(parts[0], parts[1]);
            }

            refreshToken = (MegaApiClient.AuthInfos)typeof(MegaApiClient).GetField("_authInfos", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(client);
            SaveRefreshToken(account, refreshToken);

            return client;
        }
    }
}


text:
taglib version 2 bindings

# BUILD STATUS
[![Build status](https://ci.appveyor.com/api/projects/status/fkt7jiqubahuja5o?svg=true)](https://ci.appveyor.com/project/0x00A/node-taglib2)

# INSTALLATION

### OSX/Linux

You need to have installed a proper C/C++ compiler toolchain, like GCC (For OSX please download [Xcode and Command Line Tools](https://developer.apple.com/xcode/))

### Windows

You need to have Visual C++ Build Environment setup, which you can download as a standalone [Visual C++ Build Tools](http://landinghub.visualstudio.com/visual-cpp-build-tools) package or get it as part of [Visual Studio 2015](https://www.visualstudio.com/products/visual-studio-community-vs).

# USAGE
For example, with electron...

```
ELECTRON=1 npm install
```

### WRITING TAGS
Note that `track` will overwrite `tracknumber` if specified in the same write.

```js
const taglib = require('taglib2')
const mime = require('node-mime')
const fs = require('fs')

const props = {
  artist: 'Howlin\' Wolf',
  title: 'Evil is goin\' on',
  album: 'Smokestack Lightnin\'',
  comment: 'Chess Master Series',
  genre: 'blues',
  year: 1951,
  track: 3,
  tracknumber: '1/1',
  discnumber: '1/1',
  pictures: [
    {
      "mimetype": mime('./cover.jpg'),
      "picture": fs.readFileSync('./cover.jpg')
    }
  ],
}

taglib.writeTagsSync('./file.mp3', props)
```

### READING TAGS

```js
const taglib = require('taglib2')
const tags = taglib.readTagsSync('./file.mp3')
```

#### OUTPUT
`tags.pictures` will be an array of buffers that contain image data.

```json
{
  "artist": "Howlin' Wolf",
  "albumartist": "Howlin' Wolf",
  "title": "Evil is goin' on",
  "album": "Smokestack Lightnin'",
  "comment": "Chess Master Series",
  "composer": "Chester Burnett",
  "genre": "blues",
  "year": 1951,
  "track": 3,
  "tracknumber": "3/3",
  "discnumber": "1/1",
  "pictures": [
    {
      "mimetype": "image/jpeg",
      "picture": <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 ... >
    }
  ],
  "bitrate": 192,
  "bpm": 120,
  "samplerate": 44100,
  "channels": 2,
  "compilation": false,
  "time": "1:30",
  "length": 90
}
```


text:
<?xml version="1.0" ?>
<CIM CIMVERSION="2.0" DTDVERSION="2.0">
 <MESSAGE ID="7873" PROTOCOLVERSION="1.0">
  <SIMPLEREQ>
   <IMETHODCALL NAME="EnumerateClassNames">
    <LOCALNAMESPACEPATH>
     <NAMESPACE NAME="test"/>
     <NAMESPACE NAME="static"/>
    </LOCALNAMESPACEPATH>
    <IPARAMVALUE NAME="ClassName">
     <CLASSNAME NAME="WET_Statistics"/>
    </IPARAMVALUE>
    <IPARAMVALUE NAME="DeepInheritance">
     <VALUE>
      TRUE
     </VALUE>
    </IPARAMVALUE>
   </IMETHODCALL>
  </SIMPLEREQ>
 </MESSAGE>
</CIM>


text:
require 'test_helper'

class IssuesControllerTest < ActionDispatch::IntegrationTest
  setup do
    @issue = issues(:one)
  end

  test "should get index" do
    get issues_url
    assert_response :success
  end

  test "should get new" do
    get new_issue_url
    assert_response :success
  end

  test "should create issue" do
    assert_difference('Issue.count') do
      post issues_url, params: { issue: { department: @issue.department, description: @issue.description } }
    end

    assert_redirected_to issue_url(Issue.last)
  end

  test "should show issue" do
    get issue_url(@issue)
    assert_response :success
  end

  test "should get edit" do
    get edit_issue_url(@issue)
    assert_response :success
  end

  test "should update issue" do
    patch issue_url(@issue), params: { issue: { department: @issue.department, description: @issue.description } }
    assert_redirected_to issue_url(@issue)
  end

  test "should destroy issue" do
    assert_difference('Issue.count', -1) do
      delete issue_url(@issue)
    end

    assert_redirected_to issues_url
  end
end


text:
__author__ = 'magus0219'

import logging
from tornado.web import authenticated
from .common_handler import CommonHandler
from utils.saferedisclient import redis_manager

logger_server = logging.getLogger("DeployServer.LogoutHandler")

class LogoutHandler(CommonHandler):
    @authenticated
    def get(self):
        user_id = self.get_current_user()

        tokens = redis_manager.keys('{userid}:*'.format(userid=user_id))

        for one_token in tokens:
            redis_manager.delete(one_token)

        self.clear_cookie('d-token')

        self.redirect("/deploy/login")