text:
<meta charset="utf-8">
(#) Missing `onPlayFromSearch`

!!! ERROR: Missing `onPlayFromSearch`
   This is an error.

Id
:   `MissingOnPlayFromSearch`
Summary
:   Missing `onPlayFromSearch`
Severity
:   Error
Category
:   Correctness
Platform
:   Android
Vendor
:   Android Open Source Project
Feedback
:   https://issuetracker.google.com/issues/new?component=192708
Affects
:   Kotlin and Java files, manifest files and resource files
Editing
:   This check runs on the fly in the IDE editor
See
:   https://developer.android.com/training/auto/audio/index.html#support_voice
Implementation
:   [Source Code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-checks/src/main/java/com/android/tools/lint/checks/AndroidAutoDetector.java)
Tests
:   [Source Code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-tests/src/test/java/com/android/tools/lint/checks/AndroidAutoDetectorTest.java)
Copyright Year
:   2015

To support voice searches on Android Auto, in addition to adding an
`intent-filter` for the action `onPlayFromSearch`, you also need to
override and implement `onPlayFromSearch(String query, Bundle bundle)`

(##) Example

Here is an example of lint warnings produced by this check:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~text
src/com/example/android/uamp/MSessionCallback.java:5:Error: This class
does not override onPlayFromSearch from MediaSession.Callback The method
should be overridden and implemented to support Voice search on Android
Auto. [MissingOnPlayFromSearch]

public class MSessionCallback extends Callback {
             ----------------

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here is the source file referenced above:

`src/com/example/android/uamp/MSessionCallback.java`:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~java linenumbers
package com.example.android.uamp;

import android.media.session.MediaSession.Callback;

public class MSessionCallback extends Callback {
    @Override
    public void onPlay() {
        // custom impl
    }
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can also visit the
[source code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-tests/src/test/java/com/android/tools/lint/checks/AndroidAutoDetectorTest.java)
for the unit tests for this check to see additional scenarios.

The above example was automatically extracted from the first unit test
found for this lint check, `AndroidAutoDetector.testMissingOnPlayFromSearch`.
To report a problem with this extracted sample, visit
https://issuetracker.google.com/issues/new?component=192708.

(##) Suppressing

You can suppress false positives using one of the following mechanisms:

* Using a suppression annotation like this on the enclosing
  element:

  ```kt
  // Kotlin
  @Suppress("MissingOnPlayFromSearch")
  fun method() {
     problematicStatement()
  }
  ```

  or

  ```java
  // Java
  @SuppressWarnings("MissingOnPlayFromSearch")
  void method() {
     problematicStatement();
  }
  ```

* Using a suppression comment like this on the line above:

  ```kt
  //noinspection MissingOnPlayFromSearch
  problematicStatement()
  ```

* Adding the suppression attribute
  `tools:ignore="MissingOnPlayFromSearch"` on the problematic XML
  element (or one of its enclosing elements). You may also need to add
  the following namespace declaration on the root element in the XML
  file if it's not already there:
  `xmlns:tools="http://schemas.android.com/tools"`.

  ```xml
  <?xml version="1.0" encoding="UTF-8"?>
  <manifest xmlns:tools="http://schemas.android.com/tools">
      ...
      <automotiveApp tools:ignore="MissingOnPlayFromSearch" .../>
    ...
  </manifest>
  ```

* Using a special `lint.xml` file in the source tree which turns off
  the check in that folder and any sub folder. A simple file might look
  like this:
  ```xml
  <?xml version="1.0" encoding="UTF-8"?>
  <lint>
      <issue id="MissingOnPlayFromSearch" severity="ignore" />
  </lint>
  ```
  Instead of `ignore` you can also change the severity here, for
  example from `error` to `warning`. You can find additional
  documentation on how to filter issues by path, regular expression and
  so on
  [here](https://googlesamples.github.io/android-custom-lint-rules/usage/lintxml.md.html).

* In Gradle projects, using the DSL syntax to configure lint. For
  example, you can use something like
  ```gradle
  lintOptions {
      disable 'MissingOnPlayFromSearch'
  }
  ```
  In Android projects this should be nested inside an `android { }`
  block.

* For manual invocations of `lint`, using the `--ignore` flag:
  ```
  $ lint --ignore MissingOnPlayFromSearch ...`
  ```

* Last, but not least, using baselines, as discussed
  [here](https://googlesamples.github.io/android-custom-lint-rules/usage/baselines.md.html).

<!-- Markdeep: --><style class="fallback">body{visibility:hidden;white-space:pre;font-family:monospace}</style><script src="markdeep.min.js" charset="utf-8"></script><script src="https://morgan3d.github.io/markdeep/latest/markdeep.min.js" charset="utf-8"></script><script>window.alreadyProcessedMarkdeep||(document.body.style.visibility="visible")</script>

redpajama_set_name: RedPajamaGithub


text:
package com.gelakinetic.mtgfam.fragments;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Html;
import android.text.InputType;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.alertdialogpro.AlertDialogPro;
import com.gelakinetic.mtgfam.FamiliarActivity;
import com.gelakinetic.mtgfam.R;
import com.gelakinetic.mtgfam.helpers.ToastWrapper;

import org.jetbrains.annotations.NotNull;

/**
 * This fragment contains a players profile information such as their DCI number and anything else
 * we can think of to go here
 */
public class ProfileFragment extends FamiliarFragment {

    /* Dialog constants */
    private static final int DIALOG_DCI_NUMBER = 1;

    /* UI Elements */
    private TextView mBarcodeTextView;
    private TextView mDCINumberTextView;
    private TextView mNoDCINumberTextView;

    /* String variables */
    private String mDCINumber;

    /**
     * Initialize the view and set up the button actions
     *
     * @param inflater           The LayoutInflater object that can be used to inflate any views in the fragment,
     * @param container          If non-null, this is the parent view that the fragment's UI should be attached to. The
     *                           fragment should not add the view itself, but this can be used to generate the
     *                           LayoutParams of the view.
     * @param savedInstanceState If non-null, this fragment is being re-constructed from a previous saved state as given
     *                           here.
     * @return The inflated view
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View myFragmentView = inflater.inflate(R.layout.profile_frag, container, false);

        assert myFragmentView != null;
        mBarcodeTextView = (TextView) myFragmentView.findViewById(R.id.barcode);
        mDCINumberTextView = (TextView) myFragmentView.findViewById(R.id.dci_number);
        mNoDCINumberTextView = (TextView) myFragmentView.findViewById(R.id.no_dci_number);

        Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "free3of9.ttf");
        mBarcodeTextView.setTypeface(tf);

        mDCINumber = getFamiliarActivity().mPreferenceAdapter.getDCINumber();

        checkDCINumber();

        return myFragmentView;
    }

    /**
     * @param menu     The options menu in which you place your items.
     * @param inflater The inflater to use to inflate the menu
     */
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.profile_menu, menu);
    }

    /**
     * Handle an ActionBar item click
     *
     * @param item the item clicked
     * @return true if the click was acted on
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.profile_menu_update_dci:
                showDialog();
                return true;
            case R.id.profile_menu_remove_dci:
                getFamiliarActivity().mPreferenceAdapter.setDCINumber("");
                mDCINumber = "";
                checkDCINumber();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Set up menu buttons depending on whether a DCI number has been entered
     *
     * @param menu The options menu in which you place your items.
     */
    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        MenuItem updateDCI = menu.findItem(R.id.profile_menu_update_dci);
        MenuItem removeDCI = menu.findItem(R.id.profile_menu_remove_dci);
        assert updateDCI != null;
        assert removeDCI != null;

        if (getFamiliarActivity() == null || !getFamiliarActivity().mIsMenuVisible) {
            updateDCI.setVisible(false);
            removeDCI.setVisible(false);
        } else if (mDCINumber != null && !mDCINumber.isEmpty()) {
            updateDCI.setVisible(false);
            removeDCI.setVisible(true);
        } else {
            updateDCI.setVisible(true);
            removeDCI.setVisible(false);
        }
    }

    private void showDialog() throws IllegalStateException {
        /* DialogFragment.show() will take care of adding the fragment in a transaction. We also want to remove any
        currently showing dialog, so make our own transaction and take care of that here. */

		/* If the fragment isn't visible (maybe being loaded by the pager), don't show dialogs */
        if (!this.isVisible()) {
            return;
        }

        removeDialog(getFragmentManager());

		/* Create and show the dialog. */
        final FamiliarDialogFragment newFragment = new FamiliarDialogFragment() {

            @NotNull
            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                /* We're setting this to false if we return null, so we should reset it every time to be safe */
                setShowsDialog(true);
                switch (ProfileFragment.DIALOG_DCI_NUMBER) {
                    case DIALOG_DCI_NUMBER: {
                        View view = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                                .inflate(R.layout.alert_dialog_text_entry, null, false);

                        final EditText dciEditText = (EditText) view.findViewById(R.id.text_entry);
                        dciEditText.setInputType(InputType.TYPE_CLASS_NUMBER);

                        view.findViewById(R.id.clear_button).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dciEditText.setText("");
                            }
                        });

                        final String strDCI = getFamiliarActivity().mPreferenceAdapter.getDCINumber();

                        dciEditText.setText(strDCI);

                        return new AlertDialogPro.Builder(getActivity())
                                .setTitle(R.string.profile_update_dci_dialog_title)
                                .setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        String strNumber = dciEditText.getText().toString();

                                        if (strNumber.isEmpty()) {
                                            ToastWrapper.makeText(getActivity(),
                                                    getString(R.string.profile_invalid_dci),
                                                    ToastWrapper.LENGTH_SHORT).show();

                                            return;
                                        }

                                        getFamiliarActivity().mPreferenceAdapter.setDCINumber(strNumber);
                                        mDCINumber = strNumber;
                                        checkDCINumber();
                                        dismiss();
                                    }
                                })
                                .setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        checkDCINumber();
                                        dismiss();
                                    }
                                })
                                .setView(view)
                                .create();
                    }
                    default: {
                        return DontShowDialog();
                    }
                }
            }
        };
        newFragment.show(getFragmentManager(), FamiliarActivity.DIALOG_TAG);
    }

    private void checkDCINumber() {
        if (mDCINumber.isEmpty()) {
            hideDCINumber();
        } else {
            showDCINumber();
        }
        getActivity().supportInvalidateOptionsMenu();
    }

    private void hideDCINumber() {
        mDCINumberTextView.setVisibility(View.GONE);
        mBarcodeTextView.setVisibility(View.GONE);
        mNoDCINumberTextView.setText(R.string.profile_no_dci);
        mNoDCINumberTextView.setClickable(false);
    }

    private void showDCINumber() {
        mDCINumberTextView.setText(mDCINumber);
        mBarcodeTextView.setText(mDCINumber);
        mDCINumberTextView.setVisibility(View.VISIBLE);
        mBarcodeTextView.setVisibility(View.VISIBLE);

        mNoDCINumberTextView.setText(Html.fromHtml("" + getString(R.string.profile_planeswalker_points) + ""));
        mNoDCINumberTextView.setClickable(true);
        mNoDCINumberTextView.setMovementMethod(LinkMovementMethod.getInstance());
    }
}


text:
package com.hackbulgaria.corejava;

public class Problems2Factory {
    String OATH_TOKEN = "THIS IS MY DEAR PASSWORD";

    public static Problems2 createProblems2Instance() {
        return new Problems2Impl();
    }

    public static void main(String[] args) {
    }

    public static void meh(Integer k) {
    }
}


text:
<?php

namespace App\Controller\Admin;

use App\Core\Controller;
use Base;

class HelpController extends Controller
{
    public function tocAction(Base $app)
    {
        $this->renderAdmin('help/toc.html');
    }

    public function aboutAction(Base $app)
    {
        $this->renderAdmin('help/about.html');
    }
}


text:
from tigershark.facade import CompositeAccess
from tigershark.facade import ElementAccess
from tigershark.facade import Facade
from tigershark.facade import SegmentAccess
from tigershark.facade import SegmentConversion
from tigershark.facade import SegmentSequenceAccess
from tigershark.facade import X12LoopBridge
from tigershark.facade import X12SegmentBridge
from tigershark.facade import enum
from tigershark.facade.enums.eligibility import coverage_level
from tigershark.facade.enums.eligibility import insurance_type
from tigershark.facade.enums.eligibility import service_type_codes
from tigershark.facade.f27x import Address
from tigershark.facade.f27x import ContactInformation
from tigershark.facade.f27x import DateOrTimePeriod
from tigershark.facade.f27x import DemographicInformation
from tigershark.facade.f27x import Diagnosis
from tigershark.facade.f27x import Hierarchy
from tigershark.facade.f27x import Header
from tigershark.facade.f27x import Location
from tigershark.facade.f27x import NamedEntity
from tigershark.facade.f27x import ProviderInformation
from tigershark.facade.f27x import ReferenceID
from tigershark.facade.f27x import Relationship
from tigershark.facade.f27x import TraceNumber
from tigershark.facade.utils import first

class Source(Facade, X12LoopBridge):
    """The information source is the entity with the eligibility answers"""
    loopName = "2000A"

    hierarchy = SegmentAccess("HL", x12type=SegmentConversion(Hierarchy))

    class _Information(X12LoopBridge):
        loopName = "2100A"

        name = SegmentAccess("NM1",
                x12type=SegmentConversion(NamedEntity))

    def __init__(self, anX12Message, *args, **kwargs):
        super(Source, self).__init__(anX12Message, *args, **kwargs)
        self.source_information = first(self.loops(
            self._Information, anX12Message))
        self.receivers = self.loops(Receiver, anX12Message)

class Receiver(Facade, X12LoopBridge):
    """The entity asking the questions"""
    loopName = "2000B"

    hierarchy = SegmentAccess("HL", x12type=SegmentConversion(Hierarchy))

    class _Information(X12LoopBridge):
        loopName = "2100B"

        name = SegmentAccess("NM1",
                x12type=SegmentConversion(NamedEntity))
        reference_ids = SegmentSequenceAccess("REF",
                x12type=SegmentConversion(ReferenceID))
        address_street = SegmentAccess("N3",
                x12type=SegmentConversion(Address))
        address_location = SegmentAccess("N4",
                x12type=SegmentConversion(Location))
        contact_information = SegmentSequenceAccess("PER",
                x12type=SegmentConversion(ContactInformation))
        provider_information = SegmentAccess("PRV",
                x12type=SegmentConversion(ProviderInformation))

    def __init__(self, anX12Message, *args, **kwargs):
        super(Receiver, self).__init__(anX12Message, *args, **kwargs)
        self.receiver_information = first(self.loops(
            self._Information, anX12Message))
        self.subscribers = self.loops(Subscriber, anX12Message)

class EligibilityOrBenefitInquiry(X12SegmentBridge):
    service_type = ElementAccess("EQ", 1, x12type=enum(
        service_type_codes))
    ada_code = CompositeAccess("EQ", "AD", 2)
    cpt_code = CompositeAccess("EQ", "CJ", 2)
    hcpcs_code = CompositeAccess("EQ", "HC", 2)
    icd_9_cm_code = CompositeAccess("EQ", "ID", 2)
    hiec_code = CompositeAccess("EQ", "IV", 2)
    ndc_code = CompositeAccess("EQ", "ND", 2)
    zz_code = CompositeAccess("EQ", "ZZ", 2)
    coverage_level = ElementAccess("EQ", 3, x12type=enum(
        coverage_level))
    insurance_type = ElementAccess("EQ", 4, x12type=enum(
        insurance_type))

class MonetaryAmount(X12SegmentBridge):
    spend_down = ElementAccess("AMT", 2, qualifier=(1, "R"))

class Subscriber(Facade, X12LoopBridge):
    """The person uniquely identified by the Source.

    This person was identified as a member of the Source. Subscriber may or
    may not be the patient.

    NOTE: Patient

    The Patient may be the Subscriber or the Dependent. There are several ways
    of identifying which type the Patient is, but the two most common are:

        1. The Source assigns a unique ID number to each member of the
        Subscriber's family. In this case all dependents of a Subscriber are
        uniquely addressable by the Source, and are thus considered proper
        Subscribers, not Dependents.

        2. The Source only gives a unique ID number to the Subscriber, and all
        family members are identifiable only by giving the Subscriber's and the
        Dependent's information. In this case both the Subscriber and Dependent
        will be defined.
    """
    loopName = "2000C"

    hierarchy = SegmentAccess("HL", x12type=SegmentConversion(Hierarchy))
    trace_numbers = SegmentSequenceAccess("TRN",
            x12type=SegmentConversion(TraceNumber))

    class _Information(X12LoopBridge):
        loopName = "2100C"

        name = SegmentAccess("NM1",
                x12type=SegmentConversion(NamedEntity))
        reference_ids = SegmentSequenceAccess("REF",
                x12type=SegmentConversion(ReferenceID))
        address_street = SegmentAccess("N3",
                x12type=SegmentConversion(Address))
        address_location = SegmentAccess("N4",
                x12type=SegmentConversion(Location))
        provider_information = SegmentAccess("PRV",
                x12type=SegmentConversion(ProviderInformation))
        demographic_information = SegmentAccess("DMG",
                x12type=SegmentConversion(DemographicInformation))
        relationship = SegmentAccess("INS",
                x12type=SegmentConversion(Relationship))
        dates = SegmentSequenceAccess("DTP",
                x12type=SegmentConversion(DateOrTimePeriod))

    class _EligibilityOrBenefitInformation(Facade, X12LoopBridge):
        loopName = "2110C"

        coverage_information = SegmentAccess("EQ",
                x12type=SegmentConversion(EligibilityOrBenefitInquiry))
        monetary_amount = SegmentAccess("AMT",
                x12type=SegmentConversion(MonetaryAmount))
        diagnoses = SegmentSequenceAccess("III",
                x12type=SegmentConversion(Diagnosis))
        prior_authorization_or_referral = SegmentAccess("REF",
                x12type=SegmentConversion(ReferenceID))
        date = SegmentAccess("DTP",
                x12type=SegmentConversion(DateOrTimePeriod))

    def __init__(self, anX12Message, *args, **kwargs):
        super(Subscriber, self).__init__(anX12Message, *args, **kwargs)
        self.subscriber_information = first(self.loops(
            self._Information, anX12Message))
        self.eligibility_or_benefit_information = self.loops(
                self._EligibilityOrBenefitInformation, anX12Message)
        self.dependents = self.loops(Dependent, anX12Message)

class Dependent(Facade, X12LoopBridge):
    """A person identifiable only when associated with a subscriber.

    This person cannot be uniquely identified without the presence of a
    Subscriber. The Dependent isn't a direct member of Source.

    The Dependent is a sub-loop of the Subscriber."""
    loopName = "2000D"

    hierarchy = SegmentAccess("HL", x12type=SegmentConversion(Hierarchy))
    trace_numbers = SegmentSequenceAccess("TRN",
            x12type=SegmentConversion(TraceNumber))

    class _Information(X12LoopBridge):
        loopName = "2100D"

        name = SegmentAccess("NM1",
                x12type=SegmentConversion(NamedEntity))
        reference_ids = SegmentSequenceAccess("REF",
                x12type=SegmentConversion(ReferenceID))
        address_street = SegmentAccess("N3",
                x12type=SegmentConversion(Address))
        address_location = SegmentAccess("N4",
                x12type=SegmentConversion(Location))
        provider_information = SegmentAccess("PRV",
                x12type=SegmentConversion(ProviderInformation))
        demographic_information = SegmentAccess("DMG",
                x12type=SegmentConversion(DemographicInformation))
        relationship = SegmentAccess("INS",
                x12type=SegmentConversion(Relationship))
        dates = SegmentSequenceAccess("DTP",
                x12type=SegmentConversion(DateOrTimePeriod))

    class _EligibilityOrBenefitInformation(Facade, X12LoopBridge):
        loopName = "2110D"

        coverage_information = SegmentAccess("EQ",
                x12type=SegmentConversion(EligibilityOrBenefitInquiry))
        diagnoses = SegmentSequenceAccess("III",
                x12type=SegmentConversion(Diagnosis))
        prior_authorization_or_referral = SegmentAccess("REF",
                x12type=SegmentConversion(ReferenceID))
        date = SegmentAccess("DTP",
                x12type=SegmentConversion(DateOrTimePeriod))

    def __init__(self, anX12Message, *args, **kwargs):
        super(Dependent, self).__init__(anX12Message, *args, **kwargs)
        self.dependent_information = first(self.loops(
            self._Information, anX12Message))
        self.eligibility_or_benefit_information = self.loops(
                self._EligibilityOrBenefitInformation, anX12Message)

class F270_4010(Facade):
    def __init__(self, anX12Message):
        st_loops = anX12Message.descendant('LOOP', name='ST_LOOP')
        if len(st_loops) > 0:
            self.facades = []
            for loop in st_loops:
                self.facades.append(F270_4010(loop))
        else:
            self.header = first(self.loops(Header, anX12Message))
            self.source = first(self.loops(Source, anX12Message))


text:
layout: post
title: Verses and stories from the Dhammapada
date: 2015-12-09 19:30:00
leader: Symon
---


text:
Tokenizer::Tokenizer() : buffer(""), token(""), delimiter(DEFAULT_DELIMITER)
{
    currPos = buffer.begin();
}

Tokenizer::Tokenizer(const std::string& str, const std::string& delimiter) : buffer(str), token(""), delimiter(delimiter)
{
    currPos = buffer.begin();
}

///////////////////////////////////////////////////////////////////////////////
// destructor
///////////////////////////////////////////////////////////////////////////////
Tokenizer::~Tokenizer()
{
}

///////////////////////////////////////////////////////////////////////////////
// reset string buffer, delimiter and the currsor position
///////////////////////////////////////////////////////////////////////////////
void Tokenizer::set(const std::string& str, const std::string& delimiter)
{
    this->buffer = str;
    this->delimiter = delimiter;
    this->currPos = buffer.begin();
}

void Tokenizer::setString(const std::string& str)
{
    this->buffer = str;
    this->currPos = buffer.begin();
}

void Tokenizer::setDelimiter(const std::string& delimiter)
{
    this->delimiter = delimiter;
    this->currPos = buffer.begin();
}

///////////////////////////////////////////////////////////////////////////////
// return the next token
// If cannot find a token anymore, return "".
///////////////////////////////////////////////////////////////////////////////
std::string Tokenizer::next()
{
    if(buffer.size() <= 0) return "";           // skip if buffer is empty

    token.clear();                              // reset token string

    this->skipDelimiter();                      // skip leading delimiters

    // append each char to token string until it meets delimiter
    while(currPos != buffer.end() && !isDelimiter(*currPos))
    {
        token += *currPos;
        ++currPos;
    }
    return token;
}

///////////////////////////////////////////////////////////////////////////////
// skip ang leading delimiters
///////////////////////////////////////////////////////////////////////////////
void Tokenizer::skipDelimiter()
{
    while(currPos != buffer.end() && isDelimiter(*currPos))
        ++currPos;
}

///////////////////////////////////////////////////////////////////////////////
// return true if the current character is delimiter
///////////////////////////////////////////////////////////////////////////////
bool Tokenizer::isDelimiter(char c)
{
    return (delimiter.find(c) != std::string::npos);
}


text:
package net.sf.esfinge.gamification.processors;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.commons.beanutils.PropertyUtils;

import net.sf.esfinge.gamification.achievement.Point;
import net.sf.esfinge.gamification.annotation.RemovePointsToParam;
import net.sf.esfinge.gamification.mechanics.Game;
import net.sf.esfinge.gamification.utils.ReflectionUtils;

public class RemovePointsToParameterProcessor implements AchievementProcessor {

	private int quantity;
	private String name;
	private String parameterName;
	private String propertyName;

	@Override
	public void receiveAnnotation(Annotation an) {
		RemovePointsToParam rptu = (RemovePointsToParam) an;
		quantity = rptu.quantity();
		name = rptu.name();
		parameterName = rptu.param();
		propertyName = rptu.prop();
	}

	@Override
	public void process(Game game, Object encapsulated, Method method,
			Object[] args) {
		int index = ReflectionUtils.findParameterNamed(method, parameterName);
		Object target = args[index];
		if(!propertyName.equals("")){
			try{
				target = PropertyUtils.getProperty(target, propertyName);
			} catch (IllegalAccessException | InvocationTargetException
					 | NoSuchMethodException e){
				throw new RuntimeException("Cannot retrieve property '"+propertyName+"' from class "+target.getClass(), e);
			}
		}
		Point p = new Point(quantity, name);
		game.removeAchievement(target, p);
	}

	@Override
	public void process(Game game, Object encapsulated,
			Class<? extends Method> class1, Object[] args) {
		// TODO Auto-generated method stub

	}

}


text:
import unittest
from test import support
from test.support import import_helper
from test.support import socket_helper
import smtplib
import socket

ssl = import_helper.import_module("ssl")

support.requires("network")

def check_ssl_verifiy(host, port):
    context = ssl.create_default_context()
    with socket.create_connection((host, port)) as sock:
        try:
            sock = context.wrap_socket(sock, server_hostname=host)
        except Exception:
            return False
        else:
            sock.close()
            return True

class SmtpTest(unittest.TestCase):
    testServer = 'smtp.gmail.com'
    remotePort = 587

    def test_connect_starttls(self):
        support.get_attribute(smtplib, 'SMTP_SSL')
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
        with socket_helper.transient_internet(self.testServer):
            server = smtplib.SMTP(self.testServer, self.remotePort)
            try:
                server.starttls(context=context)
            except smtplib.SMTPException as e:
                if e.args[0] == 'STARTTLS extension not supported by server.':
                    unittest.skip(e.args[0])
                else:
                    raise
            server.ehlo()
            server.quit()

class SmtpSSLTest(unittest.TestCase):
    testServer = 'smtp.gmail.com'
    remotePort = 465

    def test_connect(self):
        support.get_attribute(smtplib, 'SMTP_SSL')
        with socket_helper.transient_internet(self.testServer):
            server = smtplib.SMTP_SSL(self.testServer, self.remotePort)
            server.ehlo()
            server.quit()

    def test_connect_default_port(self):
        support.get_attribute(smtplib, 'SMTP_SSL')
        with socket_helper.transient_internet(self.testServer):
            server = smtplib.SMTP_SSL(self.testServer)
            server.ehlo()
            server.quit()

    def test_connect_using_sslcontext(self):
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
        support.get_attribute(smtplib, 'SMTP_SSL')
        with socket_helper.transient_internet(self.testServer):
            server = smtplib.SMTP_SSL(self.testServer, self.remotePort, context=context)
            server.ehlo()
            server.quit()

    def test_connect_using_sslcontext_verified(self):
        with socket_helper.transient_internet(self.testServer):
            can_verify = check_ssl_verifiy(self.testServer, self.remotePort)
            if not can_verify:
                self.skipTest("SSL certificate can't be verified")

        support.get_attribute(smtplib, 'SMTP_SSL')
        context = ssl.create_default_context()
        with socket_helper.transient_internet(self.testServer):
            server = smtplib.SMTP_SSL(self.testServer, self.remotePort, context=context)
            server.ehlo()
            server.quit()

if __name__ == "__main__":
    unittest.main()


text:
package cmput301w15t07.TravelTracker.activity;

import java.util.concurrent.CountDownLatch;

import cmput301w15t07.TravelTracker.DataSourceSingleton;
import cmput301w15t07.TravelTracker.model.DataSource;
import cmput301w15t07.TravelTracker.model.Status;
import cmput301w15t07.TravelTracker.model.UserRole;
import cmput301w15t07.TravelTracker.util.Observer;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

/**
 * The base activity for TravelTracker activities.
 *
 * Referenced http://stackoverflow.com/a/16636992 on 10/03/15
 *
 * @author Elliot,
 *         therabidsquirel
 *
 */
public abstract class TravelTrackerActivity extends Activity implements Observer<DataSource> {
    /** String used to retrieve user data from intent */
    public static final String USER_DATA = "cmput301w15t07.TravelTracker.userData";

    /** String used to retrieve claim UUID from intent */
    public static final String CLAIM_UUID = "cmput301w15t07.TravelTracker.claimUUID";

    /** String used to retrieve item UUID from intent */
    public static final String ITEM_UUID = "cmput301w15t07.TravelTracker.itemUUID";

    /** String used to retrieve Boolean from intent for whether item is created from ClaimInfo or not */
    public static final String FROM_CLAIM_INFO = "cmput301w15t07.TravelTracker.fromClaimInfo";

    /** Latch which is counted down when the activity loads its data */
    private CountDownLatch loadedLatch = new CountDownLatch(1);

    /** Whether to ignore DataSource updates */
    protected boolean ignoreUpdates = false;

    /** The data source (from DataSourceSingleton) */
    protected DataSource datasource;

    /** Whether the activity is currently loading. */
    protected boolean loading;

    /**
     * Call this when the activity has populated all the fields.
     * This will notify threads waiting for waitUntilLoaded().
     */
    public void onLoaded() {
        loadedLatch.countDown();
    }

    /**
     * Blocks the thread until the activity is loaded.
     * @throws InterruptedException
     */
    public void waitUntilLoaded() throws InterruptedException {
        loadedLatch.await();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        datasource = DataSourceSingleton.getDataSource(getApplicationContext());
    }

    // Activities can override this if they need to do more.
    @Override
    public void update(DataSource observable) {
        if (!ignoreUpdates) {
            updateActivity();
        }
    }

    /**
     * Update the activity when the dataset changes.
     * Called in onResume() and update(DataSource observable).
     */
    abstract public void updateActivity();

    /**
     * Sign out of the app, clears the activity stack, and exits to login activity.
     */
    public void signOut() {
        // adapted from
        //    http://stackoverflow.com/questions/6298275/how-to-finish-every-activity-on-the-stack-except-the-first-in-android
        // on 10 March 2015
        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // Removes other Activities from stack
        startActivity(intent);
    }

    /**
     * Appends the user's name to the title.
     * @param name The user's name.
     */
    public void appendNameToTitle(String name) {
        setTitle(getTitle() + " - " + name);
    }

    /**
     * Check if the user is a claimant and the claim status is either in_progress or returned
     * @return True if the check passes, else False
     */
    public static boolean isEditable(Status status, UserRole role) {
        return  role.equals(UserRole.CLAIMANT) &&
                (status.equals(Status.IN_PROGRESS) ||
                 status.equals(Status.RETURNED));
    }

    public void disableView(View view) {
        view.setEnabled(false);
    }

    public void colorViewEnabled(View view) {
        view.setBackgroundColor(Color.rgb(210, 210, 210));
    }

    public void colorViewDisabled(View view) {
        view.setBackgroundColor(this.getResources().getColor(android.R.color.transparent));
    }
}


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.MachineLearning.Models
{
    public partial class JobLimits : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("jobLimitsType");
            writer.WriteStringValue(JobLimitsType.ToString());
            if (Optional.IsDefined(Timeout))
            {
                if (Timeout != null)
                {
                    writer.WritePropertyName("timeout");
                    writer.WriteStringValue(Timeout.Value, "P");
                }
                else
                {
                    writer.WriteNull("timeout");
                }
            }
            writer.WriteEndObject();
        }

        internal static JobLimits DeserializeJobLimits(JsonElement element)
        {
            if (element.TryGetProperty("jobLimitsType", out JsonElement discriminator))
            {
                switch (discriminator.GetString())
                {
                    case "Sweep": return SweepJobLimits.DeserializeSweepJobLimits(element);
                    case "Command": return CommandJobLimits.DeserializeCommandJobLimits(element);
                }
            }
            return UnknownJobLimits.DeserializeUnknownJobLimits(element);
        }
    }
}


text:
import { normalize, virtualFs } from '@angular-devkit/core';
import { FilterHostTree, HostTree } from './host-tree';
import { MergeStrategy } from './interface';

describe('HostTree', () => {
  describe('readText', () => {
    it('returns text when reading a file that exists', () => {
      const tree = new HostTree();
      tree.create('/textfile1', 'abc');
      tree.create('/textfile2', '123');
      expect(tree.readText('/textfile1')).toEqual('abc');
      expect(tree.readText('/textfile2')).toEqual('123');
    });

    it('throws an error when a file does not exist', () => {
      const tree = new HostTree();
      const path = '/textfile1';
      expect(() => tree.readText(path)).toThrowError(`Path "${path}" does not exist.`);
    });

    it('throws an error when invalid UTF-8 characters are present', () => {
      const tree = new HostTree();
      const path = '/textfile1';
      tree.create(path, Buffer.from([0xff, 0xff, 0xff, 0xff]));
      expect(() => tree.readText(path)).toThrowError(`Failed to decode "${path}" as UTF-8 text.`);
    });
  });

  describe('readJson', () => {
    it('returns a JSON value when reading a file that exists', () => {
      const tree = new HostTree();
      tree.create('/textfile1', '{ "a": true, "b": "xyz" }');
      tree.create('/textfile2', '123');
      tree.create('/textfile3', 'null');
      expect(tree.readJson('/textfile1')).toEqual({ a: true, b: 'xyz' });
      expect(tree.readJson('/textfile2')).toEqual(123);
      expect(tree.readJson('/textfile3')).toBeNull();
    });

    it('returns a JSON value when reading a file with comments', () => {
      const tree = new HostTree();
      tree.create(
        '/textfile1',
        '{ "a": true, /* inner object\nmultiline comment\n */ "b": "xyz" }',
      );
      tree.create('/textfile2', '123 // number value');
      tree.create('/textfile3', 'null // null value');
      expect(tree.readJson('/textfile1')).toEqual({ a: true, b: 'xyz' });
      expect(tree.readJson('/textfile2')).toEqual(123);
      expect(tree.readJson('/textfile3')).toBeNull();
    });

    it('returns a JSON value when reading a file with trailing commas', () => {
      const tree = new HostTree();
      tree.create('/textfile1', '{ "a": true, "b": "xyz", }');
      tree.create('/textfile2', '[5, 4, 3, 2, 1, ]');
      expect(tree.readJson('/textfile1')).toEqual({ a: true, b: 'xyz' });
      expect(tree.readJson('/textfile2')).toEqual([5, 4, 3, 2, 1]);
    });

    it('throws an error when a file does not exist', () => {
      const tree = new HostTree();
      const path = '/textfile1';
      expect(() => tree.readJson(path)).toThrowError(`Path "${path}" does not exist.`);
    });

    it('throws an error if the JSON is malformed', () => {
      const tree = new HostTree();
      const path = '/textfile1';
      tree.create(path, '{ "a": true;;;;; "b": "xyz" }');
      expect(() => tree.readJson(path)).toThrowError(
        `Failed to parse "${path}" as JSON. InvalidSymbol at offset: 7.`,
      );
    });

    it('throws an error when invalid UTF-8 characters are present', () => {
      const tree = new HostTree();
      const path = '/textfile1';
      tree.create(path, Buffer.from([0xff, 0xff, 0xff, 0xff]));
      expect(() => tree.readJson(path)).toThrowError(`Failed to decode "${path}" as UTF-8 text.`);
    });
  });

  describe('merge', () => {
    it('should create files from each tree', () => {
      const tree = new HostTree();
      tree.create('/file1', 'a');
      const tree2 = new HostTree();
      tree2.create('/file2', 'a');
      tree.merge(tree2);
      expect(tree.actions[0].kind).toEqual('c');
      expect(tree.actions[1].kind).toEqual('c');
    });

    it('should overwrite if the file exists in one tree', () => {
      const tree = new HostTree();
      tree.create('/file1', 'a');
      const tree2 = new HostTree();
      tree2.create('/file1', 'b');
      tree.merge(tree2, MergeStrategy.Overwrite);
      expect(tree.actions[0].kind).toEqual('c');
    });

    it('should throw if the file exists in one tree with the correct MergeStrategy', () => {
      const tree = new HostTree();
      tree.create('/file1', 'a');
      const tree2 = new HostTree();
      tree2.create('/file1', 'b');
      expect(() => tree.merge(tree2)).toThrow();
    });

    it('should not have a second action if the file content is the same', () => {
      const tree = new HostTree();
      tree.create('/file1', 'a');
      const tree2 = new HostTree();
      tree2.create('/file1', 'a');
      tree.merge(tree2, MergeStrategy.Overwrite);
      expect(tree.actions[0].kind).toEqual('c');
      expect(tree.actions.length).toEqual(1);
    });
  });
});

describe('FilterHostTree', () => {
  it('works', () => {
    const tree = new HostTree();
    tree.create('/file1', '');
    tree.create('/file2', '');
    tree.create('/file3', '');

    const filtered = new FilterHostTree(tree, (p) => p != '/file2');
    const filteredFiles: string[] = [];
    filtered.visit((path) => filteredFiles.push(path));
    filteredFiles.sort();
    expect(filteredFiles).toEqual(['/file1', '/file3'].map(normalize));
    expect(filtered.actions.length).toEqual(2);
  });

  it('works with two filters', () => {
    const tree = new HostTree();
    tree.create('/file1', '');
    tree.create('/file2', '');
    tree.create('/file3', '');

    const filtered = new FilterHostTree(tree, (p) => p != '/file2');
    const filtered2 = new FilterHostTree(filtered, (p) => p != '/file3');
    const filteredFiles: string[] = [];
    filtered2.visit((path) => filteredFiles.push(path));
    filteredFiles.sort();
    expect(filteredFiles).toEqual(['/file1'].map(normalize));
    expect(filtered2.actions.map((a) => a.kind)).toEqual(['c']);
  });

  it('works with underlying files', () => {
    const fs = new virtualFs.test.TestHost({
      '/file1': '',
    });
    const tree = new HostTree(fs);
    tree.create('/file2', '');
    tree.create('/file3', '');

    const filtered = new FilterHostTree(tree, (p) => p != '/file2');
    const filtered2 = new FilterHostTree(filtered, (p) => p != '/file3');
    const filteredFiles: string[] = [];
    filtered2.visit((path) => filteredFiles.push(path));
    filteredFiles.sort();
    expect(filteredFiles).toEqual(['/file1'].map(normalize));
    expect(filtered2.actions.map((a) => a.kind)).toEqual([]);
  });

  it('works with created paths and files', () => {
    const tree = new HostTree();
    tree.create('/dir1/file1', '');
    tree.create('/dir2/file2', '');
    tree.create('/file3', '');

    const filtered = new FilterHostTree(tree, (p) => p != '/dir2/file2');
    const filtered2 = new FilterHostTree(filtered, (p) => p != '/file3');
    const filteredFiles: string[] = [];
    filtered2.visit((path) => filteredFiles.push(path));
    filteredFiles.sort();
    expect(filteredFiles).toEqual(['/dir1/file1'].map(normalize));
    expect(filtered2.actions.map((a) => a.kind)).toEqual(['c']);
  });

  it('works with underlying paths and files', () => {
    const fs = new virtualFs.test.TestHost({
      '/dir1/file1': '',
      '/dir2/file2': '',
    });
    const tree = new HostTree(fs);
    tree.create('/file3', '');

    const filtered = new FilterHostTree(tree, (p) => p != '/dir2/file2');
    const filtered2 = new FilterHostTree(filtered, (p) => p != '/file3');
    const filteredFiles: string[] = [];
    filtered2.visit((path) => filteredFiles.push(path));
    filteredFiles.sort();
    expect(filteredFiles).toEqual(['/dir1/file1'].map(normalize));
    expect(filtered2.actions.map((a) => a.kind)).toEqual([]);
  });

  it('subdirs only contains directories', () => {
    const fs = new virtualFs.test.TestHost({
      '/dir1/file1': '',
      '/dir1/dir2/file2': '',
      '/dir1/dir3/file3': '',
    });
    const tree = new HostTree(fs);
    const subDirs = tree.getDir('/dir1').subdirs;
    expect(subDirs as string[]).toEqual(['dir2', 'dir3']);
  });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace PROJECT.Lib.Web.Mvc
{
	public abstract class MyBaseController : MK.WebLib.Web.Mvc.BaseController
	{
		public ActionResult RequestAuthOrDeny()
		{
			if (!this.User.Identity.IsAuthenticated)
				return this.RedirectToAction("LogOn", "Account", new { returnUrl = this.Request.Url.PathAndQuery });

			throw new HttpException(403, "Forbidden. Доступ к запрошенным данным невозможен.");
		}
	}
}


text:
package org.awaitility.classes;

public final class FinalClass {
}


text:
@interface UISSBarStyleValueConverter : UISSAbstractEnumValueConverter

@end


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

package com.google.caja.parser.html;

import com.google.caja.lexer.ParseException;
import com.google.caja.reporting.MarkupRenderMode;
import com.google.caja.util.CajaTestCase;
import com.google.caja.util.FailureIsAnOption;
import com.google.caja.util.Strings;
import com.google.common.collect.ImmutableSet;

import java.util.Set;

import junit.framework.AssertionFailedError;

import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * This class tests safety and fidelity of {@link Nodes#render}.
 *

 * Caja's security depends on faithful interpretation of Caja's output.
 * Ideally Caja's XML output will always be interpreted as XML rather than
 * HTML (and vice-versa), but this type of misinterpretation is an easy
 * mistake to make.
 *

 * So what we're trying to do here is guarantee that Caja's XML and HTML
 * outputs are always "safe", whether they're subsequently interpreted or
 * misinterpreted as XML or HTML.
 *

 * There are a couple types of tests here:
 *
 *

 *
"precise" - Most DOM trees can be rendered in a way that will be
 * interpreted the same way by XML and HTML parsers.

 *
 *
"robust" - Some DOM trees cannot be rendered precisely, but we can
 * ensure that the only difference between XML and HTML interpretation is
 * the values of inert text content. This is basically a guarantee that it's
 * impossible for inert text to become misinterpreted as script.

 *
 *
"htmlOnly" - Some DOM trees can be rendered safely as HTML (and
 * misinterpretation as XML is harmless), but can't be rendered safely
 * as XML

 *
 *
"xmlOnly" - Some DOM trees can be rendered safely as XML (and
 * misinterpretation as HTML is harmless), but can't be rendered safely
 * as HTML

 *
 *
"unsafe" - Some DOM trees are unsafe to render as HTML or XML.

 *

 *
 * @author felix8a@gmail.com
 */

@SuppressWarnings("static-method")
public class NodesRenderTest extends CajaTestCase {

  public final void testEmpty() {
    precise("");
    assertRender("", "");
  }

  public final void testDiv1() {
    precise("

</div>
");
    assertRender(
        "

</div>
",
        "

</div>
");
  }

  // <![CDATA[]]> has meaning in XML but not in HTML.  These next few tests
  // verify a couple properties:
  // - If a dom tree was parsed as XML and has a CDATASection node, the
  //   node doesn't get rendered with "<![CDATA[...]]>", which would
  //   screw up HTML interpretation.

  // - If a dom tree has a text node containing "<![CDATA[", it doesn't
  //   get rendered as "<![CDATA[", which would screw up XML interpretation.

  public final void testCdata1() {
    precise("1<<![CDATA[2<]]><![CDATA[3<]]>4>5");
    assertRender(
        "1<2&lt;3<4>5",
        "1<<![CDATA[2<]]><![CDATA[3<]]>4>5");
    assertRender(
        "1<<![CDATA[2<]]><![CDATA[3<]]>4>5",
        "1<<![CDATA[2<]]><![CDATA[3<]]>4>5");
  }

  public final void testCdata2() {
    precise("
1<<![CDATA[2<]><![CDATA[3<]]>4>5
");
    assertRender(
        "
1<2&lt;3<4>5
",
        "
1<<![CDATA[2<]]><![CDATA[3<]]>4>5
");
    assertRender(
        "
1<<![CDATA[2<]]><![CDATA[3<]]>4>5
",
        "
1<<![CDATA[2<]]><![CDATA[3<]]>4>5
");
  }

  public final void testCdata3() {
    // <title> is RCDATA so this should be possible
    precise("<title>1<<![CDATA[2<]><![CDATA[3<]]>4>5</title>");
    assertRender(
        "<title>1<2&lt;3<4>5</title>",
        "<title>1<<![CDATA[2<]]><![CDATA[3<]]>4>5</title>");
    assertRender(
        "<title>1<<![CDATA[2<]]><![CDATA[3<]]>4>5</title>",
        "<title>1<<![CDATA[2<]]><![CDATA[3<]]>4>5</title>");
  }

  /*TODO(felix8a)*/ @FailureIsAnOption
  public final void testCdata4() {
    // <xmp> is RAWTEXT, no entity decoding, so precise is impossible
    robust("<xmp>1<<![CDATA[2<]><![CDATA[3<]]>4>5</xmp>");
  }

  public final void testXmp1() {
    // xmp can never contain "</xmp>", and there's no way to escape it.
    xmlOnly(xml("<xmp>1</xmp>2</xmp>"));
  }

  public final void testXmp2() {
    // non-ascii characters are not renderable safely in xmp
    xmlOnly(xml("<xmp>\u0000\u0080\u0131</xmp>"));
    assertRenderXml(
        "<xmp>�€ı</xmp>",
        "<xmp>\u0000\u0080\u0131</xmp>");
  }

  /*TODO(felix8a)*/ @FailureIsAnOption
  public final void testXmp3() {
    robust(html("<xmp> a<b </xmp>"));
  }

  public final void testScript1() {
    precise("");
    assertRender(
        "",
        "");
  }

  /*TODO(felix8a)*/ @FailureIsAnOption
  public final void testScript2() {
    precise(html(
        ""));
  }

  /*TODO(felix8a)*/ @FailureIsAnOption
  public final void testScript3() {
    htmlOnly(html(
        ""));
  }

  /*TODO(felix8a)*/ @FailureIsAnOption
  public final void testScript4() {
    unsafe(xml(""));
  }

  // --------

  @SuppressWarnings("unused")
  private void assertRenderHtml(String expected, String test) {
    assertEquals(expected, renderHtml(xml(test)));
  }

  private void assertRenderXml(String expected, String test) {
    assertEquals(expected, renderXml(xml(test)));
  }

  private void assertRender(String expected, String test) {
    Node tree = xml(test);
    assertEquals(expected, renderHtml(tree));
    assertEquals(expected, renderXml(tree));
  }

  /**
   * Check that an output string has the same meaning, whether it's parsed
   * as HTML or as XML.
   */
  private void preciseOutput(String output) {
    // TODO(felix8a): parser warnings here should be fatal?
    Node asHtml = html(output);
    Node asXml = xml(output);
    assertIdenticalRender(asHtml, asXml);
    assertIdenticalStructure(asHtml, asXml);
  }

  /**
   * Check that our rendering of a DOM tree has the same meaning, whether
   * the rendering is parsed as HTML or as XML.
   */
  private void precise(Node tree) {
    preciseOutput(Nodes.render(tree));
    preciseOutput(Nodes.render(tree, MarkupRenderMode.HTML));
    preciseOutput(Nodes.render(tree, MarkupRenderMode.XML));
    // We're only making this guarantee for the common render options.
  }

  private void precise(String input) {
    // Note, parser warnings here are unimportant. TODO(felix8a): really?
    precise(html(input));
    precise(xml(input));
  }

  // --------

  /**
   * Check that our rendering of a DOM tree has the same structure, whether
   * the rendering is parsed as HTML or as XML.
   *

   * Differences in text content are ignored, but differences in attributes
   * and attribute values are significant.
   *

   * Basically, we want to make sure that when an HTML output string is
   * interpreted as XML or vice versa, that the misinterpretation does not
   * turn inactive text into active script.
   */
  private void robust(Node tree) {
    String asHtml = renderHtml(tree);
    assertIdenticalStructure(tree, html(asHtml));
    assertIdenticalStructure(tree, xml(asHtml));
    String asXml = renderXml(tree);
    assertIdenticalStructure(tree, html(asXml));
    assertIdenticalStructure(tree, xml(asXml));
  }

  private void robust(String source) {
    robust(html(source));
    robust(xml(source));
  }

  // --------

  /**
   * Check that when we refuse to render a DOM tree as XML, we can
   * render it as HTML, and the HTML rendering is safe when misinterpreted
   * as XML.
   */
  private void htmlOnly(Node tree) {
    try {
      String result = renderXml(tree);
      throw new AssertionFailedError(
          "Unexpected renderXmlsuccess: " + result);
    } catch (UncheckedUnrenderableException e) {}
    String result = renderHtml(tree);
    assertIdenticalStructure(html(result), xml(result));
  }

  /**
   * Check that when we refuse to render a DOM tree as HTML, we can
   * render it as XML, and the XML rendering is safe when misinterpreted
   * as HTML.
   */
  private void xmlOnly(Node tree) {
    try {
      String result = renderHtml(tree);
      throw new AssertionFailedError(
          "Unexpected renderHtml success: " + result);
    } catch (UncheckedUnrenderableException e) {}
    String result = renderXml(tree);
    assertIdenticalStructure(html(result), xml(result));
  }

  /**
   * Check that when we refuse to render a DOM tree as HTML or as XML
   */
  private void unsafe(Node tree) {
    try {
      String result = renderHtml(tree);
      throw new AssertionFailedError(
          "Unexpected renderHtml success: " + result);
    } catch (UncheckedUnrenderableException e) {}
    try {
      String result = renderXml(tree);
      throw new AssertionFailedError(
          "Unexpected renderXmlsuccess: " + result);
    } catch (UncheckedUnrenderableException e) {}
  }

  // --------

  private void assertIdenticalRender(Node n1, Node n2) {
    String s1 = renderXml(n1);
    String s2 = renderXml(n2);
    assertEquals(s1, s2);
  }

  private void assertIdenticalStructure(Node n1, Node n2) {
    assertEquals(n1.getNodeType(), n2.getNodeType());
    switch (n1.getNodeType()) {
      case Node.ELEMENT_NODE:
        assertIdenticalStructure((Element) n1, (Element) n2);
        break;
      case Node.DOCUMENT_FRAGMENT_NODE:
        assertIdenticalStructure(n1.getChildNodes(), n2.getChildNodes());
        break;
      default:
        throw new IllegalStateException("Unexpected node type");
    }
  }

  // These are HTML tags whose contents have security implications.
  private static final Set<String> RISKY_ELEMENTS = ImmutableSet.of(
      "noembed", "noframes", "noscript", "script", "style");

  private void assertIdenticalStructure(Element e1, Element e2) {
    assertEquals(e1.getTagName(), e2.getTagName());

    // For RISKY_ELEMENTS, text equivalence is important.
    String tagName = Strings.lower(e1.getTagName());
    if (RISKY_ELEMENTS.contains(tagName)) {
      assertIdenticalRender(e1, e2);
      return;
    }

    // Check that attributes are identical
    NamedNodeMap a1 = e1.getAttributes();
    NamedNodeMap a2 = e2.getAttributes();
    assertEquals(a1.getLength(), a2.getLength());
    for (int i = 0; i < a1.getLength(); i++) {
      Node attr = a1.item(i);
      assertEquals(attr.getNodeValue(), a2.getNamedItem(attr.getNodeName()));
    }

    // Check that children are identical, ignoring unimportant text.
    assertIdenticalStructure(e1.getChildNodes(), e2.getChildNodes());
  }

  private void assertIdenticalStructure(NodeList nl1, NodeList nl2) {
    int p1 = nextElement(nl1, 0);
    int p2 = nextElement(nl2, 0);
    while (p1 < nl1.getLength() && p2 < nl2.getLength()) {
      assertIdenticalStructure((Element) nl1.item(p1), (Element) nl2.item(p2));
      p1 = nextElement(nl1, p1 + 1);
      p2 = nextElement(nl2, p2 + 1);
    }
    assertTrue(nl1.getLength() <= nextElement(nl1, p1));
    assertTrue(nl2.getLength() <= nextElement(nl2, p2));
  }

  // Return the next element node at or after pos
  private int nextElement(NodeList nl, int pos) {
    while (pos < nl.getLength()) {
      switch (nl.item(pos).getNodeType()) {
        case Node.CDATA_SECTION_NODE:
        case Node.TEXT_NODE:
          pos++;
          break;
        case Node.ELEMENT_NODE:
          return pos;
        default:
          throw new IllegalStateException("Unexpected node type");
      }
    }
    return nl.getLength();
  }

  private DocumentFragment html(String source) {
    try {
      return htmlFragment(fromString(source));
    } catch (ParseException e) {
      throw new RuntimeException(e);
    }
  }

  private DocumentFragment xml(String source) {
    try {
      return xmlFragment(fromString(source));
    } catch (ParseException e) {
      throw new RuntimeException(e);
    }
  }

  private String renderXml(Node node) {
    return Nodes.render(node, MarkupRenderMode.XML);
  }

  private String renderHtml(Node node) {
    return Nodes.render(node, MarkupRenderMode.HTML);
  }

}


text:
define(function(require) {
    'use strict';

    var servicesModule = require('./ServicesModule');
    require('./BaseService');

    servicesModule.factory('SpecialRegulationsService',
        ['$http',
            '$q',
            'BaseApiService',
            function($http, $q, BaseApiService) {
                function SpecialRegulationsService() {
                    BaseApiService.call(this);
                }

                var proto = SpecialRegulationsService.prototype = Object.create(BaseApiService.prototype);

                proto.getSpecialRegulations = function() {
                    var key = 'specialRegulations';
                    if (this.cache.get(key)) {
                        return this.cache.get(key);
                    }

                    var getPromise = this.callApi({}, 'SpecialRegulations/SpecialRegulations.json', this.cache)
                        .then(function(response) {
                            if (!response) {
                                return $q.reject(response);
                            }

                            return response;
                        });

                    this.cache.put(key, getPromise);
                    return getPromise;
                };

                return new SpecialRegulationsService();
            }
        ]
    );
});


text:
<!DOCTYPE html>

		<title>Pattern Lab</title>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width" />

		<link rel="stylesheet" href="../../../../css/style.css?1432750518" media="all" />

		<meta http-equiv="cache-control" content="max-age=0" />
		<meta http-equiv="cache-control" content="no-cache" />
		<meta http-equiv="expires" content="0" />
		<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
		<meta http-equiv="pragma" content="no-cache" />

		<link rel="stylesheet" href="../../styleguide/css/styleguide.css?1432750518" media="all">
		<link rel="stylesheet" href="../../styleguide/css/styleguide-specific.css?1432750518" media="all" />

Search

							<form action="#" method="post" class="inline-form search-form">
    <fieldset>
	    <legend class="is-vishidden">Search</legend>
	    Search
	    <input type="search" placeholder="Search" id="search-field" class="search-field" />
	    <button class="search-submit">

	    	Search
	    </button>
    </fieldset>
</form>

HTML

										<form action="#" method="post" class="inline-form search-form">
    <fieldset>
	    <legend class="is-vishidden">Search</legend>
	    <label for="search-field" class="is-vishidden">Search</label>
	    <input type="search" placeholder="Search" id="search-field" class="search-field" />
	    <button class="search-submit">
	    	<span class="icon-search" aria-hidden="true"></span>
	    	<span class="is-vishidden">Search</span>
	    </button>
    </fieldset>
</form>

Comment Form

							<form method="post" action="#" class="comment-form">
	<fieldset>

			Name
			<input id="comment-name" type="text" placeholder="Enter Your Name" />

			Email
			<input id="comment-email" type="email" placeholder="Your email address" />

			URL
			<input id="comment-url" type="url" placeholder="Website if you got one" />

			Comment
			<textarea id="comment-field" rows="5" placeholder="Write you comment here"></textarea>

	</fieldset>
</form>

HTML

										<form method="post" action="#" class="comment-form">
	<fieldset>
		<div class="field-container">
			<label for="comment-name">Name</label>
			<input id="comment-name" type="text" placeholder="Enter Your Name" />
		</div>
		<div class="field-container">
			<label for="comment-email">Email</label>
			<input id="comment-email" type="email" placeholder="Your email address" />
		</div>
		<div class="field-container">
			<label for="comment-url">URL</label>
			<input id="comment-url" type="url" placeholder="Website if you got one" />
		</div>
		<div class="field-container">
			<label for="comment-field">Comment</label>
			<textarea id="comment-field" rows="5" placeholder="Write you comment here"></textarea>
		</div>
	</fieldset>
</form>

Newsletter

							<form action="#" method="post" class="inline-form newsletter-form">
    <fieldset>
	    <legend>Sign up for our newsletter</legend>
	    Sign up for our newsletter

	   		<input type="newsletter" placeholder="E-mail address" id="newsletter-field" class="newsletter-field" />
	    	<button class="btn newsletter-submit">Sign Me Up</button>

    </fieldset>
</form>

HTML

										<form action="#" method="post" class="inline-form newsletter-form">
    <fieldset>
	    <legend>Sign up for our newsletter</legend>
	    <label for="newsletter-scope">Sign up for our newsletter</label>
	    <div class="inline-container">
	   		<input type="newsletter" placeholder="E-mail address" id="newsletter-field" class="newsletter-field" />
	    	<button class="btn newsletter-submit">Sign Me Up</button>
		</div>
    </fieldset>
</form>


text:
package com.keyhan.brakessupplier;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@EnableEurekaClient
public class Application {

    private static final Logger LOG= Logger.getLogger( Application.class.getName() );

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @RequestMapping("/hello_brakessupplier")
    public String hello() {
        LOG.log(Level.INFO, "requested Service 'brakes-supplier'");
        return "Hello from service 'brakes-supplier'.";
    }
}


text:
Save Search is a _dead simple_ [CraftCMS](http://www.buildwithcraft.com) plugin developed by [Page 8](http://page-8.com). It allows your last search to be saved and populated in the search box's in Craft. This is useful when navigating away from a listings page and wanting to retain your search when you return.

##Installation##
1. Download the plugin and make sure the parent folder is named `savesearch`
2. Move the folder into your `craft/plugins` directory
3. Install the plugin under **Craft Admin › Settings › Plugins**

##Usage##
After enabling continue to use Craft as normal. Your last search for an area of the CMS will automatically popualate in that search box. This is useful in browsers like Chrome where it won't retain your search when you go back. So, if you've filtered a list (title::A*), that query will be saved and your results will remain filtered.

This is way too long of an explanation for something so ridiculously simple. There's more lines in this README than there is code.

##Requirements##
It got broke for version 2.3, so I'm not acutally positive if it works for a version before this.

##Feedback?##
Contact us on Twitter [@Page8Online](https://twitter.com/Page8Online) or visit us at [page-8.com](http://page-8.com)

##Version History##
* 1.1 - Holy crow a release? Broke for 2.3. Fixed it.
* 1.0 - Initial Release

###License###
This work is licenced under the MIT license.


text:
package org.apache.camel.processor;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;

public class OnCompletionModeTest extends ContextTestSupport {

    @Test
    public void testOnCompletionScopeBefore() throws Exception {
        getMockEndpoint("mock:input").expectedBodiesReceived("Camel");
        getMockEndpoint("mock:after").expectedBodiesReceived("I was here Hello Camel");

        String out = template.requestBody("seda:foo", "Camel", String.class);
        assertEquals("I was here Hello Camel", out);

        assertMockEndpointsSatisfied();
    }

    @Test
    public void testOnCompletionScopeAfter() throws Exception {
        getMockEndpoint("mock:input").expectedBodiesReceived("World");
        getMockEndpoint("mock:after").expectedBodiesReceived("I was here Hello World");

        String out = template.requestBody("seda:bar", "World", String.class);
        assertEquals("Hello World", out);

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("seda:foo")
                    // we do not want parallel as we want to change the message
                    // before the consumer writes the response
                    .onCompletion().modeBeforeConsumer().transform(body().prepend("I was here ")).to("mock:after").end().to("mock:input").transform(body().prepend("Hello "))
                    .to("log:foo");

                from("seda:bar")
                    // need to use parallel to make copy so we do not do
                    // side-effects
                    .onCompletion().modeAfterConsumer().parallelProcessing().transform(body().prepend("I was here ")).to("mock:after").end().to("mock:input")
                    .transform(body().prepend("Hello ")).to("log:bar");
            }
        };
    }
}


text:
"use strict";

module.exports = function () {
    this.currentUrl = window.location.pathname + window.location.search;
};


text:
<?php

namespace PHPExiftool\Driver\Tag\PhaseOne;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class CameraModel extends AbstractTag
{

    protected $Id = 1040;

    protected $Name = 'CameraModel';

    protected $FullName = 'PhaseOne::Main';

    protected $GroupName = 'PhaseOne';

    protected $g0 = 'MakerNotes';

    protected $g1 = 'PhaseOne';

    protected $g2 = 'Camera';

    protected $Type = 'string';

    protected $Writable = true;

    protected $Description = 'Camera Model';

    protected $flag_Permanent = true;

}


text:
//=================================================================================================

//=================================================================================================

#ifndef _BLAZE_MATH_EXPRESSIONS_VECABSEXPR_H_
#define _BLAZE_MATH_EXPRESSIONS_VECABSEXPR_H_

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <blaze/math/expressions/AbsExpr.h>

namespace blaze {

//=================================================================================================
//
//  CLASS DEFINITION
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Base class for all vector absolute value expression templates.
// \ingroup math
//
// The VecAbsExpr class serves as a tag for all expression templates that implement a vector
// absolute value operation. All classes, that represent a vector absolute value operation
// and that are used within the expression template environment of the Blaze library have to
// derive from this class in order to qualify as vector absolute value expression template.
// Only in case a class is derived from the VecAbsExpr base class, the IsVecAbsExpr type
// trait recognizes the class as valid vector absolute value expression template.
*/
struct VecAbsExpr : private AbsExpr
{};
//*************************************************************************************************

} // namespace blaze

#endif


text:
#pragma once
#include "MapEventTypes.h"
#include "GameCommand.h"
#include "Components/BitStream.h"
#include "Components/Logging.h"

namespace SEGSEvents
{
// [[ev_def:type]]
class SidekickOffer final : public GameCommandEvent
{
public:
    // [[ev_def:field]]
    uint32_t    m_db_id;
                SidekickOffer(uint32_t db_id) : GameCommandEvent(MapEventTypes::evSidekickOffer),
                m_db_id(db_id)
                {
                }
explicit        SidekickOffer() : GameCommandEvent(MapEventTypes::evSidekickOffer) {}
    void        serializeto(BitStream &bs) const override
                {
                    bs.StorePackedBits(1,type()-MapEventTypes::evFirstServerToClient); // 28
                    bs.StoreBits(32,m_db_id);
                    qCDebug(logTeams) << "Sidekick Offer db_id:" << m_db_id;
                }
    EVENT_IMPL(SidekickOffer)
};
} // end of SEGSEvents namespace


text:
package pt.ptcris.test.scenarios;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.um.dsi.gavea.orcid.model.work.Work;

import pt.ptcris.PTCRISyncResult;
import pt.ptcris.test.TestHelper;
import pt.ptcris.test.TestClients;
import pt.ptcris.test.TestClients.Profile;
import pt.ptcris.utils.ORCIDHelper;
import pt.ptcris.utils.ORCIDWorkHelper;

/**
 * Scenario 19 of the PTCRISync specification v0.4.3, tests export.
 *
 * Features:
 * export updates with {same}
 *
 * @see Scenario
 */
public class Scenario19 extends Scenario {

	/** {@inheritDoc} */
	@Override
	List<Work> setupORCIDCRISWorks() {
		List<Work> works = new ArrayList<Work>();
		works.add(TestHelper.workDOIEIDHANDLE(null, "1", "1", "0", "0"));
		return works;
	}

	/** {@inheritDoc} */
	@Override
	List<Work> exportLocalWorks() {
		List<Work> works = new ArrayList<Work>();
		works.add(TestHelper.workDOIEIDHANDLE(BigInteger.valueOf(0), "1", "1",
				"0", "0"));
		return works;
	}

	/** {@inheritDoc} */
	@Override
	List<Work> expectedORCIDCRISWorks() {
		List<Work> works = new ArrayList<Work>();
		works.add(TestHelper.workDOIEIDHANDLE(null, "1", "1", "0", "0"));
		return works;
	}

	/** {@inheritDoc} */
	Set<Integer> expectedExportCodes(BigInteger putcode) {
		Set<Integer> res = new HashSet<Integer>();
		if (putcode.equals(BigInteger.valueOf(0)))
			res.add(PTCRISyncResult.UPTODATE);
		else
			res.add(PTCRISyncResult.ADDOK);
		return res;
	}

	/** {@inheritDoc} */
	@Override
	List<Work> expectedImportedInvalidWorks() {
		List<Work> works = new ArrayList<Work>();
		Work work = TestHelper.workDOI(null, "1", "I2");
		work.setPublicationDate(null);
		works.add(work);
		return works;
	}

	/** {@inheritDoc} */
	@Override
	Set<String> expectedInvalidCodes(BigInteger putCode) {
		Set<String> res = new HashSet<String>();
		res.add(ORCIDHelper.INVALID_PUBLICATIONDATE);
		return res;
	}

	/** {@inheritDoc} */
	@Override
	ORCIDWorkHelper crisClient() {
		return new ORCIDWorkHelper(
				TestClients.getCRISClient(Profile.ZEROVALIDWORKS));
	}

	/** {@inheritDoc} */
	@Override
	ORCIDWorkHelper externalClient() {
		return new ORCIDWorkHelper(
				TestClients.getExternalClient(Profile.ZEROVALIDWORKS));
	}

}


text:
package com.guestful.json.groovy;

/**
* @author Mathieu Carbou (mathieu.carbou@gmail.com)
*/
public interface JsonTypeSerializer<T> {
    void write(T o, JsonWriter writer);
}


text:
package io.spine.server.commandbus.given;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.spine.base.EventMessage;
import io.spine.core.Command;
import io.spine.core.CommandContext;
import io.spine.logging.Logging;
import io.spine.server.command.AbstractAssignee;
import io.spine.server.command.Assign;
import io.spine.server.command.CommandHistory;
import io.spine.server.event.EventDispatcher;
import io.spine.server.tuple.Pair;
import io.spine.server.type.CommandEnvelope;
import io.spine.server.type.EventClass;
import io.spine.server.type.EventEnvelope;
import io.spine.test.commandbus.ProjectId;
import io.spine.test.commandbus.command.CmdBusAddTask;
import io.spine.test.commandbus.command.CmdBusCreateProject;
import io.spine.test.commandbus.command.CmdBusCreateTask;
import io.spine.test.commandbus.command.CmdBusStartProject;
import io.spine.test.commandbus.event.CmdBusProjectCreated;
import io.spine.test.commandbus.event.CmdBusProjectStarted;
import io.spine.test.commandbus.event.CmdBusTaskAdded;
import io.spine.test.commandbus.event.CmdBusTaskAssigned;
import io.spine.test.commandbus.event.CmdBusTaskStarted;

import java.util.List;
import java.util.Optional;

import static com.google.common.collect.Lists.newLinkedList;

public class CommandHandlerTestEnv {

    /** Prevents instantiation of this utility class. */
    private CommandHandlerTestEnv() {
    }

    public static final class EventCatcher implements EventDispatcher {

        private final List<EventEnvelope> dispatched = newLinkedList();

        @Override
        public ImmutableSet<EventClass> messageClasses() {
            return EventClass.setOf(
                    CmdBusProjectStarted.class,
                    CmdBusTaskAssigned.class,
                    CmdBusTaskStarted.class
            );
        }

        @Override
        public ImmutableSet<EventClass> domesticEventClasses() {
            return eventClasses();
        }

        @Override
        public ImmutableSet<EventClass> externalEventClasses() {
            return EventClass.emptySet();
        }

        @Override
        public void dispatch(EventEnvelope event) {
            dispatched.add(event);
        }

        public List<EventEnvelope> dispatched() {
            return ImmutableList.copyOf(dispatched);
        }
    }

    public static class TestCommandAssignee extends AbstractAssignee implements Logging {

        private final ImmutableList<EventMessage> eventsOnStartProjectCmd =
                createEventsOnStartProjectCmd();

        private final CommandHistory commandsHandled = new CommandHistory();

        public void assertHandled(Command expected) {
            commandsHandled.assertHandled(expected);
        }

        @SuppressWarnings("CheckReturnValue")
        // Can ignore the returned ID of the command handler in these tests.
        public void handle(Command cmd) {
            var commandEnvelope = CommandEnvelope.of(cmd);
            dispatch(commandEnvelope);
        }

        public ImmutableList<EventMessage> getEventsOnStartProjectCmd() {
            return eventsOnStartProjectCmd;
        }

        @Assign
        CmdBusProjectCreated handle(CmdBusCreateProject msg, CommandContext context) {
            commandsHandled.add(msg, context);
            return CmdBusProjectCreated.newBuilder()
                    .setProjectId(msg.getProjectId())
                    .build();
        }

        @Assign
        CmdBusTaskAdded handle(CmdBusAddTask msg, CommandContext context) {
            commandsHandled.add(msg, context);
            return CmdBusTaskAdded.newBuilder()
                    .setProjectId(msg.getProjectId())
                    .build();
        }

        @Assign
        List<EventMessage> handle(CmdBusStartProject msg, CommandContext context) {
            commandsHandled.add(msg, context);
            return eventsOnStartProjectCmd;
        }

        @Assign
        Pair<CmdBusTaskAssigned, Optional<CmdBusTaskStarted>>
        handle(CmdBusCreateTask msg, CommandContext context) {
            commandsHandled.add(msg, context);
            return createEventsOnCreateTaskCmd(msg);
        }

        private ImmutableList<EventMessage> createEventsOnStartProjectCmd() {
            var id = ProjectId.newBuilder()
                    .setId(id())
                    .build();
            var startedEvent = CmdBusProjectStarted.newBuilder()
                    .setProjectId(id)
                    .build();
            var startedAgainEvent = CmdBusProjectStarted.newBuilder()
                    .setProjectId(id)
                    .build();
            return ImmutableList.of(startedEvent, startedAgainEvent);
        }

        private static Pair<CmdBusTaskAssigned, Optional<CmdBusTaskStarted>>
        createEventsOnCreateTaskCmd(CmdBusCreateTask msg) {
            var taskId = msg.getTaskId();
            var cmdTaskAssigned = CmdBusTaskAssigned.newBuilder()
                    .setTaskId(taskId)
                    .build();
            var cmdTaskStarted = msg.getStart()
                                 ? CmdBusTaskStarted.newBuilder()
                                         .setTaskId(taskId)
                                         .build()
                                 : null;
            return Pair.withNullable(cmdTaskAssigned, cmdTaskStarted);
        }
    }
}


text:
<Alloy>
	<Window id="win">
		<Label id="responseLabel" />
	    <Button id="nextTurnButton" />
	</Window>
</Alloy>


text:
<?php

/**
 * This file is part of the TableRenderer library.
 *
 * @author Łukasz Makuch <kontakt@lukaszmakuch.pl>
 * @license MIT http://opensource.org/licenses/MIT
 */

namespace lukaszmakuch\TableRenderer\ScalarRenderer;

use lukaszmakuch\TableRenderer\ScalarRenderer\Exception\UnableToGetScalarRepresentation;
use lukaszmakuch\TableRenderer\TableElement;

/**
 * Renders a model of a table as a scalar value or an array of scalar values.
 *
 * @author Łukasz Makuch <kontakt@lukaszmakuch.pl>
 */
interface ScalarRenderer
{
    /**
     * @return mixed a scalar value or an array of scalar values (or arrays of them)
     * @throws UnableToGetScalarRepresentation
     */
    public function getScalarRepresentationOf(TableElement $table);
}


text:
@implementation LYRecommendTag

@end


text:
This JS client provides basic statistics from [Jolokia server](https://jolokia.org/) as back-end

## Features

1. Memory usage
2. List of cluster nodes
3. Thread dump
4. Run Garbage collection

## How to use it

You can run the client `metrics.html` from:

1. Filesystem (clonned git repo)
2. Upload all files to your web server
3. From github at https://rawgit.com/lkrzyzanek/jolokia-stats-jsclient/master/index.html

Once you have loaded the page put to the field `url` the full path to Jolokia servlet.

### Secured Jolokia servlet via CORS

In case you have deployed Jolokia servlet on different domain than the client lives then
you need to have correctly configured CORS headers including `withCredentials` headers.


text:
<link rel="stylesheet" href="style.css" type="text/css">
<meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type">
<link rel="Start" href="index.html">
<link title="Index of types" rel=Appendix href="index_types.html">
<link title="Index of exceptions" rel=Appendix href="index_exceptions.html">
<link title="Index of values" rel=Appendix href="index_values.html">
<link title="Index of modules" rel=Appendix href="index_modules.html">
<link title="Index of module types" rel=Appendix href="index_module_types.html">
<link title="Barray" rel="Chapter" href="Barray.html">
<link title="Barray_slice" rel="Chapter" href="Barray_slice.html">
<link title="Barraylabels" rel="Chapter" href="Barraylabels.html">
<link title="Bbool" rel="Chapter" href="Bbool.html">
<link title="Bchar" rel="Chapter" href="Bchar.html">
<link title="Bfloat" rel="Chapter" href="Bfloat.html">
<link title="Bformat" rel="Chapter" href="Bformat.html">
<link title="Bfun" rel="Chapter" href="Bfun.html">
<link title="Bhash" rel="Chapter" href="Bhash.html">
<link title="Bhashtbl" rel="Chapter" href="Bhashtbl.html">
<link title="Bheap" rel="Chapter" href="Bheap.html">
<link title="Bint" rel="Chapter" href="Bint.html">
<link title="Bint64" rel="Chapter" href="Bint64.html">
<link title="Blist" rel="Chapter" href="Blist.html">
<link title="Blistlabels" rel="Chapter" href="Blistlabels.html">
<link title="Bmap" rel="Chapter" href="Bmap.html">
<link title="Bopt" rel="Chapter" href="Bopt.html">
<link title="Bord" rel="Chapter" href="Bord.html">
<link title="Bpair" rel="Chapter" href="Bpair.html">
<link title="Bparse" rel="Chapter" href="Bparse.html">
<link title="Brandom" rel="Chapter" href="Brandom.html">
<link title="Bref" rel="Chapter" href="Bref.html">
<link title="Bresult" rel="Chapter" href="Bresult.html">
<link title="Bset" rel="Chapter" href="Bset.html">
<link title="Bstring" rel="Chapter" href="Bstring.html">
<link title="Bvector" rel="Chapter" href="Bvector.html">
<link title="Sequence" rel="Chapter" href="Sequence.html">
<link title="Arg" rel="Chapter" href="Arg.html">
<link title="Array" rel="Chapter" href="Array.html">
<link title="ArrayLabels" rel="Chapter" href="ArrayLabels.html">
<link title="Bigarray" rel="Chapter" href="Bigarray.html">
<link title="Buffer" rel="Chapter" href="Buffer.html">
<link title="Bytes" rel="Chapter" href="Bytes.html">
<link title="BytesLabels" rel="Chapter" href="BytesLabels.html">
<link title="Callback" rel="Chapter" href="Callback.html">
<link title="CamlinternalFormat" rel="Chapter" href="CamlinternalFormat.html">
<link title="CamlinternalFormatBasics" rel="Chapter" href="CamlinternalFormatBasics.html">
<link title="CamlinternalLazy" rel="Chapter" href="CamlinternalLazy.html">
<link title="CamlinternalMod" rel="Chapter" href="CamlinternalMod.html">
<link title="CamlinternalOO" rel="Chapter" href="CamlinternalOO.html">
<link title="Char" rel="Chapter" href="Char.html">
<link title="Complex" rel="Chapter" href="Complex.html">
<link title="Digest" rel="Chapter" href="Digest.html">
<link title="Filename" rel="Chapter" href="Filename.html">
<link title="Format" rel="Chapter" href="Format.html">
<link title="Gc" rel="Chapter" href="Gc.html">
<link title="Genlex" rel="Chapter" href="Genlex.html">
<link title="Hashtbl" rel="Chapter" href="Hashtbl.html">
<link title="Int32" rel="Chapter" href="Int32.html">
<link title="Int64" rel="Chapter" href="Int64.html">
<link title="Lazy" rel="Chapter" href="Lazy.html">
<link title="Lexing" rel="Chapter" href="Lexing.html">
<link title="List" rel="Chapter" href="List.html">
<link title="ListLabels" rel="Chapter" href="ListLabels.html">
<link title="Map" rel="Chapter" href="Map.html">
<link title="Marshal" rel="Chapter" href="Marshal.html">
<link title="MoreLabels" rel="Chapter" href="MoreLabels.html">
<link title="Nativeint" rel="Chapter" href="Nativeint.html">
<link title="Obj" rel="Chapter" href="Obj.html">
<link title="Oo" rel="Chapter" href="Oo.html">
<link title="Parsing" rel="Chapter" href="Parsing.html">
<link title="Pervasives" rel="Chapter" href="Pervasives.html">
<link title="Printexc" rel="Chapter" href="Printexc.html">
<link title="Printf" rel="Chapter" href="Printf.html">
<link title="Queue" rel="Chapter" href="Queue.html">
<link title="Random" rel="Chapter" href="Random.html">
<link title="Scanf" rel="Chapter" href="Scanf.html">
<link title="Set" rel="Chapter" href="Set.html">
<link title="Sort" rel="Chapter" href="Sort.html">
<link title="Stack" rel="Chapter" href="Stack.html">
<link title="StdLabels" rel="Chapter" href="StdLabels.html">
<link title="Stream" rel="Chapter" href="Stream.html">
<link title="String" rel="Chapter" href="String.html">
<link title="StringLabels" rel="Chapter" href="StringLabels.html">
<link title="Sys" rel="Chapter" href="Sys.html">
<link title="Unix" rel="Chapter" href="Unix.html">
<link title="UnixLabels" rel="Chapter" href="UnixLabels.html">
<link title="Weak" rel="Chapter" href="Weak.html"><title>Arg</title>

sig

  type spec =

      Unit of (unit -> unit)

    | Bool of (bool -> unit)

    | Set of bool Pervasives.ref

    | Clear of bool Pervasives.ref

    | String of (string -> unit)

    | Set_string of string Pervasives.ref

    | Int of (int -> unit)

    | Set_int of int Pervasives.ref

    | Float of (float -> unit)

    | Set_float of float Pervasives.ref

    | Tuple of Arg.spec list

    | Symbol of string list * (string -> unit)

    | Rest of (string -> unit)

  type key = string

  type doc = string

  type usage_msg = string

  type anon_fun = string -> unit

  val parse :

    (Arg.key * Arg.spec * Arg.doc) list ->

    Arg.anon_fun -> Arg.usage_msg -> unit

  val parse_dynamic :

    (Arg.key * Arg.spec * Arg.doc) list Pervasives.ref ->

    Arg.anon_fun -> Arg.usage_msg -> unit

  val parse_argv :

    ?current:int Pervasives.ref ->

    string array ->

    (Arg.key * Arg.spec * Arg.doc) list ->

    Arg.anon_fun -> Arg.usage_msg -> unit

  val parse_argv_dynamic :

    ?current:int Pervasives.ref ->

    string array ->

    (Arg.key * Arg.spec * Arg.doc) list Pervasives.ref ->

    Arg.anon_fun -> string -> unit

  exception Help of string

  exception Bad of string

  val usage : (Arg.key * Arg.spec * Arg.doc) list -> Arg.usage_msg -> unit

  val usage_string :

    (Arg.key * Arg.spec * Arg.doc) list -> Arg.usage_msg -> string

  val align :

    ?limit:int ->

    (Arg.key * Arg.spec * Arg.doc) list ->

    (Arg.key * Arg.spec * Arg.doc) list

  val current : int Pervasives.ref

end


text:
package com.djonique.birdays.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.djonique.birdays.R;
import com.djonique.birdays.activities.MainActivity;
import com.djonique.birdays.adapters.MonthFragmentAdapter;
import com.djonique.birdays.database.DbHelper;
import com.djonique.birdays.models.Person;

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

public class MonthFragment extends Fragment {

    private MainActivity activity;
    private MonthFragmentAdapter adapter;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (getActivity() != null) {
            activity = (MainActivity) getActivity();
            addMonthPersonsFromDb();
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recycler_view, container, false);
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new MonthFragmentAdapter();
        recyclerView.setAdapter(adapter);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        adapter.notifyDataSetChanged();
    }

    public void addPerson(Person newPerson) {
        int position = -1;

        for (int i = 0; i < adapter.getItemCount(); i++) {
            Person person = adapter.getPerson(i);
            if (newPerson.getDay() < person.getDay()) {
                position = i;
                break;
            }
        }

        if (position != -1) {
            adapter.addPerson(position, newPerson);
        } else {
            adapter.addPerson(newPerson);
        }
    }

    public void addMonthPersonsFromDb() {
        adapter.removeAllPersons();
        List<Person> persons = new ArrayList<>();
        persons.addAll(activity.dbHelper.query().getThisMonthPersons());

        for (int i = 0; i < persons.size(); i++) {
            addPerson(persons.get(i));
        }
    }

    public void deleteRecord(long timeStamp) {
        adapter.removePerson(timeStamp);
    }

    public void findPerson(String name) {
        adapter.removeAllPersons();
        List<Person> persons = new ArrayList<>();
        persons.addAll(activity.dbHelper.query().getSearchMonthPerson(DbHelper.SELECTION_LIKE_NAME,
                new String[]{"%" + name + "%"}, DbHelper.COLUMN_NAME));

        for (int i = 0; i < persons.size(); i++) {
            addPerson(persons.get(i));
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        adapter.notifyDataSetChanged();
    }
}


text:
set :slim, :format => :html5
enable :sessions

get "/" do
	slim :index
end

post '/upload' do
	if params[:file]
		@image = params[:file][:image]
		new_filename = set_filename(@image[:filename])
		FileUtils.cp(@image[:tempfile].path,"public/files/#{new_filename}")
		session[:imagename] = new_filename
		redirect "/image"
	elsif
		redirect '/'
	end
end

get '/image' do
	redirect '/' if nil == session[:imagename]
	slim :image
end

post '/process' do
	if params[:scale] && params[:img]
		img = Magick::Image::read("public/files/#{session[:imagename]}")[0]
		case params[:scale]
		when "25smaller"
			img = img.scale(0.25)
		when "50smaller"
			img = img.scale(0.5)
		when "custom"
			w = params[:wimage].to_i
			h = params[:himage].to_i
			img = img.scale(w,h)
		else
		end
		new_filename = set_scaling_filename(session[:imagename])
		new_image = img.write("public/files/#{new_filename}")
		send_file "public/files/#{new_filename}", :filename => new_filename, :type => 'Application/octet-stream'
		img.destroy!
		session[:imagename] = nil
	else
		redirect '/'
	end
end

get '/about' do
	slim :about
end

not_found do
	slim :notfound
end

#test
get '/img' do
	img = Magick::Image::read("/home/ramdzi/Pictures/dct.png")[0]
	slim :test, :locals => {:gambar => img.columns}
end


text:
package test.learner;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import learner.Experience;
import learner.Learner;
import learner.features.ContinuousFeature;
import learner.features.Feature;
import learner.features.NominalFeature;
import learner.utils.Pair;

/**
 * Main class to train and test a Learner.
 *
 * @author woodser
 */
public class TestAbalone {

	private static final double PERCENT_TRAINING = .75;
	private static final double MIN_CONFIDENCE = .15;
	private static final double REPEAT = 3;
	private static final int RING_LENIENCY = 1;

	/**
	 * Program entry.
	 *
	 * @param args are not used
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void main(String[] args) throws FileNotFoundException, IOException {
		// read training / test data
		List<List<String>> rows = importCsv(new File("resources/abalone.csv"));

		// determine number of training instances vs test instances
		int numTraining = (int) Math.round(PERCENT_TRAINING * rows.size());

		// track precision, accuracy, and recall
		int right = 0, wrong = 0, unknown = 0;

		// perform experiment many times
		long time = 0;
		for (int i = 0; i < REPEAT; i++) {

			// randomize training and test set
			Collections.shuffle(rows, new Random(System.nanoTime()));

			// train a Learner with training instances
			Learner learner = new Learner();
			for (int j = 0; j < numTraining; j++) {
				learner.learn(getExperience(rows.get(j)));
			}

			// test Learner's outcome classification
			for (int j = numTraining; j < rows.size(); j++) {
				Integer actual = getOutcome(rows.get(j));
				long start = System.currentTimeMillis();
				Pair<Object, Double> classification = learner.getClassification(getFeatures(rows.get(j)), MIN_CONFIDENCE);
				Integer expected = (Integer) classification.getFirst();
				time += System.currentTimeMillis() - start;
				if (expected == null) unknown++;
				else if (Math.abs(actual - expected) <= RING_LENIENCY) right++;
				else wrong++;
			}
		}

		// print results
		double recall = (double) (right + wrong) / (double) (right + wrong + unknown);
		double precision = (double) right / (double) (right + wrong);
		double accuracy = (double) right / (double) (right + wrong + unknown);
		System.out.println("Done in " + time + " ms");
		System.out.println("Right: " + right + ", wrong: " + wrong + ", unknown: " + unknown);
		System.out.println("Accuracy: " + accuracy + ", precision: " + precision + ", recall: " + recall);
	}

	/**
	 * Imports a CSV file.
	 *
	 * @param file points to the CSV file
	 * @return List<List<String>> are the rows and values of the CSV file
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private static List<List<String>> importCsv(File file) throws FileNotFoundException, IOException {
		List<List<String>> rows = new ArrayList<List<String>>();
		try (BufferedReader br = new BufferedReader(new FileReader(file))) {
		    String line;
		    while ((line = br.readLine()) != null) {
		    	rows.add(Arrays.asList(line.split(",")));
		    }
		}
		return rows;
	}

	/**
	 * Gets a training instance from the given row.
	 *
	 * @param row is a row in the CSV training/test data
	 * @return Experience is a training instance comprised of features and an outcome
	 */
	private static Experience getExperience(List<String> row) {
		return new Experience(getFeatures(row), getOutcome(row));
	}

	/**
	 * Extracts features from the given row.
	 *
	 * @param row is a row in the CSV training/test data
	 * @return List<Feature> are the extracted features
	 */
	private static List<Feature> getFeatures(List<String> row) {
		String sex = row.get(0);
		double length = Double.parseDouble(row.get(1));
    double diameter = Double.parseDouble(row.get(2));
    double height = Double.parseDouble(row.get(3));
//    double whole_height = Double.parseDouble(row.get(4));
//    double shucked_height = Double.parseDouble(row.get(5));
    double viscera_weight = Double.parseDouble(row.get(6));
    double shell_weight = Double.parseDouble(row.get(7));
		List<Feature> features = new ArrayList<Feature>();
		features.add(new NominalFeature(sex));
		features.add(new ContinuousFeature(length));
		features.add(new ContinuousFeature(diameter));
		features.add(new ContinuousFeature(height));
//		features.add(new ContinuousFeature(whole_height));
//		features.add(new ContinuousFeature(shucked_height));
		features.add(new ContinuousFeature(viscera_weight));
		features.add(new ContinuousFeature(shell_weight));
		return features;
	}

	/**
	 * Returns the outcome of the given row.
	 *
	 * @param row is a row in the CSV training/test data
	 * @return Outcome is the outcome indicated in the row
	 */
	private static Integer getOutcome(List<String> row) {
	  return Integer.parseInt(row.get(8));
	}
}


text:
using System.Diagnostics;
using System.Globalization;

namespace Octokit
{
    /// <summary>
    /// Used to update a invitation.
    /// </summary>
    /// <remarks>
    /// </remarks>
    [DebuggerDisplay("{DebuggerDisplay,nq}")]
    public class InvitationUpdate
    {
        public InvitationUpdate(InvitationPermissionType permission)
        {
            Permissions = permission;
        }

        public InvitationPermissionType Permissions { get; private set; }

        internal string DebuggerDisplay
        {
            get
            {
                return string.Format(CultureInfo.InvariantCulture, "Permission: {0}", Permissions);
            }
        }
    }
}


text:
import includePaths from 'rollup-plugin-includepaths';
import {terser} from 'rollup-plugin-terser';

export default [{
  input: './public/app.js',
  output: {
    file: './public/app.min.js',
    format: 'es',
  },
  inlineDynamicImports: true,
  plugins: [
    includePaths({
      paths: ['node_modules'],
      extensions: ['.js'],
    }),
    terser(),
  ]
}];