text:
package com.whinc.widget.fontview;

import android.app.Application;
import android.content.Context;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by whinc on 2015/11/23.
 *
FontUtils can replace all the font under specified view.

 */
public class FontUtils {
    private static final String TAG = FontUtils.class.getSimpleName();
    private Map<String, SoftReference<Typeface>> mCache = new HashMap<>();
    private static FontUtils sSingleton = null;

    public static Typeface DEFAULT = Typeface.DEFAULT;

    // disable instantiate
    private FontUtils() {}

    public static FontUtils getInstance() {
        // double check
        if (sSingleton == null) {
            synchronized(FontUtils.class) {
                if (sSingleton == null) {
                    sSingleton = new FontUtils();
                }
            }
        }
        return sSingleton;
    }

    /**
     *
Replace the font of specified view and it's children

     * @param root The root view.
     * @param fontPath font file path relative to 'assets' directory.
     */
    public void replaceFontFromAsset(@NonNull View root, @NonNull String fontPath) {
        replaceFont(root, createTypefaceFromAsset(root.getContext(), fontPath));
    }

    /**
     *
Replace the font of specified view and it's children

     * @param root The root view.
     * @param fontPath font file path relative to 'assets' directory.
     * @param style One of {@link Typeface#NORMAL}, {@link Typeface#BOLD}, {@link Typeface#ITALIC}, {@link Typeface#BOLD_ITALIC}
     */
    public void replaceFontFromAsset(@NonNull View root, @NonNull String fontPath, int style) {
        replaceFont(root, createTypefaceFromAsset(root.getContext(), fontPath), style);
    }

    /**
     *
Replace the font of specified view and it's children

     * @param root The root view.
     * @param fontPath The full path to the font data.
     */
    public void replaceFontFromFile(@NonNull View root, @NonNull String fontPath) {
        replaceFont(root, createTypefaceFromFile(fontPath));
    }

    /**
     *
Replace the font of specified view and it's children

     * @param root The root view.
     * @param fontPath The full path to the font data.
     * @param style One of {@link Typeface#NORMAL}, {@link Typeface#BOLD}, {@link Typeface#ITALIC}, {@link Typeface#BOLD_ITALIC}
     */
    public void replaceFontFromFile(@NonNull View root, @NonNull String fontPath, int style) {
        replaceFont(root, createTypefaceFromFile(fontPath), style);
    }

    /**
     *
Replace the font of specified view and it's children with specified typeface

     */
    private void replaceFont(@NonNull View root, @NonNull Typeface typeface) {
        if (root == null || typeface == null) {
            return;
        }

        if (root instanceof TextView) { // If view is TextView or it's subclass, replace it's font
            TextView textView = (TextView)root;
            // Extract previous style of TextView
            int style = Typeface.NORMAL;
            if (textView.getTypeface() != null) {
                style = textView.getTypeface().getStyle();
            }
            textView.setTypeface(typeface, style);
        } else if (root instanceof ViewGroup) { // If view is ViewGroup, apply this method on it's child views
            ViewGroup viewGroup = (ViewGroup) root;
            for (int i = 0; i < viewGroup.getChildCount(); ++i) {
                replaceFont(viewGroup.getChildAt(i), typeface);
            }
        } // else return
    }

    /**
     *
Replace the font of specified view and it's children with specified typeface and text style

     * @param style One of {@link Typeface#NORMAL}, {@link Typeface#BOLD}, {@link Typeface#ITALIC}, {@link Typeface#BOLD_ITALIC}
     */
    private void replaceFont(@NonNull View root, @NonNull Typeface typeface, int style) {
        if (root == null || typeface == null) {
            return;
        }
        if (style < 0 || style > 3) {
            style = Typeface.NORMAL;
        }

        if (root instanceof TextView) { // If view is TextView or it's subclass, replace it's font
            TextView textView = (TextView)root;
            textView.setTypeface(typeface, style);
        } else if (root instanceof ViewGroup) { // If view is ViewGroup, apply this method on it's child views
            ViewGroup viewGroup = (ViewGroup) root;
            for (int i = 0; i < viewGroup.getChildCount(); ++i) {
                replaceFont(viewGroup.getChildAt(i), typeface, style);
            }
        } // else return
    }

    /**
     *
Create a Typeface instance with specified font file

     * @param fontPath font file path relative to 'assets' directory.
     * @return Return created typeface instance.
     */
    private Typeface createTypefaceFromAsset(Context context, String fontPath) {
        SoftReference<Typeface> typefaceRef = mCache.get(fontPath);
        Typeface typeface = null;
        if (typefaceRef == null || (typeface = typefaceRef.get()) == null) {
            typeface = Typeface.createFromAsset(context.getAssets(), fontPath);
            typefaceRef = new SoftReference<>(typeface);
            mCache.put(fontPath, typefaceRef);
        }
        return typeface;
    }

    private Typeface createTypefaceFromFile(String fontPath) {
        SoftReference<Typeface> typefaceRef = mCache.get(fontPath);
        Typeface typeface = null;
        if (typefaceRef == null || (typeface = typefaceRef.get()) == null) {
            typeface = Typeface.createFromFile(fontPath);
            typefaceRef = new SoftReference<>(typeface);
            mCache.put(fontPath, typefaceRef);
        }
        return typeface;
    }

    /**
     *
Replace system default font. Note:you should also add code below to your app theme in styles.xml.

     * {@code <item name="android:typeface">monospace</item>}
     *
The best place to call this method is {@link Application#onCreate()}, it will affect
     * whole app font.If you call this method after view is visible, you need to invalid the view to make it effective.

     * @param context {@link Context Context}
     * @param fontPath font file path relative to 'assets' directory.
     */
    public void replaceSystemDefaultFontFromAsset(@NonNull Context context, @NonNull String fontPath) {
        replaceSystemDefaultFont(createTypefaceFromAsset(context, fontPath));
    }

    /**
     *
Replace system default font. Note:you should also add code below to your app theme in styles.xml.

     * {@code <item name="android:typeface">monospace</item>}
     *
The best place to call this method is {@link Application#onCreate()}, it will affect
     * whole app font.If you call this method after view is visible, you need to invalid the view to make it effective.

     * @param context {@link Context Context}
     * @param fontPath The full path to the font data.
     */
    public void replaceSystemDefaultFontFromFile(@NonNull Context context, @NonNull String fontPath) {
        replaceSystemDefaultFont(createTypefaceFromFile(fontPath));
    }

    /**
     *
Replace system default font. Note:you should also add code below to your app theme in styles.xml.

     * {@code <item name="android:typeface">monospace</item>}
     *
The best place to call this method is {@link Application#onCreate()}, it will affect
     * whole app font.If you call this method after view is visible, you need to invalid the view to make it effective.

     */
    private void replaceSystemDefaultFont(@NonNull Typeface typeface) {
        modifyObjectField(null, "MONOSPACE", typeface);
    }

