text:
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;

using SharpDX.Toolkit.Content;
using SharpDX.Toolkit.Graphics;

namespace SharpDX.Toolkit
{
    /// <summary>
    /// Base class for a <see cref="GameSystem"/> component.
    /// </summary>
    /// <remarks>
    /// A <see cref="GameSystem"/> component can be used to
    /// </remarks>
    public class GameSystem : Component, IGameSystem, IUpdateable, IDrawable, IContentable
    {
        private readonly DisposeCollector contentCollector = new DisposeCollector();
        private readonly IServiceRegistry registry;
        private int drawOrder;
        private bool enabled;
        private Game game;
        private int updateOrder;
        private bool visible;
        private IContentManager contentManager;
        private IGraphicsDeviceService graphicsDeviceService;

        /// <summary>
        /// Initializes a new instance of the <see cref="GameSystem" /> class.
        /// </summary>
        /// <param name="registry">The registry.</param>
        public GameSystem(IServiceRegistry registry)
        {
            if(registry == null) throw new ArgumentNullException("registry");
            this.registry = registry;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="GameSystem" /> class.
        /// </summary>
        /// <param name="game">The game.</param>
        public GameSystem(Game game)
        {
            if(game == null) throw new ArgumentNullException("game");
            this.game = game;
            this.registry = game.Services;
        }

        /// <summary>
        /// Gets the <see cref="Game"/> associated with this <see cref="GameSystem"/>. This value can be null in a mock environment.
        /// </summary>
        /// <value>The game.</value>
        public Game Game
        {
            get { return game; }
        }

        /// <summary>
        /// Gets the services registry.
        /// </summary>
        /// <value>The services registry.</value>
        public IServiceRegistry Services
        {
            get
            {
                return registry;
            }
        }

        /// <summary>
        /// Gets the content manager.
        /// </summary>
        /// <value>The content.</value>
        protected IContentManager Content
        {
            get
            {
                return contentManager;
            }
        }

        /// <summary>
        /// Gets the graphics device.
        /// </summary>
        /// <value>The graphics device.</value>
        protected GraphicsDevice GraphicsDevice
        {
            get
            {
                return graphicsDeviceService != null ? graphicsDeviceService.GraphicsDevice : null;
            }
        }

        #region IDrawable Members

        public event EventHandler<EventArgs> DrawOrderChanged;

        public event EventHandler<EventArgs> VisibleChanged;

        public virtual bool BeginDraw()
        {
            return true;
        }

        public virtual void Draw(GameTime gameTime)
        {
        }

        public virtual void EndDraw()
        {
        }

        public bool Visible
        {
            get { return visible; }
            set
            {
                if (visible != value)
                {
                    visible = value;
                    OnVisibleChanged(EventArgs.Empty);
                }
            }
        }

        public int DrawOrder
        {
            get { return drawOrder; }
            set
            {
                if (drawOrder != value)
                {
                    drawOrder = value;
                    OnDrawOrderChanged(this, EventArgs.Empty);
                }
            }
        }

        #endregion

        #region IGameSystem Members

        public virtual void Initialize()
        {
            // Gets the Content Manager
            contentManager = (IContentManager)registry.GetService(typeof(IContentManager));

            // Gets the graphics device service
            graphicsDeviceService = (IGraphicsDeviceService)registry.GetService(typeof(IGraphicsDeviceService));
        }

        #endregion

        #region IUpdateable Members

        public event EventHandler<EventArgs> EnabledChanged;

        public event EventHandler<EventArgs> UpdateOrderChanged;

        public virtual void Update(GameTime gameTime)
        {
        }

        public bool Enabled
        {
            get { return enabled; }
            set
            {
                if (enabled != value)
                {
                    enabled = value;
                    OnEnabledChanged(EventArgs.Empty);
                }
            }
        }

        public int UpdateOrder
        {
            get { return updateOrder; }
            set
            {
                if (updateOrder != value)
                {
                    updateOrder = value;
                    OnUpdateOrderChanged(this, EventArgs.Empty);
                }
            }
        }

        #endregion

        protected virtual void OnDrawOrderChanged(object source, EventArgs e)
        {
            EventHandler<EventArgs> handler = DrawOrderChanged;
            if (handler != null) handler(source, e);
        }

        private void OnVisibleChanged(EventArgs e)
        {
            EventHandler<EventArgs> handler = VisibleChanged;
            if (handler != null) handler(this, e);
        }

        private void OnEnabledChanged(EventArgs e)
        {
            EventHandler<EventArgs> handler = EnabledChanged;
            if (handler != null) handler(this, e);
        }

        protected virtual void OnUpdateOrderChanged(object source, EventArgs e)
        {
            EventHandler<EventArgs> handler = UpdateOrderChanged;
            if (handler != null) handler(source, e);
        }

        #region Implementation of IContentable

        void IContentable.LoadContent()
        {
            LoadContent();
        }

        void IContentable.UnloadContent()
        {
            contentCollector.DisposeAndClear();

            UnloadContent();
        }

        protected virtual void LoadContent()
        {
        }

        protected virtual void UnloadContent()
        {
        }

        #endregion

        /// <summary>
        /// Adds an object to be disposed automatically when <see cref="UnloadContent"/> is called. See remarks.
        /// </summary>
        /// <typeparam name="T">Type of the object to dispose</typeparam>
        /// <param name="disposable">The disposable object.</param>
        /// <returns>The disposable object.</returns>
        /// <remarks>
        /// Use this method for any content that is not loaded through the <see cref="ContentManager"/>.
        /// </remarks>
        protected T ToDisposeContent<T>(T disposable) where T : IDisposable
        {
            return contentCollector.Collect(disposable);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

module.exports = function(app) {
	var users = require('../../app/controllers/users.server.controller');
	var predictions = require('../../app/controllers/predictions.server.controller');

	// Predictions Routes
	app.route('/predictions')
		.get(users.requiresLogin, predictions.list)
		.post(users.requiresLogin, predictions.create);

	app.route('/predictions/:fixutreId')
		.get(users.requiresLogin, predictions.read)
		.put(users.requiresLogin, predictions.hasAuthorization, predictions.update)
		.delete(users.requiresLogin, predictions.hasAuthorization, predictions.delete);

	//app.route('/predictions/fixture/:fixutreId')
	//	.get(predictions.readFixture);

	// Finish by binding the Prediction middleware
	//app.param('predictionId', predictions.predictionByID);
	app.param('fixutreId', predictions.predictionByFixture);
};


text:
NSString * const ASTransitionContextFromLayoutKey = @"org.asyncdisplaykit.ASTransitionContextFromLayoutKey";
NSString * const ASTransitionContextToLayoutKey = @"org.asyncdisplaykit.ASTransitionContextToLayoutKey";

@interface _ASTransitionContext ()

@property (weak, nonatomic) id<_ASTransitionContextLayoutDelegate> layoutDelegate;
@property (weak, nonatomic) id<_ASTransitionContextCompletionDelegate> completionDelegate;

@end

@implementation _ASTransitionContext

- (instancetype)initWithAnimation:(BOOL)animated
                     layoutDelegate:(id<_ASTransitionContextLayoutDelegate>)layoutDelegate
                 completionDelegate:(id<_ASTransitionContextCompletionDelegate>)completionDelegate
{
  self = [super init];
  if (self) {
    _animated = animated;
    _layoutDelegate = layoutDelegate;
    _completionDelegate = completionDelegate;
  }
  return self;
}

#pragma mark - ASContextTransitioning Protocol Implementation

- (ASLayout *)layoutForKey:(NSString *)key
{
  return [_layoutDelegate transitionContext:self layoutForKey:key];
}

- (ASSizeRange)constrainedSizeForKey:(NSString *)key
{
  return [_layoutDelegate transitionContext:self constrainedSizeForKey:key];
}

- (CGRect)initialFrameForNode:(ASDisplayNode *)node
{
  for (ASDisplayNode *subnode in [_layoutDelegate currentSubnodesWithTransitionContext:self]) {
    if (node == subnode) {
      return node.frame;
    }
  }
  return CGRectZero;
}

- (CGRect)finalFrameForNode:(ASDisplayNode *)node
{
  for (ASLayout *layout in [self layoutForKey:ASTransitionContextToLayoutKey].sublayouts) {
    if (layout.layoutableObject == node) {
      return [layout frame];
    }
  }
  return CGRectZero;
}

- (NSArray<ASDisplayNode *> *)subnodesForKey:(NSString *)key
{
  NSMutableArray<ASDisplayNode *> *subnodes = [NSMutableArray array];
  for (ASLayout *sublayout in [self layoutForKey:key].immediateSublayouts) {
    [subnodes addObject:(ASDisplayNode *)sublayout.layoutableObject];
  }
  return subnodes;
}

- (NSArray<ASDisplayNode *> *)insertedSubnodes
{
  return [_layoutDelegate insertedSubnodesWithTransitionContext:self];
}

- (NSArray<ASDisplayNode *> *)removedSubnodes
{
  return [_layoutDelegate removedSubnodesWithTransitionContext:self];
}

- (void)completeTransition:(BOOL)didComplete
{
  [_completionDelegate transitionContext:self didComplete:didComplete];
}

@end


text:
package com.sxc.doctorstrangeupdater;

/**
 * Created by jimmydaddy on 2017/4/11.
 */

import java.io.File;
import java.net.URL;
import java.util.*;

import com.facebook.react.bridge.ReadableMap;

public class DownloadParams {
    public interface OnTaskCompleted {
        void onTaskCompleted(DownloadResult res);
    }

    public interface OnDownloadBegin {
        void onDownloadBegin(int statusCode, int contentLength, Map<String, String> headers);
    }

    public interface OnDownloadProgress {
        void onDownloadProgress(int contentLength, int bytesWritten);
    }

    public URL src;
    public File dest;
    public ReadableMap headers;
    public float progressDivider;
    public OnTaskCompleted onTaskCompleted;
    public OnDownloadBegin onDownloadBegin;
    public OnDownloadProgress onDownloadProgress;
}


text:
<?php
namespace TonyPiper\TimeLog\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Created by PhpStorm.
 * User: tpiper
 * Date: 14/03/2014
 * Time: 08:45
 */
class BasicReportCommand extends ReportCommand
{
    public function configure()
    {
        $this->setName('report:basic')
            ->setDescription('Generate a basic report');

        $this->addDateOption();
        $this->addSortOrderOption();
    }

    /**
     * @param  InputInterface            $input
     * @param  OutputInterface           $output
     * @throws \InvalidArgumentException
     * @return int|null|void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $activities = $this->getActivityRepository()->findActivities(
            $input->getOption('date')
        );

        $report = $this->getReportBuilder()->render(
            $activities,
            $input->getOption('sortOrder')
        );

        $output->writeln($report);
    }
}


text:
package com.training.salestaxes.items;

public class Book extends Product
{
	public Book(String name, double price)
	{
		super(name, price);
	}

	public Book(String name, double price, boolean imported)
	{
		super(name, price, imported);
	}

	@Override
	public boolean isExemptFromTaxes()
	{
		return true;
	}
}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}

{-|
    Module      : Query
    Description : SODA Query Builders
    Copyright   : (c) Steven W
    License     : MIT
    Maintainer  : Steven W <StevenW.Info@gmail.com>
    Stability   : Unstable

Elements which make SoQL and other parts of identifying what data you want easier.
-}

module Query
    (
    -- * Query Clause Pieces
    NonNegative
    , Filter (Filter)
    , ($=)
    , Select (..)
    , Where (Where)
    , Sorting (ASC, DESC)
    , Order (Order)
    , Group (Group)
    , Having (Having)
    -- * Query and related functions
    , Query (..)
    , emptyQuery
    , queryToString
    , queryToParam
    ) where

import Data.Aeson ((.:))
import Data.Aeson
import Data.Aeson.Types
import qualified Data.Vector as V
import qualified Data.HashMap.Strict as HM
import Data.List
import Data.Time.Calendar
import Data.Time.Clock
import Datatypes
import SodaFunctions

import Debug.Trace

{-
#Notes:
 - The toParam stuff could be part of a typeclass.
 -
 - I have the column type, but I suppose we could have aliases which aren't columns, but aren't concrete values.
 -}

-- |Obviously completely untrue, but it's currently being used to keep track of where we want it to be true.
type NonNegative = Int

-- |The type of a simple filter query part.
data Filter where
    Filter :: (SodaType a, SodaExpr m) => (Column a) -> (m a) -> Filter

-- |A little utility infix operator which can be used to make creating queries look a little more like a natural SODA query.
infix 2 $=
($=) :: (SodaType a, SodaExpr m) => (Column a) -> (m a) -> Filter
($=) = Filter

-- |The type of the $select query part.
data Select where
    Select :: (SodaExpr m, SodaType a) => m a -> Select
    Alias  :: (SodaExpr m, SodaType a) => m a -> String -> Select

-- |Used with the Order type to indicate if the order of a column should be ascending or descending.
data Sorting = ASC | DESC

-- Could possibly be confused with Ord class.
-- |The type of the $order query part.
data Order where
    Order :: (SodaType a) => Column a -> Sorting -> Order

-- Check at runtime for Nothing/null as a literal value, and to make sure there aren't any aggregates.
-- |The type of the $where query part.
-- Where shouldn't be passed a literal null or have any SodaAgg within a compound type.
data Where where
    Where :: (SodaExpr m) => m Checkbox -> Where

-- |The type of the $having query part. This section of the query is similar to $where in that it acts like a filter, but it works with aggregate functions which $where doesn't. That restriction isn't encoded into this library yet though.
data Having where
    Having :: (SodaExpr m) => m Checkbox -> Having

-- Possibly confusion with the mathematical concept of a group
-- |The type of the $group query part.
data Group where
    Group :: SodaType sodatype => Column sodatype -> Group

{-
limit :: Int -> Maybe Query
limit int
    | int < 0 = Nothing
    | otherwise = Just (Limit int)

offset :: Int -> Maybe Query
offset int
    | int < 0 = Nothing
    | otherwise = Just (Offset int)
-}

-- Need to account for negative limit, which doesn't make sense, somehow.
-- I think the type parameter makes more sense than an existential type, but we'll see. The type parameter sort of represents the return type I guess.
-- |The type of the Query itself.
-- The query is represented as a Haskell record type, and you can add to or modify a query made by the bindings by creating, adding to, and/or modifying a value of type Query.
data Query = Query { selects  :: Maybe [Select]
                   , filters  :: Maybe [Filter] -- Type with columns and contents
                   , wheres   :: Maybe Where -- Is the lowercase where allowed?
                   , orders   :: Maybe [Order]
                   , groups   :: Maybe [Group] -- Depends on the select clause. Also, might need an existential type.
                   , having   :: Maybe Having -- Depends on the group clause. Similar to where clause.
                   , limit    :: Maybe NonNegative
                   , offset   :: Maybe NonNegative
                   , search   :: Maybe String -- |$q parameter
                   , subquery :: Maybe Query -- |Doesn't currently actually do anything yet.
                   , bom      :: Maybe Bool
                   }

-- |A useful value since we're often building queries from nothing.
emptyQuery :: Query
emptyQuery = Query { filters  = Nothing
                   , selects  = Nothing
                   , wheres   = Nothing
                   , orders   = Nothing
                   , groups   = Nothing
                   , having   = Nothing
                   , limit    = Nothing
                   , offset   = Nothing
                   , search   = Nothing
                   , subquery = Nothing
                   , bom      = Nothing
                   }

-- I don't know if changing ifExists order would make it more performant
-- Need to change up the namings of things.
-- |Used for getting a query as part of a URL represented with a string. Not recommended to actually use, but provided for the URL string builder and just in case somebody wants it.
queryToString :: Query -> UrlParam
queryToString query = intercalate "&" $ map stringify (queryToParam query)
    where stringify (param, val) = param ++ "=" ++ val

-- Should possibly be hidden after being imported into Soda.hs.
-- |Creates the list of pairs of parameters and values that go into the URL.
queryToParam :: Query -> [(String, String)]
queryToParam query = filters' ++ selects' ++ wheres' ++ orders' ++ groups' ++ having'++ limit' ++ offset' ++ search' ++ bom'
    where filters' = ifExists filtersToParam $ filters query
          selects' = ifExists selectsToParam $ selects query
          wheres'  = ifExists wheresToParam  $ wheres  query
          groups'  = ifExists groupsToParam  $ groups  query
          having'  = ifExists havingToParam  $ having  query
          orders'  = ifExists ordersToParam  $ orders  query
          limit'   = ifExists limitToParam   $ limit   query
          offset'  = ifExists offsetToParam  $ offset  query
          search'  = ifExists searchToParam  $ search  query
          bom'     = ifExists bomToParam     $ bom     query
          ifExists f Nothing = []
          ifExists f (Just a)  = f a

-- subqueryToParam actually can't be a recursive call to queryToParam because subqueries are represented differently. Within the subquery I think you can make a recursive call though.

---
--ToParam functions for the query parts

filtersToParam :: [Filter] -> [(String, String)]
filtersToParam filters' = map filterToParam filters'
    where filterToParam (Filter col val) = ((toUrlParam col), (toUrlParam val))

selectsToParam :: [Select] -> [(String, String)]
selectsToParam selects' = [("$select", intercalate ", " $ map selectToParam selects')]
    where selectToParam (Select col) = toUrlParam col
          selectToParam (Alias col alias) = (toUrlParam col) ++ " AS " ++ alias

wheresToParam :: Where -> [(String, String)]
wheresToParam (Where clause) = [("$where", toUrlParam clause)]

ordersToParam :: [Order] -> [(String, String)]
ordersToParam orders' = [("$order", intercalate ", " $ map orderToParam orders')]
    where orderToParam (Order col sort) = toUrlParam col ++ " " ++ sortParam sort
          sortParam ASC  = "ASC"
          sortParam DESC = "DESC"

groupsToParam :: [Group] -> [(String, String)]
groupsToParam groups' = [("$group", intercalate ", " $ map groupToParam groups')]
    where groupToParam (Group col) = toUrlParam col

havingToParam :: Having -> [(String, String)]
havingToParam (Having clause) = [("$having", toUrlParam clause)]

limitToParam :: NonNegative -> [(String, String)]
limitToParam limit' = [("$limit", show limit')]

offsetToParam :: NonNegative -> [(String, String)]
offsetToParam offset' = [("$offset", show offset')]

searchToParam :: String -> [(String, String)]
searchToParam search' = [("$q", search')]

bomToParam :: Bool -> [(String, String)]
bomToParam True = [("$$bom", "true")]
bomToParam False = [("$$bom", "false")]

-- Will probably move below to somewhere else.
--
-- Might have to import Data.Aeson.Instances

instance (SodaType a, FromJSON a) => FromJSON (Expr a) where
    parseJSON x = do
        val <- (parseJSON x) :: Parser a
        return (Expr (SodaVal val))

instance FromJSON Money where
    parseJSON a = do
        b <- (parseJSON a) :: Parser String
        return (Money (read b :: Double))

instance FromJSON SodaNum where
    parseJSON a = do
        b <- (parseJSON a) :: Parser String
        return (SodaNum (read b :: Double))

parsePoint :: Value -> Parser Point
parsePoint (Array arr) = do
    long <- (parseJSON $ (arr V.! 0)) :: Parser Double
    lat <- (parseJSON $ (arr V.! 1)) :: Parser Double
    return (Point { longitude = long, latitude = lat })
parsePoint _ = fail ("coordinates was not an array as expected")

-- Use the type parameter to add some extra checking maybe
instance FromJSON Point where
    parseJSON = withObject "Point" $ \o ->
        case HM.lookup "coordinates" o of
            Nothing -> fail ("key coordinates not present")
            Just val -> parsePoint val

-- What the JSON representation of Location is needs to be determined before writing FromJSON.

instance FromJSON Line where
    parseJSON json = do
        val <- (parseJSON json) :: Parser [Point]
        return (Line val)

instance FromJSON Polygon where
    parseJSON json = do
        val <- (parseJSON json) :: Parser [[Point]]
        return (Polygon val)


text:
#ifndef IRCD_CLASS_H
#define IRCD_CLASS_H

struct class {
    char    name[32];                /* name of the class */
    int            freq;                /* ping-timeout frequency in seconds */
    int            max;                /* maximum clients in this class */
    int            flood;                /* maximum flood weight in this class */
    int            clients;                /* current number of clients in this class
                                   (may be > max) */
    int            sendq;                /* maximum number of sendqueue items */
    char    *default_mode;        /* default modes for users in this class */
    struct message_set *mset;        /* the suggested message set, by default this
                                   is the default set */
    struct privilege_set *pset; /* the suggested privilege set, by default
                                   this is the default set */
    char    *mdext;                /* extended data */
    conf_list_t *conf;                /* the conf this class came from */
    int            dead;                /* this is set if the class should be deleted
                                   at 0 clients */

    LIST_ENTRY(class) lp;
};

class_t *create_class(char *);
void destroy_class(class_t *);
void add_to_class(class_t *, connection_t *);
void del_from_class(connection_t *);
class_t *find_class(char *);

char **class_mdext_iter(char **);
#endif
/* vi:set ts=8 sts=4 sw=4 tw=76 et: */


text:
namespace content {

// Tests playback and seeking of an audio or video file over file or http based
// on a test parameter.  Test starts with playback, then, after X seconds or the
// ended event fires, seeks near end of file; see player.html for details.  The
// test completes when either the last 'ended' or an 'error' event fires.
class MediaTest : public testing::WithParamInterface<bool>,
                  public ContentBrowserTest {
 public:
  // Play specified audio over http:// or file:// depending on |http| setting.
  void PlayAudio(const char* media_file, bool http) {
    PlayMedia("audio", media_file, http);
  }

  // Play specified video over http:// or file:// depending on |http| setting.
  void PlayVideo(const char* media_file, bool http) {
    PlayMedia("video", media_file, http);
  }

  // Run specified color format test with the expected result.
  void RunColorFormatTest(const char* media_file, const char* expected) {
    FilePath test_file_path = GetTestFilePath("media", "blackwhite.html");
    RunTest(GetFileUrlWithQuery(test_file_path, media_file), expected);
  }

 private:
  void PlayMedia(const char* tag, const char* media_file, bool http) {
    GURL gurl;

    if (http) {
      if (!test_server()->Start()) {
        ADD_FAILURE() << "Failed to start test server";
        return;
      }

      gurl = test_server()->GetURL(
          base::StringPrintf("files/media/player.html?%s=%s", tag, media_file));
    } else {
      FilePath test_file_path = GetTestFilePath("media", "player.html");
      gurl = GetFileUrlWithQuery(
          test_file_path, base::StringPrintf("%s=%s", tag, media_file));
    }

    RunTest(gurl, "ENDED");
  }

  void RunTest(const GURL& gurl, const char* expected) {
    const string16 kExpected = ASCIIToUTF16(expected);
    const string16 kEnded = ASCIIToUTF16("ENDED");
    const string16 kError = ASCIIToUTF16("ERROR");
    const string16 kFailed = ASCIIToUTF16("FAILED");
    DCHECK(kExpected == kEnded || kExpected == kError || kExpected == kFailed)
        << kExpected;

    TitleWatcher title_watcher(shell()->web_contents(), kEnded);
    title_watcher.AlsoWaitForTitle(kFailed);
    title_watcher.AlsoWaitForTitle(kError);

    NavigateToURL(shell(), gurl);

    string16 final_title = title_watcher.WaitAndGetTitle();
    EXPECT_EQ(kExpected, final_title);
  }
};

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearTheora) {
  PlayVideo("bear.ogv", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearSilentTheora) {
  PlayVideo("bear_silent.ogv", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWebm) {
  PlayVideo("bear.webm", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearSilentWebm) {
  PlayVideo("bear_silent.webm", GetParam());
}

#if defined(GOOGLE_CHROME_BUILD) || defined(USE_PROPRIETARY_CODECS)
IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearMp4) {
  PlayVideo("bear.mp4", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearSilentMp4) {
  PlayVideo("bear_silent.mp4", GetParam());
}

// While we support the big endian (be) PCM codecs on Chromium, Quicktime seems
// to be the only creator of this format and only for .mov files.
// TODO(dalecurtis/ihf): Find or create some .wav test cases for "be" format.
IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearMovPcmS16be) {
  PlayVideo("bear_pcm_s16be.mov", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearMovPcmS24be) {
  PlayVideo("bear_pcm_s24be.mov", GetParam());
}
#endif

#if defined(OS_CHROMEOS)
#if defined(GOOGLE_CHROME_BUILD) || defined(USE_PROPRIETARY_CODECS)
IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearAviMp3Mpeg4) {
  PlayVideo("bear_mpeg4_mp3.avi", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearAviMp3Divx) {
  PlayVideo("bear_divx_mp3.avi", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBear3gpAacH264) {
  PlayVideo("bear_h264_aac.3gp", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBear3gpAmrnbMpeg4) {
  PlayVideo("bear_mpeg4_amrnb.3gp", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWavGsmms) {
  PlayAudio("bear_gsm_ms.wav", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWavMulaw) {
  PlayAudio("bear_mulaw.wav", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearFlac) {
  PlayAudio("bear.flac", GetParam());
}
#endif
#endif

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWavPcm) {
  PlayAudio("bear_pcm.wav", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWavPcm3kHz) {
  PlayAudio("bear_3kHz.wav", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWavPcm192kHz) {
  PlayAudio("bear_192kHz.wav", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoTulipWebm) {
  PlayVideo("tulip2.webm", GetParam());
}

INSTANTIATE_TEST_CASE_P(File, MediaTest, ::testing::Values(false));
INSTANTIATE_TEST_CASE_P(Http, MediaTest, ::testing::Values(true));

class MediaLayoutTest : public InProcessBrowserLayoutTest {
 protected:
  MediaLayoutTest() : InProcessBrowserLayoutTest(
      FilePath(), FilePath().AppendASCII("media")) {
  }
  virtual ~MediaLayoutTest() {}
};

// Each browser test can only correspond to a single layout test, otherwise the
// 45 second timeout per test is not long enough for N tests on debug/asan/etc
// builds.

IN_PROC_BROWSER_TEST_F(MediaLayoutTest, VideoAutoplayTest) {
  RunLayoutTest("video-autoplay.html");
}

IN_PROC_BROWSER_TEST_F(MediaLayoutTest, VideoLoopTest) {
  RunLayoutTest("video-loop.html");
}

IN_PROC_BROWSER_TEST_F(MediaLayoutTest, VideoNoAutoplayTest) {
  RunLayoutTest("video-no-autoplay.html");
}

IN_PROC_BROWSER_TEST_F(MediaTest, Yuv420pTheora) {
  RunColorFormatTest("yuv420p.ogv", "ENDED");
}

IN_PROC_BROWSER_TEST_F(MediaTest, Yuv422pTheora) {
  RunColorFormatTest("yuv422p.ogv", "ENDED");
}

IN_PROC_BROWSER_TEST_F(MediaTest, Yuv444pTheora) {
  // TODO(scherkus): Support YUV444 http://crbug.com/104711
  RunColorFormatTest("yuv424p.ogv", "ERROR");
}

IN_PROC_BROWSER_TEST_F(MediaTest, Yuv420pVp8) {
  RunColorFormatTest("yuv420p.webm", "ENDED");
}

#if defined(GOOGLE_CHROME_BUILD) || defined(USE_PROPRIETARY_CODECS)
IN_PROC_BROWSER_TEST_F(MediaTest, Yuv420pH264) {
  RunColorFormatTest("yuv420p.mp4", "ENDED");
}

IN_PROC_BROWSER_TEST_F(MediaTest, Yuvj420pH264) {
  RunColorFormatTest("yuvj420p.mp4", "ENDED");
}

IN_PROC_BROWSER_TEST_F(MediaTest, Yuv422pH264) {
  RunColorFormatTest("yuv422p.mp4", "ENDED");
}

IN_PROC_BROWSER_TEST_F(MediaTest, Yuv444pH264) {
  // TODO(scherkus): Support YUV444 http://crbug.com/104711
  RunColorFormatTest("yuv444p.mp4", "ERROR");
}

#if defined(OS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(MediaTest, Yuv420pMpeg4) {
  RunColorFormatTest("yuv420p.avi", "ENDED");
}
#endif
#endif

}  // namespace content


text:
package consumertest // import "go.opentelemetry.io/collector/consumer/consumertest"

import (
	"context"
	"sync"

	"go.opentelemetry.io/collector/consumer"
	"go.opentelemetry.io/collector/pdata/plog"
	"go.opentelemetry.io/collector/pdata/pmetric"
	"go.opentelemetry.io/collector/pdata/ptrace"
)

// TracesSink is a consumer.Traces that acts like a sink that
// stores all traces and allows querying them for testing.
type TracesSink struct {
	nonMutatingConsumer
	mu        sync.Mutex
	traces    []ptrace.Traces
	spanCount int
}

var _ consumer.Traces = (*TracesSink)(nil)

// ConsumeTraces stores traces to this sink.
func (ste *TracesSink) ConsumeTraces(_ context.Context, td ptrace.Traces) error {
	ste.mu.Lock()
	defer ste.mu.Unlock()

	ste.traces = append(ste.traces, td)
	ste.spanCount += td.SpanCount()

	return nil
}

// AllTraces returns the traces stored by this sink since last Reset.
func (ste *TracesSink) AllTraces() []ptrace.Traces {
	ste.mu.Lock()
	defer ste.mu.Unlock()

	copyTraces := make([]ptrace.Traces, len(ste.traces))
	copy(copyTraces, ste.traces)
	return copyTraces
}

// SpanCount returns the number of spans sent to this sink.
func (ste *TracesSink) SpanCount() int {
	ste.mu.Lock()
	defer ste.mu.Unlock()
	return ste.spanCount
}

// Reset deletes any stored data.
func (ste *TracesSink) Reset() {
	ste.mu.Lock()
	defer ste.mu.Unlock()

	ste.traces = nil
	ste.spanCount = 0
}

// MetricsSink is a consumer.Metrics that acts like a sink that
// stores all metrics and allows querying them for testing.
type MetricsSink struct {
	nonMutatingConsumer
	mu             sync.Mutex
	metrics        []pmetric.Metrics
	dataPointCount int
}

var _ consumer.Metrics = (*MetricsSink)(nil)

// ConsumeMetrics stores metrics to this sink.
func (sme *MetricsSink) ConsumeMetrics(_ context.Context, md pmetric.Metrics) error {
	sme.mu.Lock()
	defer sme.mu.Unlock()

	sme.metrics = append(sme.metrics, md)
	sme.dataPointCount += md.DataPointCount()

	return nil
}

// AllMetrics returns the metrics stored by this sink since last Reset.
func (sme *MetricsSink) AllMetrics() []pmetric.Metrics {
	sme.mu.Lock()
	defer sme.mu.Unlock()

	copyMetrics := make([]pmetric.Metrics, len(sme.metrics))
	copy(copyMetrics, sme.metrics)
	return copyMetrics
}

// DataPointCount returns the number of metrics stored by this sink since last Reset.
func (sme *MetricsSink) DataPointCount() int {
	sme.mu.Lock()
	defer sme.mu.Unlock()
	return sme.dataPointCount
}

// Reset deletes any stored data.
func (sme *MetricsSink) Reset() {
	sme.mu.Lock()
	defer sme.mu.Unlock()

	sme.metrics = nil
	sme.dataPointCount = 0
}

// LogsSink is a consumer.Logs that acts like a sink that
// stores all logs and allows querying them for testing.
type LogsSink struct {
	nonMutatingConsumer
	mu             sync.Mutex
	logs           []plog.Logs
	logRecordCount int
}

var _ consumer.Logs = (*LogsSink)(nil)

// ConsumeLogs stores logs to this sink.
func (sle *LogsSink) ConsumeLogs(_ context.Context, ld plog.Logs) error {
	sle.mu.Lock()
	defer sle.mu.Unlock()

	sle.logs = append(sle.logs, ld)
	sle.logRecordCount += ld.LogRecordCount()

	return nil
}

// AllLogs returns the logs stored by this sink since last Reset.
func (sle *LogsSink) AllLogs() []plog.Logs {
	sle.mu.Lock()
	defer sle.mu.Unlock()

	copyLogs := make([]plog.Logs, len(sle.logs))
	copy(copyLogs, sle.logs)
	return copyLogs
}

// LogRecordCount returns the number of log records stored by this sink since last Reset.
func (sle *LogsSink) LogRecordCount() int {
	sle.mu.Lock()
	defer sle.mu.Unlock()
	return sle.logRecordCount
}

// Reset deletes any stored data.
func (sle *LogsSink) Reset() {
	sle.mu.Lock()
	defer sle.mu.Unlock()

	sle.logs = nil
	sle.logRecordCount = 0
}


text:
Hello
Goodbye
Unix


text:
<?php

namespace NetLicensing;

/**
 * PHP representation of the Product Service. See NetLicensingAPI for details:
 * https://netlicensing.io/wiki/product-services
 *
 * @package NetLicensing
 */
class ProductService
{
    /**
     * Creates new product with given properties.See NetLicensingAPI for details:
     * https://netlicensing.io/wiki/product-services#create-product
     *
     * determines the vendor on whose behalf the call is performed
     * @param \NetLicensing\Context $context
     *
     * non-null properties will be taken for the new object, null properties will either stay null, or will
     * be set to a default value, depending on property.
     * @param \NetLicensing\Product $product
     *
     * return the newly created product object
     * @return Product|null
     * @throws RestException
     * @throws \ErrorException
     */
    public static function create(Context $context, Product $product)
    {
        $response = NetLicensingService::getInstance()
            ->post($context, Constants::PRODUCT_ENDPOINT_PATH, $product->asPropertiesMap());

        $createdProduct = null;

        if (!empty($response->items->item[0])) {
            $createdProduct = ItemToProductConverter::convert($response->items->item[0]);
            $createdProduct->exists = true;
        }

        return $createdProduct;
    }

    /**
     * Gets product by its number.See NetLicensingAPI for details:
     * https://netlicensing.io/wiki/product-services#get-product
     *
     * determines the vendor on whose behalf the call is performed
     * @param \NetLicensing\Context $context
     *
     * the product number
     * @param string $number
     *
     * return the product object
     * @return Product|null
     * @throws MalformedArgumentsException
     * @throws RestException
     * @throws \ErrorException
     */
    public static function get(Context $context, $number)
    {
        CheckUtils::paramNotEmpty($number, Constants::NUMBER);

        $response = NetLicensingService::getInstance()
            ->get($context, Constants::PRODUCT_ENDPOINT_PATH . '/' . $number);

        $product = null;

        if (!empty($response->items->item[0])) {
            $product = ItemToProductConverter::convert($response->items->item[0]);
            $product->exists = true;
        }

        return $product;
    }

    /**
     * Returns products of a vendor.See NetLicensingAPI for details:
     * https://netlicensing.io/wiki/product-services#products-list
     *
     * determines the vendor on whose behalf the call is performed
     * @param \NetLicensing\Context $context
     *
     * reserved for the future use, must be omitted / set to NULL
     * @param string $filter
     *
     * array of product entities or empty array if nothing found.
     * @return Page
     * @throws RestException
     * @throws \ErrorException
     */
    public static function getList(Context $context, $filter = null)
    {
        $queryParams = (!is_null($filter)) ? [Constants::FILTER => $filter] : [];

        $response = NetLicensingService::getInstance()
            ->get($context, Constants::PRODUCT_ENDPOINT_PATH, $queryParams);

        $products = [];
        $pageNumber = !empty($response->items->pagenumber) ? $response->items->pagenumber : 0;
        $itemsNumber = !empty($response->items->itemsnumber) ? $response->items->itemsnumber : 0;
        $totalPages = !empty($response->items->totalpages) ? $response->items->totalpages : 0;
        $totalItems = !empty($response->items->totalitems) ? $response->items->totalitems : 0;

        if (!empty($response->items->item)) {
            foreach ($response->items->item as $item) {
                $product = ItemToProductConverter::convert($item);
                $product->exists = true;

                $products[] = $product;
            }
        }

        return new Page($products, $pageNumber, $itemsNumber, $totalPages, $totalItems);
    }

    /**
     * Updates product properties.See NetLicensingAPI for details:
     * https://netlicensing.io/wiki/product-services#update-product
     *
     * determines the vendor on whose behalf the call is performed
     * @param \NetLicensing\Context $context
     *
     * product number
     * @param string $number
     *
     * non-null properties will be updated to the provided values, null properties will stay unchanged.
     * @param \NetLicensing\Product $product
     *
     * updated product.
     * @return Product|null
     * @throws MalformedArgumentsException
     * @throws RestException
     * @throws \ErrorException
     */
    public static function update(Context $context, $number, Product $product)
    {
        CheckUtils::paramNotEmpty($number, Constants::NUMBER);

        $response = NetLicensingService::getInstance()
            ->post($context, Constants::PRODUCT_ENDPOINT_PATH . '/' . $number, $product->asPropertiesMap());

        $updatedProduct = null;

        if (!empty($response->items->item[0])) {
            $updatedProduct = ItemToProductConverter::convert($response->items->item[0]);
            $updatedProduct->exists = true;
        }

        return $updatedProduct;
    }

    /**
     * Deletes product.See NetLicensingAPI for details:
     * https://netlicensing.io/wiki/product-services#delete-product
     *
     * determines the vendor on whose behalf the call is performed
     * @param \NetLicensing\Context $context
     *
     * product number
     * @param string $number
     *
     * if true, any entities that depend on the one being deleted will be deleted too
     * @param bool $forceCascade
     *
     * @return bool
     * @throws RestException
     * @throws \ErrorException
     * @throws MalformedArgumentsException
     */
    public static function delete(Context $context, $number, $forceCascade = false)
    {
        CheckUtils::paramNotEmpty($number, Constants::NUMBER);

        $queryParams[Constants::CASCADE] = ((bool)$forceCascade) ? 'true' : 'false';

        NetLicensingService::getInstance()
            ->delete($context, Constants::PRODUCT_ENDPOINT_PATH . '/' . $number, $queryParams);
    }
}


text:
<?php

namespace Reporter;
use Reporter;

class ContentHtmlTest extends \PHPUnit_Framework_TestCase
{
	public function testResponseContains()
	{
		$resp = file_get_contents('tests/fixtures/resp1.txt');
		$respObject = new Response($resp);

		$this->assertTrue(Reporter\Content\Html::contains('Developer', $respObject));
		$this->assertFalse(Reporter\Content\Html::contains('foobar', $respObject));

		return $respObject;

	}

	public function testHtmlContains()
	{
		$resp = file_get_contents('tests/fixtures/resp2.txt');
		$respObject = new Response($resp);

		$this->assertTrue(Reporter\Content\Html::contains('Hello World', $respObject));
		$this->assertFalse(Reporter\Content\Html::contains('foobar', $respObject));

		return $respObject;
	}

	/**
     * @depends testResponseContains
     */
	public function testResponseDoesntContain($respObject)
	{
		$this->assertTrue(Reporter\Content\Html::doesntContain('foobar', $respObject));
		$this->assertFalse(Reporter\Content\Html::doesntContain('Developer', $respObject));
	}

	/**
     * @depends testHtmlContains
     */
	public function testHtmlDoesntContain($respObject)
	{
		$this->assertTrue(Reporter\Content\Html::doesntContain('foobar', $respObject));
		$this->assertFalse(Reporter\Content\Html::doesntContain('Hello World', $respObject));
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE gov_uscourts_docket SYSTEM "docket.dtd">
<gov_uscourts_docket>
  <nonce>itIkiv</nonce>
  <case_details>
    <court>txnd</court>
    <docket_num>3:11-cv-00002</docket_num>
    <case_name>Serious Bidness, LLC v. Does 1</case_name>
    <pacer_case_num>202294</pacer_case_num>
    <date_case_filed>2011-01-02</date_case_filed>
    <date_case_terminated>2011-02-28</date_case_terminated>
    <date_last_filing>2011-02-28</date_last_filing>
    <assigned_to>Judge Royal Furgeson</assigned_to>
    <case_cause>17:101 Copyright Infringement</case_cause>
    <nature_of_suit>820 Copyright</nature_of_suit>
    <jury_demand>None</jury_demand>
    <jurisdiction>Federal Question</jurisdiction>
  </case_details>
  <party_list>
    <party>
      <name>Serious Bidness, LLC</name>
      <type>Plaintiff</type>
      <extra_info>a Nevada Company</extra_info>
      <attorney_list>
        <attorney>
          <attorney_name>Evan F Stone</attorney_name>
          <contact>Law Offices of Evan Stone
624 W University Dr
Suite 386
Denton, TX 76201
469/248-5238
Email: evan@wolfe-stone.com</contact>
          <attorney_role>LEAD ATTORNEY
ATTORNEY TO BE NOTICED</attorney_role>
        </attorney>
      </attorney_list>
    </party>
    <party>
      <name>Does 1-109</name>
      <type>Defendant</type>
      <extra_info>TERMINATED: 02/10/2011</extra_info>
    </party>
    <party>
      <name>Doe 1</name>
      <type>Defendant</type>
    </party>
  </party_list>
  <document_list>
    <document doc_num="1" attachment_num="0">
      <pacer_doc_id>17705464613</pacer_doc_id>
      <pacer_de_seq_num>5</pacer_de_seq_num>
      <pacer_dm_id>5268201</pacer_dm_id>
      <date_filed>2011-01-02</date_filed>
      <date_entered>2011-01-02</date_entered>
      <long_desc>COMPLAINT against DOES 1-109 filed by Serious Bidness, LLC. Summons(es) not requested at this time. In each Notice of Electronic Filing, the judge assignment is indicated, and a link to the Judges Copy Requirements  is provided. The court reminds the filer that any required copy of this and future documents must be delivered to the judge, in the manner prescribed, within three business days of filing. (Filing fee $350; Receipt number 0539-3650207) Unless exempted, attorneys who are not admitted to practice in the Northern District of Texas should seek admission promptly. Forms and Instructions found at www.txnd.uscourts.gov, or by clicking here:  Attorney Information - Bar Membership (Attachments: # 1 Cover Sheet, # 2 Exhibit(s) List of Does) (Stone, Evan) (Entered: 01/02/2011)</long_desc>
      <short_desc>Complaint</short_desc>
      <upload_date>2011-01-06 18:14:07</upload_date>
      <available>1</available>
      <sha1>226ab07cadab161e91aa24c968ef0e25b58233af</sha1>
    </document>
    <document doc_num="1" attachment_num="1">
      <pacer_doc_id>17705464614</pacer_doc_id>
      <short_desc>Cover Sheet</short_desc>
    </document>
    <document doc_num="1" attachment_num="2">
      <pacer_doc_id>17705464615</pacer_doc_id>
      <short_desc>Exhibit(s) List of Does</short_desc>
      <upload_date>2011-01-12 21:45:06</upload_date>
      <available>1</available>
      <sha1>c89ca3071eab6b8b563b7e381c36eee46f5f7730</sha1>
    </document>
    <document doc_num="2" attachment_num="0">
      <pacer_doc_id>17705464618</pacer_doc_id>
      <pacer_de_seq_num>7</pacer_de_seq_num>
      <pacer_dm_id>5268204</pacer_dm_id>
      <date_filed>2011-01-02</date_filed>
      <date_entered>2011-01-02</date_entered>
      <long_desc>CERTIFICATE OF INTERESTED PERSONS/DISCLOSURE STATEMENT by Serious Bidness, LLC. (Stone, Evan) (Entered: 01/02/2011)</long_desc>
      <short_desc>Cert. Of Interested Persons/Disclosure Statement</short_desc>
    </document>
    <document doc_num="3" attachment_num="0">
      <pacer_de_seq_num>11</pacer_de_seq_num>
      <pacer_dm_id>5312516</pacer_dm_id>
      <date_filed>2011-01-26</date_filed>
      <date_entered>2011-01-27</date_entered>
      <long_desc>ORDER OF TRANSFER: Case reassigned to Judge Royal Furgeson for all further proceedings. Judge Ed Kinkeade no longer assigned to case. (Ordered by Judge Ed Kinkeade on 1/26/2011) (axm) (Entered: 01/27/2011)</long_desc>
      <short_desc>Order Reassigning Case</short_desc>
    </document>
    <document doc_num="4" attachment_num="0">
      <pacer_doc_id>17705513126</pacer_doc_id>
      <pacer_de_seq_num>14</pacer_de_seq_num>
      <pacer_dm_id>5312734</pacer_dm_id>
      <date_filed>2011-01-27</date_filed>
      <date_entered>2011-01-27</date_entered>
      <long_desc>MOTION for Discovery, MOTION to Expedite filed by Serious Bidness, LLC with Brief/Memorandum in Support. (Attachments: # 1 Exhibit(s) Memorandum of Points and Authorities, # 2 Declaration(s) Emile Morgan) (Stone, Evan) Modified on 2/8/2011 (mfw). (Entered: 01/27/2011)</long_desc>
      <short_desc>Motion for Discovery</short_desc>
    </document>
    <document doc_num="5" attachment_num="0">
      <pacer_de_seq_num>17</pacer_de_seq_num>
      <pacer_dm_id>5315628</pacer_dm_id>
      <date_filed>2011-01-28</date_filed>
      <date_entered>2011-01-28</date_entered>
      <long_desc>***VACATED per 6 ORDER***ORDER granting 4 Motion for Leave to take Discovery prior to Rule 26(f) Conference. (Ordered by Judge Royal Furgeson on 1/28/2011) (dnc) Modified on 2/8/2011 (mfw). (Entered: 01/28/2011)</long_desc>
      <short_desc>Order on Motion for Discovery</short_desc>
    </document>
    <document doc_num="6" attachment_num="0">
      <pacer_doc_id>17705530508</pacer_doc_id>
      <pacer_de_seq_num>20</pacer_de_seq_num>
      <pacer_dm_id>5328457</pacer_dm_id>
      <date_filed>2011-02-07</date_filed>
      <date_entered>2011-02-08</date_entered>
      <long_desc>ORDER VACATING THE COURT'S ORDER GRANTING PLAINTIFF'S MOTION FOR LEAVE TO TAKE DISCOVERY PRIOR TO RULE 26(1) CONFERENCE AND ORDER TO SHOW CAUSE: Show Cause Response due by 2/28/2011. Plaintiff is directed to serve a copy of this Order on each affected ISP. (Ordered by Judge Royal Furgeson on 2/7/2011) (twd) (Entered: 02/08/2011)</long_desc>
      <short_desc>Order to Show Cause</short_desc>
      <upload_date>2011-02-09 18:33:26</upload_date>
      <available>1</available>
      <sha1>1c16dd5814e8702106780d96f0020c7fe587e145</sha1>
    </document>
    <document doc_num="7" attachment_num="0">
      <pacer_doc_id>17705539094</pacer_doc_id>
      <pacer_de_seq_num>23</pacer_de_seq_num>
      <pacer_dm_id>5336446</pacer_dm_id>
      <date_filed>2011-02-10</date_filed>
      <date_entered>2011-02-14</date_entered>
      <long_desc>ORDER SEVERING DOES 2-109: All defendants except Doe 1 are SEVERED from this action; Within 30 days from the date of this order, Plaintiff may file individual complaints against those Does whom they wish to proceed. (Ordered by Judge Royal Furgeson on 2/10/2011) (twd) (Entered: 02/14/2011)</long_desc>
      <short_desc>Order</short_desc>
      <upload_date>2011-02-21 21:21:10</upload_date>
      <available>1</available>
      <sha1>5aa9e3cd113431019782287665108140cefaa391</sha1>
    </document>
    <document doc_num="8" attachment_num="0">
      <pacer_de_seq_num>25</pacer_de_seq_num>
      <pacer_dm_id>5361373</pacer_dm_id>
      <date_filed>2011-02-28</date_filed>
      <date_entered>2011-02-28</date_entered>
      <short_desc>Notice of Attorney Appearance</short_desc>
    </document>
    <document doc_num="9" attachment_num="0">
      <pacer_de_seq_num>29</pacer_de_seq_num>
      <pacer_dm_id>5361382</pacer_dm_id>
      <date_filed>2011-02-28</date_filed>
      <date_entered>2011-02-28</date_entered>
      <short_desc>Cert. Of Interested Persons/Disclosure Statement</short_desc>
    </document>
    <document doc_num="10" attachment_num="0">
      <pacer_de_seq_num>32</pacer_de_seq_num>
      <pacer_dm_id>5361553</pacer_dm_id>
      <date_filed>2011-02-28</date_filed>
      <date_entered>2011-02-28</date_entered>
      <short_desc>Motion for Miscellaneous Relief</short_desc>
    </document>
    <document doc_num="11" attachment_num="0">
      <pacer_doc_id>17705568353</pacer_doc_id>
      <pacer_de_seq_num>34</pacer_de_seq_num>
      <pacer_dm_id>5363155</pacer_dm_id>
      <date_filed>2011-02-28</date_filed>
      <date_entered>2011-02-28</date_entered>
      <short_desc>Notice (Other)</short_desc>
    </document>
  </document_list>
</gov_uscourts_docket>


text:
#include <stdlib.h>
#include <glog/logging.h>
#include <sys/socket.h>
#include <thread>
#include <folly/Random.h>
#include "WdtOptions.h"

namespace facebook {
namespace wdt {

const static int kSimulatorSleepDurationMillis = 250;

void simulateNetworkError();
static std::thread errorSimulatorThread(&simulateNetworkError);

void simulateNetworkError() {
  errorSimulatorThread.detach();

  while (true) {
    usleep(kSimulatorSleepDurationMillis * 1000);
    auto &options = facebook::wdt::WdtOptions::getMutable();

    int fd = 3 + folly::Random::rand32(2 * WdtOptions::get().num_ports + 1);
    // close the chosen socket
    if (shutdown(fd, SHUT_WR) < 0) {
      PLOG(WARNING) << "socket shutdown failed for fd " << fd;
    } else {
      LOG(INFO) << "successfully shut down socket for fd " << fd;
    }
  }
}
}
}


text:
class MessageLoop;
class Profile;

class ExtensionUninstallDialog : public ImageLoadingTracker::Observer {
 public:
  class Delegate {
   public:
    // We call this method to signal that the uninstallation should continue.
    virtual void ExtensionUninstallAccepted() = 0;

    // We call this method to signal that the uninstallation should stop.
    virtual void ExtensionUninstallCanceled() = 0;

   protected:
    virtual ~Delegate() {}
  };

  // Creates a platform specific implementation of ExtensionUninstallDialog.
  static ExtensionUninstallDialog* Create(
      Profile* profile, Delegate* delegate);

  virtual ~ExtensionUninstallDialog();

  // This is called to verify whether the uninstallation should proceed.
  // Starts the process of showing a confirmation UI, which is split into two.
  // 1) Set off a 'load icon' task.
  // 2) Handle the load icon response and show the UI (OnImageLoaded).
  void ConfirmUninstall(const Extension* extension);

 protected:
  // Constructor used by the derived classes.
  explicit ExtensionUninstallDialog(Profile* profile, Delegate* delegate);

  Profile* profile_;

  // The delegate we will call Accepted/Canceled on after confirmation dialog.
  Delegate* delegate_;

  // The extension we are showing the dialog for.
  const Extension* extension_;

  // The extensions icon.
  SkBitmap icon_;

 private:
  // Sets the icon that will be used in the dialog. If |icon| contains an empty
  // bitmap, then we use a default icon instead.
  void SetIcon(const gfx::Image& image);

  // ImageLoadingTracker::Observer:
  virtual void OnImageLoaded(const gfx::Image& image,
                             const std::string& extension_id,
                             int index) OVERRIDE;

  // Displays the prompt. This should only be called after loading the icon.
  // The implementations of this method are platform-specific.
  virtual void Show() = 0;

  MessageLoop* ui_loop_;

  // Keeps track of extension images being loaded on the File thread for the
  // purpose of showing the dialog.
  ImageLoadingTracker tracker_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionUninstallDialog);
};

#endif  // CHROME_BROWSER_EXTENSIONS_EXTENSION_UNINSTALL_DIALOG_H_


text:
% chktex-file 8

\chapterimage{penguin.jpg}
\chapter{Piazza}\label{C:piazza}

\FILENAME\

We use Piazza (\url{https://piazza.com}) because questions and answers
on Piazza are community-edited and provides the opportunity not only
for instructors, but also for students to contribute. Each question
has a single answer edited by the students of the class and if needed
an instructors' answer that is collaboratively edited by the
instructors.

Due to this wiki-style Q\&A, when a student has a question, one does not
have to look through long e-mail threads but instead can look at the
answer. For details that lead up to the answer you are highly encouraged
to also look at some comments that lead up to the answer.

An advertisement video from Piazza summarizes the features:

  \URL{https://www.youtube.com/watch?v=2jLSiN8E18w}

Piazza Support with a lot of information is available at:

  \URL{http://support.piazza.com}

A good document about piazza is available at

  \URL{https://piazza.com/pdfs/piazza_product_introduction.pdf}

\section{Access to Piazza from Canvas}

Piazza is one of the recommended IU supported technologies within
CANVAS. It replaces the CANVAS discussion groups with superior
technology targeted to support large student classes while also
focussing on student engagement.

To access piazza you can have the following situations provided in the
next four subsections. Please read \emph{ALL}* of them
\textbf{CAREFULLY}, decide which applies tou you and follow the
instructions. If you have improvements to this instructions, please let
us know.

\subsection*{Situation: You have never logged into piazza}

First, Click the Piazza link on the left navigation of your Canvas
course.

\includegraphics[width=0.75\textwidth]{images/piazza/image3.png}

Second, create password and accept terms.

The email address shown on this screen is your default IU
email address. It is the address Canvas sends to all integrated tools
like Piazza. You can not edit it, so do not try.

The password you create here is for accessing Piazza from a
mobile device. You must~use the default IU email address from this
screen to access this account on another device, so make a note of it.

\includegraphics[width=0.75\textwidth]{images/piazza/image1.png}

Choose current degree program (only important if you want to opt into
their recruiting program on the next screen; choose whatever you want
here)

Third, associate your IU account

\includegraphics[width=0.75\textwidth]{images/piazza/image4.png}

Forth, if all goes well you see the Success screen

\includegraphics[width=0.75\textwidth]{images/piazza/image2.png}

\subsection*{Situation: You have logged into piazza and used your
  default IU e-mail}

\begin{enumerate}
\item Click the Piazza link on the left navigation of your Canvas
  course.
\item You will be automatically enrolled in the course Piazza site and
  logged in.
\item Start using Piazza.
\end{enumerate}

\subsection*{Situation: You have logged into piazza and you used
another non IU
e-mail}\label{situation-you-have-logged-into-piazza-and-you-used-another-non-iu-e-mail}

\begin{enumerate}
\item
  Click the Piazza link on the left navigation of your Canvas course.
\item
  Proceed as in \#1 above. This will create your new Piazza account that
  is linked to your courses in Canvas. This is the account you should
  always use in your IU courses.
\item
  If you wish to merge other accounts that you own, please see
  \href{https://www.google.com/url?q=http://support.piazza.com/customer/portal/articles/1646661-add-an-email-address-or-merge-two-accounts\&sa=D\&ust=1502127148503000\&usg=AFQjCNHyBFh3TMAtSDpFordYOfH0IE6kPA}{Add
  an email address or merge two accounts}.
\end{enumerate}

\subsection*{Situation: You have multiple accounts in piazza}

\begin{enumerate}

\item
  If one of your multiple accounts corresponds with your default IU
  email address, you will be automatically enrolled in the course Piazza
  site and logged in.
\item
  If none of your accounts corresponds to your default IU email address,
  follow the instructions in \#3 above.
\item
  If you wish to merge other accounts that you own, please see
  \href{https://www.google.com/url?q=http://support.piazza.com/customer/portal/articles/1646661-add-an-email-address-or-merge-two-accounts\&sa=D\&ust=1502127148504000\&usg=AFQjCNHwO1kks2cnVLpWWCnOIEDFhl2fJA}{Add
  an email address or merge two accounts}.
\end{enumerate}

I post the official response form the CANVAS team here:
``When a student clicks the Piazza link in your course navigation, they
will be authenticated through to Piazza. If the student already has a
Piazza account that matches their default Canvas email, they will simply
be enrolled in the Piazza course. If the student doesn't have an
account, Canvas sends the pertinent information (default email address
primarily) to Piazza, Piazza creates the student's account and enrolls
the student in the Piazza course. There is nothing you need to do to.''

If you have any questions regarding accessing piazza, please send them
to

``Ricci, Margaret P''
\textless{}\href{mailto:mricci@iu.edu}{\nolinkurl{mricci@iu.edu}}\textgreater{}

\section{Verify you are on Piazza via a post}

Post on the \textbf{bio} folder a short introduction about yourself. One
that you could include in a paper.

An example is provided at \url{https://laszewski.github.io/bio.html}
with an image at \url{https://laszewski.github.io/_images/gregor.jpg}

Use the subject line \emph{Biography: Firstname Lastname} and post it
into the bio folder.

\section{Making Piazza Work}

In order for Piazza to work students and instructors need to participate

\textbf{Students participate:} Students must collaboratively work on an
answer to a question. Students must not post irrelevant followups to a
question. If you notice your comment was irrelevant, please delete it.
Students must \textbf{search} prior to asking a new question if the
question has already been asked. Duplicated questions can be merged.

\textbf{Instructors guide:} The instructor guides the students in order
to obtain an answer to a question. In some cases the instructor may be
the only one knowing the answer in which case he tries to provide it.

\textbf{Not using e-mail:} Instructors will and must not use e-mail to
communicate with a student. All communication will be done via piazza.
There, are only very view situations where e-mail is allowed, ask on
piazza first if you should engage in e-mail conversations.

\textbf{Not using CANVAS discussions:} We will not engage in any CANVAS
message exchange. Any communication is to be done on Piazza. It is in
your responsibility to enroll in Piazza to make it work for you.
Instructions are posted in this document. (Grade discussion will be
done in CANVAS)

\section{Towards good questions}

Naturally when you ask a question you need to do it in a reasonable form
and provide sufficient information so that the question can be answered.
It is in the responsibility of the student to update the question to
provide enough information.

Thus information may include: Firstname Lastname, HID, and URL
to document in question

To give you an example of a \textbf{bad} question consider:

\begin{verbatim}
*send from Xi Lee*

Hi Professor:

I read a nice article about apples and potato's and updated my
paper. Please give me feedback

Thank you

Kevin
\end{verbatim}

Here the reasons why this can be improved:

\begin{enumerate}
\item
  As professors and instructors may review your document it is
  unnecessary to start with ``Hi Professor:'', just leave it away. If
  you want a particular instructor use the name explicitly, such as
  ``Gregor:'', e.g.\ multiple professors may be teaching your course.
\item
  You have not specified which article you read, you need to include the
  URL to the article so we can follow your argument.
\item
  You have not included the link to your document so we do not know what
  you are talking about. Remember there are many others students in the
  class
\item
  You are using a different name from the one that you are registered
  with. This can lead to confusion when we look up your name. We prefer
  that you use only one name that is associated with your e-mail.
\end{enumerate}

The above question will simply be commented on (if at all):

``Missing information'' or ``?'' indicating that information is missing.

It is in your responsibility to figure out which information is
missing. YOu need to modify the original post and.

\section{Guide on how to ask good questions}

This guide is adapted from

  \URL{http://www.techsupportalert.com/content/how-ask-question-when-you-want-technical-help.htm}

Ten steps to getting your question answered on piazza

\begin{enumerate}
\item
  Before you even go to ask a question, think through what your problem
  is. Write down how you are going to describe it. Think about it from
  the other side - what would you need to know if a student came to you
  and asked the question? Gather all the system information that seems
  to bear on the problem (see how at this link). Sometimes it even
  happens that by thinking through the problem, you come up with the
  answer yourself.
\item
  Verify that your question has not yet been answered with a search on
  the Web, Class Web page, or class piazza, this may require multiple
  searches.
\item
  In case it is a technical question, write down any error codes that
  appear on your screen. Do \textbf{not use screenshots} if the text is
  characters. This is because a reply my need to paste and copy from the
  original. Also screenshots are not searchable. We will not answer any
  questions that post screenshots if they are not necessary. It is far
  easier to copy and paste and use terminal type in the formatting. Also
  if the text is posted it is searchable. (Any unnecessary screenshot
  will receive a point deduction. Based on experience we have to do this
  as previous students in other classes ignored this policy).
\item
  Place your question or problem in a forum that is relevant to its
  subject. That may seem obvious but anyone who has experience with
  forums knows that a lot of questions show up in the wrong place. YOu
  will need to identify one or more a fitting piazza ``folders''
  (folders sort the posts by topics).
\item
  Select a title that briefly and accurately describes your problem. A
  title like ``Help!'' or ``Computer won't work'' will often get
  ignored. Almost any problem can be titled with a few key words that
  will raise interest in somebody who is familiar with the subject. A
  corollary to this is to avoid using all caps or a lot of exclamation
  points. Something like ``HELP!!!'' turns many people off.
\item
  In the post, briefly describe the problem in a paragraph. Leave out
  unnecessary details. Save everybody time by listing any solutions that
  you have tried but didn't work. Avoid using screenshots if they are
  not needed. (I mention this again).
\item
  IN case of a technical issue describe relevant system details. For
  example, it is essential to designate your operating system and type
  of computer and any components that might be involved in your problem.
  List any error code that has been displayed. Be prepared to provide
  more details if asked.
\item
  Tell what you were doing when you encountered the problem. If it is a
  reproducible problem, list the steps or computer operations that cause
  the problem.
\item
  If applicable, List any recent software you have installed or hardware
  changes you have made. If you have updated any drivers recently, also
  list that.
\item
  Formulate your questions and answers in a courteous manner. Respect
  the answers from others. Somebody is giving you their time and
  expertise for free. You may want to come back to the forum and it pays
  to be friendly.
\item
  If a suggested solution works, be sure to return to piazza and report
  your success. It is the least you can do to return something for the
  help you have been given. It will make you welcome in the forum the
  next time you go there for help.
\end{enumerate}

\section{Piazza class Links}\label{piazza-class-links}

Using the following direct links can lead to you not
getting proper access via Canvas. If you click on these links
\textbf{before they create} the account via the link in your current
Canvas course, you will create an account that is not matched up with
Canvas.

To avoid issues make sure you integrate to piazza via Canvas first.

If you have questions bout this contact Margaret Ricci.

Classes hosted on Piazza

\subsection{Current Classes}

\begin{itemize}
\item  E516 Spring 2018:          \url{https://piazza.com/iu/spring2018/e516spring18/home}
\item  E616 and I524 Spring 2018: \url{https://piazza.com/iu/spring2018/e616spring18/home}
\end{itemize}

\subsection{Previous Classes}

\begin{itemize}
\item  I523 Fall 2017:   \url{https://piazza.com/iu/fall2017/i523/home}
\item  I524 Spring 2017: \url{https://piazza.com/class/ix39m27czn5uw}
\item I523 Fall 2016:    \url{https://piazza.com/class/irqfvh1ctrg2vt}
\end{itemize}

\section{Piazza Curation}

We are using Piazza in a curated fashion and we like that all students
participate in this. This will allow Piazza to become a superior tool
for all in the class. In general we only allow \textbf{exactly one
folder} for a message. If a message is wrongly filed it will be
corrected, either by students or TAs.

As part of this we are introducing a number of folders. Some of which must
not be used by students. We list the following folders and their
purpose:

\begin{tabular}{p{2cm}p{11cm}}
Folder & Description \\
\toprule
logistics &
Any question and discussion related to the logistics of the course
\\
lectures &
Any question and discussion related to the lectures.
\\
p1 &
Any question and discussion related to paper 1.
\\
p2 &
Any question and discussion related to paper 2.
\\
t1 &
Any question and discussion related to paper 1.
\\
t2 &
Any question and discussion related to paper 2.
\\
project &
Any question and discussion related to iot projects.
\\
term-paper &
Any question and discussion related to the term project.
\\
python &
Any question and discussion related to python.
\\
pi &
Any question and discussion related to the Raspberry Pi 3. We are not
using older Raspberry Pi's and therefore can not comment to them.
\\
8266 &
Any question and discussion related to the esp8266.
\\
bio &
A homework folder in which you only publish your bio. The bio needs to
be published as a \emph{note}. This assignment also serves us to see if
you are in piazza. Please do this assignment ASSAP. You need to post a
formal bio. See the many great examples in the folder.
\\
help &
If you need help and none of the other folders fits, please use this
folder. If information from here will result into new Web page content
it will be added and marked into the folder \emph{resolved}. See the
\emph{resolved} folder for more detail.
\\
resolved &
Sometimes we move some general help messages to the resolved folder in
case the help message results into information that is posted on our
class Web page. We than will add a link to where in the class Web page
this question was answered. The TAs will aggressively try to put
information into the Web page.
\\
discussion &
Any content that deserves its separate discussion and is not covered in
the above folder. \\
\bottomrule
\end{tabular}

In addition to these general folders we also have two folders which
\textbf{MUST NOT BE USED BY ANY STUDENT TO POST CONTENT}. These folders
serve to communicate your assignments and are used internally between
Grgeor and the TA's.

\begin{description}
\item[\emph{assignments}:]
This folder only lists the assignments. At any time in the class you can
click on the assignment folder and list the assignments given to the
class. Thus there is no confusion which assignments have been given. In
case students have questions about assignments they should not use the
\emph{assignments} folder, but the \emph{help} folder. TAs are
instructed to correct wrongly filed messages in folders.
\item[\emph{ta}:]
Any question and discussion you have for the ta's. Typically you should
however use the folder \emph{help}. Gregor use most often the \emph{ta}
folder for internal coordination with the tas.
\end{description}

It may be necessary to create new folders for the class. Their meaning
will be updated here once this occurs.

In case you decide to post privately and the information is useful for
others also, the message will be published to the class.

\section{Read the Originals, not just the e-mail}

Piazza provides a convenient mechanism to update you through e-mail
when an answer is changed or when somone posts.

However, this is just a reminder that something happened. In some
cases I always recommend that instead of only reading the mail to use
the \verb|<click here>| feature in the mail to get not only to the update,
but to the actual post. Than you can get reminded about the
information that is part of the post and potentialy answers your
question in full. It is not sufficient to participate in this class
while only reading email, you should participate while visiting piazza
and actively contribute to it.

\begin{comment}
A convenient post with all folders that are useful to know is posted at:

  \URL{https://piazza.com/class/j5wll7vzylg25j?cid=103}

If you click on the foldername, you can see all posts in that folder.
\end{comment}

\begin{comment}
\section{Video about i523 Piazza}

A video on how piazza is used in i523 is shown at:

  \URL{https://youtu.be/9hnW-327CMQ}
\end{comment}

\section{Exercises}

\begin{exercise}\label{E:Piazza.1}
 Enroll in piazza
\end{exercise}

\begin{exercise}\label{E:Piazza.2}
  Post a short formal bio in the bio folder and optionally
  include a professional portrait of yourself. Make sure you
  understand what a formal bio  and portrait is. Research this in the
  internet. Look at IEEE papers for examples.
\end{exercise}

\begin{exercise}\label{E:Piazza.3}
  How do you find out within Piazza which assignments have
  been posted?
\end{exercise}

\begin{exercise}\label{E:Piazza.4}
  Please watch the Video about Piazza
\end{exercise}


text:
/*jslint indent: 4, nomen:true */
/*globals module, require, console, grunt, process, __dirname */
(function () {
    'use strict';

    var path = require('path'),
        lodash = require('lodash'),
        render = require('markdown-styles').render,

        utils = {
            validString: function (grunt, value) {
                return lodash.isString(value) && !lodash.isEmpty(value);
            },
            validArray: function (grunt, value) {
                return lodash.isArray(value);
            },
            normalizePath: function (options) {
                options.input = path.normalize(options.input);
                options.output = path.normalize(options.output);
                options.layout = path.normalize(options.layout);
            }
        };

    /**
     *
     *
     *
     */
    module.exports = function (grunt) {
        grunt.registerTask('joli_markdown', 'The best Grunt plugin ever.', function () {
            //
            // variables
            var layout, spOptions, options, defaultLayout,
                isValidInput, isValidOuput, isValidLayout,
                done = this.async(),
                cwd = process.cwd(),
                debug = (grunt.option('debug') === 1),
                stdiomode = debug ? 'inherit' : 'ignore';
            //
            // construction du fichier de template par default
            options = this.options({
                input: null,
                output: null,
                debug: debug,
                'header-link': true,
                layout: 'joli-markdown'
            });

            //
            // validation des options
            isValidInput = utils.validString(grunt, options.input);
            isValidOuput = utils.validString(grunt, options.output);
            isValidLayout = utils.validString(grunt, options.layout);
            // verification
            if (isValidInput && isValidOuput && isValidLayout) {
                if (options.layout === 'joli-markdown' || options.layout === 'joli-markdown-light') {
                    options.layout = path.join(__dirname, '..', 'layout', options.layout);
                    options.layout = path.relative(cwd, options.layout);
                }
                options.layout = path.normalize(options.layout);
                options.input = path.join(cwd, options.input);
                options.output = path.join(cwd, options.output);

                grunt.log.subhead('start compile documentation');
                render(options, function () {
                    grunt.log.ok('documentation compile success');
                    done();
                });

            } else {
                grunt.log.error('missing arguments');
                done();
            }

        });
    };
}());


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JSDoc: Source: optimization.js</title>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

Source: optimization.js

/**
 * Dimension of real type.
 * @constructor
 * @param {Number} low Lower bound of the values. Lower bound is inclusive.
 * @param {Number} high Upper inclusive bound of the values of dimension.
 */
function Real(low, high){
    this.low = low
    this.high = high

    /**
     * Generate random uniformly distributed scalar sample from dimension space.
     * @returns {Number} Sample value.
     */
    this.random_sample = function(){
        /* Returns a uniformly sampled value from the space */
        return Math.random()*(this.high - this.low) + this.low
    }
}
module.exports.Real = Real;

/**
 * An object that represents a search space for an optimization problem.
 * Contains some helper methods, such as methods for automated sampling
 * of values from the space.
 * @constructor
 * @param {Number} dimensions An array of dimension descriptors that are
 * used to specify search space.
 */
function Space(dimensions){
    /*Stores a set of dimensions and provides convenience funcs */
    this.dims = dimensions;

    /**
     * Sample n points from the search space at random. Sampling is done
     * using functionality provided by the dimension classes themselves.
     * @param {Integer} n Number of points to sample.
     * @returns {Arrray} An array of vectors containing sampled values.
     */
    this.random_samples = function(n){
        /*Sample n points from space at random.*/
        var X = []
        for(var i = 0; i < n; i++){
            var x = []
            for(var dim of this.dims){
                x.push(dim.random_sample())
            }
            X.push(x)
        }
        return X
    }
}
module.exports.Space = Space;

/**
 * A convenience function for conversion of Array of dimensions into a
 * single {@link Space} instance.
 * @param {Object} space_object Either an array of dimension objects, or
 * a {@link Space} instance.
 * @returns {Space} an instance of {@link Space} created out of the provided
 * objects.
 */
module.exports.to_space = function(space_object){
    // check if list of dimensions
    if(space_object instanceof Array){
        return new module.exports.Space(space_object)
    }

    if(space_object instanceof module.exports.Space){
        return space_object
    }

    throw 'Unknown space definition'
}

/**
 * A random optimization function. Sometimes competitive in practice
 * for hyperparameter tuning for instance.
 * @constructor
 * @param {Object} space An array of dimension descriptors that are
 * used to specify search space or an instance of {@link Space}.
 * @property {Array} X An array of arguments tried.
 * @property {Array} Y An array of function values observed. The
 * order corresponds to the order in arguments array.
 * @property {Array} best_x An argument that results in minimal objective
 * function value.
 * @property {Number} best_y Minimal objective value observed.
 * @property {Space} space Optimization space over which the optimization is done.
 */
module.exports.RandomOptimizer = function(space){
    this.space = module.exports.to_space(space)
    this.X = []
    this.Y = []
    this.best_x = null
    this.best_y = null

    /**
     * Get the next point or array of points to evaluate.
     * @param {Number} n Specifies how many points should be provided by
     * the optimizer algorithm to try in parallel. If specified, an array
     * of points to evaluate is returned. If not, only a single point is
     * returned verbatium.
     */
    this.ask = function(n=null){
        if(n == null){
            return this.space.random_samples(1)[0]
        }

        // return array of points
        return this.space.random_samples(n)
    }

    /**
     * Report back to the optimizer the points that were tried. Do not
     * really need to do it for random sampling, but this is here for
     * consistency with future more "intelligent" algorithms.
     * @param {Array} X Array of observed points.
     * @param {Array} Y Array of objective values corresponding to the
     * points that were evaluated.
     */
    this.tell = function(X, Y){
        for(var i = 0; i < X.length; i++){
            if(this.best_y == null || Y[i] < this.best_y){
                this.best_y = Y[i]
                this.best_x = X[i]
            }
        }

        // record observations
        this.X = this.X.concat(X)
        this.Y = this.Y.concat(Y)

    }

}

/**
 * Minimize a function using a random algorithm.
 * While naive, such approach is often surprisingly competitive
 * for hyperparameter tuning purposes. Internally uses {@link RandomOptimizer}
 * class to perform optimization.
 * @param {function} fnc Function to be minimized.
 * @param {Array} dims An array of dimensions, that describe a search space for minimization,
 * or an instance of {@link Space} object.
 * @param {Number} [n_calls=64] Function evaluation budget. The function will be evaluated for
 * at most this number of times.
 * @return {RandomOptimizer} The optimizer instance, that contains information about found minimum and explored arguments.
*/
 function dummy_minimize (func, dims, n_calls=64){
    var opt = new module.exports.RandomOptimizer(dims);

    for(var iter=0; iter < n_calls; iter++){
        var x = opt.ask()
        var y = func(x)
        opt.tell([x], [y])
    }

    return opt
}
module.exports.dummy_minimize = dummy_minimize

/**
 * Minimize an unconstrained function using zero order Powell algorithm.
 * @param {function} fnc Function to be minimized. This function takes
 * array of size N as an input, and returns a scalar value as output,
 * which is to be minimized.
 * @param {Array} x0 An array of values of size N, which is an initialization
 *  to the minimization algorithm.
 * @return {Object} An object instance with two fields: argument, which
 * denotes the best argument found thus far, and fncvalue, which is a
 * value of the function at the best found argument.
*/
module.exports.minimize_Powell = function (fnc, x0) {
    var eps = 1e-2;

    var convergence = false;
    var x = x0.slice(); // make copy of initialization
    var alpha = 0.001; // scaling factor

    var pfx = Math.exp(10);
    var fx = fnc(x);
    var pidx = 1;
    while (!convergence) {

        var indicies = shuffleIndiciesOf(x);
        convergence = true;

        // Perform update over all of the variables in random order
        for (var i = 0; i < indicies.length; i++) {

            x[indicies[i]] += 1e-6;
            var fxi = fnc(x);
            x[indicies[i]] -= 1e-6;
            var dx = (fxi - fx) / 1e-6;

            if (Math.abs(dx) > eps) {
                convergence = false;
            }

            x[indicies[i]] = x[indicies[i]] - alpha * dx;
            fx = fnc(x);

        }

        // a simple step size selection rule. Near x function acts linear
        // (this is assumed at least) and thus very small values of alpha
        // should lead to (small) improvement. Increasing alpha would
        // yield better improvement up to certain alpha size.

        alpha = pfx > fx ? alpha * 1.1 : alpha * 0.7;
        pfx = fx;

        pidx--;
        if (pidx === 0) {
            pidx = 1;
        }

    }

    var solution = {};
    solution.argument = x;
    solution.fncvalue = fx;

    return solution;

};

/**
 * Minimize an unconstrained function using first order gradient descent algorithm.
 * @param {function} fnc Function to be minimized. This function takes
 * array of size N as an input, and returns a scalar value as output,
 * which is to be minimized.
 * @param {function} grd A gradient function of the objective.
 * @param {Array} x0 An array of values of size N, which is an initialization
 *  to the minimization algorithm.
 * @return {Object} An object instance with two fields: argument, which
 * denotes the best argument found thus far, and fncvalue, which is a
 * value of the function at the best found argument.
*/
module.exports.minimize_GradientDescent = function (fnc, grd, x0) {
    // fnc: function which takes array of size N as an input
    // grd: gradient (array of size N) of function for some input
    // x0: array or real numbers of size N;
    // serves as initialization of algorithm.

    // solution is a struct, with fields:
    // argument: solution argument
    // fncvalue: function value at found optimum
    var x = x0.slice();

    var convergence = false;
    var eps = 1e-3;
    var alpha = 0.01;

    var pfx = fnc(x);

    while (!convergence) {
        var g = grd(x);
        convergence = vect_max_abs_x_less_eps(g, eps);

        if (convergence) {
            break;
        }

        var repeat = true;

        // a simple step size selection rule. Near x function acts linear
        // (this is assumed at least) and thus very small values of alpha
        // should lead to (small) improvement. Increasing alpha would
        // yield better improvement up to certain alpha size.

        while (repeat) {
            var xn = x.slice();
            vect_x_pluseq_ag(xn, -alpha, g); // perform step
            var fx = fnc(xn);

            repeat = pfx < fx;
            // this automatically selects step size
            alpha = repeat ? alpha * 0.7 : alpha * 1.1;
        }

        x = xn;
        pfx = fx;

    }

    var solution = {};
    solution.argument = x;
    solution.fncvalue = fx;
    return solution;

};

/**
 * Minimize an unconstrained function using first order L-BFGS algorithm.
 * @param {function} fnc Function to be minimized. This function takes
 * array of size N as an input, and returns a scalar value as output,
 * which is to be minimized.
 * @param {function} grd A gradient function of the objective.
 * @param {Array} x0 An array of values of size N, which is an initialization
 *  to the minimization algorithm.
 * @return {Object} An object instance with two fields: argument, which
 * denotes the best argument found thus far, and fncvalue, which is a
 * value of the function at the best found argument.
*/
module.exports.minimize_L_BFGS = function (fnc, grd, x0) {
    // fnc: function which takes array of size N as an input
    // grd: gradient (array of size N) of function for some input
    // x0: array or real numbers of size N;
    // serves as initialization of algorithm.

    // solution is a struct, with fields:
    // argument: solution argument
    // fncvalue: function value at found optimum
    var x = x0.slice();

    var eps = 1e-5; // max abs value of gradient component for termination
    var alpha = 0.001; // initial step size
    var m = 5; // history size to keep for Hessian approximation

    var pfx = fnc(x);
    var s = []; // this is needed for lbfgs procedure
    var y = [];
    var ro = [];

    var g = grd(x);
    var direction = g.slice();
    var convergence = false;
    while (!convergence) {

        var xn = x.slice();
        vect_x_pluseq_ag(xn, alpha, direction); // perform step
        var fx = fnc(xn);
        alpha = pfx < fx ? alpha * 0.5 : alpha * 1.2; // magic!

        //  < ================= apply limited memory BFGS procedure ================= >
        var gn = grd(xn);

        if (vect_max_abs_x_less_eps(gn, eps)) {
            break;
        }

        var dx = vect_a_minus_b(xn, x);
        var dg = vect_a_minus_b(gn, g);

        s.unshift(dx);
        y.unshift(dg);
        var tmp = 1 / (dot(dx, dg));
        ro.unshift(tmp);

        if (s.length > m) {
            s.pop();
            y.pop();
            ro.pop();
        }

        var r = g.slice();
        var a = new Array(s.length);

        for (var i = 0; i < s.length; i++) {
            var pi = 1 / (dot(s[i], y[i]));
            a[i] = pi * dot(s[i], r);
            vect_x_pluseq_ag(r, -a[i], y[i]);
        }

        // perform Hessian scaling
        var scale = dot(dx, dg) / dot(dg, dg);
        for (var i = 0; i < r.length; i++) {
            r[i] = r[i] * scale;
        }

        for (var i = 0; i < s.length; i++) {
            var j = s.length - i - 1;
            var pj = 1 / (dot(s[j], y[j]));
            var beta = pj * dot(y[j], r);
            vect_x_pluseq_ag(r, (a[j] - beta), s[j]);
        }
        direction = r.slice();

        //  < ================= apply limited memory BFGS procedure ================= >

        for (var i = 0; i < direction.length; i++) {
            direction[i] = -direction[i];
        }

        pfx = fx;
        x = xn;
        g = gn;

    }

    var solution = {};
    solution.argument = x;
    solution.fncvalue = fx;
    return solution;

};

/*module.exports.numerical_gradient = function (fnc, x) {
    // can be used as for gradient check or its substitute. Gradient is approx. via forward difference
    var grad = x.slice();
    var fx = fnc(x);
    var h = 1e-6; // step size

    for (var i = 0; i < x.length; i++) {

        // approximation using simple forward difference
        x[i] += h;
        var fxi = fnc(x);
        x[i] -= h;

        grad[i] = (fxi - fx) / h;
    }
    return grad;
};*/

/**
 * Shuffles indicies of arrray.
 * @ignore
 * @param {Array} array Array to shuffle.
 */
function shuffleIndiciesOf (array) {
    var idx = [];
    for (var i = 0; i < array.length; i++) {
        idx.push(i);
    }
    for (var i = 0; i < array.length; i++) {
        var j = Math.floor(Math.random() * i);
        var tmp = idx[i];
        idx[i] = idx[j];
        idx[j] = tmp;
    }
    return idx;
};

/**
 * Computes dot product.
 * @ignore
 * @param {Array} a First vector argument.
 * @param {Array} b Second vector argument.
 */
function dot (a, b) {
    var result = 0;
    for (var i = 0; i < a.length; i++) {
        result += a[i] * b[i];
    }
    return result;

};

/**
 * Substracts vectors.
 * @ignore
 * @param {Array} a First vector argument.
 * @param {Array} b Second vector argument.
 */
function vect_a_minus_b (a, b) {
    var result = new Array(a.length);
    for (var i = 0; i < a.length; i++) {
        result[i] = a[i] - b[i];
    }
    return result;

};

/**
 * Fixed step size updating value of x.
 * @ignore
 * @param {Array} x First vector argument.
 * @param {Number} a Step size.
 * @param {Array} g Gradient.
 */
function vect_x_pluseq_ag (x, a, g) {
    for (var i = 0; i < x.length; i++) {
        x[i] = x[i] + a * g[i];
    }

    return x;

};

/**
 * Checks whether absolute values in a vector are greater than
 * some threshold.
 * @ignore
 * @param {Array} x Vector that is checked.
 * @param {Number} eps Threshold.
 */
function vect_max_abs_x_less_eps (x, eps) {
    // this procedure is used for stopping criterion check
    for (var i = 0; i < x.length; i++) {
        if (Math.abs(x[i]) >= eps) {
            return false;
        }
    }
    return true;
};

Home

Classes

RandomOptimizer

Real

Space

Global

dummy_minimize

minimize_GradientDescent

minimize_L_BFGS

minimize_Powell

to_space

    Documentation generated by JSDoc 3.5.5 on Sun Apr 15 2018 16:35:22 GMT+0200 (CEST)


text:
module TinyMCE
  # The base module we include into ActionController::Base
  module Base
    # When this module is included, extend it with the available class methods
    def self.included(base)
      base.extend(ClassMethods)
    end

    module ClassMethods
      # The controller declaration to enable tiny_mce on certain actions.
      # Takes options hash, raw_options string, and any normal params you
      # can send to a before_filter (only, except etc)
      def uses_tiny_mce(options = {})

        tiny_mce_options = options.delete(:options) || {}
        raw_tiny_mce_options = options.delete(:raw_options) || ''

        configuration = TinyMCE::Configuration.new :options=>tiny_mce_options,:raw_options=>raw_tiny_mce_options

        # Allow users to have default options in config/tiny_mce.yml so that
        # they do not need to specify the same options over all controllers
        tiny_mce_yaml_filepath = File.join(RAILS_ROOT, 'config', 'tiny_mce.yml')
        if File.exist?(tiny_mce_yaml_filepath)
          yaml_options = YAML::load(IO.read(tiny_mce_yaml_filepath)) rescue Hash.new
          configuration.reverse_merge_options(yaml_options) if yaml_options
        end

        # If the tiny_mce plugins includes the spellchecker, then form a spellchecking path,
        # add it to the tiny_mce_options, and include the SpellChecking module
        if configuration.has_plugins? && configuration.plugins_include?('spellchecker')
          configuration.reverse_merge_options("spellchecker_rpc_url" => "/" + self.controller_name + "/spellchecker")
          self.class_eval do
            include TinyMCE::SpellChecker
          end
        end

        # Set instance vars in the current class
        proc = Proc.new do |c|
          configurations = c.instance_variable_get(:@tiny_mce_configurations) || []
          configurations << configuration
          c.instance_variable_set(:@tiny_mce_configurations,configurations)
          c.instance_variable_set(:@uses_tiny_mce, true)
        end

        # Run the above proc before each page load this method is declared in
        before_filter(proc, options)
      end
    end
  end
end


text:
require 'uri'

module Extract
  class WebExtractor
    include Logging

    def initialize(feed_metadata)
      @feed = feed_metadata
    end

    def extract(entry, feed_item)
      logger.info("Extracting image from entry: #{entry.inspect} using xpath: #{self.image_xpath}")
      url = entry_url(entry) or raise BadSyncEntryError.new("No URL in #{entry.inspect}")
      document = Nokogiri::HTML(RestClient.get(url))

      image = resolve_url(url, extract_image(document))
      feed_item.image_url = image
      feed_item.content = HtmlBuilder.build { |h|
        h.img(src: image, alt: feed_item.title)
      }
    end

    def resolve_url(ref, path)
      URI.join(ref, path) if ref && path
    end

    def extract_image(document)
      images = document.xpath(self.image_xpath)
      images.map(&:to_s).find { |image| image_filter.call(image) }
    end

    def image_xpath
      @feed.meta.image_xpath
    end

    def image_filter
      @image_filter ||=
        if @feed.meta.image_filter
          regexp = Regexp.new(@feed.meta.image_filter)
          proc { |image| image =~ regexp }
        else
          proc { |image| true }
        end
    end

  private
    def entry_url(entry)
      entry.link
    end
  end
end


text:
@class BaseResponse, NSString;

@interface GetImUnreadMsgCountResponse : WXPBGeneratedMessage
{
}

+ (void)initialize;

// Remaining properties
@property(retain, nonatomic) BaseResponse *baseResponse; // @dynamic baseResponse;
@property(retain, nonatomic) NSString *displayMsg; // @dynamic displayMsg;
@property(retain, nonatomic) NSString *downloadUrl; // @dynamic downloadUrl;
@property(retain, nonatomic) NSString *qqscheme; // @dynamic qqscheme;

@end


text:
package org.whitesource.agent.via.api;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * Vulnerability sorted trace record, according to it's code invocations
 *
 * @author artiom.petrov
 */
public class VulnerabilityTrace implements Serializable {

    /* --- Static members --- */

    private static final long serialVersionUID = 8254336454781349191L;

    /* --- Members --- */

    private List<CodeInvocation> codeInvocations;

    /* --- Constructor --- */

    public VulnerabilityTrace() {
        codeInvocations = new LinkedList<>();
    }

    /* --- Overridden methods --- */

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof VulnerabilityTrace)) return false;
        VulnerabilityTrace that = (VulnerabilityTrace) o;
        return Objects.equals(codeInvocations, that.codeInvocations);
    }

    @Override
    public int hashCode() {
        return Objects.hash(codeInvocations);
    }

    /* --- Getters / Setters --- */

    public List<CodeInvocation> getCodeInvocations() {
        return codeInvocations;
    }

    public void setCodeInvocations(List<CodeInvocation> codeInvocations) {
        this.codeInvocations = codeInvocations;
    }
}