    private void modifyObjectField(Object obj, String fieldName, Object value) {
        try {
            Field defaultField = Typeface.class.getDeclaredField(fieldName);
            defaultField.setAccessible(true);
            defaultField.set(obj, value);

        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}


text:
namespace Lender.Slos.Extensions
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public static class DateTimeExtensions
    {
        static DateTimeExtensions()
        {
            var year = DateTime.Today.Year;

            MinValid = new DateTime(year, 1, 1);
            MaxValid = new DateTime(year, 12, 31);

            Holidays = new List<HolidayInfo>();
        }

        public static DateTime MinValid { get; set; }

        public static DateTime MaxValid { get; set; }

        public static ICollection<HolidayInfo> Holidays { get; private set; }

        public static bool IsWeekend(this DateTime dateTime)
        {
            switch (dateTime.DayOfWeek)
            {
                case DayOfWeek.Saturday:
                case DayOfWeek.Sunday:
                    return true;
                default:
                    return false;
            }
        }

        public static bool IsHoliday(this DateTime dateTime)
        {
            if (dateTime.Date < MinValid.Date)
            {
                throw new ArgumentOutOfRangeException(
                    "dateTime",
                    dateTime,
                    string.Format("Date must not be before '{0}'", MinValid.ToShortDateString()));
            }

            if (dateTime.Date > MaxValid.Date)
            {
                throw new ArgumentOutOfRangeException(
                    "dateTime",
                    dateTime,
                    string.Format("Date must not be after '{0}'", MaxValid.ToShortDateString()));
            }

            return Holidays.Where(e => e.Observed == dateTime.Date).Any();
        }

        public static bool IsWorkingDay(this DateTime dateTime)
        {
            if (IsHoliday(dateTime)) return false;

            return !IsWeekend(dateTime);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
module Mailosaur
  module Models
    class ServerCreateOptions < BaseModel
      def initialize(data = {})
        @name = data['name']
      end

      # @return [String] A name used to identify the server.
      attr_accessor :name
    end
  end
end


text:
/**
 *
 */
package me.dayler.ai.ami.service.context;

/**
 * Define session context, a instance is created for each active session.
 *
 * @author asalazar
 */
public interface SessionCtx {

    /**
     * @return Unique identifier for the session.
     */
    String getSessionID();

    /**
     * The responsibility to set this value is of the ami service handler implementation.
     *
     * @return Id to identify the call. Returns null if there is not a call associated with
     * this session.
     */
    String getCallID();

    /**
     * The responsibility to set this value is of the ami service handler implementation.
     *
     *  @param callID Id to identify the call.
     */
    void setCallID(String callID);

    /**
     * @return Channel associated to this session.
     */
    String getChannel();

    /**
     *
     * @param channel Channel associated with the session.
     */
    void setChannel(String channel);

    /**
     * @param ctxKey Context variable key;
     * @return Context variable Object associated with ctxKey.
     */
    Object getContextVar(String ctxKey);

    /**
     *
     * @param ctxKey Context variable key;
     * @return Context variable String associated with ctxKey.
     */
    String getString(String ctxKey);

    /**
     * @param ctxKey Context variable key.
     * @param ctxVar Variable object to put in the context.
     */
    void putCtxVar(String ctxKey, Object ctxVar);

    /**
     * Remove object associated with context.
     *
     * @param ctxKey Context variable key.
     */
    void removeCtxVar(String ctxKey);
}


text:
Result Grouping Template (CSWP)
================

This folder contains the display templates for grouping your search results.

File | Desciption
--- | ---
__Control_Group.html__ | This is the control template for the grouping.
__Item_Group.html__ | This is the item template for the grouping.

**Usage**
These files need to be uploaded to the master page gallery: **http://your-site/_catalogs/masterpage/**.

More information can be found on the following blog post: http://www.eliostruyf.com/grouping-search-results-with-display-templates-for-the-cswp/


text:
/**
 * Laser gun ability.
 **/
ig.module(
    'game.abilities.machine-gun'
)
.requires(
	// require the shoot ability
	'plusplus.abilities.ability-shoot',
	// require the projectile
	'game.entities.laser',
	// if you want to use the config
    // don't forget to require it
    'plusplus.core.config',
	// and some utils
	'plusplus.helpers.utils'
)
.defines(function () {
    "use strict";

	var _c = ig.CONFIG;
	var _ut = ig.utils;

	ig.MachineGun = ig.AbilityShoot.extend( {

		// this ability spawns a laser beam

		spawningEntity: ig.EntityLaser,

		// velocity towards offset direction

		offsetVelX: 200,
		offsetVelY: _c.TOP_DOWN ? 200 : 0

		// laser ability has no special type, so it won't activate on tap or hold

	} );

});


text:
package com.suny.entity.dictionary;

/**
 * 系统配置参数加载类
 *
 * @author Frank Adolf suny
 * @date   20150130
 * @note
 */
public class SystemParas {
	/***************   emotional  analysis dictionary        ****************/
	/**
	 * the chinese stop words
	 */
	public static String stop_word_dict = ReadConfigUtil.getValue("stop_word_dict_file");

	/**
	 * the absolute path of emotional dictionary
	 */
	public static String emotion_posi_dict = ReadConfigUtil.getValue("positive_dict_file");

	public static String emotion_nega_dict = ReadConfigUtil.getValue("negative_dict_file");

	/**
	 * the absolute path of family name and frequency dictionary
	 */
	public static String family_name_fre_dict = ReadConfigUtil.getValue("family_name_freq_dict");

	/**
	 * Traditional and simplified different characters
	 */
	public static String trad_diff_simpl_dict = ReadConfigUtil.getValue("trad_simple_dict_file");

	/**
	 * Special words for juage the
	 */
	public static String special_words_dict = ReadConfigUtil.getValue("special_word_dict_file");
	/**
	 * current running file path
	 */
	public static String currentRunPath = null;

	/**
	 * construction function
	 */
	public SystemParas() {
		// load all the dictionary file
		this.init();
	}

	/**
	 * this function using initinal the file path
	 */
	public  void init() {
		if (null == currentRunPath) {
			currentRunPath = System.getProperty("user.dir")+"/data_entity";
		}

		this.setDictName();
	}

	/**
	 * set the dictionary name automatic
	 * @param
	 */
	public  void setDictName() {

		if (stop_word_dict.isEmpty() == true) {
			stop_word_dict = currentRunPath + "/" + "chinese_stopword";
		}
		//
		if (emotion_posi_dict.isEmpty() == true) {
			emotion_posi_dict = currentRunPath + "/" + "posi_words";
		}
		if (emotion_nega_dict.isEmpty() == true) {
			emotion_nega_dict = currentRunPath + "/" + "nega_words";
		}
		if (family_name_fre_dict.isEmpty() == true) {
			family_name_fre_dict = currentRunPath + "/" + "family_name_fre";
		}
		if (trad_diff_simpl_dict.isEmpty() == true) {
			trad_diff_simpl_dict = currentRunPath + "/" + "trad_simp";
		}
		if (special_words_dict.isEmpty() == true) {
			special_words_dict = currentRunPath + "/" + "posi_words";
		}
	}
}


text:
package me.vilsol.blockly2java.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BField {

    String value();

}


text:
<?php echo __('Couldn\'t send E-mail. Please retry or contact to administrator.') ?>
<?php use_helper('Javascript') ?>

<?php echo link_to_function(__('Back to previous page'), 'history.back()') ?>


text:
<?php

/**
 * Tests for action=revisiondelete
 * @covers APIRevisionDelete
 * @group API
 * @group medium
 * @group Database
 */
class ApiRevisionDeleteTest extends ApiTestCase {

	public static $page = 'Help:ApiRevDel_test';
	public $revs = [];

	protected function setUp() {
		// Needs to be before setup since this gets cached
		$this->mergeMwGlobalArrayValue(
			'wgGroupPermissions',
			[ 'sysop' => [ 'deleterevision' => true ] ]
		);
		parent::setUp();
		// Make a few edits for us to play with
		for ( $i = 1; $i <= 5; $i++ ) {
			self::editPage( self::$page, MWCryptRand::generateHex( 10 ), 'summary' );
			$this->revs[] = Title::newFromText( self::$page )
				->getLatestRevID( Title::GAID_FOR_UPDATE );
		}

	}

	public function testHidingRevisions() {
		$user = self::$users['sysop']->getUser();
		$revid = array_shift( $this->revs );
		$out = $this->doApiRequest( [
			'action' => 'revisiondelete',
			'type' => 'revision',
			'target' => self::$page,
			'ids' => $revid,
			'hide' => 'content|user|comment',
			'token' => $user->getEditToken(),
		] );
		// Check the output
		$out = $out[0]['revisiondelete'];
		$this->assertEquals( $out['status'], 'Success' );
		$this->assertArrayHasKey( 'items', $out );
		$item = $out['items'][0];
		$this->assertArrayHasKey( 'userhidden', $item );
		$this->assertArrayHasKey( 'commenthidden', $item );
		$this->assertArrayHasKey( 'texthidden', $item );
		$this->assertEquals( $item['id'], $revid );

		// Now check that that revision was actually hidden
		$rev = Revision::newFromId( $revid );
		$this->assertEquals( $rev->getContent( Revision::FOR_PUBLIC ), null );
		$this->assertEquals( $rev->getComment( Revision::FOR_PUBLIC ), '' );
		$this->assertEquals( $rev->getUser( Revision::FOR_PUBLIC ), 0 );

		// Now test unhiding!
		$out2 = $this->doApiRequest( [
			'action' => 'revisiondelete',
			'type' => 'revision',
			'target' => self::$page,
			'ids' => $revid,
			'show' => 'content|user|comment',
			'token' => $user->getEditToken(),
		] );

		// Check the output
		$out2 = $out2[0]['revisiondelete'];
		$this->assertEquals( $out2['status'], 'Success' );
		$this->assertArrayHasKey( 'items', $out2 );
		$item = $out2['items'][0];

		$this->assertArrayNotHasKey( 'userhidden', $item );
		$this->assertArrayNotHasKey( 'commenthidden', $item );
		$this->assertArrayNotHasKey( 'texthidden', $item );

		$this->assertEquals( $item['id'], $revid );

		$rev = Revision::newFromId( $revid );
		$this->assertNotEquals( $rev->getContent( Revision::FOR_PUBLIC ), null );
		$this->assertNotEquals( $rev->getComment( Revision::FOR_PUBLIC ), '' );
		$this->assertNotEquals( $rev->getUser( Revision::FOR_PUBLIC ), 0 );
	}

	public function testUnhidingOutput() {
		$user = self::$users['sysop']->getUser();
		$revid = array_shift( $this->revs );
		// Hide revisions
		$this->doApiRequest( [
			'action' => 'revisiondelete',
			'type' => 'revision',
			'target' => self::$page,
			'ids' => $revid,
			'hide' => 'content|user|comment',
			'token' => $user->getEditToken(),
		] );

		$out = $this->doApiRequest( [
			'action' => 'revisiondelete',
			'type' => 'revision',
			'target' => self::$page,
			'ids' => $revid,
			'show' => 'comment',
			'token' => $user->getEditToken(),
		] );
		$out = $out[0]['revisiondelete'];
		$this->assertEquals( $out['status'], 'Success' );
		$this->assertArrayHasKey( 'items', $out );
		$item = $out['items'][0];
		// Check it has userhidden & texthidden keys
		// but no commenthidden key
		$this->assertArrayHasKey( 'userhidden', $item );
		$this->assertArrayNotHasKey( 'commenthidden', $item );
		$this->assertArrayHasKey( 'texthidden', $item );
		$this->assertEquals( $item['id'], $revid );
	}
}


text:
<?php

namespace Google\Service\Contentwarehouse;

class IndexingDupsComputedLocalizedAlternateNamesLocaleEntry extends \Google\Model
{
  /**
   * @var string
   */
  public $clusterId;
  /**
   * @var string
   */
  public $deviceMatchInfo;
  /**
   * @var string
   */
  public $language;
  /**
   * @var string
   */
  public $url;
  /**
   * @var int
   */
  public $urlEncoding;
  /**
   * @var int
   */
  public $urlRegionCode;

  /**
   * @param string
   */
  public function setClusterId($clusterId)
  {
    $this->clusterId = $clusterId;
  }
  /**
   * @return string
   */
  public function getClusterId()
  {
    return $this->clusterId;
  }
  /**
   * @param string
   */
  public function setDeviceMatchInfo($deviceMatchInfo)
  {
    $this->deviceMatchInfo = $deviceMatchInfo;
  }
  /**
   * @return string
   */
  public function getDeviceMatchInfo()
  {
    return $this->deviceMatchInfo;
  }
  /**
   * @param string
   */
  public function setLanguage($language)
  {
    $this->language = $language;
  }
  /**
   * @return string
   */
  public function getLanguage()
  {
    return $this->language;
  }
  /**
   * @param string
   */
  public function setUrl($url)
  {
    $this->url = $url;
  }
  /**
   * @return string
   */
  public function getUrl()
  {
    return $this->url;
  }
  /**
   * @param int
   */
  public function setUrlEncoding($urlEncoding)
  {
    $this->urlEncoding = $urlEncoding;
  }
  /**
   * @return int
   */
  public function getUrlEncoding()
  {
    return $this->urlEncoding;
  }
  /**
   * @param int
   */
  public function setUrlRegionCode($urlRegionCode)
  {
    $this->urlRegionCode = $urlRegionCode;
  }
  /**
   * @return int
   */
  public function getUrlRegionCode()
  {
    return $this->urlRegionCode;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(IndexingDupsComputedLocalizedAlternateNamesLocaleEntry::class, 'Google_Service_Contentwarehouse_IndexingDupsComputedLocalizedAlternateNamesLocaleEntry');


text:
package org.openkilda.wfm.topology.switchmanager.service;

import org.openkilda.floodlight.api.response.SpeakerResponse;
import org.openkilda.floodlight.api.response.rulemanager.SpeakerCommandResponse;
import org.openkilda.messaging.MessageCookie;
import org.openkilda.messaging.error.ErrorData;
import org.openkilda.messaging.error.ErrorType;
import org.openkilda.messaging.info.InfoData;
import org.openkilda.messaging.info.grpc.CreateOrUpdateLogicalPortResponse;
import org.openkilda.messaging.swmanager.request.CreateLagPortRequest;
import org.openkilda.rulemanager.RuleManager;
import org.openkilda.wfm.error.MessageDispatchException;
import org.openkilda.wfm.error.UnexpectedInputException;
import org.openkilda.wfm.share.utils.FsmExecutor;
import org.openkilda.wfm.topology.switchmanager.error.OperationTimeoutException;
import org.openkilda.wfm.topology.switchmanager.error.SpeakerFailureException;
import org.openkilda.wfm.topology.switchmanager.fsm.CreateLagPortFsm;
import org.openkilda.wfm.topology.switchmanager.fsm.CreateLagPortFsm.CreateLagContext;
import org.openkilda.wfm.topology.switchmanager.fsm.CreateLagPortFsm.CreateLagEvent;
import org.openkilda.wfm.topology.switchmanager.fsm.CreateLagPortFsm.CreateLagState;
import org.openkilda.wfm.topology.switchmanager.service.configs.LagPortOperationConfig;

import lombok.Getter;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.squirrelframework.foundation.fsm.StateMachineBuilder;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class CreateLagPortService implements SwitchManagerHubService {
    @Getter
    private final SwitchManagerCarrier carrier;

    private final LagPortOperationService lagPortOperationService;

    private final Map<String, CreateLagPortFsm> handlers = new HashMap<>();
    private final StateMachineBuilder<CreateLagPortFsm, CreateLagState, CreateLagEvent, CreateLagContext> builder;
    private final FsmExecutor<CreateLagPortFsm, CreateLagState, CreateLagEvent, CreateLagContext> fsmExecutor;

    private boolean active = true;

    public CreateLagPortService(SwitchManagerCarrier carrier, LagPortOperationConfig config, RuleManager ruleManager) {
        this.lagPortOperationService = new LagPortOperationService(config, ruleManager);
        this.builder = CreateLagPortFsm.builder();
        this.fsmExecutor = new FsmExecutor<>(CreateLagEvent.NEXT);
        this.carrier = carrier;
    }

    /**
     * Handle LAG port request.
     */
    public void handleCreateLagRequest(String key, CreateLagPortRequest request) {
        CreateLagPortFsm fsm = builder.newStateMachine(CreateLagState.START, carrier, key, request,
                lagPortOperationService);
        handlers.put(key, fsm);

        fsm.start();
        fireFsmEvent(fsm, CreateLagEvent.NEXT, CreateLagContext.builder().build());
    }

    @Override
    public void activate() {
        active = true;
    }

    @Override
    public boolean deactivate() {
        active = false;
        return isAllOperationsCompleted();
    }

    @Override
    public boolean isAllOperationsCompleted() {
        return handlers.isEmpty();
    }

    @Override
    public void timeout(@NonNull MessageCookie cookie) throws MessageDispatchException {
        OperationTimeoutException error = new OperationTimeoutException("Create operation timeout");
        fireFsmEvent(cookie, CreateLagEvent.ERROR, CreateLagContext.builder().error(error).build());
    }

    @Override
    public void dispatchWorkerMessage(InfoData payload, MessageCookie cookie)
            throws UnexpectedInputException, MessageDispatchException {
        if (payload instanceof CreateOrUpdateLogicalPortResponse) {
            handleCreateOrUpdateResponse((CreateOrUpdateLogicalPortResponse) payload, cookie);
        } else {
            throw new UnexpectedInputException(payload);
        }
    }

    @Override
    public void dispatchWorkerMessage(SpeakerResponse payload, MessageCookie cookie)
            throws UnexpectedInputException, MessageDispatchException {
        if (payload instanceof SpeakerCommandResponse) {
            SpeakerCommandResponse response = (SpeakerCommandResponse) payload;
            if (response.isSuccess()) {
                fireFsmEvent(cookie, CreateLagEvent.SPEAKER_ENTITIES_INSTALLED, CreateLagContext.builder().build());
            } else {
                ErrorData errorData = new ErrorData(ErrorType.INTERNAL_ERROR, "OpenFlow commands failed",
                        response.getFailedCommandIds().values().toString());
                fireFsmEvent(cookie, CreateLagEvent.ERROR,
                        CreateLagContext.builder().error(new SpeakerFailureException(errorData)).build());
            }
        } else {
            throw new UnexpectedInputException(payload);
        }
    }

    @Override
    public void dispatchErrorMessage(ErrorData payload, MessageCookie cookie)
            throws MessageDispatchException {
        CreateLagContext context = CreateLagContext.builder()
                .error(new SpeakerFailureException(payload))
                .build();
        fireFsmEvent(cookie, CreateLagEvent.ERROR, context);
    }

    private void handleCreateOrUpdateResponse(CreateOrUpdateLogicalPortResponse payload, MessageCookie cookie)
            throws MessageDispatchException {
        fireFsmEvent(cookie, CreateLagEvent.LAG_INSTALLED,
                CreateLagContext.builder().createdLogicalPort(payload.getLogicalPort()).build());
    }

    private void fireFsmEvent(MessageCookie cookie, CreateLagEvent event, CreateLagContext context)
            throws MessageDispatchException {
        CreateLagPortFsm handler = null;
        if (cookie != null) {
            handler = handlers.get(cookie.getValue());
        }
        if (handler == null) {
            throw new MessageDispatchException(cookie);
        }
        fireFsmEvent(handler, event, context);
    }

    private void fireFsmEvent(CreateLagPortFsm fsm, CreateLagEvent event, CreateLagContext context) {
        fsmExecutor.fire(fsm, event, context);
        removeIfCompleted(fsm);
    }

    private void removeIfCompleted(CreateLagPortFsm fsm) {
        if (fsm.isTerminated()) {
            String requestKey = fsm.getKey();
            log.info("Create LAG {} FSM have reached termination state (key={})", fsm.getRequest(), requestKey);

            handlers.remove(requestKey);
            carrier.cancelTimeoutCallback(requestKey);

            if (isAllOperationsCompleted() && !active) {
                carrier.sendInactive();
            }
        }
    }
}


text:
<!DOCTYPE html>

Static test


text:
package org.apache.flink.runtime.resourcemanager;

import org.apache.flink.runtime.clusterframework.types.ResourceProfile;

import java.io.Serializable;

/** Class containing information about the available cluster resources. */
public class ResourceOverview implements Serializable {

    private static final long serialVersionUID = 7618746920569224557L;

    private static final ResourceOverview EMPTY_RESOURCE_OVERVIEW =
            new ResourceOverview(0, 0, 0, 0, 0, ResourceProfile.ZERO, ResourceProfile.ZERO);

    private final int numberTaskManagers;

    private final int numberRegisteredSlots;

    private final int numberFreeSlots;

    private final int numberBlockedTaskManagers;

    private final int numberBlockedFreeSlots;

    private final ResourceProfile totalResource;

    private final ResourceProfile freeResource;

    public ResourceOverview(
            int numberTaskManagers,
            int numberRegisteredSlots,
            int numberFreeSlots,
            int numberBlockedTaskManagers,
            int numberBlockedFreeSlots,
            ResourceProfile totalResource,
            ResourceProfile freeResource) {
        this.numberTaskManagers = numberTaskManagers;
        this.numberRegisteredSlots = numberRegisteredSlots;
        this.numberFreeSlots = numberFreeSlots;
        this.numberBlockedTaskManagers = numberBlockedTaskManagers;
        this.numberBlockedFreeSlots = numberBlockedFreeSlots;
        this.totalResource = totalResource;
        this.freeResource = freeResource;
    }

    public int getNumberTaskManagers() {
        return numberTaskManagers;
    }

    public int getNumberRegisteredSlots() {
        return numberRegisteredSlots;
    }

    public int getNumberFreeSlots() {
        return numberFreeSlots;
    }

    public int getNumberBlockedTaskManagers() {
        return numberBlockedTaskManagers;
    }

    public int getNumberBlockedFreeSlots() {
        return numberBlockedFreeSlots;
    }

    public ResourceProfile getTotalResource() {
        return totalResource;
    }

    public ResourceProfile getFreeResource() {
        return freeResource;
    }

    public static ResourceOverview empty() {
        return EMPTY_RESOURCE_OVERVIEW;
    }
}


text:
<template name="files">

            <input type="text" placeholder="Search in Files"/>

            {{#each files}}
                {{#if showFile}}
                    {{getUserName}} - {{name}}
                {{/if}}
            {{/each}}

</template>


text:
param([switch]$GetModuleStepDetails)
if ($GetModuleStepDetails) { return (@{RunLevel = 3; Critical = $true}) }

Get-ChildItem (Join-Path $ProfileConfig.ConsolePaths.PowerShell "Exports\Aliases") -Filter "*.alias" -File | % {
	$alias = $_.BaseName
	if ($alias.StartsWith("0x")) {
		$alias = [string]::Concat(($alias | % Split '+' | % { [char][int]($_) }))
	}
	$command = Get-Content -Path $_.FullName | Select-Object -First 1
	Set-Alias -Name $alias -Value $command -Force
	Export-ModuleMember -Alias $alias
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>testing.plugin.dtexample — IPython v0.10 documentation</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="top" title="IPython v0.10 documentation" href="../../index.html" />
    <link rel="up" title="The IPython API" href="../index.html" />
    <link rel="next" title="testing.plugin.show_refs" href="IPython.testing.plugin.show_refs.html" />
    <link rel="prev" title="testing.parametric" href="IPython.testing.parametric.html" />

Navigation

          index

          modules |

          next |

          previous |

IPython v0.10 documentation »

The IPython API »

testing.plugin.dtexample¶

Module: <tt class="xref docutils literal">testing.plugin.dtexample</tt>¶

Simple example using doctests.

This file just contains doctests both using plain python and IPython prompts.
All tests should be loaded by nose.

Functions¶

<tt class="descclassname">IPython.testing.plugin.dtexample.</tt><tt class="descname">ipfunc</tt><big>(</big><big>)</big>¶

Some ipython tests...

In [1]: import os

In [3]: 2+3
Out[3]: 5

In [26]: for i in range(3):

....:     print i,
....:     print i+1,
....:

0 1 1 2 2 3

Examples that access the operating system work:

In [1]: !echo hello
hello

In [2]: !echo hello > /tmp/foo

In [3]: !cat /tmp/foo
hello

In [4]: rm -f /tmp/foo

It’s OK to use ‘_’ for the last result, but do NOT try to use IPython’s
numbered history of _NN outputs, since those won’t exist under the
doctest environment:

In [7]: ‘hi’
Out[7]: ‘hi’

In [8]: print repr(_)
‘hi’

In [7]: 3+4
Out[7]: 7

In [8]: _+3
Out[8]: 10

In [9]: ipfunc()
Out[9]: ‘ipfunc’

<tt class="descclassname">IPython.testing.plugin.dtexample.</tt><tt class="descname">iprand</tt><big>(</big><big>)</big>¶

Some ipython tests with random output.

In [7]: 3+4
Out[7]: 7

In [8]: print ‘hello’
world  # random

In [9]: iprand()
Out[9]: ‘iprand’

<tt class="descclassname">IPython.testing.plugin.dtexample.</tt><tt class="descname">iprand_all</tt><big>(</big><big>)</big>¶

Some ipython tests with fully random output.

# all-random

In [7]: 1
Out[7]: 99

In [8]: print ‘hello’
world

In [9]: iprand_all()
Out[9]: ‘junk’

<tt class="descclassname">IPython.testing.plugin.dtexample.</tt><tt class="descname">pyfunc</tt><big>(</big><big>)</big>¶

Some pure python tests...

>>> pyfunc()
'pyfunc'

>>> import os

>>> 2+3
5

>>> for i in range(3):
...     print i,
...     print i+1,
...
0 1 1 2 2 3

<tt class="descclassname">IPython.testing.plugin.dtexample.</tt><tt class="descname">random_all</tt><big>(</big><big>)</big>¶

A function where we ignore the output of ALL examples.

Examples:

# all-random

This mark tells the testing machinery that all subsequent examples should
be treated as random (ignoring their output).  They are still executed,
so if a they raise an error, it will be detected as such, but their
output is completely ignored.

>>> 1+3
junk goes here...

>>> 1+3
klasdfj;

>>> 1+2
again,  anything goes
blah...

<tt class="descclassname">IPython.testing.plugin.dtexample.</tt><tt class="descname">ranfunc</tt><big>(</big><big>)</big>¶

A function with some random output.

Normal examples are verified as usual:
>>> 1+3
4

But if you put ‘# random’ in the output, it is ignored:
>>> 1+3
junk goes here...  # random

>>> 1+2
again,  anything goes #random
if multiline, the random mark is only needed once.

>>> 1+2
You can also put the random marker at the end:
# random

>>> 1+2
# random
.. or at the beginning.

More correct input is properly verified:
>>> ranfunc()
‘ranfunc’

Table Of Contents

testing.plugin.dtexample

Module: <tt class="docutils literal">testing.plugin.dtexample</tt>

Functions

Previous topic

testing.parametric

Next topic

testing.plugin.show_refs

This Page

Show Source

Quick search

            <form class="search" action="../../search.html" method="get">
              <input type="text" name="q" size="18" /> <input type="submit" value="Go" />
              <input type="hidden" name="check_keywords" value="yes" />
              <input type="hidden" name="area" value="default" />
            </form>

Navigation

          index

          modules |

          next |

          previous |

IPython v0.10 documentation »

The IPython API »

      © Copyright 2008, The IPython Development Team.
      Last updated on Aug 04, 2009.
      Created using Sphinx 0.5.2.


text:
from django.test.client import Client, RequestFactory
from yard.resources import Resource
from yard.resources.base import model_to_fields
from yard.api import Api
from yard import fields as FIELDS
from books.tests.base import BaseTestCase
from books.models  import Book, Author

class JSONBuilderTestCase( BaseTestCase ):

    def setUp(self):
        super(JSONBuilderTestCase, self).setUp()
        self.api = Api()
        self.resource_class = type('TestResouce', (Resource,), {'model': Book})
        self.resource_class.preprocess(self.api)
        self.resource = self.resource_class({})

    def assert_json(self, objects, fields, json):
        assert len(json) == len(objects)
        for i in json:
            assert len(i) == len(fields)# + 1
            #assert 'resource_uri' in i
            for field in fields:
                assert field in i

    def build_json(self, objects, fields):
        return self.resource.serialize_all(objects, fields)

    def test_fields_with_list(self):
        objects = list(Book.objects.all())
        fields = model_to_fields(Book)
        json = self.build_json( objects, fields )
        self.assert_json( objects, fields, json )

    def test_default_fields_with_queryset(self):
        queryset = Book.objects.all()
        fields = model_to_fields(Book)
        json = self.build_json( queryset, fields )
        self.assert_json( queryset, fields, json )

    def test_one_to_one(self):
        queryset = Book.objects.all()
        fields = {
            'id': FIELDS.Unicode,
            'author': {
                'id': FIELDS.Unicode,
                'name': FIELDS.Unicode,
            }
        }
        json = self.build_json( queryset, fields )
        assert len(json) == queryset.count()
        for book in json:
            assert len(book) == len(fields)# + 1
            #assert 'resource_uri' in book
            assert 'id' in book
            assert 'author' in book
            assert 'id' in book['author']
            assert 'name' in book['author']
            #assert 'resource_uri' in book['author']

    def test_one_to_many(self):
        queryset = Author.objects.all()
        fields = {'id': FIELDS.Unicode,
            'book_set': {
                'id': FIELDS.Unicode,
                'name': FIELDS.Unicode,
            }
        }
        json = self.build_json( queryset, fields )
        assert len(json) == queryset.count()
        assert len(json[0]) == len(fields)# + 1
        for author in json:
            #assert 'resource_uri' in author
            assert 'id' in author
            assert 'book_set' in author
            assert isinstance(author['book_set'], list)
            assert len(author['book_set']) == Book.objects.filter(author__id=json[0]['id']).count()
            for book in author['book_set']:
                assert 'id' in book
                assert 'name' in book
                #assert 'resource_uri' in book


text:
/**
 Notice : this source is extracted from Hadoop metric2 package
 and some source code may changed by zavakid
 */
package com.zavakid.mushroom.lib;

import com.zavakid.mushroom.MetricsRecordBuilder;

/**
 * A mutable int counter for implementing metrics sources
 *
 * @author Hadoop metric2 package's authors
 * @since 0.1
 */
public class MetricMutableCounterInt extends MetricMutableCounter<Integer> {

    private volatile int value;

    /**
     * Construct a mutable int counter
     *
     * @param name of the counter
     * @param description of the counter
     * @param initValue the initial value of the counter
     */
    public MetricMutableCounterInt(String name, String description, int initValue){
        super(name, description);
        this.value = initValue;
    }

    public synchronized void incr() {
        ++value;
        setChanged();
    }

    /**
     * Increment the value by a delta
     *
     * @param delta of the increment
     */
    public synchronized void incr(int delta) {
        value += delta;
        setChanged();
    }

    public void snapshot(MetricsRecordBuilder builder, boolean all) {
        if (all || changed()) {
            builder.addCounter(name, description, value);
            clearChanged();
        }
    }

}


text:
The real text

This should be parsed as before


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/** @suppress {duplicate} */
var remoting = remoting || {};

(function() {

'use strict';

var ESCAPE_KEY_CODE = 27;

/**
 * This class provides common functionality to Me2MeActivity and It2MeActivity,
 * e.g. constructing the relevant UX, and delegate the custom handling of the
 * session state changes to the |parentActivity|.
 *
 * @param {remoting.Activity} parentActivity
 * @param {remoting.SessionLogger} logger
 * @param {Array<string>=} opt_additionalCapabilities
 * @implements {remoting.ClientSession.EventHandler}
 * @implements {base.Disposable}
 * @constructor
 */
remoting.DesktopRemotingActivity = function(
    parentActivity, logger, opt_additionalCapabilities) {
  /** @private */
  this.parentActivity_ = parentActivity;
  /** @private {remoting.DesktopConnectedView} */
  this.connectedView_ = null;

  opt_additionalCapabilities = opt_additionalCapabilities || [];
  /** @private */
  this.sessionFactory_ = new remoting.ClientSessionFactory(
      document.querySelector('#client-container .client-plugin-container'),
      opt_additionalCapabilities);

  /** @private {remoting.ClientSession} */
  this.session_ = null;
  /** @private {remoting.ConnectingDialog} */
  this.connectingDialog_ = remoting.modalDialogFactory.createConnectingDialog(
      parentActivity.stop.bind(parentActivity));

  /** @private */
  this.isStopped_ = false;

  /** @private */
  this.logger_ = logger;

  /** @private {base.DomEventHook} */
  this.keydownHook_ = null;
};

/**
 * Initiates a connection.
 *
 * @param {remoting.Host} host the Host to connect to.
 * @param {remoting.CredentialsProvider} credentialsProvider
 * @return {void} Nothing.
 */
remoting.DesktopRemotingActivity.prototype.start =
    function(host, credentialsProvider) {
  var that = this;
  this.isStopped_ = false;
  this.sessionFactory_.createSession(this, this.logger_).then(
    function(/** remoting.ClientSession */ session) {
      if (that.isStopped_) {
        base.dispose(session);
      } else {
        that.session_ = session;
        session.connect(host, credentialsProvider);
      }
  }).catch(remoting.Error.handler(
    function(/** !remoting.Error */ error) {
      that.parentActivity_.onConnectionFailed(error);
  }));
};

remoting.DesktopRemotingActivity.prototype.stop = function() {
  this.isStopped_ = true;
  if (this.session_) {
    this.session_.disconnect(remoting.Error.none());
    console.log('Disconnected.');
  } else {
    console.log('Canceled.');
    // Session creation in process, just report it as canceled.
    this.logger_.logSessionStateChange(
      remoting.ChromotingEvent.SessionState.CONNECTION_CANCELED);
  }
};

/**
 * @param {remoting.ConnectionInfo} connectionInfo
 */
remoting.DesktopRemotingActivity.prototype.onConnected =
    function(connectionInfo) {
  this.connectingDialog_.hide();
  remoting.setMode(remoting.AppMode.IN_SESSION);
  if (!base.isAppsV2()) {
    remoting.toolbar.center();
    remoting.toolbar.preview();
  }

  this.connectedView_ = remoting.DesktopConnectedView.create(
      base.getHtmlElement('client-container'), connectionInfo);

  // Apply the default or previously-specified keyboard remapping.
  var remapping = connectionInfo.host().options.getRemapKeys();
  this.connectedView_.setRemapKeys(remapping);
  this.parentActivity_.onConnected(connectionInfo);

  // ESC key feature tracking
  var pluginElement = connectionInfo.plugin().element();
  var onKeyDown = function(/** KeyboardEvent **/ event) {
    if (event && event.keyCode == ESCAPE_KEY_CODE
      && remoting.fullscreen.isActive()) {
      this.logger_.incrementFeatureUsage('fullscreen_esc_count');
    }
  };
  this.keydownHook_ = new base.DomEventHook(
    pluginElement, 'keydown', onKeyDown.bind(this), false);
};

remoting.DesktopRemotingActivity.prototype.onDisconnected = function(reason) {
  if (this.handleError_(reason)) {
    return;
  }

  base.dispose(this.keydownHook_);

  this.parentActivity_.onDisconnected(reason);
};

/**
 * @param {!remoting.Error} error
 */
remoting.DesktopRemotingActivity.prototype.onConnectionFailed =
    function(error) {
  if (this.handleError_(error)) {
    return;
  }
  this.parentActivity_.onConnectionFailed(error);
};

/**
 * @param {!remoting.Error} error The error to be localized and displayed.
 * @return {boolean} returns true if the error is handled.
 * @private
 */
remoting.DesktopRemotingActivity.prototype.handleError_ = function(error) {
  if (error.hasTag(remoting.Error.Tag.AUTHENTICATION_FAILED)) {
    remoting.setMode(remoting.AppMode.HOME);
    remoting.handleAuthFailureAndRelaunch();
    return true;
  }
  return false;
};

remoting.DesktopRemotingActivity.prototype.dispose = function() {
  base.dispose(this.connectedView_);
  this.connectedView_ = null;
  base.dispose(this.session_);
  this.session_ = null;
  this.connectingDialog_.hide();
};

/** @return {remoting.DesktopConnectedView} */
remoting.DesktopRemotingActivity.prototype.getConnectedView = function() {
  return this.connectedView_;
};

/**
 * @return {remoting.ClientSession}.
 */
remoting.DesktopRemotingActivity.prototype.getSession = function() {
  return this.session_;
};

/** @return {remoting.ConnectingDialog} */
remoting.DesktopRemotingActivity.prototype.getConnectingDialog = function() {
  return this.connectingDialog_;
};

})();


text:
namespace Microsoft.Azure.Management.Compute.Models
{

    /// <summary>
    /// Defines values for CapacityReservationGroupInstanceViewTypes.
    /// </summary>
    public static class CapacityReservationGroupInstanceViewTypes
    {
        public const string InstanceView = "instanceView";
    }
}


text:
@class MPEventProjection;
@class MPConsentKitFilter;

@interface MPKitConfiguration : NSObject <NSSecureCoding, NSCopying>

@property (nonatomic, strong, readonly, nonnull) NSNumber *configurationHash;
@property (nonatomic, strong, nonnull) NSDictionary *configuration;
@property (nonatomic, strong, nullable) NSDictionary *filters;
@property (nonatomic, strong, readonly, nullable) NSDictionary *bracketConfiguration;
@property (nonatomic, strong, readonly, nullable) NSArray<NSNumber *> *configuredMessageTypeProjections;
@property (nonatomic, strong, readonly, nullable) NSArray<MPEventProjection *> *defaultProjections;
@property (nonatomic, strong, readonly, nullable) NSArray<MPEventProjection *> *projections;
@property (nonatomic, strong, readonly, nullable) NSNumber *integrationId;

@property (nonatomic) BOOL attributeValueFilteringIsActive;
@property (nonatomic) BOOL attributeValueFilteringShouldIncludeMatches;
@property (nonatomic, strong, nullable) NSString *attributeValueFilteringHashedAttribute;
@property (nonatomic, strong, nullable) NSString *attributeValueFilteringHashedValue;

@property (nonatomic, weak, readonly, nullable) NSDictionary *eventTypeFilters;
@property (nonatomic, weak, readonly, nullable) NSDictionary *eventNameFilters;
@property (nonatomic, weak, readonly, nullable) NSDictionary *eventAttributeFilters;
@property (nonatomic, weak, readonly, nullable) NSDictionary *messageTypeFilters;
@property (nonatomic, weak, readonly, nullable) NSDictionary *screenNameFilters;
@property (nonatomic, weak, readonly, nullable) NSDictionary *screenAttributeFilters;
@property (nonatomic, weak, readonly, nullable) NSDictionary *userIdentityFilters;
@property (nonatomic, weak, readonly, nullable) NSDictionary *userAttributeFilters;
@property (nonatomic, weak, readonly, nullable) NSDictionary *commerceEventAttributeFilters;
@property (nonatomic, weak, readonly, nullable) NSDictionary *commerceEventEntityTypeFilters;
@property (nonatomic, weak, readonly, nullable) NSDictionary *commerceEventAppFamilyAttributeFilters;
@property (nonatomic, weak, readonly, nullable) NSDictionary *addEventAttributeList;
@property (nonatomic, weak, readonly, nullable) NSDictionary *removeEventAttributeList;
@property (nonatomic, weak, readonly, nullable) NSDictionary *singleItemEventAttributeList;
@property (nonatomic, weak, readonly, nullable) NSDictionary *consentRegulationFilters;
@property (nonatomic, weak, readonly, nullable) NSDictionary *consentPurposeFilters;
@property (nonatomic, strong, readonly, nullable) MPConsentKitFilter *consentKitFilter;
@property (nonatomic, readonly) BOOL excludeAnonymousUsers;

- (nonnull instancetype)initWithDictionary:(nonnull NSDictionary *)configurationDictionary;

@end


text:
package org.joverseer.ui.info;

import java.util.HashMap;

import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.table.TableModel;

import org.joverseer.ui.support.Messages;
import org.joverseer.ui.support.controls.TableUtils;
import org.springframework.richclient.layout.TableLayoutBuilder;

/**
 * Order info view
 * Shows information about orders in tabular format
 *
 * @author Marios Skounakis
 */
public class OrderInfoView extends InfoView {

    // hack for nicer skill names as the abbreviations are used elsewhere.
	private void hackDescriptions() {
		HashMap<String, String> friendly = new HashMap<String, String>();
		friendly.put("CS", Messages.getString("OrderRequirement.CS"));
		friendly.put("CM", Messages.getString("OrderRequirement.CM"));
		friendly.put("AS", Messages.getString("OrderRequirement.AS"));
		friendly.put("AM", Messages.getString("OrderRequirement.AM"));
		friendly.put("MS", Messages.getString("OrderRequirement.MS"));
		friendly.put("MM", Messages.getString("OrderRequirement.MM"));
		friendly.put("ES", Messages.getString("OrderRequirement.ES"));
		friendly.put("EM", Messages.getString("OrderRequirement.EM"));
		friendly.put("M", Messages.getString("OrderRequirement.M"));
		friendly.put("Move", Messages.getString("OrderRequirement.Move"));
        // hack for nicer skill names as the abbreviations are used elsewhere.
        TableModel model = this.tables.get(0).getModel();
        int col = 6;
        String code;
        String nicer;
        for(int row=0;row < model.getRowCount();row++) {
        	code = (String)model.getValueAt(row, col);
        	nicer = friendly.get(code);
        	if (nicer != null) {
        		model.setValueAt(nicer, row, col);
        	}
        }
	}
    /**
     * @wbp.parser.entryPoint
     */
    @Override
	protected JComponent createControl() {
        TableLayoutBuilder lb = new TableLayoutBuilder();

        lb.separator(Messages.getString("OrderInfoView.Orders"));
        lb.relatedGapRow();
        lb.cell(createTableFromResource("classpath:metadata/orders", 700, 2400), "align=left");
        lb.relatedGapRow();
        TableUtils.setTableColumnWidths(this.tables.get(0), new int[]{120, 64, 64, 120, 80, 120, 120, 80});

        hackDescriptions();

        JScrollPane scp = new JScrollPane(lb.getPanel());
        scp.getVerticalScrollBar().setUnitIncrement(40);
        return scp;
    }

}


text:
using content::BrowserThread;
using content::UtilityProcessHost;
using content::UtilityProcessHostClient;

// This class coordinates a web resource unpack and parse task which is run in
// a separate process.  Results are sent back to this class and routed to
// the WebResourceService.
class WebResourceService::UnpackerClient : public UtilityProcessHostClient {
 public:
  explicit UnpackerClient(WebResourceService* web_resource_service)
    : web_resource_service_(web_resource_service),
      got_response_(false) {
  }

  void Start(const std::string& json_data) {
    AddRef();  // balanced in Cleanup.

    // TODO(willchan): Look for a better signal of whether we're in a unit test
    // or not. Using |ResourceDispatcherHost::Get()| for this is pretty lame.
    // If we don't have a ResourceDispatcherHost, assume we're in a test and
    // run the unpacker directly in-process.
    bool use_utility_process =
        content::ResourceDispatcherHost::Get() &&
        !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess);
    if (use_utility_process) {
      BrowserThread::ID thread_id;
      CHECK(BrowserThread::GetCurrentThreadIdentifier(&thread_id));
      BrowserThread::PostTask(
          BrowserThread::IO, FROM_HERE,
          base::Bind(&UnpackerClient::StartProcessOnIOThread,
                     this, thread_id, json_data));
    } else {
      WebResourceUnpacker unpacker(json_data);
      if (unpacker.Run()) {
        OnUnpackWebResourceSucceeded(*unpacker.parsed_json());
      } else {
        OnUnpackWebResourceFailed(unpacker.error_message());
      }
    }
  }

 private:
  virtual ~UnpackerClient() {}

  // UtilityProcessHostClient
  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE {
    bool handled = true;
    IPC_BEGIN_MESSAGE_MAP(WebResourceService::UnpackerClient, message)
      IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_UnpackWebResource_Succeeded,
                          OnUnpackWebResourceSucceeded)
      IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_UnpackWebResource_Failed,
                          OnUnpackWebResourceFailed)
      IPC_MESSAGE_UNHANDLED(handled = false)
    IPC_END_MESSAGE_MAP()
    return handled;
  }

  virtual void OnProcessCrashed(int exit_code) OVERRIDE {
    if (got_response_)
      return;

    OnUnpackWebResourceFailed(
        "Utility process crashed while trying to retrieve web resources.");
  }

  void OnUnpackWebResourceSucceeded(
      const DictionaryValue& parsed_json) {
    web_resource_service_->Unpack(parsed_json);
    Cleanup();
  }

  void OnUnpackWebResourceFailed(const std::string& error_message) {
    LOG(ERROR) << error_message;
    Cleanup();
  }

  // Release reference and set got_response_.
  void Cleanup() {
    DCHECK(!got_response_);
    got_response_ = true;

    web_resource_service_->EndFetch();
    Release();
  }

  void StartProcessOnIOThread(BrowserThread::ID thread_id,
                              const std::string& json_data) {
    UtilityProcessHost* host = UtilityProcessHost::Create(this, thread_id);
    host->EnableZygote();
    // TODO(mrc): get proper file path when we start using web resources
    // that need to be unpacked.
    host->Send(new ChromeUtilityMsg_UnpackWebResource(json_data));
  }

  scoped_refptr<WebResourceService> web_resource_service_;

  // True if we got a response from the utility process and have cleaned up
  // already.
  bool got_response_;
};

WebResourceService::WebResourceService(
    PrefService* prefs,
    const char* web_resource_server,
    bool apply_locale_to_url,
    const char* last_update_time_pref_name,
    int start_fetch_delay_ms,
    int cache_update_delay_ms)
    : prefs_(prefs),
      ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)),
      in_fetch_(false),
      web_resource_server_(web_resource_server),
      apply_locale_to_url_(apply_locale_to_url),
      last_update_time_pref_name_(last_update_time_pref_name),
      start_fetch_delay_ms_(start_fetch_delay_ms),
      cache_update_delay_ms_(cache_update_delay_ms) {
  DCHECK(prefs);
}

WebResourceService::~WebResourceService() { }

void WebResourceService::EndFetch() {
  in_fetch_ = false;
}

void WebResourceService::StartAfterDelay() {
  int64 delay = start_fetch_delay_ms_;
  // Check whether we have ever put a value in the web resource cache;
  // if so, pull it out and see if it's time to update again.
  if (prefs_->HasPrefPath(last_update_time_pref_name_)) {
    std::string last_update_pref =
        prefs_->GetString(last_update_time_pref_name_);
    if (!last_update_pref.empty()) {
      double last_update_value;
      base::StringToDouble(last_update_pref, &last_update_value);
      int64 ms_until_update = cache_update_delay_ms_ -
          static_cast<int64>((base::Time::Now() - base::Time::FromDoubleT(
          last_update_value)).InMilliseconds());
      // Wait at least |start_fetch_delay_ms_|.
      if (ms_until_update > start_fetch_delay_ms_)
        delay = ms_until_update;
    }
  }
  // Start fetch and wait for UpdateResourceCache.
  ScheduleFetch(delay);
}

// Delay initial load of resource data into cache so as not to interfere
// with startup time.
void WebResourceService::ScheduleFetch(int64 delay_ms) {
  MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&WebResourceService::StartFetch,
                 weak_ptr_factory_.GetWeakPtr()),
      base::TimeDelta::FromMilliseconds(delay_ms));
}

// Initializes the fetching of data from the resource server.  Data
// load calls OnURLFetchComplete.
void WebResourceService::StartFetch() {
  // First, put our next cache load on the MessageLoop.
  ScheduleFetch(cache_update_delay_ms_);

  // Set cache update time in preferences.
  prefs_->SetString(last_update_time_pref_name_,
      base::DoubleToString(base::Time::Now().ToDoubleT()));

  // If we are still fetching data, exit.
  if (in_fetch_)
    return;
  in_fetch_ = true;

  // Balanced in OnURLFetchComplete.
  AddRef();

  std::string web_resource_server = web_resource_server_;
  if (apply_locale_to_url_) {
    std::string locale = g_browser_process->GetApplicationLocale();
    web_resource_server.append(locale);
  }

  url_fetcher_.reset(content::URLFetcher::Create(
      GURL(web_resource_server), content::URLFetcher::GET, this));
  // Do not let url fetcher affect existing state in system context
  // (by setting cookies, for example).
  url_fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE |
                             net::LOAD_DO_NOT_SEND_COOKIES |
                             net::LOAD_DO_NOT_SAVE_COOKIES);
  net::URLRequestContextGetter* url_request_context_getter =
      g_browser_process->system_request_context();
  url_fetcher_->SetRequestContext(url_request_context_getter);
  url_fetcher_->Start();
}

void WebResourceService::OnURLFetchComplete(const content::URLFetcher* source) {
  // Delete the URLFetcher when this function exits.
  scoped_ptr<content::URLFetcher> clean_up_fetcher(url_fetcher_.release());

  // Don't parse data if attempt to download was unsuccessful.
  // Stop loading new web resource data, and silently exit.
  if (!source->GetStatus().is_success() || (source->GetResponseCode() != 200))
    return;

  std::string data;
  source->GetResponseAsString(&data);

  // UnpackerClient releases itself.
  UnpackerClient* client = new UnpackerClient(this);
  client->Start(data);

  Release();
}


text:
"""
Stacked Bar chart

"""

from __future__ import division
from pygal.graph.bar import Bar
from pygal.util import compute_scale
from pygal.adapters import none_to_zero

class StackedBar(Bar):
    """Stacked Bar graph"""

    _adapters = [none_to_zero]

    def _get_separated_values(self):
        transposed = zip(*[serie.values for serie in self.series])
        positive_vals = [sum([
            val for val in vals
            if val is not None and val >= self.zero])
            for vals in transposed]
        negative_vals = [sum([
            val
            for val in vals
            if val is not None and val < self.zero])
            for vals in transposed]
        return positive_vals, negative_vals

    def _compute_box(self, positive_vals, negative_vals):
        self._box.ymin = negative_vals and min(min(negative_vals), self.zero)
        self._box.ymax = positive_vals and max(max(positive_vals), self.zero)

    def _compute(self):
        positive_vals, negative_vals = self._get_separated_values()
        self._compute_box(positive_vals, negative_vals)

        if self.logarithmic:
            positive_vals = filter(lambda x: x > 0, positive_vals)
            negative_vals = filter(lambda x: x > 0, negative_vals)

        positive_vals = positive_vals or [self.zero]
        negative_vals = negative_vals or [self.zero]

        x_pos = [
            x / self._len for x in range(self._len + 1)
        ] if self._len > 1 else [0, 1]  # Center if only one value

        self._points(x_pos)
        y_pos = compute_scale(
            self._box.ymin, self._box.ymax, self.logarithmic, self.order_min
        ) if not self.y_labels else map(float, self.y_labels)
        self._x_ranges = zip(x_pos, x_pos[1:])

        self._x_labels = self.x_labels and zip(self.x_labels, [
            sum(x_range) / 2 for x_range in self._x_ranges])
        self._y_labels = zip(map(self._format, y_pos), y_pos)

        self.negative_cumulation = [0] * self._len
        self.positive_cumulation = [0] * self._len

    def _bar(self, parent, x, y, index, i, zero, shift=True):
        cumulation = (self.negative_cumulation if y < self.zero else
                      self.positive_cumulation)
        zero = cumulation[i]
        cumulation[i] = zero + y
        if zero == 0:
            zero = self.zero
            y -= self.zero
        return super(StackedBar, self)._bar(
            parent, x, zero + y, index, i, zero, False)


text:
package com.github.games647.changeskin.core.model.auth;

import com.github.games647.changeskin.core.model.GameProfile;

public class Account {

    private final GameProfile profile;
    private final String accessToken;

    public Account(GameProfile profile, String accessToken) {
        this.profile = profile;
        this.accessToken = accessToken;
    }

    public GameProfile getProfile() {
        return profile;
    }

    public String getAccessToken() {
        return accessToken;
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName() + '{' +
                "profile=" + profile +
                '}';
    }
}


text:
Over the Air (OTA) Update though SSH on Raspberry Pi.

Used to flash new firmware from the Arduino IDE though a Raspberry Pi to an Arduino.
In my case I have an Arduino connected over USB OTG to a Raspberry Pi Zero W, connected over WiFi

![Screenshoot](https://github.com/AustinSaintAubin/Arduino_OTA-SSH/blob/master/Screen%20Shot.png)

## Setup: Raspberry Pi (Client)
 - Install required dependacies ``` sudo apt-get install -y avrdude gcc-avr avr-libc ```
 - Manually Copy ( Arduino IDE/.../hardware/tools/avr/etc/avrdude.conf ) to the Raspberry Pi ( ~/Arduino/avrdude.conf )
 - Manually Copy ( usbreset.sh ) to the Raspberry Pi ( ~/Arduino/usbreset.sh )

## Setup: Workstation Setup

### MacOS
 - Run: ``` sh setup_ssh-passwordless-login.sh ``` to configure Password-less SSH Login.
 - Move HARDWARE folder to: /Users/.../Documents/Arduino/HARDWARE (or your Arduino "My Sketch" folder)
 	- Run: ``` chmod +x /Users/.../Documents/Arduino/HARDWARE/Arduino_OTA-SSH/arduino_ssh_upload.sh ```

### Linux
 - Your using linux... you'll figure it out ( similar to above ).

### Windows
 - Not my problem: However, [tchilton/farduino](https://github.com/tchilton/farduino)


text:
#region file header
// ////////////////////////////////////////////////////////////////////
// ///
// ///
// /// 16.05.2015
// ///
// ///
// ////////////////////////////////////////////////////////////////////
#endregion

using System;
using System.Globalization;

namespace Elite.Insight.Core.Helpers
{
	public static class StringExtensions
	{
		private static readonly TextInfo _textInfo = new CultureInfo("en-US", false).TextInfo;

		public static string ToCleanUpperCase(this string value)
		{
			return String.IsNullOrWhiteSpace(value) ? String.Empty : value.ToUpper().Trim();
		}

		public static string ToCleanTitleCase(this string value)
		{
			return String.IsNullOrWhiteSpace(value) ? String.Empty : _textInfo.ToTitleCase(value.Trim());
		}
	}
}


text:
describe Facter::Resolvers::DmiDecode do
  describe '#resolve' do
    subject(:dmidecode) { Facter::Resolvers::DmiDecode }

    before do
      allow(Facter::Core::Execution).to receive(:execute)
        .with('dmidecode', { logger: instance_of(Facter::Log) }).and_return(command_output)
    end

    after { dmidecode.invalidate_cache }

    context 'when virtualbox hypervisor' do
      let(:command_output) { load_fixture('dmi_decode_virtualbox').read }

      it 'detects virtualbox version' do
        expect(dmidecode.resolve(:virtualbox_version)).to eql('6.1.4')
      end

      it 'detects virtualbox revision' do
        expect(dmidecode.resolve(:virtualbox_revision)).to eql('136177')
      end

      it 'does not detect vmware_version' do
        expect(dmidecode.resolve(:vmware_version)).to be_nil
      end
    end

    context 'when vmware hypervisor' do
      let(:command_output) { load_fixture('dmi_decode_vmware').read }

      it 'does not detects virtualbox version' do
        expect(dmidecode.resolve(:virtualbox_version)).to be_nil
      end

      it 'does not detect detects virtualbox revision' do
        expect(dmidecode.resolve(:virtualbox_revision)).to be_nil
      end

      it 'detect vmware_version' do
        expect(dmidecode.resolve(:vmware_version)).to eq('ESXi 6.7')
      end
    end

    context 'when dmidecode command failed' do
      let(:command_output) { 'command not found: dmidecode' }

      it 'detects virtualbox version as nil' do
        expect(dmidecode.resolve(:virtualbox_version)).to be(nil)
      end

      it 'detects virtualbox revision as nil' do
        expect(dmidecode.resolve(:virtualbox_revision)).to be(nil)
      end
    end
  end
end


text:
package tests.jsystem.framework.system;

import java.util.Vector;

import jsystem.framework.sut.SutFactory;
import jsystem.framework.system.SystemManagerImpl;
import junit.framework.SystemTestCase;

/**
 * Test for jsystem.framework.system.SystemManagerImpl class.
 *
 * @author Uri.Koaz
 */
public class SystemManagerImplTests extends SystemTestCase {

	/**
	 * The test is testing the method getAllObjects in
	 * jsystem.framework.system.SystemManagerImpl class.
	 */
	public void testGetAllObjects(){
		SutFactory.getInstance().setSut("xml4Test2.xml");

		report.step("Check Method brings all SUT elemnts");

		Vector<String> vector = SystemManagerImpl.getAllObjects();

		assertEquals(3, vector.size());

		assertEquals("device1", vector.get(0));
		assertEquals("obj", vector.get(1));
		assertEquals("notSO", vector.get(2));

		report.step("Check Method brings Only System Objects SUT elemnts");

		vector = SystemManagerImpl.getAllObjects(true);

		assertEquals(2, vector.size());

		assertEquals("device1", vector.get(0));
		assertEquals("obj", vector.get(1));
	}
}


text:
<?php

    include_once 'headOpen.php';
    include_once 'headExtIncl.php';
    include_once 'headHamBurEnd.php';
    include 'headerNav.php';

echo "

        <content>";

    include 'addTop.php'
?>

An Introduction To Programming With Processing

Transforms

                            Processing provides a convenient method for animating and interacting with components of a sketch that are transformed in various ways. The term transform when used in this context generally refers to any one of, or combinations of the following three actions:

                                 Translation, Scaling, Rotation.

Translation
 is simply another way of saying "moving" but as the term moving can tend to be somewhat ambiguous when you consider that rotation also involves movement and so too does scaling (when you consider that the components making up an object such as it's vertices move when the object is scaled), we prefer to use the term translation as it specifically refers to positional data in terms of X, Y and Z of an entity. The function for applying translations within a sketch is translate() and it accepts parameters in the form of X and Y with an optional third parameter for Z (which we will discuss later) when using a 3D renderer.

Rotation
 is a transform that we have not discussed in any of our previous sketches, and as you will see can be a useful asset to creating certain types of animation within a sketch. Amongst the functions that provide us with access to rotation are rotate(), rotateX(), rotateY() and rotateZ() these functions accept values in radians.

Scaling
 is a transform accessed with the scale() function and it accepts a single float value or two floats that relate to X and Y or three floats that relate to X, Y and Z for 3D sketches. Scaling creates the impression of making things appear to be bigger or smaller within a sketch.

                            Let's have a look at an example of a static sketch using the translate() function.

size(400,60);
rect(0,0,50,50);
translate(width/2, 0);
fill(255,0,0);
rect(0,0,50,50);

                            In the first line of the sketch, we simply defined the size of the window in which the sketch is running as being very long horizontally and short, vertically. In the following line we drew a rectangle at the origin, and because the rectMode() function by default is set to CORNER, the rectangle sits perfectly flush with the top left hand corner of the Display Window. We then used the translate() function with a modification to the X parameter, and as you would expect the next time we draw a rectangle (after changing the fill color) it's position on the X axis reflects the translation we previously applied. However, if you have a look at the X parameter for the rect() function you will notice that things are a bit different to what you might expect as the X parameter reads 0 whereas the rectangle is drawn close to the center of the Display Window and to the right of the previously drawn rectangle.
Shouldn't the rectangle be drawn at the origin if it's X parameter is 0?
If you were thinking something along those lines then you are absolutely correct and in fact the rectangle is being drawn at the origin, the main difference here is that we have used the translate() function to move the origin, not of the rectangle but of the entire coordinate system. Let's have a look at how this happens.

Transforming Coordinate Space

Although the effect of what you are seeing in the Display Window creates the impression that Processing has moved the rectangle, the rectangle as it is indicated by it's X parameter in both rect() function calls tells us something different. That is, that the rectangle has in fact not moved. The reason that the rectangle has come to be drawn in this new location is due to the effect of the entire coordinate system moving.
If you were for a moment to reflect back on the Cartesian graph system that we discussed earlier  you might remember that everything in Processing works in a similar fashion to that of something drawn on graph paper. Bearing this in mind, what we have done in the previous sketch cannot accurately be described as moving the rectangle, but more akin to "moving the graph paper".
For example if we were to draw a rectangle on a piece of graph paper, then move the graph paper around, we would in effect be creating the impression of the rectangle drawn on the graph paper moving around. The rectangle itself would not be what you are moving around, in terms of the fact that the rectangle's positional X and Y data has not changed with relation to the origin of the coordinate system it was drawn relative to. We can therefore say that the rectangle has not moved, however the coordinate system associated with it has.

                An object drawn on graph paper does not move but the graph paper does

                This is the purpose of transforms in Processing, they move the coordinate system for us. We can still move the components of a sketch through their own positional parameters, which we usually supply in terms of X and Y data for parameters of a function, but bear in mind that mixing translation techniques like this will result in the component appearing to have "moved" by the sum of the two data sets. To put this in another way, the distance the entity would appear to have moved would be the sum of the translate() function plus the X, Y and Z parameters of the function to draw the entity.

<?php
    include 'addBottom.php';
    include 'processingBNav01.php';

echo "";
    include 'processingBNav02.php';
echo "Quiz 03";

    include 'processingBNav03.php';

echo "";
     include 'processingBNav04.php';
echo "Animation System";

    include 'processingBNav05.php';

echo "

			</content>";

    include 'sideBarOpen.php';
    include 'processingNavMain.php';
    include 'sideBarClose.php';

echo "

";

    include 'footer.php';
    include 'analytics.php';
    include 'mainHTMLClose.php'
?>


text:
import deepDiff from '../src/deepDiff'

describe('deepDiff', () => {
  const objOne = {
    a: 1,
    b: {
      c: 2,
      d: 3
    },
    e: 4,
    f: true,
    g: [1, 'two', 3, 'four'],
    h: [1, 'two', 3, 'four'],
    i: true,
    j: null,
    k: 'blue',
    l: [[0, 1], [2, 3]]
  }

  const objTwo = {
    a: 1,
    b: {
      c: 2,
      d: 30,
      f: 50
    },
    e: 40,
    f: true,
    g: [1, 'two', 3, 'four'],
    h: [1, 'owt', 3, 'four'],
    i: false,
    j: null,
    k: null,
    l: [[0, 1], [2, 4]]
  }

  const expected = {
    b: {
      d: 30
    },
    e: 40,
    h: [1, 'owt', 3, 'four'],
    i: false,
    k: null,
    l: [[0, 1], [2, 4]]
  }

  const expectedWithNewKeys = {
    b: {
      d: 30,
      f: 50
    },
    e: 40,
    h: [1, 'owt', 3, 'four'],
    i: false,
    k: null,
    l: [[0, 1], [2, 4]]
  }

  it('should return the diff object between two objects', () => {
    expect(deepDiff(objOne, objTwo)).toEqual(expected)
  })

  it('should include new keys when the third parameter is true', () => {
    expect(deepDiff(objOne, objTwo, true)).toEqual(expectedWithNewKeys)
  })

  it('should throw a new TypeError if the first parameter is not an object', () => {
    const wrongParam = JSON.stringify(objOne)

    // The test will not pass by trying:
    // `expect(deepDiff(wrongParam, objTwo)).toThrowError(TypeError)
    expect(() => deepDiff(wrongParam, objTwo)).toThrowError(TypeError)
  })

  it('should throw a new TypeError if the second parameter is not an object', () => {
    const wrongParam = JSON.stringify(objTwo)

    // The test will not pass by trying:
    // `expect(deepDiff(objOne, wrongParam)).toThrowError(TypeError)
    expect(() => deepDiff(objOne, wrongParam)).toThrowError(TypeError)
  })

  it('should not throw an error if the third parameter is not a boolean', () => {
    let wrongParam = JSON.stringify(objOne)

    expect(deepDiff(objOne, objTwo, wrongParam)).toEqual(expectedWithNewKeys)

    wrongParam = null

    expect(deepDiff(objOne, objTwo, wrongParam)).toEqual(expected)
  })

  it('should not mutate the objects or reference one of the parameters', () => {
    expect(deepDiff(objOne, objTwo)).not.toBe(objOne)
    expect(deepDiff(objOne, objTwo)).not.toBe(objTwo)
  })

  it('should return null if there is no difference between objects', () => {
    expect(deepDiff(objOne, objOne)).toBe(null)
  })
})


text:
namespace web {

URLDataSourceIOSImpl::URLDataSourceIOSImpl(const std::string& source_name,
                                           URLDataSourceIOS* source)
    : source_name_(source_name), backend_(NULL), source_(source) {
}

URLDataSourceIOSImpl::~URLDataSourceIOSImpl() {
}

void URLDataSourceIOSImpl::SendResponse(
    int request_id,
    scoped_refptr<base::RefCountedMemory> bytes) {
  // Take a ref-pointer on entry so byte->Release() will always get called.
  if (URLDataManagerIOS::IsScheduledForDeletion(this)) {
    // We're scheduled for deletion. Servicing the request would result in
    // this->AddRef being invoked, even though the ref count is 0 and 'this' is
    // about to be deleted. If the AddRef were allowed through, when 'this' is
    // released it would be deleted again.
    //
    // This scenario occurs with DataSources that make history requests. Such
    // DataSources do a history query in |StartDataRequest| and the request is
    // live until the object is deleted (history requests don't up the ref
    // count). This means it's entirely possible for the DataSource to invoke
    // |SendResponse| between the time when there are no more refs and the time
    // when the object is deleted.
    return;
  }
  web::WebThread::PostTask(
      web::WebThread::IO, FROM_HERE,
      base::Bind(&URLDataSourceIOSImpl::SendResponseOnIOThread, this,
                 request_id, std::move(bytes)));
}

void URLDataSourceIOSImpl::SendResponseOnIOThread(
    int request_id,
    scoped_refptr<base::RefCountedMemory> bytes) {
  DCHECK_CURRENTLY_ON_WEB_THREAD(web::WebThread::IO);
  if (backend_)
    backend_->DataAvailable(request_id, bytes.get());
}

}  // namespace web


text:
<?php

namespace Symfony\Tests\Component\Console\Input;

use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class ArgvInputTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $_SERVER['argv'] = array('cli.php', 'foo');
        $input = new TestInput();
        $this->assertEquals(array('foo'), $input->getTokens(), '__construct() automatically get its input from the argv server variable');
    }

    public function testParser()
    {
        $input = new TestInput(array('cli.php', 'foo'));
        $input->bind(new InputDefinition(array(new InputArgument('name'))));
        $this->assertEquals(array('name' => 'foo'), $input->getArguments(), '->parse() parses required arguments');

        $input->bind(new InputDefinition(array(new InputArgument('name'))));
        $this->assertEquals(array('name' => 'foo'), $input->getArguments(), '->parse() is stateless');

        $input = new TestInput(array('cli.php', '--foo'));
        $input->bind(new InputDefinition(array(new InputOption('foo'))));
        $this->assertEquals(array('foo' => true), $input->getOptions(), '->parse() parses long options without a value');

        $input = new TestInput(array('cli.php', '--foo=bar'));
        $input->bind(new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED))));
        $this->assertEquals(array('foo' => 'bar'), $input->getOptions(), '->parse() parses long options with a required value (with a = separator)');

        $input = new TestInput(array('cli.php', '--foo', 'bar'));
        $input->bind(new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED))));
        $this->assertEquals(array('foo' => 'bar'), $input->getOptions(), '->parse() parses long options with a required value (with a space separator)');

        try {
            $input = new TestInput(array('cli.php', '--foo'));
            $input->bind(new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED))));
            $this->fail('->parse() throws a \RuntimeException if no value is passed to an option when it is required');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\RuntimeException', $e, '->parse() throws a \RuntimeException if no value is passed to an option when it is required');
            $this->assertEquals('The "--foo" option requires a value.', $e->getMessage(), '->parse() throws a \RuntimeException if no value is passed to an option when it is required');
        }

        $input = new TestInput(array('cli.php', '-f'));
        $input->bind(new InputDefinition(array(new InputOption('foo', 'f'))));
        $this->assertEquals(array('foo' => true), $input->getOptions(), '->parse() parses short options without a value');

        $input = new TestInput(array('cli.php', '-fbar'));
        $input->bind(new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED))));
        $this->assertEquals(array('foo' => 'bar'), $input->getOptions(), '->parse() parses short options with a required value (with no separator)');

        $input = new TestInput(array('cli.php', '-f', 'bar'));
        $input->bind(new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED))));
        $this->assertEquals(array('foo' => 'bar'), $input->getOptions(), '->parse() parses short options with a required value (with a space separator)');

        $input = new TestInput(array('cli.php', '-f', '-b', 'foo'));
        $input->bind(new InputDefinition(array(new InputArgument('name'), new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputOption('bar', 'b'))));
        $this->assertEquals(array('foo' => null, 'bar' => true), $input->getOptions(), '->parse() parses short options with an optional value which is not present');

        try {
            $input = new TestInput(array('cli.php', '-f'));
            $input->bind(new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED))));
            $this->fail('->parse() throws a \RuntimeException if no value is passed to an option when it is required');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\RuntimeException', $e, '->parse() throws a \RuntimeException if no value is passed to an option when it is required');
            $this->assertEquals('The "--foo" option requires a value.', $e->getMessage(), '->parse() throws a \RuntimeException if no value is passed to an option when it is required');
        }

        try {
            $input = new TestInput(array('cli.php', '-ffoo'));
            $input->bind(new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_NONE))));
            $this->fail('->parse() throws a \RuntimeException if a value is passed to an option which does not take one');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\RuntimeException', $e, '->parse() throws a \RuntimeException if a value is passed to an option which does not take one');
            $this->assertEquals('The "-o" option does not exist.', $e->getMessage(), '->parse() throws a \RuntimeException if a value is passed to an option which does not take one');
        }

        try {
            $input = new TestInput(array('cli.php', 'foo', 'bar'));
            $input->bind(new InputDefinition());
            $this->fail('->parse() throws a \RuntimeException if too many arguments are passed');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\RuntimeException', $e, '->parse() throws a \RuntimeException if too many arguments are passed');
            $this->assertEquals('Too many arguments.', $e->getMessage(), '->parse() throws a \RuntimeException if too many arguments are passed');
        }

        try {
            $input = new TestInput(array('cli.php', '--foo'));
            $input->bind(new InputDefinition());
            $this->fail('->parse() throws a \RuntimeException if an unknown long option is passed');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\RuntimeException', $e, '->parse() throws a \RuntimeException if an unknown long option is passed');
            $this->assertEquals('The "--foo" option does not exist.', $e->getMessage(), '->parse() throws a \RuntimeException if an unknown long option is passed');
        }

        try {
            $input = new TestInput(array('cli.php', '-f'));
            $input->bind(new InputDefinition());
            $this->fail('->parse() throws a \RuntimeException if an unknown short option is passed');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\RuntimeException', $e, '->parse() throws a \RuntimeException if an unknown short option is passed');
            $this->assertEquals('The "-f" option does not exist.', $e->getMessage(), '->parse() throws a \RuntimeException if an unknown short option is passed');
        }

        $input = new TestInput(array('cli.php', '-fb'));
        $input->bind(new InputDefinition(array(new InputOption('foo', 'f'), new InputOption('bar', 'b'))));
        $this->assertEquals(array('foo' => true, 'bar' => true), $input->getOptions(), '->parse() parses short options when they are aggregated as a single one');

        $input = new TestInput(array('cli.php', '-fb', 'bar'));
        $input->bind(new InputDefinition(array(new InputOption('foo', 'f'), new InputOption('bar', 'b', InputOption::VALUE_REQUIRED))));
        $this->assertEquals(array('foo' => true, 'bar' => 'bar'), $input->getOptions(), '->parse() parses short options when they are aggregated as a single one and the last one has a required value');

        $input = new TestInput(array('cli.php', '-fb', 'bar'));
        $input->bind(new InputDefinition(array(new InputOption('foo', 'f'), new InputOption('bar', 'b', InputOption::VALUE_OPTIONAL))));
        $this->assertEquals(array('foo' => true, 'bar' => 'bar'), $input->getOptions(), '->parse() parses short options when they are aggregated as a single one and the last one has an optional value');

        $input = new TestInput(array('cli.php', '-fbbar'));
        $input->bind(new InputDefinition(array(new InputOption('foo', 'f'), new InputOption('bar', 'b', InputOption::VALUE_OPTIONAL))));
        $this->assertEquals(array('foo' => true, 'bar' => 'bar'), $input->getOptions(), '->parse() parses short options when they are aggregated as a single one and the last one has an optional value with no separator');

        $input = new TestInput(array('cli.php', '-fbbar'));
        $input->bind(new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputOption('bar', 'b', InputOption::VALUE_OPTIONAL))));
        $this->assertEquals(array('foo' => 'bbar', 'bar' => null), $input->getOptions(), '->parse() parses short options when they are aggregated as a single one and one of them takes a value');
    }

    public function testGetFirstArgument()
    {
        $input = new TestInput(array('cli.php', '-fbbar'));
        $this->assertEquals('', $input->getFirstArgument(), '->getFirstArgument() returns the first argument from the raw input');

        $input = new TestInput(array('cli.php', '-fbbar', 'foo'));
        $this->assertEquals('foo', $input->getFirstArgument(), '->getFirstArgument() returns the first argument from the raw input');
    }

    public function testHasParameterOption()
    {
        $input = new TestInput(array('cli.php', '-f', 'foo'));
        $this->assertTrue($input->hasParameterOption('-f'), '->hasParameterOption() returns true if the given short option is in the raw input');

        $input = new TestInput(array('cli.php', '--foo', 'foo'));
        $this->assertTrue($input->hasParameterOption('--foo'), '->hasParameterOption() returns true if the given short option is in the raw input');

        $input = new TestInput(array('cli.php', 'foo'));
        $this->assertFalse($input->hasParameterOption('--foo'), '->hasParameterOption() returns false if the given short option is not in the raw input');
    }
}

class TestInput extends ArgvInput
{
    public function getTokens()
    {
        return $this->tokens;
    }
}